DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building an AWS Integration for Salesforce Image Handling
  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • Reproducibility as a Competitive Edge: Why Minimal Config Beats Complex Install Scripts
  • Building a Card Layout Using CSS Subgrid

Trending

  • Genkit Flows as senro Steps: Extremely Powerful AI Pipelines in Go
  • Why Kotlin or Java Is the Wrong Question For Enterprises
  • When RabbitMQ Accepts a Message but Does Not Route It to a Queue
  • Beyond the Wall of Charts: How Advanced Observability Displaced the Telemetry Dashboard

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

Automated Webservice Code Generation Using FreeMarker

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

By 
Shaamik Mitraa
·
Updated Sep. 13, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
14.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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;
}



}


FreeMarker Web Service Template

Published at DZone with permission of Shaamik Mitraa. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Building an AWS Integration for Salesforce Image Handling
  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • Reproducibility as a Competitive Edge: Why Minimal Config Beats Complex Install Scripts
  • Building a Card Layout Using CSS Subgrid

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook