Java Code Examples for org.springframework.beans.BeanWrapper#getPropertyValue()

The following examples show how to use org.springframework.beans.BeanWrapper#getPropertyValue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebLogicRequestUpgradeStrategy.java    From spring-analysis-note with MIT License 8 votes vote down vote up
@Override
protected void handleSuccess(HttpServletRequest request, HttpServletResponse response,
		UpgradeInfo upgradeInfo, TyrusUpgradeResponse upgradeResponse) throws IOException, ServletException {

	response.setStatus(upgradeResponse.getStatus());
	upgradeResponse.getHeaders().forEach((key, value) -> response.addHeader(key, Utils.getHeaderFromList(value)));

	AsyncContext asyncContext = request.startAsync();
	asyncContext.setTimeout(-1L);

	Object nativeRequest = getNativeRequest(request);
	BeanWrapper beanWrapper = new BeanWrapperImpl(nativeRequest);
	Object httpSocket = beanWrapper.getPropertyValue("connection.connectionHandler.rawConnection");
	Object webSocket = webSocketHelper.newInstance(request, httpSocket);
	webSocketHelper.upgrade(webSocket, httpSocket, request.getServletContext());

	response.flushBuffer();

	boolean isProtected = request.getUserPrincipal() != null;
	Writer servletWriter = servletWriterHelper.newInstance(webSocket, isProtected);
	Connection connection = upgradeInfo.createConnection(servletWriter, noOpCloseListener);
	new BeanWrapperImpl(webSocket).setPropertyValue("connection", connection);
	new BeanWrapperImpl(servletWriter).setPropertyValue("connection", connection);
	webSocketHelper.registerForReadEvent(webSocket);
}
 
Example 2
Source File: PropertyPathFactoryBean.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object getObject() throws BeansException {
	BeanWrapper target = this.targetBeanWrapper;
	if (target != null) {
		if (logger.isWarnEnabled() && this.targetBeanName != null &&
				this.beanFactory instanceof ConfigurableBeanFactory &&
				((ConfigurableBeanFactory) this.beanFactory).isCurrentlyInCreation(this.targetBeanName)) {
			logger.warn("Target bean '" + this.targetBeanName + "' is still in creation due to a circular " +
					"reference - obtained value for property '" + this.propertyPath + "' may be outdated!");
		}
	}
	else {
		// Fetch prototype target bean...
		Object bean = this.beanFactory.getBean(this.targetBeanName);
		target = PropertyAccessorFactory.forBeanPropertyAccess(bean);
	}
	return target.getPropertyValue(this.propertyPath);
}
 
Example 3
Source File: PropertyPathFactoryBean.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public Object getObject() throws BeansException {
	BeanWrapper target = this.targetBeanWrapper;
	if (target != null) {
		if (logger.isWarnEnabled() && this.targetBeanName != null &&
				this.beanFactory instanceof ConfigurableBeanFactory &&
				((ConfigurableBeanFactory) this.beanFactory).isCurrentlyInCreation(this.targetBeanName)) {
			logger.warn("Target bean '" + this.targetBeanName + "' is still in creation due to a circular " +
					"reference - obtained value for property '" + this.propertyPath + "' may be outdated!");
		}
	}
	else {
		// Fetch prototype target bean...
		Object bean = this.beanFactory.getBean(this.targetBeanName);
		target = PropertyAccessorFactory.forBeanPropertyAccess(bean);
	}
	return target.getPropertyValue(this.propertyPath);
}
 
Example 4
Source File: ConvertedDatatablesData.java    From springlets with Apache License 2.0 6 votes vote down vote up
private static Map<String, Object> convert(Object value, ConversionService conversionService) {

    BeanWrapper bean = new BeanWrapperImpl(value);
    PropertyDescriptor[] properties = bean.getPropertyDescriptors();
    Map<String, Object> convertedValue = new HashMap<>(properties.length);

    for (int i = 0; i < properties.length; i++) {
      String name = properties[i].getName();
      Object propertyValue = bean.getPropertyValue(name);
      if (propertyValue != null
          && conversionService.canConvert(propertyValue.getClass(), String.class)) {
        TypeDescriptor source = bean.getPropertyTypeDescriptor(name);
        String convertedPropertyValue =
            (String) conversionService.convert(propertyValue, source, TYPE_STRING);
        convertedValue.put(name, convertedPropertyValue);
      }
    }

    return convertedValue;
  }
 
Example 5
Source File: AbstractMultiCheckedElementTag.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void writeObjectEntry(TagWriter tagWriter, @Nullable String valueProperty,
		@Nullable String labelProperty, Object item, int itemIndex) throws JspException {

	BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(item);
	Object renderValue;
	if (valueProperty != null) {
		renderValue = wrapper.getPropertyValue(valueProperty);
	}
	else if (item instanceof Enum) {
		renderValue = ((Enum<?>) item).name();
	}
	else {
		renderValue = item;
	}
	Object renderLabel = (labelProperty != null ? wrapper.getPropertyValue(labelProperty) : item);
	writeElementTag(tagWriter, item, renderValue, renderLabel, itemIndex);
}
 
Example 6
Source File: BeanUtils.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
private static String[] getNullPropertyNames(Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    PropertyDescriptor[] pds = src.getPropertyDescriptors();

    Set<String> emptyNames = new HashSet<>();
    for (PropertyDescriptor pd : pds) {
        Object srcValue = src.getPropertyValue(pd.getName());
        if (srcValue == null) emptyNames.add(pd.getName());
    }
    String[] result = new String[emptyNames.size()];
    return emptyNames.toArray(result);
}
 
Example 7
Source File: BeanUtils.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
private static String[] getNullPropertyNames(Object source) {
  final BeanWrapper src = new BeanWrapperImpl(source);
  PropertyDescriptor[] pds = src.getPropertyDescriptors();

  Set<String> emptyNames = new HashSet<String>();
  for (PropertyDescriptor pd : pds) {
    Object srcValue = src.getPropertyValue(pd.getName());
    if (srcValue == null) emptyNames.add(pd.getName());
  }
  String[] result = new String[emptyNames.size()];
  return emptyNames.toArray(result);
}
 
Example 8
Source File: AbstractMultiCheckedElementTag.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void writeMapEntry(TagWriter tagWriter, String valueProperty,
		String labelProperty, Map.Entry<?, ?> entry, int itemIndex) throws JspException {

	Object mapKey = entry.getKey();
	Object mapValue = entry.getValue();
	BeanWrapper mapKeyWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapKey);
	BeanWrapper mapValueWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapValue);
	Object renderValue = (valueProperty != null ?
			mapKeyWrapper.getPropertyValue(valueProperty) : mapKey.toString());
	Object renderLabel = (labelProperty != null ?
			mapValueWrapper.getPropertyValue(labelProperty) : mapValue.toString());
	writeElementTag(tagWriter, mapKey, renderValue, renderLabel, itemIndex);
}
 
Example 9
Source File: BeanUtils.java    From spring-microservice-boilerplate with MIT License 5 votes vote down vote up
/**
 * Get names of null properties
 *
 * @param source source object
 */
private static String[] getNamesOfNullProperties(Object source) {
  final BeanWrapper src = new BeanWrapperImpl(source);
  java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

  Set<String> emptyNames = new HashSet<>();
  for (java.beans.PropertyDescriptor pd : pds) {
    Object srcValue = src.getPropertyValue(pd.getName());
    if (srcValue == null) {
      emptyNames.add(pd.getName());
    }
  }
  String[] result = new String[emptyNames.size()];
  return emptyNames.toArray(result);
}
 
Example 10
Source File: BooleanPropertyColumn.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public void populateItem(final Item<ICellPopulator<T>> item, final String componentId, final IModel<T> rowModel) {
    BeanWrapper bwi = new BeanWrapperImpl(rowModel.getObject());
    Object obj = bwi.getPropertyValue(getPropertyExpression());

    item.add(new Label(componentId, StringUtils.EMPTY));
    if (obj != null && Boolean.valueOf(obj.toString())) {
        item.add(new AttributeModifier("class", "fa fa-check"));
        item.add(new AttributeModifier("style", "display: table-cell; text-align: center;"));
    }
}
 
Example 11
Source File: BeanUtils.java    From jdal with Apache License 2.0 5 votes vote down vote up
/**
 * Get property value null if none
 * @param bean beam
 * @param name name
 * @return the property value
 */
public static Object getProperty(Object bean, String name) {
	try {
		BeanWrapper wrapper = new BeanWrapperImpl(bean);
		return wrapper.getPropertyValue(name);
	} catch (BeansException be) {
		log.error(be);
		return null;
	}
}
 
Example 12
Source File: BeanUtils.java    From incubator-wikift with Apache License 2.0 5 votes vote down vote up
/**
 * 将为空的properties给找出来,然后返回出来
 *
 * @param src
 * @return
 */
private static String[] getNullProperties(Object src) {
    BeanWrapper srcBean = new BeanWrapperImpl(src);
    PropertyDescriptor[] pds = srcBean.getPropertyDescriptors();
    Set<String> emptyName = new HashSet<>();
    for (PropertyDescriptor p : pds) {
        Object srcValue = srcBean.getPropertyValue(p.getName());
        if (srcValue == null) emptyName.add(p.getName());
    }
    String[] result = new String[emptyName.size()];
    return emptyName.toArray(result);
}
 
Example 13
Source File: BeanUtils.java    From black-shop with Apache License 2.0 5 votes vote down vote up
private static String[] getNullPropertyNames(Object source) {
  final BeanWrapper src = new BeanWrapperImpl(source);
  PropertyDescriptor[] pds = src.getPropertyDescriptors();

  Set<String> emptyNames = new HashSet<String>();
  for (PropertyDescriptor pd : pds) {
    Object srcValue = src.getPropertyValue(pd.getName());
    if (srcValue == null) emptyNames.add(pd.getName());
  }
  String[] result = new String[emptyNames.size()];
  return emptyNames.toArray(result);
}
 
Example 14
Source File: BSAbstractMultiCheckedElementTag.java    From dubai with MIT License 5 votes vote down vote up
/**
 * Copy & Paste, 无修正.
 */
private void writeMapEntry(TagWriter tagWriter, String valueProperty, String labelProperty, Map.Entry entry,
		int itemIndex) throws JspException {

	Object mapKey = entry.getKey();
	Object mapValue = entry.getValue();
	BeanWrapper mapKeyWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapKey);
	BeanWrapper mapValueWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapValue);
	Object renderValue = (valueProperty != null ? mapKeyWrapper.getPropertyValue(valueProperty) : mapKey.toString());
	Object renderLabel = (labelProperty != null ? mapValueWrapper.getPropertyValue(labelProperty) : mapValue
			.toString());
	writeElementTag(tagWriter, mapKey, renderValue, renderLabel, itemIndex);
}
 
Example 15
Source File: BeanUtils.java    From apollo with Apache License 2.0 5 votes vote down vote up
private static String[] getNullPropertyNames(Object source) {
  final BeanWrapper src = new BeanWrapperImpl(source);
  PropertyDescriptor[] pds = src.getPropertyDescriptors();

  Set<String> emptyNames = new HashSet<>();
  for (PropertyDescriptor pd : pds) {
    Object srcValue = src.getPropertyValue(pd.getName());
    if (srcValue == null) {
        emptyNames.add(pd.getName());
    }
  }
  String[] result = new String[emptyNames.size()];
  return emptyNames.toArray(result);
}
 
Example 16
Source File: BindStatus.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Create a new BindStatus instance, representing a field or object status.
 * @param requestContext the current RequestContext
 * @param path the bean and property path for which values and errors
 * will be resolved (e.g. "customer.address.street")
 * @param htmlEscape whether to HTML-escape error messages and string values
 * @throws IllegalStateException if no corresponding Errors object found
 */
public BindStatus(RequestContext requestContext, String path, boolean htmlEscape)
		throws IllegalStateException {

	this.requestContext = requestContext;
	this.path = path;
	this.htmlEscape = htmlEscape;

	// determine name of the object and property
	String beanName;
	int dotPos = path.indexOf('.');
	if (dotPos == -1) {
		// property not set, only the object itself
		beanName = path;
		this.expression = null;
	}
	else {
		beanName = path.substring(0, dotPos);
		this.expression = path.substring(dotPos + 1);
	}

	this.errors = requestContext.getErrors(beanName, false);

	if (this.errors != null) {
		// Usual case: A BindingResult is available as request attribute.
		// Can determine error codes and messages for the given expression.
		// Can use a custom PropertyEditor, as registered by a form controller.
		if (this.expression != null) {
			if ("*".equals(this.expression)) {
				this.objectErrors = this.errors.getAllErrors();
			}
			else if (this.expression.endsWith("*")) {
				this.objectErrors = this.errors.getFieldErrors(this.expression);
			}
			else {
				this.objectErrors = this.errors.getFieldErrors(this.expression);
				this.value = this.errors.getFieldValue(this.expression);
				this.valueType = this.errors.getFieldType(this.expression);
				if (this.errors instanceof BindingResult) {
					this.bindingResult = (BindingResult) this.errors;
					this.actualValue = this.bindingResult.getRawFieldValue(this.expression);
					this.editor = this.bindingResult.findEditor(this.expression, null);
				}
				else {
					this.actualValue = this.value;
				}
			}
		}
		else {
			this.objectErrors = this.errors.getGlobalErrors();
		}
		initErrorCodes();
	}

	else {
		// No BindingResult available as request attribute:
		// Probably forwarded directly to a form view.
		// Let's do the best we can: extract a plain target if appropriate.
		Object target = requestContext.getModelObject(beanName);
		if (target == null) {
			throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" +
					beanName + "' available as request attribute");
		}
		if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) {
			BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target);
			this.value = bw.getPropertyValue(this.expression);
			this.valueType = bw.getPropertyType(this.expression);
			this.actualValue = this.value;
		}
		this.errorCodes = new String[0];
		this.errorMessages = new String[0];
	}

	if (htmlEscape && this.value instanceof String) {
		this.value = HtmlUtils.htmlEscape((String) this.value);
	}
}
 
Example 17
Source File: UserPreferencesServiceImpl.java    From webanno with Apache License 2.0 4 votes vote down vote up
/**
     * Save annotation references, such as {@code BratAnnotator#windowSize}..., in a properties file
     * so that they are not required to configure every time they open the document.
     *
     * @param aUsername
     *            the user name
     * @param aMode
     *            differentiate the setting, either it is for {@code AnnotationPage} or
     *            {@code CurationPage}
     * @param aPref
     *            The Object to be saved as preference in the properties file.
     * @param aProject
     *            The project where the user is working on.
     * @throws IOException
     *             if an I/O error occurs.
     */
    private void saveLegacyPreferences(Project aProject, String aUsername, Mode aMode,
            AnnotationPreference aPref)
        throws IOException
    {
        BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(aPref);
        Properties props = new Properties();
        for (PropertyDescriptor value : wrapper.getPropertyDescriptors()) {
            if (wrapper.getPropertyValue(value.getName()) == null) {
                continue;
            }
            props.setProperty(aMode + "." + value.getName(),
                    wrapper.getPropertyValue(value.getName()).toString());
        }
        String propertiesPath = repositoryProperties.getPath().getAbsolutePath() + "/"
                + PROJECT_FOLDER + "/" + aProject.getId() + "/" + SETTINGS_FOLDER + "/" + aUsername;
        // append existing preferences for the other mode
        if (new File(propertiesPath, ANNOTATION_PREFERENCE_PROPERTIES_FILE).exists()) {
            Properties properties = loadLegacyPreferencesFile(aUsername, aProject);
            for (Entry<Object, Object> entry : properties.entrySet()) {
                String key = entry.getKey().toString();
                // Maintain other Modes of annotations confs than this one
                if (!key.substring(0, key.indexOf(".")).equals(aMode.toString())) {
                    props.put(entry.getKey(), entry.getValue());
                }
            }
        }

        // for (String name : props.stringPropertyNames()) {
        // log.info("{} = {}", name, props.getProperty(name));
        // }

        FileUtils.forceMkdir(new File(propertiesPath));
        props.store(new FileOutputStream(
                new File(propertiesPath, ANNOTATION_PREFERENCE_PROPERTIES_FILE)), null);

//        try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID,
//                String.valueOf(aProject.getId()))) {
//            log.info("Saved preferences for user [{}] in project [{}]({})", aUsername,
//                    aProject.getName(), aProject.getId());
//        }
    }
 
Example 18
Source File: XmlGenerator.java    From ecs-sync with Apache License 2.0 4 votes vote down vote up
private static <C> Element createDefaultElement(Document document, ConfigWrapper<C> configWrapper, String name, boolean addComments, boolean advancedOptions)
        throws IllegalAccessException, InstantiationException {

    // create main element
    if (name == null) name = initialLowerCase(configWrapper.getTargetClass().getSimpleName());
    Element mainElement = document.createElement(name);

    // create object instance for defaults
    C object = configWrapper.getTargetClass().newInstance();
    BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);

    List<ConfigPropertyWrapper> propertyWrappers = new ArrayList<>();
    for (String property : configWrapper.propertyNames()) {
        propertyWrappers.add(configWrapper.getPropertyWrapper(property));
    }
    Collections.sort(propertyWrappers, new Comparator<ConfigPropertyWrapper>() {
        @Override
        public int compare(ConfigPropertyWrapper o1, ConfigPropertyWrapper o2) {
            return o1.getOrderIndex() - o2.getOrderIndex();
        }
    });

    for (ConfigPropertyWrapper propertyWrapper : propertyWrappers) {
        if (propertyWrapper.isAdvanced() && !advancedOptions) continue;

        Object defaultValue = beanWrapper.getPropertyValue(propertyWrapper.getName());

        // create XMl comment[s]
        if (addComments) {
            Comment comment = document.createComment(" " + propertyWrapper.getDescription() + " ");
            mainElement.appendChild(comment);
            String specString = propertyWrapper.getDescriptor().getPropertyType().getSimpleName();
            if (propertyWrapper.isRequired()) specString += " - Required";
            if (propertyWrapper.getDescriptor().getPropertyType().isArray())
                specString += " - Repeat for multiple values";
            if (propertyWrapper.getValueList() != null && propertyWrapper.getValueList().length > 0)
                specString += " - Values: " + Arrays.toString(propertyWrapper.getValueList());
            else if (propertyWrapper.getDescriptor().getPropertyType().isEnum())
                specString += " - Values: " + Arrays.toString(propertyWrapper.getDescriptor().getPropertyType().getEnumConstants());
            if (defaultValue != null) specString += " - Default: " + defaultValue;
            comment = document.createComment(" " + specString + " ");
            mainElement.appendChild(comment);
        }

        // create XMl element
        Element propElement = document.createElement(propertyWrapper.getName());

        // set default value
        String defaultValueStr = propertyWrapper.getValueHint();
        if (defaultValue != null) defaultValueStr = conversionService.convert(defaultValue, String.class);
        if (defaultValueStr == null || defaultValueStr.length() == 0) defaultValueStr = propertyWrapper.getName();
        propElement.appendChild(document.createTextNode(defaultValueStr));

        // add to parent element
        mainElement.appendChild(propElement);
    }

    return mainElement;
}
 
Example 19
Source File: BindStatus.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Create a new BindStatus instance, representing a field or object status.
 * @param requestContext the current RequestContext
 * @param path the bean and property path for which values and errors
 * will be resolved (e.g. "customer.address.street")
 * @param htmlEscape whether to HTML-escape error messages and string values
 * @throws IllegalStateException if no corresponding Errors object found
 */
public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException {
	this.requestContext = requestContext;
	this.path = path;
	this.htmlEscape = htmlEscape;

	// determine name of the object and property
	String beanName;
	int dotPos = path.indexOf('.');
	if (dotPos == -1) {
		// property not set, only the object itself
		beanName = path;
		this.expression = null;
	}
	else {
		beanName = path.substring(0, dotPos);
		this.expression = path.substring(dotPos + 1);
	}

	this.errors = requestContext.getErrors(beanName, false);

	if (this.errors != null) {
		// Usual case: A BindingResult is available as request attribute.
		// Can determine error codes and messages for the given expression.
		// Can use a custom PropertyEditor, as registered by a form controller.
		if (this.expression != null) {
			if ("*".equals(this.expression)) {
				this.objectErrors = this.errors.getAllErrors();
			}
			else if (this.expression.endsWith("*")) {
				this.objectErrors = this.errors.getFieldErrors(this.expression);
			}
			else {
				this.objectErrors = this.errors.getFieldErrors(this.expression);
				this.value = this.errors.getFieldValue(this.expression);
				this.valueType = this.errors.getFieldType(this.expression);
				if (this.errors instanceof BindingResult) {
					this.bindingResult = (BindingResult) this.errors;
					this.actualValue = this.bindingResult.getRawFieldValue(this.expression);
					this.editor = this.bindingResult.findEditor(this.expression, null);
				}
				else {
					this.actualValue = this.value;
				}
			}
		}
		else {
			this.objectErrors = this.errors.getGlobalErrors();
		}
		this.errorCodes = initErrorCodes(this.objectErrors);
	}

	else {
		// No BindingResult available as request attribute:
		// Probably forwarded directly to a form view.
		// Let's do the best we can: extract a plain target if appropriate.
		Object target = requestContext.getModelObject(beanName);
		if (target == null) {
			throw new IllegalStateException(
					"Neither BindingResult nor plain target object for bean name '" +
					beanName + "' available as request attribute");
		}
		if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) {
			BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target);
			this.value = bw.getPropertyValue(this.expression);
			this.valueType = bw.getPropertyType(this.expression);
			this.actualValue = this.value;
		}
		this.errorCodes = new String[0];
		this.errorMessages = new String[0];
	}

	if (htmlEscape && this.value instanceof String) {
		this.value = HtmlUtils.htmlEscape((String) this.value);
	}
}
 
Example 20
Source File: ObjectPdxInstanceAdapter.java    From spring-boot-data-geode with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the {@link Object value} for the {@link PropertyDescriptor property} identified by
 * the given {@link String field name} on the underlying, target {@link Object}.
 *
 * @param fieldName {@link String} containing the name of the field to get the {@link Object value} for.
 * @return the {@link Object value} for the {@link PropertyDescriptor property} identified by
 * the given {@link String field name} on the underlying, target {@link Object}.
 * @see org.springframework.beans.BeanWrapper#getPropertyValue(String)
 * @see #getBeanWrapper()
 */
@Override
public Object getField(String fieldName) {

	BeanWrapper beanWrapper = getBeanWrapper();

	return beanWrapper.isReadableProperty(fieldName)
		? beanWrapper.getPropertyValue(fieldName)
		: null;
}