2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021-2022 Nordix Foundation
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.cps.spi.utils;
23 import java.util.HashMap;
25 import java.util.UUID;
26 import org.hibernate.HibernateException;
27 import org.hibernate.Session;
28 import org.hibernate.SessionException;
29 import org.hibernate.SessionFactory;
30 import org.hibernate.cfg.Configuration;
31 import org.onap.cps.spi.entities.AnchorEntity;
32 import org.onap.cps.spi.entities.DataspaceEntity;
33 import org.onap.cps.spi.entities.SchemaSetEntity;
34 import org.onap.cps.spi.entities.YangResourceEntity;
35 import org.springframework.stereotype.Component;
38 public class SessionManager {
40 private static SessionFactory sessionFactory;
41 private static Map<String, Session> sessionMap = new HashMap<>();
43 private synchronized void buildSessionFactory() {
44 if (sessionFactory == null) {
45 sessionFactory = new Configuration().configure("hibernate.cfg.xml")
46 .addAnnotatedClass(AnchorEntity.class)
47 .addAnnotatedClass(DataspaceEntity.class)
48 .addAnnotatedClass(SchemaSetEntity.class)
49 .addAnnotatedClass(YangResourceEntity.class)
50 .buildSessionFactory();
55 * Starts a session which allows use of locks and batch interaction with the persistence service.
57 * @return Session ID string
59 public String startSession() {
60 buildSessionFactory();
61 final Session session = sessionFactory.openSession();
62 final String sessionId = UUID.randomUUID().toString();
63 sessionMap.put(sessionId, session);
64 session.beginTransaction();
71 * @param sessionId session ID
73 public void closeSession(final String sessionId) {
75 final Session currentSession = sessionMap.get(sessionId);
76 currentSession.getTransaction().commit();
77 currentSession.close();
78 } catch (final NullPointerException e) {
79 throw new SessionException(String.format("Session with session ID %s does not exist", sessionId));
80 } catch (final HibernateException e) {
81 throw new SessionException(String.format("Unable to close session with session ID %s", sessionId));
83 sessionMap.remove(sessionId);