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

How does AI transform chaos engineering from an experiment into a critical capability? Learn how to effectively operationalize the chaos.

Data quality isn't just a technical issue: It impacts an organization's compliance, operational efficiency, and customer satisfaction.

Are you a front-end or full-stack developer frustrated by front-end distractions? Learn to move forward with tooling and clear boundaries.

Developer Experience: Demand to support engineering teams has risen, and there is a shift from traditional DevOps to workflow improvements.

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
  • How To Build AI-Powered Prompt Templates Using the Salesforce Prompt Builder

Trending

  • Safeguarding Cloud Databases: Best Practices and Risks Engineers Must Avoid
  • Kung Fu Commands: Shifu Teaches Po the Command Pattern with Java Functional Interfaces
  • AI Agents in PHP with Model Context Protocol
  • Integrating Apache Spark With Drools: A Loan Approval Demo

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.3K 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
  • How To Build AI-Powered Prompt Templates Using the Salesforce Prompt Builder

Partner Resources

×

Comments

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
  • [email protected]

Let's be friends: