Home | History | Annotate | Download | only in resourceloader
      1 /*
      2  * Copyright (C) 2010 Google Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.google.clearsilver.jsilver.resourceloader;
     18 
     19 import com.google.clearsilver.jsilver.exceptions.JSilverTemplateNotFoundException;
     20 
     21 import java.io.IOException;
     22 import java.io.Reader;
     23 import java.io.StringReader;
     24 import java.util.concurrent.ConcurrentHashMap;
     25 import java.util.concurrent.ConcurrentMap;
     26 
     27 /**
     28  * ResourceLoader that pulls all items from memory. This is particularly useful for small templates
     29  * that can be embedded in code (e.g. in unit tests).
     30  *
     31  * Content needs to be stored first using the {@link #store(String, String)} method.
     32  *
     33  * @see ResourceLoader
     34  */
     35 public class InMemoryResourceLoader extends BaseResourceLoader {
     36 
     37   private ConcurrentMap<String, String> items = new ConcurrentHashMap<String, String>();
     38 
     39   @Override
     40   public Reader open(String name) throws IOException {
     41     String content = items.get(name);
     42     return content == null ? null : new StringReader(content);
     43   }
     44 
     45   @Override
     46   public Reader openOrFail(String name) throws JSilverTemplateNotFoundException, IOException {
     47     Reader reader = open(name);
     48     if (reader == null) {
     49       throw new JSilverTemplateNotFoundException(name);
     50     } else {
     51       return reader;
     52     }
     53   }
     54 
     55   public void store(String name, String contents) {
     56     items.put(name, contents);
     57   }
     58 
     59   public void remove(String name) {
     60     items.remove(name);
     61   }
     62 
     63   public ConcurrentMap<String, String> getItems() {
     64     return items;
     65   }
     66 
     67 }
     68