@Test public void testIntrospectPropertyForItemsConnectedTo() throws InvalidPropertyException, InvocationTargetException, IllegalAccessException { String logicalId = "/myitem/myid"; MyItemType myItemType = new MyItemType(); String logicalId1 = logicalId + "1"; String logicalId2 = logicalId + "2"; MyItem myItem1 = new MyItem(logicalId1, myItemType); MyItem myItem2 = new MyItem(logicalId2, myItemType); myItem1.addConnectedRelationships(myItem2, ""); MyItem[] myItemArray = {myItem1, myItem2}; List<Fibre> items = Arrays.asList(myItemArray); String propertyName = RelationshipUtil.getRelationshipNameBetweenItems(myItem1, myItem2, ""); List<Object> properties = FibreIntrospectionUtils.introspectPropertyForFibres(propertyName, items, null); assertNotNull("Returned properties was null", properties); assertEquals("Returned properties incorrect size", 2, properties.size()); for (int count = 0; count < properties.size(); count++) { assertNotNull("Returned property was null at " + count, properties.get(count)); } assertEquals("First property incorrect", myItem2, properties.get(0)); assertEquals("Second property incorrect", myItem1, properties.get(1)); }
@Test public void testAutoGrowBeyondDefaultLimit() throws Exception { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); MutablePropertyValues mpvs = new MutablePropertyValues(); mpvs.add("friends[256]", ""); try { binder.bind(mpvs); fail("Should have thrown InvalidPropertyException"); } catch (InvalidPropertyException ex) { // expected assertTrue(ex.getRootCause() instanceof IndexOutOfBoundsException); } }
@Test public void testAutoGrowBeyondCustomLimit() throws Exception { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); binder.setAutoGrowCollectionLimit(10); MutablePropertyValues mpvs = new MutablePropertyValues(); mpvs.add("friends[16]", ""); try { binder.bind(mpvs); fail("Should have thrown InvalidPropertyException"); } catch (InvalidPropertyException ex) { // expected assertTrue(ex.getRootCause() instanceof IndexOutOfBoundsException); } }
private String resolvePropertyName(BeanWrapper target, String prefix, String name) { Iterable<String> names = getNameAndAliases(name); for (String nameOrAlias : names) { for (String candidate : new RelaxedNames(nameOrAlias)) { try { if (target.getPropertyType(joinString(prefix, candidate)) != null) { return candidate; } } catch (InvalidPropertyException ex) { // swallow and continue } } } return null; }
/** * Returns the value for the given property growing nested paths depending on the parameter. * * @param propertyName name of the property to get value for * @param autoGrowNestedPaths whether nested paths should be grown (initialized if null) * @return value for property */ protected Object getPropertyValue(String propertyName, boolean autoGrowNestedPaths) { setAutoGrowNestedPaths(autoGrowNestedPaths); Object value = null; try { value = super.getPropertyValue(propertyName); } catch (NullValueInNestedPathException e) { // swallow null values in path and return null as the value } catch (InvalidPropertyException e1) { if (!(e1.getRootCause() instanceof NullValueInNestedPathException)) { throw e1; } } return value; }
public void testAutoGrowBeyondCustomLimit() throws Exception { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); binder.setAutoGrowCollectionLimit(10); MutablePropertyValues mpvs = new MutablePropertyValues(); mpvs.add("friends[16]", ""); try { binder.bind(mpvs); fail("Should have thrown InvalidPropertyException"); } catch (InvalidPropertyException ex) { // expected assertTrue(ex.getRootCause() instanceof IndexOutOfBoundsException); } }
/** * This test ensures that the Spring Bean accessor classes work properly * since our REST implementation uses bean access to update the values. */ @Test public void testBeanWrapperAccess() throws Exception { createRequisition(); Requisition r = m_repository.getRequisition(m_defaultForeignSourceName); BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(r); assertEquals("AC", wrapper.getPropertyValue("node[0].category[0].name")); assertEquals("UK", wrapper.getPropertyValue("node[0].category[1].name")); assertEquals("low", wrapper.getPropertyValue("node[0].category[2].name")); try { wrapper.getPropertyValue("node[1].category[0].name"); fail("Did not catch expected InvalidPropertyException exception"); } catch (InvalidPropertyException e) { // Expected failure } assertEquals(0, ((RequisitionCategory[])wrapper.getPropertyValue("node[1].category")).length); wrapper.setPropertyValue("node[1].categories[0]", new RequisitionCategory("Hello world")); wrapper.setPropertyValue("node[1].categories[1]", new RequisitionCategory("Hello again")); assertEquals(2, ((RequisitionCategory[])wrapper.getPropertyValue("node[1].category")).length); }
public void testCreateBoundComboBoxStringStringString() { TestableBinding b = (TestableBinding)sbf.createBoundComboBox("name", "listProperty", "displayProperty"); assertBindingProperties(b, JComboBox.class, null, "name"); assertEquals(4, b.getContext().size()); assertEquals(sbf.getFormModel().getValueModel("listProperty"), b.getContext().get( ComboBoxBinder.SELECTABLE_ITEMS_KEY)); assertEquals("displayProperty", ((BeanPropertyValueListRenderer)b.getContext().get(ComboBoxBinder.RENDERER_KEY)).getPropertyName()); assertEquals("displayProperty", ((BeanPropertyEditorClosure)b.getContext().get(ComboBoxBinder.EDITOR_KEY)).getRenderedProperty()); assertEquals("displayProperty", getComparatorProperty(b)); try { b = (TestableBinding)sbf.createBoundComboBox("name", "someUnknownProperty", "displayProperty"); fail("cant use an unknown property to provide the selectable items"); } catch (InvalidPropertyException e) { // expected } }
@Override public Class<?> getPropertyType(String propertyName) throws BeansException { try { PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName); if (pd != null) { return pd.getPropertyType(); } // Maybe an indexed/mapped property... Object value = super.getPropertyValue(propertyName); if (value != null) { return value.getClass(); } // Check to see if there is a custom editor, // which might give an indication on the desired target type. Class<?> editorType = guessPropertyTypeFromEditors(propertyName); if (editorType != null) { return editorType; } } catch (InvalidPropertyException ex) { // Consider as not determinable. } return null; }
@Test(expected = IllegalAccessException.class) public void testIntrospectPropertyReserved() throws InvalidPropertyException, InvocationTargetException, IllegalAccessException { String logicalId = "/myfibre/myid"; MyFibreType myFibreType = new MyFibreType(); MyFibre myFibre = new MyFibre(logicalId, myFibreType); FibreIntrospectionUtils.introspectPropertyStrict("memberOf", myFibre, null); }
@Test(expected = IllegalAccessException.class) public void testIntrospectPropertyForFibresReserved() throws InvalidPropertyException, InvocationTargetException, IllegalAccessException { String logicalId = "/myfibre/myid"; MyFibreType myFibreType = new MyFibreType(); MyFibre myFibre = new MyFibre(logicalId, myFibreType); MyFibre[] myFibreArray = {myFibre}; List<Fibre> fibres = Arrays.asList(myFibreArray); FibreIntrospectionUtils.introspectPropertyForFibres("memberOf", fibres, null); }
/** * Return a named property value for the fibre. This method is not strict about the validity of * the named property, and will return a null value if the property is unknown. * * @param <T> Type of the returned property. * @param propertyName Name of property to return. * @param fibre fibre to introspect * @param context query context * @return Value of property. Note that the value will be reported as null if it is unknown. */ @JsonIgnore public static <T> T introspectProperty(final String propertyName, final Fibre fibre, final OperationContext context) { try { return introspectPropertyStrict(propertyName, fibre, context); } catch (InvocationTargetException | InvalidPropertyException | IllegalAccessException e) { if (LOG.isDebugEnabled()) { LOG.debug("Could not find property " + propertyName); } return null; } }
@SuppressWarnings("unchecked") @Override public <X> X getValue(String attrName) throws AttributeValidationException { X attributeValue = null; Exception e = null; try { attributeValue = (X) beanWrapper.getPropertyValue(attrName); } catch (IllegalArgumentException iae) { e = iae; } catch (InvalidPropertyException ipe) { //just return null } if (e != null) { throw new AttributeValidationException( "Unable to lookup attribute value by name (" + attrName + ") using introspection", e); } // JLR : KS has code to handle dynamic attributes -- not sure whether this is really needed anymore if we're actually relying on types // // Extract dynamic attributes // if(DYNAMIC_ATTRIBUTE.equals(propName)) { // dataMap.putAll((Map<String, String>)value); // } else { // dataMap.put(propName, value); // } return attributeValue; }
public static <T extends Enum<T>> String serializeEnum(ObjectMapper objMapper, Class<T> enumClass) throws BeansException, InvalidPropertyException, JsonProcessingException, PropertyAccessException { T[] enumItems = enumClass.getEnumConstants(); Map<String, Map<String, Object>> enumMap = new LinkedHashMap<>(enumItems.length); Map<String, Object> enumItemMap; Map<String, String> enumItemValueMap; String enumItemKey; BeanWrapper enumItemWrapper; PropertyDescriptor[] enumItemPropDescs; Method enumItemPropGetter; String enumItemPropName; for (T enumItem : enumItems) { enumMap.put((enumItemKey = enumItem.name()), (enumItemMap = new LinkedHashMap<>(2))); enumItemMap.put(KEY_PROP_NAME, enumItemKey); enumItemMap.put(VALUE_PROP_NAME, (enumItemValueMap = new LinkedHashMap<>((enumItemPropDescs = (enumItemWrapper = new BeanWrapperImpl(enumItem)).getPropertyDescriptors()).length))); for (PropertyDescriptor enumItemPropDesc : enumItemPropDescs) { if (((enumItemPropGetter = enumItemPropDesc.getReadMethod()) == null) || !enumItemPropGetter.isAnnotationPresent(JsonProperty.class)) { continue; } enumItemValueMap.put((enumItemPropName = enumItemPropDesc.getName()), enumItemWrapper.getPropertyValue(enumItemPropName).toString()); } } return objMapper.writeValueAsString(enumMap); }
public void testAutoGrowBeyondDefaultLimit() throws Exception { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); MutablePropertyValues mpvs = new MutablePropertyValues(); mpvs.add("friends[256]", ""); try { binder.bind(mpvs); fail("Should have thrown InvalidPropertyException"); } catch (InvalidPropertyException ex) { // expected assertTrue(ex.getRootCause() instanceof IndexOutOfBoundsException); } }
/** * 参数转换出错 * * @param e * * @return */ private ModelAndView getParamErrors(InvalidPropertyException e) { Map<String, String> errorMap = new HashMap<String, String>(); errorMap.put(e.getPropertyName(), " parameter cannot find"); JsonObjectBase jsonObject = JsonObjectUtils.buildFieldError(errorMap, ErrorCode.TYPE_MIS_MATCH); return JsonObjectUtils.JsonObjectError2ModelView((JsonObjectError) jsonObject); }
private HostAndPort parseHostAndPort(String hostString) { StringTokenizer st = new StringTokenizer(hostString, ":"); if (st.hasMoreElements() & st.countTokens() == 2) { return new HostAndPort(st.nextToken(), Integer.valueOf(st.nextToken())); } else { throw new InvalidPropertyException(this.getClass(), "hosts", "invalid host name:" + hostString + "."); } }
private Object getPropertyValue(Object assemblage, Object[] indices, int parameterIndex) { if (assemblage == null) { if (isStrictNullHandlingEnabled()) { throw new NullValueInNestedPathException(getTargetClass(), ""); } else { return null; } } Object value = null; if (assemblage.getClass().isArray()) { value = getArrayValue(assemblage, (Integer) indices[parameterIndex]); } else if (assemblage instanceof List) { value = getListValue((List) assemblage, (Integer) indices[parameterIndex]); } else if (assemblage instanceof Map) { value = getMapValue((Map) assemblage, indices[parameterIndex]); } else if (assemblage instanceof Collection) { value = getCollectionValue((Collection) assemblage, (Integer) indices[parameterIndex]); } else { throw new IllegalStateException( "getPropertyValue(Object, Object[], int) called with neither array nor collection nor map"); } if (parameterIndex == indices.length - 1) { return value; } if (value == null) { if (isStrictNullHandlingEnabled()) { throw new InvalidPropertyException(getTargetClass(), "", ""); } else { return null; } } return getPropertyValue(value, indices, parameterIndex + 1); }
private Object getArrayValue(Object array, Integer index) { if (Array.getLength(array) > index.intValue()) { return Array.get(array, index.intValue()); } else if (isStrictNullHandlingEnabled()) { throw new InvalidPropertyException(getTargetClass(), "", ""); } else { return null; } }
private Object getListValue(List list, Integer index) { if (list.size() > index.intValue()) { return list.get(index.intValue()); } else if (isStrictNullHandlingEnabled()) { throw new InvalidPropertyException(getTargetClass(), "", ""); } else { return null; } }
private Object getCollectionValue(Collection collection, Integer index) { if (collection.size() > index.intValue()) { Iterator iterator = collection.iterator(); for (int i = 0; i < index.intValue(); i++) { iterator.next(); } return iterator.next(); } else if (isStrictNullHandlingEnabled()) { throw new InvalidPropertyException(getTargetClass(), "", ""); } else { return null; } }
/** * Determine the type of the key used to index the collection/map. When jdk * is at least 1.5, maps can be specified with generics and their key type * can be resolved. * * @param propertyName name of the property. * @return the type of the key. An integer if it's not a map, {@link String} * if the jdk is less than 1.5, a specific type if the map was generified. */ public Class getIndexedPropertyKeyType(String propertyName) { if (!PropertyAccessorUtils.isIndexedProperty(propertyName)) { throw new IllegalArgumentException("'" + propertyName + "' is no indexed property"); } Class type = getPropertyType(getParentPropertyName(propertyName)); if (!Map.class.isAssignableFrom(type)) { return Integer.class; } if (JdkVersion.isAtLeastJava15()) { int nestingLevel = PropertyAccessorUtils.getNestingLevel(propertyName) - 1; Member accessor = getPropertyAccessor(getRootPropertyName(propertyName)); if (accessor instanceof Field) { return GenericCollectionTypeResolver.getMapKeyFieldType((Field) accessor, nestingLevel); } else if (accessor instanceof Method) { MethodParameter parameter = new MethodParameter((Method) accessor, ((Method) accessor) .getParameterTypes().length - 1, nestingLevel); return GenericCollectionTypeResolver.getMapKeyParameterType(parameter); } else { throw new InvalidPropertyException(getTargetClass(), propertyName, "property not accessable"); } } else { return String.class; // the default for Java 1.4 } }
@Override public Object getPropertyValue(String propertyName) throws BeansException { Field field = this.fieldMap.get(propertyName); if (field == null) { throw new NotReadablePropertyException( this.target.getClass(), propertyName, "Field '" + propertyName + "' does not exist"); } try { ReflectionUtils.makeAccessible(field); return field.get(this.target); } catch (IllegalAccessException ex) { throw new InvalidPropertyException(this.target.getClass(), propertyName, "Field is not accessible", ex); } }
/** * Set property, without trowing exceptions on errors * @param bean bean name * @param name name * @param value value */ public static void setProperty(Object bean, String name, Object value) { try { BeanWrapper wrapper = new BeanWrapperImpl(bean); wrapper.setPropertyValue(new PropertyValue(name, value)); } catch (InvalidPropertyException ipe) { log.debug("Bean has no property: " + name); } catch (PropertyAccessException pae) { log.debug("Access Error on property: " + name); } }
/** * {@inheritDoc} */ @Override public PropertyDescriptor getPropertyDescriptor(String propertyName) throws InvalidPropertyException { return wrapper.getPropertyDescriptor(propertyName); }
@Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) { LOG.warn(request.getRequestURI() + " ExceptionHandler FOUND. " + e.toString() + "\t" + e.getCause()); // PathVariable 出错 if (e instanceof TypeMismatchException) { return getParamErrors((TypeMismatchException) e); // Bean 参数无法映射错误 } else if (e instanceof InvalidPropertyException) { return getParamErrors((InvalidPropertyException) e); // @Valid 出错 } else if (e instanceof BindException) { return ParamValidateUtils.getParamErrors((BindException) e); // 业务校验处理 } else if (e instanceof FieldException) { return getParamErrors((FieldException) e); } else if (e instanceof DocumentNotFoundException) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); try { FileUtils.closeWriter(response.getWriter()); } catch (IOException e1) { e1.printStackTrace(); } return null; // 用户没有请求方法的访问权限 } else if (e instanceof AccessDeniedException) { LOG.warn("details: " + ((AccessDeniedException) e).getErrorMessage()); return buildError("auth.access.denied", ErrorCode.ACCESS_NOAUTH_ERROR); } else if (e instanceof HttpRequestMethodNotSupportedException) { return buildError("syserror.httpmethod", ErrorCode.HttpRequestMethodNotSupportedException); } else if (e instanceof MissingServletRequestParameterException) { return buildError("syserror.param.miss", ErrorCode.MissingServletRequestParameterException); } else if (e instanceof GlobalExceptionAware) { LOG.error("details: ", e); GlobalExceptionAware g = (GlobalExceptionAware) e; return buildError(g.getErrorMessage(), g.getErrorCode()); } else { LOG.warn("details: ", e); return buildError("syserror.inner", ErrorCode.GLOBAL_ERROR); } }
/** * <p>getValue</p> * * @param root a {@link java.lang.Object} object. * @return a {@link java.lang.Object} object. */ public Object getValue(Object root) throws InvalidPropertyException { return getValue(PropertyAccessorFactory.forBeanPropertyAccess(root)); }