Example usage for java.lang.reflect InvocationTargetException InvocationTargetException

List of usage examples for java.lang.reflect InvocationTargetException InvocationTargetException

Introduction

In this page you can find the example usage for java.lang.reflect InvocationTargetException InvocationTargetException.

Prototype

public InvocationTargetException(Throwable target, String s) 

Source Link

Document

Constructs a InvocationTargetException with a target exception and a detail message.

Usage

From source file:net.yacy.http.servlets.YaCyDefaultServlet.java

protected Method rewriteMethod(final File classFile) throws InvocationTargetException {
    Method m = null;/*from w  w  w  .  ja  va 2  s  .c o m*/
    // now make a class out of the stream
    try {
        final SoftReference<Method> ref = templateMethodCache.get(classFile);
        if (ref != null) {
            m = ref.get();
            if (m == null) {
                templateMethodCache.remove(classFile);
            } else {
                return m;
            }
        }

        final Class<?> c = provider.loadClass(classFile);

        final Class<?>[] params = (Class<?>[]) Array.newInstance(Class.class, 3);
        params[0] = RequestHeader.class;
        params[1] = serverObjects.class;
        params[2] = serverSwitch.class;
        m = c.getMethod("respond", params);

        if (MemoryControl.shortStatus()) {
            templateMethodCache.clear();
        } else {
            // store the method into the cache
            templateMethodCache.put(classFile, new SoftReference<Method>(m));
        }
    } catch (final ClassNotFoundException e) {
        ConcurrentLog.severe("FILEHANDLER",
                "YaCyDefaultServlet: class " + classFile + " is missing:" + e.getMessage());
        throw new InvocationTargetException(e, "class " + classFile + " is missing:" + e.getMessage());
    } catch (final NoSuchMethodException e) {
        ConcurrentLog.severe("FILEHANDLER",
                "YaCyDefaultServlet: method 'respond' not found in class " + classFile + ": " + e.getMessage());
        throw new InvocationTargetException(e,
                "method 'respond' not found in class " + classFile + ": " + e.getMessage());
    }
    return m;
}

From source file:nl.strohalm.cyclos.utils.binding.CustomBeanUtilsBean.java

@Override
public void setProperty(final Object bean, String name, final Object value)
        throws IllegalAccessException, InvocationTargetException {

    // Resolve any nested expression to get the actual target bean
    Object target = bean;// w  w  w  . j a  va  2 s  .c  o  m
    final int delim = findLastNestedIndex(name);
    if (delim >= 0) {
        try {
            target = getPropertyUtils().getProperty(bean, name.substring(0, delim));
        } catch (final NoSuchMethodException e) {
            return; // Skip this property setter
        }
        name = name.substring(delim + 1);
    }

    // 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 property name, index, and key values
    propName = name;
    final int i = propName.indexOf(PropertyUtils.INDEXED_DELIM);
    if (i >= 0) {
        final int k = propName.indexOf(PropertyUtils.INDEXED_DELIM2);
        try {
            index = Integer.parseInt(propName.substring(i + 1, k));
        } catch (final NumberFormatException e) {
            // Ignore
        }
        propName = propName.substring(0, i);
    }
    final int j = propName.indexOf(PropertyUtils.MAPPED_DELIM);
    if (j >= 0) {
        final int k = propName.indexOf(PropertyUtils.MAPPED_DELIM2);
        try {
            key = propName.substring(j + 1, k);
        } catch (final IndexOutOfBoundsException e) {
            // Ignore
        }
        propName = propName.substring(0, j);
    }

    // Calculate the property type
    if (target instanceof DynaBean) {
        final DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        final DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
        if (type.isArray() || Collection.class.isAssignableFrom(type)) {
            type = Object[].class;
        }
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (final NoSuchMethodException e) {
            return; // Skip this property setter
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) {
                return; // Read-only, skip this property setter
            }
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();

            /**
             * Overriden behaviour ------------------- When a type is Object on a mapped property, retrieve the value to check if it's an array
             */
            if (Object.class.equals(type)) {
                try {
                    final Object retrieved = getPropertyUtils().getMappedProperty(target, propName, key);
                    if (retrieved != null) {
                        final Class<?> retrievedType = retrieved.getClass();
                        if (retrievedType.isArray() || Collection.class.isAssignableFrom(retrievedType)) {
                            type = Object[].class;
                        }
                    }
                } catch (final NoSuchMethodException e) {
                    throw new PropertyException(target, propName + "(" + key + ")");
                }
            }
        } else if (descriptor instanceof IndexedPropertyDescriptor) {
            if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) {
                return; // Read-only, skip this property setter
            }
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else {
            if (descriptor.getWriteMethod() == null) {
                return; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
        }
    }

    /**
     * Overriden behaviour ------------------- When a type is Map on a mapped property, retrieve the value to check if it's an array
     */
    if (Map.class.isAssignableFrom(type) && StringUtils.isNotEmpty(key)) {
        try {
            final Map<?, ?> map = (Map<?, ?>) getPropertyUtils().getProperty(target, propName);
            final Object retrieved = map.get(key);
            if (retrieved != null) {
                final Class<?> retrievedType = retrieved.getClass();
                if (retrievedType.isArray() || Collection.class.isAssignableFrom(retrievedType)) {
                    type = Object[].class;
                }
            }
        } catch (final NoSuchMethodException e) {
            throw new PropertyException(target, propName + "(" + key + ")");
        }
    }

    // Convert the specified value to the required type
    Object newValue = null;
    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value == null) {
            final String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert(values, type);
        } else if (value instanceof String) {
            final String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert(values, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert((String[]) value, type);
        } else {
            newValue = value;
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String) {
            newValue = getConvertUtils().convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = value;
        }
    } else { // Value into scalar
        if ((value instanceof String) || (value == null)) {
            newValue = getConvertUtils().convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type);
        } else if (getConvertUtils().lookup(value.getClass()) != null) {
            newValue = getConvertUtils().convert(value.toString(), type);
        } else {
            newValue = value;
        }
    }

    // Invoke the setter method
    try {
        if (index >= 0) {
            getPropertyUtils().setIndexedProperty(target, propName, index, newValue);
        } else if (key != null) {
            getPropertyUtils().setMappedProperty(target, propName, key, newValue);
        } else {
            getPropertyUtils().setProperty(target, propName, newValue);
        }
    } catch (final NoSuchMethodException e) {
        throw new InvocationTargetException(e, "Cannot set " + propName);
    }

}

From source file:org.apache.tuscany.sca.implementation.bpel.ode.provider.BPELInvoker.java

public Object doTheWork(Object[] args) throws InvocationTargetException {
    Element response = null;//  w  w  w.  j av  a  2  s.c om

    if (!(operation.getInterface() instanceof WSDLInterface)) {
        throw new InvocationTargetException(null, "Unsupported service contract");
    }

    org.apache.ode.bpel.iapi.MyRoleMessageExchange mex = null;
    Future<?> onhold = null;

    //Process the BPEL process invocation
    Long processID = 0L;
    try {
        txMgr.begin();
        mex = odeServer.getBpelServer().getEngine().createMessageExchange(new GUID().toString(),
                bpelServiceName, bpelOperationName);
        //TODO - this will not be true for OneWay operations - need to handle those
        mex.setProperty("isTwoWay", "true");
        onhold = mex.invoke(createInvocationMessage(mex, args));

        txMgr.commit();
        // Deal with callback cases - store the callback metadata by process instance ID
        if (isCallback) {
            processID = odeServer.getProcessIDFromMex(mex.getMessageExchangeId());
            // Store the callback metadata for this invocation
            odeServer.saveCallbackMetadata(processID, service.getName(), callbackEPR);
        } // end if
    } catch (Exception e) {
        try {
            txMgr.rollback();
        } catch (SystemException se) {

        }
        throw new InvocationTargetException(e, "Error invoking BPEL process : " + e.getMessage());
    } // end try

    // Waiting until the reply is ready in case the engine needs to continue in a different thread
    if (onhold != null) {
        try {
            //add timeout to avoid blocking when there is a exception/failure
            onhold.get(TIME_OUT, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            throw new InvocationTargetException(e, "Error invoking BPEL process : " + e.getMessage());
        } // end try
    } // end if

    //Process the BPEL invocation response
    try {
        txMgr.begin();
        // Reloading the mex in the current transaction, otherwise we can't
        // be sure we have the "freshest" one.
        mex = (MyRoleMessageExchange) odeServer.getBpelServer().getEngine()
                .getMessageExchange(mex.getMessageExchangeId());

        Status status = mex.getStatus();

        switch (status) {
        case FAULT:
            if (__log.isDebugEnabled())
                __log.debug("Fault response message: " + mex.getFault());
            throw new ODEInvocationException(
                    "FAULT received from BPEL process : " + mex.getFault() + " " + mex.getFaultExplanation());
        case ASYNC:
        case RESPONSE:
            //process the method invocation result
            response = processResponse(mex.getResponse().getMessage());
            if (__log.isDebugEnabled())
                __log.debug("Response message " + response);
            break;
        case FAILURE:
            if (__log.isDebugEnabled())
                __log.debug("Failure response message: " + mex.getFault());
            break;
        default:
            throw new ODEInvocationException(
                    "FAILURE received from BPEL process : " + mex.getStatus() + " - " + mex.getFault());
        } // end switch

        txMgr.commit();
        // end of transaction two
    } catch (Exception e) {
        try {
            txMgr.rollback();
        } catch (SystemException se) {

        }
        throw new InvocationTargetException(e,
                "Error retrieving BPEL process invocation status : " + e.getMessage());
    } // end try

    // Cleanup the ODE MessageExchange object
    //mex.release();

    return response;
}

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  2  s. c  o 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);
        }
    }

}

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

/**
 * <p>Set the specified property value, performing type conversions as
 * required to conform to the type of the destination property.</p>
 *
 * <p>If the property is read only then the method returns 
 * without throwing an exception.</p>
 *
 * <p>If <code>null</code> is passed into a property expecting a primitive value,
 * then this will be converted as if it were a <code>null</code> string.</p>
 *
 * <p><strong>WARNING</strong> - The logic of this method is customized
 * to meet the needs of <code>populate()</code>, and is probably not what
 * you want for general property copying with type conversion.  For that
 * purpose, check out the <code>copyProperty()</code> method instead.</p>
 *
 * <p><strong>WARNING</strong> - PLEASE do not modify the behavior of this
 * method without consulting with the Struts developer community.  There
 * are some subtleties to its functionality that are not documented in the
 * Javadoc description above, yet are vital to the way that Struts utilizes
 * this method.</p>//from w w  w.  java  2s .  c o  m
 *
 * @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 setProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {

    // Trace logging (if enabled)
    if (log.isTraceEnabled()) {
        StringBuffer sb = new StringBuffer("  setProperty(");
        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 = findLastNestedIndex(name);
    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 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 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
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();
        } else if (descriptor instanceof IndexedPropertyDescriptor) {
            if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else {
            if (descriptor.getWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
        }
    }

    // Convert the specified value to the required type
    Object newValue = null;
    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value == null) {
            String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert((String[]) values, type);
        } else if (value instanceof String) {
            String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert((String[]) values, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert((String[]) value, type);
        } else {
            newValue = value;
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String) {
            newValue = getConvertUtils().convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = value;
        }
    } else { // Value into scalar
        if ((value instanceof String) || (value == null)) {
            newValue = getConvertUtils().convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type);
        } else if (getConvertUtils().lookup(value.getClass()) != null) {
            newValue = getConvertUtils().convert(value.toString(), type);
        } else {
            newValue = value;
        }
    }

    // Invoke the setter method
    try {
        if (index >= 0) {
            getPropertyUtils().setIndexedProperty(target, propName, index, newValue);
        } else if (key != null) {
            getPropertyUtils().setMappedProperty(target, propName, key, newValue);
        } else {
            getPropertyUtils().setProperty(target, propName, newValue);
        }
    } catch (NoSuchMethodException e) {
        throw new InvocationTargetException(e, "Cannot set " + propName);
    }

}

From source file:org.evergreen.web.utils.beanutils.BeanUtilsBean.java

/**
 * <p>Set the specified property value, performing type conversions as
 * required to conform to the type of the destination property.</p>
 *
 * <p>If the property is read only then the method returns 
 * without throwing an exception.</p>
 *
 * <p>If <code>null</code> is passed into a property expecting a primitive value,
 * then this will be converted as if it were a <code>null</code> string.</p>
 *
 * <p><strong>WARNING</strong> - The logic of this method is customized
 * to meet the needs of <code>populate()</code>, and is probably not what
 * you want for general property copying with type conversion.  For that
 * purpose, check out the <code>copyProperty()</code> method instead.</p>
 *
 * <p><strong>WARNING</strong> - PLEASE do not modify the behavior of this
 * method without consulting with the Struts developer community.  There
 * are some subtleties to its functionality that are not documented in the
 * Javadoc description above, yet are vital to the way that Struts utilizes
 * this method.</p>/* ww  w.j  ava  2 s.  c  om*/
 *
 * @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 setProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {
    // Trace logging (if enabled)
    if (log.isTraceEnabled()) {
        StringBuffer sb = new StringBuffer("  setProperty(");
        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;
    Resolver resolver = getPropertyUtils().getResolver();
    while (resolver.hasNested(name)) {
        try {
            target = getPropertyUtils().getProperty(target, resolver.next(name));
            name = resolver.remove(name);
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("    Target bean = " + target);
        log.trace("    Target name = " + name);
    }

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

    // Calculate the 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 if (target instanceof Map) {
        type = Object.class;
    } else if (target != null && target.getClass().isArray() && index >= 0) {
        type = Array.get(target, index).getClass();
    } 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
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();
        } else if (index >= 0 && descriptor instanceof IndexedPropertyDescriptor) {
            if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else if (key != null) {
            if (descriptor.getReadMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = (value == null) ? Object.class : value.getClass();
        } else {
            if (descriptor.getWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
        }
    }

    // Convert the specified value to the required type
    Object newValue = null;
    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value == null) {
            String[] values = new String[1];
            values[0] = null;
            newValue = getConvertUtils().convert(values, type);
        } else if (value instanceof String) {
            newValue = getConvertUtils().convert(value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert((String[]) value, type);
        } else {
            newValue = convert(value, type);
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String || value == null) {
            newValue = getConvertUtils().convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = convert(value, type.getComponentType());
        }
    } else { // Value into scalar
        if (value instanceof String) {
            newValue = getConvertUtils().convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type);
        } else {
            newValue = convert(value, type);
        }
    }

    // Invoke the setter method
    try {
        getPropertyUtils().setProperty(target, name, newValue);
    } catch (NoSuchMethodException e) {
        throw new InvocationTargetException(e, "Cannot set " + propName);
    }

}

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 ww w  . j  av a  2  s  . co  m
        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.jaffa.qm.finder.apis.ExcelExportService.java

/**
 * Creates a JsonConfig with the rootClass set to the input. Adds
 * custom-support for handling FlexCriteriaBean.
 *///from w ww  .  j a va 2 s.  com
private static JsonConfig createJsonConfig(Class rootClass) {
    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.setRootClass(rootClass);
    jsonConfig.setNewBeanInstanceStrategy(new NewBeanInstanceStrategy() {
        public Object newInstance(Class target, JSONObject source) throws InstantiationException,
                IllegalAccessException, SecurityException, NoSuchMethodException, InvocationTargetException {
            if (target == FlexCriteriaBean.class) {
                try {
                    // Determine the name of the associated dynaClass and
                    // use that to instantiate the FlexCriteriaBean
                    JSONObject dynaClassObject = source.getJSONObject("dynaClass");
                    String dynaClassName = dynaClassObject.getString("name");
                    FlexCriteriaBean bean = FlexCriteriaBean.instance(FlexClass.instance(dynaClassName));

                    // Add the criteria elements
                    source.remove("dynaClass");
                    for (Iterator i = source.keys(); i.hasNext();) {
                        String key = (String) i.next();
                        Class propType = bean.getDynaClass() != null
                                && bean.getDynaClass().getDynaProperty(key) != null
                                        ? bean.getDynaClass().getDynaProperty(key).getType()
                                        : String.class;
                        propType = findCriteriaFieldClass(propType);
                        Object propValue = JSONObject.toBean(source.getJSONObject(key), propType);
                        bean.set(key, propValue);
                    }
                    source.clear();

                    return bean;
                } catch (Exception e) {
                    String s = "Exception thrown while instantiating FlexCriteriaBean from " + source;
                    log.error(s, e);
                    throw new InvocationTargetException(e, s);
                }
            }
            return target.newInstance();
        }
    });
    return jsonConfig;
}

From source file:org.kawanfw.sql.servlet.DatabaseMetaDataExecutor.java

/**
 * //  w  w  w  .  ja va 2s.  c  o  m
 * Calls a remote metadata method from the PC <br>
 * 
 * @throws IOException
 *             all network, etc. errors
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws NoSuchMethodException
 * @throws SecurityException
 * @throws InvocationTargetException
 * @throws IllegalArgumentException
 */
private void callMetaDataFunction(HttpServletRequest request, OutputStream out, Connection connection)
        throws SQLException, IOException, ClassNotFoundException, InstantiationException,
        IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException

{

    // The method name
    String methodName = request.getParameter(Parameter.METHOD_NAME);
    // methodName = HtmlConverter.fromHtml(methodName);

    // The parms name
    String paramsTypes = request.getParameter(Parameter.PARAMS_TYPES);
    String paramsValues = request.getParameter(Parameter.PARAMS_VALUES);

    // Make sure all values are not null and trimed

    methodName = this.getTrimValue(methodName);
    paramsTypes = this.getTrimValue(paramsTypes);
    paramsValues = this.getTrimValue(paramsValues);

    debug("actionInvokeRemoteMethod:methodName       : " + methodName);

    // paramsTypes = HtmlConverter.fromHtml(paramsTypes);
    // paramsValues = HtmlConverter.fromHtml(paramsValues);

    List<String> listParamsTypes = ListOfStringTransport.fromJson(paramsTypes);
    List<String> listParamsValues = ListOfStringTransport.fromJson(paramsValues);

    debug("actionInvokeRemoteMethod:listParamsTypes      : " + listParamsTypes);
    debug("actionInvokeRemoteMethod:listParamsValues     : " + listParamsValues);

    DatabaseMetaData databaseMetaData = connection.getMetaData();

    // Trap DatabaseMetaData.getTables() & DatabaseMetaData.getUDTs()
    // that have special array String[] or int[] parameters
    if (methodName.equals("getTables") || methodName.equals("getUDTs") || methodName.equals("getPrimaryKeys")) {
        DatabaseMetaDataSpecial databaseMetaDataSpecial = new DatabaseMetaDataSpecial(databaseMetaData,
                methodName, listParamsValues);
        ResultSet rs = databaseMetaDataSpecial.execute();
        dumpResultSetOnServletOutStream(rs);
        return;
    }

    @SuppressWarnings("rawtypes")
    Class[] argTypes = new Class[listParamsTypes.size()];
    Object[] values = new Object[listParamsValues.size()];

    for (int i = 0; i < listParamsTypes.size(); i++) {
        String value = listParamsValues.get(i);

        String javaType = listParamsTypes.get(i);
        JavaValueBuilder javaValueBuilder = new JavaValueBuilder(javaType, value);

        argTypes[i] = javaValueBuilder.getClassOfValue();
        values[i] = javaValueBuilder.getValue();

        // Trap NULL values
        if (values[i].equals("NULL")) {
            values[i] = null;
        }

        debug("argTypes[i]: " + argTypes[i]);
        debug("values[i]  : " + values[i]);
    }

    Class<?> c = Class.forName("java.sql.DatabaseMetaData");
    Object theObject = databaseMetaData;

    // Invoke the method
    Method main = null;
    Object resultObj = null;

    // Get the Drvier Info
    String database = "";
    String productVersion = "";
    String DriverName = "";
    String DriverVersion = "";
    String driverInfo = Tag.PRODUCT;

    // try {
    // database = databaseMetaData.getDatabaseProductName();
    // productVersion = databaseMetaData.getDatabaseProductVersion();
    // DriverName = databaseMetaData.getDriverName();
    // DriverVersion= databaseMetaData.getDriverVersion();
    // driverInfo += database + " " + productVersion + " " + DriverName +
    // " " + DriverVersion;
    // } catch (Exception e1) {
    // ServerLogger.getLogger().log(Level.WARNING, Tag.PRODUCT +
    // "Impossible to get User Driver info.");
    // }

    database = databaseMetaData.getDatabaseProductName();
    productVersion = databaseMetaData.getDatabaseProductVersion();
    DriverName = databaseMetaData.getDriverName();
    DriverVersion = databaseMetaData.getDriverVersion();
    driverInfo += database + " " + productVersion + " " + DriverName + " " + DriverVersion;

    String methodParams = getMethodParams(values);

    try {
        main = c.getDeclaredMethod(methodName, argTypes);
    } catch (SecurityException e) {
        throw new SecurityException(driverInfo + " - Security - Impossible to get declared DatabaseMetaData."
                + methodName + "(" + methodParams + ")");
    } catch (NoSuchMethodException e) {
        throw new NoSuchMethodException(
                driverInfo + " - No Such Method - Impossible get declared DatabaseMetaData." + methodName + "("
                        + methodParams + ")");
    }

    try {
        resultObj = main.invoke(theObject, values);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(
                driverInfo + " - Impossible to call DatabaseMetaData." + methodName + "(" + methodParams + ")");
    } catch (IllegalAccessException e) {
        throw new IllegalAccessException(driverInfo + " - Impossible to access DatabaseMetaData method."
                + methodName + "(" + methodParams + ")");
    } catch (InvocationTargetException e) {
        throw new InvocationTargetException(e, driverInfo + " - Impossible to invoke DatabaseMetaData method."
                + methodName + "(" + methodParams + ")");
    }

    if (resultObj instanceof ResultSet) {
        ResultSet rs = (ResultSet) resultObj;
        dumpResultSetOnServletOutStream(rs);

    } else {
        // All other formats are handled in String
        String result = null;
        if (resultObj != null)
            result = resultObj.toString();
        debug("actionInvokeRemoteMethod:result: " + result);
        result = HtmlConverter.toHtml(result);

        //out.println(TransferStatus.SEND_OK);
        //out.println(result);
        ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);
        ServerSqlManager.writeLine(out, result);
    }

}

From source file:org.locationtech.udig.processingtoolbox.tools.FieldCalculatorDialog.java

@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    monitor.beginTask(String.format(Messages.Task_Executing, windowTitle), 100);

    String folder = ToolboxView.getWorkspace();
    DataStore outputDataStore = DataStoreFactory.getShapefileDataStore(folder);
    String outputTypeName = null;

    try {/*from   w  w w  . j  ava 2  s  .  c  o  m*/
        // Convert the given monitor into a progress instance
        final SubMonitor progress = SubMonitor.convert(monitor, 100);

        // prepare parameters
        Expression expression = ECQL.toExpression(txtExpression.getText());
        String field = cboField.getText();
        Class<?> fieldBinding = String.class;
        if (FeatureTypes.existProeprty(source.getSchema(), field)) {
            AttributeDescriptor attr = source.getSchema().getDescriptor(field);
            fieldBinding = attr.getType().getBinding();
        } else {
            try {
                fieldBinding = new TextColumn().findBestBinding(cboType.getText());
            } catch (Exception ee) {
                ToolboxPlugin.log(ee.getMessage());
            }
        }
        int length = spnLen.getSelection();
        monitor.worked(increment);

        // execute process
        String outputName = getUniqueName(folder, "calc_");
        FieldCalculatorOperation process = new FieldCalculatorOperation(outputName);
        process.setOutputDataStore(outputDataStore);
        SimpleFeatureCollection features = process.execute(source, expression, field, fieldBinding, length,
                progress.newChild(70));

        // post process
        if (features != null) {
            Date now = Calendar.getInstance().getTime();

            // remove service
            IService service = layer.getGeoResource().service(progress.newChild(5));
            final ID id = service.getID();
            final Map<java.lang.String, Serializable> params = service.getConnectionParams();
            service.dispose(progress.newChild(10));
            while (service.getStatus() == Status.CONNECTED) {
                Thread.sleep(100);
            }

            // replace dbf file
            String shpPath = DataUtilities.urlToFile(id.toURL()).getPath(); // .shp
            File dbfFile = new File(FilenameUtils.removeExtension(shpPath) + ".dbf");

            File tempFile = new File(dbfFile.getParent(), "fc_" + df.format(now) + ".dbf");
            if (dbfFile.renameTo(tempFile)) {
                File newFile = new File(folder, outputName + ".dbf");
                org.apache.commons.io.FileUtils.copyFile(newFile, dbfFile);
                tempFile.delete();
                updateFields(layer.getSchema());
                fillFields(cboField, layer.getSchema(), FieldType.ALL);
                cboType.setText("");
            } else {
                throw new Exception(Messages.FieldCalculatorDialog_Failed);
            }

            // reload service
            IServiceFactory serviceFactory = CatalogPlugin.getDefault().getServiceFactory();
            ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();
            IService replacement = serviceFactory.createService(params).get(0);
            catalog.replace(id, replacement);
            layer.refresh(map.getViewportModel().getBounds());

            monitor.worked(increment);
        }
        monitor.worked(increment);
    } catch (Exception e) {
        ToolboxPlugin.log(e.getMessage());
        throw new InvocationTargetException(e.getCause(), e.getMessage());
    } finally {
        // finally delete temporary files
        new ShapeFileEditor().remove(outputDataStore, outputTypeName);
        monitor.done();
    }
}