Example #1
0
  /**
   * Retrieve a field.
   *
   * @param key field name
   * @return the field (even if the field does not exist you get a field)
   */
  public Field field(String key) {

    // Value
    String fieldValue = null;
    if (data.containsKey(key)) {
      fieldValue = data.get(key);
    } else {
      if (value.isPresent()) {
        BeanWrapper beanWrapper = new BeanWrapperImpl(value.get());
        beanWrapper.setAutoGrowNestedPaths(true);
        String objectKey = key;
        if (rootName != null && key.startsWith(rootName + ".")) {
          objectKey = key.substring(rootName.length() + 1);
        }
        if (beanWrapper.isReadableProperty(objectKey)) {
          Object oValue = beanWrapper.getPropertyValue(objectKey);
          if (oValue != null) {
            final String objectKeyFinal = objectKey;
            fieldValue =
                withRequestLocale(
                    () ->
                        formatters.print(
                            beanWrapper.getPropertyTypeDescriptor(objectKeyFinal), oValue));
          }
        }
      }
    }

    // Error
    List<ValidationError> fieldErrors = errors.get(key);
    if (fieldErrors == null) {
      fieldErrors = new ArrayList<>();
    }

    // Format
    Tuple<String, List<Object>> format = null;
    BeanWrapper beanWrapper = new BeanWrapperImpl(blankInstance());
    beanWrapper.setAutoGrowNestedPaths(true);
    try {
      for (Annotation a : beanWrapper.getPropertyTypeDescriptor(key).getAnnotations()) {
        Class<?> annotationType = a.annotationType();
        if (annotationType.isAnnotationPresent(play.data.Form.Display.class)) {
          play.data.Form.Display d = annotationType.getAnnotation(play.data.Form.Display.class);
          if (d.name().startsWith("format.")) {
            List<Object> attributes = new ArrayList<>();
            for (String attr : d.attributes()) {
              Object attrValue = null;
              try {
                attrValue = a.getClass().getDeclaredMethod(attr).invoke(a);
              } catch (Exception e) {
                // do nothing
              }
              attributes.add(attrValue);
            }
            format = Tuple(d.name(), attributes);
          }
        }
      }
    } catch (NullPointerException e) {
      // do nothing
    }

    // Constraints
    List<Tuple<String, List<Object>>> constraints = new ArrayList<>();
    Class<?> classType = backedType;
    String leafKey = key;
    if (rootName != null && leafKey.startsWith(rootName + ".")) {
      leafKey = leafKey.substring(rootName.length() + 1);
    }
    int p = leafKey.lastIndexOf('.');
    if (p > 0) {
      classType = beanWrapper.getPropertyType(leafKey.substring(0, p));
      leafKey = leafKey.substring(p + 1);
    }
    if (classType != null) {
      BeanDescriptor beanDescriptor =
          play.data.validation.Validation.getValidator().getConstraintsForClass(classType);
      if (beanDescriptor != null) {
        PropertyDescriptor property = beanDescriptor.getConstraintsForProperty(leafKey);
        if (property != null) {
          constraints = Constraints.displayableConstraint(property.getConstraintDescriptors());
        }
      }
    }

    return new Field(this, key, constraints, format, fieldErrors, fieldValue);
  }
Example #2
0
//
// NOTE: This file was generated from: japidviews/_tags/picka.html
// Change to this file will be lost next time the template file is compiled.
//
@cn.bran.play.NoEnhance
public class picka extends cn.bran.play.JapidTemplateBase {
  public static final String sourceTemplate = "japidviews/_tags/picka.html";

  private void initHeaders() {
    putHeader("Content-Type", "text/html; charset=utf-8");
    setContentType("text/html; charset=utf-8");
  }

  {
  }

  // - add implicit fields with Play

  final play.mvc.Http.Request request = play.mvc.Http.Request.current();
  final play.mvc.Http.Response response = play.mvc.Http.Response.current();
  final play.mvc.Scope.Session session = play.mvc.Scope.Session.current();
  final play.mvc.Scope.RenderArgs renderArgs = play.mvc.Scope.RenderArgs.current();
  final play.mvc.Scope.Params params = play.mvc.Scope.Params.current();
  final play.data.validation.Validation validation = play.data.validation.Validation.current();
  final cn.bran.play.FieldErrors errors = new cn.bran.play.FieldErrors(validation);
  final play.Play _play = new play.Play();

  // - end of implicit fields with Play

  public picka() {
    super((StringBuilder) null);
    initHeaders();
  }

  public picka(StringBuilder out) {
    super(out);
    initHeaders();
  }

  public picka(cn.bran.japid.template.JapidTemplateBaseWithoutPlay caller) {
    super(caller);
  }

  /* based on https://github.com/branaway/Japid/issues/12
   */
  public static final String[] argNames =
      new String[] {
          /* args of the template*/
        "a", "b",
      };
  public static final String[] argTypes =
      new String[] {
          /* arg types of the template*/
        "String", "String",
      };
  public static final Object[] argDefaults =
      new Object[] {
        null, null,
      };
  public static java.lang.reflect.Method renderMethod =
      getRenderMethod(japidviews._tags.picka.class);

  {
    setRenderMethod(renderMethod);
    setArgNames(argNames);
    setArgTypes(argTypes);
    setArgDefaults(argDefaults);
    setSourceTemplate(sourceTemplate);
  }
  ////// end of named args stuff

  {
    setHasDoBody();
  }

  private String a; // line 1, japidviews/_tags/picka.html
  private String b; // line 1, japidviews/_tags/picka.html

  public cn.bran.japid.template.RenderResult render(
      DoBody body, cn.bran.japid.compiler.NamedArgRuntime... named) {
    Object[] args = buildArgs(named, body);
    try {
      return runRenderer(args);
    } catch (RuntimeException e) {
      handleException(e);
      throw e;
    } // line 1, japidviews/_tags/picka.html
  }

  private DoBody body;

  public static interface DoBody<A> {
    void render(A a);

    void setBuffer(StringBuilder sb);

    void resetBuffer();
  }

  <A> String renderBody(A a) {
    StringBuilder sb = new StringBuilder();
    if (body != null) {
      body.setBuffer(sb);
      body.render(a);
      body.resetBuffer();
    }
    return sb.toString();
  }

  public cn.bran.japid.template.RenderResult render(String a, String b, DoBody body) {
    this.body = body;
    this.a = a;
    this.b = b;
    try {
      super.layout();
    } catch (RuntimeException __e) {
      super.handleException(__e);
    } // line 1, japidviews/_tags/picka.html
    return getRenderResult();
  }

  public cn.bran.japid.template.RenderResult render(String a, String b) {
    this.a = a;
    this.b = b;
    try {
      super.layout();
    } catch (RuntimeException __e) {
      super.handleException(__e);
    } // line 1, japidviews/_tags/picka.html
    return getRenderResult();
  }

  public static cn.bran.japid.template.RenderResult apply(String a, String b) {
    return new picka().render(a, b);
  }

  @Override
  protected void doLayout() {
    beginDoLayout(sourceTemplate);
    ; // line 1, picka.html
    p("<p>\n" + "some text: "); // line 1, picka.html
    p(a); // line 3, picka.html
    p(" \n" + "</p>\n" + "<p>\n"); // line 3, picka.html
    if (body != null) {
      body.setBuffer(getOut());
      body.render(a + b);
      body.resetBuffer();
    } // line 6, picka.html
    p("</p>\n"); // line 6, picka.html
    String x = renderBody("xxx"); // line 8, picka.html
    p("["); // line 8, picka.html
    p(x); // line 9, picka.html
    p("]\n" + "<p>\n" + "more text: "); // line 9, picka.html
    p(b); // line 11, picka.html
    p("\n" + "</p>\n" + " "); // line 11, picka.html

    endDoLayout(sourceTemplate);
  }
}
Example #3
0
//
// NOTE: This file was generated from: japidviews/Application/testCacheForEager.html
// Change to this file will be lost next time the template file is compiled.
//
@cn.bran.play.NoEnhance
public class testCacheForEager extends cn.bran.play.JapidTemplateBase {
  public static final String sourceTemplate = "japidviews/Application/testCacheForEager.html";

  private void initHeaders() {
    putHeader("Content-Type", "text/html; charset=utf-8");
    setContentType("text/html; charset=utf-8");
  }

  {
  }

  // - add implicit fields with Play

  final play.mvc.Http.Request request = play.mvc.Http.Request.current();
  final play.mvc.Http.Response response = play.mvc.Http.Response.current();
  final play.mvc.Scope.Session session = play.mvc.Scope.Session.current();
  final play.mvc.Scope.RenderArgs renderArgs = play.mvc.Scope.RenderArgs.current();
  final play.mvc.Scope.Params params = play.mvc.Scope.Params.current();
  final play.data.validation.Validation validation = play.data.validation.Validation.current();
  final cn.bran.play.FieldErrors errors = new cn.bran.play.FieldErrors(validation);
  final play.Play _play = new play.Play();

  // - end of implicit fields with Play

  public testCacheForEager() {
    super((StringBuilder) null);
    initHeaders();
  }

  public testCacheForEager(StringBuilder out) {
    super(out);
    initHeaders();
  }

  public testCacheForEager(cn.bran.japid.template.JapidTemplateBaseWithoutPlay caller) {
    super(caller);
  }

  /* based on https://github.com/branaway/Japid/issues/12
   */
  public static final String[] argNames =
      new String[] {
          /* args of the template*/
        "a",
      };
  public static final String[] argTypes =
      new String[] {
          /* arg types of the template*/
        "String",
      };
  public static final Object[] argDefaults =
      new Object[] {
        null,
      };
  public static java.lang.reflect.Method renderMethod =
      getRenderMethod(japidviews.Application.testCacheForEager.class);

  {
    setRenderMethod(renderMethod);
    setArgNames(argNames);
    setArgTypes(argTypes);
    setArgDefaults(argDefaults);
    setSourceTemplate(sourceTemplate);
  }
  ////// end of named args stuff

  private String a; // line 1, japidviews/Application/testCacheForEager.html

  public cn.bran.japid.template.RenderResult render(String a) {
    this.a = a;
    try {
      super.layout();
    } catch (RuntimeException __e) {
      super.handleException(__e);
    } // line 1, japidviews/Application/testCacheForEager.html
    return getRenderResult();
  }

  public static cn.bran.japid.template.RenderResult apply(String a) {
    return new testCacheForEager().render(a);
  }

  @Override
  protected void doLayout() {
    beginDoLayout(sourceTemplate);
    ; // line 1, testCacheForEager.html
    p("\n" + "<html>\n" + "\n" + "<body>\n" + "	hello "); // line 1, testCacheForEager.html
    p(a); // line 6, testCacheForEager.html
    p(", now seconds is "); // line 6, testCacheForEager.html
    actionRunners.put(
        getOut().length(),
        new cn.bran.play.CacheablePlayActionRunner("", Application.class, "seconds", "") {
          @Override
          public void runPlayAction() throws cn.bran.play.JapidResult {
            Application.seconds(); // line 6, testCacheForEager.html
          }
        });
    p("\n"); // line 6, testCacheForEager.html
    p("\n" + "</body>\n" + "</html>"); // line 6, testCacheForEager.html

    endDoLayout(sourceTemplate);
  }
}
Example #4
0
  /**
   * Binds data to this form - that is, handles form submission.
   *
   * @param data data to submit
   * @return a copy of this form filled with the new data
   */
  @SuppressWarnings("unchecked")
  public Form<T> bind(Map<String, String> data, String... allowedFields) {

    DataBinder dataBinder;
    Map<String, String> objectData = data;
    if (rootName == null) {
      dataBinder = new DataBinder(blankInstance());
    } else {
      dataBinder = new DataBinder(blankInstance(), rootName);
      objectData = new HashMap<>();
      for (String key : data.keySet()) {
        if (key.startsWith(rootName + ".")) {
          objectData.put(key.substring(rootName.length() + 1), data.get(key));
        }
      }
    }
    if (allowedFields.length > 0) {
      dataBinder.setAllowedFields(allowedFields);
    }
    SpringValidatorAdapter validator =
        new SpringValidatorAdapter(play.data.validation.Validation.getValidator());
    dataBinder.setValidator(validator);
    dataBinder.setConversionService(formatters.conversion);
    dataBinder.setAutoGrowNestedPaths(true);
    final Map<String, String> objectDataFinal = objectData;
    withRequestLocale(
        () -> {
          dataBinder.bind(new MutablePropertyValues(objectDataFinal));
          return null;
        });
    Set<ConstraintViolation<Object>> validationErrors;
    if (groups != null) {
      validationErrors = validator.validate(dataBinder.getTarget(), groups);
    } else {
      validationErrors = validator.validate(dataBinder.getTarget());
    }

    BindingResult result = dataBinder.getBindingResult();

    for (ConstraintViolation<Object> violation : validationErrors) {
      String field = violation.getPropertyPath().toString();
      FieldError fieldError = result.getFieldError(field);
      if (fieldError == null || !fieldError.isBindingFailure()) {
        try {
          result.rejectValue(
              field,
              violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(),
              getArgumentsForConstraint(
                  result.getObjectName(), field, violation.getConstraintDescriptor()),
              getMessageForConstraintViolation(violation));
        } catch (NotReadablePropertyException ex) {
          throw new IllegalStateException(
              "JSR-303 validated property '"
                  + field
                  + "' does not have a corresponding accessor for data binding - "
                  + "check your DataBinder's configuration (bean property versus direct field access)",
              ex);
        }
      }
    }

    if (result.hasErrors() || result.getGlobalErrorCount() > 0) {
      Map<String, List<ValidationError>> errors = new HashMap<>();
      for (FieldError error : result.getFieldErrors()) {
        String key = error.getObjectName() + "." + error.getField();
        if (key.startsWith("target.") && rootName == null) {
          key = key.substring(7);
        }
        if (!errors.containsKey(key)) {
          errors.put(key, new ArrayList<>());
        }

        ValidationError validationError;
        if (error.isBindingFailure()) {
          ImmutableList.Builder<String> builder = ImmutableList.builder();
          Optional<Messages> msgs =
              Optional.of(Http.Context.current.get()).map(c -> messagesApi.preferred(c.request()));
          for (String code : error.getCodes()) {
            code = code.replace("typeMismatch", "error.invalid");
            if (!msgs.isPresent() || msgs.get().isDefinedAt(code)) {
              builder.add(code);
            }
          }
          validationError =
              new ValidationError(
                  key, builder.build().reverse(), convertErrorArguments(error.getArguments()));
        } else {
          validationError =
              new ValidationError(
                  key, error.getDefaultMessage(), convertErrorArguments(error.getArguments()));
        }
        errors.get(key).add(validationError);
      }

      List<ValidationError> globalErrors = new ArrayList<>();

      for (ObjectError error : result.getGlobalErrors()) {
        globalErrors.add(
            new ValidationError(
                "", error.getDefaultMessage(), convertErrorArguments(error.getArguments())));
      }

      if (!globalErrors.isEmpty()) {
        errors.put("", globalErrors);
      }

      return new Form(
          rootName, backedType, data, errors, Optional.empty(), groups, messagesApi, formatters);
    } else {
      Object globalError = null;
      if (result.getTarget() != null) {
        try {
          java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate");
          globalError = v.invoke(result.getTarget());
        } catch (NoSuchMethodException e) {
          // do nothing
        } catch (Throwable e) {
          throw new RuntimeException(e);
        }
      }
      if (globalError != null) {
        Map<String, List<ValidationError>> errors = new HashMap<>();
        if (globalError instanceof String) {
          errors.put("", new ArrayList<>());
          errors.get("").add(new ValidationError("", (String) globalError, new ArrayList()));
        } else if (globalError instanceof List) {
          for (ValidationError error : (List<ValidationError>) globalError) {
            List<ValidationError> errorsForKey = errors.get(error.key());
            if (errorsForKey == null) {
              errors.put(error.key(), errorsForKey = new ArrayList<>());
            }
            errorsForKey.add(error);
          }
        } else if (globalError instanceof Map) {
          errors = (Map<String, List<ValidationError>>) globalError;
        }
        return new Form(
            rootName, backedType, data, errors, Optional.empty(), groups, messagesApi, formatters);
      }
      return new Form(
          rootName,
          backedType,
          new HashMap<>(data),
          new HashMap<>(errors),
          Optional.ofNullable((T) result.getTarget()),
          groups,
          messagesApi,
          formatters);
    }
  }
Example #5
0
//
// NOTE: This file was generated from: japidviews/templates/Posts.html
// Change to this file will be lost next time the template file is compiled.
//
public class Posts extends cn.bran.play.JapidTemplateBase {
  public static final String sourceTemplate = "japidviews/templates/Posts.html";

  {
    putHeader("Content-Type", "text/html; charset=utf-8");
    setContentType("text/html; charset=utf-8");
  }

  // - add implicit fields with Play

  final play.mvc.Http.Request request = play.mvc.Http.Request.current();
  final play.mvc.Http.Response response = play.mvc.Http.Response.current();
  final play.mvc.Scope.Session session = play.mvc.Scope.Session.current();
  final play.mvc.Scope.RenderArgs renderArgs = play.mvc.Scope.RenderArgs.current();
  final play.mvc.Scope.Params params = play.mvc.Scope.Params.current();
  final play.data.validation.Validation validation = play.data.validation.Validation.current();
  final cn.bran.play.FieldErrors errors = new cn.bran.play.FieldErrors(validation);
  final play.Play _play = new play.Play();

  // - end of implicit fields with Play

  public Posts() {
    super(null);
  }

  public Posts(StringBuilder out) {
    super(out);
  }
  /* based on https://github.com/branaway/Japid/issues/12
   */
  public static final String[] argNames =
      new String[] {
        /* args of the template*/
        "blogTitle", "allPost",
      };
  public static final String[] argTypes =
      new String[] {
        /* arg types of the template*/
        "String", "List<Post>",
      };
  public static final Object[] argDefaults =
      new Object[] {
        null, null,
      };
  public static java.lang.reflect.Method renderMethod =
      getRenderMethod(japidviews.templates.Posts.class);

  {
    setRenderMethod(renderMethod);
    setArgNames(argNames);
    setArgTypes(argTypes);
    setArgDefaults(argDefaults);
    setSourceTemplate(sourceTemplate);
  }
  ////// end of named args stuff

  private String blogTitle; // line 2
  private List<Post> allPost; // line 2

  public cn.bran.japid.template.RenderResult render(String blogTitle, List<Post> allPost) {
    this.blogTitle = blogTitle;
    this.allPost = allPost;
    long t = -1;
    try {
      super.layout();
    } catch (RuntimeException e) {
      super.handleException(e);
    } // line 2
    return new cn.bran.japid.template.RenderResultPartial(
        getHeaders(), getOut(), t, actionRunners, sourceTemplate);
  }

  @Override
  protected void doLayout() {
    beginDoLayout(sourceTemplate);
    // ------
    ; // line 1

    for (Post post : allPost) { // line 4
      p("	- title: "); // line 4
      p(post.title); // line 5
      p("\n" + "	- date: "); // line 5
      p(post.postedAt); // line 6
      p("\n" + "	- author "); // line 6
      p(post.author.name); // line 7
      p(" "); // line 7
      p(post.author.gender); // line 7
      p("\n" + "	the real title: 你好\n"); // line 7
    } // line 9
    p("\n"); // line 9

    endDoLayout(sourceTemplate);
  }
}
Example #6
0
//
// NOTE: This file was generated from: japidviews/more/MyController/subview.html
// Change to this file will be lost next time the template file is compiled.
//
@cn.bran.play.NoEnhance
public class subview extends superview {
  public static final String sourceTemplate = "japidviews/more/MyController/subview.html";

  private void initHeaders() {
    putHeader("Content-Type", "text/html; charset=utf-8");
    setContentType("text/html; charset=utf-8");
  }

  {
  }

  // - add implicit fields with Play

  final play.mvc.Http.Request request = play.mvc.Http.Request.current();
  final play.mvc.Http.Response response = play.mvc.Http.Response.current();
  final play.mvc.Scope.Session session = play.mvc.Scope.Session.current();
  final play.mvc.Scope.RenderArgs renderArgs = play.mvc.Scope.RenderArgs.current();
  final play.mvc.Scope.Params params = play.mvc.Scope.Params.current();
  final play.data.validation.Validation validation = play.data.validation.Validation.current();
  final cn.bran.play.FieldErrors errors = new cn.bran.play.FieldErrors(validation);
  final play.Play _play = new play.Play();

  // - end of implicit fields with Play

  public subview() {
    super((StringBuilder) null);
    initHeaders();
  }

  public subview(StringBuilder out) {
    super(out);
    initHeaders();
  }

  public subview(cn.bran.japid.template.JapidTemplateBaseWithoutPlay caller) {
    super(caller);
  }

  /* based on https://github.com/branaway/Japid/issues/12
   */
  public static final String[] argNames =
      new String[] {
        /* args of the template*/
        "s",
      };
  public static final String[] argTypes =
      new String[] {
        /* arg types of the template*/
        "String",
      };
  public static final Object[] argDefaults =
      new Object[] {
        null,
      };
  public static java.lang.reflect.Method renderMethod =
      getRenderMethod(japidviews.more.MyController.subview.class);

  {
    setRenderMethod(renderMethod);
    setArgNames(argNames);
    setArgTypes(argTypes);
    setArgDefaults(argDefaults);
    setSourceTemplate(sourceTemplate);
  }
  ////// end of named args stuff

  private String s; // line 2, japidviews/more/MyController/subview.html

  public cn.bran.japid.template.RenderResult render(String s) {
    this.s = s;
    try {
      super.layout();
    } catch (RuntimeException __e) {
      super.handleException(__e);
    } // line 2, japidviews/more/MyController/subview.html
    return getRenderResult();
  }

  public static cn.bran.japid.template.RenderResult apply(String s) {
    return new subview().render(s);
  }

  @Override
  protected void doLayout() {
    beginDoLayout(sourceTemplate);
    ; // line 1, subview.html
    ; // line 2, subview.html
    // line 4, subview.html
    ; // line 4, subview.html
    // line 5, subview.html
    p("\n" + "\n" + "hello "); // line 5, subview.html
    p(s); // line 8, subview.html
    p("\n"); // line 8, subview.html
    new japidviews.more.MyController._tags.taggy(subview.this)
        .render(s); // line 10, subview.html// line 10, subview.html
    p(" "); // line 10, subview.html

    endDoLayout(sourceTemplate);
  }

  @Override
  protected void side() {
    p("my side bar");
    ;
  }

  @Override
  protected void title() {
    p("my title from subview");
    ;
  }
}
Example #7
0
//
// NOTE: This file was generated from: japidviews/templates/invokeInLoop.html
// Change to this file will be lost next time the template file is compiled.
//
@cn.bran.play.NoEnhance
public class invokeInLoop extends cn.bran.play.JapidTemplateBase {
  public static final String sourceTemplate = "japidviews/templates/invokeInLoop.html";

  {
    putHeader("Content-Type", "text/html; charset=utf-8");
    setContentType("text/html; charset=utf-8");
  }

  // - add implicit fields with Play

  final play.mvc.Http.Request request = play.mvc.Http.Request.current();
  final play.mvc.Http.Response response = play.mvc.Http.Response.current();
  final play.mvc.Scope.Session session = play.mvc.Scope.Session.current();
  final play.mvc.Scope.RenderArgs renderArgs = play.mvc.Scope.RenderArgs.current();
  final play.mvc.Scope.Params params = play.mvc.Scope.Params.current();
  final play.data.validation.Validation validation = play.data.validation.Validation.current();
  final cn.bran.play.FieldErrors errors = new cn.bran.play.FieldErrors(validation);
  final play.Play _play = new play.Play();

  // - end of implicit fields with Play

  public invokeInLoop() {
    super(null);
  }

  public invokeInLoop(StringBuilder out) {
    super(out);
  }
  /* based on https://github.com/branaway/Japid/issues/12
   */
  public static final String[] argNames =
      new String[] {
          /* args of the template*/
        "posts",
      };
  public static final String[] argTypes =
      new String[] {
          /* arg types of the template*/
        "List<Post>",
      };
  public static final Object[] argDefaults =
      new Object[] {
        null,
      };
  public static java.lang.reflect.Method renderMethod =
      getRenderMethod(japidviews.templates.invokeInLoop.class);

  {
    setRenderMethod(renderMethod);
    setArgNames(argNames);
    setArgTypes(argTypes);
    setArgDefaults(argDefaults);
    setSourceTemplate(sourceTemplate);
  }
  ////// end of named args stuff

  private List<Post> posts; // line 2

  public cn.bran.japid.template.RenderResult render(List<Post> posts) {
    this.posts = posts;
    long t = -1;
    try {
      super.layout();
    } catch (RuntimeException e) {
      super.handleException(e);
    } // line 2
    return new cn.bran.japid.template.RenderResultPartial(
        getHeaders(), getOut(), t, actionRunners, sourceTemplate);
  }

  @Override
  protected void doLayout() {
    beginDoLayout(sourceTemplate);
    // ------
    ; // line 1
    p("\n"); // line 2
    p("\n" + "\n"); // line 7
    for (int i = 0; i < 3; i++) { // line 9
      final int j = i; // line 10
      p("	"); // line 10
      actionRunners.put(
          getOut().length(),
          new cn.bran.play.CacheablePlayActionRunner("", Application.class, "echo", j) {
            @Override
            public void runPlayAction() throws cn.bran.play.JapidResult {
              Application.echo(j); // line 11
            }
          });
      p("\n"); // line 11
      p("\n"); // line 11
    } // line 12
    p("<p/>\n"); // line 12
    p("\n" + "\n"); // line 14
    for (final Post p : posts) { // line 16
      p("    another notation for invoking actions:  \n" + "    "); // line 16
      actionRunners.put(
          getOut().length(),
          new cn.bran.play.CacheablePlayActionRunner("", Application.class, "echoPost", p) {
            @Override
            public void runPlayAction() throws cn.bran.play.JapidResult {
              Application.echoPost(p); // line 18
            }
          });
      p("\n"); // line 18
    } // line 19
    ; // line 19

    endDoLayout(sourceTemplate);
  }
}
Example #8
0
//
// NOTE: This file was generated from: japidviews/more/ContentNegotiation/index.xml
// Change to this file will be lost next time the template file is compiled.
//
@cn.bran.play.NoEnhance
public class index_xml extends cn.bran.play.JapidTemplateBase {
  public static final String sourceTemplate = "japidviews/more/ContentNegotiation/index.xml";

  private void initHeaders() {
    putHeader("Content-Type", "text/xml; charset=utf-8");
    setContentType("text/xml; charset=utf-8");
  }

  {
  }

  // - add implicit fields with Play

  final play.mvc.Http.Request request = play.mvc.Http.Request.current();
  final play.mvc.Http.Response response = play.mvc.Http.Response.current();
  final play.mvc.Scope.Session session = play.mvc.Scope.Session.current();
  final play.mvc.Scope.RenderArgs renderArgs = play.mvc.Scope.RenderArgs.current();
  final play.mvc.Scope.Params params = play.mvc.Scope.Params.current();
  final play.data.validation.Validation validation = play.data.validation.Validation.current();
  final cn.bran.play.FieldErrors errors = new cn.bran.play.FieldErrors(validation);
  final play.Play _play = new play.Play();

  // - end of implicit fields with Play

  public index_xml() {
    super((StringBuilder) null);
    initHeaders();
  }

  public index_xml(StringBuilder out) {
    super(out);
    initHeaders();
  }

  public index_xml(cn.bran.japid.template.JapidTemplateBaseWithoutPlay caller) {
    super(caller);
  }

  /* based on https://github.com/branaway/Japid/issues/12
   */
  public static final String[] argNames = new String[] {
        /* args of the template*/
      };
  public static final String[] argTypes = new String[] {
        /* arg types of the template*/
      };
  public static final Object[] argDefaults = new Object[] {};
  public static java.lang.reflect.Method renderMethod =
      getRenderMethod(japidviews.more.ContentNegotiation.index_xml.class);

  {
    setRenderMethod(renderMethod);
    setArgNames(argNames);
    setArgTypes(argTypes);
    setArgDefaults(argDefaults);
    setSourceTemplate(sourceTemplate);
  }
  ////// end of named args stuff

  public cn.bran.japid.template.RenderResult render() {
    try {
      super.layout();
    } catch (RuntimeException __e) {
      super.handleException(__e);
    } // line 0, japidviews/more/ContentNegotiation/index.xml
    return getRenderResult();
  }

  public static cn.bran.japid.template.RenderResult apply() {
    return new index_xml().render();
  }

  @Override
  protected void doLayout() {
    beginDoLayout(sourceTemplate);
    p("<format>\n"); // line 1, index.xml
    p(request.format); // line 2, index.xml
    p("\n" + "</format>"); // line 2, index.xml

    endDoLayout(sourceTemplate);
  }
}
Example #9
0
  /**
   * Binds data to this form - that is, handles form submission.
   *
   * @param data data to submit
   * @return a copy of this form filled with the new data
   */
  public Form<T> bind(Map<String, String> data, String... allowedFields) {

    DataBinder dataBinder = null;
    Map<String, String> objectData = data;
    if (rootName == null) {
      dataBinder = new DataBinder(blankInstance());
    } else {
      dataBinder = new DataBinder(blankInstance(), rootName);
      objectData = new HashMap<String, String>();
      for (String key : data.keySet()) {
        if (key.startsWith(rootName + ".")) {
          objectData.put(key.substring(rootName.length() + 1), data.get(key));
        }
      }
    }
    if (allowedFields.length > 0) {
      dataBinder.setAllowedFields(allowedFields);
    }
    SpringValidatorAdapter validator =
        new SpringValidatorAdapter(play.data.validation.Validation.getValidator());
    dataBinder.setValidator(validator);
    dataBinder.setConversionService(play.data.format.Formatters.conversion);
    dataBinder.setAutoGrowNestedPaths(true);
    dataBinder.bind(new MutablePropertyValues(objectData));
    Set<ConstraintViolation<Object>> validationErrors;
    if (groups != null) {
      validationErrors = validator.validate(dataBinder.getTarget(), groups);
    } else {
      validationErrors = validator.validate(dataBinder.getTarget());
    }

    BindingResult result = dataBinder.getBindingResult();

    for (ConstraintViolation<Object> violation : validationErrors) {
      String field = violation.getPropertyPath().toString();
      FieldError fieldError = result.getFieldError(field);
      if (fieldError == null || !fieldError.isBindingFailure()) {
        try {
          result.rejectValue(
              field,
              violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(),
              getArgumentsForConstraint(
                  result.getObjectName(), field, violation.getConstraintDescriptor()),
              violation.getMessage());
        } catch (NotReadablePropertyException ex) {
          throw new IllegalStateException(
              "JSR-303 validated property '"
                  + field
                  + "' does not have a corresponding accessor for data binding - "
                  + "check your DataBinder's configuration (bean property versus direct field access)",
              ex);
        }
      }
    }

    if (result.hasErrors()) {
      Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
      for (FieldError error : result.getFieldErrors()) {
        String key = error.getObjectName() + "." + error.getField();
        if (key.startsWith("target.") && rootName == null) {
          key = key.substring(7);
        }
        List<Object> arguments = new ArrayList<Object>();
        for (Object arg : error.getArguments()) {
          if (!(arg
              instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) {
            arguments.add(arg);
          }
        }
        if (!errors.containsKey(key)) {
          errors.put(key, new ArrayList<ValidationError>());
        }
        errors
            .get(key)
            .add(
                new ValidationError(
                    key,
                    error.isBindingFailure() ? "error.invalid" : error.getDefaultMessage(),
                    arguments));
      }
      return new Form(rootName, backedType, data, errors, None(), groups);
    } else {
      Object globalError = null;
      if (result.getTarget() != null) {
        try {
          java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate");
          globalError = v.invoke(result.getTarget());
        } catch (NoSuchMethodException e) {
        } catch (Throwable e) {
          throw new RuntimeException(e);
        }
      }
      if (globalError != null) {
        Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
        if (globalError instanceof String) {
          errors.put("", new ArrayList<ValidationError>());
          errors.get("").add(new ValidationError("", (String) globalError, new ArrayList()));
        } else if (globalError instanceof List) {
          errors.put("", (List<ValidationError>) globalError);
        } else if (globalError instanceof Map) {
          errors = (Map<String, List<ValidationError>>) globalError;
        }
        return new Form(rootName, backedType, data, errors, None(), groups);
      }
      return new Form(
          rootName,
          backedType,
          new HashMap<String, String>(data),
          new HashMap<String, List<ValidationError>>(errors),
          Some((T) result.getTarget()),
          groups);
    }
  }
//
// NOTE: This file was generated from: japidviews/AdminController/flashPurchaseList.html
// Change to this file will be lost next time the template file is compiled.
//
@cn.bran.play.NoEnhance
public class flashPurchaseList extends backStageLayout {
  public static final String sourceTemplate = "japidviews/AdminController/flashPurchaseList.html";

  private void initHeaders() {
    putHeader("Content-Type", "text/html; charset=utf-8");
    setContentType("text/html; charset=utf-8");
  }

  {
  }

  // - add implicit fields with Play

  final play.mvc.Http.Request request = play.mvc.Http.Request.current();
  final play.mvc.Http.Response response = play.mvc.Http.Response.current();
  final play.mvc.Scope.Session session = play.mvc.Scope.Session.current();
  final play.mvc.Scope.RenderArgs renderArgs = play.mvc.Scope.RenderArgs.current();
  final play.mvc.Scope.Params params = play.mvc.Scope.Params.current();
  final play.data.validation.Validation validation = play.data.validation.Validation.current();
  final cn.bran.play.FieldErrors errors = new cn.bran.play.FieldErrors(validation);
  final play.Play _play = new play.Play();

  // - end of implicit fields with Play

  public flashPurchaseList() {
    super((StringBuilder) null);
    initHeaders();
  }

  public flashPurchaseList(StringBuilder out) {
    super(out);
    initHeaders();
  }

  public flashPurchaseList(cn.bran.japid.template.JapidTemplateBaseWithoutPlay caller) {
    super(caller);
  }

  /* based on https://github.com/branaway/Japid/issues/12
   */
  public static final String[] argNames =
      new String[] {
          /* args of the template*/
        "announcementList", "currentPage", "totalPage",
      };
  public static final String[] argTypes =
      new String[] {
          /* arg types of the template*/
        "List<Announcements>", "int", "int",
      };
  public static final Object[] argDefaults =
      new Object[] {
        null, null, null,
      };
  public static java.lang.reflect.Method renderMethod =
      getRenderMethod(japidviews.AdminController.flashPurchaseList.class);

  {
    setRenderMethod(renderMethod);
    setArgNames(argNames);
    setArgTypes(argTypes);
    setArgDefaults(argDefaults);
    setSourceTemplate(sourceTemplate);
  }
  ////// end of named args stuff

  private List<Announcements>
      announcementList; // line 3, japidviews/AdminController/flashPurchaseList.html
  private int currentPage; // line 3, japidviews/AdminController/flashPurchaseList.html
  private int totalPage; // line 3, japidviews/AdminController/flashPurchaseList.html

  public cn.bran.japid.template.RenderResult render(
      List<Announcements> announcementList, int currentPage, int totalPage) {
    this.announcementList = announcementList;
    this.currentPage = currentPage;
    this.totalPage = totalPage;
    try {
      super.layout();
    } catch (RuntimeException __e) {
      super.handleException(__e);
    } // line 3, japidviews/AdminController/flashPurchaseList.html
    return getRenderResult();
  }

  public static cn.bran.japid.template.RenderResult apply(
      List<Announcements> announcementList, int currentPage, int totalPage) {
    return new flashPurchaseList().render(announcementList, currentPage, totalPage);
  }

  @Override
  protected void doLayout() {
    beginDoLayout(sourceTemplate);
    ; // line 1, japidviews\AdminController\flashPurchaseList.html
    // line 6, japidviews\AdminController\flashPurchaseList.html
    // line 7, japidviews\AdminController\flashPurchaseList.html
    p(
        "<div class=\"navbar-inner\">\n"
            + "</div>\n"
            + "<div class=\"container\">\n"
            + "	<!-- 左菜单 -->\n"
            + "	"); // line 11, japidviews\AdminController\flashPurchaseList.html
    new leftMenusTag(flashPurchaseList.this)
        .render(); // line 16, japidviews\AdminController\flashPurchaseList.html// line 16,
                   // japidviews\AdminController\flashPurchaseList.html
    p(
        "    	<!-- 主内容 -->\n"
            + "		  <div class=\"content\" id=\"content\">\n"
            + "            <!-- 标题 -->\n"
            + "            <h3 class=\"title add-commodity-title\">活动列表</h3>\n"
            + "			"); // line 16, japidviews\AdminController\flashPurchaseList.html
    p(
        "            <!-- table -->\n"
            + "            <table class=\"table\">\n"
            + "                <tr>\n"
            + "                    <th>活动名称</th>\n"
            + "                    <th>开始时间</th>\n"
            + "                    <th>结束时间</th>\n"
            + "                    <th class=\"handle-w1\">操作</th>\n"
            + "                </tr>\n"
            + "                "); // line 24, japidviews\AdminController\flashPurchaseList.html
    if (!announcementList.isEmpty()) { // line 33, japidviews\AdminController\flashPurchaseList.html
      for (Announcements announcements :
          announcementList) { // line 34, japidviews\AdminController\flashPurchaseList.html
        p(
            "                	<tr>\n"
                + "                    <td>"); // line 34,
                                               // japidviews\AdminController\flashPurchaseList.html
        p(announcements.title); // line 36, japidviews\AdminController\flashPurchaseList.html
        p(
            "</td>\n"
                + "                    <td>"); // line 36,
                                               // japidviews\AdminController\flashPurchaseList.html
        p(announcements.startTime); // line 37, japidviews\AdminController\flashPurchaseList.html
        p(
            "</td>\n"
                + "                    <td>"); // line 37,
                                               // japidviews\AdminController\flashPurchaseList.html
        p(announcements.endTime); // line 38, japidviews\AdminController\flashPurchaseList.html
        p(
            "</td>\n"
                + "                    <td>\n"
                + "                    	<a id=\"preview\" href=\""); // line 38,
                                                                     // japidviews\AdminController\flashPurchaseList.html
        p(
            lookup(
                "AdminController.preview",
                announcements.id)); // line 40, japidviews\AdminController\flashPurchaseList.html
        p(
            "\" class=\"defaultBtn btn-sm btn-green\">预览</a>\n"
                + "                        <a id=\"del\" href=\""); // line 40,
                                                                    // japidviews\AdminController\flashPurchaseList.html
        p(
            lookup(
                "AdminController.deleteFastGood",
                announcements.id)); // line 41, japidviews\AdminController\flashPurchaseList.html
        p(
            "\" class=\"defaultBtn btn-sm btn-red\">删除</a>\n"
                + "                    </td>\n"
                + "                </tr>\n"
                + "                "); // line 41, japidviews\AdminController\flashPurchaseList.html
      } // line 44, japidviews\AdminController\flashPurchaseList.html
    } // line 45, japidviews\AdminController\flashPurchaseList.html
    p(
        "            </table>\n"
            + "            "); // line 45, japidviews\AdminController\flashPurchaseList.html
    new pagination(flashPurchaseList.this)
        .render(
            getUrl(),
            "page",
            currentPage,
            totalPage,
            null); // line 47, japidviews\AdminController\flashPurchaseList.html// line 47,
                   // japidviews\AdminController\flashPurchaseList.html
    // line 48, japidviews\AdminController\flashPurchaseList.html
    p(
        "            <!-- h20 -->\n"
            + "            <div class=\"h20\"></div>\n"
            + "		</div>\n"
            + "\n"
            + "    </div>\n"
            + "</body>\n"
            + "</html>"); // line 50, japidviews\AdminController\flashPurchaseList.html

    endDoLayout(sourceTemplate);
  }

  @Override
  protected void moreJSLink() {
    // line 7, japidviews\AdminController\flashPurchaseList.html
    p(
        "<script>\n"
            + "    main.setSidebarHover(\"index\");\n"
            + "</script>\n"); // line 7, japidviews\AdminController\flashPurchaseList.html
    ;
  }

  @Override
  protected void title() {
    // line 6, japidviews\AdminController\flashPurchaseList.html
    p("后台管理-活动列表"); // line 6, japidviews\AdminController\flashPurchaseList.html
    ;
  }

  public String getUrl() {
    StringBuilder sb = new StringBuilder();
    StringBuilder ori = getOut();
    this.setOut(sb);
    TreeMap<Integer, cn.bran.japid.template.ActionRunner> parentActionRunners = actionRunners;
    actionRunners = new TreeMap<Integer, cn.bran.japid.template.ActionRunner>();
    // line 48, japidviews\AdminController\flashPurchaseList.html
    p("            	"); // line 48, japidviews\AdminController\flashPurchaseList.html
    p(
        lookup(
            "AdminController.flashPurchaseList",
            new Object[] {})); // line 49, japidviews\AdminController\flashPurchaseList.html
    p("            "); // line 49, japidviews\AdminController\flashPurchaseList.html

    this.setOut(ori);
    if (actionRunners.size() > 0) {
      StringBuilder _sb2 = new StringBuilder();
      int segStart = 0;
      for (Map.Entry<Integer, cn.bran.japid.template.ActionRunner> _arEntry :
          actionRunners.entrySet()) {
        int pos = _arEntry.getKey();
        _sb2.append(sb.substring(segStart, pos));
        segStart = pos;
        cn.bran.japid.template.ActionRunner _a_ = _arEntry.getValue();
        _sb2.append(_a_.run().getContent().toString());
      }
      _sb2.append(sb.substring(segStart));
      actionRunners = parentActionRunners;
      return _sb2.toString();
    } else {
      actionRunners = parentActionRunners;
      return sb.toString();
    }
  }
}
Example #11
0
//
// NOTE: This file was generated from: japidviews/templates/Actions.html
// Change to this file will be lost next time the template file is compiled.
//
public class Actions extends cn.bran.play.JapidTemplateBase {
  public static final String sourceTemplate = "japidviews/templates/Actions.html";

  {
    putHeader("Content-Type", "text/html; charset=utf-8");
    setContentType("text/html; charset=utf-8");
  }

  // - add implicit fields with Play

  final play.mvc.Http.Request request = play.mvc.Http.Request.current();
  final play.mvc.Http.Response response = play.mvc.Http.Response.current();
  final play.mvc.Scope.Session session = play.mvc.Scope.Session.current();
  final play.mvc.Scope.RenderArgs renderArgs = play.mvc.Scope.RenderArgs.current();
  final play.mvc.Scope.Params params = play.mvc.Scope.Params.current();
  final play.data.validation.Validation validation = play.data.validation.Validation.current();
  final cn.bran.play.FieldErrors errors = new cn.bran.play.FieldErrors(validation);
  final play.Play _play = new play.Play();

  // - end of implicit fields with Play

  public Actions() {
    super(null);
  }

  public Actions(StringBuilder out) {
    super(out);
  }
  /* based on https://github.com/branaway/Japid/issues/12
   */
  public static final String[] argNames =
      new String[] {
        /* args of the template*/
        "post",
      };
  public static final String[] argTypes =
      new String[] {
        /* arg types of the template*/
        "models.japidsample.Post",
      };
  public static final Object[] argDefaults =
      new Object[] {
        null,
      };
  public static java.lang.reflect.Method renderMethod =
      getRenderMethod(japidviews.templates.Actions.class);

  {
    setRenderMethod(renderMethod);
    setArgNames(argNames);
    setArgTypes(argTypes);
    setArgDefaults(argDefaults);
    setSourceTemplate(sourceTemplate);
  }
  ////// end of named args stuff

  private models.japidsample.Post post; // line 1

  public cn.bran.japid.template.RenderResult render(models.japidsample.Post post) {
    this.post = post;
    long t = -1;
    try {
      super.layout();
    } catch (RuntimeException e) {
      super.handleException(e);
    } // line 1
    return new cn.bran.japid.template.RenderResultPartial(
        getHeaders(), getOut(), t, actionRunners, sourceTemplate);
  }

  @Override
  protected void doLayout() {
    beginDoLayout(sourceTemplate);
    // ------
    ; // line 1
    p("\n" + "\n" + "<form url=\""); // line 1
    p(lookup("showAll", new Object[] {})); // line 4
    p("\"></form>\n" + "<form url=\""); // line 4
    p(lookup("Clients.showAccounts", post.title, post.title)); // line 5
    p("\"></form>\n" + "<form url=\""); // line 5
    p(lookupAbs("Clients.showAccounts", post.title.substring(1, 2))); // line 6
    p("\"></form>\n" + "<form url='"); // line 6
    p(lookupAbs("Clients.showAccounts", new String[] {"aa", "bb"})); // line 7
    p("'></form>\n" + "<form url=\""); // line 7
    p(lookupStatic("/public/stylesheets/main.css")); // line 8
    p("\"></form>\n"); // line 8

    endDoLayout(sourceTemplate);
  }
}