@RequestMapping("/dbuilder/getFilterTemplate")
  public String getBuilderFilterTemplate(ModelMap model, @RequestParam("json") String json)
      throws Exception {
    Map<String, Object> obj = PropertyUtil.getPropertiesValueFromJson(json);
    DataListFilter filter = new DataListFilter();
    filter.setLabel(obj.get("label").toString());
    filter.setName(obj.get("name").toString());
    if (obj.get("operator") != null) {
      filter.setOperator(obj.get("operator").toString());
    }
    if (obj.get("type") != null) {
      Map typeMap = (Map) obj.get("type");
      DataListFilterType type =
          (DataListFilterType) pluginManager.getPlugin(typeMap.get("className").toString());
      if (type != null) {
        if (!"{}".equals(typeMap.get("properties"))) {
          type.setProperties((Map) typeMap.get("properties"));
        }
        filter.setType(type);
      }
    }

    model.addAttribute(
        "template",
        filter.getType().getTemplate(new DataList(), filter.getName(), filter.getLabel()));
    return "dbuilder/filterTmplate";
  }
Beispiel #2
0
 /**
  * Reads a resource from a plugin. java.util.Formatter text patterns supported.
  *
  * @param pluginName
  * @param resourceUrl
  * @param arguments
  * @param removeNewLines
  * @param translationFileName
  * @return null if the resource is not found or in the case of an exception
  * @see java.util.Formatter
  */
 public static String readPluginResource(
     String pluginName,
     String resourceUrl,
     Object[] arguments,
     boolean removeNewLines,
     String translationFileName) {
   String output = null;
   if (pluginName != null && resourceUrl != null) {
     PluginManager pluginManager = (PluginManager) appContext.getBean("pluginManager");
     output =
         pluginManager.readPluginResourceAsString(
             pluginName, resourceUrl, arguments, removeNewLines, translationFileName);
   }
   // replace app path
   if (output != null && !output.isEmpty()) {
     String appPath = "";
     AppDefinition appDef = AppUtil.getCurrentAppDefinition();
     if (appDef != null) {
       appPath = "/" + appDef.getAppId() + "/" + appDef.getVersion();
     }
     output = output.replaceAll("\\[APP_PATH\\]", appPath);
   }
   return output;
 }
  @RequestMapping("/console/app/(*:appId)/(~:version)/form/builder/(*:formId)")
  public String formBuilder(
      ModelMap model,
      @RequestParam("appId") String appId,
      @RequestParam(value = "version", required = false) String version,
      @RequestParam("formId") String formId,
      @RequestParam(required = false) String json) {
    // verify app version
    ConsoleWebPlugin consoleWebPlugin =
        (ConsoleWebPlugin) pluginManager.getPlugin(ConsoleWebPlugin.class.getName());
    String page = consoleWebPlugin.verifyAppVersion(appId, version);
    if (page != null) {
      return page;
    }

    // set flag in request
    FormUtil.setFormBuilderActive(true);

    // load form definition
    model.addAttribute("appId", appId);
    AppDefinition appDef = appService.getAppDefinition(appId, version);
    FormDefinition formDef = null;
    if (appDef == null) {
      // TODO: handle invalid app
    } else {
      model.addAttribute("appDefinition", appDef);
      formDef = formDefinitionDao.loadById(formId, appDef);
    }

    if (formDef != null) {
      String formJson = null;
      if (json != null && !json.trim().isEmpty()) {
        // read custom JSON from request
        formJson = json;
      } else {
        // get JSON from form definition
        formJson = formDef.getJson();
      }
      if (formJson != null && formJson.trim().length() > 0) {
        String processedformJson = PropertyUtil.propertiesJsonLoadProcessing(formJson);

        try {
          FormUtil.setProcessedFormJson(processedformJson);
          String elementHtml = formService.previewElement(formJson);
          model.addAttribute("elementHtml", elementHtml);
          model.addAttribute("elementJson", processedformJson);
        } finally {
          FormUtil.clearProcessedFormJson();
        }
      } else {
        // default empty form
        String tableName = formDef.getTableName();
        if (tableName == null || tableName.isEmpty()) {
          tableName = formDef.getId();
        }
        String escapedFormName = StringEscapeUtils.escapeJavaScript(formDef.getName());
        String defaultJson =
            "{className: 'org.joget.apps.form.model.Form',  \"properties\":{ \"id\":\""
                + formId
                + "\", \"name\":\""
                + escapedFormName
                + "\", \"tableName\":\""
                + tableName
                + "\", \"loadBinder\":{ \"className\":\"org.joget.apps.form.lib.WorkflowFormBinder\" }, \"storeBinder\":{ \"className\":\"org.joget.apps.form.lib.WorkflowFormBinder\" } }}";
        String formHtml = formService.previewElement(defaultJson);
        model.addAttribute("elementHtml", formHtml);
      }
    } else {
      // default empty form
      String formJson =
          "{className: 'org.joget.apps.form.model.Form',  \"properties\":{ \"id\":\""
              + formId
              + "\", \"name\":\"\" \"loadBinder\":{ \"className\":\"org.joget.apps.form.lib.WorkflowFormBinder\" }, \"storeBinder\":{ \"className\":\"org.joget.apps.form.lib.WorkflowFormBinder\" } }}";
      String formHtml = formService.previewElement(formJson);
      model.addAttribute("elementHtml", formHtml);
    }

    // add palette
    model.addAttribute("palette", formBuilderPalette);

    // add form def id
    model.addAttribute("formId", formId);
    model.addAttribute("formDef", formDef);

    return "fbuilder/formBuilder";
  }
  @RequestMapping("/form/embed")
  public String embedForm(
      ModelMap model,
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam("_submitButtonLabel") String buttonLabel,
      @RequestParam("_json") String json,
      @RequestParam("_callback") String callback,
      @RequestParam("_setting") String callbackSetting,
      @RequestParam(required = false) String id,
      @RequestParam(value = "_a", required = false) String action)
      throws JSONException, UnsupportedEncodingException {
    FormData formData = new FormData();
    if (id != null && !id.isEmpty()) {
      formData.setPrimaryKeyValue(id);
    }
    Form form = formService.loadFormFromJson(json, formData);

    AppDefinition appDef = AppUtil.getCurrentAppDefinition();
    String appId = "";
    String appVersion = "";
    if (appDef != null) {
      appId = appDef.getAppId();
      appVersion = appDef.getVersion().toString();
    }
    String nonce = request.getParameter("_nonce");
    if (form == null
        || !SecurityUtil.verifyNonce(
            nonce,
            new String[] {"EmbedForm", appId, appVersion, form.getPropertyString("id"), nonce})) {
      response.setStatus(HttpServletResponse.SC_FORBIDDEN);
      return null;
    }

    if (callbackSetting == null || (callbackSetting != null && callbackSetting.isEmpty())) {
      callbackSetting = "{}";
    }

    form.setProperty(
        "url",
        "?_nonce="
            + URLEncoder.encode(nonce, "UTF-8")
            + "&_a=submit&_callback="
            + callback
            + "&_setting="
            + StringEscapeUtils.escapeHtml(callbackSetting)
            + "&_submitButtonLabel="
            + StringEscapeUtils.escapeHtml(buttonLabel));

    if (form != null) {
      // if id field not exist, automatically add an id hidden field
      Element idElement = FormUtil.findElement(FormUtil.PROPERTY_ID, form, formData);
      if (idElement == null) {
        Collection<Element> formElements = form.getChildren();
        idElement = new HiddenField();
        idElement.setProperty(FormUtil.PROPERTY_ID, FormUtil.PROPERTY_ID);
        idElement.setParent(form);
        formElements.add(idElement);
      }

      // create new section for buttons
      Section section = new Section();
      section.setProperty(FormUtil.PROPERTY_ID, "section-actions");
      Collection<Element> sectionChildren = new ArrayList<Element>();
      section.setChildren(sectionChildren);
      Collection<Element> formChildren = form.getChildren(formData);
      if (formChildren == null) {
        formChildren = new ArrayList<Element>();
      }
      formChildren.add(section);

      // add new horizontal column to section
      Column column = new Column();
      column.setProperty("horizontal", "true");
      Collection<Element> columnChildren = new ArrayList<Element>();
      column.setChildren(columnChildren);
      sectionChildren.add(column);

      Element hiddenField = (Element) pluginManager.getPlugin(HiddenField.class.getName());
      hiddenField.setProperty(FormUtil.PROPERTY_ID, "_json");
      hiddenField.setProperty(FormUtil.PROPERTY_VALUE, json);
      columnChildren.add((Element) hiddenField);

      Element submitButton = (Element) pluginManager.getPlugin(SubmitButton.class.getName());
      submitButton.setProperty(FormUtil.PROPERTY_ID, "submit");
      submitButton.setProperty("label", buttonLabel);
      columnChildren.add((Element) submitButton);
    }

    // generate form HTML
    String formHtml = null;

    if ("submit".equals(action)) {
      formData = formService.retrieveFormDataFromRequest(formData, request);
      formData = formService.executeFormActions(form, formData);

      // check for validation errors
      Map<String, String> errors = formData.getFormErrors();
      int errorCount = 0;
      if (!formData.getStay() && (errors == null || errors.isEmpty())) {
        // render normal template
        formHtml = formService.generateElementHtml(form, formData);

        // convert submitted
        JSONObject jsonResult = new JSONObject();

        // get binder of main form
        FormStoreBinder mainBinder = form.getStoreBinder();
        FormRowSet rows = formData.getStoreBinderData(mainBinder);

        for (FormRow row : rows) {
          for (Object o : row.keySet()) {
            jsonResult.accumulate(o.toString(), row.get(o));
          }
          Map<String, String> tempFilePathMap = row.getTempFilePathMap();
          if (tempFilePathMap != null && !tempFilePathMap.isEmpty()) {
            jsonResult.put(FormUtil.PROPERTY_TEMP_FILE_PATH, tempFilePathMap);
          }
        }

        model.addAttribute("jsonResult", StringEscapeUtils.escapeJavaScript(jsonResult.toString()));
      } else {
        // render error template
        formHtml = formService.generateElementErrorHtml(form, formData);
        errorCount = errors.size();
      }

      model.addAttribute("setting", callbackSetting);
      model.addAttribute("callback", callback);
      model.addAttribute("submitted", Boolean.TRUE);
      model.addAttribute("errorCount", errorCount);
      model.addAttribute("stay", formData.getStay());
    } else {
      formHtml = formService.retrieveFormHtml(form, formData);
    }

    model.addAttribute("formHtml", formHtml);

    if (request.getParameter("_mapp") != null) {
      response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
      response.setHeader("Access-Control-Allow-Credentials", "true");
      response.setHeader("Content-type", "application/xml");

      return "mapp/embedForm";
    } else {
      return "fbuilder/embedForm";
    }
  }
Beispiel #5
0
  public static String processHashVariable(
      String content,
      WorkflowAssignment wfAssignment,
      String escapeFormat,
      Map<String, String> replaceMap,
      AppDefinition appDef) {
    // check for hash # to avoid unnecessary processing
    if (!containsHashVariable(content)) {
      return content;
    }

    // parse content
    if (content != null) {
      Pattern pattern = Pattern.compile("\\#([^#^\"^ ])*\\.([^#^\"])*\\#");
      Matcher matcher = pattern.matcher(content);
      List<String> varList = new ArrayList<String>();
      while (matcher.find()) {
        varList.add(matcher.group());
      }

      try {
        if (!varList.isEmpty()) {
          PluginManager pluginManager = (PluginManager) appContext.getBean("pluginManager");
          PluginDefaultPropertiesDao pluginDefaultPropertiesDao =
              (PluginDefaultPropertiesDao) appContext.getBean("pluginDefaultPropertiesDao");
          Collection<Plugin> pluginList = pluginManager.list(HashVariablePlugin.class);
          Map<String, HashVariablePlugin> hashVariablePluginCache =
              new HashMap<String, HashVariablePlugin>();

          for (String var : varList) {
            String tempVar = var.replaceAll("#", "");

            for (Plugin p : pluginList) {
              HashVariablePlugin hashVariablePlugin = (HashVariablePlugin) p;
              if (tempVar.startsWith(hashVariablePlugin.getPrefix() + ".")) {
                tempVar = tempVar.replaceFirst(hashVariablePlugin.getPrefix() + ".", "");

                HashVariablePlugin cachedPlugin =
                    hashVariablePluginCache.get(hashVariablePlugin.getClassName());
                if (cachedPlugin == null) {
                  cachedPlugin =
                      (HashVariablePlugin)
                          pluginManager.getPlugin(hashVariablePlugin.getClassName());
                  // get default plugin properties

                  if (appDef == null) {
                    appDef = AppUtil.getCurrentAppDefinition();
                  }
                  PluginDefaultProperties pluginDefaultProperties =
                      pluginDefaultPropertiesDao.loadById(cachedPlugin.getClassName(), appDef);
                  if (pluginDefaultProperties != null
                      && pluginDefaultProperties.getPluginProperties() != null
                      && pluginDefaultProperties.getPluginProperties().trim().length() > 0) {
                    cachedPlugin.setProperties(
                        PropertyUtil.getPropertiesValueFromJson(
                            pluginDefaultProperties.getPluginProperties()));
                  }

                  // put appDef & wfAssignment to properties
                  cachedPlugin.setProperty("appDefinition", appDef);
                  cachedPlugin.setProperty("workflowAssignment", wfAssignment);
                  hashVariablePluginCache.put(hashVariablePlugin.getClassName(), cachedPlugin);
                }

                // process nested hash
                while (tempVar.contains("{") && tempVar.contains("}")) {
                  Pattern nestedPattern = Pattern.compile("\\{([^\\{^\\}])*\\}");
                  Matcher nestedMatcher = nestedPattern.matcher(tempVar);
                  while (nestedMatcher.find()) {
                    String nestedHash = nestedMatcher.group();
                    String nestedHashString = nestedHash.replace("{", "#");
                    nestedHashString = nestedHashString.replace("}", "#");

                    String processedNestedHashValue =
                        processHashVariable(
                            nestedHashString, wfAssignment, escapeFormat, replaceMap, appDef);
                    tempVar =
                        tempVar.replaceAll(
                            StringUtil.escapeString(nestedHash, StringUtil.TYPE_REGEX, null),
                            StringUtil.escapeString(
                                processedNestedHashValue, escapeFormat, replaceMap));
                  }
                }

                // get result from plugin
                String value = cachedPlugin.processHashVariable(tempVar);

                if (value != null && !StringUtil.TYPE_REGEX.equals(escapeFormat)) {
                  value = StringUtil.escapeRegex(value);
                }

                // escape special char in HashVariable
                var = cachedPlugin.escapeHashVariable(var);

                // replace
                if (value != null) {
                  content =
                      content.replaceAll(
                          var, StringUtil.escapeString(value, escapeFormat, replaceMap));
                }
              }
            }
          }
        }
      } catch (Exception ex) {
        LogUtil.error(AppUtil.class.getName(), ex, "");
      }
    }
    return content;
  }