private void bindParameterFromTemplate(ComponentPageElement component, AttributeToken token) {
    String name = token.getName();
    ComponentResources resources = component.getComponentResources();

    // If already bound (i.e., from the component class, via @Component), then
    // ignore the value in the template. This may need improving to just ignore
    // the value if it is an unprefixed literal string.

    if (resources.isBound(name)) return;

    // Meta default of literal for the template.

    String defaultBindingPrefix =
        determineDefaultBindingPrefix(component, name, BindingConstants.LITERAL);

    Binding binding =
        findBinding(
            loadingElement,
            component,
            name,
            token.getValue(),
            defaultBindingPrefix,
            token.getLocation());

    if (binding != null) {
      component.bindParameter(name, binding);

      Map<String, Binding> bindingMap = componentIdToBindingMap.get(component.getCompleteId());
      bindingMap.put(name, binding);
    }
  }
Beispiel #2
0
  Object defaultBlankLabel() {
    Messages containerMessages = resources.getContainerMessages();

    String key = resources.getId() + "-blanklabel";

    if (containerMessages.contains(key)) return containerMessages.get(key);

    return null;
  }
Beispiel #3
0
  @SuppressWarnings("unchecked")
  SelectModel defaultModel() {
    Class valueType = resources.getBoundType("value");

    if (valueType == null) return null;

    if (Enum.class.isAssignableFrom(valueType))
      return new EnumSelectModel(valueType, resources.getContainerMessages());

    return null;
  }
  @SetupRender
  public void init() {

    sorterPersist = sorter;
    selected = null;
    if (!componentResources.isBound("hideIfEmpty")) {
      hideIfEmpty = true;
    }

    if (!componentResources.isBound("toggleNeeded")) {
      toggleNeeded = false;
    }
  }
Beispiel #5
0
  Object onDelete(String courseUuid) {
    if (!StudentUtil.isPossibleUuid(courseUuid)) {
      LOG.info("Invalid CourseUUID");
      courseUuid = null;
      course = null;
      return this;
    }

    this.courseUuid = courseUuid;
    int courseVersion = 0;

    try {
      courseManagerService.deleteCourse(courseUuid, courseVersion);
    } catch (ObjectNotFoundException e) {
      // object has already been deleted.
      LOG.trace("course not found: " + courseUuid);
    } catch (RestClientFailureException e) {
      createForm.recordError("Internal error on server.");
      createForm.recordError(e.getMessage());

      // Display the cause. In a real system we would try harder to get a
      // user-friendly message.
      deleteMessage = ExceptionUtil.getRootCauseMessage(e);

      // Trigger new event "failedDelete" which will bubble up.
      componentResources.triggerEvent(FAILED_DELETE, new Object[] {courseUuid}, null);
      // We don't want "delete" to bubble up, so we return true to say
      // we've handled it.
      // TODO: replace with exception service
      LOG.debug("internal error on server during validation", e);
      return true;
    } catch (Exception e) {
      // Display the cause. In a real system we would try harder to get a
      // user-friendly message.
      deleteMessage = ExceptionUtil.getRootCauseMessage(e);

      // Trigger new event "failedDelete" which will bubble up.
      componentResources.triggerEvent(FAILED_DELETE, new Object[] {courseUuid}, null);
      // We don't want "delete" to bubble up, so we return true to say
      // we've handled it.
      // TODO: replace with exception service
      LOG.info("unhandled exception during deletion", e);
      return true;
    }

    // Trigger new event "successfulDelete" which will bubble up.
    componentResources.triggerEvent(SUCCESFUL_DELETE, new Object[] {courseUuid}, null);
    // We don't want "delete" to bubble up, so we return true to say we've
    // handled it.
    return indexPage;
  }
Beispiel #6
0
  boolean beginRender(MarkupWriter writer) {
    final Field field = this.field;

    decorator.beforeLabel(field);

    labelElement = writer.element("label");

    resources.renderInformalParameters(writer);

    // Since we don't know if the field has rendered yet, we need to defer writing the for and id
    // attributes until we know the field has rendered (and set its clientId property). That's
    // exactly what Heartbeat is for.

    Runnable command =
        new Runnable() {
          public void run() {
            String fieldId = field.getClientId();

            labelElement.forceAttributes("for", fieldId, "id", fieldId + ":label");

            decorator.insideLabel(field, labelElement);
          }
        };

    heartbeat.defer(command);

    return !ignoreBody;
  }
Beispiel #7
0
  private StringBuilder transformJS(
      String js,
      List<String> srcPaths,
      ComponentResources resources,
      String basedir,
      String urlParam) {

    StringBuilder sb = new StringBuilder((int) (js.length() * 0.5));

    if (urlParam.equalsIgnoreCase("siteSearch")) {
      Pattern file = Pattern.compile("./(autocomplete_tags.txt)");
      Matcher m = file.matcher(js);
      int start = 0;
      while (m.find()) {
        sb.append(js, start, m.start());

        String img = basedir + ComponentConstants.RESOURCES_DIR + File.separator + m.group(0);
        srcPaths.add(img);
        sb.append(
            resources.createEventLink(ComponentConstants.SRC_EVENT, (srcPaths.size() - 1)).toURI());

        start = m.end();
      }
      sb.append(js, start, js.length());
    } else sb.append(js);

    return sb;
  }
Beispiel #8
0
 Binding defaultTime() {
   return new AbstractBinding(resources.getLocation()) {
     public Object get() {
       return annotationProvider.getAnnotation(TimeSignificant.class) != null;
     }
   };
 }
  public Component getContainer() {
    if (containerResources == null) {
      return null;
    }

    return containerResources.getComponent();
  }
Beispiel #10
0
  Binding defaultFormat() {
    return new AbstractBinding(resources.getLocation()) {
      @Override
      public boolean isInvariant() {
        return false;
      }

      public Object get() {
        DateFormat shortDateFormat =
            time
                ? DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale)
                : DateFormat.getDateInstance(DateFormat.SHORT, locale);

        if (shortDateFormat instanceof SimpleDateFormat) {
          SimpleDateFormat simpleDateFormat = (SimpleDateFormat) shortDateFormat;

          String pattern = simpleDateFormat.toPattern();

          String revised = pattern.replaceAll("(?<!y)yy(?!y)", "yyyy");

          return new SimpleDateFormat(revised);
        }

        return shortDateFormat;
      }
    };
  }
Beispiel #11
0
 Object onActionFromLogout() throws RemoteException {
   persistentLocale.set(
       new Locale(service.getSOInterfaceConfiguration(visitor.getId()).getDefaultLanguage()));
   logout();
   cmpResources.discardPersistentFieldChanges();
   if (_request.getSession() != null) _request.getSession().invalidate();
   return Login.class;
 }
Beispiel #12
0
  /**
   * Event method in order to get the datas to display.
   *
   * @throws IOException
   */
  @OnEvent(value = JQueryEventConstants.DATA)
  JSONObject onData() throws IOException {
    /**
     * If ajax mode, we filter on server-side, otherwise, we filter from the available data already
     * loaded (see DefaultDataTableModel#filterData)
     */
    if (getMode()) {
      /** Give a chance to the developer to update the GridDataSource to filter data server-side */
      resources.triggerEvent(JQueryEventConstants.FILTER_DATA, null, null);
      /** Give a chance to the developer to sort the GridDataSource server-side */
      resources.triggerEvent(JQueryEventConstants.SORT_DATA, null, null);
    }

    return getDataTModel()
        .sendResponse(
            request, getSource(), getDataModel(), getSortModel(), getOverrides(), getMode());
  }
Beispiel #13
0
  /** This method will construct the JSON options and call the DataTable contructor */
  @AfterRender
  void setJS() {

    JSONObject setup = new JSONObject();

    setup.put("id", getClientId());

    JSONObject dataTableParams = new JSONObject();

    if (getMode()) {
      dataTableParams.put("sAjaxSource", resources.createEventLink("data").toAbsoluteURI());
      dataTableParams.put("bServerSide", "true");
      dataTableParams.put("bProcessing", "true");
    }

    dataTableParams.put("sPaginationType", "full_numbers");

    dataTableParams.put("iDisplayLength", getRowsPerPage());

    dataTableParams.put(
        "aLengthMenu",
        new JSONLiteral(
            "[["
                + getRowsPerPage()
                + ","
                + (getRowsPerPage() * 2)
                + ","
                + (getRowsPerPage() * 4)
                + "],["
                + getRowsPerPage()
                + ","
                + (getRowsPerPage() * 2)
                + ","
                + (getRowsPerPage() * 4)
                + "]]"));

    // We set the bSortable parameters for each column. Cf :
    // http://www.datatables.net/usage/columns
    // We set also the mDataProp parameters to handle ColReorder plugin. Cf
    // :
    // http://datatables.net/release-datatables/extras/ColReorder/server_side.html
    JSONArray columnConfs = new JSONArray();
    for (String propertyName : getPropertyNames()) {
      JSONObject confs = new JSONObject();
      confs.put("mDataProp", propertyName);
      confs.put("bSortable", getModel().get(propertyName).isSortable());
      columnConfs.put(confs);
    }

    dataTableParams.put("aoColumns", columnConfs);

    dataTableParams.put("oLanguage", setI18NMessages());

    JQueryUtils.merge(dataTableParams, getOptions());
    setup.put("params", dataTableParams);

    support.addInitializerCall("dataTable", setup);
  }
  @SetupRender
  final void setup() {
    // Often, these controlName and clientId will end up as the same value. There are many
    // exceptions, including a form that renders inside a loop, or a form inside a component
    // that is used multiple times.

    if (formSupport == null)
      throw new RuntimeException(
          String.format(
              "Component %s must be enclosed by a Form component.", resources.getCompleteId()));

    assignedClientId = allocateClientId();

    String controlName = formSupport.allocateControlName(resources.getId());

    formSupport.storeAndExecute(this, new Setup(controlName));
    formSupport.store(this, PROCESS_SUBMISSION_ACTION);
  }
  public BeanModel getMyModel() {
    BeanModel myModel =
        _beanModelSource.createDisplayModel(User.class, _componentResources.getMessages());

    myModel.include("firstName", "lastName");
    myModel.get("firstName").sortable(false);
    myModel.get("lastName").label("Surname");
    return myModel;
  }
Beispiel #16
0
 @BeginRender
 void beginRender(MarkupWriter writer) {
   if (checked) {
     writer.element("input", "type", "checkbox", "checked", "checked");
   } else {
     writer.element("input", "type", "checkbox");
   }
   resources.renderInformalParameters(writer);
   writer.end();
 }
Beispiel #17
0
 boolean onFailureFromCreateForm() {
   // Rather than letting "failure" bubble up which doesn't say what you
   // were trying to do, we trigger new event
   // "failedCreate". It will bubble up because we don't have a handler
   // method for it.
   componentResources.triggerEvent(FAILED_CREATE, null, null);
   // We don't want "failure" to bubble up, so we return true to say we've
   // handled it.
   return true;
 }
Beispiel #18
0
  void setupRender() {

    if (_myModel == null) {
      _myModel = _beanModelSource.createDisplayModel(User.class, _componentResources.getMessages());
      _myModel.add("action", null);
      _myModel.include("firstName", "lastName", "action");
      _myModel.get("firstName").sortable(false);
      _myModel.get("lastName").label("Surname");
    }
    users = createUsers(50);
  }
Beispiel #19
0
  boolean onFailureFromUpdateForm() {
    versionFlash = course.getVersion();

    // Rather than letting "failure" bubble up which doesn't say what you
    // were trying to do, we trigger new event
    // "failedUpdate". It will bubble up because we don't have a handler
    // method for it.
    componentResources.triggerEvent(FAILED_UPDATE, new Object[] {courseUuid}, null);
    // We don't want "failure" to bubble up, so we return true to say we've
    // handled it.
    return true;
  }
Beispiel #20
0
  boolean onSuccessFromUpdateForm() {
    // We want to tell our containing page explicitly what course we've
    // updated, so we trigger new event
    // "successfulUpdate" with a parameter. It will bubble up because we
    // don't have a handler method for it.
    componentResources.triggerEvent(SUCCESSFUL_UPDATE, new Object[] {courseUuid}, null);

    // We don't want "success" to bubble up, so we return true to say we've
    // handled it.
    mode = Mode.REVIEW;
    return true;
  }
Beispiel #21
0
  boolean beginRender(MarkupWriter writer) {
    clientId = javaScriptSupport.allocateClientId(resources);

    if (storage != null) {
      List<Alert> alerts = storage.getAlerts();
      if (!alerts.isEmpty()) {
        for (Alert alert : alerts) {

          String alertType = alert.severity.name().toLowerCase();
          String css = alertType;
          if ("info".equals(alertType)) {
            css = "success";
          }
          css = "alert-" + css;

          writer.element("div", "id", clientId, "class", "alert " + css);
          {
            resources.renderInformalParameters(writer);

            String dismiss = resources.createEventLink("dismiss", alert.id).toURI();
            if (alert.duration.persistent) {
              writer.element("a", "href", dismiss, "class", "close");

            } else {
              writer.element("a", "href", "#", "class", "close", "data-dismiss", "alert");
            }
            writer.write(dismissText);
            writer.end();

            writer.write(alert.message);
          }
          writer.end();
        }
      }
      storage.dismissNonPersistent();
    }

    return false;
  }
  private Asset getComponentAsset(
      ComponentResources resources, String expandedPath, Resource metaResource) {

    if (expandedPath.contains(":") || expandedPath.startsWith("/")) {
      return getAssetInLocale(resources.getBaseResource(), expandedPath, resources.getLocale());
    }

    // So, it's relative to the component.  First, check if there's a match using the 5.4 rules.

    if (metaResource.exists()) {
      return getAssetForResource(metaResource);
    }

    Resource oldStyle =
        findLocalizedResource(resources.getBaseResource(), expandedPath, resources.getLocale());

    if (oldStyle == null || !oldStyle.exists()) {
      return null;
    }

    return getAssetForResource(oldStyle);
  }
Beispiel #23
0
  private StringBuilder transformHTML(
      String snippetHTML,
      String basedir,
      List<String> srcPaths,
      ComponentResources resources,
      String urlParam) {
    StringBuilder sb = new StringBuilder((int) (snippetHTML.length() * 0.5));

    int start = 0;
    String path = null;

    Matcher m = p.matcher(snippetHTML);

    while (m.find()) {
      sb.append(snippetHTML, start, m.start());
      sb.append(m.group(1));
      sb.append("=\"");
      try {
        if (m.group(2).indexOf(ComponentConstants.THEME_IMG_DIR) != -1) {
          path = m.group(2);
        } else if (!(m.group(1).equals("href")
                && (m.group(2).startsWith("#") || m.group(2).startsWith("http")))
            && m.group(2).indexOf(asm.get(ChoosenTheme.class).getDir()) == -1
            && !m.group(2).contains("/assets/")
            && !m.group(2).contains(ComponentConstants.SRC_EVENT)) {

          String img = basedir + ComponentConstants.RESOURCES_DIR + File.separator + m.group(2);

          srcPaths.add(img);

          path =
              resources
                  .createEventLink(ComponentConstants.SRC_EVENT, (srcPaths.size() - 1))
                  .toURI();

        } else path = m.group(2);

      } catch (Exception e) {
        path = m.group(2);
      } finally {
        sb.append(path);
      }

      sb.append('"');
      start = m.end();
    }
    sb.append(snippetHTML, start, snippetHTML.length());

    return sb;
  }
Beispiel #24
0
  void beginRender(MarkupWriter writer) {
    writer.element("select", "name", getControlName(), "id", getClientId());

    putPropertyNameIntoBeanValidationContext("value");

    validate.render(writer);

    removePropertyNameFromBeanValidationContext();

    resources.renderInformalParameters(writer);

    decorateInsideField();

    // Disabled is via a mixin

    if (this.zone != null) {
      Link link = resources.createEventLink(CHANGE_EVENT);

      JSONObject spec =
          new JSONObject("selectId", getClientId(), "zoneId", zone, "url", link.toURI());

      javascriptSupport.addInitializerCall("linkSelectToZone", spec);
    }
  }
Beispiel #25
0
  private void sortAndsendEvent(String propertyName) {
    List<T> listToSort = sorterPersist.getListToSort();

    if (null != sorterPersist.getComparator(propertyName)) {
      Collections.sort(listToSort, sorterPersist.getComparator(propertyName));
    }

    if (Order.DESC.equals(sorterPersist.getOrder(propertyName))) {
      Collections.reverse(listToSort);
    }

    componentResources
        .getContainer()
        .getComponentResources()
        .triggerEvent(eventName, new Object[] {listToSort}, null);
  }
Beispiel #26
0
  /** FILTER: remote control for advanced file search (open the widjet) */
  public void onActionFromToggleAdvancedSearch() {
    advancedSearchMode = !advancedSearchMode;

    Object[] ob = {advancedSearchMode};

    // componentResources.getContainer().getComponentResources().triggerEvent("eventToggleAdvancedSearchFromListDocument",	ob, null);

    // sorter component MUST BE a component of a list of document
    // we want to call the parent of list of document (index)
    componentResources
        .getContainer()
        .getComponentResources()
        .getContainer()
        .getComponentResources()
        .triggerEvent("eventToggleAdvancedSearchSorterComponent", ob, null);
  }
  @OnEvent(component = "uploadFile", value = JQueryEventConstants.NON_XHR_UPLOAD)
  Object onNonXHRUploadFile(UploadedFileItem uploadedFile) {

    logger.info(" >>> onNonXHRUploadFile");

    if (uploadedFile != null) {
      this.uploadedFiles.add(uploadedFile);
    }

    final JSONObject result = new JSONObject();
    final JSONObject params =
        new JSONObject()
            .put("url", resources.createEventLink("myCustomEvent", "NON_XHR_UPLOAD").toURI())
            .put("zoneId", "uploadResult");

    result.put(AjaxUpload.UPDATE_ZONE_CALLBACK, params);
    return result;
  }
  boolean beforeRenderBody() throws ClassNotFoundException {
    Method method = null;

    Class<?> pageClass = componentResources.getPage().getClass();
    for (Method m : pageClass.getDeclaredMethods()) {
      if (m.getName().toLowerCase().equals("on" + event.toLowerCase())) {
        method = m;
        break;
      }
      OnEvent event = m.getAnnotation(OnEvent.class);
      if (event != null) {
        if (event.value().equals(event)) {
          method = m;
          break;
        }
      }
    }
    if (method == null) {
      return true;
    }

    return objectSecurityService.hasAccess(method);
  }
Beispiel #29
0
 Object onActionFromCancel() throws ValidationException {
   cmpResources.discardPersistentFieldChanges();
   return SearchCustomer.class;
 }
Beispiel #30
0
 Object onActionFromFinish() throws RemoteException {
   customer.setContacts(contacts.toArray(new Contact[contacts.size()]));
   service.updateContact(customer);
   cmpResources.discardPersistentFieldChanges();
   return SearchCustomer.class;
 }