Java 类freemarker.template.TemplateBooleanModel 实例源码

项目:Equella    文件:ButtonListDirective.java   
@Override
@SuppressWarnings("nls")
protected TagRenderer createTagRenderer(HtmlMutableListState state, Environment env, Map<?, ?> params,
    TemplateDirectiveBody body, TemplateModel[] loopVars) throws TemplateModelException
{
    String tag = "div";
    if( params.containsKey("tag") )
    {
        tag = ((SimpleScalar) params.get("tag")).getAsString();
    }

    boolean hideDisabledOptions = false;
    if( params.containsKey("hideDisabledOptions") )
    {
        hideDisabledOptions = ((TemplateBooleanModel) params.get("hideDisabledOptions")).getAsBoolean();
    }

    return new ButtonListTagRenderer(tag, (HtmlListState) state, env, body, loopVars, hideDisabledOptions);
}
项目:scipio-erp    文件:TransformUtil.java   
/**
 * Gets boolean arg.
 * <p>
 * Will automatically interpret string true/false as boolean.
 */
public static Boolean getBooleanArg(TemplateModel obj, Boolean defaultValue) throws TemplateModelException {
    if (obj instanceof TemplateBooleanModel) {
        return ((TemplateBooleanModel) obj).getAsBoolean();
    }
    else if (obj instanceof TemplateScalarModel) {
        TemplateScalarModel s = (TemplateScalarModel) obj;
        String val = s.getAsString();
        // SCIPIO: empty check is desirable and makes it so caller can request default by specifying ""
        if (!val.isEmpty()) {
            return "true".equalsIgnoreCase(s.getAsString());
        }
    } else if (obj != null) {
        throw new TemplateModelException("Expected boolean model or string model representation of boolean, but got a " +
                obj.getClass() + " instead");
    }
    return defaultValue;
}
项目:scipio-erp    文件:TransformUtil.java   
public static Object getBooleanOrStringArg(TemplateModel obj, Object defaultValue, boolean useDefaultWhenEmpty, boolean nonEscaping) throws TemplateModelException {
    Object result = null;
    if (obj instanceof TemplateBooleanModel) {
        return ((TemplateBooleanModel) obj).getAsBoolean();
    } else if (obj instanceof TemplateScalarModel) {
        TemplateScalarModel s = (TemplateScalarModel) obj;
        result = LangFtlUtil.getAsString(s, nonEscaping);
    } else if (obj != null) {
        result = obj.toString();
    } else {
        return defaultValue;
    }
    if (useDefaultWhenEmpty && (result instanceof String) && ((String) result).isEmpty()) {
        return defaultValue;
    }
    return result;
}
项目:tern    文件:Directives.java   
public static boolean getBoolParam(final Environment env,Map params,String key,boolean def) throws TemplateException
{
    final TemplateModel tv = (TemplateModel)params.get(key);
    if(tv == null) 
    {
        return def;
    }

    if(tv instanceof TemplateBooleanModel)
    {
        return ((TemplateBooleanModel)tv).getAsBoolean();
           //throw new TemplateException(
           //       String.format("Expected a boolean model. '%s' is instead %s", key,tv.getClass().getName()) 
           //        , env);
       }

    return Convert.parseBool(tv.toString());
}
项目:ccshop    文件:TextShowMethod.java   
@Override
public Object exec(List<Object> args) throws Exception {
    if (args != null && !args.isEmpty()) {
        Object value = args.get(0);
        if (value != null) {
            if (value instanceof TemplateModel) {
                if (value instanceof TemplateBooleanModel) {
                    return String.valueOf(((TemplateBooleanModel) value).getAsBoolean());
                }
            } else if (value instanceof Enum) {
            }
            return value.toString();
        }
    }
    return "";
}
项目:jeecms6    文件:DirectiveUtils.java   
public static Boolean getBool(String name, Map<String, TemplateModel> params)
        throws TemplateException {
    TemplateModel model = params.get(name);
    if (model == null) {
        return null;
    }
    if (model instanceof TemplateBooleanModel) {
        return ((TemplateBooleanModel) model).getAsBoolean();
    } else if (model instanceof TemplateNumberModel) {
        return !(((TemplateNumberModel) model).getAsNumber().intValue() == 0);
    } else if (model instanceof TemplateScalarModel) {
        String s = ((TemplateScalarModel) model).getAsString();
        // 空串应该返回null还是true呢?
        if (!StringUtils.isBlank(s)) {
            return !(s.equals("0") || s.equalsIgnoreCase("false") || s
                    .equalsIgnoreCase("f"));
        } else {
            return null;
        }
    } else {
        throw new MustBooleanException(name);
    }
}
项目:haloDao-Hibernate3    文件:DirectiveUtils.java   
public static Boolean getBool(String name, Map<String, TemplateModel> params)
        throws TemplateException {
    TemplateModel model = params.get(name);
    if (model == null) {
        return null;
    }
    if (model instanceof TemplateBooleanModel) {
        return ((TemplateBooleanModel) model).getAsBoolean();
    } else if (model instanceof TemplateNumberModel) {
        return !(((TemplateNumberModel) model).getAsNumber().intValue() == 0);
    } else if (model instanceof TemplateScalarModel) {
        String s = ((TemplateScalarModel) model).getAsString();
        // 空串应该返回null还是true呢?
        if (!StringUtils.isBlank(s)) {
            return !(s.equals("0") || s.equalsIgnoreCase("false") || s
                    .equalsIgnoreCase("f"));
        } else {
            return null;
        }
    } else {
        throw new MustBooleanException(name);
    }
}
项目:SelfSoftShop    文件:DirectiveUtil.java   
/**
 * 获取Boolean类型的参数值
 * 
 * @return 参数值
 */
public static Boolean getBooleanParameter(String name, Map<String, TemplateModel> params) throws TemplateModelException {
    TemplateModel templateModel = params.get(name);
    if (templateModel == null) {
        return null;
    }
    if (templateModel instanceof TemplateScalarModel) {
        String value = ((TemplateScalarModel) templateModel).getAsString();
        if (StringUtils.isEmpty(value)) {
            return null;
        } else {
            return Boolean.valueOf(value);
        }
    } else if ((templateModel instanceof TemplateBooleanModel)) {
        return ((TemplateBooleanModel) templateModel).getAsBoolean();
    } else {
        throw new TemplateModelException("The \"" + name + "\" parameter " + "must be a boolean.");
    }
}
项目:appleframework    文件:DirectiveUtil.java   
/**
 * 获取Boolean类型的参数值
 * 
 * @return 参数值
 */
public static Boolean getBooleanParameter(String name, Map<String, TemplateModel> params) throws TemplateModelException {
    TemplateModel templateModel = params.get(name);
    if (templateModel == null) {
        return null;
    }
    if (templateModel instanceof TemplateScalarModel) {
        String value = ((TemplateScalarModel) templateModel).getAsString();
        if (StringUtils.isEmpty(value)) {
            return null;
        } else {
            return Boolean.valueOf(value);
        }
    } else if ((templateModel instanceof TemplateBooleanModel)) {
        return ((TemplateBooleanModel) templateModel).getAsBoolean();
    } else {
        throw new TemplateModelException("The \"" + name + "\" parameter " + "must be a boolean.");
    }
}
项目:Lottery    文件:DirectiveUtils.java   
public static Boolean getBool(String name, Map<String, TemplateModel> params)
        throws TemplateException {
    TemplateModel model = params.get(name);
    if (model == null) {
        return null;
    }
    if (model instanceof TemplateBooleanModel) {
        return ((TemplateBooleanModel) model).getAsBoolean();
    } else if (model instanceof TemplateNumberModel) {
        return !(((TemplateNumberModel) model).getAsNumber().intValue() == 0);
    } else if (model instanceof TemplateScalarModel) {
        String s = ((TemplateScalarModel) model).getAsString();
        // 空串应该返回null还是true呢?
        if (!StringUtils.isBlank(s)) {
            return !(s.equals("0") || s.equalsIgnoreCase("false") || s
                    .equalsIgnoreCase("f"));
        } else {
            return null;
        }
    } else {
        throw new MustBooleanException(name);
    }
}
项目:scipio-erp    文件:MultiVarMethod.java   
@SuppressWarnings("unchecked")
static Collection<String> getAsRawSequence(TemplateModel elems) throws TemplateModelException {
    if (elems == null || elems instanceof TemplateBooleanModel) {
        return Collections.emptyList();
    } else if (elems instanceof TemplateCollectionModel || elems instanceof TemplateSequenceModel) {
        return (Collection<String>) LangFtlUtil.unwrapAlways(elems);
    } else if (elems instanceof TemplateHashModelEx) {
        return (Collection<String>) LangFtlUtil.getMapKeys(elems);
    } else {
        throw new TemplateModelException("invalid parameter type, can't interpret as sequence: " + elems.getClass());
    }
}
项目:scipio-erp    文件:TemplateFtlUtil.java   
public static String escapeVal(String value, String lang, Boolean strict, Environment env) throws TemplateModelException {
    if (value == null || value.isEmpty() || lang == null || lang.isEmpty()) {
        return value;
    }
    if (strict != null) {
        return execEscapeValFunction(new SimpleScalar(value), new SimpleScalar(lang), 
                strict ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE, env).getAsString();
    } else {
        return execEscapeValFunction(new SimpleScalar(value), new SimpleScalar(lang), env).getAsString();
    }
}
项目:scipio-erp    文件:TemplateFtlUtil.java   
public static String escapeFullUrl(String value, String lang, Boolean strict, Environment env) throws TemplateModelException {
    if (value == null || value.isEmpty() || lang == null || lang.isEmpty()) {
        return value;
    }
    if (strict != null) {
        return execEscapeFullUrlFunction(new SimpleScalar(value), new SimpleScalar(lang), 
                strict ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE, env).getAsString();
    } else {
        return execEscapeFullUrlFunction(new SimpleScalar(value), new SimpleScalar(lang), env).getAsString();
    }
}
项目:sonar-gitlab-plugin    文件:AbstractIssuesTemplateMethodModelEx.java   
private Object execOneArg(Object arg) throws TemplateModelException {
    if (arg instanceof TemplateScalarModel) {
        String name = ((TemplateScalarModel) arg).getAsString();
        try {
            Severity severity = Severity.valueOf(name);
            return exec(reportIssues.stream().filter(i -> isSeverityEquals(i, severity)));
        } catch (IllegalArgumentException e) {
            throw new TemplateModelException("Failed call 1 Severity arg (INFO,MINOR,MAJOR,CRITICAL,BLOCKER)", e);
        }
    } else if (arg instanceof TemplateBooleanModel) {
        boolean r = ((TemplateBooleanModel) arg).getAsBoolean();
        return exec(reportIssues.stream().filter(i -> isSameReportedOnDiff(i, r)));
    }
    throw new TemplateModelException("Failed call accept boolean or Severity");
}
项目:sonar-gitlab-plugin    文件:AbstractIssuesTemplateMethodModelEx.java   
private Object execTwoArg(Object arg1, Object arg2) throws TemplateModelException {
    if (arg1 instanceof TemplateScalarModel && arg2 instanceof TemplateBooleanModel) {
        String name = ((TemplateScalarModel) arg1).getAsString();
        boolean r = ((TemplateBooleanModel) arg2).getAsBoolean();
        try {
            Severity severity = Severity.valueOf(name);
            return exec(reportIssues.stream().filter(i -> isSeverityEquals(i, severity) && isSameReportedOnDiff(i, r)));
        } catch (IllegalArgumentException e) {
            throw new TemplateModelException("Failed call Severity arg (INFO,MINOR,MAJOR,CRITICAL,BLOCKER)", e);
        }
    }
    throw new TemplateModelException("Failed call accept 2 args boolean or Severity");
}
项目:sonar-gitlab-plugin    文件:IssuesTemplateMethodModelExTest.java   
@Test
public void testSuccess() {
    Assertions.assertThat(list(Collections.emptyList())).isEmpty();
    Assertions.assertThat(list(Collections.singletonList(new SimpleScalar("MAJOR")))).isEmpty();
    Assertions.assertThat(list(Collections.singletonList(TemplateBooleanModel.FALSE))).isEmpty();
    Assertions.assertThat(list(Arrays.asList(new SimpleScalar("MAJOR"), TemplateBooleanModel.FALSE))).isEmpty();
}
项目:sonar-gitlab-plugin    文件:IssuesTemplateMethodModelExTest.java   
@Test
public void testFailed() {
    Assertions.assertThatThrownBy(() -> list(Collections.singletonList(null))).hasCauseInstanceOf(TemplateModelException.class);
    Assertions.assertThatThrownBy(() -> list(Collections.singletonList(new SimpleScalar("TOTO")))).hasCauseInstanceOf(TemplateModelException.class);
    Assertions.assertThatThrownBy(() -> list(Arrays.asList(TemplateBooleanModel.FALSE, new SimpleScalar("MAJOR")))).hasCauseInstanceOf(TemplateModelException.class);
    Assertions.assertThatThrownBy(() -> list(Arrays.asList(new SimpleScalar("TOTO"), TemplateBooleanModel.FALSE))).hasCauseInstanceOf(TemplateModelException.class);
    Assertions.assertThatThrownBy(() -> list(Arrays.asList(new SimpleScalar("TOTO"), TemplateBooleanModel.FALSE, TemplateBooleanModel.FALSE))).hasCauseInstanceOf(TemplateModelException.class);
}
项目:sonar-gitlab-plugin    文件:IssueCountTemplateMethodModelExTest.java   
@Test
public void testSuccess() {
    Assertions.assertThat(count(Collections.emptyList())).isEqualTo(0);
    Assertions.assertThat(count(Collections.singletonList(new SimpleScalar("MAJOR")))).isEqualTo(0);
    Assertions.assertThat(count(Collections.singletonList(TemplateBooleanModel.FALSE))).isEqualTo(0);
    Assertions.assertThat(count(Arrays.asList(new SimpleScalar("MAJOR"), TemplateBooleanModel.FALSE))).isEqualTo(0);
}
项目:sonar-gitlab-plugin    文件:IssueCountTemplateMethodModelExTest.java   
@Test
public void testFailed() {
    Assertions.assertThatThrownBy(() -> count(Collections.singletonList(null))).hasCauseInstanceOf(TemplateModelException.class);
    Assertions.assertThatThrownBy(() -> count(Collections.singletonList(new SimpleScalar("TOTO")))).hasCauseInstanceOf(TemplateModelException.class);
    Assertions.assertThatThrownBy(() -> count(Arrays.asList(TemplateBooleanModel.FALSE, new SimpleScalar("MAJOR")))).hasCauseInstanceOf(TemplateModelException.class);
    Assertions.assertThatThrownBy(() -> count(Arrays.asList(new SimpleScalar("TOTO"), TemplateBooleanModel.FALSE))).hasCauseInstanceOf(TemplateModelException.class);
    Assertions.assertThatThrownBy(() -> count(Arrays.asList(new SimpleScalar("TOTO"), TemplateBooleanModel.FALSE, TemplateBooleanModel.FALSE))).hasCauseInstanceOf(TemplateModelException.class);
}
项目:freemarker-scripting    文件:MyBatisParamDirective.java   
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
    throws TemplateException, IOException {
  SimpleScalar name = (SimpleScalar) params.get("name");
  if (params.containsKey("value")) {
    Object valueObject = params.get("value");
    Object value;
    if (valueObject == null) {
      value = null;
    } else if (valueObject instanceof WrapperTemplateModel) {
      value = ((WrapperTemplateModel) valueObject).getWrappedObject();
    } else if (valueObject instanceof TemplateScalarModel) {
      value = ((TemplateScalarModel) valueObject).getAsString();
    } else if (valueObject instanceof TemplateNumberModel) {
      value = ((TemplateNumberModel) valueObject).getAsNumber();
    } else if (valueObject instanceof TemplateDateModel) {
      value = ((TemplateDateModel) valueObject).getAsDate();
    } else if (valueObject instanceof TemplateBooleanModel) {
      value = ((TemplateBooleanModel) valueObject).getAsBoolean();
    } else {
      throw new UnsupportedOperationException(
          String.format("Type %s is not supported yet in this context.", valueObject.getClass().getSimpleName()));
    }

    TemplateModel generatedParamsObject = env.getGlobalVariables().get(FreeMarkerSqlSource.GENERATED_PARAMS_KEY);
    List generatedParams;
    if (generatedParamsObject instanceof DefaultListAdapter) {
      generatedParams = (List) ((DefaultListAdapter) generatedParamsObject).getWrappedObject();
    } else {
      generatedParams = ((GeneratedParamsTemplateModel) generatedParamsObject).getGeneratedParams();
    }
    String generatedParamName = "_p" + generatedParams.size();
    env.getOut().write(String.format("#{%s}", generatedParamName));
    generatedParams.add(value);
  } else {
    env.getOut().write(String.format("#{%s}", name));
  }
}
项目:onetwo    文件:FtlUtils.java   
public static boolean getParameterByBoolean(Map<?, ?> params, String name, boolean def){
    TemplateModel attr = getParameter(params, name, false);
    if(attr!=null){
        try {
            if(TemplateBooleanModel.class.isInstance(attr)){
                return ((TemplateBooleanModel)attr).getAsBoolean();
            }else{
                return Boolean.valueOf(attr.toString());
            }
        } catch (Exception e) {
            return def;
        }
    }
    return def;
}
项目:scipio-erp    文件:FormatDateMethod.java   
@SuppressWarnings("unchecked")
@Override
public Object exec(List args) throws TemplateModelException {
    if (args == null || args.size() < 1 || args.size() > 5)
        throw new TemplateModelException("Invalid number of arguments");
    if (!(args.get(0) instanceof TemplateDateModel))
        throw new TemplateModelException("First argument is not a Date object/model");
    TemplateDateModel dateModel = ((TemplateDateModel) args.get(0));
    String dateTimeFormat = (args.size() > 1) ? LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(1))) : null;
    TemplateModel specLocaleModel = (args.size() > 2) ? ((TemplateModel) args.get(2)) : null;
    TemplateModel specTimeZoneModel = (args.size() > 3) ? ((TemplateModel) args.get(3)) : null;
    String dateType = (args.size() > 4) ? LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(4))) : null;

    Environment env = CommonFtlUtil.getCurrentEnvironment();

    Date date = dateModel.getAsDate();

    if (dateTimeFormat != null && dateTimeFormat.isEmpty()) {
        dateTimeFormat = null;
    }

    // NOTE: 2016-10-12: CANNOT pass null locale or timeZone because it causes crash.
    // warn when missing.

    Locale locale;
    if (specLocaleModel == null || specLocaleModel instanceof TemplateBooleanModel) {
        if (specLocaleModel == null || ((TemplateBooleanModel) specLocaleModel).getAsBoolean()) {
            locale = LangFtlUtil.getLocale(TransformUtil.getFtlContextGlobalVar("locale", env));
            if (locale == null) {
                locale = Locale.getDefault();
                Debug.logWarning("Scipio: formatDate(Time): locale empty (from context); using system default", module);
            }
        } else {
            locale = Locale.getDefault();
            Debug.logWarning("Scipio: formatDate(Time): locale false (from caller); using system default", module);
        }
    } else {
        locale = LangFtlUtil.getLocale(specLocaleModel);
        if (locale == null) {
            locale = Locale.getDefault();
            Debug.logWarning("Scipio: formatDate(Time): locale empty (from caller); using system default", module);
        }
    }

    TimeZone timeZone;
    if (specTimeZoneModel == null || specTimeZoneModel instanceof TemplateBooleanModel) {
        if (specTimeZoneModel == null || ((TemplateBooleanModel) specTimeZoneModel).getAsBoolean()) {
            timeZone = LangFtlUtil.getTimeZone(TransformUtil.getFtlContextGlobalVar("timeZone", env));
            if (timeZone == null) {
                timeZone = TimeZone.getDefault();
                Debug.logWarning("Scipio: formatDate(Time): timeZone empty (from context); using system default", module);
            }
        } else {
            timeZone = TimeZone.getDefault();
            Debug.logWarning("Scipio: formatDate(Time): timeZone false (from caller); using system default", module);
        }
    } else {
        timeZone = LangFtlUtil.getTimeZone(specTimeZoneModel);
        if (timeZone == null) {
            timeZone = TimeZone.getDefault();
            Debug.logWarning("Scipio: formatDate(Time): timeZone empty (from caller); using"
                    + " system default", module);
        }
    }

    Object res;
    if (dateType == null || dateType.isEmpty() || "date".equals(dateType)) { // "date" is default
        res = UtilFormatOut.formatDate(date, dateTimeFormat, locale, timeZone);
    } else if ("time".equals(dateType)) {
        res = UtilFormatOut.formatTime(date, dateTimeFormat, locale, timeZone);
    } else {
        res = UtilFormatOut.formatDateTime(date, dateTimeFormat, locale, timeZone);
    }
    return res;
}
项目:scipio-erp    文件:LangFtlUtil.java   
public static TemplateBooleanModel toBooleanModel(boolean value, Environment env) throws TemplateModelException {
    return value ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
}
项目:geeCommerce-Java-Shop-Software-and-PIM    文件:CatalogMediaAssetURLDirective.java   
@SuppressWarnings({ "rawtypes", "deprecation" })
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
    throws TemplateException, IOException {
    if (log.isTraceEnabled()) {
        log.trace(params);
    }

    SimpleNumber width = (SimpleNumber) params.get("width");
    SimpleNumber height = (SimpleNumber) params.get("height");
    SimpleScalar uri = (SimpleScalar) params.get("uri");
    SimpleScalar var = (SimpleScalar) params.get("var");
    BeanModel pSource = (BeanModel) params.get("src");
    TemplateBooleanModel pParent = (TemplateBooleanModel) params.get("parent");

    if (pSource != null && uri != null)
        throw new IllegalArgumentException("The parameters 'src' and 'uri' cannot be set at the same time.");

    if (pSource == null && uri == null)
        throw new IllegalArgumentException("You must provide either a 'src' or 'uri' parameter.");

    Product product = null;
    String uriStr = null;
    boolean fallbackToParent = false;

    if (pParent != null) {
        fallbackToParent = pParent.getAsBoolean();
    }

    if (pSource != null) {

        if (!(pSource instanceof BeanModel))
            throw new IllegalArgumentException("The parameter 'src' must be of type BeanModel (Product)");

        Object beanModel = ((BeanModel) pSource).getWrappedObject();

        if (beanModel instanceof Product) {
            product = (Product) beanModel;

            if (product.getMainImage() != null) {
                uriStr = product.getMainImage().getPath();
            }

            if (uriStr == null && product.isVariant() && fallbackToParent) {
                Product parent = product.getParent();

                if (parent != null && parent.getMainImage() != null) {
                    uriStr = parent.getMainImage().getPath();
                }
            }
        } else {
            throw new IllegalArgumentException("The source-object must be of type Product");
        }
    }

    if (uri != null || uriStr != null) {
        if (uri != null) {
            uriStr = uri.getAsString();
        }

        String varStr = null;

        if (var != null)
            varStr = var.getAsString();

        if (!Str.isEmpty(uriStr)) {
            String mediaAssetURL = catalogMediaHelper.toMediaAssetURL(uriStr,
                width == null ? null : width.getAsNumber().intValue(),
                height == null ? null : height.getAsNumber().intValue());

            if (varStr != null) {
                env.setVariable(varStr, DefaultObjectWrapper.getDefaultInstance().wrap(mediaAssetURL));
            } else {
                env.getOut().write(mediaAssetURL);
            }
        }
    }
}
项目:intellij-ce-playground    文件:FmHasDependencyMethodTest.java   
@SuppressWarnings("rawtypes")
private static void check(boolean expected, String s, Map<String, Object> paramMap) throws TemplateModelException {
  FmHasDependencyMethod method = new FmHasDependencyMethod(paramMap);
  List list = Collections.singletonList(new SimpleScalar(s));
  assertEquals(expected, ((TemplateBooleanModel)method.exec(list)).getAsBoolean());
}
项目:spring-boot-freemarker-showcase    文件:RepeatDirective.java   
public void execute(Environment env, Map params, TemplateModel[] loopVars,
                    TemplateDirectiveBody body) throws TemplateException, IOException {

    // ---------------------------------------------------------------------
    // 处理参数

    int countParam = 0;
    boolean countParamSet = false;
    boolean hrParam = false;

    Iterator paramIter = params.entrySet().iterator();
    while (paramIter.hasNext()) {
        Map.Entry ent = (Map.Entry) paramIter.next();

        String paramName = (String) ent.getKey();
        TemplateModel paramValue = (TemplateModel) ent.getValue();

        if (paramName.equals(PARAM_NAME_COUNT)) {
            if (!(paramValue instanceof TemplateNumberModel)) {
                throw new TemplateModelException("The \"" + PARAM_NAME_HR
                        + "\" parameter " + "must be a number.");
            }
            countParam = ((TemplateNumberModel) paramValue).getAsNumber()
                    .intValue();
            countParamSet = true;
            if (countParam < 0) {
                throw new TemplateModelException("The \"" + PARAM_NAME_HR
                        + "\" parameter " + "can't be negative.");
            }
        } else if (paramName.equals(PARAM_NAME_HR)) {
            if (!(paramValue instanceof TemplateBooleanModel)) {
                throw new TemplateModelException("The \"" + PARAM_NAME_HR
                        + "\" parameter " + "must be a boolean.");
            }
            hrParam = ((TemplateBooleanModel) paramValue).getAsBoolean();
        } else {
            throw new TemplateModelException("Unsupported parameter: "
                    + paramName);
        }
    }
    if (!countParamSet) {
        throw new TemplateModelException("The required \""
                + PARAM_NAME_COUNT + "\" paramter" + "is missing.");
    }

    if (loopVars.length > 1) {
        throw new TemplateModelException(
                "At most one loop variable is allowed.");
    }

    // Yeah, it was long and boring...

    // ---------------------------------------------------------------------
    // 真正开始处理输出内容

    Writer out = env.getOut();
    if (body != null) {
        for (int i = 0; i < countParam; i++) {
            // 输出  <hr> 如果 参数hr 设置为true
            if (hrParam && i != 0) {
                out.write("<hr>");
            }

            // 设置循环变量
            if (loopVars.length > 0) {
                loopVars[0] = new SimpleNumber(i + 1);
            }

            // 执行标签内容(same as <#nested> in FTL).
            body.render(env.getOut());
        }
    }
}
项目:private-freemarker    文件:CssOutputInFTLDirective.java   
/**
 * 
 */
public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars,
        TemplateDirectiveBody body) throws TemplateException, IOException {
    // Check if no parameters were given:
    if (params.isEmpty()) {
        return;
    }
    if (loopVars.length > 1) {
        throw new TemplateModelException("At most one loop variable is allowed.");
    }
    String[] cssFileArray = null;
    // 获取remote flag,如果是flag是true则读文件服务器上面的,否则读取本地服务器
    boolean remoteFlag = false;
    TemplateModel paramValue = (TemplateModel) params.get(REMOTE_FLAG);
    if (paramValue != null) {
        if (!(paramValue instanceof TemplateBooleanModel)) {
            throw new TemplateModelException("The \"" + REMOTE_FLAG
                    + "\" parameter " + "must be a boolean.");
        } else {
            remoteFlag = ((TemplateBooleanModel) paramValue).getAsBoolean();
        }
    }
    //获取css文件列表
    SimpleScalar cssValue = (SimpleScalar) params.get(CSS);
    String cssFiles = cssValue.getAsString();
    if (StringUtils.isEmpty(cssFiles)) {
        return;
    } else {
        cssFileArray = cssFiles.split(",");
    }
    // ---------------------------------------------------------------------
    // Do the actual directive execution:
    /*
     * 参考TemplateDirectiveModel的注释 <@cssOutput
     * css="css/wxsales/reset.css,css/wxsales/common.css"> ${name}
     * </@cssOutput> body != null 如果<@cssOutput/> or
     * <@cssOutput></@cssOutput> body = null
     */
    if (body != null) {}
    Writer out = env.getOut();
    out.write("<style>\n");
    if(remoteFlag){
        remoteStaticServer(cssFileArray, out);
    }else{
        localServer(cssFileArray, out);
    }
    out.write("</style>");
}
项目:private-freemarker    文件:SaicObjectWrapper.java   
@SuppressWarnings("rawtypes")
@Override
public TemplateModel wrap(Object obj) throws TemplateModelException {
       if (obj == null) {
           return super.wrap(null);
       }
       if (obj instanceof TemplateModel) {
           return (TemplateModel) obj;
       }
       if (obj instanceof String) {
           return new SimpleScalar((String) obj);
       }
       if (obj instanceof Number) {
           return new SimpleNumber((Number) obj);
       }
       if (obj instanceof java.util.Date) {
           if(obj instanceof java.sql.Date) {
               return new SimpleDate((java.sql.Date) obj);
           }
           if(obj instanceof java.sql.Time) {
               return new SimpleDate((java.sql.Time) obj);
           }
           if(obj instanceof java.sql.Timestamp) {
               return new SimpleDate((java.sql.Timestamp) obj);
           }
           return new SimpleDate((java.util.Date) obj, getDefaultDateType());
       }
       if (obj.getClass().isArray()) {
           obj = convertArray(obj);
       }
       if (obj instanceof Collection) {
           return new SimpleSequence((Collection) obj, this);
       }
       if (obj instanceof Boolean) {
           return obj.equals(Boolean.TRUE) ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
       }
       if (obj instanceof Iterator) {
           return new SimpleCollection((Iterator) obj, this);
       }
       return handleUnknownType(obj);
   }
项目:kurento-module-creator    文件:CppObjectType.java   
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException {

  Object type = arguments.get(0);

  if (type instanceof StringModel) {
    type = ((StringModel) type).getWrappedObject();
    if (type instanceof Return) {
      type = ((Return) type).getType();
    }
  }

  boolean isParam = true;
  String prefix = "";
  String suffix = "";

  if (arguments.size() > 1) {
    isParam = ((TemplateBooleanModel) arguments.get(1)).getAsBoolean();
  }

  if (arguments.size() > 2) {
    prefix = arguments.get(2).toString();
  }

  if (arguments.size() > 3) {
    suffix = arguments.get(3).toString();
  }

  if (type == null) {
    if (isParam) {
      return "void ";
    } else {
      return "void";
    }
  }

  if (type instanceof TypeRef) {
    TypeRef typeRef = (TypeRef) type;
    if (typeRef.isList()) {
      if (isParam) {
        return "const std::vector<" + getTypeAsString(typeRef.getName(), false, prefix, suffix)
            + "> &";
      } else {
        return "std::vector<" + getTypeAsString(typeRef.getName(), false, prefix, suffix) + ">";
      }
    } else if (typeRef.isMap()) {
      if (isParam) {
        return "const std::map <std::string,"
            + getTypeAsString(typeRef.getName(), false, prefix, suffix) + "> &";
      } else {
        return "std::map <std::string,"
            + getTypeAsString(typeRef.getName(), false, prefix, suffix) + ">";
      }
    } else {
      return getTypeAsString(typeRef.getName(), isParam, prefix, suffix);
    }
  }

  return getTypeAsString(type.toString(), isParam, prefix, suffix);
}
项目:kurento-module-creator    文件:JavaObjectType.java   
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException {

  Object type = arguments.get(0);

  if (type instanceof StringModel) {
    type = ((StringModel) type).getWrappedObject();
    if (type instanceof Return) {
      type = ((Return) type).getType();
    }
  }

  boolean asObject = true;
  if (arguments.size() > 1) {
    asObject = ((TemplateBooleanModel) arguments.get(1)).getAsBoolean();
  }

  if (type == null) {
    if (asObject) {
      return "Void";
    } else {
      return "void";
    }
  }

  if (type instanceof TypeRef) {
    TypeRef typeRef = (TypeRef) type;
    if (typeRef.isList()) {
      return "java.util.List<" + getTypeAsString(typeRef.getType(), true) + ">";
    } else if (typeRef.isMap()) {
      return "java.util.Map<String," + getTypeAsString(typeRef.getType(), true) + ">";
    } else {
      return getTypeAsString(typeRef.getType(), asObject);
    }
  }

  if (type instanceof Type) {
    return getTypeAsString((Type) type, asObject);
  }

  if (type instanceof String) {
    return getTypeAsString((String) type, asObject);
  }

  return type;
}
项目:private-freemarker    文件:CssOutputInFTLDirective.java   
/**
 * 
 */
public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars,
        TemplateDirectiveBody body) throws TemplateException, IOException {
    // Check if no parameters were given:
    if (params.isEmpty()) {
        return;
    }
    if (loopVars.length > 1) {
        throw new TemplateModelException("At most one loop variable is allowed.");
    }
    String[] cssFileArray = null;
    // 获取remote flag,如果是flag是true则读文件服务器上面的,否则读取本地服务器
    boolean remoteFlag = false;
    TemplateModel paramValue = (TemplateModel) params.get(REMOTE_FLAG);
    if (paramValue != null) {
        if (!(paramValue instanceof TemplateBooleanModel)) {
            throw new TemplateModelException("The \"" + REMOTE_FLAG
                    + "\" parameter " + "must be a boolean.");
        } else {
            remoteFlag = ((TemplateBooleanModel) paramValue).getAsBoolean();
        }
    }
    //获取css文件列表
    SimpleScalar cssValue = (SimpleScalar) params.get(CSS);
    String cssFiles = cssValue.getAsString();
    if (StringUtils.isEmpty(cssFiles)) {
        return;
    } else {
        cssFileArray = cssFiles.split(",");
    }
    // ---------------------------------------------------------------------
    // Do the actual directive execution:
    /*
     * 参考TemplateDirectiveModel的注释 <@cssOutput
     * css="css/wxsales/reset.css,css/wxsales/common.css"> ${name}
     * </@cssOutput> body != null 如果<@cssOutput/> or
     * <@cssOutput></@cssOutput> body = null
     */
    if (body != null) {}
    Writer out = env.getOut();
    out.write("<style>\n");
    if(remoteFlag){
        remoteStaticServer(cssFileArray, out);
    }else{
        localServer(cssFileArray, out);
    }
    out.write("</style>");
}
项目:private-freemarker    文件:SaicObjectWrapper.java   
@SuppressWarnings("rawtypes")
@Override
public TemplateModel wrap(Object obj) throws TemplateModelException {
       if (obj == null) {
           return super.wrap(null);
       }
       if (obj instanceof TemplateModel) {
           return (TemplateModel) obj;
       }
       if (obj instanceof String) {
           return new SimpleScalar((String) obj);
       }
       if (obj instanceof Number) {
           return new SimpleNumber((Number) obj);
       }
       if (obj instanceof java.util.Date) {
           if(obj instanceof java.sql.Date) {
               return new SimpleDate((java.sql.Date) obj);
           }
           if(obj instanceof java.sql.Time) {
               return new SimpleDate((java.sql.Time) obj);
           }
           if(obj instanceof java.sql.Timestamp) {
               return new SimpleDate((java.sql.Timestamp) obj);
           }
           return new SimpleDate((java.util.Date) obj, getDefaultDateType());
       }
       if (obj.getClass().isArray()) {
           obj = convertArray(obj);
       }
       if (obj instanceof Collection) {
           return new SimpleSequence((Collection) obj, this);
       }
       if (obj instanceof Boolean) {
           return obj.equals(Boolean.TRUE) ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
       }
       if (obj instanceof Iterator) {
           return new SimpleCollection((Iterator) obj, this);
       }
       return handleUnknownType(obj);
   }
项目:windup    文件:GetEffortDetailsForProjectTraversalMethod.java   
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException
{
    // Process arguments
    ExecutionStatistics.get().begin(NAME);
    if (arguments.size() < 2)
    {
        throw new TemplateModelException(
            "Error, method expects at least three arguments"
            + " (projectModel: ProjectModel, recursive: Boolean, [includeTags: Set<String>], [excludeTags: Set<String>])");
    }
    StringModel projectModelTraversalArg = (StringModel) arguments.get(0);
    ProjectModelTraversal projectModelTraversal = (ProjectModelTraversal) projectModelTraversalArg.getWrappedObject();

    TemplateBooleanModel recursiveBooleanModel = (TemplateBooleanModel) arguments.get(1);
    boolean recursive = recursiveBooleanModel.getAsBoolean();

    Set<String> includeTags = Collections.emptySet();
    if (arguments.size() >= 3)
    {
        includeTags = FreeMarkerUtil.simpleSequenceToSet((SimpleSequence) arguments.get(2));
    }

    Set<String> excludeTags = Collections.emptySet();
    if (arguments.size() >= 4)
    {
        excludeTags = FreeMarkerUtil.simpleSequenceToSet((SimpleSequence) arguments.get(3));
    }

    Set<String> issueCategories = Collections.emptySet();
    if (arguments.size() >= 5)
    {
        issueCategories = FreeMarkerUtil.simpleSequenceToSet((SimpleSequence) arguments.get(4));
    }

    // Get values for classification and hints.
    Map<Integer, Integer> classificationEffortDetails =
            classificationService.getMigrationEffortByPoints(projectModelTraversal, includeTags, excludeTags, issueCategories, recursive, false);
    Map<Integer, Integer> hintEffortDetails =
            inlineHintService.getMigrationEffortByPoints(projectModelTraversal, includeTags, excludeTags, issueCategories, recursive, false);

    Map<Integer, Integer> results = sumMaps(classificationEffortDetails, hintEffortDetails);

    ExecutionStatistics.get().end(NAME);


    int points = sumPoints(results);
    LOG.fine(String.format("%s() FM function called:\n\t\t\tEFFORT: %3d = %s = C%s + H%s; %s, %srecur, tags: %s, excl: %s",
            NAME, points, results, classificationEffortDetails, hintEffortDetails,
            projectModelTraversal, recursive ? "" : "!", includeTags, excludeTags));

    return results;
}
项目:windup    文件:GetEffortCountForProjectByIssueCategoryMethod.java   
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException
{
    ExecutionStatistics.get().begin(NAME);
    if (arguments.size() < 3)
    {
        throw new TemplateModelException(
                    "Error, method expects at least three arguments (event:GraphRewrite, projectModelTraversal:ProjectModelTraversal, recursive:Boolean, [includeTags:Set<String>]. [excludeTags:Set<String>])");
    }

    GraphRewrite event = (GraphRewrite)((StringModel)arguments.get(0)).getWrappedObject();

    StringModel projectModelTraversalArg = (StringModel) arguments.get(1);
    ProjectModelTraversal traversal = (ProjectModelTraversal) projectModelTraversalArg.getWrappedObject();

    TemplateBooleanModel recursiveBooleanModel = (TemplateBooleanModel) arguments.get(2);
    boolean recursive = recursiveBooleanModel.getAsBoolean();

    Set<String> includeTags = Collections.emptySet();
    if (arguments.size() >= 4)
    {
        includeTags = FreeMarkerUtil.simpleSequenceToSet((SimpleSequence) arguments.get(3));
    }

    Set<String> excludeTags = Collections.emptySet();
    if (arguments.size() >= 5)
    {
        excludeTags = FreeMarkerUtil.simpleSequenceToSet((SimpleSequence) arguments.get(4));
    }

    Map<IssueCategoryModel, Integer> classificationEffortDetails = classificationService.getMigrationEffortBySeverity(event, traversal, includeTags,
                excludeTags, Collections.emptySet(), recursive);
    Map<IssueCategoryModel, Integer> hintEffortDetails = inlineHintService.getMigrationEffortBySeverity(event, traversal, includeTags, excludeTags,
            Collections.emptySet(), recursive);

    Map<IssueCategoryModel, Integer> results = new TreeMap<>(new IssueCategoryModel.IssueSummaryPriorityComparator());
    addAllIncidents(results, classificationEffortDetails);
    addAllIncidents(results, hintEffortDetails);

    ExecutionStatistics.get().end(NAME);
    return results;
}
项目:windup    文件:RenderApplicationPieChartDirective.java   
@Override
public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars,
            TemplateDirectiveBody body)
            throws TemplateException, IOException
{
    StringModel projectStringModel = (StringModel) params.get("project");
    ProjectModel projectModel = null;
    if (projectStringModel != null)
        projectModel = (ProjectModel) projectStringModel.getWrappedObject();

    StringModel projectTraversalStringModel = (StringModel) params.get("projectTraversal");
    ProjectModelTraversal projectTraversal = null;
    if (projectTraversalStringModel != null)
        projectTraversal = (ProjectModelTraversal) projectTraversalStringModel.getWrappedObject();

    if (projectModel != null && projectTraversal != null)
        throw new WindupException(NAME + " both 'project' and 'projectTraversal' were specified. Only one of these values should be specified.");
    else if (projectModel == null && projectTraversal == null)
        throw new WindupException(NAME + " neither 'project' nor 'projectTraversal' were specified. At least one of these must be specified.");

    TemplateBooleanModel recursiveBooleanModel = (TemplateBooleanModel) params.get("recursive");
    boolean recursive = recursiveBooleanModel.getAsBoolean();
    SimpleScalar elementIDStringModel = (SimpleScalar) params.get("elementID");
    String elementID = elementIDStringModel.getAsString();

    Set<String> includeTags = FreeMarkerUtil.simpleSequenceToSet((SimpleSequence) params.get("includeTags"));
    Set<String> excludeTags = FreeMarkerUtil.simpleSequenceToSet((SimpleSequence) params.get("excludeTags"));

    TypeReferenceService typeReferenceService = new TypeReferenceService(context);
    Map<String, Integer> data;
    if (projectModel != null)
        data = typeReferenceService.getPackageUseFrequencies(projectModel, includeTags, excludeTags, 2, recursive);
    else
        data = typeReferenceService.getPackageUseFrequencies(projectTraversal, includeTags, excludeTags, 2, recursive);

    if (data.keySet().size() > 0)
    {
        drawPie(env.getOut(), data, elementID);
    }
    else
    {
        // if we aren't drawing a pie, remove the element that would have held it
        Writer writer = env.getOut();
        writer.append("<script type='text/javascript'>");
        writer.append("$('#" + elementID + "').parent().remove()");
        writer.append("</script>");
    }
}
项目:marmotta    文件:TemplateBooleanTransformer.java   
/**
 * Transform the KiWiNode node into the datatype T. In case the node cannot be transformed to
 * the respective datatype, throws an IllegalArgumentException that needs to be caught by the class
 * carrying out the transformation.
 *
 *
 *
 * @param nodeRDFBackend
 * @param node
 * @param configuration
 * @return
 */
@Override
public TemplateBooleanModel transform(final RDFBackend<Node> nodeRDFBackend, final Node node, final Map<String, String> configuration) throws IllegalArgumentException {
    return new TemplateBooleanModel() {
        @Override
        public boolean getAsBoolean() throws TemplateModelException {
            return delegate.transform(nodeRDFBackend,node, configuration);
        }
    };
}