org.springframework.core.io.ResourceLoader

Here are the examples of the java api org.springframework.core.io.ResourceLoader taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

633 Examples 7

19 View Source File : RsaUtils.java
License : Apache License 2.0
Project Creator : Zoctan

/**
 * RSA 工具
 *
 * <p>用openssl生成512位RSA:
 *
 * <p>生成私钥: openssl genrsa -out key.pem 512
 *
 * <p>从私钥中导出公钥: openssl rsa -in key.pem -pubout -out public-key.pem
 *
 * <p>公钥加密: openssl rsautl -encrypt -in xx.file -inkey public-key.pem -pubin -out xx.en
 *
 * <p>私钥解密: openssl rsautl -decrypt -in xx.en -inkey key.pem -out xx.de
 *
 * <p>pkcs8编码(Java): openssl pkcs8 -topk8 -inform PEM -in key.pem -outform PEM -out private-key.pem
 * -nocrypt
 *
 * <p>最后将公私玥放在/resources/rsa/:private-key.pem public-key.pem
 *
 * @author Zoctan
 * @date 2018/07/20
 */
@Slf4j
@Component
public clreplaced RsaUtils {

    private static final String ALGORITHM = "RSA";

    private final ResourceLoader resourceLoader = new DefaultResourceLoader();

    @javax.annotation.Resource
    private RsaConfigurationProperties rsaProperties;

    public RsaUtils() {
        if (!Optional.ofNullable(this.rsaProperties).isPresent()) {
            this.rsaProperties = new RsaConfigurationProperties();
        }
    }

    /**
     * 生成密钥对
     *
     * @param keyLength 密钥长度(最少512位)
     * @return 密钥对 公钥 keyPair.getPublic() 私钥 keyPair.getPrivate()
     * @throws Exception e
     */
    public static KeyPair genKeyPair(final int keyLength) throws Exception {
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RsaUtils.ALGORITHM);
        keyPairGenerator.initialize(keyLength);
        return keyPairGenerator.generateKeyPair();
    }

    /**
     * 公钥加密
     *
     * @param content 待加密数据
     * @param publicKey 公钥
     * @return 加密内容
     * @throws Exception e
     */
    public static byte[] encrypt(final byte[] content, final PublicKey publicKey) throws Exception {
        final Cipher cipher = Cipher.getInstance(RsaUtils.ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(content);
    }

    /**
     * 私钥解密
     *
     * @param content 加密数据
     * @param privateKey 私钥
     * @return 解密内容
     * @throws Exception e
     */
    public static byte[] decrypt(final byte[] content, final PrivateKey privateKey) throws Exception {
        final Cipher cipher = Cipher.getInstance(RsaUtils.ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(content);
    }

    /**
     * 公钥加密
     *
     * @param content 待加密数据
     * @return 加密内容
     * @throws Exception e
     */
    public byte[] encrypt(final byte[] content) throws Exception {
        return RsaUtils.encrypt(content, this.loadPublicKey());
    }

    /**
     * 私钥解密
     *
     * @param content 加密数据
     * @return 解密内容
     * @throws Exception e
     */
    public byte[] decrypt(final byte[] content) throws Exception {
        return RsaUtils.decrypt(content, this.loadPrivateKey());
    }

    /**
     * 加载pem格式X509编码的公钥
     *
     * @return 公钥
     */
    public PublicKey loadPublicKey() throws RsaException {
        final byte[] decoded;
        if (this.rsaProperties.isUseFile()) {
            decoded = this.loadAndReplaceAndDecodeByBase64(this.rsaProperties.getPublicKeyPath(), this.rsaProperties.getPublicKeyHead(), this.rsaProperties.getPublicKeyTail());
        } else {
            decoded = Base64.decodeBase64(this.rsaProperties.getPublicKey());
        }
        final X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
        try {
            final KeyFactory keyFactory = KeyFactory.getInstance(RsaUtils.ALGORITHM);
            return keyFactory.generatePublic(spec);
        } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
            RsaUtils.log.error("==> {}", e.getMessage());
            return null;
        }
    }

    /**
     * 加载pem格式PKCS8编码的私钥
     *
     * @return 私钥
     */
    public PrivateKey loadPrivateKey() throws RsaException {
        final byte[] decoded;
        if (this.rsaProperties.isUseFile()) {
            decoded = this.loadAndReplaceAndDecodeByBase64(this.rsaProperties.getPrivateKeyPath(), this.rsaProperties.getPrivateKeyHead(), this.rsaProperties.getPrivateKeyTail());
        } else {
            decoded = Base64.decodeBase64(this.rsaProperties.getPrivateKey());
        }
        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
        try {
            final KeyFactory keyFactory = KeyFactory.getInstance(RsaUtils.ALGORITHM);
            return keyFactory.generatePrivate(spec);
        } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
            RsaUtils.log.error("==> {}", e.getMessage());
            return null;
        }
    }

    /**
     * 加载文件后替换头和尾并解密
     *
     * @return 文件字节
     */
    private byte[] loadAndReplaceAndDecodeByBase64(final String keyPath, final String headReplace, final String tailReplace) throws RsaException {
        final Resource resource = Optional.ofNullable(keyPath).map(this.resourceLoader::getResource).get();
        if (!resource.exists()) {
            throw new RsaException("==> 密钥不存在");
        }
        try {
            final String key = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
            return Base64.decodeBase64(key.replace(headReplace, "").trim().replace(tailReplace, "").trim());
        } catch (final IOException e) {
            throw new RsaException("==> 密钥读取异常: {}", e);
        }
    }
}

19 View Source File : ResourceUtils.java
License : MIT License
Project Creator : Zo3i

/**
 * 资源供给类
 * @author ThinkGem
 * @version 2016-9-16
 */
public clreplaced ResourceUtils extends org.springframework.util.ResourceUtils {

    private static ResourceLoader resourceLoader;

    private static ResourcePatternResolver resourceResolver;

    static {
        resourceLoader = new DefaultResourceLoader();
        resourceResolver = new PathMatchingResourcePatternResolver(resourceLoader);
    }

    /**
     * 获取资源加载器(可读取jar内的文件)
     * @author ThinkGem
     */
    public static ResourceLoader getResourceLoader() {
        return resourceLoader;
    }

    /**
     * 获取ClreplacedLoader
     */
    public static ClreplacedLoader getClreplacedLoader() {
        return resourceLoader.getClreplacedLoader();
    }

    /**
     * 获取资源加载器(可读取jar内的文件)
     */
    public static Resource getResource(String location) {
        return resourceLoader.getResource(location);
    }

    /**
     * 获取资源文件流(用后记得关闭)
     * @param location
     * @author ThinkGem
     * @throws IOException
     */
    public static InputStream getResourceFileStream(String location) throws IOException {
        Resource resource = resourceLoader.getResource(location);
        return resource.getInputStream();
    }

    /**
     * 获取资源文件内容
     * @param location
     * @author ThinkGem
     */
    public static String getResourceFileContent(String location) {
        InputStream is = null;
        try {
            is = ResourceUtils.getResourceFileStream(location);
            return IOUtils.toString(is, "UTF-8");
        } catch (IOException e) {
            throw ExceptionUtils.unchecked(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    /**
     * Spring 搜索资源文件
     * @param locationPattern
     * @author ThinkGem
     */
    public static Resource[] getResources(String locationPattern) {
        try {
            Resource[] resources = resourceResolver.getResources(locationPattern);
            return resources;
        } catch (IOException e) {
            throw ExceptionUtils.unchecked(e);
        }
    }
}

19 View Source File : ResourceUtil.java
License : GNU Affero General Public License v3.0
Project Creator : zhouhuan751312

/**
 * <p>资源供给</p>
 *
 * @author: zhouzhou Emall:[email protected]
 * @date: 2019-03-26 17:57
 * @web: http://www.j2eefast.com
 * @version: 1.0.1
 */
public clreplaced ResourceUtil extends org.springframework.util.ResourceUtils {

    private static ResourceLoader resourceLoader;

    private static ResourcePatternResolver resourceResolver;

    static {
        resourceLoader = new DefaultResourceLoader();
        resourceResolver = new PathMatchingResourcePatternResolver(resourceLoader);
    }

    /**
     * 获取资源加载器(可读取jar内的文件)
     * @author ThinkGem
     */
    public static ResourceLoader getResourceLoader() {
        return resourceLoader;
    }

    /**
     * 获取ClreplacedLoader
     */
    public static ClreplacedLoader getClreplacedLoader() {
        return resourceLoader.getClreplacedLoader();
    }

    /**
     * 获取资源加载器(可读取jar内的文件)
     */
    public static Resource getResource(String location) {
        return resourceLoader.getResource(location);
    }

    /**
     * 获取资源文件流(用后记得关闭)
     * @param location
     * @author ThinkGem
     * @throws IOException
     */
    public static InputStream getResourceFileStream(String location) throws IOException {
        Resource resource = resourceLoader.getResource(location);
        return resource.getInputStream();
    }

    /**
     * 获取资源文件内容
     * @param location
     * @author ThinkGem
     */
    public static String getResourceFileContent(String location) {
        try (InputStream is = ResourceUtil.getResourceFileStream(location)) {
            return IOUtils.toString(is, "UTF-8");
        } catch (IOException e) {
            throw ExceptionUtil.unchecked(e);
        }
    }

    /**
     * Spring 搜索资源文件
     * @param locationPattern
     * @author ThinkGem
     */
    public static Resource[] getResources(String locationPattern) {
        try {
            Resource[] resources = resourceResolver.getResources(locationPattern);
            return resources;
        } catch (IOException e) {
            throw ExceptionUtil.unchecked(e);
        }
    }
}

19 View Source File : ResourceUtils.java
License : GNU Affero General Public License v3.0
Project Creator : zhouhuan751312

/**
 * 资源供给类
 * @author ThinkGem
 * @version 2016-9-16
 */
@Slf4j
public clreplaced ResourceUtils extends org.springframework.util.ResourceUtils {

    private static ResourceLoader resourceLoader;

    private static ResourcePatternResolver resourceResolver;

    static {
        resourceLoader = new DefaultResourceLoader();
        resourceResolver = new PathMatchingResourcePatternResolver(resourceLoader);
    }

    /**
     * 获取资源加载器(可读取jar内的文件)
     * @author ThinkGem
     */
    public static ResourceLoader getResourceLoader() {
        return resourceLoader;
    }

    /**
     * 获取ClreplacedLoader
     */
    public static ClreplacedLoader getClreplacedLoader() {
        return resourceLoader.getClreplacedLoader();
    }

    /**
     * 获取资源加载器(可读取jar内的文件)
     */
    public static Resource getResource(String location) {
        return resourceLoader.getResource(location);
    }

    /**
     * 获取资源文件流(用后记得关闭)
     * @param location
     * @author ThinkGem
     * @throws IOException
     */
    public static InputStream getResourceFileStream(String location) throws IOException {
        Resource resource = resourceLoader.getResource(location);
        return resource.getInputStream();
    }

    /**
     * 获取资源文件内容
     * @param location
     * @author ThinkGem
     */
    public static String getResourceFileContent(String location) {
        try (InputStream is = ResourceUtils.getResourceFileStream(location)) {
            return IOUtils.toString(is, "UTF-8");
        } catch (IOException e) {
            log.error("获取资源文件内容", e);
        }
        return "";
    }

    /**
     * Spring 搜索资源文件
     * @param locationPattern
     * @author ThinkGem
     */
    public static Resource[] getResources(String locationPattern) {
        try {
            Resource[] resources = resourceResolver.getResources(locationPattern);
            return resources;
        } catch (IOException e) {
            log.error("搜索资源文件", e);
        }
        return null;
    }
}

19 View Source File : AwareService.java
License : GNU General Public License v3.0
Project Creator : zhonghuasheng

@Service
public clreplaced AwareService implements BeanNameAware, ResourceLoaderAware {

    private String beanName;

    private ResourceLoader resourceLoader;

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public void print() {
        System.out.println("BeanName is " + beanName);
        Resource resource = resourceLoader.getResource("clreplacedpath:el-test.txt");
        try {
            System.out.println(IOUtils.toString(resource.getInputStream(), "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

19 View Source File : AwareService.java
License : GNU General Public License v3.0
Project Creator : zhonghuasheng

@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
    this.resourceLoader = resourceLoader;
}

19 View Source File : CustomScannerRegistrar.java
License : Apache License 2.0
Project Creator : zhangjiayi0608

@Slf4j
public clreplaced CustomScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

    private static final String SPRING_BEAN_BASE_PACKAGE = "github.zayn.spring";

    private static final String BASE_PACKAGE_ATTRIBUTE_NAME = "basePackage";

    private ResourceLoader resourceLoader;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        // get the attributes and values ​​of RpcScan annotation
        AnnotationAttributes rpcScanAnnotationAttributes = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(RpcPackageScan.clreplaced.getName()));
        String[] rpcScanBasePackages = new String[0];
        if (rpcScanAnnotationAttributes != null) {
            // get the value of the basePackage property
            rpcScanBasePackages = rpcScanAnnotationAttributes.getStringArray(BASE_PACKAGE_ATTRIBUTE_NAME);
        }
        if (rpcScanBasePackages.length == 0) {
            rpcScanBasePackages = new String[] { ((StandardAnnotationMetadata) annotationMetadata).getIntrospectedClreplaced().getPackage().getName() };
        }
        // Scan the RpcService annotation
        CustomScanner rpcServiceScanner = new CustomScanner(beanDefinitionRegistry, RpcService.clreplaced);
        // Scan the Component annotation
        CustomScanner springBeanScanner = new CustomScanner(beanDefinitionRegistry, Component.clreplaced);
        if (resourceLoader != null) {
            rpcServiceScanner.setResourceLoader(resourceLoader);
            springBeanScanner.setResourceLoader(resourceLoader);
        }
        int springBeanAmount = springBeanScanner.scan(SPRING_BEAN_BASE_PACKAGE);
        log.info("springBeanScanner扫描的数量 [{}]", springBeanAmount);
        int rpcServiceCount = rpcServiceScanner.scan(rpcScanBasePackages);
        log.info("rpcServiceScanner扫描的数量 [{}]", rpcServiceCount);
    }
}

19 View Source File : SpringBootMockServletContext.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * {@link MockServletContext} implementation for Spring Boot. Respects well-known Spring
 * Boot resource locations and uses an empty directory for "/" if no locations can be
 * found.
 *
 * @author Phillip Webb
 * @since 1.4.0
 */
public clreplaced SpringBootMockServletContext extends MockServletContext {

    private static final String[] SPRING_BOOT_RESOURCE_LOCATIONS = new String[] { "clreplacedpath:META-INF/resources", "clreplacedpath:resources", "clreplacedpath:static", "clreplacedpath:public" };

    private final ResourceLoader resourceLoader;

    private File emptyRootFolder;

    public SpringBootMockServletContext(String resourceBasePath) {
        this(resourceBasePath, new FileSystemResourceLoader());
    }

    public SpringBootMockServletContext(String resourceBasePath, ResourceLoader resourceLoader) {
        super(resourceBasePath, resourceLoader);
        this.resourceLoader = resourceLoader;
    }

    @Override
    protected String getResourceLocation(String path) {
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        String resourceLocation = getResourceBasePathLocation(path);
        if (exists(resourceLocation)) {
            return resourceLocation;
        }
        for (String prefix : SPRING_BOOT_RESOURCE_LOCATIONS) {
            resourceLocation = prefix + path;
            if (exists(resourceLocation)) {
                return resourceLocation;
            }
        }
        return super.getResourceLocation(path);
    }

    protected final String getResourceBasePathLocation(String path) {
        return super.getResourceLocation(path);
    }

    private boolean exists(String resourceLocation) {
        try {
            Resource resource = this.resourceLoader.getResource(resourceLocation);
            return resource.exists();
        } catch (Exception ex) {
            return false;
        }
    }

    @Override
    public URL getResource(String path) throws MalformedURLException {
        URL resource = super.getResource(path);
        if (resource == null && "/".equals(path)) {
            // Liquibase replacedumes that "/" always exists, if we don't have a directory
            // use a temporary location.
            try {
                if (this.emptyRootFolder == null) {
                    synchronized (this) {
                        File tempFolder = File.createTempFile("spr", "servlet");
                        tempFolder.delete();
                        tempFolder.mkdirs();
                        tempFolder.deleteOnExit();
                        this.emptyRootFolder = tempFolder;
                    }
                }
                return this.emptyRootFolder.toURI().toURL();
            } catch (IOException ex) {
            // Ignore
            }
        }
        return resource;
    }
}

19 View Source File : ClassLoaderFilesResourcePatternResolverTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void customResourceLoaderIsUsedInWebApplication() {
    GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext());
    ResourceLoader resourceLoader = mock(ResourceLoader.clreplaced);
    context.setResourceLoader(resourceLoader);
    this.resolver = new ClreplacedLoaderFilesResourcePatternResolver(context, this.files);
    this.resolver.getResource("foo.txt");
    verify(resourceLoader).getResource("foo.txt");
}

19 View Source File : ClassLoaderFilesResourcePatternResolverTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void customResourceLoaderIsUsedInNonWebApplication() {
    GenericApplicationContext context = new GenericApplicationContext();
    ResourceLoader resourceLoader = mock(ResourceLoader.clreplaced);
    context.setResourceLoader(resourceLoader);
    this.resolver = new ClreplacedLoaderFilesResourcePatternResolver(context, this.files);
    this.resolver.getResource("foo.txt");
    verify(resourceLoader).getResource("foo.txt");
}

19 View Source File : Restarter.java
License : Apache License 2.0
Project Creator : yuanmabiji

private void prepare(GenericApplicationContext applicationContext) {
    ResourceLoader resourceLoader = new ClreplacedLoaderFilesResourcePatternResolver(applicationContext, this.clreplacedLoaderFiles);
    applicationContext.setResourceLoader(resourceLoader);
}

19 View Source File : JspTemplateAvailabilityProviderTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link JspTemplateAvailabilityProvider}.
 *
 * @author Yunkun Huang
 */
public clreplaced JspTemplateAvailabilityProviderTests {

    private final JspTemplateAvailabilityProvider provider = new JspTemplateAvailabilityProvider();

    private final ResourceLoader resourceLoader = new DefaultResourceLoader();

    private final MockEnvironment environment = new MockEnvironment();

    @Test
    public void availabilityOfTemplateThatDoesNotExist() {
        replacedertThat(isTemplateAvailable("whatever")).isFalse();
    }

    @Test
    public void availabilityOfTemplateWithCustomPrefix() {
        this.environment.setProperty("spring.mvc.view.prefix", "clreplacedpath:/custom-templates/");
        replacedertThat(isTemplateAvailable("custom.jsp")).isTrue();
    }

    @Test
    public void availabilityOfTemplateWithCustomSuffix() {
        this.environment.setProperty("spring.mvc.view.prefix", "clreplacedpath:/custom-templates/");
        this.environment.setProperty("spring.mvc.view.suffix", ".jsp");
        replacedertThat(isTemplateAvailable("suffixed")).isTrue();
    }

    private boolean isTemplateAvailable(String view) {
        return this.provider.isTemplateAvailable(view, this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader);
    }
}

19 View Source File : ThymeleafTemplateAvailabilityProviderTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link ThymeleafTemplateAvailabilityProvider}.
 *
 * @author Andy Wilkinson
 */
public clreplaced ThymeleafTemplateAvailabilityProviderTests {

    private final TemplateAvailabilityProvider provider = new ThymeleafTemplateAvailabilityProvider();

    private final ResourceLoader resourceLoader = new DefaultResourceLoader();

    private final MockEnvironment environment = new MockEnvironment();

    @Test
    public void availabilityOfTemplateInDefaultLocation() {
        replacedertThat(this.provider.isTemplateAvailable("home", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isTrue();
    }

    @Test
    public void availabilityOfTemplateThatDoesNotExist() {
        replacedertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isFalse();
    }

    @Test
    public void availabilityOfTemplateWithCustomPrefix() {
        this.environment.setProperty("spring.thymeleaf.prefix", "clreplacedpath:/custom-templates/");
        replacedertThat(this.provider.isTemplateAvailable("custom", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isTrue();
    }

    @Test
    public void availabilityOfTemplateWithCustomSuffix() {
        this.environment.setProperty("spring.thymeleaf.suffix", ".thymeleaf");
        replacedertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isTrue();
    }
}

19 View Source File : TemplateAvailabilityProvidersTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link TemplateAvailabilityProviders}.
 *
 * @author Phillip Webb
 */
public clreplaced TemplateAvailabilityProvidersTests {

    private TemplateAvailabilityProviders providers;

    @Mock
    private TemplateAvailabilityProvider provider;

    private String view = "view";

    private ClreplacedLoader clreplacedLoader = getClreplaced().getClreplacedLoader();

    private MockEnvironment environment = new MockEnvironment();

    @Mock
    private ResourceLoader resourceLoader;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        this.providers = new TemplateAvailabilityProviders(Collections.singleton(this.provider));
    }

    @Test
    public void createWhenApplicationContextIsNullShouldThrowException() {
        replacedertThatIllegalArgumentException().isThrownBy(() -> new TemplateAvailabilityProviders((ApplicationContext) null)).withMessageContaining("ClreplacedLoader must not be null");
    }

    @Test
    public void createWhenUsingApplicationContextShouldLoadProviders() {
        ApplicationContext applicationContext = mock(ApplicationContext.clreplaced);
        given(applicationContext.getClreplacedLoader()).willReturn(this.clreplacedLoader);
        TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders(applicationContext);
        replacedertThat(providers.getProviders()).isNotEmpty();
        verify(applicationContext).getClreplacedLoader();
    }

    @Test
    public void createWhenClreplacedLoaderIsNullShouldThrowException() {
        replacedertThatIllegalArgumentException().isThrownBy(() -> new TemplateAvailabilityProviders((ClreplacedLoader) null)).withMessageContaining("ClreplacedLoader must not be null");
    }

    @Test
    public void createWhenUsingClreplacedLoaderShouldLoadProviders() {
        TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders(this.clreplacedLoader);
        replacedertThat(providers.getProviders()).isNotEmpty();
    }

    @Test
    public void createWhenProvidersIsNullShouldThrowException() {
        replacedertThatIllegalArgumentException().isThrownBy(() -> new TemplateAvailabilityProviders((Collection<TemplateAvailabilityProvider>) null)).withMessageContaining("Providers must not be null");
    }

    @Test
    public void createWhenUsingProvidersShouldUseProviders() {
        TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders(Collections.singleton(this.provider));
        replacedertThat(providers.getProviders()).containsOnly(this.provider);
    }

    @Test
    public void getProviderWhenApplicationContextIsNullShouldThrowException() {
        replacedertThatIllegalArgumentException().isThrownBy(() -> this.providers.getProvider(this.view, null)).withMessageContaining("ApplicationContext must not be null");
    }

    @Test
    public void getProviderWhenViewIsNullShouldThrowException() {
        replacedertThatIllegalArgumentException().isThrownBy(() -> this.providers.getProvider(null, this.environment, this.clreplacedLoader, this.resourceLoader)).withMessageContaining("View must not be null");
    }

    @Test
    public void getProviderWhenEnvironmentIsNullShouldThrowException() {
        replacedertThatIllegalArgumentException().isThrownBy(() -> this.providers.getProvider(this.view, null, this.clreplacedLoader, this.resourceLoader)).withMessageContaining("Environment must not be null");
    }

    @Test
    public void getProviderWhenClreplacedLoaderIsNullShouldThrowException() {
        replacedertThatIllegalArgumentException().isThrownBy(() -> this.providers.getProvider(this.view, this.environment, null, this.resourceLoader)).withMessageContaining("ClreplacedLoader must not be null");
    }

    @Test
    public void getProviderWhenResourceLoaderIsNullShouldThrowException() {
        replacedertThatIllegalArgumentException().isThrownBy(() -> this.providers.getProvider(this.view, this.environment, this.clreplacedLoader, null)).withMessageContaining("ResourceLoader must not be null");
    }

    @Test
    public void getProviderWhenNoneMatchShouldReturnNull() {
        TemplateAvailabilityProvider found = this.providers.getProvider(this.view, this.environment, this.clreplacedLoader, this.resourceLoader);
        replacedertThat(found).isNull();
        verify(this.provider).isTemplateAvailable(this.view, this.environment, this.clreplacedLoader, this.resourceLoader);
    }

    @Test
    public void getProviderWhenMatchShouldReturnProvider() {
        given(this.provider.isTemplateAvailable(this.view, this.environment, this.clreplacedLoader, this.resourceLoader)).willReturn(true);
        TemplateAvailabilityProvider found = this.providers.getProvider(this.view, this.environment, this.clreplacedLoader, this.resourceLoader);
        replacedertThat(found).isSameAs(this.provider);
    }

    @Test
    public void getProviderShouldCacheMatchResult() {
        given(this.provider.isTemplateAvailable(this.view, this.environment, this.clreplacedLoader, this.resourceLoader)).willReturn(true);
        this.providers.getProvider(this.view, this.environment, this.clreplacedLoader, this.resourceLoader);
        this.providers.getProvider(this.view, this.environment, this.clreplacedLoader, this.resourceLoader);
        verify(this.provider, times(1)).isTemplateAvailable(this.view, this.environment, this.clreplacedLoader, this.resourceLoader);
    }

    @Test
    public void getProviderShouldCacheNoMatchResult() {
        this.providers.getProvider(this.view, this.environment, this.clreplacedLoader, this.resourceLoader);
        this.providers.getProvider(this.view, this.environment, this.clreplacedLoader, this.resourceLoader);
        verify(this.provider, times(1)).isTemplateAvailable(this.view, this.environment, this.clreplacedLoader, this.resourceLoader);
    }

    @Test
    public void getProviderWhenCacheDisabledShouldNotUseCache() {
        given(this.provider.isTemplateAvailable(this.view, this.environment, this.clreplacedLoader, this.resourceLoader)).willReturn(true);
        this.environment.setProperty("spring.template.provider.cache", "false");
        this.providers.getProvider(this.view, this.environment, this.clreplacedLoader, this.resourceLoader);
        this.providers.getProvider(this.view, this.environment, this.clreplacedLoader, this.resourceLoader);
        verify(this.provider, times(2)).isTemplateAvailable(this.view, this.environment, this.clreplacedLoader, this.resourceLoader);
    }
}

19 View Source File : GroovyTemplateAvailabilityProviderTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link GroovyTemplateAvailabilityProvider}.
 *
 * @author Andy Wilkinson
 */
public clreplaced GroovyTemplateAvailabilityProviderTests {

    private TemplateAvailabilityProvider provider = new GroovyTemplateAvailabilityProvider();

    private ResourceLoader resourceLoader = new DefaultResourceLoader();

    private MockEnvironment environment = new MockEnvironment();

    @Test
    public void availabilityOfTemplateInDefaultLocation() {
        replacedertThat(this.provider.isTemplateAvailable("home", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isTrue();
    }

    @Test
    public void availabilityOfTemplateThatDoesNotExist() {
        replacedertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isFalse();
    }

    @Test
    public void availabilityOfTemplateWithCustomLoaderPath() {
        this.environment.setProperty("spring.groovy.template.resource-loader-path", "clreplacedpath:/custom-templates/");
        replacedertThat(this.provider.isTemplateAvailable("custom", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isTrue();
    }

    @Test
    public void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() {
        this.environment.setProperty("spring.groovy.template.resource-loader-path[0]", "clreplacedpath:/custom-templates/");
        replacedertThat(this.provider.isTemplateAvailable("custom", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isTrue();
    }

    @Test
    public void availabilityOfTemplateWithCustomPrefix() {
        this.environment.setProperty("spring.groovy.template.prefix", "prefix/");
        replacedertThat(this.provider.isTemplateAvailable("prefixed", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isTrue();
    }

    @Test
    public void availabilityOfTemplateWithCustomSuffix() {
        this.environment.setProperty("spring.groovy.template.suffix", ".groovytemplate");
        replacedertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isTrue();
    }
}

19 View Source File : FreeMarkerTemplateAvailabilityProviderTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link FreeMarkerTemplateAvailabilityProvider}.
 *
 * @author Andy Wilkinson
 */
public clreplaced FreeMarkerTemplateAvailabilityProviderTests {

    private final TemplateAvailabilityProvider provider = new FreeMarkerTemplateAvailabilityProvider();

    private final ResourceLoader resourceLoader = new DefaultResourceLoader();

    private final MockEnvironment environment = new MockEnvironment();

    @Test
    public void availabilityOfTemplateInDefaultLocation() {
        replacedertThat(this.provider.isTemplateAvailable("home", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isTrue();
    }

    @Test
    public void availabilityOfTemplateThatDoesNotExist() {
        replacedertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isFalse();
    }

    @Test
    public void availabilityOfTemplateWithCustomLoaderPath() {
        this.environment.setProperty("spring.freemarker.template-loader-path", "clreplacedpath:/custom-templates/");
        replacedertThat(this.provider.isTemplateAvailable("custom", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isTrue();
    }

    @Test
    public void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() {
        this.environment.setProperty("spring.freemarker.template-loader-path[0]", "clreplacedpath:/custom-templates/");
        replacedertThat(this.provider.isTemplateAvailable("custom", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isTrue();
    }

    @Test
    public void availabilityOfTemplateWithCustomPrefix() {
        this.environment.setProperty("spring.freemarker.prefix", "prefix/");
        replacedertThat(this.provider.isTemplateAvailable("prefixed", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isTrue();
    }

    @Test
    public void availabilityOfTemplateWithCustomSuffix() {
        this.environment.setProperty("spring.freemarker.suffix", ".freemarker");
        replacedertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader)).isTrue();
    }
}

19 View Source File : JspTemplateAvailabilityProvider.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Override
public boolean isTemplateAvailable(String view, Environment environment, ClreplacedLoader clreplacedLoader, ResourceLoader resourceLoader) {
    if (ClreplacedUtils.isPresent("org.apache.jasper.compiler.JspConfig", clreplacedLoader)) {
        String resourceName = getResourceName(view, environment);
        if (resourceLoader.getResource(resourceName).exists()) {
            return true;
        }
        return new File("src/main/webapp", resourceName).exists();
    }
    return false;
}

19 View Source File : TemplateAvailabilityProviders.java
License : Apache License 2.0
Project Creator : yuanmabiji

private TemplateAvailabilityProvider findProvider(String view, Environment environment, ClreplacedLoader clreplacedLoader, ResourceLoader resourceLoader) {
    for (TemplateAvailabilityProvider candidate : this.providers) {
        if (candidate.isTemplateAvailable(view, environment, clreplacedLoader, resourceLoader)) {
            return candidate;
        }
    }
    return null;
}

19 View Source File : PathBasedTemplateAvailabilityProvider.java
License : Apache License 2.0
Project Creator : yuanmabiji

private boolean isTemplateAvailable(String view, ResourceLoader resourceLoader, TemplateAvailabilityProperties properties) {
    String location = properties.getPrefix() + view + properties.getSuffix();
    for (String path : properties.getLoaderPath()) {
        if (resourceLoader.getResource(path + location).exists()) {
            return true;
        }
    }
    return false;
}

19 View Source File : JdbcSessionConfiguration.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Bean
@ConditionalOnMissingBean
public JdbcSessionDataSourceInitializer jdbcSessionDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader, JdbcSessionProperties properties) {
    return new JdbcSessionDataSourceInitializer(dataSource, resourceLoader, properties);
}

19 View Source File : MustacheResourceTemplateLoader.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Mustache TemplateLoader implementation that uses a prefix, suffix and the Spring
 * Resource abstraction to load a template from a file, clreplacedpath, URL etc. A
 * {@link TemplateLoader} is needed in the {@link Compiler} when you want to render
 * partials (i.e. tiles-like features).
 *
 * @author Dave Syer
 * @since 1.2.2
 * @see Mustache
 * @see Resource
 */
public clreplaced MustacheResourceTemplateLoader implements TemplateLoader, ResourceLoaderAware {

    private String prefix = "";

    private String suffix = "";

    private String charSet = "UTF-8";

    private ResourceLoader resourceLoader = new DefaultResourceLoader();

    public MustacheResourceTemplateLoader() {
    }

    public MustacheResourceTemplateLoader(String prefix, String suffix) {
        this.prefix = prefix;
        this.suffix = suffix;
    }

    /**
     * Set the charset.
     * @param charSet the charset
     */
    public void setCharset(String charSet) {
        this.charSet = charSet;
    }

    /**
     * Set the resource loader.
     * @param resourceLoader the resource loader
     */
    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public Reader getTemplate(String name) throws Exception {
        return new InputStreamReader(this.resourceLoader.getResource(this.prefix + name + this.suffix).getInputStream(), this.charSet);
    }
}

19 View Source File : MustacheResourceTemplateLoader.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Set the resource loader.
 * @param resourceLoader the resource loader
 */
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
    this.resourceLoader = resourceLoader;
}

19 View Source File : DataSourceInitializer.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Initialize a {@link DataSource} based on a matching {@link DataSourceProperties}
 * config.
 *
 * @author Dave Syer
 * @author Phillip Webb
 * @author Eddú Meléndez
 * @author Stephane Nicoll
 * @author Kazuki Shimizu
 */
clreplaced DataSourceInitializer {

    private static final Log logger = LogFactory.getLog(DataSourceInitializer.clreplaced);

    private final DataSource dataSource;

    private final DataSourceProperties properties;

    private final ResourceLoader resourceLoader;

    /**
     * Create a new instance with the {@link DataSource} to initialize and its matching
     * {@link DataSourceProperties configuration}.
     * @param dataSource the datasource to initialize
     * @param properties the matching configuration
     * @param resourceLoader the resource loader to use (can be null)
     */
    DataSourceInitializer(DataSource dataSource, DataSourceProperties properties, ResourceLoader resourceLoader) {
        this.dataSource = dataSource;
        this.properties = properties;
        this.resourceLoader = (resourceLoader != null) ? resourceLoader : new DefaultResourceLoader();
    }

    /**
     * Create a new instance with the {@link DataSource} to initialize and its matching
     * {@link DataSourceProperties configuration}.
     * @param dataSource the datasource to initialize
     * @param properties the matching configuration
     */
    DataSourceInitializer(DataSource dataSource, DataSourceProperties properties) {
        this(dataSource, properties, null);
    }

    public DataSource getDataSource() {
        return this.dataSource;
    }

    /**
     * Create the schema if necessary.
     * @return {@code true} if the schema was created
     * @see DataSourceProperties#getSchema()
     */
    public boolean createSchema() {
        List<Resource> scripts = getScripts("spring.datasource.schema", this.properties.getSchema(), "schema");
        if (!scripts.isEmpty()) {
            if (!isEnabled()) {
                logger.debug("Initialization disabled (not running DDL scripts)");
                return false;
            }
            String username = this.properties.getSchemaUsername();
            String preplacedword = this.properties.getSchemaPreplacedword();
            runScripts(scripts, username, preplacedword);
        }
        return !scripts.isEmpty();
    }

    /**
     * Initialize the schema if necessary.
     * @see DataSourceProperties#getData()
     */
    public void initSchema() {
        List<Resource> scripts = getScripts("spring.datasource.data", this.properties.getData(), "data");
        if (!scripts.isEmpty()) {
            if (!isEnabled()) {
                logger.debug("Initialization disabled (not running data scripts)");
                return;
            }
            String username = this.properties.getDataUsername();
            String preplacedword = this.properties.getDataPreplacedword();
            runScripts(scripts, username, preplacedword);
        }
    }

    private boolean isEnabled() {
        DataSourceInitializationMode mode = this.properties.getInitializationMode();
        if (mode == DataSourceInitializationMode.NEVER) {
            return false;
        }
        if (mode == DataSourceInitializationMode.EMBEDDED && !isEmbedded()) {
            return false;
        }
        return true;
    }

    private boolean isEmbedded() {
        try {
            return EmbeddedDatabaseConnection.isEmbedded(this.dataSource);
        } catch (Exception ex) {
            logger.debug("Could not determine if datasource is embedded", ex);
            return false;
        }
    }

    private List<Resource> getScripts(String propertyName, List<String> resources, String fallback) {
        if (resources != null) {
            return getResources(propertyName, resources, true);
        }
        String platform = this.properties.getPlatform();
        List<String> fallbackResources = new ArrayList<>();
        fallbackResources.add("clreplacedpath*:" + fallback + "-" + platform + ".sql");
        fallbackResources.add("clreplacedpath*:" + fallback + ".sql");
        return getResources(propertyName, fallbackResources, false);
    }

    private List<Resource> getResources(String propertyName, List<String> locations, boolean validate) {
        List<Resource> resources = new ArrayList<>();
        for (String location : locations) {
            for (Resource resource : doGetResources(location)) {
                if (resource.exists()) {
                    resources.add(resource);
                } else if (validate) {
                    throw new InvalidConfigurationPropertyValueException(propertyName, resource, "The specified resource does not exist.");
                }
            }
        }
        return resources;
    }

    private Resource[] doGetResources(String location) {
        try {
            SortedResourcesFactoryBean factory = new SortedResourcesFactoryBean(this.resourceLoader, Collections.singletonList(location));
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (Exception ex) {
            throw new IllegalStateException("Unable to load resources from " + location, ex);
        }
    }

    private void runScripts(List<Resource> resources, String username, String preplacedword) {
        if (resources.isEmpty()) {
            return;
        }
        ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.setContinueOnError(this.properties.isContinueOnError());
        populator.setSeparator(this.properties.getSeparator());
        if (this.properties.getSqlScriptEncoding() != null) {
            populator.setSqlScriptEncoding(this.properties.getSqlScriptEncoding().name());
        }
        for (Resource resource : resources) {
            populator.addScript(resource);
        }
        DataSource dataSource = this.dataSource;
        if (StringUtils.hasText(username) && StringUtils.hasText(preplacedword)) {
            dataSource = DataSourceBuilder.create(this.properties.getClreplacedLoader()).driverClreplacedName(this.properties.determineDriverClreplacedName()).url(this.properties.determineUrl()).username(username).preplacedword(preplacedword).build();
        }
        DatabasePopulatorUtils.execute(populator, dataSource);
    }
}

19 View Source File : RedisReactiveAutoConfiguration.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Bean
@ConditionalOnMissingBean(name = "reactiveRedisTemplate")
@ConditionalOnBean(ReactiveRedisConnectionFactory.clreplaced)
public ReactiveRedisTemplate<Object, Object> reactiveRedisTemplate(ReactiveRedisConnectionFactory reactiveRedisConnectionFactory, ResourceLoader resourceLoader) {
    JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer(resourceLoader.getClreplacedLoader());
    RedisSerializationContext<Object, Object> serializationContext = RedisSerializationContext.newSerializationContext().key(jdkSerializer).value(jdkSerializer).hashKey(jdkSerializer).hashValue(jdkSerializer).build();
    return new ReactiveRedisTemplate<>(reactiveRedisConnectionFactory, serializationContext);
}

19 View Source File : AbstractRepositoryConfigurationSourceSupport.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Base {@link ImportBeanDefinitionRegistrar} used to auto-configure Spring Data
 * Repositories.
 *
 * @author Phillip Webb
 * @author Dave Syer
 * @author Oliver Gierke
 */
public abstract clreplaced AbstractRepositoryConfigurationSourceSupport implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {

    private ResourceLoader resourceLoader;

    private BeanFactory beanFactory;

    private Environment environment;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClreplacedMetadata, BeanDefinitionRegistry registry) {
        new RepositoryConfigurationDelegate(getConfigurationSource(registry), this.resourceLoader, this.environment).registerRepositoriesIn(registry, getRepositoryConfigurationExtension());
    }

    private AnnotationRepositoryConfigurationSource getConfigurationSource(BeanDefinitionRegistry beanDefinitionRegistry) {
        StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(getConfiguration(), true);
        return new AnnotationRepositoryConfigurationSource(metadata, getAnnotation(), this.resourceLoader, this.environment, beanDefinitionRegistry) {

            @Override
            public Streamable<String> getBasePackages() {
                return AbstractRepositoryConfigurationSourceSupport.this.getBasePackages();
            }

            @Override
            public BootstrapMode getBootstrapMode() {
                return AbstractRepositoryConfigurationSourceSupport.this.getBootstrapMode();
            }
        };
    }

    protected Streamable<String> getBasePackages() {
        return Streamable.of(AutoConfigurationPackages.get(this.beanFactory));
    }

    /**
     * The Spring Data annotation used to enable the particular repository support.
     * @return the annotation clreplaced
     */
    protected abstract Clreplaced<? extends Annotation> getAnnotation();

    /**
     * The configuration clreplaced that will be used by Spring Boot as a template.
     * @return the configuration clreplaced
     */
    protected abstract Clreplaced<?> getConfiguration();

    /**
     * The {@link RepositoryConfigurationExtension} for the particular repository support.
     * @return the repository configuration extension
     */
    protected abstract RepositoryConfigurationExtension getRepositoryConfigurationExtension();

    /**
     * The {@link BootstrapMode} for the particular repository support. Defaults to
     * {@link BootstrapMode#DEFAULT}.
     * @return the bootstrap mode
     */
    protected BootstrapMode getBootstrapMode() {
        return BootstrapMode.DEFAULT;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}

19 View Source File : OnResourceCondition.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * {@link Condition} that checks for specific resources.
 *
 * @author Dave Syer
 * @see ConditionalOnResource
 */
@Order(Ordered.HIGHEST_PRECEDENCE + 20)
clreplaced OnResourceCondition extends SpringBootCondition {

    private final ResourceLoader defaultResourceLoader = new DefaultResourceLoader();

    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // 获得@ConditionalOnResource注解的属性元数据
        MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(ConditionalOnResource.clreplaced.getName(), true);
        // 获得资源加载器,若ConditionContext中有ResourceLoader则用ConditionContext中的,没有则用默认的
        ResourceLoader loader = (context.getResourceLoader() != null) ? context.getResourceLoader() : this.defaultResourceLoader;
        List<String> locations = new ArrayList<>();
        // 将@ConditionalOnResource中定义的resources属性值取出来装进locations集合
        collectValues(locations, attributes.get("resources"));
        replacedert.isTrue(!locations.isEmpty(), "@ConditionalOnResource annotations must specify at " + "least one resource location");
        // missing集合是装不存在指定资源的资源路径的
        List<String> missing = new ArrayList<>();
        // 遍历所有的资源路径,若指定的路径的资源不存在则将其资源路径存进missing集合中
        for (String location : locations) {
            // 这里针对有些资源路径是Placeholders的情况,即处理${}
            String resource = context.getEnvironment().resolvePlaceholders(location);
            if (!loader.getResource(resource).exists()) {
                missing.add(location);
            }
        }
        // 如果存在某个资源不存在,那么则报错
        if (!missing.isEmpty()) {
            return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnResource.clreplaced).didNotFind("resource", "resources").items(Style.QUOTE, missing));
        }
        // 所有资源都存在,那么则返回能找到就提的资源
        return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnResource.clreplaced).found("location", "locations").items(locations));
    }

    // 将@ConditionalOnResource中定义的resources属性值取出来装进locations集合
    private void collectValues(List<String> names, List<Object> values) {
        for (Object value : values) {
            for (Object item : (Object[]) value) {
                names.add((String) item);
            }
        }
    }
}

19 View Source File : BatchAutoConfiguration.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(DataSource.clreplaced)
public BatchDataSourceInitializer batchDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader) {
    return new BatchDataSourceInitializer(dataSource, resourceLoader, this.properties);
}

19 View Source File : AutoConfigurationImportSelector.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * {@link DeferredImportSelector} to handle {@link EnableAutoConfiguration
 * auto-configuration}. This clreplaced can also be subclreplaceded if a custom variant of
 * {@link EnableAutoConfiguration @EnableAutoConfiguration} is needed.
 *
 * @author Phillip Webb
 * @author Andy Wilkinson
 * @author Stephane Nicoll
 * @author Madhura Bhave
 * @since 1.3.0
 * @see EnableAutoConfiguration
 */
public clreplaced AutoConfigurationImportSelector implements DeferredImportSelector, BeanClreplacedLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {

    private static final AutoConfigurationEntry EMPTY_ENTRY = new AutoConfigurationEntry();

    private static final String[] NO_IMPORTS = {};

    private static final Log logger = LogFactory.getLog(AutoConfigurationImportSelector.clreplaced);

    private static final String PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";

    private ConfigurableListableBeanFactory beanFactory;

    private Environment environment;

    private ClreplacedLoader beanClreplacedLoader;

    private ResourceLoader resourceLoader;

    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        if (!isEnabled(annotationMetadata)) {
            return NO_IMPORTS;
        }
        // 加载spring-autoconfigure-metadata.properties文件的键值对数据到autoConfigurationMetadata,
        // 供AutoConfigurationImportSelector过滤加载。注意spring-autoconfigure-metadata.properties文件为maven build构建的时候生成的
        AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClreplacedLoader);
        // 基于@Configuration注解的元数据相关过滤条件返回自动配置类,如@SpringBootApplication(exclude = FreeMarkerAutoConfiguration.clreplaced),
        // 则要排除FreeMarkerAutoConfiguration这个自动配置类
        AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
        return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
    }

    /**
     * Return the {@link AutoConfigurationEntry} based on the {@link AnnotationMetadata}
     * of the importing {@link Configuration @Configuration} clreplaced.
     * @param autoConfigurationMetadata the auto-configuration metadata
     * @param annotationMetadata the annotation metadata of the configuration clreplaced
     * @return the auto-configurations that should be imported
     */
    // 获取符合条件的自动配置类,避免加载不必要的自动配置类从而造成内存浪费
    protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) {
        // 获取是否有配置spring.boot.enableautoconfiguration属性,默认返回true
        if (!isEnabled(annotationMetadata)) {
            return EMPTY_ENTRY;
        }
        // 获得@Congiguration标注的Configuration类即被审视introspectedClreplaced的注解数据,
        // 比如:@SpringBootApplication(exclude = FreeMarkerAutoConfiguration.clreplaced)
        // 将会获取到exclude = FreeMarkerAutoConfiguration.clreplaced和excludeName=""的注解数据
        AnnotationAttributes attributes = getAttributes(annotationMetadata);
        // 【1】得到spring.factories文件配置的所有自动配置类
        List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
        // 利用LinkedHashSet移除重复的配置类
        configurations = removeDuplicates(configurations);
        // 得到要排除的自动配置类,比如注解属性exclude的配置类
        // 比如:@SpringBootApplication(exclude = FreeMarkerAutoConfiguration.clreplaced)
        // 将会获取到exclude = FreeMarkerAutoConfiguration.clreplaced的注解数据
        Set<String> exclusions = getExclusions(annotationMetadata, attributes);
        // 检查要被排除的配置类,因为有些不是自动配置类,故要抛出异常
        checkExcludedClreplacedes(configurations, exclusions);
        // 【2】将要排除的配置类移除
        configurations.removeAll(exclusions);
        // 【3】因为从spring.factories文件获取的自动配置类太多,如果有些不必要的自动配置类都加载进内存,会造成内存浪费,因此这里需要进行过滤
        // 注意这里会调用AutoConfigurationImportFilter的match方法来判断是否符合@ConditionalOnBean,@ConditionalOnClreplaced或@ConditionalOnWebApplication,后面会重点分析一下
        configurations = filter(configurations, autoConfigurationMetadata);
        // 【4】获取了符合条件的自动配置类后,此时触发AutoConfigurationImportEvent事件,
        // 目的是告诉ConditionEvaluationReport条件评估报告器对象来记录符合条件的自动配置类
        // 该事件什么时候会被触发?--> 在刷新容器时调用invokeBeanFactoryPostProcessors后置处理器时触发
        fireAutoConfigurationImportEvents(configurations, exclusions);
        // 【5】将符合条件和要排除的自动配置类封装进AutoConfigurationEntry对象,并返回
        return new AutoConfigurationEntry(configurations, exclusions);
    }

    @Override
    public Clreplaced<? extends Group> getImportGroup() {
        return AutoConfigurationGroup.clreplaced;
    }

    protected boolean isEnabled(AnnotationMetadata metadata) {
        if (getClreplaced() == AutoConfigurationImportSelector.clreplaced) {
            // 获取是否有配置spring.boot.enableautoconfiguration属性,默认返回true
            return getEnvironment().getProperty(EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, Boolean.clreplaced, true);
        }
        return true;
    }

    /**
     * Return the appropriate {@link AnnotationAttributes} from the
     * {@link AnnotationMetadata}. By default this method will return attributes for
     * {@link #getAnnotationClreplaced()}.
     * @param metadata the annotation metadata
     * @return annotation attributes
     */
    protected AnnotationAttributes getAttributes(AnnotationMetadata metadata) {
        String name = getAnnotationClreplaced().getName();
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(name, true));
        replacedert.notNull(attributes, () -> "No auto-configuration attributes found. Is " + metadata.getClreplacedName() + " annotated with " + ClreplacedUtils.getShortName(name) + "?");
        return attributes;
    }

    /**
     * Return the source annotation clreplaced used by the selector.
     * @return the annotation clreplaced
     */
    protected Clreplaced<?> getAnnotationClreplaced() {
        return EnableAutoConfiguration.clreplaced;
    }

    /**
     * Return the auto-configuration clreplaced names that should be considered. By default
     * this method will load candidates using {@link SpringFactoriesLoader} with
     * {@link #getSpringFactoriesLoaderFactoryClreplaced()}.
     * @param metadata the source metadata
     * @param attributes the {@link #getAttributes(AnnotationMetadata) annotation
     * attributes}
     * @return a list of candidate configurations
     */
    protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
        List<String> configurations = // 得到所有自动配置类
        SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClreplaced(), // getSpringFactoriesLoaderFactoryClreplaced()返回EnableAutoConfiguration.clreplaced
        getBeanClreplacedLoader());
        replacedert.notEmpty(configurations, "No auto configuration clreplacedes found in META-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct.");
        return configurations;
    }

    /**
     * Return the clreplaced used by {@link SpringFactoriesLoader} to load configuration
     * candidates.
     * @return the factory clreplaced
     */
    protected Clreplaced<?> getSpringFactoriesLoaderFactoryClreplaced() {
        return EnableAutoConfiguration.clreplaced;
    }

    private void checkExcludedClreplacedes(List<String> configurations, Set<String> exclusions) {
        List<String> invalidExcludes = new ArrayList<>(exclusions.size());
        for (String exclusion : exclusions) {
            if (ClreplacedUtils.isPresent(exclusion, getClreplaced().getClreplacedLoader()) && !configurations.contains(exclusion)) {
                invalidExcludes.add(exclusion);
            }
        }
        if (!invalidExcludes.isEmpty()) {
            handleInvalidExcludes(invalidExcludes);
        }
    }

    /**
     * Handle any invalid excludes that have been specified.
     * @param invalidExcludes the list of invalid excludes (will always have at least one
     * element)
     */
    protected void handleInvalidExcludes(List<String> invalidExcludes) {
        StringBuilder message = new StringBuilder();
        for (String exclude : invalidExcludes) {
            message.append("\t- ").append(exclude).append(String.format("%n"));
        }
        throw new IllegalStateException(String.format("The following clreplacedes could not be excluded because they are" + " not auto-configuration clreplacedes:%n%s", message));
    }

    /**
     * Return any exclusions that limit the candidate configurations.
     * @param metadata the source metadata
     * @param attributes the {@link #getAttributes(AnnotationMetadata) annotation
     * attributes}
     * @return exclusions or an empty set
     */
    protected Set<String> getExclusions(AnnotationMetadata metadata, AnnotationAttributes attributes) {
        Set<String> excluded = new LinkedHashSet<>();
        excluded.addAll(asList(attributes, "exclude"));
        excluded.addAll(Arrays.asList(attributes.getStringArray("excludeName")));
        excluded.addAll(getExcludeAutoConfigurationsProperty());
        return excluded;
    }

    private List<String> getExcludeAutoConfigurationsProperty() {
        if (getEnvironment() instanceof ConfigurableEnvironment) {
            Binder binder = Binder.get(getEnvironment());
            return binder.bind(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].clreplaced).map(Arrays::asList).orElse(Collections.emptyList());
        }
        String[] excludes = getEnvironment().getProperty(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].clreplaced);
        return (excludes != null) ? Arrays.asList(excludes) : Collections.emptyList();
    }

    private List<String> filter(List<String> configurations, AutoConfigurationMetadata autoConfigurationMetadata) {
        long startTime = System.nanoTime();
        // 将从spring.factories中获取的自动配置类转出字符串数组
        String[] candidates = StringUtils.toStringArray(configurations);
        // 定义skip数组,是否需要跳过。注意skip数组与candidates数组顺序一一对应
        boolean[] skip = new boolean[candidates.length];
        boolean skipped = false;
        // getAutoConfigurationImportFilters方法:拿到OnBeanCondition,OnClreplacedCondition和OnWebApplicationCondition
        // 然后遍历这三个条件类去过滤从spring.factories加载的大量配置类
        for (AutoConfigurationImportFilter filter : getAutoConfigurationImportFilters()) {
            // 调用各种aware方法,将beanClreplacedLoader,beanFactory等注入到filter对象中,
            // 这里的filter对象即OnBeanCondition,OnClreplacedCondition或OnWebApplicationCondition
            invokeAwareMethods(filter);
            // 判断各种filter来判断每个candidate(这里实质要通过candidate(自动配置类)拿到其标注的
            // @ConditionalOnClreplaced,@ConditionalOnBean和@ConditionalOnWebApplication里面的注解值)是否匹配,
            // 注意candidates数组与match数组一一对应
            /* *********************【重点关注】******************************* */
            boolean[] match = filter.match(candidates, autoConfigurationMetadata);
            // 遍历match数组,注意match顺序跟candidates的自动配置类一一对应
            for (int i = 0; i < match.length; i++) {
                // 若有不匹配的话
                if (!match[i]) {
                    // 不匹配的将记录在skip数组,标志skip[i]为true,也与candidates数组一一对应
                    skip[i] = true;
                    // 因为不匹配,将相应的自动配置类置空
                    candidates[i] = null;
                    // 标注skipped为true
                    skipped = true;
                }
            }
        }
        // 这里表示若所有自动配置类经过OnBeanCondition,OnClreplacedCondition和OnWebApplicationCondition过滤后,全部都匹配的话,则全部原样返回
        if (!skipped) {
            return configurations;
        }
        // 建立result集合来装匹配的自动配置类
        List<String> result = new ArrayList<>(candidates.length);
        for (int i = 0; i < candidates.length; i++) {
            // 若skip[i]为false,则说明是符合条件的自动配置类,此时添加到result集合中
            if (!skip[i]) {
                result.add(candidates[i]);
            }
        }
        // 打印日志
        if (logger.isTraceEnabled()) {
            int numberFiltered = configurations.size() - result.size();
            logger.trace("Filtered " + numberFiltered + " auto configuration clreplaced in " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) + " ms");
        }
        // 最后返回符合条件的自动配置类
        return new ArrayList<>(result);
    }

    // 拿到OnBeanCondition,OnClreplacedCondition和OnWebApplicationCondition
    protected List<AutoConfigurationImportFilter> getAutoConfigurationImportFilters() {
        return SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.clreplaced, this.beanClreplacedLoader);
    }

    protected final <T> List<T> removeDuplicates(List<T> list) {
        return new ArrayList<>(new LinkedHashSet<>(list));
    }

    protected final List<String> asList(AnnotationAttributes attributes, String name) {
        String[] value = attributes.getStringArray(name);
        return Arrays.asList((value != null) ? value : new String[0]);
    }

    private void fireAutoConfigurationImportEvents(List<String> configurations, Set<String> exclusions) {
        // 从spring.factories总获取到AutoConfigurationImportListener即ConditionEvaluationReportAutoConfigurationImportListener
        List<AutoConfigurationImportListener> listeners = getAutoConfigurationImportListeners();
        if (!listeners.isEmpty()) {
            // 新建一个AutoConfigurationImportEvent事件
            AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, configurations, exclusions);
            // 遍历刚获取到的AutoConfigurationImportListener
            for (AutoConfigurationImportListener listener : listeners) {
                // 这里调用各种Aware方法用于触发事件前赋值,比如设置factory,environment等
                invokeAwareMethods(listener);
                // 真正触发AutoConfigurationImportEvent事件即回调listener的onXXXEveent方法。这里用于记录自动配置类的评估信息
                listener.onAutoConfigurationImportEvent(event);
            }
        }
    }

    protected List<AutoConfigurationImportListener> getAutoConfigurationImportListeners() {
        return SpringFactoriesLoader.loadFactories(AutoConfigurationImportListener.clreplaced, this.beanClreplacedLoader);
    }

    private void invokeAwareMethods(Object instance) {
        if (instance instanceof Aware) {
            if (instance instanceof BeanClreplacedLoaderAware) {
                ((BeanClreplacedLoaderAware) instance).setBeanClreplacedLoader(this.beanClreplacedLoader);
            }
            if (instance instanceof BeanFactoryAware) {
                ((BeanFactoryAware) instance).setBeanFactory(this.beanFactory);
            }
            if (instance instanceof EnvironmentAware) {
                ((EnvironmentAware) instance).setEnvironment(this.environment);
            }
            if (instance instanceof ResourceLoaderAware) {
                ((ResourceLoaderAware) instance).setResourceLoader(this.resourceLoader);
            }
        }
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        replacedert.isInstanceOf(ConfigurableListableBeanFactory.clreplaced, beanFactory);
        this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
    }

    protected final ConfigurableListableBeanFactory getBeanFactory() {
        return this.beanFactory;
    }

    @Override
    public void setBeanClreplacedLoader(ClreplacedLoader clreplacedLoader) {
        this.beanClreplacedLoader = clreplacedLoader;
    }

    protected ClreplacedLoader getBeanClreplacedLoader() {
        return this.beanClreplacedLoader;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    protected final Environment getEnvironment() {
        return this.environment;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    protected final ResourceLoader getResourceLoader() {
        return this.resourceLoader;
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 1;
    }

    private static clreplaced AutoConfigurationGroup implements DeferredImportSelector.Group, BeanClreplacedLoaderAware, BeanFactoryAware, ResourceLoaderAware {

        private final Map<String, AnnotationMetadata> entries = new LinkedHashMap<>();

        private final List<AutoConfigurationEntry> autoConfigurationEntries = new ArrayList<>();

        private ClreplacedLoader beanClreplacedLoader;

        private BeanFactory beanFactory;

        private ResourceLoader resourceLoader;

        private AutoConfigurationMetadata autoConfigurationMetadata;

        @Override
        public void setBeanClreplacedLoader(ClreplacedLoader clreplacedLoader) {
            this.beanClreplacedLoader = clreplacedLoader;
        }

        @Override
        public void setBeanFactory(BeanFactory beanFactory) {
            this.beanFactory = beanFactory;
        }

        @Override
        public void setResourceLoader(ResourceLoader resourceLoader) {
            this.resourceLoader = resourceLoader;
        }

        // 这里用来处理自动配置类,比如过滤掉不符合匹配条件的自动配置类
        @Override
        public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) {
            replacedert.state(deferredImportSelector instanceof AutoConfigurationImportSelector, () -> String.format("Only %s implementations are supported, got %s", AutoConfigurationImportSelector.clreplaced.getSimpleName(), deferredImportSelector.getClreplaced().getName()));
            // 1,调用getAutoConfigurationEntry方法得到自动配置类放入autoConfigurationEntry对象中
            AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector).getAutoConfigurationEntry(// 这里注意autoConfigurationMetadata和annotationMetadata的区别,autoConfigurationMetadata的properteis的键是自动配置类+条件注解类,值是条件注解类里面的属性值,TODO 唯一得注意的是有些自定义的配置类或加载配置类不在里面,这里不太明白
            getAutoConfigurationMetadata(), // annotationMetadata即的启动类标注有@SpringBootApplication的注解属性值
            annotationMetadata);
            // 2,又将封装了自动配置类的autoConfigurationEntry对象装进autoConfigurationEntries集合
            this.autoConfigurationEntries.add(autoConfigurationEntry);
            // 3,遍历刚获取的自动配置类
            for (String importClreplacedName : autoConfigurationEntry.getConfigurations()) {
                // 这里符合条件的自动配置类作为key,annotationMetadata作为值放进entries集合
                this.entries.putIfAbsent(importClreplacedName, annotationMetadata);
            }
        }

        // selectImports这个方法在上面的process方法后面调用
        @Override
        public Iterable<Entry> selectImports() {
            if (this.autoConfigurationEntries.isEmpty()) {
                return Collections.emptyList();
            }
            // 这里得到所有要排除的自动配置类的set集合
            Set<String> allExclusions = this.autoConfigurationEntries.stream().map(AutoConfigurationEntry::getExclusions).flatMap(Collection::stream).collect(Collectors.toSet());
            // 这里得到经过滤后所有符合条件的自动配置类的set集合
            Set<String> processedConfigurations = this.autoConfigurationEntries.stream().map(AutoConfigurationEntry::getConfigurations).flatMap(Collection::stream).collect(Collectors.toCollection(LinkedHashSet::new));
            // 移除掉要排除的自动配置类
            processedConfigurations.removeAll(allExclusions);
            // 对标注有@Order注解的自动配置类进行排序,
            return sortAutoConfigurations(processedConfigurations, getAutoConfigurationMetadata()).stream().map((importClreplacedName) -> new Entry(this.entries.get(importClreplacedName), importClreplacedName)).collect(Collectors.toList());
        }

        private AutoConfigurationMetadata getAutoConfigurationMetadata() {
            if (this.autoConfigurationMetadata == null) {
                this.autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClreplacedLoader);
            }
            return this.autoConfigurationMetadata;
        }

        private List<String> sortAutoConfigurations(Set<String> configurations, AutoConfigurationMetadata autoConfigurationMetadata) {
            return new AutoConfigurationSorter(getMetadataReaderFactory(), autoConfigurationMetadata).getInPriorityOrder(configurations);
        }

        private MetadataReaderFactory getMetadataReaderFactory() {
            try {
                return this.beanFactory.getBean(SharedMetadataReaderFactoryContextInitializer.BEAN_NAME, MetadataReaderFactory.clreplaced);
            } catch (NoSuchBeanDefinitionException ex) {
                return new CachingMetadataReaderFactory(this.resourceLoader);
            }
        }
    }

    protected static clreplaced AutoConfigurationEntry {

        private final List<String> configurations;

        private final Set<String> exclusions;

        private AutoConfigurationEntry() {
            this.configurations = Collections.emptyList();
            this.exclusions = Collections.emptySet();
        }

        /**
         * Create an entry with the configurations that were contributed and their
         * exclusions.
         * @param configurations the configurations that should be imported
         * @param exclusions the exclusions that were applied to the original list
         */
        AutoConfigurationEntry(Collection<String> configurations, Collection<String> exclusions) {
            this.configurations = new ArrayList<>(configurations);
            this.exclusions = new HashSet<>(exclusions);
        }

        public List<String> getConfigurations() {
            return this.configurations;
        }

        public Set<String> getExclusions() {
            return this.exclusions;
        }
    }
}

19 View Source File : SpringApplicationBannerPrinter.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Clreplaced used by {@link SpringApplication} to print the application banner.
 *
 * @author Phillip Webb
 */
clreplaced SpringApplicationBannerPrinter {

    static final String BANNER_LOCATION_PROPERTY = "spring.banner.location";

    static final String BANNER_IMAGE_LOCATION_PROPERTY = "spring.banner.image.location";

    static final String DEFAULT_BANNER_LOCATION = "banner.txt";

    static final String[] IMAGE_EXTENSION = { "gif", "jpg", "png" };

    private static final Banner DEFAULT_BANNER = new SpringBootBanner();

    private final ResourceLoader resourceLoader;

    private final Banner fallbackBanner;

    SpringApplicationBannerPrinter(ResourceLoader resourceLoader, Banner fallbackBanner) {
        this.resourceLoader = resourceLoader;
        this.fallbackBanner = fallbackBanner;
    }

    public Banner print(Environment environment, Clreplaced<?> sourceClreplaced, Log logger) {
        Banner banner = getBanner(environment);
        try {
            logger.info(createStringFromBanner(banner, environment, sourceClreplaced));
        } catch (UnsupportedEncodingException ex) {
            logger.warn("Failed to create String for banner", ex);
        }
        return new PrintedBanner(banner, sourceClreplaced);
    }

    public Banner print(Environment environment, Clreplaced<?> sourceClreplaced, PrintStream out) {
        Banner banner = getBanner(environment);
        banner.printBanner(environment, sourceClreplaced, out);
        return new PrintedBanner(banner, sourceClreplaced);
    }

    private Banner getBanner(Environment environment) {
        Banners banners = new Banners();
        banners.addIfNotNull(getImageBanner(environment));
        banners.addIfNotNull(getTextBanner(environment));
        if (banners.hasAtLeastOneBanner()) {
            return banners;
        }
        if (this.fallbackBanner != null) {
            return this.fallbackBanner;
        }
        return DEFAULT_BANNER;
    }

    private Banner getTextBanner(Environment environment) {
        String location = environment.getProperty(BANNER_LOCATION_PROPERTY, DEFAULT_BANNER_LOCATION);
        Resource resource = this.resourceLoader.getResource(location);
        if (resource.exists()) {
            return new ResourceBanner(resource);
        }
        return null;
    }

    private Banner getImageBanner(Environment environment) {
        String location = environment.getProperty(BANNER_IMAGE_LOCATION_PROPERTY);
        if (StringUtils.hasLength(location)) {
            Resource resource = this.resourceLoader.getResource(location);
            return resource.exists() ? new ImageBanner(resource) : null;
        }
        for (String ext : IMAGE_EXTENSION) {
            Resource resource = this.resourceLoader.getResource("banner." + ext);
            if (resource.exists()) {
                return new ImageBanner(resource);
            }
        }
        return null;
    }

    private String createStringFromBanner(Banner banner, Environment environment, Clreplaced<?> mainApplicationClreplaced) throws UnsupportedEncodingException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        banner.printBanner(environment, mainApplicationClreplaced, new PrintStream(baos));
        String charset = environment.getProperty("spring.banner.charset", "UTF-8");
        return baos.toString(charset);
    }

    /**
     * {@link Banner} comprised of other {@link Banner Banners}.
     */
    private static clreplaced Banners implements Banner {

        private final List<Banner> banners = new ArrayList<>();

        public void addIfNotNull(Banner banner) {
            if (banner != null) {
                this.banners.add(banner);
            }
        }

        public boolean hasAtLeastOneBanner() {
            return !this.banners.isEmpty();
        }

        @Override
        public void printBanner(Environment environment, Clreplaced<?> sourceClreplaced, PrintStream out) {
            for (Banner banner : this.banners) {
                banner.printBanner(environment, sourceClreplaced, out);
            }
        }
    }

    /**
     * Decorator that allows a {@link Banner} to be printed again without needing to
     * specify the source clreplaced.
     */
    private static clreplaced PrintedBanner implements Banner {

        private final Banner banner;

        private final Clreplaced<?> sourceClreplaced;

        PrintedBanner(Banner banner, Clreplaced<?> sourceClreplaced) {
            this.banner = banner;
            this.sourceClreplaced = sourceClreplaced;
        }

        @Override
        public void printBanner(Environment environment, Clreplaced<?> sourceClreplaced, PrintStream out) {
            sourceClreplaced = (sourceClreplaced != null) ? sourceClreplaced : this.sourceClreplaced;
            this.banner.printBanner(environment, sourceClreplaced, out);
        }
    }
}

19 View Source File : AbstractDataSourceInitializer.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Base clreplaced used for {@link DataSource} initialization.
 *
 * @author Vedran Pavic
 * @author Stephane Nicoll
 * @since 1.5.0
 */
public abstract clreplaced AbstractDataSourceInitializer {

    private static final String PLATFORM_PLACEHOLDER = "@@platform@@";

    private final DataSource dataSource;

    private final ResourceLoader resourceLoader;

    protected AbstractDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader) {
        replacedert.notNull(dataSource, "DataSource must not be null");
        replacedert.notNull(resourceLoader, "ResourceLoader must not be null");
        this.dataSource = dataSource;
        this.resourceLoader = resourceLoader;
    }

    @PostConstruct
    protected void initialize() {
        if (!isEnabled()) {
            return;
        }
        ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        String schemaLocation = getSchemaLocation();
        if (schemaLocation.contains(PLATFORM_PLACEHOLDER)) {
            String platform = getDatabaseName();
            schemaLocation = schemaLocation.replace(PLATFORM_PLACEHOLDER, platform);
        }
        populator.addScript(this.resourceLoader.getResource(schemaLocation));
        populator.setContinueOnError(true);
        customize(populator);
        DatabasePopulatorUtils.execute(populator, this.dataSource);
    }

    private boolean isEnabled() {
        if (getMode() == DataSourceInitializationMode.NEVER) {
            return false;
        }
        if (getMode() == DataSourceInitializationMode.EMBEDDED && !EmbeddedDatabaseConnection.isEmbedded(this.dataSource)) {
            return false;
        }
        return true;
    }

    /**
     * Customize the {@link ResourceDatabasePopulator}.
     * @param populator the configured database populator
     */
    protected void customize(ResourceDatabasePopulator populator) {
    }

    protected abstract DataSourceInitializationMode getMode();

    protected abstract String getSchemaLocation();

    protected String getDatabaseName() {
        try {
            String productName = JdbcUtils.commonDatabaseName(JdbcUtils.extractDatabaseMetaData(this.dataSource, "getDatabaseProductName").toString());
            DatabaseDriver databaseDriver = DatabaseDriver.fromProductName(productName);
            if (databaseDriver == DatabaseDriver.UNKNOWN) {
                throw new IllegalStateException("Unable to detect database type");
            }
            return databaseDriver.getId();
        } catch (MetaDataAccessException ex) {
            throw new IllegalStateException("Unable to detect database type", ex);
        }
    }
}

19 View Source File : ConfigFileApplicationListener.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Add config file property sources to the specified environment.
 * @param environment the environment to add source to
 * @param resourceLoader the resource loader
 * @see #addPostProcessors(ConfigurableApplicationContext)
 */
protected void addPropertySources(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
    RandomValuePropertySource.addToEnvironment(environment);
    // 加载配置文件等配置属性,TODO:应该有配置文件和外部配置等?【加载配置文件的主线】
    new Loader(environment, resourceLoader).load();
}

19 View Source File : SpringApplicationBuilder.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * {@link ResourceLoader} for the application context. If a custom clreplaced loader is
 * needed, this is where it would be added.
 * @param resourceLoader the resource loader to set.
 * @return the current builder
 */
public SpringApplicationBuilder resourceLoader(ResourceLoader resourceLoader) {
    this.application.setResourceLoader(resourceLoader);
    return this;
}

19 View Source File : BeanDefinitionLoader.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Loads bean definitions from underlying sources, including XML and JavaConfig. Acts as a
 * simple facade over {@link AnnotatedBeanDefinitionReader},
 * {@link XmlBeanDefinitionReader} and {@link ClreplacedPathBeanDefinitionScanner}. See
 * {@link SpringApplication} for the types of sources that are supported.
 *
 * @author Phillip Webb
 * @see #setBeanNameGenerator(BeanNameGenerator)
 */
clreplaced BeanDefinitionLoader {

    private final Object[] sources;

    private final AnnotatedBeanDefinitionReader annotatedReader;

    private final XmlBeanDefinitionReader xmlReader;

    private BeanDefinitionReader groovyReader;

    private final ClreplacedPathBeanDefinitionScanner scanner;

    private ResourceLoader resourceLoader;

    /**
     * Create a new {@link BeanDefinitionLoader} that will load beans into the specified
     * {@link BeanDefinitionRegistry}.
     * @param registry the bean definition registry that will contain the loaded beans
     * @param sources the bean sources
     */
    BeanDefinitionLoader(BeanDefinitionRegistry registry, Object... sources) {
        replacedert.notNull(registry, "Registry must not be null");
        replacedert.notEmpty(sources, "Sources must not be empty");
        this.sources = sources;
        this.annotatedReader = new AnnotatedBeanDefinitionReader(registry);
        this.xmlReader = new XmlBeanDefinitionReader(registry);
        if (isGroovyPresent()) {
            this.groovyReader = new GroovyBeanDefinitionReader(registry);
        }
        this.scanner = new ClreplacedPathBeanDefinitionScanner(registry);
        this.scanner.addExcludeFilter(new ClreplacedExcludeFilter(sources));
    }

    /**
     * Set the bean name generator to be used by the underlying readers and scanner.
     * @param beanNameGenerator the bean name generator
     */
    public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) {
        this.annotatedReader.setBeanNameGenerator(beanNameGenerator);
        this.xmlReader.setBeanNameGenerator(beanNameGenerator);
        this.scanner.setBeanNameGenerator(beanNameGenerator);
    }

    /**
     * Set the resource loader to be used by the underlying readers and scanner.
     * @param resourceLoader the resource loader
     */
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
        this.xmlReader.setResourceLoader(resourceLoader);
        this.scanner.setResourceLoader(resourceLoader);
    }

    /**
     * Set the environment to be used by the underlying readers and scanner.
     * @param environment the environment
     */
    public void setEnvironment(ConfigurableEnvironment environment) {
        this.annotatedReader.setEnvironment(environment);
        this.xmlReader.setEnvironment(environment);
        this.scanner.setEnvironment(environment);
    }

    /**
     * Load the sources into the reader.
     * @return the number of loaded beans
     */
    public int load() {
        int count = 0;
        for (Object source : this.sources) {
            count += load(source);
        }
        return count;
    }

    private int load(Object source) {
        replacedert.notNull(source, "Source must not be null");
        if (source instanceof Clreplaced<?>) {
            return load((Clreplaced<?>) source);
        }
        if (source instanceof Resource) {
            return load((Resource) source);
        }
        if (source instanceof Package) {
            return load((Package) source);
        }
        if (source instanceof CharSequence) {
            return load((CharSequence) source);
        }
        throw new IllegalArgumentException("Invalid source type " + source.getClreplaced());
    }

    private int load(Clreplaced<?> source) {
        if (isGroovyPresent() && GroovyBeanDefinitionSource.clreplaced.isreplacedignableFrom(source)) {
            // Any GroovyLoaders added in beans{} DSL can contribute beans here
            GroovyBeanDefinitionSource loader = BeanUtils.instantiateClreplaced(source, GroovyBeanDefinitionSource.clreplaced);
            load(loader);
        }
        if (isComponent(source)) {
            this.annotatedReader.register(source);
            return 1;
        }
        return 0;
    }

    private int load(GroovyBeanDefinitionSource source) {
        int before = this.xmlReader.getRegistry().getBeanDefinitionCount();
        ((GroovyBeanDefinitionReader) this.groovyReader).beans(source.getBeans());
        int after = this.xmlReader.getRegistry().getBeanDefinitionCount();
        return after - before;
    }

    private int load(Resource source) {
        if (source.getFilename().endsWith(".groovy")) {
            if (this.groovyReader == null) {
                throw new BeanDefinitionStoreException("Cannot load Groovy beans without Groovy on clreplacedpath");
            }
            return this.groovyReader.loadBeanDefinitions(source);
        }
        return this.xmlReader.loadBeanDefinitions(source);
    }

    private int load(Package source) {
        return this.scanner.scan(source.getName());
    }

    private int load(CharSequence source) {
        String resolvedSource = this.xmlReader.getEnvironment().resolvePlaceholders(source.toString());
        // Attempt as a Clreplaced
        try {
            return load(ClreplacedUtils.forName(resolvedSource, null));
        } catch (IllegalArgumentException | ClreplacedNotFoundException ex) {
        // swallow exception and continue
        }
        // Attempt as resources
        Resource[] resources = findResources(resolvedSource);
        int loadCount = 0;
        boolean atLeastOneResourceExists = false;
        for (Resource resource : resources) {
            if (isLoadCandidate(resource)) {
                atLeastOneResourceExists = true;
                loadCount += load(resource);
            }
        }
        if (atLeastOneResourceExists) {
            return loadCount;
        }
        // Attempt as package
        Package packageResource = findPackage(resolvedSource);
        if (packageResource != null) {
            return load(packageResource);
        }
        throw new IllegalArgumentException("Invalid source '" + resolvedSource + "'");
    }

    private boolean isGroovyPresent() {
        return ClreplacedUtils.isPresent("groovy.lang.MetaClreplaced", null);
    }

    private Resource[] findResources(String source) {
        ResourceLoader loader = (this.resourceLoader != null) ? this.resourceLoader : new PathMatchingResourcePatternResolver();
        try {
            if (loader instanceof ResourcePatternResolver) {
                return ((ResourcePatternResolver) loader).getResources(source);
            }
            return new Resource[] { loader.getResource(source) };
        } catch (IOException ex) {
            throw new IllegalStateException("Error reading source '" + source + "'");
        }
    }

    private boolean isLoadCandidate(Resource resource) {
        if (resource == null || !resource.exists()) {
            return false;
        }
        if (resource instanceof ClreplacedPathResource) {
            // A simple package without a '.' may accidentally get loaded as an XML
            // doreplacedent if we're not careful. The result of getInputStream() will be
            // a file list of the package content. We double check here that it's not
            // actually a package.
            String path = ((ClreplacedPathResource) resource).getPath();
            if (path.indexOf('.') == -1) {
                try {
                    return Package.getPackage(path) == null;
                } catch (Exception ex) {
                // Ignore
                }
            }
        }
        return true;
    }

    private Package findPackage(CharSequence source) {
        Package pkg = Package.getPackage(source.toString());
        if (pkg != null) {
            return pkg;
        }
        try {
            // Attempt to find a clreplaced in this package
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(getClreplaced().getClreplacedLoader());
            Resource[] resources = resolver.getResources(ClreplacedUtils.convertClreplacedNameToResourcePath(source.toString()) + "/*.clreplaced");
            for (Resource resource : resources) {
                String clreplacedName = StringUtils.stripFilenameExtension(resource.getFilename());
                load(Clreplaced.forName(source.toString() + "." + clreplacedName));
                break;
            }
        } catch (Exception ex) {
        // swallow exception and continue
        }
        return Package.getPackage(source.toString());
    }

    private boolean isComponent(Clreplaced<?> type) {
        // This has to be a bit of a guess. The only way to be sure that this type is
        // eligible is to make a bean definition out of it and try to instantiate it.
        if (AnnotationUtils.findAnnotation(type, Component.clreplaced) != null) {
            return true;
        }
        // Nested anonymous clreplacedes are not eligible for registration, nor are groovy
        // closures
        if (type.getName().matches(".*\\$_.*closure.*") || type.isAnonymousClreplaced() || type.getConstructors() == null || type.getConstructors().length == 0) {
            return false;
        }
        return true;
    }

    /**
     * Simple {@link TypeFilter} used to ensure that specified {@link Clreplaced} sources are
     * not accidentally re-added during scanning.
     */
    private static clreplaced ClreplacedExcludeFilter extends AbstractTypeHierarchyTraversingFilter {

        private final Set<String> clreplacedNames = new HashSet<>();

        ClreplacedExcludeFilter(Object... sources) {
            super(false, false);
            for (Object source : sources) {
                if (source instanceof Clreplaced<?>) {
                    this.clreplacedNames.add(((Clreplaced<?>) source).getName());
                }
            }
        }

        @Override
        protected boolean matchClreplacedName(String clreplacedName) {
            return this.clreplacedNames.contains(clreplacedName);
        }
    }

    /**
     * Source for Bean definitions defined in Groovy.
     */
    @FunctionalInterface
    protected interface GroovyBeanDefinitionSource {

        Closure<?> getBeans();
    }
}

19 View Source File : BeanDefinitionLoader.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Set the resource loader to be used by the underlying readers and scanner.
 * @param resourceLoader the resource loader
 */
public void setResourceLoader(ResourceLoader resourceLoader) {
    this.resourceLoader = resourceLoader;
    this.xmlReader.setResourceLoader(resourceLoader);
    this.scanner.setResourceLoader(resourceLoader);
}

19 View Source File : BeanDefinitionLoader.java
License : Apache License 2.0
Project Creator : yuanmabiji

private Resource[] findResources(String source) {
    ResourceLoader loader = (this.resourceLoader != null) ? this.resourceLoader : new PathMatchingResourcePatternResolver();
    try {
        if (loader instanceof ResourcePatternResolver) {
            return ((ResourcePatternResolver) loader).getResources(source);
        }
        return new Resource[] { loader.getResource(source) };
    } catch (IOException ex) {
        throw new IllegalStateException("Error reading source '" + source + "'");
    }
}

19 View Source File : ChannelPluginsScannerRegister.java
License : Apache License 2.0
Project Creator : yin5980280

/**
 * @author : 潘多拉
 * @version : 1.0
 * @date : 2020/12/27 3:22 下午
 * @link : cn.org.easysite.payment.plugin.support.spring.register.ChannelPluginsScannerRegister
 */
@Slf4j
public clreplaced ChannelPluginsScannerRegister implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, BeanClreplacedLoaderAware, EnvironmentAware {

    private ResourceLoader resourceLoader;

    private ClreplacedLoader clreplacedLoader;

    private Environment environment;

    @Override
    public void setBeanClreplacedLoader(ClreplacedLoader clreplacedLoader) {
        this.clreplacedLoader = clreplacedLoader;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClreplacedMetadata, BeanDefinitionRegistry registry) {
        Set<String> basePackages = getBasePackages(importingClreplacedMetadata);
        ClreplacedPathScanningCandidateComponentProvider scanner = getScanner();
        scanner.setResourceLoader(this.resourceLoader);
        scanner.addIncludeFilter(new AnnotationTypeFilter(Channel.clreplaced));
        for (String basePackage : basePackages) {
            Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents(basePackage);
            for (BeanDefinition candidateComponent : candidateComponents) {
                if (candidateComponent instanceof AnnotatedBeanDefinition) {
                    AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
                    AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
                    this.registerPluginBean(registry, annotationMetadata);
                }
            }
        }
    }

    /**
     * 注册bean
     * @param registry
     * @param annotationMetadata
     */
    private void registerPluginBean(BeanDefinitionRegistry registry, AnnotationMetadata annotationMetadata) {
        try {
            String clreplacedName = annotationMetadata.getClreplacedName();
            Clreplaced<?> beanClazz = Clreplaced.forName(clreplacedName);
            if (!beanClazz.isAnnotationPresent(Channel.clreplaced)) {
                throw new RuntimeException("@Channel is required!");
            }
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(beanClazz);
            BeanDefinition definition = builder.getRawBeanDefinition();
            registry.registerBeanDefinition(beanClazz.getSimpleName(), definition);
        } catch (ClreplacedNotFoundException e) {
            log.error("Could not register target clreplaced: " + annotationMetadata.getClreplacedName(), e);
        }
    }

    protected Set<String> getBasePackages(AnnotationMetadata importingClreplacedMetadata) {
        Map<String, Object> attributes = importingClreplacedMetadata.getAnnotationAttributes(EnablePaymentPluginRegistries.clreplaced.getCanonicalName());
        Set<String> basePackages = new HashSet<>();
        for (String pkg : (String[]) attributes.get("basePackages")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }
        for (Clreplaced<?> clazz : (Clreplaced[]) attributes.get("basePackageClreplacedes")) {
            basePackages.add(ClreplacedUtils.getPackageName(clazz));
        }
        if (basePackages.isEmpty()) {
            basePackages.add(ClreplacedUtils.getPackageName(importingClreplacedMetadata.getClreplacedName()));
        }
        return basePackages;
    }

    protected ClreplacedPathScanningCandidateComponentProvider getScanner() {
        return new ClreplacedPathScanningCandidateComponentProvider(false, this.environment) {

            @Override
            protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
                if (beanDefinition.getMetadata().isIndependent()) {
                    if (beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().getInterfaceNames().length == 1 && Annotation.clreplaced.getName().equals(beanDefinition.getMetadata().getInterfaceNames()[0])) {
                        try {
                            Clreplaced<?> target = ClreplacedUtils.forName(beanDefinition.getMetadata().getClreplacedName(), ChannelPluginsScannerRegister.this.clreplacedLoader);
                            return !target.isAnnotation();
                        } catch (Exception ex) {
                            this.logger.error("Could not load target clreplaced: " + beanDefinition.getMetadata().getClreplacedName(), ex);
                        }
                    }
                    return true;
                }
                return false;
            }
        };
    }
}

19 View Source File : FeignRequestRegistrar.java
License : Apache License 2.0
Project Creator : yfh0918

public clreplaced FeignRequestRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {

    private ResourceLoader resourceLoader;

    private Environment environment;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClreplacedMetadata, BeanDefinitionRegistry registry) {
        registerNamingRequests(importingClreplacedMetadata, registry);
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    public void registerNamingRequests(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        LinkedHashSet<BeanDefinition> candidateComponents = new LinkedHashSet<>();
        ClreplacedPathScanningCandidateComponentProvider scanner = getScanner();
        scanner.setResourceLoader(this.resourceLoader);
        scanner.addIncludeFilter(new AnnotationTypeFilter(FeignRequest.clreplaced));
        Set<String> basePackages = getBasePackages(metadata);
        for (String basePackage : basePackages) {
            candidateComponents.addAll(scanner.findCandidateComponents(basePackage));
        }
        for (BeanDefinition candidateComponent : candidateComponents) {
            if (candidateComponent instanceof AnnotatedBeanDefinition) {
                AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
                AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
                replacedert.isTrue(annotationMetadata.isInterface(), "@NamingRequest can only be specified on an interface");
                Map<String, Object> attributes = annotationMetadata.getAnnotationAttributes(FeignRequest.clreplaced.getCanonicalName());
                registerNamingRequest(registry, annotationMetadata, attributes);
            }
        }
    }

    protected void registerNamingRequest(BeanDefinitionRegistry registry, AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
        String clreplacedName = annotationMetadata.getClreplacedName();
        BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(FeignRequestFactoryBean.clreplaced);
        try {
            definition.addConstructorArgValue(Clreplaced.forName(clreplacedName));
        } catch (ClreplacedNotFoundException e) {
            throw new NamingException(clreplacedName + " is not found");
        }
        definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
        AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
        BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, clreplacedName);
        BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
    }

    protected Set<String> getBasePackages(AnnotationMetadata importingClreplacedMetadata) {
        Map<String, Object> attributes = importingClreplacedMetadata.getAnnotationAttributes(EnableFeignRequest.clreplaced.getCanonicalName());
        Set<String> basePackages = new HashSet<>();
        for (String pkg : (String[]) attributes.get("value")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }
        for (String pkg : (String[]) attributes.get("basePackages")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }
        for (Clreplaced<?> clazz : (Clreplaced[]) attributes.get("basePackageClreplacedes")) {
            basePackages.add(ClreplacedUtils.getPackageName(clazz));
        }
        if (basePackages.isEmpty()) {
            basePackages.add(ClreplacedUtils.getPackageName(importingClreplacedMetadata.getClreplacedName()));
        }
        return basePackages;
    }

    protected ClreplacedPathScanningCandidateComponentProvider getScanner() {
        return new ClreplacedPathScanningCandidateComponentProvider(false, this.environment) {

            @Override
            protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
                boolean isCandidate = false;
                if (beanDefinition.getMetadata().isIndependent()) {
                    if (!beanDefinition.getMetadata().isAnnotation()) {
                        isCandidate = true;
                    }
                }
                return isCandidate;
            }
        };
    }
}

19 View Source File : ServiceBeanDefinitionRegistry.java
License : Apache License 2.0
Project Creator : yeecode

@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
    this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
    this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader);
}

19 View Source File : TenantManagerConfiguration.java
License : Apache License 2.0
Project Creator : xm-online

@SneakyThrows
@Bean
public TenantConfigProvisioner tenantConfigProvisioner(TenantConfigRepository tenantConfigRepository, PermissionProperties permissionProperties, ApplicationProperties applicationProperties, ResourceLoader resourceLoader) {
    Resource[] resources = getResourcePatternResolver(resourceLoader).getResources(DEFAULT_EMAILS_PATTERN);
    List<Configuration> emailConfigs = stream(resources).filter(pathIsExpected()).map(this::resourceToConfiguration).collect(Collectors.toList());
    TenantConfigProvisioner provisioner = TenantConfigProvisioner.builder().tenantConfigRepository(tenantConfigRepository).configuration(of().path(permissionProperties.getRolesSpecPath()).content(getEmptyYml()).build()).configuration(of().path(permissionProperties.getPermissionsSpecPath()).content(getEmptyYml()).build()).configuration(of().path(applicationProperties.getTenantPropertiesPathPattern()).content(readResource(DEFAULT_CONFIG_PATH)).build()).configuration(of().path(applicationProperties.getTenantLoginPropertiesPathPattern()).content(readResource(DEFAULT_LOGINS_CONFIG_PATH)).build()).configurations(emailConfigs).build();
    log.info("Configured tenant config provisioner: {}", provisioner);
    return provisioner;
}

19 View Source File : XmMultiTenantSpringLiquibase.java
License : Apache License 2.0
Project Creator : xm-online

@Slf4j
public clreplaced XmMulreplacedenantSpringLiquibase extends MulreplacedenantSpringLiquibase {

    private ResourceLoader resourceLoader;

    public XmMulreplacedenantSpringLiquibase() {
        super();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        if (getDataSource() == null && getSchemas() == null) {
            super.afterPropertiesSet();
        } else {
            if (getDataSource() == null && getSchemas() != null) {
                throw new LiquibaseException("When schemas are defined you should also define a base dataSource");
            }
            if (getDataSource() != null) {
                log.info("Schema based mulreplacedenancy enabled");
                if (CollectionUtils.isEmpty(getSchemas())) {
                    log.warn("Schemas not defined, using defaultSchema only");
                    setSchemas(new ArrayList<>());
                    getSchemas().add(getDefaultSchema());
                }
                runOnAllSchemasXm();
            }
        }
    }

    private void runOnAllSchemasXm() throws LiquibaseException {
        for (String schema : getSchemas()) {
            if (schema.equals("default")) {
                schema = null;
            }
            log.info("Initializing Liquibase for schema {}", schema);
            try {
                SpringLiquibase liquibase = getXmSpringLiquibase(getDataSource());
                liquibase.setDefaultSchema(schema);
                liquibase.afterPropertiesSet();
                log.info("Liquibase run for schema {}", schema);
            } catch (Exception e) {
                log.error("Failed to initialize Liquibase for schema {}", schema, e);
            }
        }
    }

    private SpringLiquibase getXmSpringLiquibase(DataSource dataSource) {
        SpringLiquibase liquibase = new SpringLiquibase();
        liquibase.setChangeLog(getChangeLog());
        liquibase.setChangeLogParameters(getParameters());
        liquibase.setContexts(getContexts());
        liquibase.setLabels(getLabels());
        liquibase.setDropFirst(isDropFirst());
        liquibase.setShouldRun(isShouldRun());
        liquibase.setRollbackFile(getRollbackFile());
        liquibase.setResourceLoader(getResourceLoader());
        liquibase.setDataSource(dataSource);
        liquibase.setDefaultSchema(getDefaultSchema());
        return liquibase;
    }

    private ResourceLoader getResourceLoader() {
        return resourceLoader;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        super.setResourceLoader(resourceLoader);
        this.resourceLoader = resourceLoader;
    }
}

19 View Source File : XmMultiTenantSpringLiquibase.java
License : Apache License 2.0
Project Creator : xm-online

/**
 * {@inheritDoc}
 */
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
    super.setResourceLoader(resourceLoader);
    this.resourceLoader = resourceLoader;
}

19 View Source File : TenantDatabaseProvisioner.java
License : Apache License 2.0
Project Creator : xm-online

@Slf4j
@Service
@RequiredArgsConstructor
public clreplaced TenantDatabaseProvisioner implements TenantProvisioner {

    private final DataSource dataSource;

    private final LiquibaseProperties properties;

    private final ResourceLoader resourceLoader;

    private final DropSchemaResolver schemaDropResolver;

    @SneakyThrows
    @Override
    public void createTenant(final Tenant tenant) {
        String tenantKey = tenant.getTenantKey().toUpperCase();
        replacedertTenantKeyValid(tenantKey);
        createSchema(tenantKey);
        migrateSchema(tenantKey);
    }

    @Override
    public void manageTenant(final String tenantKey, final String state) {
        log.info("Nothing to do with DB during manage tenant: {}, state = {}", tenantKey, state);
    }

    @SneakyThrows
    @Override
    public void deleteTenant(final String tenantKey) {
        String tenantKeyUpper = tenantKey.toUpperCase();
        replacedertTenantKeyValid(tenantKeyUpper);
        String sql = String.format(schemaDropResolver.getSchemaDropCommand(), tenantKeyUpper);
        executeUpdateWithAutoCommit(dataSource, sql);
    }

    private void createSchema(final String tenantKey) throws SQLException {
        String sql = String.format(DDL_CREATE_SCHEMA, tenantKey);
        executeUpdateWithAutoCommit(dataSource, sql);
    }

    @SneakyThrows
    protected void migrateSchema(String tenantKey) {
        String changeLogPath = getChangelogPath();
        StopWatch stopWatch = StopWatch.createStarted();
        log.info("start Liquibase migration for tenant {}, changelog path: {}", tenantKey, changeLogPath);
        try {
            SpringLiquibase liquibase = new SpringLiquibase();
            liquibase.setResourceLoader(resourceLoader);
            liquibase.setDataSource(dataSource);
            liquibase.setChangeLog(changeLogPath);
            liquibase.setContexts(properties.getContexts());
            liquibase.setDefaultSchema(tenantKey);
            liquibase.setDropFirst(properties.isDropFirst());
            liquibase.setChangeLogParameters(properties.getParameters());
            liquibase.setShouldRun(true);
            liquibase.afterPropertiesSet();
        } finally {
            log.info("stop  Liquibase migration for tenant {}, time: {} ms", tenantKey, stopWatch.getTime());
        }
    }

    private String getChangelogPath() {
        return Optional.ofNullable(properties.getChangeLog()).filter(StringUtils::isNotEmpty).orElse(CHANGE_LOG_PATH);
    }
}

19 View Source File : XmLepResourceServiceFileUnitTest.java
License : Apache License 2.0
Project Creator : xm-online

/**
 * The {@link XmLepResourceServiceFileUnitTest} clreplaced.
 */
@RunWith(SpringRunner.clreplaced)
@ContextConfiguration(clreplacedes = { EmptyTestConfig.clreplaced })
public clreplaced XmLepResourceServiceFileUnitTest {

    private static final String APP_NAME = "test-app";

    private static final String TENANT_KEY_VALUE = "test";

    private static final String SCRIPT_CLreplacedPATH_URL = "clreplacedpath:/lep/test/resource/service/Script$$before.groovy";

    private static final String USER_HOME = "user.home";

    @Rule
    public ProvideSystemProperty properties;

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    @Autowired
    private ResourceLoader resourceLoader;

    private LepResourceService resourceService;

    private File testScriptDir;

    private String oldUserHome;

    @Before
    public void before() throws IOException {
        oldUserHome = System.getProperty(USER_HOME);
        // init temp folder
        testScriptDir = folder.newFolder("home", "xm-online", "config", "tenants", TENANT_KEY_VALUE.toUpperCase(), APP_NAME, "lep", "resource", "service");
        // init system property
        File userHomeDir = Paths.get(folder.getRoot().toPath().toString(), "home").toFile();
        System.setProperty(USER_HOME, userHomeDir.getAbsolutePath());
        // copy script from clreplacedpath to file system tmp folder
        File scriptFile = Paths.get(testScriptDir.getAbsolutePath(), "Script$$before.groovy").toFile();
        if (!scriptFile.createNewFile()) {
            throw new IllegalStateException("Can't create file: " + scriptFile.getAbsolutePath());
        }
        InputStream scriptIn = resourceLoader.getResource(SCRIPT_CLreplacedPATH_URL).getInputStream();
        Files.copy(scriptIn, scriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        scriptIn.close();
        // init resource service
        Map<String, ResourceLoader> urlPrefixToResourceLoader = new HashMap<>();
        urlPrefixToResourceLoader.put("file:", new FileSystemResourceLoader());
        RouterResourceLoader routerResourceLoader = new RouterResourceLoader(urlPrefixToResourceLoader);
        resourceService = new XmLepResourceService(APP_NAME, FILE, routerResourceLoader);
    }

    @After
    public void after() {
        System.setProperty(USER_HOME, oldUserHome);
    }

    @Test
    public void lepKeySuccessFileResolving() throws IOException {
        ContextsHolder holder = ContextHolderUtils.buildWithTenant(TENANT_KEY_VALUE);
        // build resource key
        LepResourceKey resourceKey = UrlLepResourceKey.valueOfUrlResourcePath("/resource/service/Script$$before.groovy");
        LepResource resource = resourceService.getResource(holder, resourceKey);
        replacedertNotNull(resource);
        replacedertFalse(resource.isComposite());
        replacedertNotNull(resource.getValue(InputStream.clreplaced));
        String scriptText = IOUtils.toString(resource.getValue(InputStream.clreplaced), Charset.forName("UTF-8"));
        replacedertEquals("return 'Hello from Script$$before.groovy'\n", scriptText);
    }
}

19 View Source File : XmLepResourceServiceClassPathUnitTest.java
License : Apache License 2.0
Project Creator : xm-online

/**
 * The {@link XmLepResourceServiceClreplacedPathUnitTest} clreplaced.
 */
@RunWith(SpringRunner.clreplaced)
@ContextConfiguration(clreplacedes = { EmptyTestConfig.clreplaced })
public clreplaced XmLepResourceServiceClreplacedPathUnitTest {

    @Rule
    public ExpectedException expectedEx = ExpectedException.none();

    @Autowired
    private ResourceLoader resourceLoader;

    private LepResourceService resourceService;

    @Before
    public void before() {
        resourceService = new XmLepResourceService("test-app", CLreplacedPATH, resourceLoader);
    }

    @Test
    public void getResourceDescriptorThrowsNpeOnNullKey() {
        expectedEx.expect(NullPointerException.clreplaced);
        expectedEx.expectMessage("resourceKey can't be null");
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super");
        resourceService.getResourceDescriptor(holder, null);
    }

    @Test
    public void getResourceDescriptorReturnNullOnNonExistingKey() {
        // build resource key
        LepResourceKey resourceKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/_QWE_Script_XYZ$$type.groovy");
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super");
        LepResourceDescriptor resourceDescriptor = resourceService.getResourceDescriptor(holder, resourceKey);
        replacedertNull(resourceDescriptor);
    }

    private static void replacedertValidClreplacedpathResourceDescriptor(LepResourceKey resourceKey, LepResourceDescriptor resourceDescriptor) {
        replacedertNotNull(resourceDescriptor);
        replacedertEquals(XmLepResourceType.GROOVY, resourceDescriptor.getType());
        replacedertEquals(resourceKey, resourceDescriptor.getKey());
        replacedertEquals(Instant.EPOCH, resourceDescriptor.getCreationTime());
        replacedertNotNull(resourceDescriptor.getModificationTime());
    }

    @Test
    public void getValidBeforeResourceDescriptor() {
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super");
        // build resource key
        LepResourceKey resourceKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/ScriptWithBeforeAfter$$before.groovy");
        LepResourceDescriptor resourceDescriptor = resourceService.getResourceDescriptor(holder, resourceKey);
        replacedertValidClreplacedpathResourceDescriptor(resourceKey, resourceDescriptor);
    }

    @Test
    public void getValidAroundResourceDescriptor() {
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super");
        // build resource key
        LepResourceKey resourceKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/ScriptWithAround$$around.groovy");
        LepResourceDescriptor resourceDescriptor = resourceService.getResourceDescriptor(holder, resourceKey);
        replacedertValidClreplacedpathResourceDescriptor(resourceKey, resourceDescriptor);
    }

    @Test
    public void getValidTenantResourceDescriptor() {
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super");
        // build resource key
        LepResourceKey resourceKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/ScriptWithTenant$$tenant.groovy");
        LepResourceDescriptor resourceDescriptor = resourceService.getResourceDescriptor(holder, resourceKey);
        replacedertValidClreplacedpathResourceDescriptor(resourceKey, resourceDescriptor);
    }

    @Test
    public void getValidDefaultResourceDescriptor() {
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super");
        // build resource key
        LepResourceKey resourceKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/Script$$default.groovy");
        LepResourceDescriptor resourceDescriptor = resourceService.getResourceDescriptor(holder, resourceKey);
        replacedertValidClreplacedpathResourceDescriptor(resourceKey, resourceDescriptor);
    }

    @Test
    public void getValidAfterResourceDescriptor() {
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super");
        // build resource key
        LepResourceKey resourceKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/ScriptWithBeforeAfter$$after.groovy");
        LepResourceDescriptor resourceDescriptor = resourceService.getResourceDescriptor(holder, resourceKey);
        replacedertValidClreplacedpathResourceDescriptor(resourceKey, resourceDescriptor);
    }

    // =========== RESOURCES TESTS
    @Test
    public void getResourceThrowsNpeOnNullKey() {
        expectedEx.expect(NullPointerException.clreplaced);
        expectedEx.expectMessage("resourceKey can't be null");
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super puper");
        resourceService.getResource(holder, null);
    }

    @Test
    public void getResourceReturnNullOnNonExistingKey() {
        // build resource key
        LepResourceKey resourceKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/Abc_Script_Xyz$$some-type.groovy");
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super");
        LepResource resource = resourceService.getResource(holder, resourceKey);
        replacedertNull(resource);
    }

    private static void replacedertValidClreplacedpathResource(LepResourceKey resourceKey, LepResource resource, String expectedScriptText) {
        replacedertNotNull(resource);
        replacedertNotNull(resource.getDescriptor());
        replacedertValidClreplacedpathResourceDescriptor(resourceKey, resource.getDescriptor());
        String scriptText = resource.getValue(String.clreplaced);
        replacedertTrue("Expected contains script text: [" + expectedScriptText + "], actual text: [" + scriptText + "]", scriptText.startsWith(expectedScriptText));
    }

    @Test
    public void getValidBeforeResource() {
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super");
        // build resource key
        LepResourceKey resourceKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/ScriptWithBeforeAfter$$before.groovy");
        LepResource resource = resourceService.getResource(holder, resourceKey);
        replacedertValidClreplacedpathResource(resourceKey, resource, "return \"ScriptWithBeforeAfter.groovy before, tenant: super\"");
    }

    @Test
    public void getValidAroundResource() {
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super");
        // build resource key
        LepResourceKey resourceKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/ScriptWithAround$$around.groovy");
        LepResource resource = resourceService.getResource(holder, resourceKey);
        replacedertValidClreplacedpathResource(resourceKey, resource, "return \"ScriptWithAround.groovy around, tenant: super\"");
    }

    @Test
    public void getValidTenantResource() {
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super");
        // build resource key
        LepResourceKey resourceKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/ScriptWithTenant$$tenant.groovy");
        LepResource resource = resourceService.getResource(holder, resourceKey);
        replacedertValidClreplacedpathResource(resourceKey, resource, "return \"ScriptWithTenant.groovy tenant, tenant: super\"");
    }

    @Test
    public void getValidDefaultResource() {
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super");
        // build resource key
        LepResourceKey resourceKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/Script$$default.groovy");
        LepResource resource = resourceService.getResource(holder, resourceKey);
        replacedertValidClreplacedpathResource(resourceKey, resource, "return \"Script.groovy default\"");
    }

    @Test
    public void getValidAfterResource() {
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super");
        // build resource key
        LepResourceKey resourceKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/ScriptWithBeforeAfter$$after.groovy");
        LepResource resource = resourceService.getResource(holder, resourceKey);
        replacedertValidClreplacedpathResource(resourceKey, resource, "return \"ScriptWithBeforeAfter.groovy after, tenant: super\"");
    }

    @Test
    public void getValidTenantResourceForTenant() {
        // build resource key
        LepResourceKey resourceKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/ScriptWithTenant$$tenant.groovy");
        // TENANT 'super'
        ContextsHolder holder = ContextHolderUtils.buildWithTenant("super");
        LepResource resource = resourceService.getResource(holder, resourceKey);
        replacedertValidClreplacedpathResource(resourceKey, resource, "return \"ScriptWithTenant.groovy tenant, tenant: super\"");
        // TENANT 'test'
        holder = ContextHolderUtils.buildWithTenant("test");
        resource = resourceService.getResource(holder, resourceKey);
        replacedertValidClreplacedpathResource(resourceKey, resource, "return \"ScriptWithTenant.groovy tenant, tenant: test\"");
    }
}

19 View Source File : XmGroovyExecutionStrategyUnitTest.java
License : Apache License 2.0
Project Creator : xm-online

/**
 * The {@link XmGroovyExecutionStrategyUnitTest} clreplaced.
 * <br>
 * SpringRunner - needed only for simplify ResourceLoader injection.
 * EmptyTestConfig - needed only for init Spring Application Context.
 */
@RunWith(SpringRunner.clreplaced)
@ContextConfiguration(clreplacedes = { EmptyTestConfig.clreplaced })
public clreplaced XmGroovyExecutionStrategyUnitTest {

    @Autowired
    private ResourceLoader resourceLoader;

    private XmGroovyExecutionStrategy execStrategy;

    private Supplier<GroovyScriptRunner> resourceExecutorSupplier;

    @Before
    public void before() {
        MockitoAnnotations.initMocks(this);
        this.execStrategy = new XmGroovyExecutionStrategy();
        ScriptNameLepResourceKeyMapper mapper = new DefaultScriptNameLepResourceKeyMapper();
        LazyGroovyScriptEngineProviderStrategy providerStrategy = new LazyGroovyScriptEngineProviderStrategy(mapper);
        GroovyScriptRunner scriptRunner = new StrategyGroovyLepExecutor(mapper, providerStrategy, execStrategy);
        resourceExecutorSupplier = () -> scriptRunner;
    }

    private LepManagerService buildLepManagerService(String tenantKeyValue) {
        TenantContext tenantContext = mock(TenantContext.clreplaced);
        when(tenantContext.getTenantKey()).thenReturn(Optional.of(TenantKey.valueOf(tenantKeyValue)));
        // AuthenticationContext
        XmAuthenticationContext authContext = mock(XmAuthenticationContext.clreplaced);
        // Thread context
        ScopedContext threadContext = mock(ScopedContext.clreplaced);
        Mockito.when(threadContext.getValue(eq(THREAD_CONTEXT_KEY_TENANT_CONTEXT), eq(TenantContext.clreplaced))).thenReturn(tenantContext);
        // Execution context
        ScopedContext executionContext = Mockito.mock(ScopedContext.clreplaced);
        Map<String, Object> executionContextValues = new HashMap<>();
        executionContextValues.put(XmLepScriptConstants.BINDING_KEY_TENANT_CONTEXT, tenantContext);
        executionContextValues.put(XmLepScriptConstants.BINDING_KEY_AUTH_CONTEXT, authContext);
        Mockito.when(executionContext.getValues()).thenReturn(executionContextValues);
        ContextsHolder holder = Mockito.mock(ContextsHolder.clreplaced);
        Mockito.when(holder.getContext(eq(ContextScopes.THREAD))).thenReturn(threadContext);
        Mockito.when(holder.getContext(eq(ContextScopes.EXECUTION))).thenReturn(executionContext);
        XmLepResourceService resourceService = new XmLepResourceService("test-app", CLreplacedPATH, resourceLoader);
        LepManagerService managerService = Mockito.mock(LepManagerService.clreplaced);
        Mockito.when(managerService.getResourceService()).thenReturn(resourceService);
        Mockito.when(managerService.getContext(eq(ContextScopes.THREAD))).thenReturn(threadContext);
        Mockito.when(managerService.getContext(eq(ContextScopes.EXECUTION))).thenReturn(executionContext);
        return managerService;
    }

    private static void switchTenantContext(LepManagerService managerService, String tenantKey) {
        TenantContext tenantContext = mock(TenantContext.clreplaced);
        when(tenantContext.getTenantKey()).thenReturn(Optional.of(TenantKey.valueOf(tenantKey)));
        ScopedContext threadContext = managerService.getContext(ContextScopes.THREAD);
        when(threadContext.getValue(eq(THREAD_CONTEXT_KEY_TENANT_CONTEXT), eq(TenantContext.clreplaced))).thenReturn(tenantContext);
        ScopedContext executionContext = managerService.getContext(ContextScopes.EXECUTION);
        executionContext.getValues().put(XmLepScriptConstants.BINDING_KEY_TENANT_CONTEXT, tenantContext);
    }

    private LepMethod buildEmptyLepMethod() {
        MethodSignature methodSignature = Mockito.mock(MethodSignature.clreplaced);
        Mockito.when(methodSignature.getParameterNames()).thenReturn(new String[0]);
        Mockito.when(methodSignature.getParameterTypes()).thenReturn(new Clreplaced<?>[0]);
        LepMethod lepMethod = Mockito.mock(LepMethod.clreplaced);
        Mockito.when(lepMethod.getMethodArgValues()).thenReturn(new Object[0]);
        Mockito.when(lepMethod.getMethodSignature()).thenReturn(methodSignature);
        return lepMethod;
    }

    @Test
    public void simpleDefaultScriptValidExecution() throws LepInvocationCauseException {
        LepManagerService managerService = buildLepManagerService("super");
        LepMethod lepMethod = buildEmptyLepMethod();
        UrlLepResourceKey compositeKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/Script.groovy");
        // execute script
        Object result = execStrategy.executeLepResource(compositeKey, lepMethod, managerService, resourceExecutorSupplier);
        replacedertNotNull(result);
        replacedertEquals("Script.groovy default", result);
    }

    @Test
    public void simpleTenantScriptValidExecution() throws LepInvocationCauseException {
        LepManagerService managerService = buildLepManagerService("super");
        LepMethod lepMethod = buildEmptyLepMethod();
        UrlLepResourceKey compositeKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/ScriptWithTenant.groovy");
        // execute script
        Object result = execStrategy.executeLepResource(compositeKey, lepMethod, managerService, resourceExecutorSupplier);
        replacedertNotNull(result);
        replacedertEquals("ScriptWithTenant.groovy tenant, tenant: super", result);
    }

    @Test
    public void simpleAroundScriptValidExecution() throws LepInvocationCauseException {
        LepManagerService managerService = buildLepManagerService("super");
        LepMethod lepMethod = buildEmptyLepMethod();
        UrlLepResourceKey compositeKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/ScriptWithAround.groovy");
        // execute script
        Object result = execStrategy.executeLepResource(compositeKey, lepMethod, managerService, resourceExecutorSupplier);
        replacedertNotNull(result);
        replacedertEquals("ScriptWithAround.groovy around, tenant: super", result);
    }

    @Test
    public void simpleBeforeAfterScriptValidExecution() throws LepInvocationCauseException {
        LepManagerService managerService = buildLepManagerService("super");
        LepMethod lepMethod = buildEmptyLepMethod();
        UrlLepResourceKey compositeKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/ScriptWithBeforeAfter.groovy");
        // execute script
        Object result = execStrategy.executeLepResource(compositeKey, lepMethod, managerService, resourceExecutorSupplier);
        replacedertNotNull(result);
        replacedertEquals("ScriptWithBeforeAfter.groovy default", result);
    }

    @Test
    public void checkDefaultScriptBindingParams() throws LepInvocationCauseException {
        LepManagerService managerService = buildLepManagerService("super");
        MethodSignature methodSignature = Mockito.mock(MethodSignature.clreplaced);
        Mockito.when(methodSignature.getParameterNames()).thenReturn(new String[] { "name", "age" });
        LepMethod lepMethod = Mockito.mock(LepMethod.clreplaced);
        Mockito.when(lepMethod.getMethodArgValues()).thenReturn(new Object[] { "John Doe", 23 });
        Mockito.when(lepMethod.getMethodSignature()).thenReturn(methodSignature);
        UrlLepResourceKey compositeKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/CheckBindingParams.groovy");
        // execute script
        execStrategy.executeLepResource(compositeKey, lepMethod, managerService, resourceExecutorSupplier);
    }

    /**
     * Demonstrate fixed issue #13555 - LEP script executed from other tenant.
     */
    @Test
    public void simpleAroundScriptSwitchTenantDespiteCompositeKey() throws LepInvocationCauseException {
        LepManagerService managerService = buildLepManagerService("super");
        LepMethod lepMethod = buildEmptyLepMethod();
        UrlLepResourceKey compositeKey = UrlLepResourceKey.valueOfUrlResourcePath("/general/ScriptWithAround.groovy");
        // execute script
        Object result = execStrategy.executeLepResource(compositeKey, lepMethod, managerService, resourceExecutorSupplier);
        replacedertNotNull(result);
        replacedertEquals("ScriptWithAround.groovy around, tenant: super", result);
        switchTenantContext(managerService, "test");
        result = execStrategy.executeLepResource(compositeKey, lepMethod, managerService, resourceExecutorSupplier);
        replacedertNotNull(result);
        // That was a critical issue after tenant contex swith script still executed from previous tenant!!!
        replacedertEquals("ScriptWithAround.groovy around, tenant: test", result);
    }

    @Test
    public void simpleAroundScriptSwitchTenantExecutionFixed() throws LepInvocationCauseException {
        LepManagerService managerService = buildLepManagerService("super");
        LepMethod lepMethod = buildEmptyLepMethod();
        UrlLepResourceKey compositeKey = UrlLepResourceKey.valueOfUrlResourcePath("//super/general/ScriptWithAround.groovy");
        // execute script
        Object result = execStrategy.executeLepResource(compositeKey, lepMethod, managerService, resourceExecutorSupplier);
        replacedertNotNull(result);
        replacedertEquals("ScriptWithAround.groovy around, tenant: super", result);
        switchTenantContext(managerService, "test");
        compositeKey = UrlLepResourceKey.valueOfUrlResourcePath("//test/general/ScriptWithAround.groovy");
        result = execStrategy.executeLepResource(compositeKey, lepMethod, managerService, resourceExecutorSupplier);
        replacedertNotNull(result);
        replacedertEquals("ScriptWithAround.groovy around, tenant: test", result);
    }

    @Test
    public void testTenantContextSwitch() {
        LepManagerService managerService = buildLepManagerService("super");
        replacedertEquals("super", extractThreadTenantValue(managerService));
        replacedertEquals("super", extractExecutionTenantValue(managerService));
        switchTenantContext(managerService, "test");
        replacedertEquals("test", extractThreadTenantValue(managerService));
        replacedertEquals("test", extractExecutionTenantValue(managerService));
    }

    @Test
    public void testURLAuthority() throws MalformedURLException {
        UrlLepResourceKey urlLepResourceKey = new UrlLepResourceKey("lep://super/general/ScriptWithAround.groovy");
        replacedertEquals("super", urlLepResourceKey.getUrl().getAuthority());
        replacedertEquals("/general/ScriptWithAround.groovy", urlLepResourceKey.getUrl().getPath());
        replacedertEquals("lep", urlLepResourceKey.getUrl().getProtocol());
    }

    @Test
    public void testGetAvailableAtomicResourceKeys() throws MalformedURLException {
        LepManagerService managerService = buildLepManagerService("super");
        UrlLepResourceKey urlLepResourceKey = new UrlLepResourceKey("lep://super/general/ScriptWithAround.groovy");
        Map<XmLepResourceSubType, UrlLepResourceKey> availableAtomicResourceKeys = execStrategy.getAvailableAtomicResourceKeys(urlLepResourceKey, managerService);
        replacedertEquals(2, availableAtomicResourceKeys.size());
        replacedertEquals("lep://super/general/ScriptWithAround$$around.groovy", availableAtomicResourceKeys.get(XmLepResourceSubType.AROUND).getId());
        replacedertEquals("lep://super/general/ScriptWithAround$$default.groovy", availableAtomicResourceKeys.get(XmLepResourceSubType.DEFAULT).getId());
    }

    @Test
    public void testGetAvailableAtomicResourceKeysToNenantScript() throws MalformedURLException {
        LepManagerService managerService = buildLepManagerService("unknown");
        UrlLepResourceKey urlLepResourceKey = new UrlLepResourceKey("lep://unknown/general/ScriptWithAround.groovy");
        Map<XmLepResourceSubType, UrlLepResourceKey> availableAtomicResourceKeys = execStrategy.getAvailableAtomicResourceKeys(urlLepResourceKey, managerService);
        replacedertEquals(1, availableAtomicResourceKeys.size());
        replacedertTrue(availableAtomicResourceKeys.containsKey(XmLepResourceSubType.DEFAULT));
        replacedertEquals("lep://unknown/general/ScriptWithAround$$default.groovy", availableAtomicResourceKeys.get(XmLepResourceSubType.DEFAULT).getId());
    }

    @Test
    public void testGetAvailableAtomicResourceKeysSwitchTenant() throws MalformedURLException {
        LepManagerService managerService = buildLepManagerService("super");
        UrlLepResourceKey urlLepResourceKey = new UrlLepResourceKey("lep://super/general/ScriptWithAround.groovy");
        Map<XmLepResourceSubType, UrlLepResourceKey> availableAtomicResourceKeys = execStrategy.getAvailableAtomicResourceKeys(urlLepResourceKey, managerService);
        replacedertEquals(2, availableAtomicResourceKeys.size());
        replacedertEquals("lep://super/general/ScriptWithAround$$around.groovy", availableAtomicResourceKeys.get(XmLepResourceSubType.AROUND).getId());
        replacedertEquals("lep://super/general/ScriptWithAround$$default.groovy", availableAtomicResourceKeys.get(XmLepResourceSubType.DEFAULT).getId());
        switchTenantContext(managerService, "test");
        urlLepResourceKey = new UrlLepResourceKey("lep://test/general/ScriptWithAround.groovy");
        availableAtomicResourceKeys = execStrategy.getAvailableAtomicResourceKeys(urlLepResourceKey, managerService);
        replacedertEquals("lep://test/general/ScriptWithAround$$around.groovy", availableAtomicResourceKeys.get(XmLepResourceSubType.AROUND).getId());
        replacedertEquals("lep://test/general/ScriptWithAround$$default.groovy", availableAtomicResourceKeys.get(XmLepResourceSubType.DEFAULT).getId());
    }

    private static String extractThreadTenantValue(final LepManagerService managerService) {
        TenantContext tenantContext = managerService.getContext(ContextScopes.THREAD).getValue(THREAD_CONTEXT_KEY_TENANT_CONTEXT, TenantContext.clreplaced);
        return TenantContextUtils.getRequiredTenantKeyValue(tenantContext);
    }

    private static String extractExecutionTenantValue(final LepManagerService managerService) {
        TenantContext tenantContext = (TenantContext) managerService.getContext(ContextScopes.EXECUTION).getValues().get(XmLepScriptConstants.BINDING_KEY_TENANT_CONTEXT);
        return TenantContextUtils.getRequiredTenantKeyValue(tenantContext);
    }
}

19 View Source File : XmLepResourceService.java
License : Apache License 2.0
Project Creator : xm-online

/**
 * The {@link XmLepResourceService} clreplaced.
 */
@Slf4j
public clreplaced XmLepResourceService implements LepResourceService {

    private static final Pattern SCRIPT_TYPE_PATTERN = Pattern.compile("^.*\\Q" + XmLepConstants.SCRIPT_NAME_SEPARATOR + "\\E(.*?)\\Q" + XmLepConstants.FILE_EXTENSION_GROOVY + "\\E$");

    private final TenantScriptStorage tenantScriptStorage;

    private final String appName;

    @Getter
    private final ResourceLoader routerResourceLoader;

    public XmLepResourceService(String appName, TenantScriptStorage tenantScriptStorage, ResourceLoader routerResourceLoader) {
        this.appName = Objects.requireNonNull(appName, "appName can't be null");
        this.tenantScriptStorage = Objects.requireNonNull(tenantScriptStorage, "tenantScriptStorage can't be null");
        this.routerResourceLoader = routerResourceLoader;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isResourceExists(ContextsHolder contextsHolder, LepResourceKey resourceKey) {
        return getScriptResource(contextsHolder, resourceKey).exists();
    }

    // lep:/some/group/<script_name>$<enreplacedyType>$<from_state_name>$<to_state_name>$<script_type>.groovy
    // lep:/com/icthh/lep/<script_name>$<enreplacedyType>$<state>$<script_type>.groovy
    /**
     * {@inheritDoc}
     */
    @Override
    public LepResourceDescriptor getResourceDescriptor(ContextsHolder contextsHolder, LepResourceKey resourceKey) {
        Objects.requireNonNull(resourceKey, "resourceKey can't be null");
        Resource scriptResource = getScriptResource(contextsHolder, resourceKey);
        if (!scriptResource.exists()) {
            log.debug("No LEP resource for key {}", resourceKey);
            return null;
        }
        return getLepResourceDescriptor(resourceKey, scriptResource);
    }

    private LepResourceDescriptor getLepResourceDescriptor(LepResourceKey resourceKey, Resource scriptResource) {
        // get script modification time
        Instant modificationTime;
        try {
            modificationTime = Instant.ofEpochMilli(scriptResource.lastModified());
        } catch (IOException e) {
            throw new IllegalStateException("Error while getting script resource modification time: " + e.getMessage(), e);
        }
        // build descriptor
        return new DefaultLepResourceDescriptor(getResourceType(resourceKey), resourceKey, Instant.EPOCH, modificationTime);
    }

    private static LepResourceType getResourceType(LepResourceKey resourceKey) {
        String id = resourceKey.getId();
        if (StringUtils.isBlank(id)) {
            throw new IllegalArgumentException("Resource key id cant be blank");
        }
        if (id.endsWith(XmLepConstants.SCRIPT_EXTENSION_GROOVY)) {
            return XmLepResourceType.GROOVY;
        }
        throw new IllegalStateException("Unsupported LEP resource script type for key: " + resourceKey.toString());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public LepResource getResource(ContextsHolder contextsHolder, LepResourceKey resourceKey) {
        Objects.requireNonNull(resourceKey, "resourceKey can't be null");
        log.debug("Getting LEP resource for key {}", resourceKey);
        final Resource scriptResource = getScriptResource(contextsHolder, resourceKey);
        if (!scriptResource.exists()) {
            log.debug("No LEP resource for key {}", resourceKey);
            return null;
        }
        // build descriptor
        LepResourceDescriptor descriptor = getLepResourceDescriptor(resourceKey, scriptResource);
        log.debug("LEP resource for key {} found, descriptor: {}", resourceKey, descriptor);
        return new ScriptLepResource(descriptor, ScriptLepResource.DEFAULT_ENCODING, new InputStreamSupplier() {

            /**
             * {@inheritDoc}
             */
            @Override
            public InputStream getInputStream() throws IOException {
                return scriptResource.getInputStream();
            }
        });
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public LepResource saveResource(ContextsHolder contextsHolder, LepKey extensionKey, LepResource resource) {
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Version> getResourceVersions(ContextsHolder contextsHolder, LepResourceKey resourceKey) {
        return Collections.emptyList();
    }

    private Resource getScriptResource(ContextsHolder contextsHolder, LepResourceKey resourceKey) {
        String location = getResourceLocation(contextsHolder, resourceKey);
        log.trace("LEP resource with key '{}' resolved to location '{}'", resourceKey, location);
        return routerResourceLoader.getResource(location);
    }

    private String getResourceLocation(ContextsHolder contextsHolder, LepResourceKey resourceKey) {
        if (!(resourceKey instanceof UrlLepResourceKey)) {
            throw new IllegalArgumentException("Unsupported LEP resource key type: " + resourceKey.getClreplaced().getCanonicalName());
        }
        UrlLepResourceKey urlKey = UrlLepResourceKey.clreplaced.cast(resourceKey);
        String path = urlKey.getUrlResourcePath();
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        // get script type ? '$default.groovy'
        Matcher matcher = SCRIPT_TYPE_PATTERN.matcher(path);
        if (!matcher.find()) {
            throw new IllegalArgumentException("Can't find script type in LEP resource key: " + resourceKey);
        }
        String type = matcher.group(1);
        // is default script
        if (XmLepResourceSubType.DEFAULT.getName().equals(type)) {
            return getDefaultScriptLocation(path);
        } else {
            // tenant script
            return getTenantScriptLocation(path, contextsHolder);
        }
    }

    private String getDefaultScriptLocation(String path) {
        // exclude type
        int beforeTypeIndex = path.lastIndexOf(XmLepConstants.SCRIPT_NAME_SEPARATOR);
        int scriptExtIndex = path.lastIndexOf(XmLepConstants.SCRIPT_EXTENSION_SEPARATOR);
        String pathForDefault = path.substring(0, beforeTypeIndex) + path.substring(scriptExtIndex);
        return CLreplacedPATH_URL_PREFIX + "/lep/default" + pathForDefault;
    }

    private String getTenantScriptLocation(String path, ContextsHolder contextsHolder) {
        String tenantKey = LepContextUtils.getTenantKey(contextsHolder);
        return tenantScriptStorage.resolvePath(tenantKey, appName, path);
    }
}

19 View Source File : LepSpringConfiguration.java
License : Apache License 2.0
Project Creator : xm-online

/**
 * The {@link LepSpringConfiguration} clreplaced.
 */
@Configuration
public abstract clreplaced LepSpringConfiguration {

    private static final String FILE_URL_PREFIX = "file:";

    private static final int RESOURCE_LOADERS_CAPACITY = 3;

    private final String appName;

    private final ApplicationEventPublisher eventPublisher;

    private final ResourceLoader resourceLoader;

    @Autowired
    @Lazy
    private XmLepScriptConfigServerResourceLoader xmLepScriptConfigServerResourceLoader;

    @Autowired
    @Lazy
    private LoggingConfigService loggingConfigService;

    protected LepSpringConfiguration(String appName, ApplicationEventPublisher eventPublisher, ResourceLoader resourceLoader) {
        this.appName = Objects.requireNonNull(appName);
        this.eventPublisher = eventPublisher;
        this.resourceLoader = resourceLoader;
    }

    @Bean
    @Scope(SCOPE_SINGLETON)
    protected LepManager lepManager() {
        return new SpringLepManager(extensionService(), lepExecutor(), applicationLepProcessingEventPublisher(), lepResourceService(), loggingConfigService);
    }

    @Bean
    public ScriptNameLepResourceKeyMapper scriptNameLepResourceKeyMapper() {
        return new DefaultScriptNameLepResourceKeyMapper();
    }

    @Bean
    public XmGroovyScriptEngineProviderStrategy xmGroovyScriptEngineProviderStrategy() {
        return new XmGroovyScriptEngineProviderStrategy(scriptNameLepResourceKeyMapper());
    }

    @Bean
    public XmGroovyExecutionStrategy xmGroovyExecutionStrategy() {
        return new XmGroovyExecutionStrategy();
    }

    @Bean
    public LepExecutor lepExecutor() {
        return new StrategyGroovyLepExecutor(scriptNameLepResourceKeyMapper(), xmGroovyScriptEngineProviderStrategy(), xmGroovyExecutionStrategy());
    }

    @Bean
    public ExtensionService extensionService() {
        return new XmExtensionService();
    }

    @Bean
    public ApplicationLepProcessingEventPublisher applicationLepProcessingEventPublisher() {
        return new ApplicationLepProcessingEventPublisher(eventPublisher);
    }

    @Bean
    public XmLepScriptConfigServerResourceLoader cfgResourceLoader() {
        return new XmLepScriptConfigServerResourceLoader(appName);
    }

    @Bean
    public RouterResourceLoader routerResourceLoader() {
        Map<String, ResourceLoader> routerMap = new HashMap<>(RESOURCE_LOADERS_CAPACITY);
        routerMap.put(CLreplacedPATH_URL_PREFIX, resourceLoader);
        routerMap.put(XM_MS_CONFIG_URL_PREFIX, xmLepScriptConfigServerResourceLoader);
        routerMap.put(FILE_URL_PREFIX, new FileSystemResourceLoader());
        return new RouterResourceLoader(routerMap);
    }

    protected abstract TenantScriptStorage getTenantScriptStorageType();

    @Bean
    public LepResourceService lepResourceService() {
        return new XmLepResourceService(appName, getTenantScriptStorageType(), routerResourceLoader());
    }
}

19 View Source File : LepServicesRegistrar.java
License : Apache License 2.0
Project Creator : xm-online

/**
 * The {@link LepServicesRegistrar} register LEP service bean definitions for interfaces marked with {@link LepService}
 * when processing @{@link Configuration} clreplacedes with annottaion {@link EnableLepServices}.
 */
public clreplaced LepServicesRegistrar implements ImportBeanDefinitionRegistrar, // BeanClreplacedLoaderAware
ResourceLoaderAware, // BeanClreplacedLoaderAware
EnvironmentAware {

    /**
     * Resource loader for {@link LepService} annotation scanning.
     */
    private ResourceLoader resourceLoader;

    /**
     * Environment for {@link LepServiceProvider}.
     */
    private Environment environment;

    /**
     * {@inheritDoc}
     */
    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClreplacedMetadata, BeanDefinitionRegistry registry) {
        LepServiceProvider scanner = getScanner();
        Set<String> basePackages = getBasePackages(importingClreplacedMetadata);
        for (String basePackage : basePackages) {
            Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents(basePackage);
            for (BeanDefinition candidateComponent : candidateComponents) {
                if (candidateComponent instanceof AnnotatedBeanDefinition) {
                    AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
                    AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
                    Map<String, Object> attributes = annotationMetadata.getAnnotationAttributes(LepService.clreplaced.getCanonicalName());
                    registerLepService(registry, annotationMetadata, attributes);
                }
            }
        }
    }

    private void registerLepService(BeanDefinitionRegistry registry, AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
        // has a default, won't be null
        boolean primary = (Boolean) attributes.get("primary");
        String clreplacedName = annotationMetadata.getClreplacedName();
        BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(LepServiceFactoryBean.clreplaced);
        definition.addPropertyValue("type", clreplacedName);
        definition.addPropertyValue("annotationMetadata", annotationMetadata);
        definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
        AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
        beanDefinition.setPrimary(primary);
        String name = getBeanName(annotationMetadata, attributes);
        String alias = name + LepService.clreplaced.getSimpleName();
        String qualifier = getQualifier(attributes);
        if (StringUtils.hasText(qualifier)) {
            alias = qualifier;
        }
        BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, name, new String[] { alias });
        BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
    }

    private static String getBeanName(AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
        // name & value are aliases
        String beanName = (String) attributes.get("value");
        if (!StringUtils.isEmpty(beanName)) {
            return beanName;
        } else {
            // generate bean name from clreplaced name
            String shortName = ClreplacedUtils.getShortName(annotationMetadata.getClreplacedName());
            return StringUtils.uncapitalize(shortName);
        }
    }

    private static String getQualifier(Map<String, Object> lepServiceAttributes) {
        if (lepServiceAttributes == null) {
            return null;
        }
        String qualifier = (String) lepServiceAttributes.get("qualifier");
        if (StringUtils.hasText(qualifier)) {
            return qualifier;
        }
        return null;
    }

    private LepServiceProvider getScanner() {
        LepServiceProvider scanner = new LepServiceProvider(this.environment);
        scanner.setResourceLoader(this.resourceLoader);
        return scanner;
    }

    private Set<String> getBasePackages(AnnotationMetadata importingClreplacedMetadata) {
        Map<String, Object> attributes = importingClreplacedMetadata.getAnnotationAttributes(EnableLepServices.clreplaced.getCanonicalName());
        Set<String> basePackages = new HashSet<>();
        for (String pkg : (String[]) attributes.get("value")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }
        for (String pkg : (String[]) attributes.get("basePackages")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }
        for (Clreplaced<?> clazz : (Clreplaced[]) attributes.get("basePackageClreplacedes")) {
            basePackages.add(ClreplacedUtils.getPackageName(clazz));
        }
        if (basePackages.isEmpty()) {
            basePackages.add(ClreplacedUtils.getPackageName(importingClreplacedMetadata.getClreplacedName()));
        }
        return basePackages;
    }
}

19 View Source File : RouterResourceLoader.java
License : Apache License 2.0
Project Creator : xm-online

@Override
public Resource getResource(String location) {
    String urlPrefix = getUrlPrefix(location);
    if (urlPrefix == null) {
        throw new IllegalStateException("Can't detect URL prefix for location: " + location);
    }
    ResourceLoader resourceLoader = urlPrefixToResourceLoader.get(urlPrefix);
    if (resourceLoader == null) {
        throw new IllegalStateException("Unsupported resource URL prefix: " + urlPrefix);
    }
    return resourceLoader.getResource(location);
}

19 View Source File : RouterResourceLoader.java
License : Apache License 2.0
Project Creator : xm-online

@Override
public ClreplacedLoader getClreplacedLoader() {
    ResourceLoader resourceLoader = urlPrefixToResourceLoader.get(ResourceLoader.CLreplacedPATH_URL_PREFIX);
    if (resourceLoader == null) {
        resourceLoader = urlPrefixToResourceLoader.values().stream().findFirst().orElse(null);
    }
    if (resourceLoader == null) {
        return ClreplacedUtils.getDefaultClreplacedLoader();
    }
    return resourceLoader.getClreplacedLoader();
}

See More Examples