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.

DatabaseBuilder.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /*
  2. Copyright (c) 2012 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;
  14. import java.io.File;
  15. import java.io.IOException;
  16. import java.nio.channels.FileChannel;
  17. import java.nio.charset.Charset;
  18. import java.text.SimpleDateFormat;
  19. import java.util.Calendar;
  20. import java.util.Date;
  21. import java.util.GregorianCalendar;
  22. import java.util.HashMap;
  23. import java.util.Map;
  24. import java.util.TimeZone;
  25. import com.healthmarketscience.jackcess.impl.CodecProvider;
  26. import com.healthmarketscience.jackcess.impl.DatabaseImpl;
  27. import com.healthmarketscience.jackcess.impl.PropertyMapImpl;
  28. import com.healthmarketscience.jackcess.util.MemFileChannel;
  29. /**
  30. * Builder style class for opening/creating a {@link Database}.
  31. * <p/>
  32. * Simple example usage:
  33. * <pre>
  34. * Database db = DatabaseBuilder.open(new File("test.mdb"));
  35. * </pre>
  36. * <p/>
  37. * Advanced example usage:
  38. * <pre>
  39. * Database db = new DatabaseBuilder(new File("test.mdb"))
  40. * .setReadOnly(true)
  41. * .open();
  42. * </pre>
  43. *
  44. * @author James Ahlborn
  45. * @usage _general_class_
  46. */
  47. public class DatabaseBuilder
  48. {
  49. /** the file name of the mdb to open/create */
  50. private File _mdbFile;
  51. /** whether or not to open existing mdb read-only */
  52. private boolean _readOnly;
  53. /** whether or not to auto-sync writes to the filesystem */
  54. private boolean _autoSync = Database.DEFAULT_AUTO_SYNC;
  55. /** optional charset for mdbs with unspecified charsets */
  56. private Charset _charset;
  57. /** optional timezone override for interpreting dates */
  58. private TimeZone _timeZone;
  59. /** optional CodecProvider for handling encoded mdbs */
  60. private CodecProvider _codecProvider;
  61. /** FileFormat to use when creating a new mdb */
  62. private Database.FileFormat _fileFormat;
  63. /** optional pre-opened FileChannel, will _not_ be closed by Database
  64. close */
  65. private FileChannel _channel;
  66. /** database properties (if any) */
  67. private Map<String,PropertyMap.Property> _dbProps;
  68. /** database summary properties (if any) */
  69. private Map<String,PropertyMap.Property> _summaryProps;
  70. /** database user-defined (if any) */
  71. private Map<String,PropertyMap.Property> _userProps;
  72. public DatabaseBuilder() {
  73. this(null);
  74. }
  75. public DatabaseBuilder(File mdbFile) {
  76. _mdbFile = mdbFile;
  77. }
  78. /**
  79. * File containing an existing database for {@link #open} or target file for
  80. * new database for {@link #create} (in which case, <b>tf this file already
  81. * exists, it will be overwritten.</b>)
  82. * @usage _general_method_
  83. */
  84. public DatabaseBuilder setFile(File mdbFile) {
  85. _mdbFile = mdbFile;
  86. return this;
  87. }
  88. /**
  89. * Sets flag which, iff {@code true}, will force opening file in
  90. * read-only mode ({@link #open} only).
  91. * @usage _general_method_
  92. */
  93. public DatabaseBuilder setReadOnly(boolean readOnly) {
  94. _readOnly = readOnly;
  95. return this;
  96. }
  97. /**
  98. * Sets whether or not to enable auto-syncing on write. if {@code true},
  99. * write operations will be immediately flushed to disk upon completion.
  100. * This leaves the database in a (fairly) consistent state on each write,
  101. * but can be very inefficient for many updates. if {@code false}, flushing
  102. * to disk happens at the jvm's leisure, which can be much faster, but may
  103. * leave the database in an inconsistent state if failures are encountered
  104. * during writing. Writes may be flushed at any time using {@link
  105. * Database#flush}.
  106. * @usage _intermediate_method_
  107. */
  108. public DatabaseBuilder setAutoSync(boolean autoSync) {
  109. _autoSync = autoSync;
  110. return this;
  111. }
  112. /**
  113. * Sets the Charset to use, if {@code null}, uses default.
  114. * @usage _intermediate_method_
  115. */
  116. public DatabaseBuilder setCharset(Charset charset) {
  117. _charset = charset;
  118. return this;
  119. }
  120. /**
  121. * Sets the TimeZone to use for interpreting dates, if {@code null}, uses
  122. * default
  123. * @usage _intermediate_method_
  124. */
  125. public DatabaseBuilder setTimeZone(TimeZone timeZone) {
  126. _timeZone = timeZone;
  127. return this;
  128. }
  129. /**
  130. * Sets the CodecProvider for handling page encoding/decoding, may be
  131. * {@code null} if no special encoding is necessary
  132. * @usage _intermediate_method_
  133. */
  134. public DatabaseBuilder setCodecProvider(CodecProvider codecProvider) {
  135. _codecProvider = codecProvider;
  136. return this;
  137. }
  138. /**
  139. * Sets the version of new database ({@link #create} only).
  140. * @usage _general_method_
  141. */
  142. public DatabaseBuilder setFileFormat(Database.FileFormat fileFormat) {
  143. _fileFormat = fileFormat;
  144. return this;
  145. }
  146. /**
  147. * Sets a pre-opened FileChannel. if provided explicitly, <i>it will not be
  148. * closed by the Database instance</i>. This allows ultimate control of
  149. * where the mdb file exists (which may not be on disk, e.g.
  150. * {@link MemFileChannel}). If provided, the File parameter will be
  151. * available from {@link Database#getFile}, but otherwise ignored.
  152. * @usage _advanced_method_
  153. */
  154. public DatabaseBuilder setChannel(FileChannel channel) {
  155. _channel = channel;
  156. return this;
  157. }
  158. /**
  159. * Sets the database property with the given name to the given value.
  160. * Attempts to determine the type of the property (see
  161. * {@link PropertyMap#put(String,Object)} for details on determining the
  162. * property type).
  163. */
  164. public DatabaseBuilder putDatabaseProperty(String name, Object value) {
  165. return putDatabaseProperty(name, null, value);
  166. }
  167. /**
  168. * Sets the database property with the given name and type to the given
  169. * value.
  170. */
  171. public DatabaseBuilder putDatabaseProperty(String name, DataType type,
  172. Object value) {
  173. _dbProps = putProperty(_dbProps, name, type, value);
  174. return this;
  175. }
  176. /**
  177. * Sets the summary database property with the given name to the given
  178. * value. Attempts to determine the type of the property (see
  179. * {@link PropertyMap#put(String,Object)} for details on determining the
  180. * property type).
  181. */
  182. public DatabaseBuilder putSummaryProperty(String name, Object value) {
  183. return putSummaryProperty(name, null, value);
  184. }
  185. /**
  186. * Sets the summary database property with the given name and type to
  187. * the given value.
  188. */
  189. public DatabaseBuilder putSummaryProperty(String name, DataType type,
  190. Object value) {
  191. _summaryProps = putProperty(_summaryProps, name, type, value);
  192. return this;
  193. }
  194. /**
  195. * Sets the user-defined database property with the given name to the given
  196. * value. Attempts to determine the type of the property (see
  197. * {@link PropertyMap#put(String,Object)} for details on determining the
  198. * property type).
  199. */
  200. public DatabaseBuilder putUserDefinedProperty(String name, Object value) {
  201. return putUserDefinedProperty(name, null, value);
  202. }
  203. /**
  204. * Sets the user-defined database property with the given name and type to
  205. * the given value.
  206. */
  207. public DatabaseBuilder putUserDefinedProperty(String name, DataType type,
  208. Object value) {
  209. _userProps = putProperty(_userProps, name, type, value);
  210. return this;
  211. }
  212. private static Map<String,PropertyMap.Property> putProperty(
  213. Map<String,PropertyMap.Property> props, String name, DataType type,
  214. Object value)
  215. {
  216. if(props == null) {
  217. props = new HashMap<String,PropertyMap.Property>();
  218. }
  219. props.put(name, PropertyMapImpl.createProperty(name, type, value));
  220. return props;
  221. }
  222. /**
  223. * Opens an existingnew Database using the configured information.
  224. */
  225. public Database open() throws IOException {
  226. return DatabaseImpl.open(_mdbFile, _readOnly, _channel, _autoSync, _charset,
  227. _timeZone, _codecProvider);
  228. }
  229. /**
  230. * Creates a new Database using the configured information.
  231. */
  232. public Database create() throws IOException {
  233. Database db = DatabaseImpl.create(_fileFormat, _mdbFile, _channel, _autoSync,
  234. _charset, _timeZone);
  235. if(_dbProps != null) {
  236. PropertyMap props = db.getDatabaseProperties();
  237. props.putAll(_dbProps.values());
  238. props.save();
  239. }
  240. if(_summaryProps != null) {
  241. PropertyMap props = db.getSummaryProperties();
  242. props.putAll(_summaryProps.values());
  243. props.save();
  244. }
  245. if(_userProps != null) {
  246. PropertyMap props = db.getUserDefinedProperties();
  247. props.putAll(_userProps.values());
  248. props.save();
  249. }
  250. return db;
  251. }
  252. /**
  253. * Open an existing Database. If the existing file is not writeable, the
  254. * file will be opened read-only. Auto-syncing is enabled for the returned
  255. * Database.
  256. *
  257. * @param mdbFile File containing the database
  258. *
  259. * @see DatabaseBuilder for more flexible Database opening
  260. * @usage _general_method_
  261. */
  262. public static Database open(File mdbFile) throws IOException {
  263. return new DatabaseBuilder(mdbFile).open();
  264. }
  265. /**
  266. * Create a new Database for the given fileFormat
  267. *
  268. * @param fileFormat version of new database.
  269. * @param mdbFile Location to write the new database to. <b>If this file
  270. * already exists, it will be overwritten.</b>
  271. *
  272. * @see DatabaseBuilder for more flexible Database creation
  273. * @usage _general_method_
  274. */
  275. public static Database create(Database.FileFormat fileFormat, File mdbFile)
  276. throws IOException
  277. {
  278. return new DatabaseBuilder(mdbFile).setFileFormat(fileFormat).create();
  279. }
  280. /**
  281. * Returns a SimpleDateFormat for the given format string which is
  282. * configured with a compatible Calendar instance (see
  283. * {@link #toCompatibleCalendar}).
  284. */
  285. public static SimpleDateFormat createDateFormat(String formatStr) {
  286. SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
  287. toCompatibleCalendar(sdf.getCalendar());
  288. return sdf;
  289. }
  290. /**
  291. * Ensures that the given {@link Calendar} is configured to be compatible
  292. * with how Access handles dates. Specifically, alters the gregorian change
  293. * (the java default gregorian change switches to julian dates for dates pre
  294. * 1582-10-15, whereas Access uses <a href="https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar">proleptic gregorian dates</a>).
  295. */
  296. public static Calendar toCompatibleCalendar(Calendar cal) {
  297. if(cal instanceof GregorianCalendar) {
  298. ((GregorianCalendar)cal).setGregorianChange(new Date(Long.MIN_VALUE));
  299. }
  300. return cal;
  301. }
  302. }