Java tutorial
/** * Copyright (c) Anton Johansson <antoon.johansson@gmail.com> * * 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.antonjohansson.managementcenter.core.web; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import static org.apache.commons.io.IOUtils.copy; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.Objects; import java.util.Optional; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Serves static Vaadin resources. * * @author Anton Johansson */ public class VaadinResourcesServlet extends HttpServlet { private static final String CONTEXT = "/management-center"; @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = getRequestURI(request); Optional<URL> resource = getResource(name); if (!resource.isPresent()) { response.sendError(SC_NOT_FOUND); return; } try (InputStream input = resource.get().openStream(); OutputStream output = response.getOutputStream()) { copy(input, output); } } private String getRequestURI(HttpServletRequest request) { String requestURI = request.getRequestURI(); if (requestURI.startsWith(CONTEXT)) { requestURI = requestURI.substring(CONTEXT.length()); } return requestURI; } private Optional<URL> getResource(String name) { return WebActivator.vaadinBundles().map(b -> b.getResource(name)).filter(Objects::nonNull).findAny(); } }