1   package com.trendmicro.grid.acl.metadata;
2   
3   import com.trendmicro.grid.acl.commons.collections.StringCache;
4   
5   import java.util.concurrent.ConcurrentMap;
6   
7   /**
8    * Implements a string cache that can be used to reduce the memory footprint of Metadata elements
9    * by sharing instances of equal strings.
10   *
11   * @author juergen_kellerer, 2010-06-25
12   * @version 1.0
13   */
14  public class MetadataStringCache extends StringCache {
15  
16  	private static final long serialVersionUID = -714419543858155943L;
17  
18  	boolean includeStringValues;
19  
20  	public MetadataStringCache() {
21  	}
22  
23  	public MetadataStringCache(ConcurrentMap<String, String> cache, boolean includeStringValues) {
24  		super(cache);
25  		this.includeStringValues = includeStringValues;
26  	}
27  
28  	/**
29  	 * Shares the strings in the given metadata element.
30  	 *
31  	 * @param metadata the element to share the strings in.
32  	 */
33  	public void shareStrings(Metadata metadata) {
34  		if (metadata == null || metadata.getMetaElements().isEmpty())
35  			return;
36  
37  		final ValidatedMetaMap sourceMap = metadata.metaElements;
38  		final ValidatorResolver sourceResolver = sourceMap.getValidatorResolver();
39  
40  		final ValidatedMetaMap newMap = new ValidatedMetaMap(sourceMap.size(), null);
41  		for (Meta meta : sourceMap.valuesWithoutValidation()) {
42  			meta.name = toSharedString(meta.name);
43  
44  			if (includeStringValues && meta.getDataType() == DataType.STRING) {
45  				if (meta.value instanceof String)
46  					meta.value = toSharedString((String) meta.value);
47  				else if (meta.value instanceof String[])
48  					toSharedStrings((String[]) meta.value);
49  			}
50  
51  			newMap.put(meta.name, meta);
52  		}
53  
54  		newMap.setValidatorResolver(sourceResolver);
55  		metadata.metaElements = newMap;
56  	}
57  }