freemarker.ext.beans.BeanModel Java Examples

The following examples show how to use freemarker.ext.beans.BeanModel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LangFtlUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * Converts map to a simple wrapper, if applicable, by rewrapping
 * known complex map wrappers that implement <code>WrapperTemplateModel</code>.
 * <p>
 * If the specified ObjectWrapper is a BeansWrapper, this forces rewrapping as a SimpleMapModel.
 * If it isn't we assume caller specified an objectWrapper that will rewrap the map with
 * a simple model (we have no way of knowing).
 * <p>
 * WARN: Bypasses auto-escaping for complex maps; caller must decide how to handle
 * (e.g. the object wrapper used to rewrap the result).
 * Other types of maps are not altered.
 *
 * @deprecated don't use
 */
@SuppressWarnings("unused")
@Deprecated
private static TemplateHashModel toSimpleMapRewrapAdapters(TemplateModel object, ObjectWrapper objectWrapper) throws TemplateModelException {
    if (object instanceof SimpleMapModel || object instanceof BeanModel || object instanceof DefaultMapAdapter) {
        // Permissive
        Map<?, ?> wrappedObject = (Map<?, ?>) ((WrapperTemplateModel) object).getWrappedObject();
        if (objectWrapper instanceof BeansWrapper) {
            // Bypass the beanswrapper wrap method and always make simple wrapper
            return new SimpleMapModel(wrappedObject, (BeansWrapper) objectWrapper);
        } else {
            // If anything other than BeansWrapper, assume caller is aware and his wrapper will create a simple map
            return (TemplateHashModel) objectWrapper.wrap(wrappedObject);
        }
    }
    else if (object instanceof TemplateHashModel) {
        return (TemplateHashModel) object;
    }
    else {
        throw new TemplateModelException("object is not a recognized map type");
    }
}
 
Example #2
Source File: FreeMarkerWorker.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
* Gets BeanModel from FreeMarker context and returns the object that it wraps.
* @param varName the name of the variable in the FreeMarker context.
* @param env the FreeMarker Environment
*/
public static <T> T getWrappedObject(String varName, Environment env) {
    Object obj = null;
    try {
        obj = env.getVariable(varName);
        if (obj != null) {
            if (obj == TemplateModel.NOTHING) {
                obj = null;
            } else if (obj instanceof BeanModel) {
                BeanModel bean = (BeanModel) obj;
                obj = bean.getWrappedObject();
            } else if (obj instanceof SimpleScalar) {
                obj = obj.toString();
            }
        }
    } catch (TemplateModelException e) {
        Debug.logInfo(e.getMessage(), module);
    }
    return UtilGenerics.<T>cast(obj);
}
 
Example #3
Source File: SetContextFieldTransform.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException {
    if (args == null || args.size() != 2)
        throw new TemplateModelException("Invalid number of arguements");
    if (!(args.get(0) instanceof TemplateScalarModel))
        throw new TemplateModelException("First argument not an instance of TemplateScalarModel");
    // SCIPIO: This is too limiting...
    //if (!(args.get(1) instanceof BeanModel) && !(args.get(1) instanceof TemplateNumberModel) && !(args.get(1) instanceof TemplateScalarModel))
    //    throw new TemplateModelException("Second argument not an instance of BeanModel nor TemplateNumberModel nor TemplateScalarModel");

    Environment env = FreeMarkerWorker.getCurrentEnvironment();
    BeanModel req = (BeanModel)env.getVariable("context");
    Map<String, Object> context = (Map<String, Object>) req.getWrappedObject();

    // SCIPIO: name should not be escaped
    //String name = ((TemplateScalarModel) args.get(0)).getAsString();
    String name = LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(0)));
    Object valueModel = args.get(1);
    Object value = null;
    // SCIPIO: Let DeepUnwrap handle this...
    //if (args.get(1) instanceof TemplateNumberModel)
    //    value = ((TemplateNumberModel) args.get(1)).getAsNumber();
    //if (args.get(1) instanceof BeanModel)
    //    value = ((BeanModel) args.get(1)).getWrappedObject();
    // SCIPIO: NOTE: Unlike this above, this call will avoid the auto-escaping as implemented by Ofbiz (sensitive to DeepUnwrap implementation)
    value = LangFtlUtil.unwrapAlwaysUnlessNull(valueModel);

    context.put(name, value);
    return new SimpleScalar("");
}
 
Example #4
Source File: SortFilesByPathMethod.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Iterable<Object> getIterable(Object arg) throws TemplateModelException
{
    if (arg instanceof BeanModel)
    {
        BeanModel beanModel = (BeanModel) arg;
        return (Iterable<Object>) beanModel.getWrappedObject();
    }
    else if (arg instanceof SimpleSequence)
    {
        SimpleSequence simpleSequence = (SimpleSequence) arg;
        return (Iterable<Object>) simpleSequence.toList();
    }
    else if (arg instanceof DefaultIterableAdapter)
    {
        DefaultIterableAdapter adapter = (DefaultIterableAdapter) arg;
        return (Iterable<Object>) adapter.getAdaptedObject(Iterable.class);
    }
    else if (arg instanceof DefaultListAdapter)
    {
        DefaultListAdapter defaultListAdapter = (DefaultListAdapter) arg;
        return (Iterable<Object>) defaultListAdapter.getWrappedObject();
    }
    else
    {
        throw new WindupException("Unrecognized type passed to: " + getMethodName() + ": "
                    + arg.getClass().getCanonicalName());
    }
}
 
Example #5
Source File: SourceReportGenerator.java    From testability-explorer with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Object exec(List arguments) throws TemplateModelException {
  TemplateModel model = (TemplateModel) arguments.get(0);
  if (model instanceof SimpleNumber) {
    SimpleNumber number = (SimpleNumber) model;
    return number;
  } else if (model instanceof BeanModel) {
    BeanModel arg0 = (BeanModel) model;
    Cost cost = (Cost) arg0.getAdaptedObject(Cost.class);
    return costModel.computeOverall(cost);
  } else {
    throw new IllegalStateException();
  }
}
 
Example #6
Source File: SourceReportGenerator.java    From testability-explorer with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Object exec(List arguments) throws TemplateModelException {
  TemplateModel model = (TemplateModel) arguments.get(0);
  if (model instanceof SimpleNumber) {
    SimpleNumber number = (SimpleNumber) model;
    return "" + number;
  } else if (model instanceof BeanModel) {
    BeanModel arg0 = (BeanModel) model;
    Cost cost = (Cost) arg0.getAdaptedObject(Cost.class);
    return "Cost: " + costModel.computeOverall(cost) + " [" + cost + "]";
  } else {
    throw new IllegalStateException();
  }
}
 
Example #7
Source File: AbstractDirective.java    From onetwo with Apache License 2.0 5 votes vote down vote up
protected <T> T getVariable(String varName, Environment env) throws TemplateModelException{
	Object value = env.getVariable(varName);
	if (value instanceof BeanModel) {
		value = ((BeanModel) value).getWrappedObject();
	}
	return (T)value;
}
 
Example #8
Source File: ForeachDirective.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
	TemplateModel listModel = FtlUtils.getRequiredParameter(params, PARAMS_LIST);
	String joiner = FtlUtils.getParameterByString(params, PARAMS_JOINER, "");
	if(StringUtils.isBlank(joiner))
		joiner = FtlUtils.getParameterByString(params, PARAMS_SEPARATOR, "");//兼容当初定义错的写法
	
	Object datas = null;
	if(listModel instanceof BeanModel){
		datas = ((BeanModel) listModel).getWrappedObject();
	}else{
		throw new BaseException("error: " + listModel);
	}
	
	List<?> listDatas = LangUtils.asList(datas);
	int index = 0;
	for(Object data : listDatas){
		if(loopVars.length>=1)
			loopVars[0] = FtlUtils.wrapAsModel(data);
		if(loopVars.length>=2)
			loopVars[1] = FtlUtils.wrapAsModel(index);
		
		if(index!=0)
			env.getOut().write(joiner);
		
		body.render(env.getOut());
		index++;
	}
}
 
Example #9
Source File: LangFtlUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Gets collection as a keys.
 * <p>
 * WARN: This bypasses auto-escaping in all cases. Caller must decide how to handle.
 * (e.g. the object wrapper used to rewrap the result).
 */
public static Set<String> getAsStringSet(TemplateModel model) throws TemplateModelException {
    Set<String> exKeys = null;
    if (model != null) {
        if (model instanceof BeanModel && ((BeanModel) model).getWrappedObject() instanceof Set) {
            // WARN: bypasses auto-escaping
            exKeys = UtilGenerics.cast(((BeanModel) model).getWrappedObject());
        }
        else if (model instanceof TemplateCollectionModel) {
            exKeys = new HashSet<String>();
            TemplateModelIterator keysIt = ((TemplateCollectionModel) model).iterator();
            while(keysIt.hasNext()) {
                exKeys.add(getAsStringNonEscaping((TemplateScalarModel) keysIt.next()));
            }
        }
        else if (model instanceof TemplateSequenceModel) {
            TemplateSequenceModel seqModel = (TemplateSequenceModel) model;
            exKeys = new HashSet<String>(seqModel.size());
            for(int i=0; i < seqModel.size(); i++) {
                exKeys.add(getAsStringNonEscaping((TemplateScalarModel) seqModel.get(i)));
            }
        }
        else {
            throw new TemplateModelException("Include/exclude keys argument not a collection or set of strings");
        }
    }
    return exKeys;
}
 
Example #10
Source File: SetGlobalContextFieldMethod.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@Override
public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException {
    if (args == null || args.size() != 2)
        throw new TemplateModelException("Invalid number of arguments");
    if (!(args.get(0) instanceof TemplateScalarModel))
        throw new TemplateModelException("First argument not an instance of TemplateScalarModel");
    // SCIPIO: This is too limiting
    //if (!(args.get(1) instanceof BeanModel) && !(args.get(1) instanceof TemplateNumberModel) && !(args.get(1) instanceof TemplateScalarModel))
    //    throw new TemplateModelException("Second argument not an instance of BeanModel nor TemplateNumberModel nor TemplateScalarModel");

    Environment env = FreeMarkerWorker.getCurrentEnvironment();
    BeanModel globalContextModel = (BeanModel) env.getVariable("globalContext");
    @SuppressWarnings("unchecked")
    Map<String, Object> globalContext = (Map<String, Object>) globalContextModel.getWrappedObject();

    String name = LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(0)));
    Object valueModel = args.get(1);
    Object value = null;
    // SCIPIO: Let DeepUnwrap handle this...
    //if (args.get(1) instanceof TemplateScalarModel)
    //    value = ((TemplateScalarModel) args.get(1)).getAsString();
    //if (args.get(1) instanceof TemplateNumberModel)
    //    value = ((TemplateNumberModel) args.get(1)).getAsNumber();
    //if (args.get(1) instanceof BeanModel)
    //    value = ((BeanModel) args.get(1)).getWrappedObject();
    // SCIPIO: NOTE: Unlike this above, this call will avoid the auto-escaping as implemented by Ofbiz (sensitive to DeepUnwrap implementation)
    value = LangFtlUtil.unwrapAlwaysUnlessNull(valueModel);

    globalContext.put(name, value);
    return new SimpleScalar("");
}
 
Example #11
Source File: CropContentMethod.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see freemarker.template.TemplateMethodModel#exec(java.util.List)
 */
public Object exec(List args) throws TemplateModelException
{
    String result = null;
    
    if (args.size() == 2)
    {
        Object arg0 = args.get(0);
        Object arg1 = args.get(1);
        
        if (arg0 instanceof BeanModel && arg1 instanceof TemplateNumberModel)
        {
            Object wrapped = ((BeanModel)arg0).getWrappedObject();
            if (wrapped instanceof TemplateContentData)
            {
                int bytes = ((TemplateNumberModel)arg1).getAsNumber().intValue();
                
                try 
                {
            	    result = ((TemplateContentData)wrapped).getContentAsText(bytes);
                } 
                catch (ContentIOException e)
                {
                   logger.warn("unable to getContentAsText", e);
            	   /*
                    * Unable to extract content - return empty text instead.
                    * Probably here through a transformation failure.
                    * This method is called from FreeMarker so throwing the 
                    * exception causes problems.
                    */
                   result = "";
                }
            }
        }
    }
    
    return result != null ? result : "";
}
 
Example #12
Source File: SetRequestAttributeMethod.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException {
    if (args == null || args.size() != 2)
        throw new TemplateModelException("Invalid number of arguements");
    if (!(args.get(0) instanceof TemplateScalarModel))
        throw new TemplateModelException("First argument not an instance of TemplateScalarModel");
    // SCIPIO: This is too limiting...
    //if (!(args.get(1) instanceof BeanModel) && !(args.get(1) instanceof TemplateNumberModel) && !(args.get(1) instanceof TemplateScalarModel))
    //    throw new TemplateModelException("Second argument not an instance of BeanModel nor TemplateNumberModel nor TemplateScalarModel");

    Environment env = FreeMarkerWorker.getCurrentEnvironment();
    BeanModel req = (BeanModel)env.getVariable("request");
    HttpServletRequest request = (HttpServletRequest) req.getWrappedObject();

    // SCIPIO: name should not be escaped
    //String name = ((TemplateScalarModel) args.get(0)).getAsString();
    String name = LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(0)));
    Object valueModel = args.get(1);
    Object value = null;
    // SCIPIO: Let DeepUnwrap handle this...
    //if (args.get(1) instanceof TemplateScalarModel)
    //    value = ((TemplateScalarModel) args.get(1)).getAsString();
    //if (args.get(1) instanceof TemplateNumberModel)
    //    value = ((TemplateNumberModel) args.get(1)).getAsNumber();
    //if (args.get(1) instanceof BeanModel)
    //    value = ((BeanModel) args.get(1)).getWrappedObject();
    // SCIPIO: NOTE: Unlike this above, this call will avoid the auto-escaping as implemented by Ofbiz (sensitive to DeepUnwrap implementation)
    value = LangFtlUtil.unwrapAlwaysUnlessNull(valueModel);

    request.setAttribute(name, value);
    return new SimpleScalar("");
}
 
Example #13
Source File: FreeMarkerWorker.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T unwrap(Object o) {
    Object returnObj = null;

    if (o == TemplateModel.NOTHING) {
        returnObj = null;
    } else if (o instanceof SimpleScalar) {
        returnObj = o.toString();
    } else if (o instanceof BeanModel) {
        returnObj = ((BeanModel) o).getWrappedObject();
    }

    return (T) returnObj;
}
 
Example #14
Source File: FreemarkerTemplateEngine.java    From enkan with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public Object createFunction(Function<List, Object> func) {
    return (TemplateMethodModelEx) arguments ->
            func.apply((List)arguments.stream().map(arg -> {
                if (arg instanceof BeanModel) {
                    return ((StringModel) arg).getWrappedObject();
                } else {
                    return arg;
                }
            }).collect(Collectors.toList()));
}
 
Example #15
Source File: ShortQNameMethod.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see freemarker.template.TemplateMethodModel#exec(java.util.List)
 */
public Object exec(List args) throws TemplateModelException
{
    String result = null;
    
    if (args.size() == 1)
    {
        // arg 0 can be either wrapped QName object or a String 
        String arg0String = null;
        Object arg0 = args.get(0);
        if (arg0 instanceof BeanModel)
        {
            arg0String = ((BeanModel)arg0).getWrappedObject().toString();
        }
        else if (arg0 instanceof TemplateScalarModel)
        {
            arg0String = ((TemplateScalarModel)arg0).getAsString();
        }

        try
        {
        result = createQName(arg0String).toPrefixString(services.getNamespaceService());
    }
        catch (NamespaceException e) 
        {
            // not valid qname -> return original value
            result = arg0String;
        }
    }
    
    return result != null ? result : "";
}
 
Example #16
Source File: HasPermissionMethod.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see freemarker.template.TemplateMethodModel#exec(java.util.List)
 */
public Object exec(List args) throws TemplateModelException
{
    int result = 0;
    
    if (args.size() == 2)
    {
        // arg 0 must be a wrapped TemplateNode object
        BeanModel arg0 = (BeanModel)args.get(0);
        
        // arg 1 must be a String permission name
        String permission;
        Object arg1 = args.get(1);
        if (arg1 instanceof TemplateScalarModel)
        {
            permission = ((TemplateScalarModel)arg1).getAsString();
            
            if (arg0.getWrappedObject() instanceof TemplateNode)
            {
                // test to see if this node has the permission
                if ( ((TemplateNode)arg0.getWrappedObject()).hasPermission(permission) )
                {
                    result = 1;
                }
            }
        }
    }
    
    return Integer.valueOf(result);
}
 
Example #17
Source File: HasAspectMethod.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see freemarker.template.TemplateMethodModel#exec(java.util.List)
 */
public Object exec(List args) throws TemplateModelException
{
    int result = 0;
    
    if (args.size() == 2)
    {
        // arg 0 must be a wrapped TemplateNode object
        BeanModel arg0 = (BeanModel)args.get(0);
        
        // arg 1 can be either wrapped QName object or a String 
        String arg1String = null;
        Object arg1 = args.get(1);
        if (arg1 instanceof BeanModel)
        {
            arg1String = ((BeanModel)arg1).getWrappedObject().toString();
        }
        else if (arg1 instanceof TemplateScalarModel)
        {
            arg1String = ((TemplateScalarModel)arg1).getAsString();
        }
        if (arg0.getWrappedObject() instanceof TemplateNode)
        {
            // test to see if this node has the aspect
            if ( ((TemplateNode)arg0.getWrappedObject()).hasAspect(arg1String) )
            {
                result = 1;
            }
        }
    }
    
    return Integer.valueOf(result);
}
 
Example #18
Source File: Steps.java    From requirementsascode with Apache License 2.0 4 votes vote down vote up
public static Flow getFlowFromFreemarker(Object argument) {
  return (Flow) ((BeanModel) argument).getAdaptedObject(Flow.class);
}
 
Example #19
Source File: Steps.java    From requirementsascode with Apache License 2.0 4 votes vote down vote up
public static Step getStepFromFreemarker(Object argument) {
  return (Step) ((BeanModel) argument).getAdaptedObject(Step.class);
}
 
Example #20
Source File: AbstractAdapter.java    From freemarker-java-8 with Apache License 2.0 4 votes vote down vote up
public AbstractAdapter(E entity, BeansWrapper wrapper) {
    this.entity = entity;
    this.fallback = new BeanModel(entity, Objects.requireNonNull(wrapper, "wrapper"));
}
 
Example #21
Source File: Steps.java    From requirementsascode with Apache License 2.0 4 votes vote down vote up
public static Class<?> getClassFromFreemarker(Object argument) {
  return (Class<?>) ((BeanModel) argument).getAdaptedObject(Class.class);
}
 
Example #22
Source File: DirectivesUtils.java    From onetwo with Apache License 2.0 4 votes vote down vote up
public static BeanModel wrapAsBeanModel(Object obj){
	return FtlUtils.wrapAsBeanModel(obj);
}
 
Example #23
Source File: ReactWhileOfStep.java    From requirementsascode with Apache License 2.0 4 votes vote down vote up
private Step getStep(Object argument) {
return (Step) ((BeanModel) argument).getAdaptedObject(Step.class);
   }
 
Example #24
Source File: SpringBeansTemplateHashModelEx.java    From ogham with Apache License 2.0 4 votes vote down vote up
@Override
public TemplateModel get(String key) throws TemplateModelException {
	return new BeanModel(applicationContext.getBean(key.startsWith("@") ? key.substring(1) : key), beansWrapper);
}