Search in sources :

Example 1 with PluginEntry

use of com.google.gerrit.server.plugins.PluginEntry in project gerrit by GerritCodeReview.

the class HttpPluginServlet method sendAutoIndex.

private void sendAutoIndex(PluginContentScanner scanner, final String prefix, final String pluginName, PluginResourceKey cacheKey, HttpServletResponse res, long lastModifiedTime) throws IOException {
    List<PluginEntry> cmds = new ArrayList<>();
    List<PluginEntry> servlets = new ArrayList<>();
    List<PluginEntry> restApis = new ArrayList<>();
    List<PluginEntry> docs = new ArrayList<>();
    PluginEntry about = null;
    Predicate<PluginEntry> filter = entry -> {
        String name = entry.getName();
        Optional<Long> size = entry.getSize();
        if (name.startsWith(prefix) && (name.endsWith(".md") || name.endsWith(".html")) && size.isPresent()) {
            if (size.get() <= 0 || size.get() > SMALL_RESOURCE) {
                log.warn(String.format("Plugin %s: %s omitted from document index. " + "Size %d out of range (0,%d).", pluginName, name.substring(prefix.length()), size.get(), SMALL_RESOURCE));
                return false;
            }
            return true;
        }
        return false;
    };
    List<PluginEntry> entries = Collections.list(scanner.entries()).stream().filter(filter).collect(toList());
    for (PluginEntry entry : entries) {
        String name = entry.getName().substring(prefix.length());
        if (name.startsWith("cmd-")) {
            cmds.add(entry);
        } else if (name.startsWith("servlet-")) {
            servlets.add(entry);
        } else if (name.startsWith("rest-api-")) {
            restApis.add(entry);
        } else if (name.startsWith("about.")) {
            if (about == null) {
                about = entry;
            } else {
                log.warn(String.format("Plugin %s: Multiple 'about' documents found; using %s", pluginName, about.getName().substring(prefix.length())));
            }
        } else {
            docs.add(entry);
        }
    }
    Collections.sort(cmds, PluginEntry.COMPARATOR_BY_NAME);
    Collections.sort(docs, PluginEntry.COMPARATOR_BY_NAME);
    StringBuilder md = new StringBuilder();
    md.append(String.format("# Plugin %s #\n", pluginName));
    md.append("\n");
    appendPluginInfoTable(md, scanner.getManifest().getMainAttributes());
    if (about != null) {
        InputStreamReader isr = new InputStreamReader(scanner.getInputStream(about), UTF_8);
        StringBuilder aboutContent = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(isr)) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty()) {
                    aboutContent.append("\n");
                } else {
                    aboutContent.append(line).append("\n");
                }
            }
        }
        // Only append the About section if there was anything in it
        if (aboutContent.toString().trim().length() > 0) {
            md.append("## About ##\n");
            md.append("\n").append(aboutContent);
        }
    }
    appendEntriesSection(scanner, docs, "Documentation", md, prefix, 0);
    appendEntriesSection(scanner, servlets, "Servlets", md, prefix, "servlet-".length());
    appendEntriesSection(scanner, restApis, "REST APIs", md, prefix, "rest-api-".length());
    appendEntriesSection(scanner, cmds, "Commands", md, prefix, "cmd-".length());
    sendMarkdownAsHtml(md.toString(), pluginName, cacheKey, res, lastModifiedTime);
}
Also used : RestApiServlet(com.google.gerrit.httpd.restapi.RestApiServlet) FileUtil.lastModified(com.google.gerrit.common.FileUtil.lastModified) FilterChain(javax.servlet.FilterChain) ResourceKey(com.google.gerrit.httpd.resources.ResourceKey) ServletException(javax.servlet.ServletException) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) PluginsCollection(com.google.gerrit.server.plugins.PluginsCollection) SshInfo(com.google.gerrit.server.ssh.SshInfo) Matcher(java.util.regex.Matcher) HttpHeaders(com.google.common.net.HttpHeaders) Locale(java.util.Locale) Map(java.util.Map) Splitter(com.google.common.base.Splitter) StartPluginListener(com.google.gerrit.server.plugins.StartPluginListener) Path(java.nio.file.Path) ServletConfig(javax.servlet.ServletConfig) HttpServlet(javax.servlet.http.HttpServlet) Predicate(java.util.function.Predicate) ApiType(com.google.gerrit.server.plugins.Plugin.ApiType) RawParseUtils(org.eclipse.jgit.util.RawParseUtils) MarkdownFormatter(com.google.gerrit.server.documentation.MarkdownFormatter) GuiceFilter(com.google.inject.servlet.GuiceFilter) Attributes(java.util.jar.Attributes) Resource(com.google.gerrit.httpd.resources.Resource) List(java.util.List) ServletResponse(javax.servlet.ServletResponse) ReloadPluginListener(com.google.gerrit.server.plugins.ReloadPluginListener) ByteStreams(com.google.common.io.ByteStreams) Optional(java.util.Optional) RegistrationHandle(com.google.gerrit.extensions.registration.RegistrationHandle) Pattern(java.util.regex.Pattern) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Singleton(com.google.inject.Singleton) PluginContentScanner(com.google.gerrit.server.plugins.PluginContentScanner) HashMap(java.util.HashMap) CacheHeaders(com.google.gwtexpui.server.CacheHeaders) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) Strings(com.google.common.base.Strings) CanonicalWebUrl(com.google.gerrit.server.config.CanonicalWebUrl) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) Charset(java.nio.charset.Charset) Plugin(com.google.gerrit.server.plugins.Plugin) ATTR_CHARACTER_ENCODING(com.google.gerrit.server.plugins.PluginEntry.ATTR_CHARACTER_ENCODING) OutputStream(java.io.OutputStream) RequestUtil(com.google.gerrit.util.http.RequestUtil) ServletRequest(javax.servlet.ServletRequest) IO(org.eclipse.jgit.util.IO) Logger(org.slf4j.Logger) Files(java.nio.file.Files) UTF_8(java.nio.charset.StandardCharsets.UTF_8) CharMatcher(com.google.common.base.CharMatcher) SmallResource(com.google.gerrit.httpd.resources.SmallResource) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ATTR_CONTENT_TYPE(com.google.gerrit.server.plugins.PluginEntry.ATTR_CONTENT_TYPE) Maps(com.google.common.collect.Maps) InputStreamReader(java.io.InputStreamReader) PluginEntry(com.google.gerrit.server.plugins.PluginEntry) Collectors.toList(java.util.stream.Collectors.toList) Provider(com.google.inject.Provider) Named(com.google.inject.name.Named) ServletContext(javax.servlet.ServletContext) BufferedReader(java.io.BufferedReader) Cache(com.google.common.cache.Cache) MimeUtilFileTypeRegistry(com.google.gerrit.server.mime.MimeUtilFileTypeRegistry) Collections(java.util.Collections) InputStream(java.io.InputStream) Optional(java.util.Optional) InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) BufferedReader(java.io.BufferedReader) PluginEntry(com.google.gerrit.server.plugins.PluginEntry)

Example 2 with PluginEntry

use of com.google.gerrit.server.plugins.PluginEntry in project gerrit by GerritCodeReview.

the class HttpPluginServlet method onDefault.

private void onDefault(PluginHolder holder, HttpServletRequest req, HttpServletResponse res) throws IOException {
    if (!"GET".equals(req.getMethod()) && !"HEAD".equals(req.getMethod())) {
        CacheHeaders.setNotCacheable(res);
        res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }
    String pathInfo = RequestUtil.getEncodedPathInfo(req);
    if (pathInfo.length() < 1) {
        Resource.NOT_FOUND.send(req, res);
        return;
    }
    String file = pathInfo.substring(1);
    PluginResourceKey key = PluginResourceKey.create(holder.plugin, file);
    Resource rsc = resourceCache.getIfPresent(key);
    if (rsc != null && req.getHeader(HttpHeaders.IF_MODIFIED_SINCE) == null) {
        rsc.send(req, res);
        return;
    }
    String uri = req.getRequestURI();
    if ("".equals(file)) {
        res.sendRedirect(uri + holder.docPrefix + "index.html");
        return;
    }
    if (file.startsWith(holder.staticPrefix)) {
        if (holder.plugin.getApiType() == ApiType.JS) {
            sendJsPlugin(holder.plugin, key, req, res);
        } else {
            PluginContentScanner scanner = holder.plugin.getContentScanner();
            Optional<PluginEntry> entry = scanner.getEntry(file);
            if (entry.isPresent()) {
                if (hasUpToDateCachedResource(rsc, entry.get().getTime())) {
                    rsc.send(req, res);
                } else {
                    sendResource(scanner, entry.get(), key, res);
                }
            } else {
                resourceCache.put(key, Resource.NOT_FOUND);
                Resource.NOT_FOUND.send(req, res);
            }
        }
    } else if (file.equals(holder.docPrefix.substring(0, holder.docPrefix.length() - 1))) {
        res.sendRedirect(uri + "/index.html");
    } else if (file.startsWith(holder.docPrefix) && file.endsWith("/")) {
        res.sendRedirect(uri + "index.html");
    } else if (file.startsWith(holder.docPrefix)) {
        PluginContentScanner scanner = holder.plugin.getContentScanner();
        Optional<PluginEntry> entry = scanner.getEntry(file);
        if (!entry.isPresent()) {
            entry = findSource(scanner, file);
        }
        if (!entry.isPresent() && file.endsWith("/index.html")) {
            String pfx = file.substring(0, file.length() - "index.html".length());
            long pluginLastModified = lastModified(holder.plugin.getSrcFile());
            if (hasUpToDateCachedResource(rsc, pluginLastModified)) {
                rsc.send(req, res);
            } else {
                sendAutoIndex(scanner, pfx, holder.plugin.getName(), key, res, pluginLastModified);
            }
        } else if (entry.isPresent() && entry.get().getName().endsWith(".md")) {
            if (hasUpToDateCachedResource(rsc, entry.get().getTime())) {
                rsc.send(req, res);
            } else {
                sendMarkdownAsHtml(scanner, entry.get(), holder.plugin.getName(), key, res);
            }
        } else if (entry.isPresent()) {
            if (hasUpToDateCachedResource(rsc, entry.get().getTime())) {
                rsc.send(req, res);
            } else {
                sendResource(scanner, entry.get(), key, res);
            }
        } else {
            resourceCache.put(key, Resource.NOT_FOUND);
            Resource.NOT_FOUND.send(req, res);
        }
    } else {
        resourceCache.put(key, Resource.NOT_FOUND);
        Resource.NOT_FOUND.send(req, res);
    }
}
Also used : Optional(java.util.Optional) PluginContentScanner(com.google.gerrit.server.plugins.PluginContentScanner) Resource(com.google.gerrit.httpd.resources.Resource) SmallResource(com.google.gerrit.httpd.resources.SmallResource) PluginEntry(com.google.gerrit.server.plugins.PluginEntry)

Example 3 with PluginEntry

use of com.google.gerrit.server.plugins.PluginEntry in project gerrit by GerritCodeReview.

the class HttpPluginServlet method appendEntriesSection.

private void appendEntriesSection(PluginContentScanner scanner, List<PluginEntry> entries, String sectionTitle, StringBuilder md, String prefix, int nameOffset) throws IOException {
    if (!entries.isEmpty()) {
        md.append("## ").append(sectionTitle).append(" ##\n");
        for (PluginEntry entry : entries) {
            String rsrc = entry.getName().substring(prefix.length());
            String entryTitle;
            if (rsrc.endsWith(".html")) {
                entryTitle = rsrc.substring(nameOffset, rsrc.length() - 5).replace('-', ' ');
            } else if (rsrc.endsWith(".md")) {
                entryTitle = extractTitleFromMarkdown(scanner, entry);
                if (Strings.isNullOrEmpty(entryTitle)) {
                    entryTitle = rsrc.substring(nameOffset, rsrc.length() - 3).replace('-', ' ');
                }
            } else {
                entryTitle = rsrc.substring(nameOffset).replace('-', ' ');
            }
            md.append(String.format("* [%s](%s)\n", entryTitle, rsrc));
        }
        md.append("\n");
    }
}
Also used : PluginEntry(com.google.gerrit.server.plugins.PluginEntry)

Aggregations

PluginEntry (com.google.gerrit.server.plugins.PluginEntry)3 Resource (com.google.gerrit.httpd.resources.Resource)2 SmallResource (com.google.gerrit.httpd.resources.SmallResource)2 PluginContentScanner (com.google.gerrit.server.plugins.PluginContentScanner)2 Optional (java.util.Optional)2 CharMatcher (com.google.common.base.CharMatcher)1 Splitter (com.google.common.base.Splitter)1 Strings (com.google.common.base.Strings)1 Cache (com.google.common.cache.Cache)1 Lists (com.google.common.collect.Lists)1 Maps (com.google.common.collect.Maps)1 ByteStreams (com.google.common.io.ByteStreams)1 HttpHeaders (com.google.common.net.HttpHeaders)1 FileUtil.lastModified (com.google.gerrit.common.FileUtil.lastModified)1 RegistrationHandle (com.google.gerrit.extensions.registration.RegistrationHandle)1 ResourceKey (com.google.gerrit.httpd.resources.ResourceKey)1 RestApiServlet (com.google.gerrit.httpd.restapi.RestApiServlet)1 CanonicalWebUrl (com.google.gerrit.server.config.CanonicalWebUrl)1 MarkdownFormatter (com.google.gerrit.server.documentation.MarkdownFormatter)1 MimeUtilFileTypeRegistry (com.google.gerrit.server.mime.MimeUtilFileTypeRegistry)1