/******************************************************************************* * Copyright (c) 2007, 2010 Association for Decentralized Information Management * in Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation *******************************************************************************/ package org.simantics.layer0.utils; import java.util.HashMap; import java.util.Map; import org.simantics.db.Resource; /** * Service that creates unique names for resources and * resource paths. */ public class NameMap { int maxLength; Map cache = new HashMap(); int curId = 0; public NameMap(int maxLength) { this.maxLength = maxLength; } protected boolean isValid(String name) { return true; } private static final int charA = 65; private static final int char0 = 48 - 26; public void clear() { curId = 0; cache.clear(); } public String getName(Resource resource) { String ret = cache.get(resource); while(ret == null) { int id = curId++; byte[] c = new byte[5]; c[0] = '@'; for(int i=0;i<4;++i) { int lid = id%36; if(lid < 26) c[4-i] = (byte)(charA + lid); else c[4-i] = (byte)(char0 + lid); id /= 36; } ret = new String(c); if(isValid(ret)) cache.put(resource, ret); else ret = null; } return ret; } public static void main(String[] args) { NameMap m = new NameMap(24); for(int i=0;i<100;++i) System.out.println(m.getName(new Resource() { @Override public int getThreadHash() { return hashCode(); } @Override public long getResourceId() { return 3; } @Override public Resource get() { return this; } @Override public boolean isPersistent() { return false; } @Override public int compareTo(Resource o) { // TODO Auto-generated method stub return 0; } @Override public boolean equalsResource(Resource other) { return equals(other); } })); } public String getName(Resource[] resources) { String ret = ""; for(Resource r : resources) ret += getName(r); return ret; } }