You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IndexCodes.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /*
  2. Copyright (c) 2008 Health Market Science, Inc.
  3. This library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. This library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with this library; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  14. USA
  15. You can contact Health Market Science at info@healthmarketscience.com
  16. or at the following address:
  17. Health Market Science
  18. 2700 Horizon Drive
  19. Suite 200
  20. King of Prussia, PA 19406
  21. */
  22. package com.healthmarketscience.jackcess;
  23. import java.io.BufferedReader;
  24. import java.io.IOException;
  25. import java.io.InputStreamReader;
  26. import java.util.Arrays;
  27. import java.util.HashMap;
  28. import java.util.Map;
  29. /**
  30. * Various constants used for creating index entries.
  31. *
  32. * @author James Ahlborn
  33. */
  34. public class IndexCodes {
  35. static final byte ASC_START_FLAG = (byte)0x7F;
  36. static final byte ASC_NULL_FLAG = (byte)0x00;
  37. static final byte DESC_START_FLAG = (byte)0x80;
  38. static final byte DESC_NULL_FLAG = (byte)0xFF;
  39. static final byte END_TEXT = (byte)0x01;
  40. static final byte END_EXTRA_TEXT = (byte)0x00;
  41. static final byte MID_GUID = (byte)0x09;
  42. static final byte ASC_END_GUID = (byte)0x08;
  43. static final byte DESC_END_GUID = (byte)0xF7;
  44. static final byte ASC_BOOLEAN_TRUE = (byte)0x00;
  45. static final byte ASC_BOOLEAN_FALSE = (byte)0xFF;
  46. static final byte DESC_BOOLEAN_TRUE = ASC_BOOLEAN_FALSE;
  47. static final byte DESC_BOOLEAN_FALSE = ASC_BOOLEAN_TRUE;
  48. // unprintable char is removed from normal text.
  49. // pattern for unprintable chars in the extra bytes:
  50. // 01 01 01 <pos> 06 <code> )
  51. // <pos> = 7 + (4 * char_pos) | 0x8000 (as short)
  52. // <code> = char code
  53. static final int UNPRINTABLE_COUNT_START = 7;
  54. static final int UNPRINTABLE_COUNT_MULTIPLIER = 4;
  55. static final int UNPRINTABLE_OFFSET_FLAGS = 0x8000;
  56. static final byte UNPRINTABLE_MIDFIX = (byte)0x06;
  57. // international char is replaced with ascii char.
  58. // pattern for international chars in the extra bytes:
  59. // [ 02 (for each normal char) ] [ <symbol_code> (for each inat char) ]
  60. static final byte INTERNATIONAL_EXTRA_PLACEHOLDER = (byte)0x02;
  61. // see Index.writeCrazyCodes for details on writing crazy codes
  62. static final byte CRAZY_CODE_START = (byte)0x80;
  63. static final byte CRAZY_CODE_1 = (byte)0x02;
  64. static final byte CRAZY_CODE_2 = (byte)0x03;
  65. static final byte[] CRAZY_CODES_SUFFIX =
  66. new byte[]{(byte)0xFF, (byte)0x02, (byte)0x80, (byte)0xFF, (byte)0x80};
  67. static final byte CRAZY_CODES_UNPRINT_SUFFIX = (byte)0xFF;
  68. // stash the codes in some resource files
  69. private static final String CODES_FILE =
  70. "com/healthmarketscience/jackcess/index_codes.txt";
  71. private static final String EXT_CODES_FILE =
  72. "com/healthmarketscience/jackcess/index_codes_ext.txt";
  73. /**
  74. * Enum which classifies the types of char encoding strategies used when
  75. * creating text index entries.
  76. */
  77. enum Type {
  78. SIMPLE("S") {
  79. @Override public CharHandler parseCodes(String[] codeStrings) {
  80. return parseSimpleCodes(codeStrings);
  81. }
  82. },
  83. INTERNATIONAL("I") {
  84. @Override public CharHandler parseCodes(String[] codeStrings) {
  85. return parseInternationalCodes(codeStrings);
  86. }
  87. },
  88. UNPRINTABLE("U") {
  89. @Override public CharHandler parseCodes(String[] codeStrings) {
  90. return parseUnprintableCodes(codeStrings);
  91. }
  92. },
  93. UNPRINTABLE_EXT("P") {
  94. @Override public CharHandler parseCodes(String[] codeStrings) {
  95. return parseUnprintableExtCodes(codeStrings);
  96. }
  97. },
  98. INTERNATIONAL_EXT("Z") {
  99. @Override public CharHandler parseCodes(String[] codeStrings) {
  100. return parseInternationalExtCodes(codeStrings);
  101. }
  102. },
  103. IGNORED("X") {
  104. @Override public CharHandler parseCodes(String[] codeStrings) {
  105. return IGNORED_CHAR_HANDLER;
  106. }
  107. };
  108. private final String _prefixCode;
  109. private Type(String prefixCode) {
  110. _prefixCode = prefixCode;
  111. }
  112. public String getPrefixCode() {
  113. return _prefixCode;
  114. }
  115. public abstract CharHandler parseCodes(String[] codeStrings);
  116. }
  117. /**
  118. * Base class for the handlers which hold thetext index character encoding
  119. * information.
  120. */
  121. abstract static class CharHandler {
  122. public abstract Type getType();
  123. public byte[] getInlineBytes() {
  124. return null;
  125. }
  126. public byte[] getExtraBytes() {
  127. return null;
  128. }
  129. public byte[] getUnprintableBytes() {
  130. return null;
  131. }
  132. public byte getExtraByteModifier() {
  133. return 0;
  134. }
  135. public byte getCrazyFlag() {
  136. return 0;
  137. }
  138. }
  139. /**
  140. * CharHandler for Type.SIMPLE
  141. */
  142. private static final class SimpleCharHandler extends CharHandler {
  143. private byte[] _bytes;
  144. private SimpleCharHandler(byte[] bytes) {
  145. _bytes = bytes;
  146. }
  147. @Override public Type getType() {
  148. return Type.SIMPLE;
  149. }
  150. @Override public byte[] getInlineBytes() {
  151. return _bytes;
  152. }
  153. }
  154. /**
  155. * CharHandler for Type.INTERNATIONAL
  156. */
  157. private static final class InternationalCharHandler extends CharHandler {
  158. private byte[] _bytes;
  159. private byte[] _extraBytes;
  160. private InternationalCharHandler(byte[] bytes, byte[] extraBytes) {
  161. _bytes = bytes;
  162. _extraBytes = extraBytes;
  163. }
  164. @Override public Type getType() {
  165. return Type.INTERNATIONAL;
  166. }
  167. @Override public byte[] getInlineBytes() {
  168. return _bytes;
  169. }
  170. @Override public byte[] getExtraBytes() {
  171. return _extraBytes;
  172. }
  173. }
  174. /**
  175. * CharHandler for Type.UNPRINTABLE
  176. */
  177. private static final class UnprintableCharHandler extends CharHandler {
  178. private byte[] _unprintBytes;
  179. private UnprintableCharHandler(byte[] unprintBytes) {
  180. _unprintBytes = unprintBytes;
  181. }
  182. @Override public Type getType() {
  183. return Type.UNPRINTABLE;
  184. }
  185. @Override public byte[] getUnprintableBytes() {
  186. return _unprintBytes;
  187. }
  188. }
  189. /**
  190. * CharHandler for Type.UNPRINTABLE_EXT
  191. */
  192. private static final class UnprintableExtCharHandler extends CharHandler {
  193. private byte _extraByteMod;
  194. private UnprintableExtCharHandler(Byte extraByteMod) {
  195. _extraByteMod = extraByteMod;
  196. }
  197. @Override public Type getType() {
  198. return Type.UNPRINTABLE_EXT;
  199. }
  200. @Override public byte getExtraByteModifier() {
  201. return _extraByteMod;
  202. }
  203. }
  204. /**
  205. * CharHandler for Type.INTERNATIONAL_EXT
  206. */
  207. private static final class InternationalExtCharHandler extends CharHandler {
  208. private byte[] _bytes;
  209. private byte[] _extraBytes;
  210. private byte _crazyFlag;
  211. private InternationalExtCharHandler(byte[] bytes, byte[] extraBytes,
  212. byte crazyFlag) {
  213. _bytes = bytes;
  214. _extraBytes = extraBytes;
  215. _crazyFlag = crazyFlag;
  216. }
  217. @Override public Type getType() {
  218. return Type.INTERNATIONAL_EXT;
  219. }
  220. @Override public byte[] getInlineBytes() {
  221. return _bytes;
  222. }
  223. @Override public byte[] getExtraBytes() {
  224. return _extraBytes;
  225. }
  226. @Override public byte getCrazyFlag() {
  227. return _crazyFlag;
  228. }
  229. }
  230. /** shared CharHandler instance for Type.IGNORED */
  231. static final CharHandler IGNORED_CHAR_HANDLER = new CharHandler() {
  232. @Override public Type getType() {
  233. return Type.IGNORED;
  234. }
  235. };
  236. /** alternate shared CharHandler instance for "surrogate" chars (which we do
  237. not handle) */
  238. static final CharHandler SURROGATE_CHAR_HANDLER = new CharHandler() {
  239. @Override public Type getType() {
  240. return Type.IGNORED;
  241. }
  242. @Override public byte[] getInlineBytes() {
  243. throw new IllegalStateException(
  244. "Surrogate pair chars are not handled");
  245. }
  246. };
  247. private static final char FIRST_CHAR = (char)0x0000;
  248. private static final char LAST_CHAR = (char)0x00FF;
  249. private static final char FIRST_EXT_CHAR = LAST_CHAR + 1;
  250. private static final char LAST_EXT_CHAR = (char)0xFFFF;
  251. private static final class Codes
  252. {
  253. /** handlers for the first 256 chars. use nested class to lazy load the
  254. handlers */
  255. private static final CharHandler[] _values = loadCodes(
  256. CODES_FILE, FIRST_CHAR, LAST_CHAR);
  257. }
  258. private static final class ExtCodes
  259. {
  260. /** handlers for the rest of the chars in BMP 0. use nested class to
  261. lazy load the handlers */
  262. private static final CharHandler[] _values = loadCodes(
  263. EXT_CODES_FILE, FIRST_EXT_CHAR, LAST_EXT_CHAR);
  264. }
  265. private IndexCodes() {
  266. }
  267. /**
  268. * Returns the CharHandler for the given character.
  269. */
  270. static CharHandler getCharHandler(char c)
  271. {
  272. if(c <= LAST_CHAR) {
  273. return Codes._values[c];
  274. }
  275. int extOffset = asUnsignedChar(c) - asUnsignedChar(FIRST_EXT_CHAR);
  276. return ExtCodes._values[extOffset];
  277. }
  278. /**
  279. * Loads the CharHandlers for the given range of characters from the
  280. * resource file with the given name.
  281. */
  282. private static CharHandler[] loadCodes(String codesFilePath,
  283. char firstChar, char lastChar)
  284. {
  285. int numCodes = (asUnsignedChar(lastChar) - asUnsignedChar(firstChar)) + 1;
  286. CharHandler[] values = new CharHandler[numCodes];
  287. Map<String,Type> prefixMap = new HashMap<String,Type>();
  288. for(Type type : Type.values()) {
  289. prefixMap.put(type.getPrefixCode(), type);
  290. }
  291. BufferedReader reader = null;
  292. try {
  293. reader = new BufferedReader(
  294. new InputStreamReader(
  295. Thread.currentThread().getContextClassLoader()
  296. .getResourceAsStream(codesFilePath), "US-ASCII"));
  297. int start = asUnsignedChar(firstChar);
  298. int end = asUnsignedChar(lastChar);
  299. for(int i = start; i <= end; ++i) {
  300. char c = (char)i;
  301. CharHandler ch = null;
  302. if(Character.isHighSurrogate(c) || Character.isLowSurrogate(c)) {
  303. // surrogate chars are not included in the codes files
  304. ch = SURROGATE_CHAR_HANDLER;
  305. } else {
  306. String codeLine = reader.readLine();
  307. ch = parseCodes(prefixMap, codeLine);
  308. }
  309. values[(i - start)] = ch;
  310. }
  311. } catch(IOException e) {
  312. throw new RuntimeException("failed loading index codes file " +
  313. codesFilePath, e);
  314. } finally {
  315. if (reader != null) {
  316. try {
  317. reader.close();
  318. } catch (IOException ex) {
  319. // ignored
  320. }
  321. }
  322. }
  323. return values;
  324. }
  325. /**
  326. * Returns a CharHandler parsed from the given line from an index codes
  327. * file.
  328. */
  329. private static CharHandler parseCodes(Map<String,Type> prefixMap,
  330. String codeLine)
  331. {
  332. String prefix = codeLine.substring(0, 1);
  333. String suffix = ((codeLine.length() > 1) ? codeLine.substring(2) : "");
  334. return prefixMap.get(prefix).parseCodes(suffix.split(",", -1));
  335. }
  336. /**
  337. * Returns a SimpleCharHandler parsed from the given index code strings.
  338. */
  339. private static CharHandler parseSimpleCodes(String[] codeStrings)
  340. {
  341. if(codeStrings.length != 1) {
  342. throw new IllegalStateException("Unexpected code strings " +
  343. Arrays.asList(codeStrings));
  344. }
  345. return new SimpleCharHandler(codesToBytes(codeStrings[0], true));
  346. }
  347. /**
  348. * Returns an InternationalCharHandler parsed from the given index code
  349. * strings.
  350. */
  351. private static CharHandler parseInternationalCodes(String[] codeStrings)
  352. {
  353. if(codeStrings.length != 2) {
  354. throw new IllegalStateException("Unexpected code strings " +
  355. Arrays.asList(codeStrings));
  356. }
  357. return new InternationalCharHandler(codesToBytes(codeStrings[0], true),
  358. codesToBytes(codeStrings[1], true));
  359. }
  360. /**
  361. * Returns a UnprintableCharHandler parsed from the given index code
  362. * strings.
  363. */
  364. private static CharHandler parseUnprintableCodes(String[] codeStrings)
  365. {
  366. if(codeStrings.length != 1) {
  367. throw new IllegalStateException("Unexpected code strings " +
  368. Arrays.asList(codeStrings));
  369. }
  370. return new UnprintableCharHandler(codesToBytes(codeStrings[0], true));
  371. }
  372. /**
  373. * Returns a UnprintableExtCharHandler parsed from the given index code
  374. * strings.
  375. */
  376. private static CharHandler parseUnprintableExtCodes(String[] codeStrings)
  377. {
  378. if(codeStrings.length != 1) {
  379. throw new IllegalStateException("Unexpected code strings " +
  380. Arrays.asList(codeStrings));
  381. }
  382. byte[] bytes = codesToBytes(codeStrings[0], true);
  383. if(bytes.length != 1) {
  384. throw new IllegalStateException("Unexpected code strings " +
  385. Arrays.asList(codeStrings));
  386. }
  387. return new UnprintableExtCharHandler(bytes[0]);
  388. }
  389. /**
  390. * Returns a InternationalExtCharHandler parsed from the given index code
  391. * strings.
  392. */
  393. private static CharHandler parseInternationalExtCodes(String[] codeStrings)
  394. {
  395. if(codeStrings.length != 3) {
  396. throw new IllegalStateException("Unexpected code strings " +
  397. Arrays.asList(codeStrings));
  398. }
  399. byte crazyFlag = ("1".equals(codeStrings[2]) ?
  400. CRAZY_CODE_1 : CRAZY_CODE_2);
  401. return new InternationalExtCharHandler(codesToBytes(codeStrings[0], true),
  402. codesToBytes(codeStrings[1], false),
  403. crazyFlag);
  404. }
  405. /**
  406. * Converts a string of hex encoded bytes to a byte[], optionally throwing
  407. * an exception if no codes are given.
  408. */
  409. private static byte[] codesToBytes(String codes, boolean required)
  410. {
  411. if(codes.length() == 0) {
  412. if(required) {
  413. throw new IllegalStateException("empty code bytes");
  414. }
  415. return null;
  416. }
  417. byte[] bytes = new byte[codes.length() / 2];
  418. for(int i = 0; i < bytes.length; ++i) {
  419. int charIdx = i*2;
  420. bytes[i] = (byte)(Integer.parseInt(codes.substring(charIdx, charIdx + 2),
  421. 16));
  422. }
  423. return bytes;
  424. }
  425. /**
  426. * Returns an the char value converted to an unsigned char value. Note, I
  427. * think this is unnecessary (I think java treats chars as unsigned), but I
  428. * did this just to be on the safe side.
  429. */
  430. private static int asUnsignedChar(char c)
  431. {
  432. return c & 0xFFFF;
  433. }
  434. static boolean isNullEntry(byte startEntryFlag) {
  435. return((startEntryFlag == ASC_NULL_FLAG) ||
  436. (startEntryFlag == DESC_NULL_FLAG));
  437. }
  438. static byte getNullEntryFlag(boolean isAscending) {
  439. return(isAscending ? ASC_NULL_FLAG : DESC_NULL_FLAG);
  440. }
  441. static byte getStartEntryFlag(boolean isAscending) {
  442. return(isAscending ? ASC_START_FLAG : DESC_START_FLAG);
  443. }
  444. }