001/* 002 * Copyright 2012-2017 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.autoconfigure.template; 018 019import java.io.IOException; 020 021import org.springframework.core.io.Resource; 022import org.springframework.core.io.ResourceLoader; 023import org.springframework.core.io.support.ResourcePatternResolver; 024import org.springframework.util.Assert; 025 026/** 027 * Contains a location that templates can be loaded from. 028 * 029 * @author Phillip Webb 030 * @since 1.2.1 031 */ 032public class TemplateLocation { 033 034 private final String path; 035 036 public TemplateLocation(String path) { 037 Assert.notNull(path, "Path must not be null"); 038 this.path = path; 039 } 040 041 /** 042 * Determine if this template location exists using the specified 043 * {@link ResourcePatternResolver}. 044 * @param resolver the resolver used to test if the location exists 045 * @return {@code true} if the location exists. 046 */ 047 public boolean exists(ResourcePatternResolver resolver) { 048 Assert.notNull(resolver, "Resolver must not be null"); 049 if (resolver.getResource(this.path).exists()) { 050 return true; 051 } 052 try { 053 return anyExists(resolver); 054 } 055 catch (IOException ex) { 056 return false; 057 } 058 } 059 060 private boolean anyExists(ResourcePatternResolver resolver) throws IOException { 061 String searchPath = this.path; 062 if (searchPath.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) { 063 searchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX 064 + searchPath.substring(ResourceLoader.CLASSPATH_URL_PREFIX.length()); 065 } 066 if (searchPath.startsWith(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX)) { 067 Resource[] resources = resolver.getResources(searchPath); 068 for (Resource resource : resources) { 069 if (resource.exists()) { 070 return true; 071 } 072 } 073 } 074 return false; 075 } 076 077 @Override 078 public String toString() { 079 return this.path; 080 } 081 082}