001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019 020package org.apache.isis.core.commons.resource; 021 022import java.io.InputStream; 023import java.io.OutputStream; 024import java.util.ArrayList; 025import java.util.List; 026 027import org.slf4j.Logger; 028import org.slf4j.LoggerFactory; 029 030public class ResourceStreamSourceChainOfResponsibility extends ResourceStreamSourceAbstract { 031 032 private static Logger LOG = LoggerFactory.getLogger(ResourceStreamSourceChainOfResponsibility.class); 033 034 private final List<ResourceStreamSource> resourceStreamSources = new ArrayList<ResourceStreamSource>(); 035 036 public ResourceStreamSourceChainOfResponsibility(final ResourceStreamSource... resourceStreamSources) { 037 for (final ResourceStreamSource rss : resourceStreamSources) { 038 addResourceStreamSource(rss); 039 } 040 } 041 042 public void addResourceStreamSource(final ResourceStreamSource rss) { 043 this.resourceStreamSources.add(rss); 044 } 045 046 @Override 047 protected InputStream doReadResource(final String resourcePath) { 048 for (final ResourceStreamSource rss : resourceStreamSources) { 049 final InputStream resourceStream = rss.readResource(resourcePath); 050 if (resourceStream != null) { 051 return resourceStream; 052 } 053 } 054 if (LOG.isDebugEnabled()) { 055 LOG.debug("could not load resource path '" + resourcePath + "' from " + getName()); 056 } 057 return null; 058 } 059 060 @Override 061 public OutputStream writeResource(final String resourcePath) { 062 for (final ResourceStreamSource rss : resourceStreamSources) { 063 final OutputStream os = rss.writeResource(resourcePath); 064 if (os != null) { 065 return os; 066 } 067 } 068 return null; 069 } 070 071 @Override 072 public String getName() { 073 return "chain [" + resourceStreamNames() + "]"; 074 } 075 076 private String resourceStreamNames() { 077 final StringBuilder buf = new StringBuilder(); 078 boolean first = true; 079 for (final ResourceStreamSource rss : resourceStreamSources) { 080 if (first) { 081 first = false; 082 } else { 083 buf.append(", "); 084 } 085 buf.append(rss.getName()); 086 } 087 return buf.toString(); 088 } 089 090}