Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

CalculatedColumnUtil.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /*
  2. Copyright (c) 2014 James Ahlborn
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.healthmarketscience.jackcess.impl;
  14. import java.io.IOException;
  15. import java.math.BigDecimal;
  16. import java.nio.ByteBuffer;
  17. import java.nio.ByteOrder;
  18. /**
  19. * Utility code for dealing with calculated columns.
  20. * <p/>
  21. * These are the currently possible calculated types: FLOAT, DOUBLE, INT,
  22. * LONG, BIG_INT, GUID, SHORT_DATE_TIME, MONEY, BOOLEAN, NUMERIC, TEXT, MEMO.
  23. *
  24. * @author James Ahlborn
  25. */
  26. class CalculatedColumnUtil
  27. {
  28. // offset to the int which specifies the length of the actual data
  29. private static final int CALC_DATA_LEN_OFFSET = 16;
  30. // offset to the actual data
  31. private static final int CALC_DATA_OFFSET = CALC_DATA_LEN_OFFSET + 4;
  32. // total amount of extra bytes added for calculated values
  33. static final int CALC_EXTRA_DATA_LEN = 23;
  34. // ms access seems to define all fixed-len calc fields as this length
  35. static final short CALC_FIXED_FIELD_LEN = 39;
  36. // fully encode calculated BOOLEAN "true" value
  37. private static final byte[] CALC_BOOL_TRUE = wrapCalculatedValue(
  38. new byte[]{(byte)0xFF});
  39. // fully encode calculated BOOLEAN "false" value
  40. private static final byte[] CALC_BOOL_FALSE = wrapCalculatedValue(
  41. new byte[]{0});
  42. /**
  43. * Creates the appropriate ColumnImpl class for a calculated column and
  44. * reads a column definition in from a buffer
  45. *
  46. * @param args column construction info
  47. * @usage _advanced_method_
  48. */
  49. static ColumnImpl create(ColumnImpl.InitArgs args) throws IOException
  50. {
  51. switch(args.type) {
  52. case BOOLEAN:
  53. return new CalcBooleanColImpl(args);
  54. case TEXT:
  55. return new CalcTextColImpl(args);
  56. case MEMO:
  57. return new CalcMemoColImpl(args);
  58. default:
  59. // fall through
  60. }
  61. if(args.type.getHasScalePrecision()) {
  62. return new CalcNumericColImpl(args);
  63. }
  64. return new CalcColImpl(args);
  65. }
  66. /**
  67. * Grabs the real data bytes from a calculated value.
  68. */
  69. private static byte[] unwrapCalculatedValue(byte[] data) {
  70. if(data.length < CALC_DATA_OFFSET) {
  71. return data;
  72. }
  73. ByteBuffer buffer = PageChannel.wrap(data);
  74. buffer.position(CALC_DATA_LEN_OFFSET);
  75. int dataLen = buffer.getInt();
  76. byte[] newData = new byte[Math.min(buffer.remaining(), dataLen)];
  77. buffer.get(newData);
  78. return newData;
  79. }
  80. /**
  81. * Wraps the given data bytes with the extra calculated value data and
  82. * returns a new ByteBuffer containing the final data.
  83. */
  84. private static ByteBuffer wrapCalculatedValue(ByteBuffer buffer) {
  85. ByteBuffer newBuf = prepareWrappedCalcValue(
  86. buffer.remaining(), buffer.order());
  87. newBuf.put(buffer);
  88. newBuf.rewind();
  89. return newBuf;
  90. }
  91. /**
  92. * Wraps the given data bytes with the extra calculated value data and
  93. * returns a new byte[] containing the final data.
  94. */
  95. private static byte[] wrapCalculatedValue(byte[] data) {
  96. int dataLen = data.length;
  97. data = ByteUtil.copyOf(data, 0, dataLen + CALC_EXTRA_DATA_LEN,
  98. CALC_DATA_OFFSET);
  99. PageChannel.wrap(data).putInt(CALC_DATA_LEN_OFFSET, dataLen);
  100. return data;
  101. }
  102. /**
  103. * Prepares a calculated value buffer for data of the given length.
  104. */
  105. private static ByteBuffer prepareWrappedCalcValue(int dataLen, ByteOrder order)
  106. {
  107. ByteBuffer buffer = ByteBuffer.allocate(
  108. dataLen + CALC_EXTRA_DATA_LEN).order(order);
  109. buffer.putInt(CALC_DATA_LEN_OFFSET, dataLen);
  110. buffer.position(CALC_DATA_OFFSET);
  111. return buffer;
  112. }
  113. /**
  114. * General calculated column implementation.
  115. */
  116. private static class CalcColImpl extends ColumnImpl
  117. {
  118. CalcColImpl(InitArgs args) throws IOException {
  119. super(args);
  120. }
  121. @Override
  122. public Object read(byte[] data, ByteOrder order) throws IOException {
  123. data = unwrapCalculatedValue(data);
  124. if((data.length == 0) && !getType().isVariableLength()) {
  125. // apparently "null" values can be written as actual data
  126. return null;
  127. }
  128. return super.read(data, order);
  129. }
  130. @Override
  131. protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
  132. ByteOrder order)
  133. throws IOException
  134. {
  135. // we should only be working with fixed length types
  136. ByteBuffer buffer = writeFixedLengthField(
  137. obj, prepareWrappedCalcValue(getType().getFixedSize(), order));
  138. buffer.rewind();
  139. return buffer;
  140. }
  141. }
  142. /**
  143. * Calculated BOOLEAN column implementation.
  144. */
  145. private static class CalcBooleanColImpl extends ColumnImpl
  146. {
  147. CalcBooleanColImpl(InitArgs args) throws IOException {
  148. super(args);
  149. }
  150. @Override
  151. public boolean storeInNullMask() {
  152. // calculated booleans are _not_ stored in null mask
  153. return false;
  154. }
  155. @Override
  156. public Object read(byte[] data, ByteOrder order) throws IOException {
  157. data = unwrapCalculatedValue(data);
  158. if(data.length == 0) {
  159. return Boolean.FALSE;
  160. }
  161. return ((data[0] != 0) ? Boolean.TRUE : Boolean.FALSE);
  162. }
  163. @Override
  164. protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
  165. ByteOrder order)
  166. throws IOException
  167. {
  168. return ByteBuffer.wrap(
  169. toBooleanValue(obj) ? CALC_BOOL_TRUE : CALC_BOOL_FALSE).order(order);
  170. }
  171. }
  172. /**
  173. * Calculated TEXT column implementation.
  174. */
  175. private static class CalcTextColImpl extends TextColumnImpl
  176. {
  177. CalcTextColImpl(InitArgs args) throws IOException {
  178. super(args);
  179. }
  180. @Override
  181. public short getLengthInUnits() {
  182. // the byte "length" includes the calculated field overhead. remove
  183. // that to get the _actual_ data length (in units)
  184. return (short)getType().toUnitSize(getLength() - CALC_EXTRA_DATA_LEN);
  185. }
  186. @Override
  187. public Object read(byte[] data, ByteOrder order) throws IOException {
  188. return decodeTextValue(unwrapCalculatedValue(data));
  189. }
  190. @Override
  191. protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
  192. ByteOrder order)
  193. throws IOException
  194. {
  195. return wrapCalculatedValue(super.writeRealData(
  196. obj, remainingRowLength, order));
  197. }
  198. }
  199. /**
  200. * Calculated MEMO column implementation.
  201. */
  202. private static class CalcMemoColImpl extends MemoColumnImpl
  203. {
  204. CalcMemoColImpl(InitArgs args) throws IOException {
  205. super(args);
  206. }
  207. @Override
  208. protected int getMaxLengthInUnits() {
  209. // the byte "length" includes the calculated field overhead. remove
  210. // that to get the _actual_ data length (in units)
  211. return getType().toUnitSize(getType().getMaxSize() - CALC_EXTRA_DATA_LEN);
  212. }
  213. @Override
  214. protected byte[] readLongValue(byte[] lvalDefinition)
  215. throws IOException
  216. {
  217. return unwrapCalculatedValue(super.readLongValue(lvalDefinition));
  218. }
  219. @Override
  220. protected ByteBuffer writeLongValue(byte[] value, int remainingRowLength)
  221. throws IOException
  222. {
  223. return super.writeLongValue(
  224. wrapCalculatedValue(value), remainingRowLength);
  225. }
  226. }
  227. /**
  228. * Calculated NUMERIC column implementation.
  229. */
  230. private static class CalcNumericColImpl extends NumericColumnImpl
  231. {
  232. CalcNumericColImpl(InitArgs args) throws IOException {
  233. super(args);
  234. }
  235. @Override
  236. public byte getPrecision() {
  237. return (byte)getType().getMaxPrecision();
  238. }
  239. @Override
  240. public Object read(byte[] data, ByteOrder order) throws IOException {
  241. data = unwrapCalculatedValue(data);
  242. if(data.length == 0) {
  243. // apparently "null" values can be written as actual data
  244. return null;
  245. }
  246. return readCalcNumericValue(ByteBuffer.wrap(data).order(order));
  247. }
  248. @Override
  249. protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
  250. ByteOrder order)
  251. throws IOException
  252. {
  253. int totalDataLen = Math.min(CALC_EXTRA_DATA_LEN + 16 + 4, getLength());
  254. // data length must be multiple of 4
  255. int dataLen = toMul4(totalDataLen - CALC_EXTRA_DATA_LEN);
  256. ByteBuffer buffer = prepareWrappedCalcValue(dataLen, order);
  257. writeCalcNumericValue(buffer, obj, dataLen);
  258. buffer.rewind();
  259. return buffer;
  260. }
  261. private static BigDecimal readCalcNumericValue(ByteBuffer buffer)
  262. {
  263. short totalLen = buffer.getShort();
  264. // numeric bytes need to be a multiple of 4 and we currently handle at
  265. // most 16 bytes
  266. int numByteLen = ((totalLen > 0) ? totalLen : buffer.remaining()) - 2;
  267. numByteLen = Math.min(toMul4(numByteLen), 16);
  268. byte scale = buffer.get();
  269. boolean negate = (buffer.get() != 0);
  270. byte[] tmpArr = ByteUtil.getBytes(buffer, numByteLen);
  271. if(buffer.order() != ByteOrder.BIG_ENDIAN) {
  272. fixNumericByteOrder(tmpArr);
  273. }
  274. return toBigDecimal(tmpArr, negate, scale);
  275. }
  276. private void writeCalcNumericValue(ByteBuffer buffer, Object value,
  277. int dataLen)
  278. throws IOException
  279. {
  280. Object inValue = value;
  281. try {
  282. BigDecimal decVal = toBigDecimal(value);
  283. inValue = decVal;
  284. int signum = decVal.signum();
  285. if(signum < 0) {
  286. decVal = decVal.negate();
  287. }
  288. int maxScale = getType().getMaxScale();
  289. if(decVal.scale() > maxScale) {
  290. // adjust scale according to max (will cause the an
  291. // ArithmeticException if number has too many decimal places)
  292. decVal = decVal.setScale(maxScale);
  293. }
  294. int scale = decVal.scale();
  295. // check precision
  296. if(decVal.precision() > getType().getMaxPrecision()) {
  297. throw new IOException(withErrorContext(
  298. "Numeric value is too big for specified precision "
  299. + getType().getMaxPrecision() + ": " + decVal));
  300. }
  301. // convert to unscaled BigInteger, big-endian bytes
  302. byte[] intValBytes = toUnscaledByteArray(decVal, dataLen - 4);
  303. if(buffer.order() != ByteOrder.BIG_ENDIAN) {
  304. fixNumericByteOrder(intValBytes);
  305. }
  306. buffer.putShort((short)(dataLen - 2));
  307. buffer.put((byte)scale);
  308. // write sign byte
  309. buffer.put((signum < 0) ? NUMERIC_NEGATIVE_BYTE : 0);
  310. buffer.put(intValBytes);
  311. } catch(ArithmeticException e) {
  312. throw (IOException)
  313. new IOException(withErrorContext(
  314. "Numeric value '" + inValue + "' out of range"))
  315. .initCause(e);
  316. }
  317. }
  318. private static void fixNumericByteOrder(byte[] bytes) {
  319. // this is a little weird. it looks like they decided to truncate
  320. // leading 0 bytes and _then_ swap endian, which ends up kind of odd.
  321. int pos = 0;
  322. if((bytes.length % 8) != 0) {
  323. // leading 4 bytes are swapped
  324. ByteUtil.swap4Bytes(bytes, 0);
  325. pos += 4;
  326. }
  327. // then fix endianness of each 8 byte segment
  328. for(; pos < bytes.length; pos+=8) {
  329. ByteUtil.swap8Bytes(bytes, pos);
  330. }
  331. }
  332. private static int toMul4(int val) {
  333. return ((val / 4) * 4);
  334. }
  335. }
  336. }