/**
   * validation check를 할때 hashMap name이 view(jsp)에서 입력되었는지를 알수 있게 하기 위해서는 stack에 getter setter로 정의된
   * hashMap(여기에서는 reqMap이름을 쓴다)이름을 지정하고 hashMap에 저장된 값을 리턴한다.
   */
  @Override
  protected Object getFieldValue(String name, Object object) throws ValidationException {
    ValueStack stack = ActionContext.getContext().getValueStack();

    boolean pop = false;

    if (!(stack.getRoot().contains(object))) {
      stack.push(object);
      pop = true;
    }

    Object retVal = null;
    // HashMap reqMap의 값을 stack에 넣어준다.
    Object obj = (Map) stack.findValue("reqMap");

    // HashMap reqMap이 null이 아닐때
    if (obj != null) {
      Map m = (Map) obj;
      // stack에 있는 HashMap reqMap값을 name으로 가져와서 valueStack에 올려준다.
      retVal = m.get(name);
    }
    // HashMap reqMap이 null일때
    else {
      // getter setter을 사용한 name의 값을 valueStack에 올려준다.
      retVal = stack.findValue(name);
    }

    if (pop) {
      stack.pop();
    }

    return retVal;
  }
Exemplo n.º 2
0
    public void beforeResult(ActionInvocation invocation, String resultCode) {
      ValueStack stack = invocation.getStack();
      CompoundRoot root = stack.getRoot();

      boolean needsRefresh = true;
      Object newModel = action.getModel();

      // Check to see if the new model instance is already on the stack
      for (Object item : root) {
        if (item.equals(newModel)) {
          needsRefresh = false;
        }
      }

      // Add the new model on the stack
      if (needsRefresh) {

        // Clear off the old model instance
        if (originalModel != null) {
          root.remove(originalModel);
        }
        if (newModel != null) {
          stack.push(newModel);
        }
      }
    }
Exemplo n.º 3
0
  /**
   * Get a message from the first TextProvider encountered in the stack. If the first TextProvider
   * doesn't provide the message the default message is returned.
   *
   * <p>The search for a TextProvider is iterative from the root of the stack.
   *
   * <p>This method was refactored from {@link org.apache.struts2.components.Text} to use a
   * consistent implementation across UIBean components.
   *
   * @param key the message key in the resource bundle
   * @param defaultMessage the message to return if not found (evaluated for OGNL)
   * @param args an array args to be used in a {@link java.text.MessageFormat} message
   * @param stack the value stack to use for finding the text
   * @param searchStack search stack for the key
   * @return the message if found, otherwise the defaultMessage
   */
  public static String getText(
      String key, String defaultMessage, List<Object> args, ValueStack stack, boolean searchStack) {
    String msg = null;
    TextProvider tp = null;

    for (Object o : stack.getRoot()) {
      if (o instanceof TextProvider) {
        tp = (TextProvider) o;
        msg = tp.getText(key, null, args, stack);

        break;
      }
    }

    if (msg == null) {
      // evaluate the defaultMesage as an OGNL expression
      if (searchStack) msg = stack.findString(defaultMessage);

      if (msg == null) {
        // use the defaultMessage literal value
        msg = defaultMessage;
      }

      if (LOG.isWarnEnabled()) {
        if (tp != null) {
          LOG.warn(
              "The first TextProvider in the ValueStack ("
                  + tp.getClass().getName()
                  + ") could not locate the message resource with key '"
                  + key
                  + "'");
        } else {
          LOG.warn(
              "Could not locate the message resource '"
                  + key
                  + "' as there is no TextProvider in the ValueStack.");
        }
        if (defaultMessage.equals(msg)) {
          LOG.warn(
              "The default value expression '"
                  + defaultMessage
                  + "' was evaluated and did not match a property.  The literal value '"
                  + defaultMessage
                  + "' will be used.");
        } else {
          LOG.warn(
              "The default value expression '" + defaultMessage + "' evaluated to '" + msg + "'");
        }
      }
    }
    return msg;
  }
  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);
    }
  }