001/* 002 * Copyright 2012-2018 the original author or authors. 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.springframework.boot.cli.app; 018 019import java.io.IOException; 020import java.io.InputStream; 021import java.util.jar.Manifest; 022 023import javax.servlet.ServletContext; 024import javax.servlet.ServletException; 025 026import org.springframework.boot.builder.SpringApplicationBuilder; 027import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 028 029/** 030 * {@link SpringBootServletInitializer} for CLI packaged WAR files. 031 * 032 * @author Phillip Webb 033 * @since 1.3.0 034 */ 035public class SpringApplicationWebApplicationInitializer 036 extends SpringBootServletInitializer { 037 038 /** 039 * The entry containing the source class. 040 */ 041 public static final String SOURCE_ENTRY = "Spring-Application-Source-Classes"; 042 043 private String[] sources; 044 045 @Override 046 public void onStartup(ServletContext servletContext) throws ServletException { 047 try { 048 this.sources = getSources(servletContext); 049 } 050 catch (IOException ex) { 051 throw new IllegalStateException(ex); 052 } 053 super.onStartup(servletContext); 054 } 055 056 private String[] getSources(ServletContext servletContext) throws IOException { 057 Manifest manifest = getManifest(servletContext); 058 if (manifest == null) { 059 throw new IllegalStateException("Unable to read manifest"); 060 } 061 String sources = manifest.getMainAttributes().getValue(SOURCE_ENTRY); 062 return sources.split(","); 063 } 064 065 private Manifest getManifest(ServletContext servletContext) throws IOException { 066 InputStream stream = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF"); 067 return (stream != null) ? new Manifest(stream) : null; 068 } 069 070 @Override 071 protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { 072 try { 073 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 074 Class<?>[] sourceClasses = new Class<?>[this.sources.length]; 075 for (int i = 0; i < this.sources.length; i++) { 076 sourceClasses[i] = classLoader.loadClass(this.sources[i]); 077 } 078 return builder.sources(sourceClasses) 079 .properties("spring.groovy.template.check-template-location=false"); 080 } 081 catch (Exception ex) { 082 throw new IllegalStateException(ex); 083 } 084 } 085 086}