javax.jdo.PersistenceManagerFactory Java Examples

The following examples show how to use javax.jdo.PersistenceManagerFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LocalPersistenceManagerFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testLocalPersistenceManagerFactoryBeanWithName() throws IOException {
	LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() {
		@Override
		protected PersistenceManagerFactory newPersistenceManagerFactory(String name) {
			throw new IllegalArgumentException(name);
		}
	};
	pmfb.setPersistenceManagerFactoryName("myName");
	try {
		pmfb.afterPropertiesSet();
		fail("Should have thrown IllegalArgumentException");
	}
	catch (IllegalArgumentException ex) {
		// expected
		assertTrue("Correct exception", "myName".equals(ex.getMessage()));
	}
}
 
Example #2
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
public void CreateProducts() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        Product product = new Product("Tablet", 80.0);
        pm.makePersistent(product);
        Product product2 = new Product("Phone", 20.0);
        pm.makePersistent(product2);
        Product product3 = new Product("Laptop", 200.0);
        pm.makePersistent(product3);
        for (int i = 0; i < 100; i++) {
            String nam = "Product-" + i;
            double price = rnd.nextDouble();
            Product productx = new Product(nam, price);
            pm.makePersistent(productx);
        }
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}
 
Example #3
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
public void persistXML() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        ProductXML productXML = new ProductXML(0, "Tablet", 80.0);
        pm.makePersistent(productXML);
        ProductXML productXML2 = new ProductXML(1, "Phone", 20.0);
        pm.makePersistent(productXML2);
        ProductXML productXML3 = new ProductXML(2, "Laptop", 200.0);
        pm.makePersistent(productXML3);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}
 
Example #4
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void listXMLProducts() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();

        Query q = pm.newQuery("SELECT FROM " + ProductXML.class.getName());
        List<ProductXML> products = (List<ProductXML>) q.execute();
        Iterator<ProductXML> iter = products.iterator();
        while (iter.hasNext()) {
            ProductXML p = iter.next();
            LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.getName(), p.getPrice() });
            pm.deletePersistent(p);
        }
        LOGGER.log(Level.INFO, "--------------------------------------------------------------");
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }

        pm.close();
    }
}
 
Example #5
Source File: LocalPersistenceManagerFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testLocalPersistenceManagerFactoryBeanWithNameAndProperties() throws IOException {
	LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() {
		@Override
		protected PersistenceManagerFactory newPersistenceManagerFactory(String name) {
			throw new IllegalArgumentException(name);
		}
	};
	pmfb.setPersistenceManagerFactoryName("myName");
	pmfb.getJdoPropertyMap().put("myKey", "myValue");
	try {
		pmfb.afterPropertiesSet();
		fail("Should have thrown IllegalStateException");
	}
	catch (IllegalStateException ex) {
		// expected
		assertTrue(ex.getMessage().indexOf("persistenceManagerFactoryName") != -1);
		assertTrue(ex.getMessage().indexOf("jdoProp") != -1);
	}
}
 
Example #6
Source File: JDOPMRetriever.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
public  Object getPersistenceManager(String client,PersistenceManagerFactory pmf) 
{
	Map<String,PersistenceManager> map = (Map<String,PersistenceManager>)super.get();
	PersistenceManager pm = null;
	if (map != null)
		pm = map.get(client);
	
    if(pm == null || pm.isClosed()) 
    {
        pm = pmf.getPersistenceManager( ); 
        pm.setUserObject(client);
        if (map == null)
        	map = new HashMap<>();
        map.put(client, pm);
        set(map);
    }

    return pm;
}
 
Example #7
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void ListProducts() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();

        Query q = pm.newQuery("SELECT FROM " + Product.class.getName() + " WHERE price > 10");
        List<Product> products = (List<Product>) q.execute();
        Iterator<Product> iter = products.iterator();
        while (iter.hasNext()) {
            Product p = iter.next();
            LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
        }
        LOGGER.log(Level.INFO, "--------------------------------------------------------------");
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }

        pm.close();
    }
}
 
Example #8
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public void DeleteProducts() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        Query query = pm.newQuery(Product.class, "name == \"Android Phone\"");
        Collection result = (Collection) query.execute();
        Product product = (Product) result.iterator().next();
        pm.deletePersistent(product);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}
 
Example #9
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public void UpdateProducts() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        Query query = pm.newQuery(Product.class, "name == \"Phone\"");
        Collection result = (Collection) query.execute();
        Product product = (Product) result.iterator().next();
        product.setName("Android Phone");
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}
 
Example #10
Source File: HivePersistenceManagerFactory.java    From metacat with Apache License 2.0 5 votes vote down vote up
/**
 * getPersistenceManagerFactory.
 *
 * @param props props
 * @return PersistenceManagerFactory
 */
public static PersistenceManagerFactory getPersistenceManagerFactory(final Map props) {
    final String name = String.valueOf(props.get(HiveConfigConstants.JAVAX_JDO_OPTION_NAME));
    PersistenceManagerFactory result = factories.get(name);
    if (result == null) {
        result = getpersistencemanagerfactory(props);
    }
    return result;
}
 
Example #11
Source File: TransactionAwarePersistenceManagerFactoryProxy.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set the target JDO PersistenceManagerFactory that this proxy should
 * delegate to. This should be the raw PersistenceManagerFactory, as
 * accessed by JdoTransactionManager.
 * @see org.springframework.orm.jdo.JdoTransactionManager
 */
public void setTargetPersistenceManagerFactory(PersistenceManagerFactory target) {
	Assert.notNull(target, "Target PersistenceManagerFactory must not be null");
	this.target = target;
	Class<?>[] ifcs = ClassUtils.getAllInterfacesForClass(target.getClass(), target.getClass().getClassLoader());
	this.proxy = (PersistenceManagerFactory) Proxy.newProxyInstance(
			target.getClass().getClassLoader(), ifcs, new PersistenceManagerFactoryInvocationHandler());
}
 
Example #12
Source File: TransactionAwarePersistenceManagerFactoryProxy.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Set the target JDO PersistenceManagerFactory that this proxy should
 * delegate to. This should be the raw PersistenceManagerFactory, as
 * accessed by JdoTransactionManager.
 * @see org.springframework.orm.jdo.JdoTransactionManager
 */
public void setTargetPersistenceManagerFactory(PersistenceManagerFactory target) {
	Assert.notNull(target, "Target PersistenceManagerFactory must not be null");
	this.target = target;
	Class<?>[] ifcs = ClassUtils.getAllInterfacesForClass(target.getClass(), target.getClass().getClassLoader());
	this.proxy = (PersistenceManagerFactory) Proxy.newProxyInstance(
			target.getClass().getClassLoader(), ifcs, new PersistenceManagerFactoryInvocationHandler());
}
 
Example #13
Source File: HivePersistenceManagerFactory.java    From metacat with Apache License 2.0 5 votes vote down vote up
private static synchronized PersistenceManagerFactory getpersistencemanagerfactory(final Map props) {
    final String name = String.valueOf(props.get(HiveConfigConstants.JAVAX_JDO_OPTION_NAME));
    PersistenceManagerFactory result = factories.get(name);
    if (result == null) {
        final DataSource dataSource = DataSourceManager.get().get(name);
        final Map<String, Object> properties = Maps.newHashMap();
        properties.put(HiveConfigConstants.DATANUCLEUS_FIXEDDATASTORE,
            props.get(HiveConfigConstants.DATANUCLEUS_FIXEDDATASTORE));
        properties.put(HiveConfigConstants.DATANUCLEUS_AUTOCREATESCHEMA,
            props.get(HiveConfigConstants.DATANUCLEUS_AUTOCREATESCHEMA));
        properties.put(HiveConfigConstants.DATANUCLEUS_IDENTIFIERFACTORY,
            HiveConfigConstants.DATANUCLEUS_DATANUCLEU1);
        properties.put(HiveConfigConstants.DATANUCLEUS_CONNECTIONFACTORY, dataSource);
        properties.put(HiveConfigConstants.DATANUCLEUS_RDBMS_USELEGACYNATIVEVALUESTRATEGY, true);
        properties.put(HiveConfigConstants.DATANUCLEUS_TRANSACTIONISOLATION,
            HiveConfigConstants.DATANUCLEUS_READCOMMITTED);
        properties.put(HiveConfigConstants.DATANUCLEUS_VALIDATETABLE, false);
        properties.put(HiveConfigConstants.DATANUCLEUS_VALIDATECONSTRAINTS, false);
        properties.put(HiveConfigConstants.DATANUCLEUS_VALIDATECOLUMNS, false);
        properties.put(HiveConfigConstants.DATANUCLEUS_CACHE_LEVEL2, false);
        properties.put(HiveConfigConstants.DATANUCLEUS_CACHE_LEVEL2_TYPE, "none");
        properties.put(HiveConfigConstants.DATANUCLEUS_PERSISTENCYBYREACHATCOMMIT, false);
        properties.put(HiveConfigConstants.DATANUCLEUS_AUTOSTARTMECHANISMMODE, "Checked");
        properties.put(HiveConfigConstants.DATANUCLEUS_DETACHALLONCOMMIT, true);
        properties.put(HiveConfigConstants.DATANUCLEUS_DETACHALLONROLLBACK, true);
        properties.put(HiveConfigConstants.JAVAX_JDO_DATASTORETIMEOUT,
            props.get(HiveConfigConstants.JAVAX_JDO_DATASTORETIMEOUT));
        properties.put(HiveConfigConstants.JAVAX_JDO_DATASTOREREADTIMEOUT,
            props.get(HiveConfigConstants.JAVAX_JDO_DATASTOREREADTIMEOUT));
        properties.put(HiveConfigConstants.JAVAX_JDO_DATASTOREWRITETIMEOUT,
            props.get(HiveConfigConstants.JAVAX_JDO_DATASTOREWRITETIMEOUT));
        result = JDOPersistenceManagerFactory.getPersistenceManagerFactory(properties);
        factories.put(name, result);
    }
    return result;
}
 
Example #14
Source File: GuideToJDO.java    From tutorials with MIT License 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void QuerySQL() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();

        // SQL :
        LOGGER.log(Level.INFO, "SQL --------------------------------------------------------------");
        Query query = pm.newQuery("javax.jdo.query.SQL", "SELECT * FROM PRODUCT");
        query.setClass(Product.class);
        List<Product> results = query.executeList();

        Iterator<Product> iter = results.iterator();
        while (iter.hasNext()) {
            Product p = iter.next();
            LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
        }
        LOGGER.log(Level.INFO, "--------------------------------------------------------------");

        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }

        pm.close();
    }
}
 
Example #15
Source File: PersistenceManagerFactoryUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Obtain a JDO PersistenceManager via the given factory. Is aware of a
 * corresponding PersistenceManager bound to the current thread,
 * for example when using JdoTransactionManager. Will create a new
 * PersistenceManager else, if "allowCreate" is {@code true}.
 * <p>Same as {@code getPersistenceManager}, but throwing the original JDOException.
 * @param pmf PersistenceManagerFactory to create the PersistenceManager with
 * @param allowCreate if a non-transactional PersistenceManager should be created
 * when no transactional PersistenceManager can be found for the current thread
 * @return the PersistenceManager
 * @throws JDOException if the PersistenceManager couldn't be created
 * @throws IllegalStateException if no thread-bound PersistenceManager found and
 * "allowCreate" is {@code false}
 * @see #getPersistenceManager(javax.jdo.PersistenceManagerFactory, boolean)
 * @see JdoTransactionManager
 */
public static PersistenceManager doGetPersistenceManager(PersistenceManagerFactory pmf, boolean allowCreate)
	throws JDOException, IllegalStateException {

	Assert.notNull(pmf, "No PersistenceManagerFactory specified");

	PersistenceManagerHolder pmHolder =
			(PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf);
	if (pmHolder != null) {
		if (!pmHolder.isSynchronizedWithTransaction() &&
				TransactionSynchronizationManager.isSynchronizationActive()) {
			pmHolder.setSynchronizedWithTransaction(true);
			TransactionSynchronizationManager.registerSynchronization(
					new PersistenceManagerSynchronization(pmHolder, pmf, false));
		}
		return pmHolder.getPersistenceManager();
	}

	if (!allowCreate && !TransactionSynchronizationManager.isSynchronizationActive()) {
		throw new IllegalStateException("No JDO PersistenceManager bound to thread, " +
				"and configuration does not allow creation of non-transactional one here");
	}

	logger.debug("Opening JDO PersistenceManager");
	PersistenceManager pm = pmf.getPersistenceManager();

	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		logger.debug("Registering transaction synchronization for JDO PersistenceManager");
		// Use same PersistenceManager for further JDO actions within the transaction.
		// Thread object will get removed by synchronization at transaction completion.
		pmHolder = new PersistenceManagerHolder(pm);
		pmHolder.setSynchronizedWithTransaction(true);
		TransactionSynchronizationManager.registerSynchronization(
				new PersistenceManagerSynchronization(pmHolder, pmf, true));
		TransactionSynchronizationManager.bindResource(pmf, pmHolder);
	}

	return pm;
}
 
Example #16
Source File: PersistenceManagerFactoryUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Apply the current transaction timeout, if any, to the given JDO Query object.
 * @param query the JDO Query object
 * @param pmf JDO PersistenceManagerFactory that the Query was created for
 * @throws JDOException if thrown by JDO methods
 */
public static void applyTransactionTimeout(Query query, PersistenceManagerFactory pmf) throws JDOException {
	Assert.notNull(query, "No Query object specified");
	PersistenceManagerHolder pmHolder =
			(PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf);
	if (pmHolder != null && pmHolder.hasTimeout() &&
			pmf.supportedOptions().contains("javax.jdo.option.DatastoreTimeout")) {
		int timeout = (int) pmHolder.getTimeToLiveInMillis();
		query.setDatastoreReadTimeoutMillis(timeout);
		query.setDatastoreWriteTimeoutMillis(timeout);
	}
}
 
Example #17
Source File: PersistenceManagerFactoryUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return whether the given JDO PersistenceManager is transactional, that is,
 * bound to the current thread by Spring's transaction facilities.
 * @param pm the JDO PersistenceManager to check
 * @param pmf JDO PersistenceManagerFactory that the PersistenceManager
 * was created with (can be {@code null})
 * @return whether the PersistenceManager is transactional
 */
public static boolean isPersistenceManagerTransactional(
		PersistenceManager pm, PersistenceManagerFactory pmf) {

	if (pmf == null) {
		return false;
	}
	PersistenceManagerHolder pmHolder =
			(PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf);
	return (pmHolder != null && pm == pmHolder.getPersistenceManager());
}
 
Example #18
Source File: PersistenceManagerFactoryUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Apply the current transaction timeout, if any, to the given JDO Query object.
 * @param query the JDO Query object
 * @param pmf JDO PersistenceManagerFactory that the Query was created for
 * @throws JDOException if thrown by JDO methods
 */
public static void applyTransactionTimeout(Query query, PersistenceManagerFactory pmf) throws JDOException {
	Assert.notNull(query, "No Query object specified");
	PersistenceManagerHolder pmHolder =
			(PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf);
	if (pmHolder != null && pmHolder.hasTimeout() &&
			pmf.supportedOptions().contains("javax.jdo.option.DatastoreTimeout")) {
		int timeout = (int) pmHolder.getTimeToLiveInMillis();
		query.setDatastoreReadTimeoutMillis(timeout);
		query.setDatastoreWriteTimeoutMillis(timeout);
	}
}
 
Example #19
Source File: PersistenceManagerFactoryUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Actually release a PersistenceManager for the given factory.
 * Same as {@code releasePersistenceManager}, but throwing the original JDOException.
 * @param pm PersistenceManager to close
 * @param pmf PersistenceManagerFactory that the PersistenceManager was created with
 * (can be {@code null})
 * @throws JDOException if thrown by JDO methods
 */
public static void doReleasePersistenceManager(PersistenceManager pm, PersistenceManagerFactory pmf)
		throws JDOException {

	if (pm == null) {
		return;
	}
	// Only release non-transactional PersistenceManagers.
	if (!isPersistenceManagerTransactional(pm, pmf)) {
		logger.debug("Closing JDO PersistenceManager");
		pm.close();
	}
}
 
Example #20
Source File: OpenPersistenceManagerInViewFilter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Look up the PersistenceManagerFactory that this filter should use.
 * The default implementation looks for a bean with the specified name
 * in Spring's root application context.
 * @return the PersistenceManagerFactory to use
 * @see #getPersistenceManagerFactoryBeanName
 */
protected PersistenceManagerFactory lookupPersistenceManagerFactory() {
	if (logger.isDebugEnabled()) {
		logger.debug("Using PersistenceManagerFactory '" + getPersistenceManagerFactoryBeanName() +
				"' for OpenPersistenceManagerInViewFilter");
	}
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
	return wac.getBean(getPersistenceManagerFactoryBeanName(), PersistenceManagerFactory.class);
}
 
Example #21
Source File: AbstractJDOTest.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void setUp() throws Exception {
  super.setUp();
  final PersistenceManagerFactory emf = getPersistenceManagerFactory();
  if (emf == null || emf.isClosed() || lastTestClass != getClass()) {
    setPersistenceManagerFactory(createPersistenceManagerFactory());
    lastTestClass = getClass();
  }
}
 
Example #22
Source File: TransactionAwarePersistenceManagerFactoryProxy.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	// Invocation on PersistenceManagerFactory interface coming in...

	if (method.getName().equals("equals")) {
		// Only consider equal when proxies are identical.
		return (proxy == args[0]);
	}
	else if (method.getName().equals("hashCode")) {
		// Use hashCode of PersistenceManagerFactory proxy.
		return System.identityHashCode(proxy);
	}
	else if (method.getName().equals("getPersistenceManager")) {
		PersistenceManagerFactory target = getTargetPersistenceManagerFactory();
		PersistenceManager pm =
				PersistenceManagerFactoryUtils.doGetPersistenceManager(target, isAllowCreate());
		Class<?>[] ifcs = ClassUtils.getAllInterfacesForClass(pm.getClass(), pm.getClass().getClassLoader());
		return Proxy.newProxyInstance(
				pm.getClass().getClassLoader(), ifcs, new PersistenceManagerInvocationHandler(pm, target));
	}

	// Invoke method on target PersistenceManagerFactory.
	try {
		return method.invoke(getTargetPersistenceManagerFactory(), args);
	}
	catch (InvocationTargetException ex) {
		throw ex.getTargetException();
	}
}
 
Example #23
Source File: JDOTest.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void setUp() throws Exception {
  super.setUp();
  final PersistenceManagerFactory emf = getPersistenceManagerFactory();
  if (emf == null || emf.isClosed() || lastTestClass != getClass()) {
    setPersistenceManagerFactory(createPersistenceManagerFactory());
    lastTestClass = getClass();
  }
}
 
Example #24
Source File: GuideToJDOIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenProduct_WhenNewThenPerformTransaction() {
    PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
    pumd.addClassName("com.baeldung.libraries.jdo.Product");
    pumd.setExcludeUnlistedClasses();
    pumd.addProperty("javax.jdo.option.ConnectionDriverName", "org.h2.Driver");
    pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence");
    pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa");
    pumd.addProperty("javax.jdo.option.ConnectionPassword", "");
    pumd.addProperty("datanucleus.autoCreateSchema", "true");
    pumd.addProperty("datanucleus.schema.autoCreateTables", "true");

    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        for (int i = 0; i < 100; i++) {
            String nam = "Product-" + i;
            Product productx = new Product(nam, (double) i);
            pm.makePersistent(productx);
        }
        tx.commit();
    } catch (Throwable thr) {
        fail("Failed test : " + thr.getMessage());
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }

    pmf.close();
}
 
Example #25
Source File: OpenPersistenceManagerInViewTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testOpenPersistenceManagerInViewInterceptor() throws Exception {
	PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class);
	PersistenceManager pm = mock(PersistenceManager.class);

	OpenPersistenceManagerInViewInterceptor interceptor = new OpenPersistenceManagerInViewInterceptor();
	interceptor.setPersistenceManagerFactory(pmf);

	MockServletContext sc = new MockServletContext();
	MockHttpServletRequest request = new MockHttpServletRequest(sc);

	given(pmf.getPersistenceManager()).willReturn(pm);
	interceptor.preHandle(new ServletWebRequest(request));
	assertTrue(TransactionSynchronizationManager.hasResource(pmf));

	// check that further invocations simply participate
	interceptor.preHandle(new ServletWebRequest(request));

	interceptor.preHandle(new ServletWebRequest(request));
	interceptor.postHandle(new ServletWebRequest(request), null);
	interceptor.afterCompletion(new ServletWebRequest(request), null);

	interceptor.postHandle(new ServletWebRequest(request), null);
	interceptor.afterCompletion(new ServletWebRequest(request), null);

	interceptor.preHandle(new ServletWebRequest(request));
	interceptor.postHandle(new ServletWebRequest(request), null);
	interceptor.afterCompletion(new ServletWebRequest(request), null);

	interceptor.postHandle(new ServletWebRequest(request), null);
	assertTrue(TransactionSynchronizationManager.hasResource(pmf));

	interceptor.afterCompletion(new ServletWebRequest(request), null);
	assertFalse(TransactionSynchronizationManager.hasResource(pmf));
}
 
Example #26
Source File: JDOFactory.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
private void registerFactory(String clientName, String databaseName, DataSource ds) {
  	Properties connectionProperties = (Properties) dataNucleusProperties.clone();
  	connectionProperties.put("javax.jdo.option.ConnectionFactory", ds);
if (databaseName != null)
  		connectionProperties.setProperty("datanucleus.mapping.Catalog", databaseName);
  	logger.info("Adding PMF factory for client "+clientName+" with database "+databaseName);
      PersistenceManagerFactory factory = JDOHelper.getPersistenceManagerFactory(connectionProperties);
      factories.put(clientName, factory);
  }
 
Example #27
Source File: JDOFactory.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
/**
 * 	Return the singleton persistence manager factory instance.
 */
public synchronized PersistenceManagerFactory getPersistenceManagerFactory ()
{
	if (factories.size() == 1)
		return factories.values().iterator().next();
	else
		return null;
}
 
Example #28
Source File: OAuthServiceImplRobotTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the case when the user has not started the authorization process (no
 * request token).
 */
public final void testCheckAuthorizationNoRequestToken() {
  // Setup.
  LoginFormHandler loginForm = mock(LoginFormHandler.class);
  OAuthClient client = mock(OAuthClient.class);
  PersistenceManager pm = mock(PersistenceManager.class);
  PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class);

  OAuthAccessor accessor = buildAccessor(CONSUMER_KEY, CONSUMER_SECRET,
      REQUEST_TOKEN_URL, AUTHORIZE_URL, CALLBACK_URL, ACCESS_TOKEN_URL);
  accessor.requestToken = REQUEST_TOKEN_STRING;
  oauthService = new OAuthServiceImpl(accessor, client, pmf,
      USER_RECORD_KEY);
  OAuthUser userWithRequestToken = new OAuthUser(USER_RECORD_KEY, REQUEST_TOKEN_STRING);

  // Expectations.
  when(pmf.getPersistenceManager()).thenReturn(pm);
  when(pm.getObjectById(OAuthUser.class, USER_RECORD_KEY)).thenReturn(null, userWithRequestToken,
      userWithRequestToken);

  assertFalse(oauthService.checkAuthorization(null, loginForm));

  String authUrl = userWithRequestToken.getAuthUrl();
  try {
    new URL(authUrl);
  } catch (MalformedURLException e) {
    fail("Malformed authUrl");
  }

  assertTrue(Pattern.matches(".+(oauth_token){1}.+", authUrl));
  assertTrue(Pattern.matches(".+(oauth_callback){1}.+", authUrl));
}
 
Example #29
Source File: SpringPersistenceManagerProxyBean.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Return the target PersistenceManagerFactory for this proxy.
 */
protected PersistenceManagerFactory getPersistenceManagerFactory() {
	return this.persistenceManagerFactory;
}
 
Example #30
Source File: TransactionAwarePersistenceManagerFactoryProxy.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public PersistenceManagerInvocationHandler(PersistenceManager target, PersistenceManagerFactory pmf) {
	this.target = target;
	this.persistenceManagerFactory = pmf;
}