Skip to content

Commit

Permalink
Added functionality to build EntityManagerFactory from META-INF/persi…
Browse files Browse the repository at this point in the history
…stence.xml file.
  • Loading branch information
smile.animesh committed Jul 29, 2010
1 parent 2ccdc39 commit 963328e
Show file tree
Hide file tree
Showing 8 changed files with 710 additions and 22 deletions.
166 changes: 166 additions & 0 deletions src/main/java/com/impetus/kundera/ejb/EntityManagerFactoryBuilder.java
@@ -0,0 +1,166 @@
/*
* Copyright 2010 Impetus Infotech.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.impetus.kundera.ejb;

import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.spi.PersistenceUnitTransactionType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* Builds EmtityManagerFactory instances from classpath
*
* @author animesh.kumar
*
*/
public class EntityManagerFactoryBuilder {

/** The Constant log. */
private static final Log log = LogFactory.getLog(EntityManagerFactoryBuilder.class);

private static final String PROVIDER_IMPLEMENTATION_NAME = KunderaPersistence.class.getName();

/**
* Builds up EntityManagerFactory for a given persistenceUnitName and
* overriding properties.
*
* @param persistenceUnitName
* @param integration
* @return
*/
public EntityManagerFactory buildEntityManagerFactory (String persistenceUnitName, Map<Object, Object> override) {
PersistenceMetadata metadata = getPersistenceMetadata(persistenceUnitName);

Properties props = new Properties();
// Override properties
Properties metadataProperties = metadata.getProps();
// Make sure, it's empty or Unmodifiable
override = override == null ? Collections.EMPTY_MAP : Collections.unmodifiableMap( override );

// Take all from Metadata and override with supplied map
for (Map.Entry<Object, Object> entry : metadataProperties.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();

if (override.containsKey(key)) {
value = override.get(key);
}
props.put(key, value);
}

// Now take all the remaining ones from override
for (Map.Entry<Object, Object> entry : override.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();

if (!props.containsKey(key)) {
props.put(key, value);
}
}

log.info("Building EntityManagerFactory for name: " + metadata.getName() + ", and Properties:" + props);
return new EntityManagerFactoryImpl(metadata.getName(), props);
}

private PersistenceMetadata getPersistenceMetadata (String persistenceUnitName) {
log.info( "Look up for persistence unit: " + persistenceUnitName );

List<PersistenceMetadata> metadatas = findPersistenceMetadatas();

// If there is just ONE persistenceUnit, then use this irrespective of the name
if ( metadatas.size() == 1 ) {
return metadatas.get(0);
}

// Since there is more persistenceUnits, you must provide a name to look up
if ( isEmpty(persistenceUnitName) ) {
throw new PersistenceException( "No name provided and several persistence units found" );
}

// Look for one that interests us
for (PersistenceMetadata metadata : metadatas) {
if (metadata.getName().equals(persistenceUnitName)) {
return metadata;
}
}

throw new PersistenceException("Could not find persistence unit in the classpath for name: " + persistenceUnitName);
}

private List<PersistenceMetadata> findPersistenceMetadatas () {
try {
Enumeration<URL> xmls = Thread.currentThread()
.getContextClassLoader().getResources(
"META-INF/persistence.xml");

if (!xmls.hasMoreElements()) {
log.info("Could not find any META-INF/persistence.xml " +
"file in the classpath");
}

Set<String> persistenceUnitNames = new HashSet<String>();
List<PersistenceMetadata> persistenceUnits = new ArrayList<PersistenceMetadata>();

while (xmls.hasMoreElements()) {
URL url = xmls.nextElement();
log.trace("Analyse of persistence.xml: " + url);
List<PersistenceMetadata> metadataFiles = PersistenceXmlLoader
.findPersistenceUnits (url, PersistenceUnitTransactionType.RESOURCE_LOCAL);

// Pick only those that have Kundera Provider
for (PersistenceMetadata metadata : metadataFiles) {
// check for provider
if ( metadata.getProvider() == null || PROVIDER_IMPLEMENTATION_NAME.equalsIgnoreCase(
metadata.getProvider()
) ) {
persistenceUnits.add(metadata);
}

// check for unique names
if (persistenceUnitNames.contains(metadata.getName())) {
throw new PersistenceException("Duplicate persistence-units for name: " + metadata.getName());
}
persistenceUnitNames.add(metadata.getName());
}
}

return persistenceUnits;
} catch (Exception e) {
if (e instanceof PersistenceException) {
throw (PersistenceException) e;
} else {
throw new PersistenceException(e);
}
}
}

// helper class
private static boolean isEmpty (String str) {
return null == str || str.isEmpty();
}
}
64 changes: 53 additions & 11 deletions src/main/java/com/impetus/kundera/ejb/EntityManagerFactoryImpl.java
Expand Up @@ -18,6 +18,7 @@
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;
import java.util.Properties;

Expand Down Expand Up @@ -68,7 +69,7 @@ public class EntityManagerFactoryImpl implements EntityManagerFactory {
private String[] nodes;

/** The port. */
private int port;
private Integer port;

/** The keyspace. */
private String keyspace;
Expand Down Expand Up @@ -118,7 +119,7 @@ public EntityManagerFactoryImpl(String persistenceUnitName, Map props) {
// if props is NULL or empty, look for kundera.properties and populate
if (props == null || props.isEmpty()) {
try {

log.debug("Trying to load Kundera Properties from " + propsFileName);
loadProperties(propsFileName);
} catch (IOException e) {
throw new PersistenceException(e);
Expand Down Expand Up @@ -160,28 +161,69 @@ private void loadProperties(String propsFileName) throws IOException {
* Inits the.
*/
private void init() {
nodes = ((String) props.get("kundera.nodes")).split(",");
port = Integer.parseInt((String) props.get("kundera.port"));
keyspace = (String) props.get("kundera.keyspace");

// Look for kundera.nodes
try {
String kunderaNodes = (String)props.get("kundera.nodes");
if (null == kunderaNodes || kunderaNodes.isEmpty()) {
throw new IllegalArgumentException();
}
nodes = kunderaNodes.split(",");
} catch (Exception e) {
throw new IllegalArgumentException("Mandatory property missing 'kundera.nodes'");
}

// kundera.port
String kunderaPort = (String) props.get("kundera.port");
if (null == kunderaPort || kunderaPort.isEmpty()) {
throw new IllegalArgumentException("Mandatory property missing 'kundera.port'");
}
try {
port = Integer.parseInt(kunderaPort);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid value for property 'kundera.port': " + kunderaPort + ". (Should it be 9160?)");
}

// kundera.keyspace
keyspace = (String) props.get("kundera.keyspace");
if (null == keyspace || keyspace.isEmpty()) {
throw new IllegalArgumentException("Mandatory property missing 'kundera.keyspace'");
}

// sessionless
String sessionless_ = (String) props.get("sessionless");
if (sessionless_ == null) {
sessionless = true;
} else {
sessionless = Boolean.parseBoolean(sessionless_);
try {
sessionless = Boolean.parseBoolean(sessionless_);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid value for property 'sessionless': " + kunderaPort + ". (It should be true/false)");
}
}

// kundera.client
String cassandraClient = (String) props.get("kundera.client");
if (null == cassandraClient || cassandraClient.isEmpty()) {
throw new IllegalArgumentException("Mandatory property missing 'kundera.client'");
}

// Instantiate the client
try {
if ( cassandraClient.endsWith( ".class" ) ) {
cassandraClient = cassandraClient.substring( 0, cassandraClient.length() - 6 );
}

client = (CassandraClient) Class.forName(cassandraClient).newInstance();
client.setContactNodes(nodes);
client.setDefaultPort(port);
// client.setKeySpace(keyspace);
// connect to Cassandra DB
client.connect();
} catch (Exception e) {
throw new IllegalArgumentException("Must define CassandraClient! " + e.getMessage());
throw new IllegalArgumentException("Invalid value for property 'kundera.client': " + cassandraClient + ". (Should it be com.impetus.kundera.client.PelopsClient?");
}

log.info("Connecting to Cassandra... (nodes:" + Arrays.asList(nodes) + ", port:" + port + ", keyspace:" + keyspace + ")");

// connect to Cassandra DB
client.connect();
}

/**
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/com/impetus/kundera/ejb/KunderaPersistence.java
Expand Up @@ -44,7 +44,7 @@ public KunderaPersistence() {
*/
@Override
public final EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) {
return new EntityManagerFactoryImpl(info.getPersistenceUnitName(), map);
return createEntityManagerFactory(info.getPersistenceUnitName(), map);
}

/*
Expand All @@ -56,7 +56,8 @@ public final EntityManagerFactory createContainerEntityManagerFactory(Persistenc
*/
@Override
public final EntityManagerFactory createEntityManagerFactory(String emName, Map map) {
return new EntityManagerFactoryImpl(emName, map);
EntityManagerFactoryBuilder conf = new EntityManagerFactoryBuilder();
return conf.buildEntityManagerFactory(emName, map);
}

}

0 comments on commit 963328e

Please sign in to comment.