001 /*
002 GRANITE DATA SERVICES
003 Copyright (C) 2011 GRANITE DATA SERVICES S.A.S.
004
005 This file is part of Granite Data Services.
006
007 Granite Data Services is free software; you can redistribute it and/or modify
008 it under the terms of the GNU Library General Public License as published by
009 the Free Software Foundation; either version 2 of the License, or (at your
010 option) any later version.
011
012 Granite Data Services is distributed in the hope that it will be useful, but
013 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
014 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
015 for more details.
016
017 You should have received a copy of the GNU Library General Public License
018 along with this library; if not, see <http://www.gnu.org/licenses/>.
019 */
020
021 package org.granite.tide.data;
022
023 import javax.jdo.PersistenceManager;
024 import javax.jdo.PersistenceManagerFactory;
025 import javax.jdo.Transaction;
026
027 import org.granite.tide.TideTransactionManager;
028
029 /**
030 * Responsible for attaching a entity with the entity mangager
031 * @author William DRAI
032 *
033 */
034 public class JDOPersistenceManager extends AbstractTidePersistenceManager implements TideTransactionPersistenceManager {
035
036 protected PersistenceManager pm;
037
038
039 public JDOPersistenceManager() {
040 super(new JDOTransactionManager());
041 }
042
043 public JDOPersistenceManager(PersistenceManagerFactory pmf) {
044 this(pmf, null);
045 }
046
047 public JDOPersistenceManager(PersistenceManagerFactory pmf, TideTransactionManager tm) {
048 super(tm != null ? tm : new JDOTransactionManager());
049 pm = pmf.getPersistenceManager();
050 }
051
052 public Object getCurrentTransaction() {
053 Transaction t = pm.currentTransaction();
054 t.begin();
055 return t;
056 }
057
058 @Override
059 public void close() {
060 if (pm != null && !pm.isClosed())
061 pm.close();
062 }
063
064
065 /**
066 * Finds the entity with the JDO persistence manager.
067 * @return the entity
068 */
069 @Override
070 public Object fetchEntity(Object entity, String[] fetch) {
071 Object id = pm.getObjectId(entity);
072 if (id == null)
073 return null;
074
075 return pm.getObjectById(id);
076 }
077
078
079 public static class JDOTransactionManager implements TideTransactionManager {
080
081 public Object begin(TideTransactionPersistenceManager pm) {
082 if (pm != null)
083 return pm.getCurrentTransaction();
084 return null;
085 }
086
087 public void commit(Object t) throws Exception {
088 ((Transaction)t).commit();
089 }
090
091 public void rollback(Object t) {
092 ((Transaction)t).rollback();
093 }
094 }
095 }