StringResourceProvider.java
Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2011 Google Inc.
00003  * 
00004  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
00005  * use this file except in compliance with the License. You may obtain a copy of
00006  * the License at
00007  * 
00008  * http://www.apache.org/licenses/LICENSE-2.0
00009  * 
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
00012  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
00013  * License for the specific language governing permissions and limitations under
00014  * the License.
00015  */
00016 
00017 package org.ros.internal.message;
00018 
00019 import com.google.common.collect.ImmutableMap;
00020 import com.google.common.collect.Maps;
00021 
00022 import org.ros.exception.RosMessageRuntimeException;
00023 
00024 import java.io.IOException;
00025 import java.io.InputStream;
00026 import java.nio.charset.Charset;
00027 import java.util.Map;
00028 import java.util.NoSuchElementException;
00029 
00033 public class StringResourceProvider {
00034 
00035   private final Map<String, String> cache;
00036 
00037   public StringResourceProvider() {
00038     cache = Maps.newConcurrentMap();
00039   }
00040 
00041   public String get(String resourceName) {
00042     if (!has(resourceName)) {
00043       throw new NoSuchElementException("Resource does not exist: " + resourceName);
00044     }
00045     if (!cache.containsKey(resourceName)) {
00046       InputStream in = getClass().getResourceAsStream(resourceName);
00047       StringBuilder out = new StringBuilder();
00048       Charset charset = Charset.forName("US-ASCII");
00049       byte[] buffer = new byte[8192];
00050       try {
00051         for (int bytesRead; (bytesRead = in.read(buffer)) != -1;) {
00052           out.append(new String(buffer, 0, bytesRead, charset));
00053         }
00054       } catch (IOException e) {
00055         throw new RosMessageRuntimeException("Failed to read resource: " + resourceName, e);
00056       }
00057       cache.put(resourceName, out.toString());
00058     }
00059     return cache.get(resourceName);
00060   }
00061 
00062   public boolean has(String resourceName) {
00063     return cache.containsKey(resourceName) || getClass().getResource(resourceName) != null;
00064   }
00065 
00066   public Map<String, String> getCachedStrings() {
00067     return ImmutableMap.copyOf(cache);
00068   }
00069 
00070   public void addStringToCache(String resourceName, String resourceContent) {
00071     cache.put(resourceName, resourceContent);
00072   }
00073 }


rosjava_bootstrap
Author(s): Daniel Stonier , Damon Kohler
autogenerated on Fri Aug 28 2015 12:41:44