Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Automated Webservice Code Generation Using FreeMarker

DZone's Guide to

Automated Webservice Code Generation Using FreeMarker

How to use FreeMarker to automatically generate a new file based on existing code.

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

Sometimes we need to generate template source code upon which to add modifications. It saves a lot of time for developers. Without automated generation of source code, developers need to create source files and require methods repetitively. With automation, tools will generate files for them, developers only have to put their logic in generated files.

Say for all JPA entities in a project, basic CRUD operations will be exposed as web service. Either the developer creates a web service manually or we can create the same thing with a tool.

In this article, will generate a simple Java web service using FreeMarker. Later, you can modify the web service to fit it in your project.

FreeMarker is a Java template engine which will dynamically create an output. To generate an Output, FreeMarker needs an FTL file (FreeMarker template language), where instructions and placeholder are written, and a Java file where you provide the actual data to replace the placeholder. FreeMarker combines them and generates the desired Output.

Image title

FreeMarker output generation process

Benefits of FreeMarker (taken from the FreeMarker website):

  1. Powerful template language: Conditional blocks, iterations, assignments, string, and arithmetic operations and formatting, macros, and functions, including other templates, escaping by default (optional), and many more.

    Multipurpose and lightweight: Zero dependencies, any output format, can load templates from any place (pluggable), many configuration options

    Internationalization/localization-aware: Locale sensitive number and date/time formatting, localized template variations.

    XML processing capabilities: Drop XML DOM-s into the data-model and traverse them, or even process them declaratively

    Versatile data-model: Java objects are exposed to the template as a tree of variables through pluggable adapters, which decides how the template sees them.

To generate a Java Webservice file using FreeMarker following steps are needed.

  1. Create an FTL file. Here we define commands for an output-defined place holder, which will be replaced by the actual value of a Java object.

    ${package}
    
    import javax.jws.*;
    
    @WebService()
    public class ${name}
    {
    
    @WebMethod()
    public ${return} ${methodname}(${params})
    {
       ${body}
       return ${val}
    }
    
    }
  2.  Next, create a Java file, which will provide data for the placeholder, and states the location where the output will be saved. To run this file, you  need to download freemarker*.jar.

package com.example;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class WebServiceGenerator {

private static WebServiceGenerator engine = new WebServiceGenerator();
private Template template=null;
Map<String, Object> dataMap = new HashMap<String, Object>();

private WebServiceGenerator() 
{
init();
}

private void init() 
{

Configuration cfg = new Configuration();
try {
template = cfg.getTemplate("src/javaGen.ftl");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public static WebServiceGenerator get()
{
return engine;
}

public WebServiceGenerator buildData()
{
dataMap.put("package", this.getClass().getPackage()+";");
dataMap.put("name", "HelloWorldservice");
dataMap.put("return", "String");
dataMap.put("methodname", "hello");
dataMap.put("params", "String name");
dataMap.put("body", "String res= \"Hi\" + name;\n System.out.println(res);");
dataMap.put("val", "res;");
System.out.println("Preparing Data");



return engine;
}

public void  writeFile()
{
Writer file=null;
try {
file = new FileWriter (new File("C:\\installer\\HelloWorldservice.java"));
template.process(dataMap, file);
file.flush();
System.out.println("Success");

}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{

try {
file.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}




public static void main(String[] args) {

WebServiceGenerator.get().buildData().writeFile();

}

}


Output:

package com.example;

import javax.jws.*;

@WebService()
public class HelloWorldservice
{

@WebMethod()
public String hello(String name)
{
   String res= "Hi" + name;
 System.out.println(res);
return res;
}



}


Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:
source code ,java ,automation ,objects

Published at DZone with permission of Shamik Mitra, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}