Exemplo n.º 1
0
 private Class<? extends Object> getPropertyTypeWithClass(
     Class<? extends Object> clazz, String dataName) throws Exception {
   if (clazz == null) throw new IllegalArgumentException();
   int delim = dataName.indexOf('.');
   if (delim < 0) {
     PropertyDescriptor pd = OgnlRuntime.getPropertyDescriptor(clazz, dataName);
     if (pd == null) throw new IllegalArgumentException();
     return pd.getPropertyType();
   } else {
     PropertyDescriptor pd =
         OgnlRuntime.getPropertyDescriptor(clazz, dataName.substring(0, delim));
     if (pd == null) throw new IllegalArgumentException();
     return getPropertyTypeWithClass(pd.getPropertyType(), dataName.substring(delim + 1));
   }
 }
 @Test
 public void shouldInstantiateAnObjectIfRequiredToSetAProperty() throws OgnlException {
   OgnlRuntime.setNullHandler(House.class, handler);
   House house = new House();
   Ognl.setValue("mouse.name", context, house, "James");
   MatcherAssert.assertThat(house.getMouse().getName(), Matchers.is(Matchers.equalTo("James")));
 }
 @Test
 public void shouldNotInstantiateIfLastTerm() throws OgnlException, NoSuchMethodException {
   OgnlRuntime.setNullHandler(House.class, handler);
   final TypeConverter typeConverter = mockery.mock(TypeConverter.class);
   final House house = new House();
   final Mouse tom = new Mouse();
   mockery.checking(
       new Expectations() {
         {
           one(typeConverter)
               .convertValue(
                   context,
                   house,
                   House.class.getDeclaredMethod("setMouse", Mouse.class),
                   "mouse",
                   "22",
                   Mouse.class);
           will(returnValue(tom));
         }
       });
   Ognl.setTypeConverter(context, typeConverter);
   Ognl.setValue("mouse", context, house, "22");
   MatcherAssert.assertThat(house.getMouse(), Matchers.is(Matchers.equalTo(tom)));
   mockery.assertIsSatisfied();
 }
 @Test
 public void shouldInstantiateAListOfStrings() throws OgnlException {
   mockery.checking(
       new Expectations() {
         {
           one(removal).add((Collection<?>) with(an(Collection.class)));
         }
       });
   OgnlRuntime.setNullHandler(House.class, handler);
   OgnlRuntime.setNullHandler(Mouse.class, handler);
   House house = new House();
   Ognl.setValue("mouse.eyeColors[0]", context, house, "Blue");
   Ognl.setValue("mouse.eyeColors[1]", context, house, "Green");
   MatcherAssert.assertThat(
       house.getMouse().getEyeColors().get(0), Matchers.is(Matchers.equalTo("Blue")));
   MatcherAssert.assertThat(
       house.getMouse().getEyeColors().get(1), Matchers.is(Matchers.equalTo("Green")));
 }
Exemplo n.º 5
0
 static {
   OgnlRuntime.setPropertyAccessor(S2Container.class, new S2ContainerPropertyAccessor());
   Desc.useContextClassLoader = true;
   ProxyFactory.classLoaderProvider =
       new ClassLoaderProvider() {
         public ClassLoader get(ProxyFactory proxyFactory) {
           return Thread.currentThread().getContextClassLoader();
         }
       };
 }
 protected OGNLAttributeEvaluator createOGNLEvaluator() {
   try {
     PropertyAccessor objectPropertyAccessor = OgnlRuntime.getPropertyAccessor(Object.class);
     PropertyAccessor applicationContextPropertyAccessor =
         new NestedObjectDelegatePropertyAccessor<>(
             new TilesApplicationContextNestedObjectExtractor(), objectPropertyAccessor);
     PropertyAccessor anyScopePropertyAccessor = new AnyScopePropertyAccessor();
     PropertyAccessor scopePropertyAccessor = new ScopePropertyAccessor();
     PropertyAccessorDelegateFactory<Request> factory =
         new TilesContextPropertyAccessorDelegateFactory(
             objectPropertyAccessor,
             applicationContextPropertyAccessor,
             anyScopePropertyAccessor,
             scopePropertyAccessor);
     PropertyAccessor tilesRequestAccessor = new DelegatePropertyAccessor<>(factory);
     OgnlRuntime.setPropertyAccessor(Request.class, tilesRequestAccessor);
     return new OGNLAttributeEvaluator();
   } catch (OgnlException e) {
     throw new TilesContainerFactoryException("Cannot initialize OGNL evaluator", e);
   }
 }
 @Before
 public void setup() {
   this.handler = new ReflectionBasedNullHandler();
   this.context = (OgnlContext) Ognl.createDefaultContext(null);
   context.setTraceEvaluations(true);
   this.mockery = new VRaptorMockery(true);
   this.container = mockery.mock(Container.class);
   context.put(Container.class, container);
   this.removal = mockery.mock(EmptyElementsRemoval.class);
   this.converters = mockery.mock(Converters.class);
   mockery.checking(
       new Expectations() {
         {
           allowing(container).instanceFor(EmptyElementsRemoval.class);
           will(returnValue(removal));
           allowing(container).instanceFor(Converters.class);
           will(returnValue(converters));
         }
       });
   OgnlRuntime.setPropertyAccessor(List.class, new ListAccessor());
   OgnlRuntime.setPropertyAccessor(Object[].class, new ArrayAccessor());
 }
Exemplo n.º 8
0
  public void testCanSetADependentObject() throws Exception {
    String dogName = "fido";

    OgnlRuntime.setNullHandler(
        Owner.class,
        new NullHandler() {
          public Object nullMethodResult(Map map, Object o, String s, Object[] objects) {
            return null;
          }

          public Object nullPropertyValue(Map map, Object o, Object o1) {
            String methodName = o1.toString();
            String getter =
                "set" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
            Method[] methods = o.getClass().getDeclaredMethods();
            System.out.println(getter);

            for (Method method : methods) {
              String name = method.getName();

              if (!getter.equals(name) || (method.getParameterTypes().length != 1)) {
                continue;
              } else {
                Class clazz = method.getParameterTypes()[0];

                try {
                  Object param = clazz.newInstance();
                  method.invoke(o, new Object[] {param});

                  return param;
                } catch (Exception e) {
                  throw new RuntimeException(e);
                }
              }
            }

            return null;
          }
        });

    Owner owner = new Owner();
    Map context = Ognl.createDefaultContext(owner);
    Map props = new HashMap();
    props.put("dog.name", dogName);

    ognlUtil.setProperties(props, owner, context);
    assertNotNull("expected Ognl to create an instance of Dog", owner.getDog());
    assertEquals(dogName, owner.getDog().getName());
  }
 public void contextInitialized(ServletContextEvent servletContextEvent) {
   OgnlRuntime.setSecurityManager(null);
 }
Exemplo n.º 10
0
  public static void buildValidatorAttribute(
      String validatorAttrValue,
      AbstractUITag tag,
      ValueStack stack,
      HttpServletRequest req,
      UIBean uiBean) {
    Map<String, Object> dynamicAttributes = new HashMap<String, Object>();
    if (validatorAttrValue == null) {
      Map<String, Object> validator = new HashMap<String, Object>();
      Map<String, String> messages = new HashMap<String, String>();
      CompoundRoot rootList = stack.getRoot();
      Object entity = null;
      Object controller = null;
      for (Object obj : rootList) {
        if (obj instanceof Persistable) {
          entity = obj;
        } else if (obj instanceof ActionSupport) {
          controller = obj;
        }
      }

      if (entity != null) {
        try {
          String tagName = tag.name;
          Method method =
              OgnlRuntime.getGetMethod(
                  (OgnlContext) stack.getContext(), entity.getClass(), tagName);
          if (method == null) {
            String[] tagNameSplits = StringUtils.split(tagName, ".");
            if (tagNameSplits.length >= 2) {
              Class<?> retClass = entity.getClass();
              for (String tagNameSplit : tagNameSplits) {
                method =
                    OgnlRuntime.getGetMethod(
                        (OgnlContext) stack.getContext(), retClass, tagNameSplit);
                if (method != null) {
                  retClass = method.getReturnType();
                }
              }
              if (method == null) {
                retClass = controller.getClass();
                for (String tagNameSplit : tagNameSplits) {
                  method =
                      OgnlRuntime.getGetMethod(
                          (OgnlContext) stack.getContext(), retClass, tagNameSplit);
                  if (method != null) {
                    retClass = method.getReturnType();
                  }
                }
              }
            }
          }

          if (method != null) {
            Column column = method.getAnnotation(Column.class);
            if (column != null) {
              if (column.nullable() == false) {
                if (tag.requiredLabel == null) {
                  uiBean.setRequiredLabel("true");
                }
              }
              if (column.unique() == true) {
                validator.put("unique", "true");
              }
            }

            Class<?> retType = method.getReturnType();
            if (retType == LocalDate.class) {
              validator.put("date", true);
              validator.put("dateISO", true);
            } else if (retType == LocalDateTime.class) {
              validator.put("timestamp", true);
            } else if (retType == DateTime.class || retType == Date.class) {
              JsonSerialize jsonSerialize = method.getAnnotation(JsonSerialize.class);
              if (jsonSerialize != null) {
                if (JodaDateJsonSerializer.class == jsonSerialize.using()
                    || DateJsonSerializer.class == jsonSerialize.using()) {
                  validator.put("date", true);
                  validator.put("dateISO", true);
                } else if (JodaDateTimeJsonSerializer.class == jsonSerialize.using()
                    || DateTimeJsonSerializer.class == jsonSerialize.using()) {
                  validator.put("timestamp", true);
                }
              }
            } else if (retType == BigDecimal.class) {
              validator.put("number", true);
            } else if (retType == Integer.class) {
              validator.put("number", true);
              validator.put("digits", true);
            } else if (retType == Long.class) {
              validator.put("number", true);
              validator.put("digits", true);
            }

            Size size = method.getAnnotation(Size.class);
            if (size != null) {
              if (size.min() > 0) {
                validator.put("minlength", size.min());
              }
              if (size.max() < Integer.MAX_VALUE) {
                validator.put("maxlength", size.max());
              }
            }

            Email email = method.getAnnotation(Email.class);
            if (email != null) {
              validator.put("email", true);
            }

            Pattern pattern = method.getAnnotation(Pattern.class);
            if (pattern != null) {
              validator.put("regex", pattern.regexp());
              String message = pattern.message();
              if (!"{javax.validation.constraints.Pattern.message}".equals(message)) {
                messages.put("regex", message);
              }
            }
          }
        } catch (IntrospectionException e) {
          e.printStackTrace();
        } catch (OgnlException e) {
          e.printStackTrace();
        }
      }

      if (validator.size() > 0) {
        try {
          if (messages.size() > 0) {
            validator.put("messages", messages);
          }
          String json = mapper.writeValueAsString(validator);
          json = json.replaceAll("\\\"", "'");
          dynamicAttributes.put("validator", json);
          uiBean.setDynamicAttributes(dynamicAttributes);
        } catch (JsonProcessingException e) {
          e.printStackTrace();
        }
      }
    } else {
      dynamicAttributes.put("validator", validatorAttrValue);
      uiBean.setDynamicAttributes(dynamicAttributes);
    }
  }
Exemplo n.º 11
0
 static {
   OgnlRuntime.setPropertyAccessor(ContextMap.class, new ContextAccessor());
 }