spullara / mustache.java

Implementation of mustache.js for Java
http://www.javarants.com/the-ideal-web-application-templating-system-b301fa4a1f49
Other
1.9k stars 285 forks source link

URL MustacheResolver does not work #134

Closed vbauer closed 4 years ago

vbauer commented 9 years ago

I've tried to implement custom MustacheResolver to fetch templates by HTTP (or HTTPS) and faced with the following problem:

I try to fetch the following resource: "https://raw.github.com/kongchen/api-doc-template/master/v2.0/strapdown.html.mustache" (using simple URLConnection)

After that mustache.java tries to include the following partial: "https:/raw.github.com/kongchen/api-doc-template/master/v2.0/markdown.mustache"

As you can see the URL is not correct "https:/" instead of "https://".

Maybe it could help:

public class ExtendedMustacheResolver implements MustacheResolver {

    private final MustacheResolver defaultResolver;

    public ExtendedMustacheResolver() {
        defaultResolver = new DefaultResolver();
    }

    public ExtendedMustacheResolver(final File fileRoot) {
        defaultResolver = new DefaultResolver(fileRoot);
    }

    @Override
    public Reader getReader(final String resourceName) {
        final Reader reader = defaultResolver.getReader(resourceName);
        if (reader == null) {
            final URI templateUri = getTemplateUri(resourceName);
            try {
                final URL url = templateUri.toURL();
                final InputStream in = url.openStream();
                return new InputStreamReader(in, Charsets.UTF_8);
            } catch (final Exception ex) {
                return null;
            }
        }
        return reader;
    }

    private URI getTemplateUri(final String templatePath) {
        URI uri;
        try {
            uri = new URI(templatePath);
        } catch (final URISyntaxException e) {
            uri = getTemplateFileUri(templatePath);
        }
        if (!uri.isAbsolute()) {
            uri = getTemplateFileUri(templatePath);
        }
        return uri;
    }

    private URI getTemplateFileUri(final String templatePath) {
        final File file = new File(templatePath);
        if (!file.exists()) {
            throw new GenerateException(
                "Template "
                    + file.getAbsoluteFile()
                    + " not found. You can go to https://github.com/kongchen/api-doc-template to get templates.");
        }
        return file.toURI();
    }

}
avetokhin commented 9 years ago

+1

xvik commented 9 years ago

+1

spullara commented 9 years ago

I would consider a pull request that changes the partial resolution to support this.