Advertisement
Guest User

Untitled

a guest
Dec 30th, 2016
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.45 KB | None | 0 0
  1. package dropwizardold;
  2.  
  3. import com.google.common.base.Throwables;
  4.  
  5. import io.dropwizard.logging.BootstrapLogging;
  6.  
  7. import org.hibernate.Session;
  8. import org.hibernate.SessionFactory;
  9. import org.hibernate.Transaction;
  10. import org.hibernate.cfg.AvailableSettings;
  11. import org.hibernate.cfg.Configuration;
  12. import org.hibernate.context.internal.ManagedSessionContext;
  13. import org.junit.rules.ExternalResource;
  14.  
  15. import java.util.HashMap;
  16. import java.util.LinkedHashSet;
  17. import java.util.Map;
  18. import java.util.Map.Entry;
  19. import java.util.Set;
  20. import java.util.UUID;
  21. import java.util.concurrent.Callable;
  22.  
  23. /**
  24. * A JUnit rule for testing DAOs and Hibernate entities. It allows to quickly
  25. * test the database access code without starting the Dropwizard infrastructure.
  26. * <p>
  27. * Example:
  28. *
  29. * <pre>
  30. * <code>
  31. * {@literal @}Rule
  32. * public DAOTestRule daoTestRule = DAOTestRule.newBuilder()
  33. * .addEntityClass(Person.class)
  34. * .build();
  35. *
  36. * private PersonDAO personDAO;
  37. *
  38. * {@literal @}Before
  39. * public void setUp() throws Exception {
  40. * personDAO = new PersonDAO(daoTestRule.getSessionFactory());
  41. * }
  42. *
  43. * {@literal @}Test
  44. * public void createPerson() {
  45. * Person wizard = daoTestRule.inTransaction(() -> personDAO.create(new Person("Merlin", "The chief wizard")));
  46. * assertThat(wizard.getId()).isGreaterThan(0);
  47. * assertThat(wizard.getFullName()).isEqualTo("Merlin");
  48. * assertThat(wizard.getJobTitle()).isEqualTo("The chief wizard");
  49. * }
  50. * </code>
  51. * </pre>
  52. *
  53. * </p>
  54. */
  55. public class DAOTestRule extends ExternalResource {
  56.  
  57. static {
  58. BootstrapLogging.bootstrap();
  59. }
  60.  
  61. public static class Builder {
  62.  
  63. private String url = "jdbc:h2:mem:" + UUID.randomUUID();
  64. private String username = "sa";
  65. private final String password = "";
  66. private String driver = "org.h2.Driver";
  67. private String hbm2ddlAuto = "create";
  68. private boolean showSql = false;
  69. private boolean useSqlComments = false;
  70. private final Set<Class<?>> entityClasses = new LinkedHashSet<>();
  71. private final Map<String, String> properties = new HashMap<>();
  72.  
  73. public Builder setUrl(String url) {
  74. this.url = url;
  75. return this;
  76. }
  77.  
  78. public Builder setUsername(String username) {
  79. this.username = username;
  80. return this;
  81. }
  82.  
  83. public Builder setDriver(Class<? extends java.sql.Driver> driver) {
  84. this.driver = driver.getName();
  85. return this;
  86. }
  87.  
  88. public Builder setHbm2DdlAuto(String hbm2ddlAuto) {
  89. this.hbm2ddlAuto = hbm2ddlAuto;
  90. return this;
  91. }
  92.  
  93. public Builder setShowSql(boolean showSql) {
  94. this.showSql = showSql;
  95. return this;
  96. }
  97.  
  98. public Builder useSqlComments(boolean useSqlComments) {
  99. this.useSqlComments = useSqlComments;
  100. return this;
  101. }
  102.  
  103. public Builder addEntityClass(Class<?> entityClass) {
  104. this.entityClasses.add(entityClass);
  105. return this;
  106. }
  107.  
  108. public Builder setProperty(String key, String value) {
  109. this.properties.put(key, value);
  110. return this;
  111. }
  112.  
  113. public DAOTestRule build() {
  114. final Configuration config = new Configuration();
  115. config.setProperty(AvailableSettings.URL, url);
  116. config.setProperty(AvailableSettings.USER, username);
  117. config.setProperty(AvailableSettings.PASS, password);
  118. config.setProperty(AvailableSettings.DRIVER, driver);
  119. config.setProperty(AvailableSettings.HBM2DDL_AUTO, hbm2ddlAuto);
  120. config.setProperty(AvailableSettings.SHOW_SQL,
  121. String.valueOf(showSql));
  122. config.setProperty(AvailableSettings.USE_SQL_COMMENTS,
  123. String.valueOf(useSqlComments));
  124. // Use the same configuration as in the Hibernate bundle to reduce
  125. // differences between
  126. // testing and production environments.
  127. config.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS,
  128. "managed");
  129. config.setProperty(AvailableSettings.USE_GET_GENERATED_KEYS, "true");
  130. config.setProperty(AvailableSettings.GENERATE_STATISTICS, "true");
  131. config.setProperty(AvailableSettings.USE_REFLECTION_OPTIMIZER,
  132. "true");
  133. config.setProperty(AvailableSettings.ORDER_UPDATES, "true");
  134. config.setProperty(AvailableSettings.ORDER_INSERTS, "true");
  135. config.setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS,
  136. "true");
  137. config.setProperty("jadira.usertype.autoRegisterUserTypes", "true");
  138.  
  139. System.out.println("XD");
  140.  
  141. for (Class<?> oneEntity : entityClasses) {
  142. config.addAnnotatedClass(oneEntity);
  143. }
  144.  
  145. for (Entry<String, String> e : properties.entrySet()) {
  146. config.setProperty(e.getKey(), e.getValue());
  147. }
  148.  
  149. return new DAOTestRule(config.buildSessionFactory());
  150. }
  151. }
  152.  
  153. /**
  154. * Creates a new builder for {@link DAOTestRule}, which allows to customize
  155. * a {@link SessionFactory} by different parameters. By default uses the H2
  156. * database in the memory mode.
  157. *
  158. * @return a new {@link Builder}
  159. */
  160. public static Builder newBuilder() {
  161. return new Builder();
  162. }
  163.  
  164. private final SessionFactory sessionFactory;
  165.  
  166. /**
  167. * Use {@link DAOTestRule#newBuilder()}
  168. */
  169. private DAOTestRule(SessionFactory sessionFactory) {
  170. this.sessionFactory = sessionFactory;
  171. }
  172.  
  173. @Override
  174. protected void before() throws Throwable {
  175. if (ManagedSessionContext.hasBind(sessionFactory)) {
  176. return;
  177. }
  178.  
  179. final Session session = sessionFactory.openSession();
  180. ManagedSessionContext.bind(session);
  181. }
  182.  
  183. @Override
  184. protected void after() {
  185. if (!ManagedSessionContext.hasBind(sessionFactory)) {
  186. return;
  187. }
  188.  
  189. final Session currentSession = sessionFactory.getCurrentSession();
  190. if (currentSession.isOpen()) {
  191. currentSession.close();
  192. }
  193. ManagedSessionContext.unbind(sessionFactory);
  194. }
  195.  
  196. /**
  197. * Returns the current active session factory for injecting to DAOs.
  198. *
  199. * @return {@link SessionFactory} with an open session.
  200. */
  201. public SessionFactory getSessionFactory() {
  202. return sessionFactory;
  203. }
  204.  
  205. /**
  206. * Performs a call in a transaction
  207. *
  208. * @param call
  209. * the call
  210. * @param <T>
  211. * the type of the returned result
  212. * @return the result of the call
  213. */
  214. public <T> T inTransaction(Callable<T> call) {
  215. final Session session = sessionFactory.getCurrentSession();
  216. final Transaction transaction = session.beginTransaction();
  217. try {
  218. final T result = call.call();
  219. transaction.commit();
  220. return result;
  221. } catch (final Exception e) {
  222. transaction.rollback();
  223. // Throwables.throwIfUnchecked(e);
  224. throw new RuntimeException(e);
  225. }
  226. }
  227.  
  228. /**
  229. * Performs an action in a transaction
  230. *
  231. * @param action
  232. * the action
  233. */
  234. public void inTransaction(Runnable action) {
  235. // action.run();
  236. System.out.println("Not Supported Yet");
  237. }
  238. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement