Search in sources :

Example 1 with GenerateException

use of com.laytonsmith.tools.docgen.DocGenTemplates.Generator.GenerateException in project CommandHelper by EngineHub.

the class DocGenTemplates method main.

public static void main(String[] args) throws Exception {
    Implementation.setServerType(Implementation.Type.SHELL);
    Map<String, Generator> g = new HashMap<>();
    g.put("A", new Generator() {

        @Override
        public String generate(String... args) throws GenerateException {
            return "(" + args[0] + ")";
        }
    });
    g.put("B", new Generator() {

        @Override
        public String generate(String... args) throws GenerateException {
            return "<text>";
        }
    });
    g.putAll(DocGenTemplates.GetGenerators());
    String t = "<%SYNTAX|html|\n<%MySQL_CREATE_TABLE_QUERY%>\n%>";
    StreamUtils.GetSystemOut().println(DoTemplateReplacement(t, g));
}
Also used : HashMap(java.util.HashMap) CString(com.laytonsmith.core.constructs.CString) GenerateException(com.laytonsmith.tools.docgen.DocGenTemplates.Generator.GenerateException)

Example 2 with GenerateException

use of com.laytonsmith.tools.docgen.DocGenTemplates.Generator.GenerateException in project CommandHelper by EngineHub.

the class SiteDeploy method getStandardGenerators.

private Map<String, Generator> getStandardGenerators() {
    Map<String, Generator> g = new HashMap<>();
    g.put("resourceBase", new Generator() {

        @Override
        public String generate(String... args) {
            return SiteDeploy.this.resourceBase;
        }
    });
    g.put("branding", new Generator() {

        @Override
        public String generate(String... args) {
            return Implementation.GetServerType().getBranding();
        }
    });
    g.put("siteRoot", new Generator() {

        @Override
        public String generate(String... args) {
            return SiteDeploy.this.siteBase;
        }
    });
    g.put("docsBase", new Generator() {

        @Override
        public String generate(String... args) {
            return SiteDeploy.this.docsBase;
        }
    });
    g.put("apiJsonVersion", new Generator() {

        @Override
        public String generate(String... args) throws GenerateException {
            return apiJsonVersion;
        }
    });
    /**
     * The cacheBuster template is meant to make it easier to deal with caching of resources. The template allows
     * you to specify the resource, and it creates a path to the resource using resourceBase, but it also appends a
     * hash of the file, so that as the file changes, so does the hash (using a ?v=hash query string). Most
     * resources live in /siteDeploy/resources/*, and so the shorthand is to use
     * %%cacheBuster|path/to/resource.css%%. However, this isn't always correct, because resources can live all over
     * the place. In that case, you should use the following format:
     * %%cacheBuster|/absolute/path/to/resource.css|path/to/resource/in/html.css%%
     */
    g.put("cacheBuster", new Generator() {

        @Override
        public String generate(String... args) {
            String resourceLoc = SiteDeploy.this.resourceBase + args[0];
            String loc = args[0];
            if (!loc.startsWith("/")) {
                loc = "/siteDeploy/resources/" + loc;
            } else {
                resourceLoc = SiteDeploy.this.resourceBase + args[1];
            }
            String hash = "0";
            try {
                InputStream in = SiteDeploy.class.getResourceAsStream(loc);
                if (in == null) {
                    throw new RuntimeException("Could not find " + loc + " in resources folder for cacheBuster template");
                }
                hash = getLocalMD5(in);
            } catch (IOException ex) {
                Logger.getLogger(SiteDeploy.class.getName()).log(Level.SEVERE, null, ex);
            }
            return resourceLoc + "?v=" + hash;
        }
    });
    final Generator learningTrailGen = new Generator() {

        @Override
        public String generate(String... args) {
            String learning_trail = StreamUtils.GetString(SiteDeploy.class.getResourceAsStream("/siteDeploy/LearningTrail.json"));
            List<Map<String, List<Map<String, String>>>> ret = new ArrayList<>();
            @SuppressWarnings("unchecked") List<Map<String, List<Object>>> lt = (List<Map<String, List<Object>>>) JSONValue.parse(learning_trail);
            for (Map<String, List<Object>> l : lt) {
                for (Map.Entry<String, List<Object>> e : l.entrySet()) {
                    String category = e.getKey();
                    List<Map<String, String>> catInfo = new ArrayList<>();
                    for (Object ll : e.getValue()) {
                        Map<String, String> pageInfo = new LinkedHashMap<>();
                        String page = null;
                        String name = null;
                        if (ll instanceof String) {
                            name = page = (String) ll;
                        } else if (ll instanceof Map) {
                            @SuppressWarnings("unchecked") Map<String, String> p = (Map<String, String>) ll;
                            if (p.entrySet().size() != 1) {
                                throw new RuntimeException("Invalid JSON for learning trail");
                            }
                            for (Map.Entry<String, String> ee : p.entrySet()) {
                                page = ee.getKey();
                                name = ee.getValue();
                            }
                        } else {
                            throw new RuntimeException("Invalid JSON for learning trail");
                        }
                        assert page != null && name != null;
                        boolean exists;
                        if (page.contains(".")) {
                            // We can't really check this, because it might be a synthetic page, like
                            // api.json. So we just have to set it to true.
                            exists = true;
                        } else {
                            exists = SiteDeploy.class.getResourceAsStream("/docs/" + page) != null;
                        }
                        pageInfo.put("name", name);
                        pageInfo.put("page", page);
                        pageInfo.put("category", category);
                        pageInfo.put("exists", Boolean.toString(exists));
                        catInfo.add(pageInfo);
                    }
                    Map<String, List<Map<String, String>>> m = new HashMap<>();
                    m.put(category, catInfo);
                    ret.add(m);
                }
            }
            return JSONValue.toJSONString(ret);
        }
    };
    g.put("js_string_learning_trail", new Generator() {

        @Override
        public String generate(String... args) throws GenerateException {
            String g = learningTrailGen.generate(args);
            g = g.replaceAll("\\\\", "\\\\");
            g = g.replaceAll("\"", "\\\\\"");
            return g;
        }
    });
    g.put("learning_trail", learningTrailGen);
    /**
     * If showTemplateCredit is false, then this will return "display: none;" otherwise, it will return an empty
     * string.
     */
    g.put("showTemplateCredit", new Generator() {

        @Override
        public String generate(String... args) throws GenerateException {
            return showTemplateCredit ? "" : "display: none;";
        }
    });
    return g;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) GenerateException(com.laytonsmith.tools.docgen.DocGenTemplates.Generator.GenerateException) LinkedHashMap(java.util.LinkedHashMap) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) Generator(com.laytonsmith.tools.docgen.DocGenTemplates.Generator)

Example 3 with GenerateException

use of com.laytonsmith.tools.docgen.DocGenTemplates.Generator.GenerateException in project CommandHelper by EngineHub.

the class SiteDeploy method deployResources.

/**
 * Pages deployed: All pages under the siteDeploy/resources folder. They are transferred as is, including
 * recursively looking through the folder structure. Binary files are also supported. index.js (after template
 * replacement)
 */
private void deployResources() {
    generateQueue.submit(new Runnable() {

        @Override
        public void run() {
            try {
                File root = new File(SiteDeploy.class.getResource("/siteDeploy/resources").toExternalForm());
                ZipReader reader = new ZipReader(root);
                Queue<File> q = new LinkedList<>();
                q.addAll(Arrays.asList(reader.listFiles()));
                while (q.peek() != null) {
                    ZipReader r = new ZipReader(q.poll());
                    if (r.isDirectory()) {
                        q.addAll(Arrays.asList(r.listFiles()));
                    } else {
                        String fileName = r.getFile().getAbsolutePath().replaceFirst(Pattern.quote(reader.getFile().getAbsolutePath()), "");
                        writeFromStream(r.getInputStream(), "resources" + fileName);
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(SiteDeploy.class.getName()).log(Level.SEVERE, null, ex);
            }
            String index_js = StreamUtils.GetString(SiteDeploy.class.getResourceAsStream("/siteDeploy/index.js"));
            try {
                writeFromString(DocGenTemplates.DoTemplateReplacement(index_js, getStandardGenerators()), "resources/js/index.js");
            } catch (Generator.GenerateException ex) {
                Logger.getLogger(SiteDeploy.class.getName()).log(Level.SEVERE, "GenerateException in /siteDeploy/index.js", ex);
            }
            currentGenerateTask.addAndGet(1);
        }
    });
    totalGenerateTasks.addAndGet(1);
}
Also used : ZipReader(com.laytonsmith.PureUtilities.ZipReader) IOException(java.io.IOException) GenerateException(com.laytonsmith.tools.docgen.DocGenTemplates.Generator.GenerateException) File(java.io.File) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Queue(java.util.Queue)

Example 4 with GenerateException

use of com.laytonsmith.tools.docgen.DocGenTemplates.Generator.GenerateException in project CommandHelper by EngineHub.

the class DocGenTemplates method DoTemplateReplacement.

/**
 * A utility method to replace all template methods in a generic template string.
 *
 * @param template The template string on which to perform the replacements
 * @param generators The list of String-Generator entries, where the String is the template name, and the Generator
 * is the replacement to use.
 * @return
 */
public static String DoTemplateReplacement(String template, Map<String, Generator> generators) throws GenerateException {
    try {
        if (Implementation.GetServerType() != Implementation.Type.BUKKIT) {
            Prefs.init(null);
        }
    } catch (IOException ex) {
        Logger.getLogger(DocGenTemplates.class.getName()).log(Level.SEVERE, null, ex);
    }
    ClassDiscovery.getDefaultInstance().addDiscoveryLocation(ClassDiscovery.GetClassContainer(DocGenTemplates.class));
    // Find all the <%templates%> (which are the same as %%templates%%, but are nestable)
    int templateStack = 0;
    StringBuilder tBuilder = new StringBuilder();
    StringBuilder tArgument = new StringBuilder();
    boolean inTemplate = false;
    for (int i = 0; i < template.length(); i++) {
        Character c1 = template.charAt(i);
        Character c2 = '\0';
        if (i < template.length() - 1) {
            c2 = template.charAt(i + 1);
        }
        if (c1 == '<' && c2 == '%') {
            // start template
            inTemplate = true;
            templateStack++;
            if (templateStack == 1) {
                i++;
                continue;
            }
        }
        if (c1 == '%' && c2 == '>') {
            // end template
            templateStack--;
            if (templateStack == 0) {
                // Process the template now
                String[] args = tArgument.toString().split("\\|");
                String name = args[0];
                if (args.length > 1) {
                    args = ArrayUtils.slice(args, 1, args.length - 1);
                }
                // Loop over the arguments and resolve them first
                for (int j = 0; j < args.length; j++) {
                    args[j] = DoTemplateReplacement(args[j], generators);
                }
                if (generators.containsKey(name)) {
                    String result = generators.get(name).generate(args);
                    tBuilder.append(result);
                }
                tArgument = new StringBuilder();
            }
            if (templateStack == 0) {
                i++;
                continue;
            }
        }
        if (templateStack == 0) {
            tBuilder.append(c1);
        } else {
            tArgument.append(c1);
        }
    }
    template = tBuilder.toString();
    // Find all the %%templates%% in the template
    Matcher m = Pattern.compile("(?:%|<)%([^\\|%]+)([^%]*?)%(?:%|>)").matcher(template);
    StringBuilder templateBuilder = new StringBuilder();
    int lastMatch = 0;
    boolean appended = false;
    while (m.find()) {
        if (!appended) {
            templateBuilder.append(template.substring(lastMatch, m.start()));
            appended = true;
        }
        String name = m.group(1);
        try {
            if (generators.containsKey(name)) {
                String[] tmplArgs = ArrayUtils.EMPTY_STRING_ARRAY;
                if (m.group(2) != null && !m.group(2).isEmpty()) {
                    // We have arguments
                    // remove the initial |, then split
                    tmplArgs = m.group(2).substring(1).split("\\|");
                }
                for (int i = 0; i < tmplArgs.length; i++) {
                    tmplArgs[i] = DoTemplateReplacement(tmplArgs[i], generators);
                }
                String templateValue = generators.get(name).generate(tmplArgs);
                templateBuilder.append(templateValue);
            // template = template.replaceAll("%%" + Pattern.quote(name) + "%%", templateValue);
            }
            lastMatch = m.end();
            appended = false;
        } catch (GenerateException e) {
            throw e;
        } catch (Exception e) {
            // Oh well, skip it.
            e.printStackTrace();
        }
    }
    if (!appended) {
        templateBuilder.append(template.substring(lastMatch));
    }
    return templateBuilder.toString();
}
Also used : Matcher(java.util.regex.Matcher) IOException(java.io.IOException) CString(com.laytonsmith.core.constructs.CString) GenerateException(com.laytonsmith.tools.docgen.DocGenTemplates.Generator.GenerateException) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) GenerateException(com.laytonsmith.tools.docgen.DocGenTemplates.Generator.GenerateException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

GenerateException (com.laytonsmith.tools.docgen.DocGenTemplates.Generator.GenerateException)4 IOException (java.io.IOException)3 CString (com.laytonsmith.core.constructs.CString)2 HashMap (java.util.HashMap)2 ZipReader (com.laytonsmith.PureUtilities.ZipReader)1 ConfigCompileException (com.laytonsmith.core.exceptions.ConfigCompileException)1 Generator (com.laytonsmith.tools.docgen.DocGenTemplates.Generator)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1 InputStream (java.io.InputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 ArrayList (java.util.ArrayList)1 LinkedHashMap (java.util.LinkedHashMap)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1 Map (java.util.Map)1 Queue (java.util.Queue)1 TreeMap (java.util.TreeMap)1 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)1 Matcher (java.util.regex.Matcher)1