001/* 002 * Copyright 2014 Atteo. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.atteo.moonshine.webjars; 018 019import java.io.DataInputStream; 020import java.io.IOException; 021import java.io.InputStream; 022 023import javax.servlet.ServletException; 024import javax.servlet.ServletOutputStream; 025import javax.servlet.http.HttpServlet; 026import javax.servlet.http.HttpServletRequest; 027import javax.servlet.http.HttpServletResponse; 028 029public class WebJarsServlet extends HttpServlet { 030 private static final int BUFSIZE = 4096; 031 private final String destination; 032 033 public WebJarsServlet(String destination) { 034 this.destination = destination; 035 } 036 037 @Override 038 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, 039 IOException { 040 String path = request.getPathInfo(); 041 if (path == null) { 042 response.sendError(HttpServletResponse.SC_NOT_FOUND); 043 return; 044 } 045 046 String mimetype = request.getServletContext().getMimeType(path); 047 if (mimetype == null) { 048 mimetype = "application/octet-stream"; 049 } 050 response.setContentType(mimetype); 051 052 try (InputStream stream = WebJarsServlet.class.getResourceAsStream(destination + path); 053 DataInputStream dataStream = new DataInputStream(stream); 054 ServletOutputStream out = response.getOutputStream()) { 055 if (stream == null) { 056 response.sendError(HttpServletResponse.SC_NOT_FOUND); 057 return; 058 } 059 060 int length; 061 byte[] byteBuffer = new byte[BUFSIZE]; 062 while ((length = dataStream.read(byteBuffer)) != -1) { 063 out.write(byteBuffer, 0, length); 064 } 065 } 066 } 067}