2 * ============LICENSE_START=======================================================
3 * feature-session-persistence
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.drools.persistence;
23 import javax.persistence.EntityManager;
24 import javax.persistence.EntityManagerFactory;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
29 public class JpaDroolsSessionConnector implements DroolsSessionConnector {
31 private static Logger logger = LoggerFactory.getLogger(JpaDroolsSessionConnector.class);
33 private final EntityManagerFactory emf;
35 public JpaDroolsSessionConnector(EntityManagerFactory emf) {
40 public DroolsSession get(String sessName) {
42 EntityManager em = emf.createEntityManager();
43 DroolsSessionEntity entity = null;
45 try (EntityMgrTrans trans = new EntityMgrTrans(em)) {
47 entity = em.find(DroolsSessionEntity.class, sessName);
59 public void replace(DroolsSession sess) {
60 String sessName = sess.getSessionName();
62 logger.info("replace: Entering and manually updating session name= {}", sessName);
64 EntityManager em = emf.createEntityManager();
66 try (EntityMgrTrans trans = new EntityMgrTrans(em)) {
68 if (!update(em, sess)) {
75 logger.info("replace: Exiting");
79 * Adds a session to the persistent store.
81 * @param em entity manager
82 * @param sess session to be added
84 private void add(EntityManager em, DroolsSession sess) {
85 logger.info("add: Inserting session id={}", sess.getSessionId());
87 DroolsSessionEntity ent = new DroolsSessionEntity(sess.getSessionName(), sess.getSessionId());
93 * Updates a session, if it exists within the persistent store.
95 * @param em entity manager
96 * @param sess session data to be persisted
97 * @return {@code true} if a record was updated, {@code false} if it was not found
99 private boolean update(EntityManager em, DroolsSession sess) {
101 DroolsSessionEntity session = em.find(DroolsSessionEntity.class, sess.getSessionName());
102 if (session == null) {
106 logger.info("update: Updating session id to {}", sess.getSessionId());
107 session.setSessionId(sess.getSessionId());