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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Building an AWS Integration for Salesforce Image Handling
  • 50+ Top Angular Interview Questions and Answers
  • Build a Web Application Based on Your Excel Files
  • Automated Bug Fixing: From Templates to AI Agents

Trending

  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  • Power BI Embedded Analytics — Part 2: Power BI Embedded Overview
  • Integrating Security as Code: A Necessity for DevSecOps
  • Understanding and Mitigating IP Spoofing Attacks

Automated Webservice Code Generation Using FreeMarker

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

By 
Shamik Mitra user avatar
Shamik Mitra
·
Updated Sep. 13, 16 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
14.2K Views

Join the DZone community and get the full member experience.

Join For Free

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 Shamik Mitra, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Building an AWS Integration for Salesforce Image Handling
  • 50+ Top Angular Interview Questions and Answers
  • Build a Web Application Based on Your Excel Files
  • Automated Bug Fixing: From Templates to AI Agents

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!