com.commercehub.dropwizard.BuildInfoServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.commercehub.dropwizard.BuildInfoServlet.java

Source

/*
 * Copyright (C) 2014 Commerce Technologies, Inc.
 *
 * Licensed 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 com.commercehub.dropwizard;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

public class BuildInfoServlet extends HttpServlet {

    final Logger log = LoggerFactory.getLogger(BuildInfoServlet.class);

    public static final String ATTRIBUTE_BLACKLIST_INIT_PARAM = "attributeBlacklist";
    public static final char ATTRIBUTE_BLACKLIST_SEPARATOR = ',';

    private ObjectWriter objectWriter;
    private CacheControl cacheControl;
    private Properties manifestAttributes;

    @Override
    public void init(ServletConfig config) {
        objectWriter = new ObjectMapper().writer();

        cacheControl = new CacheControl();
        cacheControl.setMustRevalidate(true);
        cacheControl.setNoCache(true);
        cacheControl.setNoStore(true);

        // cache build information
        manifestAttributes = new Properties();
        ImmutableSet<String> attributeBlacklist = getAttributeBlacklist(config);
        try {
            Enumeration<URL> resources = getClass().getClassLoader().getResources(JarFile.MANIFEST_NAME);
            if (resources != null) {
                while (resources.hasMoreElements()) {
                    Manifest manifest = new Manifest(resources.nextElement().openStream());
                    Attributes attributes = manifest.getMainAttributes();
                    for (Object key : attributes.keySet()) {
                        Attributes.Name attrName = (Attributes.Name) key;
                        if (!attributeBlacklist.contains(attrName.toString())) {
                            manifestAttributes.setProperty(attrName.toString(), attributes.getValue(attrName));
                        }
                    }
                }
            }
        } catch (IOException e) {
            log.warn("Unable to retrieve build info", e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader(HttpHeaders.CACHE_CONTROL, cacheControl.toString());
        response.setStatus(HttpServletResponse.SC_OK);

        String requestedKey = getRequestedKey(request);
        if (StringUtils.isNotBlank(requestedKey)) {
            writeValueForKey(requestedKey, response);
        } else if (requestedHtml(request)) {
            writeAllHtml(response);
        } else {
            writeAllJson(response);
        }
    }

    private void writeValueForKey(String requestedKey, HttpServletResponse response) throws IOException {
        String value = manifestAttributes.getProperty(requestedKey);
        if (StringUtils.isNotBlank(value)) {
            response.setContentType(MediaType.TEXT_PLAIN);
            response.getWriter().print(value);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    private void writeAllJson(HttpServletResponse response) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON);
        objectWriter.writeValue(response.getWriter(), manifestAttributes);
    }

    private void writeAllHtml(HttpServletResponse response) throws IOException {
        response.setContentType(MediaType.TEXT_HTML);
        PrintWriter writer = response.getWriter();

        writer.println("<html>");
        writer.println("  <body>");
        writer.println("    <h1>Info</h1>");
        writer.println("    <ul>");
        for (String key : manifestAttributes.stringPropertyNames()) {
            writer.format("      <li>%s: %s</li>", key, manifestAttributes.get(key));
        }
        writer.println("    </ul>");
        writer.println("  </body>");
        writer.println("</html>");
    }

    private static ImmutableSet<String> getAttributeBlacklist(ServletConfig config) {
        String attributeBlacklistParam = config.getInitParameter(ATTRIBUTE_BLACKLIST_INIT_PARAM);
        if (StringUtils.isNotBlank(attributeBlacklistParam)) {
            Set<String> blacklist = Sets.newHashSet();
            for (String attribute : StringUtils.split(attributeBlacklistParam, ATTRIBUTE_BLACKLIST_SEPARATOR)) {
                blacklist.add(StringUtils.strip(attribute));
            }
            return ImmutableSet.copyOf(blacklist);
        }
        return ImmutableSet.of();
    }

    private static String getRequestedKey(HttpServletRequest request) {
        return StringUtils.substring(request.getPathInfo(), 1);
    }

    private static boolean requestedHtml(HttpServletRequest req) {
        String accept = req.getHeader(HttpHeaders.ACCEPT);
        return StringUtils.isNotBlank(accept) && accept.contains(MediaType.TEXT_HTML);
    }

}