Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
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 }