freemarker.ext.beans.BeansWrapper Java Examples

The following examples show how to use freemarker.ext.beans.BeansWrapper. 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: CodeRenderer.java    From jpa-entity-generator with MIT License 6 votes vote down vote up
/**
 * Renders source code by using Freemarker template engine.
 */
public static String render(String templatePath, RenderingData data) throws IOException, TemplateException {
    Configuration config = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
    StringTemplateLoader templateLoader = new StringTemplateLoader();
    String source;
    try (InputStream is = ResourceReader.getResourceAsStream(templatePath);
         BufferedReader buffer = new BufferedReader(new InputStreamReader(is))) {
        source = buffer.lines().collect(Collectors.joining("\n"));
    }
    templateLoader.putTemplate("template", source);
    config.setTemplateLoader(templateLoader);
    config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    config.setObjectWrapper(new BeansWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
    config.setWhitespaceStripping(true);

    try (Writer writer = new java.io.StringWriter()) {
        Template template = config.getTemplate("template");
        template.process(data, writer);
        return writer.toString();
    }
}
 
Example #2
Source File: TemplateHelper.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected static Map<String, Object> prepareParams(Map<String, ?> parameterValues) {
    Map<String, Object> parameterValuesWithStats = new HashMap<>(parameterValues);
    BeansWrapper beansWrapper = new BeansWrapperBuilder(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS).build();
    parameterValuesWithStats.put("statics", beansWrapper.getStaticModels());

    @SuppressWarnings("unchecked")
    Map<String, Object> params = LazyMap.lazyMap(parameterValuesWithStats, propertyName -> {
        for (String appProperty : AppContext.getPropertyNames()) {
            if (appProperty.replace(".", "_").equals(propertyName)) {
                return AppContext.getProperty(propertyName);
            }
        }
        return null;
    });

    return params;
}
 
Example #3
Source File: FreemarkerStaticModels.java    From cms with Apache License 2.0 6 votes vote down vote up
public static TemplateHashModel useStaticPackage(String packageName) {
	try {
		// BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
		// Create the builder:
	    BeansWrapperBuilder builder = new BeansWrapperBuilder(Configuration.VERSION_2_3_23);
	    // Set desired BeansWrapper configuration properties:
	    builder.setUseModelCache(true);
	    builder.setExposeFields(true);
	    
	    // Get the singleton:
	    BeansWrapper wrapper = builder.build();
	    // You don't need the builder anymore.
		TemplateHashModel staticModels = wrapper.getStaticModels();
		TemplateHashModel fileStatics = (TemplateHashModel) staticModels.get(packageName);
		return fileStatics;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #4
Source File: ObjectWrapperUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
@Override
public ObjectWrapper getWrapper(Environment env) {
    ObjectWrapper curr = env.getObjectWrapper();
    if (curr instanceof ScipioExtendedObjectWrapper) {
        if (curr instanceof ScipioBeansWrapper) {
            if (((BeansWrapper) curr).isSimpleMapWrapper()) {
                return FreeMarkerWorker.getDefaultOfbizSimpleMapWrapper();
            } else {
                return FreeMarkerWorker.getDefaultOfbizWrapper();
            }
        } else {
            return FreeMarkerWorker.getDefaultOfbizSimpleMapWrapper();
        }
    } else {
        return curr;
    }
}
 
Example #5
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
 * any map wrappers that implement <code>WrapperTemplateModel</code>.
 * <p>
 * This method is very permissive: anything that wraps a Map is accepted.
 * Other types of hashes are returned as-is.
 * <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 toSimpleMapRewrapAny(TemplateModel object, ObjectWrapper objectWrapper) throws TemplateModelException {
    if (object instanceof WrapperTemplateModel) {
        // 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 #6
Source File: FreemarkerUtil.java    From junitperf with Apache License 2.0 6 votes vote down vote up
/**
 * define Configuration
 * @param encoding 编码
 * @param isForce 是否强制
 * @return 配置
 */
public static Configuration getConfiguration(String encoding, boolean isForce) {
    if (configuration == null
            || isForce) {
        configuration = new Configuration();
        //编码
        configuration.setEncoding(Locale.getDefault(), encoding);

        //// 设置对象的包装器
        configuration.setObjectWrapper(new DefaultObjectWrapper());

        // 设置异常处理器//这样的话就可以${a.b.c.d}即使没有属性也不会出错
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);

        //默认 FTL map 中不支持非 String 的 key
        configuration.setObjectWrapper(new BeansWrapper());
    }

    return configuration;
}
 
Example #7
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 #8
Source File: LangFtlUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * Adapts a map to a TemplateHashModelEx using an appropriate simple adapter, normally
 * DefaultMapAdapter (or SimpleMapModel for BeansWrapper compatibility).
 * <p>
 * The ObjectWrapper is expected to implement at least ObjectWrapperWithAPISupport.
 * <p>
 * WARN: If impossible, it will duplicate the map using SimpleHash; but because this may result
 * in loss of ordering, a log warning will be printed.
 */
public static TemplateHashModelEx makeSimpleMapAdapter(Map<?, ?> map, ObjectWrapper objectWrapper, boolean permissive) throws TemplateModelException {
    // COMPATIBILITY MODE: check if exactly BeansWrapper, or a class that we know extends it WITHOUT extending DefaultObjectWrapper
    if (objectWrapper instanceof ScipioBeansWrapper || BeansWrapper.class.equals(objectWrapper.getClass())) {
        return new SimpleMapModel(map, (BeansWrapper) objectWrapper);
    } else if (objectWrapper instanceof ObjectWrapperWithAPISupport) {
        return DefaultMapAdapter.adapt(map, (ObjectWrapperWithAPISupport) objectWrapper);
    } else {
        if (permissive) {
            Debug.logWarning("Scipio: adaptSimpleMap: Unsupported Freemarker object wrapper (expected to implement ObjectWrapperWithAPISupport or BeansWrapper); forced to adapt map"
                    + " using SimpleHash; this could cause loss of map insertion ordering; please switch renderer setup to a different ObjectWrapper", module);
            return new SimpleHash(map, objectWrapper);
        } else {
            throw new TemplateModelException("Tried to wrap a Map using an adapter class,"
                    + " but our ObjectWrapper does not implement ObjectWrapperWithAPISupport or BeansWrapper"
                    + "; please switch renderer setup to a different ObjectWrapper");
        }
    }
}
 
Example #9
Source File: ProcessorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testShowItIsPossibleToPassInBeansWrappedObject() throws Exception {
    FileObject root = FileUtil.createMemoryFileSystem().getRoot();
    FileObject fo = FileUtil.createData(root, "simpleObject.txt");
    OutputStream os = fo.getOutputStream();
    String txt = "<#if (classInfo.getMethods().size() > 0) >The size is greater than 0.</#if>";
    os.write(txt.getBytes());
    os.close();       
    
    
    StringWriter w = new StringWriter();
                    
    Map<String,Object> parameters = Collections.<String,Object>singletonMap(
        "classInfo", BeansWrapper.getDefaultInstance().wrap(new ClassInfo())
    );
    apply(fo, w, parameters);
    assertEquals("The size is greater than 0.", w.toString());
}
 
Example #10
Source File: TrasformazioniUtils.java    From govpay with GNU General Public License v3.0 6 votes vote down vote up
private static void _convertFreeMarkerTemplate(String name, byte[] template, Map<String,Object> dynamicMap, Writer writer) throws TrasformazioneException {
	try {
		// ** Aggiungo utility per usare metodi statici ed istanziare oggetti

		// statici
		BeansWrapper wrapper = new BeansWrapper(Configuration.VERSION_2_3_23);
		TemplateModel classModel = wrapper.getStaticModels();
		dynamicMap.put(Costanti.MAP_CLASS_LOAD_STATIC, classModel);

		// newObject
		dynamicMap.put(Costanti.MAP_CLASS_NEW_INSTANCE, new freemarker.template.utility.ObjectConstructor());


		// ** costruisco template
		Template templateFTL = TemplateUtils.buildTemplate(name, template);
		templateFTL.process(dynamicMap, writer);
		writer.flush();

	}catch(Exception e) {
		throw new TrasformazioneException(e.getMessage(),e);
	}
}
 
Example #11
Source File: FtlUtil.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
public static TemplateHashModel generateStaticModel(String packageName) {
    try {
        BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
        TemplateHashModel staticModels = wrapper.getStaticModels();
        TemplateHashModel fileStatics = (TemplateHashModel) staticModels.get(packageName);
        return fileStatics;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #12
Source File: FreemarkerConfigurationBuilder.java    From ogham with Apache License 2.0 5 votes vote down vote up
private static BeansWrapper getBeansWrapper(Configuration configuration) {
	ObjectWrapper objectWrapper = configuration.getObjectWrapper();
	if (objectWrapper instanceof BeansWrapper) {
		return (BeansWrapper) objectWrapper;
	}
	return new BeansWrapperBuilder(configuration.getIncompatibleImprovements()).build();
}
 
Example #13
Source File: PreprocessorImpl.java    From maven-confluence-plugin with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> getModel(Map<String, Object> variables) throws TemplateModelException {
    Map<String, Object> model = new HashMap<>(variables);
    BeansWrapper beans = new BeansWrapper(VERSION);
    model.put("enums", beans.getEnumModels());
    model.put("statics", beans.getStaticModels());
    model.put("Paths", beans.getStaticModels().get(Paths.class.getName()));
    model.put("Files", beans.getStaticModels().get(Files.class.getName()));
    return model;
}
 
Example #14
Source File: ObjectWrapperUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@Override
public ObjectWrapper getWrapper(Environment env) {
    ObjectWrapper wrapper = env.getObjectWrapper();
    // FIXME: Support for extended ScipioDefaultObjectWrapper: it is currently ditched by this code
    if (wrapper instanceof ScipioExtendedBeansWrapper && ((BeansWrapper) wrapper).isSimpleMapWrapper() == simpleMap) {
        return wrapper;
    } else {
        // semi-reliable way to get the language
        Object simpleEncoder = null;
        try {
            simpleEncoder = LangFtlUtil.unwrapOrNull(env.getGlobalVariable("simpleEncoder"));
        } catch (TemplateModelException e) {
            ;
        }
        if (simpleEncoder != null) {
            if (simpleEncoder instanceof UtilCodec.HtmlEncoder) { // heuristic
                return simpleMap ? defaultHtmlExtendedWrapper : defaultHtmlExtendedSimpleMapWrapper;
            } else {
                // TODO: REVIEW: what is this doing for non-html?? HtmlWidget was missing other lang support,
                // that's why not doing it here...
                return simpleMap ? FreeMarkerWorker.getDefaultOfbizWrapper() : FreeMarkerWorker.getDefaultOfbizSimpleMapWrapper();
            }
        } else {
            // FIXME: if we don't know the lang, we have to play it safe and use html
            return simpleMap ? defaultHtmlExtendedWrapper : defaultHtmlExtendedSimpleMapWrapper;
        }
    }
}
 
Example #15
Source File: FreemarkerConfigurer.java    From ogham with Apache License 2.0 5 votes vote down vote up
private static BeansWrapper getBeansWrapper(Configuration configuration) {
	ObjectWrapper objectWrapper = configuration.getObjectWrapper();
	if (objectWrapper instanceof BeansWrapper) {
		return (BeansWrapper) objectWrapper;
	}
	return new BeansWrapperBuilder(configuration.getIncompatibleImprovements()).build();
}
 
Example #16
Source File: DelegatorWrapperModel.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@Override
public TemplateModel wrap(Object object, ScipioObjectWrapper objectWrapper) throws TemplateModelException {
    if (object instanceof Delegator) {
        return new DelegatorWrapperModel(object, (BeansWrapper) objectWrapper);
    }
    return null;
}
 
Example #17
Source File: BaseDocumentationTest.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void loadTemplates() {
  loader = new ClassTemplateLoader(
      BaseDocumentationTest.class,
      "templates"
  );

  configuration = new Configuration(Configuration.getVersion());
  configuration.setDefaultEncoding("UTF-8");
  configuration.setTemplateLoader(loader);
  configuration.setObjectWrapper(new BeansWrapper(Configuration.getVersion()));
  configuration.setNumberFormat("computer");
}
 
Example #18
Source File: FreeMarkerConfigFactory.java    From youran with Apache License 2.0 5 votes vote down vote up
/**
 * 获取freemarker可使用的bean
 *
 * @param clz
 * @return
 */
public TemplateModel getStaticModel(Class clz) {
    BeansWrapper beansWrapper = beansWrapperBuilder.build();
    try {
        return beansWrapper.getStaticModels().get(clz.getName());
    } catch (TemplateModelException e) {
        throw new RuntimeException(e);
    }
}
 
Example #19
Source File: FreeMarkerInlineRenderUtils.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Get the object wrapper from the FreeMarker environment, as a {@link BeansWrapper}.
 *
 * @param env The FreeMarker environment.
 * @return The object wrapper from the FreeMarker environment, type-cast as {@link BeansWrapper}
 * .
 */
public static BeansWrapper getBeansWrapper(Environment env) {
    ObjectWrapper wrapper = env.getObjectWrapper();

    if (!(wrapper instanceof BeansWrapper)) {
        throw new UnsupportedOperationException("FreeMarker environment uses unsupported ObjectWrapper " + wrapper);
    }

    return (BeansWrapper) wrapper;
}
 
Example #20
Source File: SimpleMethodModel.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new simple method model instance.
 *
 * @param objectWrapper the object wrapper to use
 * @param object the object source on which the method will be invoked
 * @param methodName the name of the method to invoke
 */
public SimpleMethodModel(BeansWrapper objectWrapper,
                         Object object,
                         String methodName) {
    Objects.requireNonNull(objectWrapper);
    this.objectWrapper = objectWrapper;
    Objects.requireNonNull(object);
    this.object = object;
    Objects.requireNonNull(methodName);
    this.methodName = methodName;
}
 
Example #21
Source File: TemplateObjectMethods.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
private static BeansWrapper getBeansWrapper(){
	//创建builder:
    BeansWrapperBuilder builder = new BeansWrapperBuilder(Configuration.getVersion());
    // 设置所需的beanswrapper属性
    //builder.setUseModelCache(true);是否启用缓存
    //builder.setExposeFields(true);//是否启用返回类的公共实例。
    builder.setSimpleMapWrapper(true);//模板能使用Map方法
    // Get the singleton:
    BeansWrapper beansWrapper = builder.build();
	
	return beansWrapper;
}
 
Example #22
Source File: TemplateCustomMethods.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
private static BeansWrapper getBeansWrapper(){	
	//创建builder:
    BeansWrapperBuilder builder = new BeansWrapperBuilder(Configuration.getVersion());
    // 设置所需的beanswrapper属性
    //builder.setUseModelCache(true);是否启用缓存
    //builder.setExposeFields(true);//是否启用返回类的公共实例。
    builder.setSimpleMapWrapper(true);//模板能使用Map方法
    // Get the singleton:
    BeansWrapper beansWrapper = builder.build();
	
	return beansWrapper;
}
 
Example #23
Source File: FreemarkerConfig.java    From TrackRay with GNU General Public License v3.0 5 votes vote down vote up
static TemplateHashModel useStaticPackage(String packageName) {
    try {
        BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
        TemplateHashModel staticModels = wrapper.getStaticModels();
        return (TemplateHashModel) staticModels.get(packageName);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #24
Source File: FtlUtil.java    From xmfcn-spring-cloud with Apache License 2.0 5 votes vote down vote up
public static TemplateHashModel generateStaticModel(String packageName) {
    try {
        BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
        TemplateHashModel staticModels = wrapper.getStaticModels();
        TemplateHashModel fileStatics = (TemplateHashModel) staticModels.get(packageName);
        return fileStatics;
    } catch (Exception e) {

    }
    return null;
}
 
Example #25
Source File: SpeedTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testSpeedOfFreemarker() throws Exception {
    Configuration cfg = new Configuration();
    cfg.setDirectoryForTemplateLoading(getWorkDir());
    cfg.setObjectWrapper(new BeansWrapper());
    Template templ = cfg.getTemplate("template.txt");
    
    for(int i = 0; i < whereTo.length; i++) {
        Writer out = new BufferedWriter(new FileWriter(whereTo[i]));
        templ.process(parameters, out);
        out.close();
    }
}
 
Example #26
Source File: MessagesForCostDetailBoxTest.java    From testability-explorer with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();
  Configuration cfg = new Configuration();
  cfg.setTemplateLoader(new ClassPathTemplateLoader(ReportGeneratorProvider.PREFIX));
  BeansWrapper objectWrapper = new DefaultObjectWrapper();
  cfg.setObjectWrapper(objectWrapper);
  ResourceBundleModel messageBundleModel =
      new ResourceBundleModel(ResourceBundle.getBundle("messages"), objectWrapper);
  issueQueue = Lists.newLinkedList();
  template = cfg.getTemplate("costDetailBoxTest.ftl");
  model = new HashMap<String, Object>();
  model.put("message", messageBundleModel);
  model.put("sourceLink", new SourceLinkerModel(new SourceLinker("", "")));
}
 
Example #27
Source File: AboutTestabilityReportGeneratorTest.java    From testability-explorer with Apache License 2.0 5 votes vote down vote up
public void testExample() throws Exception {
  IssuesReporter reporter = new IssuesReporter(new LinkedList<ClassIssues>(), costModel);
  ReportModel model = new AboutTestabilityReport(reporter, new SourceLoader(null) {
    @Override
    public Source load(String name) {
      return new Source(asList(
          new Line(1, "Copyright garbage!"),
          new Line(2, "package com.google.test.metric.example;"),
          new Line(3, "import java.util.List;"),
          new Line(4, "  "),
          new Line(5, "class SumOfPrimes {"),
          new Line(6, "  public void sum() {}"),
          new Line(7, "}")));
    }
  });
  Configuration configuration = new Configuration();
  configuration.setTemplateLoader(new ClassPathTemplateLoader(ReportGeneratorProvider.PREFIX));
  BeansWrapper objectWrapper = new DefaultObjectWrapper();
  configuration.setObjectWrapper(objectWrapper);
  ResourceBundleModel bundleModel = new ResourceBundleModel(getBundle("messages"), objectWrapper);
  model.setMessageBundle(bundleModel);
  generator = new FreemarkerReportGenerator(model, new PrintStream(out),
          "about/Report.html", configuration);
  generator.printHeader();
  generator.addClassCost(new ClassCost("com.google.test.metric.example.Lessons.SumOfPrimes1",
      asList(new MethodCost("", "foo()", 1, false, false, false))));
  generator.printFooter();

  String text = out.toString();
  assertTrue(text, text.contains(">SumOfPrimes1<"));
  assertTrue(text, text.contains(">Lessons<"));
  assertTrue(text, text.contains("sum"));
  assertFalse(text, text.contains("Copyright"));
  assertFalse(text, text.contains("package com.google"));
  assertFalse(text, text.contains("import java.util"));
  assertFalse(text, text.contains("<span class=\"nocode\">4:"));
}
 
Example #28
Source File: SpringBeansTemplateHashModelEx.java    From ogham with Apache License 2.0 4 votes vote down vote up
public SpringBeansTemplateHashModelEx(ApplicationContext applicationContext, BeansWrapper beansWrapper) {
	super();
	this.applicationContext = applicationContext;
	this.beansWrapper = beansWrapper;
}
 
Example #29
Source File: ReportGeneratorProvider.java    From testability-explorer with Apache License 2.0 4 votes vote down vote up
/**
 * Method to allow retaining a handle on preconfigured model objects.
 *
 * @param costModel Cost Model for the {@link ReportGenerator}
 * @param reportModel Can be {@code null} if {@link ReportFormat} is not
 *    {@link ReportFormat#html} or {@link ReportFormat#about}
 * @param sourceLoader Source Loader used by {@link ReportFormat#source} reports.
 * @return a ready to use {@link ReportGenerator}
 */
public ReportGenerator build(CostModel costModel, ReportModel reportModel,
    SourceLoader sourceLoader) {
  SourceLinker linker = new SourceLinker(
      options.getSrcFileLineUrl(), options.getSrcFileUrl());
  Configuration cfg = new Configuration();
  cfg.setTemplateLoader(new ClassPathTemplateLoader(PREFIX));
  BeansWrapper objectWrapper = new DefaultObjectWrapper();
  cfg.setObjectWrapper(objectWrapper);
  ResourceBundleModel bundleModel = new ResourceBundleModel(getBundle("messages"),
      objectWrapper);

  ReportGenerator report;
  switch (reportFormat) {
    case summary:
      report = new TextReportGenerator(out, costModel, options);
      break;
    case html:
      reportModel.setMessageBundle(bundleModel);
      reportModel.setSourceLinker(new SourceLinkerModel(linker));
      report = new FreemarkerReportGenerator(reportModel, out,
          FreemarkerReportGenerator.HTML_REPORT_TEMPLATE, cfg);
      break;
    case props:
      report = new PropertiesReportGenerator(out, costModel);
      break;
    case source:
      GradeCategories gradeCategories = new GradeCategories(options.getMaxExcellentCost(),
          options.getMaxAcceptableCost());
      report = new SourceReportGenerator(gradeCategories, sourceLoader,
          new File("te-report"), costModel, new Date(), options.getWorstOffenderCount(), cfg);
      break;
    case xml:
      XMLSerializer xmlSerializer = new XMLSerializer();
      xmlSerializer.setOutputByteStream(out);
      OutputFormat format = new OutputFormat();
      format.setIndenting(true);
      xmlSerializer.setOutputFormat(format);
      report = new XMLReportGenerator(xmlSerializer, costModel, options);
      break;
    case about:
      reportModel.setMessageBundle(bundleModel);
      reportModel.setSourceLinker(new SourceLinkerModel(linker));
      report = new FreemarkerReportGenerator(reportModel, out, "about/Report.html", cfg);
      break;
    default:
      throw new IllegalStateException("Unknown report format " + reportFormat);
  }
  return report;
}
 
Example #30
Source File: LazySpringBeanAccessModel.java    From ogham with Apache License 2.0 4 votes vote down vote up
public LazySpringBeanAccessModel(ApplicationContext applicationContext, BeansWrapper beansWrapper, String name) {
	super();
	this.applicationContext = applicationContext;
	this.beansWrapper = beansWrapper;
	this.name = name;
}