protected Map getComplexParams(Map params) { HashMap map = new HashMap(params.size()); for (Iterator iterator = params.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); Object value = entry.getValue(); if (value != null && complexType(value)) { if (value instanceof freemarker.ext.beans.BeanModel) { map.put(entry.getKey(), ((freemarker.ext.beans.BeanModel) value).getWrappedObject()); } else if (value instanceof SimpleNumber) { map.put(entry.getKey(), ((SimpleNumber) value).getAsNumber()); } else if (value instanceof SimpleSequence) { try { map.put(entry.getKey(), ((SimpleSequence) value).toList()); } catch (TemplateModelException e) { if (LOG.isErrorEnabled()) { LOG.error("There was a problem converting a SimpleSequence to a list", e); } } } } } return map; }
/** * Parse sequence parameter. * * @param params the params * @param paramName the param name * @return the string [ ] * @throws TemplateModelException the template model exception */ @SuppressWarnings("rawtypes") protected String[] parseSequenceParameter(Map params, String paramName) throws TemplateModelException { Object paramModel = params.get(paramName); if (paramModel == null) { return null; } if (!(paramModel instanceof SimpleSequence)) { throw new IllegalArgumentException(paramName + " must be sequence"); } List<String> list = transformSimpleSequenceAsStringList((SimpleSequence)paramModel, paramName); return list.toArray(new String[list.size()]); }
/** * Transform simple sequence as string list. * * @param sequence the sequence * @param paramName the param name * @return the list * @throws TemplateModelException the template model exception */ private List<String> transformSimpleSequenceAsStringList(SimpleSequence sequence, String paramName) throws TemplateModelException { List<String> list = new ArrayList<>(); int size = sequence.size(); for (int i = 0; i < size; i++) { TemplateModel model = sequence.get(i); if (!(model instanceof SimpleScalar)) { throw new IllegalArgumentException(paramName + "'s item must be string"); } list.add(((SimpleScalar)model).getAsString()); } return list; }
private SimpleSequence loadDataModel(Engine engine, List<?> args) throws Exception { final List<TemplateModel> templateModels = new ArrayList<TemplateModel>(); for (int i = 0; i < args.size(); i++) { final String resourceName = args.get(i).toString(); final URL resource = loadResource(engine, resourceName); if (resource != null) { final TemplateModel templateModel = templateLoader.load(resource); if (templateModel != null) { templateModels.add(templateModel); } } else { throw new IllegalArgumentException("resource[" + i + "] not found: " + resourceName); } } return new SimpleSequence(templateModels); }
public Object exec(List arguments) throws TemplateModelException { if (arguments.size() < 1) { throw new TemplateModelException("Wrong arguments"); } //所有参数都要先转成SimpleSequence SimpleSequence arg0 = (SimpleSequence)arguments.get(0); //把参数转换为list List<String> list = arg0.toList(); TemplateScalarModel value = (TemplateScalarModel)arguments.get(1); return list.contains(value.getAsString()); }
@SuppressWarnings("unchecked") @Override public Object exec(List args) throws TemplateModelException { if (args == null || args.size() != 2) { throw new TemplateModelException("Invalid number of arguments (expected: 2)"); } String styleString = LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(0))); styleString = TemplateFtlUtil.getPlainClassArgNames(styleString); String prefix = LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(1))); String[] names = StringUtils.split(styleString, ' '); // NOTE: For emergency/safety reasons, use the current wrapper, which MAY be escaping. // style strings contain only simple characters anyway. ObjectWrapper objectWrapper = LangFtlUtil.getCurrentObjectWrapper(); SimpleSequence res = new SimpleSequence(names.length, objectWrapper); for(String name : names) { if (name.startsWith(prefix)) { res.add(name); } } // redundant //return LangFtlUtil.wrap(res, objectWrapper); return res; }
public static void addToSimpleList(SimpleSequence dest, TemplateModel source) throws TemplateModelException { if (source instanceof TemplateCollectionModel) { addToSimpleList(dest, (TemplateCollectionModel) source); } else if (source instanceof TemplateSequenceModel) { addToSimpleList(dest, (TemplateSequenceModel) source); } else { throw new TemplateModelException("Can't add to simple list from source type (non-list type): " + source.getClass()); } }
public static List<Object> getSequence(SimpleSequence ss){ List<Object> res=new ArrayList<Object>(); for(int i=0;i<ss.size();i++){ try { Object obj=ss.get(i); res.add(unwrapObject(obj)); } catch (TemplateModelException e) { e.printStackTrace(); } } return res; }
private SimpleSequence loadDataModel(Engine engine, List<?> args) throws Exception { final List<Class<?>> classes = loadClasses(engine, args); final List<TemplateModel> templateModels = new ArrayList<TemplateModel>(); for (final Class<?> clazz : classes) { final TemplateModel templateModel = templateLoader.load(clazz); if (templateModel != null) { templateModels.add(templateModel); } } return new SimpleSequence(templateModels); }
@SuppressWarnings("rawtypes") @Override public SimpleSequence load(Engine engine, List args) throws Exception { System.out.println("loading option set definitions..."); System.out.println("...args: " + args); final SimpleSequence result = super.load(engine, args); System.out.println("loaded " + result.size() + " option set definitions."); return result; }
@SuppressWarnings("rawtypes") @Override public SimpleSequence load(Engine engine, List args) throws Exception { System.out.println("loading command definitions..."); System.out.println("...args: " + args); final SimpleSequence result = super.load(engine, args); System.out.println("loaded " + result.size() + " command definitions."); return result; }
/** * Converts a FreeMarker {@link SimpleSequence} to a {@link Set}. * */ public static Set<String> simpleSequenceToSet(SimpleSequence simpleSequence) { if (simpleSequence == null) return Collections.emptySet(); Set<String> result = new HashSet<>(); for (int i = 0; i < simpleSequence.size(); i++) { try { Object sequenceEntry = simpleSequence.get(i); if (sequenceEntry instanceof SimpleScalar) { result.add(((SimpleScalar) sequenceEntry).getAsString()); } else { result.add(simpleSequence.get(i).toString()); } } catch (Exception e) { throw new RuntimeException(e); } } return result; }
@Override public Object exec(List arguments) throws TemplateModelException { if (arguments.isEmpty()) throw new TemplateModelException("Method " + getMethodName() + " requires the following parameters (GraphRewrite event, ProjectModel project, Set<String> includeTags, Set<String> excludeTags)"); // Gets the graph rewrite event final GraphRewrite event = (GraphRewrite)((StringModel)arguments.get(0)).getWrappedObject(); // Get the project if one was passed in final ProjectModel projectModel; StringModel projectModelArg = (StringModel) arguments.get(1); if (projectModelArg == null) projectModel = null; else projectModel = (ProjectModel) projectModelArg.getWrappedObject(); Set<String> includeTags = FreeMarkerUtil.simpleSequenceToSet((SimpleSequence) arguments.get(2)); Set<String> excludeTags = FreeMarkerUtil.simpleSequenceToSet((SimpleSequence) arguments.get(3)); Set<ProjectModel> projectModels = getProjects(projectModel); Map<IssueCategoryModel, List<ProblemSummary>> problemSummariesOriginal = ProblemSummaryService.getProblemSummaries(event.getGraphContext(), projectModels, includeTags, excludeTags); // Convert the keys to String to make Freemarker happy Comparator<IssueCategoryModel> severityComparator = new IssueCategoryModel.IssueSummaryPriorityComparator(); Map<IssueCategoryModel, List<ProblemSummary>> problemSummaries = new TreeMap<>(severityComparator); problemSummaries.putAll(problemSummariesOriginal); Map<String, List<ProblemSummary>> primarySummariesByString = new LinkedHashMap<>(problemSummariesOriginal.size()); for (Map.Entry<IssueCategoryModel, List<ProblemSummary>> entry : problemSummaries.entrySet()) { String severityString = entry.getKey() == null ? null : entry.getKey().getName(); primarySummariesByString.put(severityString, entry.getValue()); } return primarySummariesByString; }
@Override public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { ExecutionStatistics.get().begin(NAME); try { if (arguments.size() != 3) { throw new TemplateModelException("Error, method expects one argument (FileModel, includeTags:Set<String>, excludeTags:Set<String>)"); } StringModel stringModelArg = (StringModel) arguments.get(0); FileModel fileModel = (FileModel) stringModelArg.getWrappedObject(); Set<String> includeTags = FreeMarkerUtil.simpleSequenceToSet((SimpleSequence) arguments.get(1)); Set<String> excludeTags = FreeMarkerUtil.simpleSequenceToSet((SimpleSequence) arguments.get(2)); SourceReportModel result = sourceReportService.getSourceReportForFileModel(fileModel); if (result == null) return false; return TagUtil.hasHintsOrClassificationsWithRelevantTags(result.getSourceFileModel(), includeTags, excludeTags); } finally { ExecutionStatistics.get().end(NAME); } }
@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()); } }
/** * Supposed to convert to simple sequence. * <p> * WARN: Bypasses auto-escaping for complex maps, caller must decide how to handle. * (e.g. the object wrapper used to rewrap the result). * <p> * DEV NOTE: I stopped writing/testing this when found out most of the problems w.r.t. collections are not * the FTL types this time but the way they're used in Ofbiz templates. * FTL's CollectionModel (subclass of TemplateCollectionModel) is supposed to cover everything and * won't suffer from the same problems maps have. */ @SuppressWarnings("unchecked") @Deprecated private static TemplateSequenceModel toSimpleSequence(TemplateModel object, ObjectWrapper objectWrapper) throws TemplateModelException { if (object instanceof TemplateSequenceModel) { return (TemplateSequenceModel) object; } else if (object instanceof WrapperTemplateModel) { WrapperTemplateModel wrapperModel = (WrapperTemplateModel) object; // WARN: bypasses auto-escaping Object wrappedObject = wrapperModel.getWrappedObject(); if (wrappedObject instanceof List) { return DefaultListAdapter.adapt((List<Object>) wrappedObject, (RichObjectWrapper) objectWrapper); } else if (wrappedObject instanceof Object[]) { return DefaultArrayAdapter.adapt((Object[]) wrappedObject, (ObjectWrapperAndUnwrapper) objectWrapper); } else if (wrappedObject instanceof Set) { throw new UnsupportedOperationException("Not yet implemented"); } else if (wrappedObject instanceof Collection) { throw new UnsupportedOperationException("Not yet implemented"); } else if (wrappedObject instanceof Iterable) { throw new UnsupportedOperationException("Not yet implemented"); } else { throw new TemplateModelException("Cannot convert bean-wrapped object of type " + (object != null ? object.getClass() : "null") + " to simple sequence"); } } else if (object instanceof TemplateCollectionModel) { TemplateCollectionModel collModel = (TemplateCollectionModel) object; SimpleSequence res = new SimpleSequence(objectWrapper); TemplateModelIterator it = collModel.iterator(); while(it.hasNext()) { res.add(it.next()); } return res; } else { throw new TemplateModelException("Cannot convert object of type " + (object != null ? object.getClass() : "null") + " to simple sequence"); } }
public static void addToSimpleList(SimpleSequence dest, TemplateCollectionModel source) throws TemplateModelException { TemplateModelIterator it = source.iterator(); while(it.hasNext()) { dest.add(it.next()); } }
public static void addToSimpleList(SimpleSequence dest, TemplateSequenceModel source) throws TemplateModelException { for(int i=0; i < source.size(); i++) { dest.add(source.get(0)); } }
public TemplateCollectionModel values() { return new CollectionAndSequence(new SimpleSequence(((Map) object).values(), wrapper)); }
protected boolean complexType(Object value) { return value instanceof freemarker.ext.beans.BeanModel || value instanceof SimpleNumber || value instanceof SimpleSequence; }
@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); }
@SuppressWarnings("rawtypes") @Override public SimpleSequence load(Engine engine, List args) throws Exception { return loadDataModel(engine, args); }
@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; }
@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; }
@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>"); } }