001/* 002 * Copyright 2020 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.core.resources; 017 018import java.util.HashSet; 019import java.util.Set; 020 021import org.apache.avalon.framework.configuration.Configuration; 022import org.apache.avalon.framework.configuration.ConfigurationException; 023import org.apache.avalon.framework.service.ServiceException; 024import org.apache.avalon.framework.service.ServiceManager; 025import org.apache.commons.lang3.StringUtils; 026import org.apache.excalibur.source.SourceResolver; 027 028import org.ametys.core.resources.ImageResourceHandler.SizedSource; 029 030/** 031 * {@link ResourceHandlerProvider} for images. 032 */ 033public class ImageResourceHandlerProvider extends AbstractSimpleResourceHandlerProvider 034{ 035 /** The source resolver */ 036 protected SourceResolver _resolver; 037 038 /** The supported mime types */ 039 protected Set<String> _supportedMimeTypes; 040 041 @Override 042 public void service(ServiceManager manager) throws ServiceException 043 { 044 super.service(manager); 045 _resolver = (SourceResolver) manager.lookup(SourceResolver.ROLE); 046 } 047 048 @Override 049 public void configure(Configuration configuration) throws ConfigurationException 050 { 051 super.configure(configuration); 052 053 _supportedMimeTypes = new HashSet<>(); 054 055 Configuration[] mimeTypes = configuration.getChild("mimeTypes").getChildren("mimeType"); 056 for (Configuration mimeType : mimeTypes) 057 { 058 _supportedMimeTypes.add(StringUtils.lowerCase(mimeType.getValue())); 059 } 060 } 061 062 @Override 063 public ResourceHandler getResourceHandler(String location) throws Exception 064 { 065 ResourceHandler resourceHandler = super.getResourceHandler(location); 066 if (resourceHandler != null) 067 { 068 return resourceHandler; 069 } 070 071 SizedSource sizedSource = ImageResourceHandler._resolveSource(location, _resolver); 072 if (sizedSource != null) 073 { 074 if (_supportedMimeTypes.stream() 075 .anyMatch(mimeType -> StringUtils.equalsIgnoreCase(sizedSource.source().getMimeType(), mimeType))) 076 { 077 return new ImageResourceHandler(sizedSource); 078 } 079 else 080 { 081 _resolver.release(sizedSource.source()); 082 } 083 } 084 085 return null; 086 } 087 088 @Override 089 protected ResourceHandler createResourceHandler(String source) 090 { 091 return new ImageResourceHandler(); 092 } 093}