/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.shardingsphere.example.generator;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.Objects;

/**
 * Example generate engine.
 */
public final class ExampleGenerateEngine {
    
    private static final Configuration TEMPLATE_CONFIG = new Configuration(Configuration.VERSION_2_3_31);
    
    private static final String DATA_MODEL_PATH = "/data-model/data-model.yaml";
    
    private static final String OUTPUT_PATH = "./examples/shardingsphere-sample/shardingsphere-jdbc-sample/shardingsphere-jdbc-${mode}-example"
            + "<#assign package=\"\">"
            + "<#if feature?split(\",\")?size gt 1>"
            + "<#assign package=\"mixed\">"
            + "<#else>"
            + "<#assign package=feature />"
            + "</#if>"
            + "/shardingsphere-jdbc-${mode}-${transaction}-example/shardingsphere-jdbc-${mode}-${transaction}-${package}-example"
            + "/shardingsphere-jdbc-${mode}-${transaction}-${package}-${framework}-example/src/main/";
    
    private static final String JAVA_CLASS_PATH = "java/org/apache/shardingsphere/example/"
            + "<#assign package=\"\">"
            + "<#if feature?split(\",\")?size gt 1>"
            + "<#assign package=\"mixed\">"
            + "<#else>"
            + "<#assign package=feature?replace('-', '/') />"
            + "</#if>"
            + "${package}/${framework?replace('-', '/')}";
    
    private static final String RESOURCES_PATH = "resources";
    
    private static Map<String, String> javaClassTemplateMap;
    
    private static Map<String, String> resourceTemplateMap;
    
    static {
        try {
            TEMPLATE_CONFIG.setDirectoryForTemplateLoading(new File(Objects.requireNonNull(ExampleGenerateEngine.class.getClassLoader().getResource("template")).getFile()));
            TEMPLATE_CONFIG.setDefaultEncoding("UTF-8");
        } catch (final IOException ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * Generate file.
     * 
     * @param args args
     * @throws IOException IO exception
     * @throws TemplateException template exception
     */
    @SuppressWarnings("unchecked")
    public static void main(final String[] args) throws IOException, TemplateException {
        try (InputStream input = ExampleGenerateEngine.class.getResourceAsStream(DATA_MODEL_PATH)) {
            Map<String, String> dataModel = new Yaml().loadAs(input, Map.class);
            fillTemplateMap(dataModel);
            generateJavaClasses(dataModel);
            generateResourcesFile(dataModel);
        }
    }
    
    private static void fillTemplateMap(final Map<String, String> dataModel) {
        javaClassTemplateMap = ExampleTemplateFactory.getJavaClassTemplateMap(dataModel);
        resourceTemplateMap = ExampleTemplateFactory.getResourceTemplateMap(dataModel);
    }
    
    private static void generateJavaClasses(final Map<String, String> dataModel) throws IOException, TemplateException {
        String outputPath = processString(dataModel, OUTPUT_PATH + JAVA_CLASS_PATH);
        for (String each : javaClassTemplateMap.keySet()) {
            processFile(dataModel, each, outputPath + "/" + javaClassTemplateMap.get(each));
        }
    }
    
    private static void generateResourcesFile(final Map<String, String> dataModel) throws IOException, TemplateException {
        String outputPath = processString(dataModel, OUTPUT_PATH + RESOURCES_PATH);
        for (String each : resourceTemplateMap.keySet()) {
            processFile(dataModel, each, outputPath + "/" + resourceTemplateMap.get(each));
        }
    }
    
    private static String processString(final Object model, final String templateString) throws IOException, TemplateException {
        try (StringWriter result = new StringWriter();
             StringReader reader = new StringReader(templateString)) {
            new Template("string", reader, TEMPLATE_CONFIG).process(model, result);
            return result.toString();
        }
    }
    
    private static void processFile(final Object model, final String templateFile, final String outputFile) throws IOException, TemplateException {
        try (Writer writer = new FileWriter(outputFile)) {
            TEMPLATE_CONFIG.getTemplate(templateFile).process(model, writer);
        }
    }
}

@@ -1116,37 +1116,8 @@
 am;%0A
-import java.io.StringReader;%0A
 impo
@@ -1186,16 +1186,44 @@
 il.Map;%0A
+import java.util.Map.Entry;%0A
 import j
@@ -2603,139 +2603,8 @@
    %0A
-    private static Map%3CString, String%3E javaClassTemplateMap;%0A    %0A    private static Map%3CString, String%3E resourceTemplateMap;%0A    %0A
     
@@ -3437,256 +3437,31 @@
     
-fillTemplateMap(dataModel);%0A            generateJavaClasses(dataModel);%0A            generateResourcesFile(dataModel);%0A        %7D%0A    %7D%0A    %0A    private static void fillTemplateMap(final Map%3CString, String%3E dataModel) %7B%0A        javaClassTemplateMap =
+generateFile(dataModel,
  Exa
@@ -3518,39 +3518,63 @@
 del)
-;%0A        resourceTemplateMap =
+, JAVA_CLASS_PATH);%0A            generateFile(dataModel,
  Exa
@@ -3626,17 +3626,44 @@
 taModel)
-;
+, RESOURCES_PATH);%0A        %7D
 %0A    %7D%0A 
@@ -3702,19 +3702,12 @@
 rate
-JavaClasses
+File
 (fin
@@ -3742,390 +3742,80 @@
 odel
-) throws IOException, TemplateException %7B%0A        String outputPath = processString(dataModel, OUTPUT_PATH + JAVA_CLASS_PATH);%0A        for (String each : javaClassTemplateMap.keySet()) %7B%0A            processFile(dataModel, each, outputPath + %22/%22 + javaClassTemplateMap.get(each));%0A        %7D%0A    %7D%0A    %0A    private static void generateResourcesFile(final Map%3CString, String%3E dataModel
+, final Map%3CString, String%3E templateMap, final String outputRelativePath
 ) th
@@ -3880,29 +3880,28 @@
 tPath = 
-processString
+generatePath
 (dataMod
@@ -3922,61 +3922,73 @@
 H + 
-RESOURCES_PATH);%0A        for (String each : resourceT
+outputRelativePath);%0A        for (Entry%3CString, String%3E entry : t
 empl
@@ -3994,18 +3994,20 @@
 lateMap.
-k
 e
+ntr
 ySet()) 
@@ -4044,19 +4044,29 @@
 Model, e
-ach
+ntry.getKey()
 , output
@@ -4082,36 +4082,23 @@
 %22 + 
-resourceTemplateMap.get(each
+entry.getValue(
 ));%0A
@@ -4148,21 +4148,20 @@
 ing 
-processString
+generatePath
 (fin
@@ -4190,30 +4190,28 @@
  String 
-templateString
+relativePath
 ) throws
@@ -4301,77 +4301,8 @@
 er()
-;%0A             StringReader reader = new StringReader(templateString)
 ) %7B%0A
@@ -4331,23 +4331,27 @@
 te(%22
-string%22, reader
+path%22, relativePath
 , TE

Refactor ExampleGenerateEngine.generateJavaClasses and generateResourcesFile (#14933)