1 package org.apache.onami.persist; 2 3 /* 4 * Licensed to the Apache Software Foundation (ASF) under one 5 * or more contributor license agreements. See the NOTICE file 6 * distributed with this work for additional information 7 * regarding copyright ownership. The ASF licenses this file 8 * to you under the Apache License, Version 2.0 (the 9 * "License"); you may not use this file except in compliance 10 * with the License. You may obtain a copy of the License at 11 * 12 * http://www.apache.org/licenses/LICENSE-2.0 13 * 14 * Unless required by applicable law or agreed to in writing, 15 * software distributed under the License is distributed on an 16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 * KIND, either express or implied. See the License for the 18 * specific language governing permissions and limitations 19 * under the License. 20 */ 21 22 import javax.inject.Inject; 23 import javax.inject.Singleton; 24 import javax.persistence.EntityManagerFactory; 25 26 import static org.apache.onami.persist.Preconditions.checkNotNull; 27 28 /** 29 * Implementation of {@link PersistenceService} and {@link EntityManagerFactoryProvider} for 30 * container managed persistence units. 31 */ 32 @Singleton 33 class ContainerManagedEntityManagerFactoryProvider 34 implements EntityManagerFactoryProvider, PersistenceService 35 { 36 37 /** 38 * The source for retrieving the entity manager factory instance. 39 */ 40 private final EntityManagerFactorySource emfSource; 41 42 /** 43 * Currently active entity manager factory. 44 * Is {@code null} when the persistence service is not running. 45 */ 46 private EntityManagerFactory emf; 47 48 /** 49 * Constructor. 50 * 51 * @param emfSource the source for the {@link EntityManagerFactory}. Must not be {@code null}. 52 */ 53 @Inject 54 ContainerManagedEntityManagerFactoryProvider( EntityManagerFactorySource emfSource ) 55 { 56 this.emfSource = checkNotNull( emfSource, "emfSource is mandatory!" ); 57 } 58 59 /** 60 * {@inheritDoc} 61 */ 62 // @Override 63 public EntityManagerFactory get() 64 { 65 if ( isRunning() ) 66 { 67 return emf; 68 } 69 70 throw new IllegalStateException( "PersistenceService is not running." ); 71 } 72 73 /** 74 * {@inheritDoc} 75 */ 76 // @Override 77 public void start() 78 { 79 if ( isRunning() ) 80 { 81 throw new IllegalStateException( "PersistenceService is already running." ); 82 } 83 84 emf = emfSource.getEntityManagerFactory(); 85 } 86 87 /** 88 * {@inheritDoc} 89 */ 90 // @Override 91 public boolean isRunning() 92 { 93 return null != emf; 94 } 95 96 /** 97 * {@inheritDoc} 98 */ 99 // @Override 100 public void stop() 101 { 102 emf = null; 103 // the entity manager factory must NOT be closed: 104 // - it was created by the container and it is therefore the responsibility of the container to close it 105 // - we cannot know if another part of the application has obtained the same instance 106 } 107 108 }