Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (c) 2005 Henri Sivonen
   * Copyright (c) 2007-2014 Mozilla Foundation
   *
   * Permission is hereby granted, free of charge, to any person obtaining a 
   * copy of this software and associated documentation files (the "Software"), 
   * to deal in the Software without restriction, including without limitation 
   * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
   * and/or sell copies of the Software, and to permit persons to whom the 
  * Software is furnished to do so, subject to the following conditions:
  *
  * The above copyright notice and this permission notice shall be included in 
  * all copies or substantial portions of the Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
  * DEALINGS IN THE SOFTWARE.
  */
 
 package nu.validator.servlet;
 
 
 
 

Author(s):
hsivonen
Version:
$Id$
 
 public class VerifierServlet extends HttpServlet {
    
 
     private static final long serialVersionUID = 7811043632732680935L;
 
     private static final Logger log4j = Logger.getLogger(VerifierServlet.class);
 
     static final String GENERIC_HOST = System.getProperty("nu.validator.servlet.host.generic""");
 
     static final String HTML5_HOST = System.getProperty("nu.validator.servlet.host.html5""");
 
     static final String PARSETREE_HOST = System.getProperty("nu.validator.servlet.host.parsetree""");
 
     static final String GENERIC_PATH = System.getProperty("nu.validator.servlet.path.generic""/");
 
     static final String HTML5_PATH = System.getProperty("nu.validator.servlet.path.html5""/html5/");
 
     static final String PARSETREE_PATH = System.getProperty("nu.validator.servlet.path.parsetree""/parsetree/");
 
     private static final byte[] GENERIC_ROBOTS_TXT;
 
     private static final byte[] HTML5_ROBOTS_TXT;
 
     private static final byte[] PARSETREE_ROBOTS_TXT;
 
     private static final byte[] STYLE_CSS;
 
     private static final byte[] SCRIPT_JS;
 
     private static final byte[] ICON_PNG;
 
     private static final byte[] ABOUT_HTML;
 
     static {
         try {
         } catch (UnsupportedEncodingException e) {
             throw new RuntimeException(e);
         }
         try {
              = readFromClassLoaderIntoByteArray("nu/validator/localentities/files/style.css");
              = readFromClassLoaderIntoByteArray("nu/validator/localentities/files/script.js");
              = readFromClassLoaderIntoByteArray("nu/validator/localentities/files/icon.png");
              = readFromClassLoaderIntoByteArray("nu/validator/localentities/files/about.html");
         } catch (IOException e) {
             throw new RuntimeException(e);
         }
         PrudentHttpEntityResolver.setParams(
             Integer.parseInt(System.getProperty("nu.validator.servlet.connection-timeout","5000")),
             Integer.parseInt(System.getProperty("nu.validator.servlet.socket-timeout","5000")),
            100);
        PrudentHttpEntityResolver.setUserAgent(System.getProperty("nu.validator.servlet.user-agent","Validator.nu/LV"));
        // force some class loading
        new VerifierServletTransaction(nullnull);
        new MessageEmitterAdapter(nullfalsenull, 0, falsenull);
    }

    
    private static byte[] buildRobotsTxt(String primaryHostString primaryPathString secondaryHostString secondaryPathString tertiaryHostString tertiaryPaththrows UnsupportedEncodingException {
        StringBuilder builder = new StringBuilder();
        builder.append("User-agent: *\nDisallow: ");
        builder.append(primaryPath);
        builder.append("?\n");
        if (primaryHost.equals(secondaryHost)) {
            builder.append("Disallow: ");
            builder.append(secondaryPath);
            builder.append("?\n");
        }
        if (primaryHost.equals(tertiaryHost)) {
            builder.append("Disallow: ");
            builder.append(tertiaryPath);
            builder.append("?\n");
        }
        return builder.toString().getBytes("UTF-8");
    }
    private static byte[] readFromClassLoaderIntoByteArray(String name)
            throws IOException {
                name);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            for (int b = ios.read(); b != -1; b = ios.read()) {
                baos.write(b);
            }
            ios.close();
            baos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return baos.toByteArray();
    }
    private void writeResponse(byte[] bufferString type,
            HttpServletResponse responsethrows IOException {
        try {
            response.setContentType(type);
            response.setContentLength(buffer.length);
            response.setDateHeader("Expires",
                    System.currentTimeMillis() + 43200000); // 12 hours
            OutputStream out = response.getOutputStream();
            out.write(buffer);
            out.flush();
            out.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    
    @Override
    protected void doGet(HttpServletRequest requestHttpServletResponse responsethrows ServletExceptionIOException {
        if ("/robots.txt".equals(request.getPathInfo())) {
            String serverName = request.getServerName();
            byte[] robotsTxt = null;
            if (hostMatch(serverName)) {
                robotsTxt = ;
            } else if (hostMatch(serverName)) {
                robotsTxt = ;
            } else if (hostMatch(serverName)) {
                robotsTxt = ;
            } else {
                response.sendError(.);
                return;
            }
            writeResponse(robotsTxt"text/plain; charset=utf-8"response);
            return;
        } else if ("/style.css".equals(request.getPathInfo())) {
            writeResponse("text/css; charset=utf-8"response);
            return;
        } else if ("/script.js".equals(request.getPathInfo())) {
            writeResponse("text/javascript; charset=utf-8"response);
            return;
        } else if ("/icon.png".equals(request.getPathInfo())) {
            writeResponse("image/png"response);
            return;
        } else if ("/about.html".equals(request.getPathInfo())) {
            writeResponse("text/html; charset=utf-8"response);
            return;
        } else if (. != null && "/stats.html".equals(request.getPathInfo())) {
            ..writeToResponse(response);
            return;
        }
        doPost(requestresponse);
    }
    private boolean hostMatch(String referenceString host) {
        if ("".equals(reference)) {
            return true;
        } else {
            // XXX case-sensitivity
            return reference.equalsIgnoreCase(host);
        }
    }

    
    @Override
    protected void doOptions(HttpServletRequest request,
            HttpServletResponse responsethrows ServletExceptionIOException {
        String pathInfo = request.getPathInfo();
        if ("*".equals(pathInfo)) { // useless RFC 2616 complication
            return;
        } else if ("/robots.txt".equals(pathInfo)) {
            String serverName = request.getServerName();
            if (hostMatch(serverName)
                    || hostMatch(serverName)
                    || hostMatch(serverName)) {
                sendGetOnlyOptions(requestresponse);
                return;
            } else {
                response.sendError(.);
                return;
            }
        }
        doPost(requestresponse);
    }

    
    @Override
    protected void doTrace(HttpServletRequest requestHttpServletResponse responsethrows ServletExceptionIOException {
    }

    
    protected void doPost(HttpServletRequest request,
            HttpServletResponse responsethrows ServletExceptionIOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/"// Fix for Jigsaw
        }
        String serverName = request.getServerName();
        if ("/robots.txt".equals(pathInfo)) {
            // if we get here, we've got a POST
            response.sendError(.);
            return;
        }
        .debug("pathInfo: " + pathInfo);
        .debug("serverName: " + serverName);
        boolean isOptions = "OPTIONS".equals(request.getMethod());
        if ("validator.nu".equals(serverName) && "/html5/".equals(pathInfo)) {
                response.setStatus(.);
                String queryString = request.getQueryString();
                response.setHeader("Location""http://html5.validator.nu/" + (queryString == null ? "" : "?" + queryString));
        } else if (hostMatch(serverName) && .equals(pathInfo)) {
            response.setHeader("Access-Control-Allow-Origin""*");
            response.setHeader("Access-Control-Allow-Headers""content-type");
            if (isOptions) {
                sendOptions(requestresponse);
            } else {
                new VerifierServletTransaction(requestresponse).service();
            }
        } else if (hostMatch(serverName) && .equals(pathInfo)) {
            response.setHeader("Access-Control-Allow-Origin""*");
            response.setHeader("Access-Control-Allow-Headers""content-type");
            if (isOptions) {
                sendOptions(requestresponse);
            } else {
                new Html5ConformanceCheckerTransaction(requestresponse).service();
            }
        } else if (hostMatch(serverName) && .equals(pathInfo)) {
            if (isOptions) {
                sendGetOnlyOptions(requestresponse);
            } else {
                new ParseTreePrinter(requestresponse).service();
            }
        } else {
            response.sendError(.);
        }
    }
    private void sendGetOnlyOptions(HttpServletRequest requestHttpServletResponse response) {
        response.setHeader("Allow""GET, HEAD, OPTIONS");
        response.setHeader("Access-Control-Allow-Methods""GET, HEAD, POST, OPTIONS");
        response.setContentType("application/octet-stream");
        response.setContentLength(0);
    }
    private void sendOptions(HttpServletRequest requestHttpServletResponse response) {
        response.setHeader("Access-Control-Max-Age""43200"); // 12 hours
        response.setHeader("Allow""GET, HEAD, POST, OPTIONS");
        response.setHeader("Access-Control-Allow-Methods""GET, HEAD, POST, OPTIONS");
        response.setContentType("application/octet-stream");
        response.setContentLength(0);
    }
New to GrepCode? Check out our FAQ X