Generate POJO or Utility using Freemarker

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.javahunter.taher.utility;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import java.io.File;
import java.io.FileOutputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;

/**
 *
 * @author TaherT
 */
public class DTOGenerator {

    public static void main(String[] args) throws Exception {
        String[] springConfig = {"/database.xml"};
        ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);
        JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class);
        String[] tables = new String[]{"student"};//Add Comma seperated Tables to generate code.
        genDTO(tables,jdbcTemplate);//Generate Data Transfer Object from mysql Table
        genXML(tables, jdbcTemplate);//Generate XML required for spring batch configs
    }
    
    /**
     * @param args the command line arguments
     */
    public static void genDTO(String[] tables, JdbcTemplate jdbcTemplate) throws Exception {
        for (int i = 0; i < tables.length; i++) {
            String tableName = tables[i];
            String className = tables[i];
            String modelData = generateDTOCode(tableName, className, jdbcTemplate);
            File file = new File(DTOGenerator.class.getResource("").getFile().replace("target/classes", "src/main/java").replace("/utility/", "/dto/") + StringUtils.capitalize(className) + ".java");
            FileOutputStream fop = new FileOutputStream(file);
            if (!file.exists()) {
                file.createNewFile();
            }
            byte[] contentInBytes = modelData.getBytes();
            fop.write(contentInBytes);
            fop.flush();
            fop.close();
        }
    }

    public static void genXML(String[] tables, JdbcTemplate jdbcTemplate) throws Exception {
        Map<String, Object> datamodel = new HashMap<String, Object>();
        datamodel.put("tableNames", tables);
        Map<String, String> query = new HashMap<>();
        for (int i = 0; i < tables.length; i++) {
            query.put(tables[i], InsertStatementGenerator.insertStatement(tables[i], jdbcTemplate));
        }
        datamodel.put("tableQuery", query);
        String modelData = freemarkerDo(datamodel, "xml.ftl");
        try {
            File file = new File("D:/testfile.xml");
            FileOutputStream fop = new FileOutputStream(file);
            if (!file.exists()) {
                file.createNewFile();
            }
            byte[] contentInBytes = modelData.getBytes();
            fop.write(contentInBytes);
            fop.flush();
            fop.close();
            System.out.println("INFO Read Me : Please open " + file + " and follow instructions in comments");
        } catch (java.io.FileNotFoundException e) {
            System.out.println("ERROR : " + e + " Configure file path and file name for XML generation");
        }
    }    

    public static String generateDTOCode(String modelName, String className, JdbcTemplate jdbcTemplate) {
        try {
            Map<String, Object> datamodel = new HashMap<String, Object>();
            datamodel.put("className", className);
            datamodel.put("columns", jdbcTemplate.queryForList("SELECT COLUMN_NAME,"
                    + "REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(DATA_TYPE,'varchar','String'),'smallint','int'),'bigint','Long'),'bit','boolean'),"
                    + "'char','String'),'datetime','Date'),'tinyint','boolean'),'text','String'),'mediumint','int'),'date','Date'),'mediumtext','String'),'longtext','String'),'enum','String'),'mediumString','String'),'longString','String'),'longblob','byte[]') as DATA_TYPE,COLUMN_KEY,IS_NULLABLE "
                    + "FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema='school' and table_name = '" + modelName + "'"));
            return freemarkerDo(datamodel, "dto.ftl");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String freemarkerDo(Map datamodel, String template) throws Exception {
        Configuration cfg = new Configuration();
        System.out.println(DTOGenerator.class.getResource("").getFile().replace("target/classes", "src/main/java"));
        cfg.setDirectoryForTemplateLoading(new File(DTOGenerator.class.getResource("").getFile().replace("target/classes", "src/main/java")));
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        Template temp = cfg.getTemplate(template);
        StringWriter writer = new StringWriter();
        temp.process(datamodel, writer);
        return writer.toString();
    }
}
package com.javahunter.taher.dto;
import java.util.Date;
/**
 * @author TaherT
 */


public class ${className?cap_first} {

    <#list columns as column>        
    private ${column.DATA_TYPE} ${column.COLUMN_NAME};
    </#list>
    <#list columns as column>        
    public ${column.DATA_TYPE} get${column.COLUMN_NAME?cap_first}(){
        return ${column.COLUMN_NAME};
    }
    public void set${column.COLUMN_NAME?cap_first}(${column.DATA_TYPE} ${column.COLUMN_NAME}){        
        this.${column.COLUMN_NAME} = <#if (column.COLUMN_NAME=='oldID')>${columns[0].COLUMN_NAME}<#else>${column.COLUMN_NAME}</#if>;
    } 
    </#list>
    @Override
    public String toString() {
        return "${className?cap_first} : " + "${columns[0].COLUMN_NAME}=" + ${columns[0].COLUMN_NAME} + "}";
    }    
}

<!--To be added in readquery.properties file at EOF-->
<#list tableNames as tableName>        
read.${tableName}=select * from ${tableName}
</#list>


<!--To be added in xmlpath.properties-->
<#list tableNames as tableName>        
xml.${tableName}=${"@@@{jobParameters['projectID_folder']}"?replace("@@@", "$")}/${tableName}.xml
</#list>


<!--To be added in context.xml with bean id="projectUnmarshaller" between <util:map></util:map> at EOF-->
<#list tableNames as tableName>
<entry key="${tableName}" value="com.javahunter.taher.dto.${tableName?cap_first}" />
</#list>


<!--To be added in db-qmetry-reader.xml at the EOF-->
<#list tableNames as tableName>
<#assign readplacer = "@@@{read.${tableName}}"?replace("@@@", "$")>
<bean id="${tableName}DBReader" class="org.springframework.batch.item.database.JdbcCursorItemReader" scope="step">
    <property name="dataSource" ref="dataSource" />    
    <property name="sql" value="${readplacer}"/>
    <property name="rowMapper">
        <bean class="org.springframework.jdbc.core.BeanPropertyRowMapper" >
            <property name="mappedClass" value="com.javahunter.taher.dto.${tableName?cap_first}"></property>
        </bean>
    </property>
</bean> 
</#list>


<!--To be added in job-qmetry-backup.xml. If table is having heavy data than it should be configured above split(parallelTables) step in sequence remove generated <flow> tag. If table is mid/low than add inside split(parallelTables) at EOF-->
<#list tableNames as tableName>
<flow>
    <step id="stepBak${tableName?cap_first}">
        <tasklet>
            <chunk reader="${tableName}DBReader" writer="${tableName}XMLWriter"
                  commit-interval="100" />
        </tasklet>            
    </step>
</flow>
</#list>


<!--To be added in xml-qmetry-writer.xml at EOF-->
<#list tableNames as tableName>
<#assign xmlplacer = "@@@{qmetry.drivelater}@@@{qmetry.docsto}@@@{xml.${tableName}}"?replace("@@@", "$")>
<bean id="${tableName}XMLWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter" scope="step">    
    <property name="resource" value="file:${xmlplacer}" />
    <property name="marshaller" ref="projectUnmarshaller" />
    <property name="rootTagName" value="${tableName}s" />
</bean> 
</#list>


<!--To be added in writequery.properties at EOF-->
<#list tableNames as tableName>
write.${tableName}= ${tableQuery[tableName]}
</#list>


<!--To be added in xml-qmetry-reader.xml at EOF-->
<#list tableNames as tableName>
<#assign xmlplacer = "@@@{qmetry.drivelater}@@@{qmetry.docsto}@@@{xml.${tableName}}"?replace("@@@", "$")>
<bean id="${tableName}XMLReader" class="org.springframework.batch.item.xml.StaxEventItemReader" scope="step">
    <property name="resource" value="file:${xmlplacer}" />
    <property name="fragmentRootElementName" value="${tableName}" />
    <property name="unmarshaller" ref="projectUnmarshaller"/>                    
</bean>
</#list>


<!--To be added in job-qmetry-restore.xml; need to check table_batch.txt in trunk and find the position where to be placed according to its parent table-->
<#list tableNames as tableName>
<step id="stepRes${tableName?cap_first}">
    <tasklet transaction-manager="transactionManager">
        <chunk reader="${tableName}XMLReader" writer="${tableName}DBWriter"
               commit-interval="100" />
    </tasklet>                                
</step>
</#list>


<!--To be added in db-qmetry-writer.xml at EOF-->
<#list tableNames as tableName>
<#assign writeplacer = "@@@{write.${tableName}}"?replace("@@@", "$")>
<bean id="${tableName}DBWriter" class="org.springframework.batch.item.database.JdbcBatchItemWriter" scope="step">
    <property name="dataSource" ref="dataSource" />
    <property name="sql" value="${writeplacer}"/>
    <property name="itemSqlParameterSourceProvider">
        <bean class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider" />
    </property>
</bean>
</#list>
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.javahunter.taher.utility;

import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 *
 * @author taher.tinwala
 */
public class InsertStatementGenerator {

    public static void main(String[] args) throws Exception{
        System.out.println(insertStatement("project",null));
    }

    public static String insertStatement(String modelName,JdbcTemplate jdbcTemplate) throws Exception {
        StringBuilder query = new StringBuilder();
        List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT COLUMN_NAME,"
                + "REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(DATA_TYPE,'varchar','String'),'smallint','int'),'bigint','Long'),'bit','boolean'),"
                + "'char','String'),'datetime','Date'),'tinyint','boolean') as DATA_TYPE,COLUMN_KEY "
                + "FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema='"+jdbcTemplate.getDataSource().getConnection().getCatalog()+"' and table_name = '" + modelName + "' AND COLUMN_KEY <> 'PRI'");
        query.append("insert into ");
        query.append(modelName);
        query.append(" (");
        for (Map<String, Object> map : list) {
//            if(!map.get("COLUMN_KEY").toString().equals("PRI")){
                query.append(map.get("COLUMN_NAME"));
                query.append(",");
//            }
            
        }
        query.delete(query.length()-1, query.length());
        query.append(")");
        query.append(" values (");
        for (Map<String, Object> map : list) {
//            if(!map.get("COLUMN_KEY").toString().equals("PRI")){
                query.append(":");
                query.append(map.get("COLUMN_NAME"));
                query.append(",");
//            }            
        }
        query.delete(query.length()-1, query.length());
        query.append(")");
        return query.toString();
    }
}

Advertisements
This entry was posted in freemarker, Spring batch and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s