Exemplo n.º 1
1
  /**
   * Coerce the given object to targetType.
   *
   * @param value object to be coerced
   * @param targetType which should be object coerced into
   * @return the given value coerced to targetType
   */
  public static <T> T coerce(Object value, Class<T> targetType) {
    if (value == null) {
      return null;
    }

    if (targetType.isInstance(value)) {
      return targetType.cast(value);
    }

    if (value instanceof String) {
      PropertyEditor editor = PropertyEditorManager.findEditor(targetType);
      if (editor == null && Primitives.isWrapperType(targetType)) {
        editor = PropertyEditorManager.findEditor(Primitives.unwrap(targetType));
      }

      if (editor != null) {

        editor.setAsText((String) value);
        return targetType.cast(editor.getValue());
      } else if (targetType.isEnum()) {
        return targetType.cast(Enum.valueOf((Class<Enum>) targetType, (String) value));
      }
    }

    throw new IllegalArgumentException(
        MessageFormat.format(
            "Cannot convert {0} to object of {1} type", value, targetType.getName()));
  }
  private static Object newValue(final Class<?> type, final String value) {
    final PropertyEditor editor = PropertyEditorFinder.getInstance().find(type);
    if (editor == null) {
      SarLogger.ROOT_LOGGER.propertyNotFound(type);
      return null;
    }
    editor.setAsText(value);

    return editor.getValue();
  }
Exemplo n.º 3
0
 /**
  * Convert a string value to its Object value.
  *
  * @param value - String value
  * @param prop - PropertyDescriptor
  * @return The object set to value (i.e. Integer). Will return String if no PropertyEditor is
  *     found.
  * @throws InstantiationException - Thrown on error getting the property editor from the property
  *     descriptor.
  * @throws IllegalAccessException - Thrown on error getting the property editor from the property
  *     descriptor.
  */
 protected Object convertValue(String value, PropertyDescriptor prop)
     throws InstantiationException, IllegalAccessException {
   PropertyEditor editor = getPropertyEditor(prop);
   Object obj = value;
   if (null != editor) {
     editor.setAsText(value);
     obj = editor.getValue();
   }
   return obj;
 }
 /**
  * Convert the given text value using the given property editor.
  *
  * @param oldValue the previous value, if available (may be <code>null</code>)
  * @param newTextValue the proposed text value
  * @param editor the PropertyEditor to use
  * @return the converted value
  */
 protected Object doConvertTextValue(Object oldValue, String newTextValue, PropertyEditor editor) {
   try {
     editor.setValue(oldValue);
   } catch (Exception ex) {
     if (logger.isDebugEnabled()) {
       logger.debug(
           "PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call",
           ex);
     }
     // Swallow and proceed.
   }
   editor.setAsText(newTextValue);
   return editor.getValue();
 }
  public Element getElementServiceBindingValue(ServiceBinding binding, Element input) {
    if (input == null) throw new IllegalArgumentException("input cannot be null");

    PropertyEditor editor = PropertyEditorFinder.getInstance().find(Element.class);
    if (editor == null)
      throw new IllegalStateException("Cannot find PropertyEditor for type Element");

    editor.setValue(input);
    Reader reader = new StringReader(editor.getAsText());
    Writer writer = new StringWriter();

    doXslTransform(binding, getConfig(binding), reader, writer);

    editor.setAsText(writer.toString());
    return (Element) editor.getValue();
  }
 public static Object getValueFromBeanInfoPropertyEditor(
     Class<?> attrClass, String attrName, String attrValue, Class<?> propertyEditorClass)
     throws JasperException {
   try {
     PropertyEditor pe = (PropertyEditor) propertyEditorClass.newInstance();
     pe.setAsText(attrValue);
     return pe.getValue();
   } catch (Exception ex) {
     throw new JasperException(
         Localizer.getMessage(
             "jsp.error.beans.property.conversion",
             attrValue,
             attrClass.getName(),
             attrName,
             ex.getMessage()));
   }
 }
Exemplo n.º 7
0
 private static Object convert(TypeConverter typeConverter, Class<?> type, Object value)
     throws URISyntaxException, NoTypeConversionAvailableException {
   if (typeConverter != null) {
     return typeConverter.mandatoryConvertTo(type, value);
   }
   if (type == URI.class) {
     return new URI(value.toString());
   }
   PropertyEditor editor = PropertyEditorManager.findEditor(type);
   if (editor != null) {
     // property editor is not thread safe, so we need to lock
     Object answer;
     synchronized (LOCK) {
       editor.setAsText(value.toString());
       answer = editor.getValue();
     }
     return answer;
   }
   return null;
 }
 public static Object getValueFromPropertyEditorManager(
     Class<?> attrClass, String attrName, String attrValue) throws JasperException {
   try {
     PropertyEditor propEditor = PropertyEditorManager.findEditor(attrClass);
     if (propEditor != null) {
       propEditor.setAsText(attrValue);
       return propEditor.getValue();
     } else {
       throw new IllegalArgumentException(
           Localizer.getMessage("jsp.error.beans.propertyeditor.notregistered"));
     }
   } catch (IllegalArgumentException ex) {
     throw new JasperException(
         Localizer.getMessage(
             "jsp.error.beans.property.conversion",
             attrValue,
             attrClass.getName(),
             attrName,
             ex.getMessage()));
   }
 }
  public Object getValue(ServiceValueContext valueContext) throws Exception {
    MBeanAttributeInfo attributeInfo = valueContext.getAttributeInfo();
    ClassLoader cl = valueContext.getClassloader();

    String typeName = attributeInfo.getType();
    if (typeName == null)
      throw new DeploymentException(
          "AttributeInfo for " + attributeInfo.getName() + " has no type");

    // see if it is a primitive type first
    Class typeClass = Classes.getPrimitiveTypeForName(typeName);
    if (typeClass == null) {
      // nope try look up
      try {
        typeClass = cl.loadClass(typeName);
      } catch (ClassNotFoundException e) {
        throw new DeploymentException(
            "Class not found for attribute: " + attributeInfo.getName(), e);
      }
    }

    PropertyEditor editor = PropertyEditorFinder.getInstance().find(typeClass);
    if (editor == null)
      throw new DeploymentException(
          "No property editor for attribute: "
              + attributeInfo.getName()
              + "; type="
              + typeClass.getName());

    // JBAS-1709, temporarily switch the TCL so that property
    // editors have access to the actual deployment ClassLoader.
    ClassLoader tcl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(cl);
    try {
      editor.setAsText(text);
      return editor.getValue();
    } finally {
      Thread.currentThread().setContextClassLoader(tcl);
    }
  }
Exemplo n.º 10
0
 /**
  * Configures the given component by setting the value for the appropriate config option.
  *
  * @param component the component to be configured
  * @param configName the name of the config option
  * @param configValue the value of the config option
  */
 @Deprecated
 public static <T> void configure(Component component, String configName, T configValue) {
   List<Field> fields = getAllFields(component);
   for (Field f : fields) {
     ConfigOption option = f.getAnnotation(ConfigOption.class);
     if (option != null) {
       if (option.name().equals(configName)) {
         try {
           PropertyEditor editor = PropertyEditor.class.newInstance();
           editor.setAsText(configValue.toString());
           Method method =
               component
                   .getClass()
                   .getMethod(
                       "set"
                           + Character.toUpperCase(f.getName().charAt(0))
                           + f.getName().substring(1),
                       getClassForObject(editor.getValue()));
           method.invoke(component, editor.getValue());
         } catch (IllegalArgumentException e) {
           e.printStackTrace();
         } catch (InstantiationException e) {
           e.printStackTrace();
         } catch (IllegalAccessException e) {
           e.printStackTrace();
         } catch (InvocationTargetException e) {
           e.printStackTrace();
         } catch (SecurityException e) {
           e.printStackTrace();
         } catch (NoSuchMethodException e) {
           e.printStackTrace();
         }
       }
     }
   }
 }
  /**
   * Convert the value to the required type (if necessary from a String), for the specified
   * property.
   *
   * @param propertyName name of the property
   * @param oldValue previous value, if available (may be <code>null</code>)
   * @param newValue proposed change value
   * @param requiredType the type we must convert to (or <code>null</code> if not known, for example
   *     in case of a collection element)
   * @return the new value, possibly the result of type conversion
   * @throws TypeMismatchException if type conversion failed
   */
  protected Object doTypeConversionIfNecessary(
      String propertyName,
      String fullPropertyName,
      Object oldValue,
      Object newValue,
      Class requiredType)
      throws TypeMismatchException {

    Object convertedValue = newValue;
    if (convertedValue != null) {

      // Custom editor for this type?
      PropertyEditor pe = findCustomEditor(requiredType, fullPropertyName);

      // Value not of required type?
      if (pe != null
          || (requiredType != null
              && (requiredType.isArray()
                  || !requiredType.isAssignableFrom(convertedValue.getClass())))) {

        if (requiredType != null) {
          if (pe == null) {
            // No custom editor -> check BeanWrapperImpl's default editors.
            pe = (PropertyEditor) getDefaultEditor(requiredType);
            if (pe == null) {
              // No BeanWrapper default editor -> check standard JavaBean editors.
              pe = PropertyEditorManager.findEditor(requiredType);
            }
          }
        }

        if (pe != null && !(convertedValue instanceof String)) {
          // Not a String -> use PropertyEditor's setValue.
          // With standard PropertyEditors, this will return the very same object;
          // we just want to allow special PropertyEditors to override setValue
          // for type conversion from non-String values to the required type.
          try {
            pe.setValue(convertedValue);
            Object newConvertedValue = pe.getValue();
            if (newConvertedValue != convertedValue) {
              convertedValue = newConvertedValue;
              // Reset PropertyEditor: It already did a proper conversion.
              // Don't use it again for a setAsText call.
              pe = null;
            }
          } catch (IllegalArgumentException ex) {
            throw new TypeMismatchException(
                createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType, ex);
          }
        }

        if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[]) {
          // Convert String array to a comma-separated String.
          // Only applies if no PropertyEditor converted the String array before.
          // The CSV String will be passed into a PropertyEditor's setAsText method, if any.
          if (logger.isDebugEnabled()) {
            logger.debug(
                "Converting String array to comma-delimited String [" + convertedValue + "]");
          }
          convertedValue = StringUtils.arrayToCommaDelimitedString((String[]) convertedValue);
        }

        if (pe != null && convertedValue instanceof String) {
          // Use PropertyEditor's setAsText in case of a String value.
          if (logger.isDebugEnabled()) {
            logger.debug(
                "Converting String to [" + requiredType + "] using property editor [" + pe + "]");
          }
          try {
            pe.setValue(oldValue);
            pe.setAsText((String) convertedValue);
            convertedValue = pe.getValue();
          } catch (IllegalArgumentException ex) {
            throw new TypeMismatchException(
                createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType, ex);
          }
        }

        if (requiredType != null) {
          // Array required -> apply appropriate conversion of elements.
          if (requiredType.isArray()) {
            Class componentType = requiredType.getComponentType();
            if (convertedValue instanceof Collection) {
              // Convert Collection elements to array elements.
              Collection coll = (Collection) convertedValue;
              Object result = Array.newInstance(componentType, coll.size());
              int i = 0;
              for (Iterator it = coll.iterator(); it.hasNext(); i++) {
                Object value =
                    doTypeConversionIfNecessary(
                        propertyName,
                        propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX,
                        null,
                        it.next(),
                        componentType);
                Array.set(result, i, value);
              }
              return result;
            } else if (convertedValue != null && convertedValue.getClass().isArray()) {
              // Convert Collection elements to array elements.
              int arrayLength = Array.getLength(convertedValue);
              Object result = Array.newInstance(componentType, arrayLength);
              for (int i = 0; i < arrayLength; i++) {
                Object value =
                    doTypeConversionIfNecessary(
                        propertyName,
                        propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX,
                        null,
                        Array.get(convertedValue, i),
                        componentType);
                Array.set(result, i, value);
              }
              return result;
            } else {
              // A plain value: convert it to an array with a single component.
              Object result = Array.newInstance(componentType, 1);
              Object value =
                  doTypeConversionIfNecessary(
                      propertyName,
                      propertyName + PROPERTY_KEY_PREFIX + 0 + PROPERTY_KEY_SUFFIX,
                      null,
                      convertedValue,
                      componentType);
              Array.set(result, 0, value);
              return result;
            }
          }

          // If the resulting value definitely doesn't match the required type,
          // try field lookup as fallback. If no matching field found,
          // throw explicit TypeMismatchException with full context information.
          if (convertedValue != null
              && !requiredType.isPrimitive()
              && !requiredType.isAssignableFrom(convertedValue.getClass())) {

            // In case of String value, try to find matching field (for JDK 1.5
            // enum or custom enum with values defined as static fields).
            if (convertedValue instanceof String) {
              try {
                Field enumField = requiredType.getField((String) convertedValue);
                return enumField.get(null);
              } catch (Exception ex) {
                logger.debug("Field [" + convertedValue + "] isn't an enum value", ex);
              }
            }

            // Definitely doesn't match: throw TypeMismatchException.
            throw new TypeMismatchException(
                createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType);
          }
        }
      }
    }

    return convertedValue;
  }
  protected synchronized XADataSource getXADataSource() throws ResourceException {
    if (xadsSelector != null) {
      XAData xada = (XAData) xadsSelector.getUrlObject();
      return xada.xads;
    }
    if (xads == null) {
      if (xaDataSourceClass == null)
        throw new JBossResourceException("No XADataSourceClass supplied!");
      try {
        Class clazz = Thread.currentThread().getContextClassLoader().loadClass(xaDataSourceClass);
        xads = (XADataSource) clazz.newInstance();
        Class[] NOCLASSES = new Class[] {};
        for (Iterator i = xaProps.keySet().iterator(); i.hasNext(); ) {
          String name = (String) i.next();
          String value = xaProps.getProperty(name);
          char firstCharName = Character.toUpperCase(name.charAt(0));
          if (name.length() > 1) name = firstCharName + name.substring(1);
          else name = "" + firstCharName;
          // This is a bad solution.  On the other hand the only known example
          // of a setter with no getter is for Oracle with password.
          // Anyway, each xadatasource implementation should get its
          // own subclass of this that explicitly sets the
          // properties individually.
          Class type = null;
          try {
            Method getter = clazz.getMethod("get" + name, NOCLASSES);
            type = getter.getReturnType();
          } catch (NoSuchMethodException e) {
            try {
              // HACK for now until we can rethink the XADataSourceProperties variable and pass type
              // information
              Method isMethod = clazz.getMethod("is" + name, NOCLASSES);
              type = isMethod.getReturnType();

            } catch (NoSuchMethodException nsme) {
              type = String.class;
            }
          }

          Method setter = clazz.getMethod("set" + name, new Class[] {type});
          PropertyEditor editor = PropertyEditorManager.findEditor(type);
          if (editor == null)
            throw new JBossResourceException("No property editor found for type: " + type);
          editor.setAsText(value);
          setter.invoke(xads, new Object[] {editor.getValue()});
        }
      } catch (ClassNotFoundException cnfe) {
        throw new JBossResourceException(
            "Class not found for XADataSource " + xaDataSourceClass, cnfe);
      } catch (InstantiationException ie) {
        throw new JBossResourceException("Could not create an XADataSource: ", ie);
      } catch (IllegalAccessException iae) {
        throw new JBossResourceException("Could not set a property: ", iae);
      } catch (IllegalArgumentException iae) {
        throw new JBossResourceException("Could not set a property: ", iae);
      } catch (InvocationTargetException ite) {
        throw new JBossResourceException("Could not invoke setter on XADataSource: ", ite);
      } catch (NoSuchMethodException nsme) {
        throw new JBossResourceException("Could not find accessor on XADataSource: ", nsme);
      }
    }
    return xads;
  }
Exemplo n.º 13
0
  @SuppressWarnings("rawtypes")
  private static MenuManager generateListEditorFor(
      final IMenuManager manager,
      final MenuManager subMenu,
      final PropertyDescriptor thisP,
      final Editable[] editables,
      final Layers theLayers,
      final Layer topLevelLayer) {

    // find out the type of the editor
    final Method m = thisP.getReadMethod();
    final Class cl = m.getReturnType();
    MenuManager result = subMenu;

    // is there a custom editor for this type?
    final Class c = thisP.getPropertyEditorClass();

    PropertyEditor pe = null;
    // try to create an editor for this class
    try {
      if (c != null) pe = (PropertyEditor) c.newInstance();
    } catch (final Exception e) {
      MWC.Utilities.Errors.Trace.trace(e);
    }

    // did it work?
    if (pe == null) {
      // try to find an editor for this through our manager
      pe = PropertyEditorManager.findEditor(cl);
    }

    // retrieve the tags
    final String[] tags = pe.getTags();

    // are there any tags for this class?
    if (tags != null) {
      // create a drop-down list
      final MenuManager thisChoice = new MenuManager(thisP.getDisplayName());

      // sort out the setter details
      final Method getter = thisP.getReadMethod();

      // get the current value
      Object val = null;
      try {
        val = getter.invoke(editables[0], (Object[]) null);
      } catch (final Exception e) {
        MWC.Utilities.Errors.Trace.trace(e);
      }
      pe.setValue(val);

      // convert the current value to text
      final String currentValue = pe.getAsText();

      // and now a drop-down item for each options
      for (int j = 0; j < tags.length; j++) {
        final String thisTag = tags[j];
        pe.setAsText(thisTag);
        final Object thisValue = pe.getValue();

        // create the item
        final IAction thisA =
            new Action(thisTag, IAction.AS_RADIO_BUTTON) {
              public void run() {
                try {
                  // hey, since this is a radio button, we get two events when the
                  // selection changes - one for the value being unset, and the
                  // other
                  // for the value being set. So just fire for the new value (the
                  // one that's checked)
                  if (isChecked()) {
                    final Method setter = thisP.getWriteMethod();

                    // ok, place the change in the action
                    final ListPropertyAction la =
                        new ListPropertyAction(
                            thisP.getDisplayName(),
                            editables,
                            getter,
                            setter,
                            thisValue,
                            theLayers,
                            topLevelLayer);

                    // and add it to the history
                    CorePlugin.run(la);
                  }
                } catch (final Exception e) {
                  CorePlugin.logError(
                      IStatus.INFO, "While executing select editor for:" + thisP, e);
                }
              }
            };

        // is this the current one?
        if (thisTag.equals(currentValue)) {
          thisA.setChecked(true);
        }

        // add it to the menu
        thisChoice.add(thisA);
      }

      // is our sub-menu already created?
      if (result == null) {
        String nameStr;
        if (editables.length > 1) nameStr = MULTIPLE_ITEMS_STR;
        else nameStr = editables[0].getName();

        result = new MenuManager(nameStr);
        manager.add(result);
      }

      result.add(thisChoice);
    }

    return result;
  }
  @Test
  public void testPropertyEditor() throws Exception {

    // test
    Class<T> type = getType();
    PropertyEditor editor = finder.find(type);

    String[] inputData = getInputData();
    Object[] expectedData = getOutputData();
    String[] expectedStringData = getConvertedToText();
    try {
      assertTrue("Did not find property editor for type: " + type, editor != null);
      assertEquals(
          "Editor has wrong package!",
          this.getClass().getPackage(),
          editor.getClass().getPackage());
      logger.finest(
          "Found property editor for: " + type + ", editor=" + editor.getClass().getName());
      assertEquals(editor + " input length", inputData.length, expectedData.length);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    for (int i = 0; i < inputData.length; i++) {
      String input = inputData[i];
      editor.setAsText(input);
      // TODO: check instance?
      T expected = (T) expectedData[i];
      T output = (T) editor.getValue();

      Comparator<T> c = getComparator();
      boolean equals = false;
      if (c == null) {
        equals = output != null ? output.equals(expected) : expected == null;
      } else {
        equals = c.compare(output, expected) == 0;
      }

      assertTrue(
          "Test at index '"
              + i
              + "'. Transform("
              + editor
              + ") of "
              + input
              + "\n does not equal! \nexpected = "
              + logT(expected)
              + "\noutput = "
              + logT(output),
          equals);

      String expectedStringOutput = expectedStringData[i];
      String stringOutput = editor.getAsText();
      logger.finest("setAsText '" + logString(input) + "'");
      logger.finest("getAsText '" + logString(stringOutput) + "'");
      if (type != Properties.class) {
        // We can't meaningfully compare the PropertiesEditor string output
        String msg =
            "Test at index '"
                + i
                + "'. PropertyEditor: "
                + editor.getClass().getName()
                + ", getAsText() == expectedStringOutput '";
        assertEquals(msg, expectedStringOutput, stringOutput);
      }
    }
  }
Exemplo n.º 15
0
  public static void setValues(
      Object target, Map<?, ?> attribs, boolean isXmlAttribs, boolean failOnMissingSetter) {
    Class<?> objectClass = target.getClass();

    // go thru simple string setters first.
    for (Map.Entry<?, ?> entry : attribs.entrySet()) {
      String propName = (String) entry.getKey();
      String setter = BeanUtils.setterName(propName);
      String fluentSetter = BeanUtils.fluentSetterName(propName);

      try {
        Method method;
        if (isXmlAttribs) {
          method = objectClass.getMethod(setter, Element.class);
          method.invoke(target, entry.getValue());
        } else {
          method = objectClass.getMethod(setter, String.class);
          method.invoke(target, entry.getValue());
        }

        continue;
      } catch (NoSuchMethodException me) {
        // this is ok, but certainly log this as a warning
        // this is hugely noisy!
        // if (log.isWarnEnabled()) log.warn("Unrecognised attribute " + propName + ".  Please check
        // your configuration.  Ignoring!!");
      } catch (Exception e) {
        throw new CacheConfigurationException(
            "Unable to invoke setter " + setter + " on " + objectClass, e);
      }

      boolean setterFound = false;
      // if we get here, we could not find a String or Element setter.
      for (Method m : objectClass.getMethods()) {
        if (setter.equals(m.getName()) || fluentSetter.equals(m.getName())) {
          Class<?> paramTypes[] = m.getParameterTypes();
          if (paramTypes.length != 1) {
            log.tracef(
                "Rejecting setter %s on class %s due to incorrect number of parameters",
                m, objectClass);
            continue; // try another param with the same name.
          }

          Class<?> parameterType = paramTypes[0];
          PropertyEditor editor = PropertyEditorManager.findEditor(parameterType);
          if (editor == null) {
            throw new CacheConfigurationException(
                "Couldn't find a property editor for parameter type " + parameterType);
          }

          editor.setAsText((String) attribs.get(propName));

          Object parameter = editor.getValue();
          // if (log.isDebugEnabled()) log.debug("Invoking setter method: " + setter + " with
          // parameter \"" + parameter + "\" of type " + parameter.getClass());

          try {
            m.invoke(target, parameter);
            setterFound = true;
            break;
          } catch (Exception e) {
            throw new CacheConfigurationException(
                "Unable to invoke setter " + setter + " on " + objectClass, e);
          }
        }
      }
      // Skip hot rod properties ...
      if (!setterFound && failOnMissingSetter && !propName.startsWith("infinispan.client.hotrod"))
        throw new CacheConfigurationException(
            "Couldn't find a setter named ["
                + setter
                + "] which takes a single parameter, for parameter "
                + propName
                + " on class ["
                + objectClass
                + "]");
    }
  }