00001 package edu.tum.cs.srldb;
00002
00003 import java.util.HashSet;
00004 import java.util.Map;
00005
00006 import edu.tum.cs.srldb.datadict.DDAttribute;
00007 import edu.tum.cs.srldb.datadict.DDRelation;
00008 import edu.tum.cs.srldb.datadict.DataDictionary;
00009 import edu.tum.cs.util.datastruct.Map2D;
00010
00016 public class IdentifierNamer {
00017 protected Map2D<String, String, String> identifiers;
00018 protected Map2D<String, String, Integer> counts;
00019 protected HashSet<String> reservedWords;
00020
00021 public IdentifierNamer(DataDictionary dd) {
00022 identifiers = new Map2D<String, String, String>();
00023 counts = new Map2D<String, String, Integer>();
00024 reservedWords = new HashSet<String>();
00025
00026 for(DDAttribute attrib : dd.getAttributes()) {
00027 reservedWords.add(Database.stdPredicateName(attrib.getName()));
00028 }
00029 for(DDRelation rel : dd.getRelations()) {
00030 reservedWords.add(Database.stdPredicateName(rel.getName()));
00031 }
00032 }
00033
00034 protected boolean isAvailable(String context, String id) {
00035 if(reservedWords.contains(id))
00036 return false;
00037 Map<String, String> submap = identifiers.getSubmap(context);
00038 if(submap == null)
00039 return true;
00040 return !submap.containsValue(id);
00041 }
00042
00043 public String getShortIdentifier(String category, String name) {
00044 return getIdentifier(category, name.toLowerCase(), true, false);
00045 }
00046
00047 public String getCountedShortIdentifier(String category, String name) {
00048 return getIdentifier(category, name.toLowerCase(), true, true);
00049 }
00050
00051 public String getLongIdentifier(String category, String name) {
00052 return getIdentifier(category, name, false, false);
00053 }
00054
00055 public String getCountedLongIdentifier(String category, String name) {
00056 return getIdentifier(category, name, false, true);
00057 }
00058
00059 public String getIdentifier(String category, String name, boolean shortName, boolean counted) {
00060 String id = identifiers.get(category, name);
00061 if(id != null) {
00062 if(!counted)
00063 return id;
00064 Integer count = counts.get(category, name);
00065 if(count == null) {
00066 count = new Integer(0);
00067 counts.put(count);
00068 }
00069 count++;
00070 if(count == 1)
00071 return id;
00072 else
00073 return id + count;
00074 }
00075 String idProposal = name;
00076 for(int i = shortName ? 1 : name.length(); true; i++) {
00077 idProposal = i > name.length() ? idProposal + "_" : name.substring(0, i);
00078 if(isAvailable(category, idProposal)) {
00079 identifiers.put(category, name, idProposal);
00080 return idProposal;
00081 }
00082 }
00083 }
00084
00085 public void resetCounts() {
00086 counts = new Map2D<String, String, Integer>();
00087 }
00088 }