Merge 1806 code of vid-common
[vid.git] / vid-app-common / src / main / java / org / onap / vid / utils / DaoUtils.java
1 package org.onap.vid.utils;
2
3 import org.hibernate.Session;
4 import org.hibernate.SessionFactory;
5 import org.hibernate.Transaction;
6 import org.onap.vid.exceptions.GenericUncheckedException;
7 import org.onap.portalsdk.core.FusionObject;
8
9 import java.util.HashMap;
10 import java.util.function.Function;
11
12 public class DaoUtils {
13
14     //all credit for this wonderful method go to is9613
15     public static<T> T tryWithSessionAndTransaction(SessionFactory sessionFactory, Function<Session, T> update) {
16         // opens a session and transactions, executes the input query.
17         // gracefully close session and transaction once error occurres.
18         Session session = null;
19         Transaction tx = null;
20         try {
21             session = sessionFactory.openSession();
22             tx = session.beginTransaction();
23
24             T res = update.apply(session);
25
26             tx.commit();
27
28             return res;
29         } catch (RuntimeException e) {
30             try {
31                 if (tx != null) {
32                     tx.rollback();
33                 }
34             } catch (RuntimeException e2) {
35                 // e2 is ingnored; we would like to know the
36                 // original failure reason, not only the reason
37                 // for rollback's failure
38                 throw new GenericUncheckedException("Failed rolling back transaction", e);
39             }
40             throw new GenericUncheckedException("Rolled back transaction", e);
41         } finally {
42             if (session != null) {
43                 session.close();
44             }
45         }
46     }
47
48     public static HashMap<String, Object> getPropsMap() {
49         HashMap<String, Object> props = new HashMap<>();
50         props.put(FusionObject.Parameters.PARAM_USERID, 0);
51         return props;
52     }
53 }