code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
private void retryInit() throws GeomajasException {
// do not hammer the service
long now = System.currentTimeMillis();
if (now > lastInitRetry + cooldownTimeBetweenInitializationRetries) {
lastInitRetry = now;
try {
log.debug("Retrying to (re-)initialize layer {}", getId());
postConstruct();
} catch (Exception e) { // NOSONAR
log.warn("Failed initializing layer: ", e.getMessage());
}
}
if (!usable) {
throw new GeomajasException(ExceptionCode.LAYER_CONFIGURATION_PROBLEM);
}
} | --------------------------------------------------- |
private String formatUrl(String imageUrl) {
if (useProxy || null != authentication || useCache) {
String token = securityContext.getToken();
if (null != token) {
StringBuilder url = new StringBuilder(imageUrl);
int pos = url.lastIndexOf("?");
if (pos > 0) {
url.append("&");
} else {
url.append("?");
}
url.append("userToken=");
url.append(token);
return url.toString();
}
}
return imageUrl;
} | Adds userToken to url if we are proxying or caching (eg. indirect calls)
@param imageUrl
@return |
public LockEntry getWriter(Object obj)
{
PersistenceBroker broker = getBroker();
Identity oid = new Identity(obj, broker);
return getWriter(oid);
} | returns the LockEntry for the Writer of object obj.
If now writer exists, null is returned. |
public Collection getReaders(Object obj)
{
checkTimedOutLocks();
Identity oid = new Identity(obj,getBroker());
return getReaders(oid);
} | returns a collection of Reader LockEntries for object obj.
If no LockEntries could be found an empty Vector is returned. |
public boolean addReader(TransactionImpl tx, Object obj)
{
checkTimedOutLocks();
Identity oid = new Identity(obj,getBroker());
LockEntry reader = new LockEntry(oid.toString(),
tx.getGUID(),
System.currentTimeMillis(),
LockStrategyFactory.getIsolationLevel(obj),
LockEntry.LOCK_READ);
addReaderInternal(reader);
return true;
} | Add a reader lock entry for transaction tx on object obj
to the persistent storage. |
public void removeReader(TransactionImpl tx, Object obj)
{
checkTimedOutLocks();
Identity oid = new Identity(obj, getBroker());
String oidString = oid.toString();
String txGuid = tx.getGUID();
removeReaderInternal(oidString, txGuid);
} | remove a reader lock entry for transaction tx on object obj
from the persistent storage. |
public void removeWriter(LockEntry writer)
{
checkTimedOutLocks();
String oidString = writer.getOidString();
ObjectLocks objectLocks = null;
synchronized (locktable)
{
objectLocks = (ObjectLocks) locktable.get(oidString);
}
if (objectLocks == null)
{
return;
}
else
{
/**
* MBAIRD, last one out, close the door and turn off the lights.
* if no locks (readers or writers) exist for this object, let's remove
* it from the locktable.
*/
synchronized (locktable)
{
Map readers = objectLocks.getReaders();
objectLocks.setWriter(null);
// no need to check if writer is null, we just set it.
if (readers.size() == 0)
{
locktable.remove(oidString);
}
}
}
} | remove a writer lock entry for transaction tx on object obj
from the persistent storage. |
public boolean upgradeLock(LockEntry reader)
{
checkTimedOutLocks();
String oidString = reader.getOidString();
ObjectLocks objectLocks = null;
synchronized (locktable)
{
objectLocks = (ObjectLocks) locktable.get(oidString);
}
if (objectLocks == null)
{
return false;
}
else
{
// add writer entry
LockEntry writer = new LockEntry(reader.getOidString(),
reader.getTransactionId(),
System.currentTimeMillis(),
reader.getIsolationLevel(),
LockEntry.LOCK_WRITE);
objectLocks.setWriter(writer);
// remove reader entry
objectLocks.getReaders().remove(reader.getTransactionId());
return true;
}
} | upgrade a reader lock entry for transaction tx on object obj
and write it to the persistent storage. |
public boolean setWriter(TransactionImpl tx, Object obj)
{
checkTimedOutLocks();
Identity oid = new Identity(obj, tx.getBroker());
LockEntry writer = new LockEntry(oid.toString(),
tx.getGUID(),
System.currentTimeMillis(),
LockStrategyFactory.getIsolationLevel(obj),
LockEntry.LOCK_WRITE);
String oidString = oid.toString();
setWriterInternal(writer, oidString);
return true;
} | generate a writer lock entry for transaction tx on object obj
and write it to the persistent storage. |
public boolean hasReadLock(TransactionImpl tx, Object obj)
{
checkTimedOutLocks();
Identity oid = new Identity(obj,getBroker());
String oidString = oid.toString();
String txGuid = tx.getGUID();
return hasReadLockInternal(oidString, txGuid);
} | check if there is a reader lock entry for transaction tx on object obj
in the persistent storage. |
private void removeTimedOutLocks(long timeout)
{
int count = 0;
long maxAge = System.currentTimeMillis() - timeout;
boolean breakFromLoop = false;
ObjectLocks temp = null;
synchronized (locktable)
{
Iterator it = locktable.values().iterator();
/**
* run this loop while:
* - we have more in the iterator
* - the breakFromLoop flag hasn't been set
* - we haven't removed more than the limit for this cleaning iteration.
*/
while (it.hasNext() && !breakFromLoop && (count <= MAX_LOCKS_TO_CLEAN))
{
temp = (ObjectLocks) it.next();
if (temp.getWriter() != null)
{
if (temp.getWriter().getTimestamp() < maxAge)
{
// writer has timed out, set it to null
temp.setWriter(null);
}
}
if (temp.getYoungestReader() < maxAge)
{
// all readers are older than timeout.
temp.getReaders().clear();
if (temp.getWriter() == null)
{
// all readers and writer are older than timeout,
// remove the objectLock from the iterator (which
// is backed by the map, so it will be removed.
it.remove();
}
}
else
{
// we need to walk each reader.
Iterator readerIt = temp.getReaders().values().iterator();
LockEntry readerLock = null;
while (readerIt.hasNext())
{
readerLock = (LockEntry) readerIt.next();
if (readerLock.getTimestamp() < maxAge)
{
// this read lock is old, remove it.
readerIt.remove();
}
}
}
count++;
}
}
} | removes all timed out lock entries from the persistent storage.
The timeout value can be set in the OJB properties file. |
public void run() {
boolean isActive = true;
//
// if interrupted (unlikely), end thread
//
try {
//
// loop until the AsyncAppender is closed.
//
while (isActive) {
LoggingEvent[] events = null;
//
// extract pending events while synchronized
// on buffer
//
synchronized (buffer) {
int bufferSize = buffer.size();
isActive = !isAsyncAppenderClosed(parent);
while ((bufferSize == 0) && isActive) {
buffer.wait();
bufferSize = buffer.size();
isActive = !isAsyncAppenderClosed(parent);
}
if (bufferSize > 0) {
events = new LoggingEvent[bufferSize + discardMap.size()];
buffer.toArray(events);
//
// add events due to buffer overflow
//
int index = bufferSize;
for (Iterator iter = discardMap.values().iterator(); iter.hasNext();) {
events[index++] = ((DiscardSummary) iter.next()).createEvent();
}
//
// clear buffer and discard map
//
buffer.clear();
discardMap.clear();
//
// allow blocked appends to continue
buffer.notifyAll();
}
}
//
// process events after lock on buffer is released.
//
if (events != null) {
for (int i = 0; i < events.length; i++) {
synchronized (appenders) {
LoggingEvent event = events[i];
@SuppressWarnings("unchecked")
Enumeration<Appender> allAppenders = appenders.getAllAppenders();
while (allAppenders.hasMoreElements()) {
Appender appender = allAppenders.nextElement();
//since we may update the appender layout we must sync so other threads won't use it by mistake
synchronized (appender) {
Layout originalLayout = appender.getLayout();
boolean appenderUpdated = udpateLayoutIfNeeded(appender, event);
appender.doAppend(event);
if (appenderUpdated) {
appender.setLayout(originalLayout);
}
}
}
}
}
}
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
} | {@inheritDoc} |
public void launchPlatform() {
logger.info("Launching Jadex Platform...");
platform = (IExternalAccess) Starter.createPlatform(null).get(
new ThreadSuspendable());
IServiceProvider container = (IServiceProvider) platform
.getServiceProvider();
cmsService = SServiceProvider.getService(container,
IComponentManagementService.class).get(new ThreadSuspendable());
messageService = SServiceProvider.getService(container,
IMessageService.class).get(new ThreadSuspendable());
createdAgents = new HashMap<String, IComponentIdentifier>();
} | Platform is launched and the external access of the message service and
the component management service (CMS) are saved |
public void createAgent(String agent_name, String path) {
IComponentIdentifier agent = cmsService.createComponent(agent_name,
path, null, null).get(new ThreadSuspendable());
createdAgents.put(agent_name, agent);
} | Creates a real agent in the platform
@param agent_name
The name that the agent is gonna have in the platform
@param path
The path of the description (xml) of the agent |
public IExternalAccess getAgentsExternalAccess(String agent_name) {
return cmsService.getExternalAccess(getAgentID(agent_name)).get(
new ThreadSuspendable());
} | This method searches in the Component Management Service, so given an
agent name returns its IExternalAccess
@param agent_name
The name of the agent in the platform
@return The IComponentIdentifier of the agent in the platform |
public void create(final DbProduct dbProduct) {
if(repositoryHandler.getProduct(dbProduct.getName()) != null){
throw new WebApplicationException(Response.status(Response.Status.CONFLICT).entity("Product already exist!").build());
}
repositoryHandler.store(dbProduct);
} | Creates a new Product in Grapes database
@param dbProduct DbProduct |
public DbProduct getProduct(final String name) {
final DbProduct dbProduct = repositoryHandler.getProduct(name);
if(dbProduct == null){
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.entity("Product " + name + " does not exist.").build());
}
return dbProduct;
} | Returns a product regarding its name
@param name String
@return DbProduct |
public void deleteProduct(final String name) {
final DbProduct dbProduct = getProduct(name);
repositoryHandler.deleteProduct(dbProduct.getName());
} | Deletes a product from the database
@param name String |
public void setProductModules(final String name, final List<String> moduleNames) {
final DbProduct dbProduct = getProduct(name);
dbProduct.setModules(moduleNames);
repositoryHandler.store(dbProduct);
} | Patches the product module names
@param name String
@param moduleNames List<String> |
@Override
public synchronized Object getBeliefValue(String agent_name, String belief_name,
Connector connector) {
return JadeAgentIntrospector.getInstance().dataToTest.get(agent_name).get(belief_name);
} | /* (non-Javadoc)
@see es.upm.dit.gsi.beast.platform.AgentIntrospector#getBeliefValue(java.lang.String, java.lang.String, es.upm.dit.gsi.beast.platform.Connector) |
@Override
public synchronized void setBeliefValue(String agent_name, String belief_name,
Object new_value, Connector connector) {
JadeAgentIntrospector.getInstance().dataToTest.get(agent_name).put(belief_name, new_value);
} | /* (non-Javadoc)
@see es.upm.dit.gsi.beast.platform.AgentIntrospector#setBeliefValue(java.lang.String, java.lang.String, java.lang.Object, es.upm.dit.gsi.beast.platform.Connector) |
@Override
public Object[] getAgentPlans(String agent_name, Connector connector) {
// Not supported in JADE
connector.getLogger().warning("Non suported method for Jade Platform. There is no plans in Jade platform.");
throw new java.lang.UnsupportedOperationException("Non suported method for Jade Platform. There is no extra properties.");
} | Non-supported in JadeAgentIntrospector |
protected void loadProfileIfNeeded()
{
final Object key = getProfileKey();
if (key != null)
{
final MetadataManager mm = MetadataManager.getInstance();
if (!key.equals(mm.getCurrentProfileKey()))
{
mm.loadProfile(key);
}
}
} | Reactivates metadata profile used when creating proxy, if needed.
Calls to this method should be guarded by checking
{@link #_perThreadDescriptorsEnabled} since the profile never
needs to be reloaded if not using pre-thread metadata changes. |
protected synchronized int loadSize() throws PersistenceBrokerException
{
PersistenceBroker broker = getBroker();
try
{
return broker.getCount(getQuery());
}
catch (Exception ex)
{
throw new PersistenceBrokerException(ex);
}
finally
{
releaseBroker(broker);
}
} | Determines the number of elements that the query would return. Override this
method if the size shall be determined in a specific way.
@return The number of elements |
protected Collection loadData() throws PersistenceBrokerException
{
PersistenceBroker broker = getBroker();
try
{
Collection result;
if (_data != null) // could be set by listener
{
result = _data;
}
else if (_size != 0)
{
// TODO: returned ManageableCollection should extend Collection to avoid
// this cast
result = (Collection) broker.getCollectionByQuery(getCollectionClass(), getQuery());
}
else
{
result = (Collection)getCollectionClass().newInstance();
}
return result;
}
catch (Exception ex)
{
throw new PersistenceBrokerException(ex);
}
finally
{
releaseBroker(broker);
}
} | Loads the data from the database. Override this method if the objects
shall be loaded in a specific way.
@return The loaded data |
protected void beforeLoading()
{
if (_listeners != null)
{
CollectionProxyListener listener;
if (_perThreadDescriptorsEnabled) {
loadProfileIfNeeded();
}
for (int idx = _listeners.size() - 1; idx >= 0; idx--)
{
listener = (CollectionProxyListener)_listeners.get(idx);
listener.beforeLoading(this);
}
}
} | Notifies all listeners that the data is about to be loaded. |
public void clear()
{
Class collClass = getCollectionClass();
// ECER: assure we notify all objects being removed,
// necessary for RemovalAwareCollections...
if (IRemovalAwareCollection.class.isAssignableFrom(collClass))
{
getData().clear();
}
else
{
Collection coll;
// BRJ: use an empty collection so isLoaded will return true
// for non RemovalAwareCollections only !!
try
{
coll = (Collection) collClass.newInstance();
}
catch (Exception e)
{
coll = new ArrayList();
}
setData(coll);
}
_size = 0;
} | Clears the proxy. A cleared proxy is defined as loaded
@see Collection#clear() |
protected synchronized void releaseBroker(PersistenceBroker broker)
{
/*
arminw:
only close the broker instance if we get
it from the PBF, do nothing if we obtain it from
PBThreadMapping
*/
if (broker != null && _needsClose)
{
_needsClose = false;
broker.close();
}
} | Release the broker instance. |
protected synchronized PersistenceBroker getBroker() throws PBFactoryException
{
/*
mkalen:
NB! The loadProfileIfNeeded must be called _before_ acquiring a broker below,
since some methods in PersistenceBrokerImpl will keep a local reference to
the descriptor repository that was active during broker construction/refresh
(not checking the repository beeing used on method invocation).
PersistenceBrokerImpl#getClassDescriptor(Class clazz) is such a method,
that will throw ClassNotPersistenceCapableException on the following scenario:
(All happens in one thread only):
t0: activate per-thread metadata changes
t1: load, register and activate profile A
t2: load object O1 witch collection proxy C to objects {O2} (C stores profile key K(A))
t3: close broker from t2
t4: load, register and activate profile B
t5: reference O1.getO2Collection, causing C loadData() to be invoked
t6: C calls getBroker
broker B is created and descriptorRepository is set to descriptors from profile B
t7: C calls loadProfileIfNeeded, re-activating profile A
t8: C calls B.getCollectionByQuery
t9: B gets callback (via QueryReferenceBroker) to getClassDescriptor
the local descriptorRepository from t6 is used!
=> We will now try to query for {O2} with profile B
(even though we re-activated profile A in t7)
=> ClassNotPersistenceCapableException
Keeping loadProfileIfNeeded() at the start of this method changes everything from t6:
t6: C calls loadProfileIfNeeded, re-activating profile A
t7: C calls getBroker,
broker B is created and descriptorRepository is set to descriptors from profile A
t8: C calls B.getCollectionByQuery
t9: B gets callback to getClassDescriptor,
the local descriptorRepository from t6 is used
=> We query for {O2} with profile A
=> All good :-)
*/
if (_perThreadDescriptorsEnabled)
{
loadProfileIfNeeded();
}
PersistenceBroker broker;
if (getBrokerKey() == null)
{
/*
arminw:
if no PBKey is set we throw an exception, because we don't
know which PB (connection) should be used.
*/
throw new OJBRuntimeException("Can't find associated PBKey. Need PBKey to obtain a valid" +
"PersistenceBroker instance from intern resources.");
}
// first try to use the current threaded broker to avoid blocking
broker = PersistenceBrokerThreadMapping.currentPersistenceBroker(getBrokerKey());
// current broker not found or was closed, create a intern new one
if (broker == null || broker.isClosed())
{
broker = PersistenceBrokerFactory.createPersistenceBroker(getBrokerKey());
// signal that we use a new internal obtained PB instance to read the
// data and that this instance have to be closed after use
_needsClose = true;
}
return broker;
} | Acquires a broker instance. If no PBKey is available a runtime exception will be thrown.
@return A broker instance |
public synchronized void addListener(CollectionProxyListener listener)
{
if (_listeners == null)
{
_listeners = new ArrayList();
}
// to avoid multi-add of same listener, do check
if(!_listeners.contains(listener))
{
_listeners.add(listener);
}
} | Adds a listener to this collection.
@param listener The listener to add |
public final boolean roll(final LoggingEvent loggingEvent) {
boolean rolled = false;
if (this.isMaxFileSizeExceeded()) {
super.roll(loggingEvent.getTimeStamp());
rolled = true;
}
return rolled;
} | /*
(non-Javadoc)
@see org.apache.log4j.appender.FileRollable#roll() |
public String getURN() throws InvalidRegistrationContentException {
if (parsedConfig==null || parsedConfig.urn==null || parsedConfig.urn.trim().isEmpty()) {
throw new InvalidRegistrationContentException("Invalid registration config - failed to read mediator URN");
}
return parsedConfig.urn;
} | Reads and returns the mediator URN from the JSON content.
@see #RegistrationConfig(String) |
public boolean deleteExisting(final File file) {
if (!file.exists()) {
return true;
}
boolean deleted = false;
if (file.canWrite()) {
deleted = file.delete();
} else {
LogLog.debug(file + " is not writeable for delete (retrying)");
}
if (!deleted) {
if (!file.exists()) {
deleted = true;
} else {
file.delete();
deleted = (!file.exists());
}
}
return deleted;
} | Delete with retry.
@param file
@return <tt>true</tt> if the file was successfully deleted. |
public boolean rename(final File from, final File to) {
boolean renamed = false;
if (this.isWriteable(from)) {
renamed = from.renameTo(to);
} else {
LogLog.debug(from + " is not writeable for rename (retrying)");
}
if (!renamed) {
from.renameTo(to);
renamed = (!from.exists());
}
return renamed;
} | Rename with retry.
@param from
@param to
@return <tt>true</tt> if the file was successfully renamed. |
public Transaction newTransaction()
{
if ((getCurrentDatabase() == null))
{
throw new DatabaseClosedException("Database is NULL, must have a DB in order to create a transaction");
}
TransactionImpl tx = new TransactionImpl(this);
try
{
getConfigurator().configure(tx);
}
catch (ConfigurationException e)
{
throw new ODMGRuntimeException("Error in configuration of TransactionImpl instance: " + e.getMessage());
}
return tx;
} | Create a <code>Transaction</code> object and associate it with the current thread.
@return The newly created <code>Transaction</code> instance.
@see Transaction |
public DList newDList()
{
if ((getCurrentDatabase() == null))
{
throw new DatabaseClosedException("Database is NULL, cannot create a DList with a null database.");
}
return (DList) DListFactory.singleton.createCollectionOrMap(getCurrentPBKey());
} | Create a new <code>DList</code> object.
@return The new <code>DList</code> object.
@see DList |
public DBag newDBag()
{
if ((getCurrentDatabase() == null))
{
throw new DatabaseClosedException("Database is NULL, cannot create a DBag with a null database.");
}
return (DBag) DBagFactory.singleton.createCollectionOrMap(getCurrentPBKey());
} | Create a new <code>DBag</code> object.
@return The new <code>DBag</code> object.
@see DBag |
public DSet newDSet()
{
if ((getCurrentDatabase() == null))
{
throw new DatabaseClosedException("Database is NULL, cannot create a DSet with a null database.");
}
return (DSet) DSetFactory.singleton.createCollectionOrMap(getCurrentPBKey());
} | Create a new <code>DSet</code> object.
@return The new <code>DSet</code> object.
@see DSet |
public DArray newDArray()
{
if ((getCurrentDatabase() == null))
{
throw new DatabaseClosedException("Database is NULL, cannot create a DArray with a null database.");
}
return (DArray) DArrayFactory.singleton.createCollectionOrMap(getCurrentPBKey());
} | Create a new <code>DArray</code> object.
@return The new <code>DArray</code> object.
@see DArray |
public DMap newDMap()
{
if ((getCurrentDatabase() == null))
{
throw new DatabaseClosedException("Database is NULL, cannot create a DMap with a null database.");
}
return (DMap) DMapFactory.singleton.createCollectionOrMap(getCurrentPBKey());
} | Create a new <code>DMap</code> object.
@return The new <code>DMap</code> object.
@see DMap |
public String getObjectId(Object obj)
{
Identity oid = null;
PersistenceBroker broker = null;
try
{
if (getCurrentDatabase() != null)
{
/**
* is there an open database we are calling getObjectId against? if yes, use it
*/
broker = PersistenceBrokerFactory.createPersistenceBroker(getCurrentDatabase().getPBKey());
}
else
{
log.warn("Can't find open database, try to use the default configuration");
/**
* otherwise, use default.
*/
broker = PersistenceBrokerFactory.defaultPersistenceBroker();
}
oid = broker.serviceIdentity().buildIdentity(obj);
}
finally
{
if(broker != null)
{
broker.close();
}
}
return new String(SerializationUtils.serialize(oid));
} | Get a <code>String</code> representation of the object's identifier.
OJB returns the serialized Identity of the object.
@param obj The object whose identifier is being accessed.
@return The object's identifier in the form of a String |
protected synchronized void registerOpenDatabase(DatabaseImpl newDB)
{
DatabaseImpl old_db = getCurrentDatabase();
if (old_db != null)
{
try
{
if (old_db.isOpen())
{
log.warn("## There is still an opened database, close old one ##");
old_db.close();
}
}
catch (Throwable t)
{
//ignore
}
}
if (log.isDebugEnabled()) log.debug("Set current database " + newDB + " PBKey was " + newDB.getPBKey());
setCurrentDatabase(newDB);
// usedDatabases.add(newDB.getPBKey());
} | Register opened database via the PBKey. |
public String toXML()
{
RepositoryTags tags = RepositoryTags.getInstance();
String eol = SystemUtils.LINE_SEPARATOR;
//opening tag + attributes
StringBuffer result = new StringBuffer( 1024 );
result.append( " <" );
result.append( tags.getTagById( INDEX_DESCRIPTOR ) );
result.append( " " );
// index name
result.append( tags.getAttribute( NAME, getName() ) );
result.append( " " );
// unique attribute
result.append( tags.getAttribute( UNIQUE, "" + isUnique() ) );
result.append( ">" );
result.append( eol );
// index columns
for( int i = 0; i < indexColumns.size(); i++ )
{
String l_name = ( String ) indexColumns.elementAt( i );
result.append( " " );
result.append( tags.getOpeningTagNonClosingById( INDEX_COLUMN ) );
result.append( " " );
result.append( tags.getAttribute( NAME, l_name ) );
result.append( " />" );
result.append( eol );
}
// closing tag
result.append( " " );
result.append( tags.getClosingTagById( INDEX_DESCRIPTOR ) );
result.append( " " );
result.append( eol );
return result.toString();
} | /*
@see XmlCapable#toXML() |
public String[] getAttributeNames()
{
Set keys = (attributeMap == null ? new HashSet() : attributeMap.keySet());
String[] result = new String[keys.size()];
keys.toArray(result);
return result;
} | Returns an array of the names of all atributes of this descriptor.
@return The list of attribute names (will not be <code>null</code>) |
public void storeMtoNImplementor(CollectionDescriptor cod, Object realObject, Object otherObj, Collection mnKeys)
{
ClassDescriptor cld = pb.getDescriptorRepository().getDescriptorFor(realObject.getClass());
ValueContainer[] pkValues = pb.serviceBrokerHelper().getKeyValues(cld, realObject);
String[] pkColumns = cod.getFksToThisClass();
ClassDescriptor otherCld = pb.getDescriptorRepository().getDescriptorFor(ProxyHelper.getRealClass(otherObj));
ValueContainer[] otherPkValues = pb.serviceBrokerHelper().getKeyValues(otherCld, otherObj);
String[] otherPkColumns = cod.getFksToItemClass();
String table = cod.getIndirectionTable();
MtoNBroker.Key key = new MtoNBroker.Key(otherPkValues);
if(mnKeys.contains(key))
{
return;
}
/*
fix for OJB-76, composite M & N keys that have some fields common
find the "shared" indirection table columns, values and remove these from m- or n- side
*/
for(int i = 0; i < otherPkColumns.length; i++)
{
int index = ArrayUtils.indexOf(pkColumns, otherPkColumns[i]);
if(index != -1)
{
// shared indirection table column found, remove this column from one side
pkColumns = (String[]) ArrayUtils.remove(pkColumns, index);
// remove duplicate value too
pkValues = (ValueContainer[]) ArrayUtils.remove(pkValues, index);
}
}
String[] cols = mergeColumns(pkColumns, otherPkColumns);
String insertStmt = pb.serviceSqlGenerator().getInsertMNStatement(table, pkColumns, otherPkColumns);
ValueContainer[] values = mergeContainer(pkValues, otherPkValues);
GenericObject gObj = new GenericObject(table, cols, values);
if(! tempObjects.contains(gObj))
{
pb.serviceJdbcAccess().executeUpdateSQL(insertStmt, cld, pkValues, otherPkValues);
tempObjects.add(gObj);
}
} | Stores new values of a M:N association in a indirection table.
@param cod The {@link org.apache.ojb.broker.metadata.CollectionDescriptor} for the m:n relation
@param realObject The real object
@param otherObj The referenced object
@param mnKeys The all {@link org.apache.ojb.broker.core.MtoNBroker.Key} matching the real object |
public List getMtoNImplementor(CollectionDescriptor cod, Object obj)
{
ResultSetAndStatement rs = null;
ArrayList result = new ArrayList();
ClassDescriptor cld = pb.getDescriptorRepository().getDescriptorFor(obj.getClass());
ValueContainer[] pkValues = pb.serviceBrokerHelper().getKeyValues(cld, obj);
String[] pkColumns = cod.getFksToThisClass();
String[] fkColumns = cod.getFksToItemClass();
String table = cod.getIndirectionTable();
String selectStmt = pb.serviceSqlGenerator().getSelectMNStatement(table, fkColumns, pkColumns);
ClassDescriptor itemCLD = pb.getDescriptorRepository().getDescriptorFor(cod.getItemClass());
Collection extents = pb.getDescriptorRepository().getAllConcreteSubclassDescriptors(itemCLD);
if(extents.size() > 0)
{
itemCLD = (ClassDescriptor) extents.iterator().next();
}
FieldDescriptor[] itemClassPKFields = itemCLD.getPkFields();
if(itemClassPKFields.length != fkColumns.length)
{
throw new PersistenceBrokerException("All pk fields of the element-class need to" +
" be declared in the indirection table. Element class is "
+ itemCLD.getClassNameOfObject() + " with " + itemClassPKFields.length + " pk-fields." +
" Declared 'fk-pointing-to-element-class' elements in collection-descriptor are"
+ fkColumns.length);
}
try
{
rs = pb.serviceJdbcAccess().executeSQL(selectStmt, cld, pkValues, Query.NOT_SCROLLABLE);
while(rs.m_rs.next())
{
ValueContainer[] row = new ValueContainer[fkColumns.length];
for(int i = 0; i < row.length; i++)
{
row[i] = new ValueContainer(rs.m_rs.getObject(i + 1), itemClassPKFields[i].getJdbcType());
}
result.add(new MtoNBroker.Key(row));
}
}
catch(PersistenceBrokerException e)
{
throw e;
}
catch(SQLException e)
{
throw new PersistenceBrokerSQLException(e);
}
finally
{
if(rs != null) rs.close();
}
return result;
} | get a Collection of Keys of already existing m:n rows
@param cod
@param obj
@return Collection of Key |
public void deleteMtoNImplementor(CollectionDescriptor cod, Object obj)
{
ClassDescriptor cld = pb.getDescriptorRepository().getDescriptorFor(obj.getClass());
ValueContainer[] pkValues = pb.serviceBrokerHelper().getKeyValues(cld, obj);
String[] pkColumns = cod.getFksToThisClass();
String table = cod.getIndirectionTable();
String deleteStmt = pb.serviceSqlGenerator().getDeleteMNStatement(table, pkColumns, null);
pb.serviceJdbcAccess().executeUpdateSQL(deleteStmt, cld, pkValues, null);
} | delete all rows from m:n table belonging to obj
@param cod
@param obj |
public void deleteMtoNImplementor(CollectionDescriptor cod, Object obj, Iterator collectionIterator, Collection mnKeys)
{
if(mnKeys.isEmpty() || collectionIterator == null)
{
return;
}
List workList = new ArrayList(mnKeys);
MtoNBroker.Key relatedObjKeys;
ClassDescriptor relatedCld = pb.getDescriptorRepository().getDescriptorFor(cod.getItemClass());
Object relatedObj;
// remove keys of relatedObject from the existing m:n rows in workList
while(collectionIterator.hasNext())
{
relatedObj = collectionIterator.next();
relatedObjKeys = new MtoNBroker.Key(pb.serviceBrokerHelper().getKeyValues(relatedCld, relatedObj, true));
workList.remove(relatedObjKeys);
}
// delete all remaining keys in workList
ClassDescriptor cld = pb.getDescriptorRepository().getDescriptorFor(obj.getClass());
ValueContainer[] pkValues = pb.serviceBrokerHelper().getKeyValues(cld, obj);
String[] pkColumns = cod.getFksToThisClass();
String[] fkColumns = cod.getFksToItemClass();
String table = cod.getIndirectionTable();
String deleteStmt;
ValueContainer[] fkValues;
Iterator iter = workList.iterator();
while(iter.hasNext())
{
fkValues = ((MtoNBroker.Key) iter.next()).m_containers;
deleteStmt = pb.serviceSqlGenerator().getDeleteMNStatement(table, pkColumns, fkColumns);
pb.serviceJdbcAccess().executeUpdateSQL(deleteStmt, cld, pkValues, fkValues);
}
} | deletes all rows from m:n table that are not used in relatedObjects
@param cod
@param obj
@param collectionIterator
@param mnKeys |
public void check(ModelDef modelDef, String checkLevel) throws ConstraintException
{
ensureReferencedKeys(modelDef, checkLevel);
checkReferenceForeignkeys(modelDef, checkLevel);
checkCollectionForeignkeys(modelDef, checkLevel);
checkKeyModifications(modelDef, checkLevel);
} | Checks the given model.
@param modelDef The model
@param checkLevel The amount of checks to perform
@exception ConstraintException If a constraint has been violated |
private void ensureReferencedKeys(ModelDef modelDef, String checkLevel) throws ConstraintException
{
ClassDescriptorDef classDef;
CollectionDescriptorDef collDef;
ReferenceDescriptorDef refDef;
for (Iterator it = modelDef.getClasses(); it.hasNext();)
{
classDef = (ClassDescriptorDef)it.next();
for (Iterator refIt = classDef.getReferences(); refIt.hasNext();)
{
refDef = (ReferenceDescriptorDef)refIt.next();
if (!refDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))
{
ensureReferencedPKs(modelDef, refDef);
}
}
for (Iterator collIt = classDef.getCollections(); collIt.hasNext();)
{
collDef = (CollectionDescriptorDef)collIt.next();
if (!collDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))
{
if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE))
{
ensureReferencedPKs(modelDef, collDef);
}
else
{
ensureReferencedFKs(modelDef, collDef);
}
}
}
}
} | Ensures that the primary/foreign keys referenced by references/collections are present
in the target type even if generate-table-info="false", by evaluating the subtypes
of the target type.
@param modelDef The model
@param checkLevel The current check level (this constraint is always checked)
@throws ConstraintException If there is an error with the keys of the subtypes or there
ain't any subtypes |
private void ensureReferencedPKs(ModelDef modelDef, ReferenceDescriptorDef refDef) throws ConstraintException
{
String targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF);
ClassDescriptorDef targetClassDef = modelDef.getClass(targetClassName);
ensurePKsFromHierarchy(targetClassDef);
} | Ensures that the primary keys required by the given reference are present in the referenced class.
@param modelDef The model
@param refDef The reference
@throws ConstraintException If there is a conflict between the primary keys |
private void ensureReferencedPKs(ModelDef modelDef, CollectionDescriptorDef collDef) throws ConstraintException
{
String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);
ClassDescriptorDef elementClassDef = modelDef.getClass(elementClassName);
String indirTable = collDef.getProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE);
String localKey = collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);
String remoteKey = collDef.getProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY);
boolean hasRemoteKey = remoteKey != null;
ArrayList fittingCollections = new ArrayList();
// we're checking for the fitting remote collection(s) and also
// use their foreignkey as remote-foreignkey in the original collection definition
for (Iterator it = elementClassDef.getAllExtentClasses(); it.hasNext();)
{
ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();
// find the collection in the element class that has the same indirection table
for (Iterator collIt = subTypeDef.getCollections(); collIt.hasNext();)
{
CollectionDescriptorDef curCollDef = (CollectionDescriptorDef)collIt.next();
if (indirTable.equals(curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE)) &&
(collDef != curCollDef) &&
(!hasRemoteKey || CommaListIterator.sameLists(remoteKey, curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY))) &&
(!curCollDef.hasProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY) ||
CommaListIterator.sameLists(localKey, curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY))))
{
fittingCollections.add(curCollDef);
}
}
}
if (!fittingCollections.isEmpty())
{
// if there is more than one, check that they match, i.e. that they all have the same foreignkeys
if (!hasRemoteKey && (fittingCollections.size() > 1))
{
CollectionDescriptorDef firstCollDef = (CollectionDescriptorDef)fittingCollections.get(0);
String foreignKey = firstCollDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);
for (int idx = 1; idx < fittingCollections.size(); idx++)
{
CollectionDescriptorDef curCollDef = (CollectionDescriptorDef)fittingCollections.get(idx);
if (!CommaListIterator.sameLists(foreignKey, curCollDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY)))
{
throw new ConstraintException("Cannot determine the element-side collection that corresponds to the collection "+
collDef.getName()+" in type "+collDef.getOwner().getName()+
" because there are at least two different collections that would fit."+
" Specifying remote-foreignkey in the original collection "+collDef.getName()+
" will perhaps help");
}
}
// store the found keys at the collections
collDef.setProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY, foreignKey);
for (int idx = 0; idx < fittingCollections.size(); idx++)
{
CollectionDescriptorDef curCollDef = (CollectionDescriptorDef)fittingCollections.get(idx);
curCollDef.setProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY, localKey);
}
}
}
// copy subclass pk fields into target class (if not already present)
ensurePKsFromHierarchy(elementClassDef);
} | Ensures that the primary keys required by the given collection with indirection table are present in
the element class.
@param modelDef The model
@param collDef The collection
@throws ConstraintException If there is a problem with the fitting collection (if any) or the primary keys |
private void ensureReferencedFKs(ModelDef modelDef, CollectionDescriptorDef collDef) throws ConstraintException
{
String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);
ClassDescriptorDef elementClassDef = modelDef.getClass(elementClassName);
String fkFieldNames = collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);
ArrayList missingFields = new ArrayList();
SequencedHashMap fkFields = new SequencedHashMap();
// first we gather all field names
for (CommaListIterator it = new CommaListIterator(fkFieldNames); it.hasNext();)
{
String fieldName = (String)it.next();
FieldDescriptorDef fieldDef = elementClassDef.getField(fieldName);
if (fieldDef == null)
{
missingFields.add(fieldName);
}
fkFields.put(fieldName, fieldDef);
}
// next we traverse all sub types and gather fields as we go
for (Iterator it = elementClassDef.getAllExtentClasses(); it.hasNext() && !missingFields.isEmpty();)
{
ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();
for (int idx = 0; idx < missingFields.size();)
{
FieldDescriptorDef fieldDef = subTypeDef.getField((String)missingFields.get(idx));
if (fieldDef != null)
{
fkFields.put(fieldDef.getName(), fieldDef);
missingFields.remove(idx);
}
else
{
idx++;
}
}
}
if (!missingFields.isEmpty())
{
throw new ConstraintException("Cannot find field "+missingFields.get(0).toString()+" in the hierarchy with root type "+
elementClassDef.getName()+" which is used as foreignkey in collection "+
collDef.getName()+" in "+collDef.getOwner().getName());
}
// copy the found fields into the element class
ensureFields(elementClassDef, fkFields.values());
} | Ensures that the foreign keys required by the given collection are present in the element class.
@param modelDef The model
@param collDef The collection
@throws ConstraintException If there is a problem with the foreign keys |
private void ensurePKsFromHierarchy(ClassDescriptorDef classDef) throws ConstraintException
{
SequencedHashMap pks = new SequencedHashMap();
for (Iterator it = classDef.getAllExtentClasses(); it.hasNext();)
{
ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();
ArrayList subPKs = subTypeDef.getPrimaryKeys();
// check against already present PKs
for (Iterator pkIt = subPKs.iterator(); pkIt.hasNext();)
{
FieldDescriptorDef fieldDef = (FieldDescriptorDef)pkIt.next();
FieldDescriptorDef foundPKDef = (FieldDescriptorDef)pks.get(fieldDef.getName());
if (foundPKDef != null)
{
if (!isEqual(fieldDef, foundPKDef))
{
throw new ConstraintException("Cannot pull up the declaration of the required primary key "+fieldDef.getName()+
" because its definitions in "+fieldDef.getOwner().getName()+" and "+
foundPKDef.getOwner().getName()+" differ");
}
}
else
{
pks.put(fieldDef.getName(), fieldDef);
}
}
}
ensureFields(classDef, pks.values());
} | Gathers the pk fields from the hierarchy of the given class, and copies them into the class.
@param classDef The root of the hierarchy
@throws ConstraintException If there is a conflict between the pk fields |
private void ensureFields(ClassDescriptorDef classDef, Collection fields) throws ConstraintException
{
boolean forceVirtual = !classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true);
for (Iterator it = fields.iterator(); it.hasNext();)
{
FieldDescriptorDef fieldDef = (FieldDescriptorDef)it.next();
// First we check whether this field is already present in the class
FieldDescriptorDef foundFieldDef = classDef.getField(fieldDef.getName());
if (foundFieldDef != null)
{
if (isEqual(fieldDef, foundFieldDef))
{
if (forceVirtual)
{
foundFieldDef.setProperty(PropertyHelper.OJB_PROPERTY_VIRTUAL_FIELD, "true");
}
continue;
}
else
{
throw new ConstraintException("Cannot pull up the declaration of the required field "+fieldDef.getName()+
" from type "+fieldDef.getOwner().getName()+" to basetype "+classDef.getName()+
" because there is already a different field of the same name");
}
}
// perhaps a reference or collection ?
if (classDef.getCollection(fieldDef.getName()) != null)
{
throw new ConstraintException("Cannot pull up the declaration of the required field "+fieldDef.getName()+
" from type "+fieldDef.getOwner().getName()+" to basetype "+classDef.getName()+
" because there is already a collection of the same name");
}
if (classDef.getReference(fieldDef.getName()) != null)
{
throw new ConstraintException("Cannot pull up the declaration of the required field "+fieldDef.getName()+
" from type "+fieldDef.getOwner().getName()+" to basetype "+classDef.getName()+
" because there is already a reference of the same name");
}
classDef.addFieldClone(fieldDef);
classDef.getField(fieldDef.getName()).setProperty(PropertyHelper.OJB_PROPERTY_VIRTUAL_FIELD, "true");
}
} | Ensures that the specified fields are present in the given class.
@param classDef The class to copy the fields into
@param fields The fields to copy
@throws ConstraintException If there is a conflict between the new fields and fields in the class |
private boolean isEqual(FieldDescriptorDef first, FieldDescriptorDef second)
{
return first.getName().equals(second.getName()) &&
first.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN).equals(second.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN)) &&
first.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE).equals(second.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));
} | Tests whether the two field descriptors are equal, i.e. have same name, same column
and same jdbc-type.
@param first The first field
@param second The second field
@return <code>true</code> if they are equal |
private void checkCollectionForeignkeys(ModelDef modelDef, String checkLevel) throws ConstraintException
{
if (CHECKLEVEL_NONE.equals(checkLevel))
{
return;
}
ClassDescriptorDef classDef;
CollectionDescriptorDef collDef;
for (Iterator it = modelDef.getClasses(); it.hasNext();)
{
classDef = (ClassDescriptorDef)it.next();
for (Iterator collIt = classDef.getCollections(); collIt.hasNext();)
{
collDef = (CollectionDescriptorDef)collIt.next();
if (!collDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))
{
if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE))
{
checkIndirectionTable(modelDef, collDef);
}
else
{
checkCollectionForeignkeys(modelDef, collDef);
}
}
}
}
} | Checks the foreignkeys of all collections in the model.
@param modelDef The model
@param checkLevel The current check level (this constraint is checked in basic and strict)
@exception ConstraintException If the value for foreignkey is invalid |
private void checkIndirectionTable(ModelDef modelDef, CollectionDescriptorDef collDef) throws ConstraintException
{
String foreignkey = collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);
if ((foreignkey == null) || (foreignkey.length() == 0))
{
throw new ConstraintException("The collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" has no foreignkeys");
}
// we know that the class is present because the collection constraints have been checked already
// TODO: we must check whether there is a collection at the other side; if the type does not map to a
// table then we have to check its subtypes
String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);
ClassDescriptorDef elementClass = modelDef.getClass(elementClassName);
CollectionDescriptorDef remoteCollDef = collDef.getRemoteCollection();
if (remoteCollDef == null)
{
// error if there is none and we don't have remote-foreignkey specified
if (!collDef.hasProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY))
{
throw new ConstraintException("The collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" must specify remote-foreignkeys as the class on the other side of the m:n association has no corresponding collection");
}
}
else
{
String remoteKeys2 = remoteCollDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);
if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY))
{
// check that the specified remote-foreignkey equals the remote foreignkey setting
String remoteKeys1 = collDef.getProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY);
if (!CommaListIterator.sameLists(remoteKeys1, remoteKeys2))
{
throw new ConstraintException("The remote-foreignkey property specified for collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" doesn't match the foreignkey property of the corresponding collection "+remoteCollDef.getName()+" in class "+elementClass.getName());
}
}
else
{
// ensure the remote-foreignkey setting
collDef.setProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY, remoteKeys2);
}
}
// issue a warning if the foreignkey and remote-foreignkey columns are the same (issue OJB-67)
String remoteForeignkey = collDef.getProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY);
if (CommaListIterator.sameLists(foreignkey, remoteForeignkey))
{
LogHelper.warn(true,
getClass(),
"checkIndirectionTable",
"The remote foreignkey ("+remoteForeignkey+") for the collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" is identical (ignoring case) to the foreign key ("+foreignkey+").");
}
// for torque we generate names for the m:n relation that are unique across inheritance
// but only if we don't have inherited collections
if (collDef.getOriginal() != null)
{
CollectionDescriptorDef origDef = (CollectionDescriptorDef)collDef.getOriginal();
CollectionDescriptorDef origRemoteDef = origDef.getRemoteCollection();
// we're removing any torque relation name properties from the base collection
origDef.setProperty(PropertyHelper.TORQUE_PROPERTY_RELATION_NAME, null);
origDef.setProperty(PropertyHelper.TORQUE_PROPERTY_INV_RELATION_NAME, null);
if (origRemoteDef != null)
{
origRemoteDef.setProperty(PropertyHelper.TORQUE_PROPERTY_RELATION_NAME, null);
origRemoteDef.setProperty(PropertyHelper.TORQUE_PROPERTY_INV_RELATION_NAME, null);
}
}
else if (!collDef.hasProperty(PropertyHelper.TORQUE_PROPERTY_RELATION_NAME))
{
if (remoteCollDef == null)
{
collDef.setProperty(PropertyHelper.TORQUE_PROPERTY_RELATION_NAME, collDef.getName());
collDef.setProperty(PropertyHelper.TORQUE_PROPERTY_INV_RELATION_NAME, "inverse "+collDef.getName());
}
else
{
String relName = collDef.getName()+"-"+remoteCollDef.getName();
collDef.setProperty(PropertyHelper.TORQUE_PROPERTY_RELATION_NAME, relName);
remoteCollDef.setProperty(PropertyHelper.TORQUE_PROPERTY_INV_RELATION_NAME, relName);
relName = remoteCollDef.getName()+"-"+collDef.getName();
collDef.setProperty(PropertyHelper.TORQUE_PROPERTY_INV_RELATION_NAME, relName);
remoteCollDef.setProperty(PropertyHelper.TORQUE_PROPERTY_RELATION_NAME, relName);
}
}
} | Checks the indirection-table and foreignkey of the collection. This constraint also ensures that
for the collections on both ends (if they exist), the remote-foreignkey property is set correctly.
@param modelDef The model
@param collDef The collection descriptor
@exception ConstraintException If the value for foreignkey is invalid |
private void checkCollectionForeignkeys(ModelDef modelDef, CollectionDescriptorDef collDef) throws ConstraintException
{
String foreignkey = collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);
if ((foreignkey == null) || (foreignkey.length() == 0))
{
throw new ConstraintException("The collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" has no foreignkeys");
}
String remoteForeignkey = collDef.getProperty(PropertyHelper.OJB_PROPERTY_REMOTE_FOREIGNKEY);
if ((remoteForeignkey != null) && (remoteForeignkey.length() > 0))
{
// warning because a remote-foreignkey was specified for a 1:n collection (issue OJB-67)
LogHelper.warn(true,
getClass(),
"checkCollectionForeignkeys",
"For the collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+", a remote foreignkey was specified though it is a 1:n, not a m:n collection");
}
ClassDescriptorDef ownerClass = (ClassDescriptorDef)collDef.getOwner();
ArrayList primFields = ownerClass.getPrimaryKeys();
String elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);
ArrayList queue = new ArrayList();
ClassDescriptorDef elementClass;
ArrayList keyFields;
FieldDescriptorDef keyField;
FieldDescriptorDef primField;
String primType;
String keyType;
// we know that the class is present because the collection constraints have been checked already
queue.add(modelDef.getClass(elementClassName));
while (!queue.isEmpty())
{
elementClass = (ClassDescriptorDef)queue.get(0);
queue.remove(0);
for (Iterator it = elementClass.getExtentClasses(); it.hasNext();)
{
queue.add(it.next());
}
if (!elementClass.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true))
{
continue;
}
try
{
keyFields = elementClass.getFields(foreignkey);
}
catch (NoSuchFieldException ex)
{
throw new ConstraintException("The collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" specifies a foreignkey "+ex.getMessage()+" that is not a persistent field in the element class (or its subclass) "+elementClass.getName());
}
if (primFields.size() != keyFields.size())
{
throw new ConstraintException("The number of foreignkeys ("+keyFields.size()+") of the collection "+collDef.getName()+" in class "+collDef.getOwner().getName()+" doesn't match the number of primarykeys ("+primFields.size()+") of its owner class "+ownerClass.getName());
}
for (int idx = 0; idx < keyFields.size(); idx++)
{
keyField = (FieldDescriptorDef)keyFields.get(idx);
if (keyField.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))
{
throw new ConstraintException("The collection "+collDef.getName()+" in class "+ownerClass.getName()+" uses the field "+keyField.getName()+" as foreignkey although this field is ignored in the element class (or its subclass) "+elementClass.getName());
}
}
// the jdbc types of the primary keys must match the jdbc types of the foreignkeys (in the correct order)
for (int idx = 0; idx < primFields.size(); idx++)
{
keyField = (FieldDescriptorDef)keyFields.get(idx);
if (keyField.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))
{
throw new ConstraintException("The collection "+collDef.getName()+" in class "+ownerClass.getName()+" uses the field "+keyField.getName()+" as foreignkey although this field is ignored in the element class (or its subclass) "+elementClass.getName());
}
primField = (FieldDescriptorDef)primFields.get(idx);
primType = primField.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE);
keyType = keyField.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE);
if (!primType.equals(keyType))
{
throw new ConstraintException("The jdbc-type of foreignkey "+keyField.getName()+" in the element class (or its subclass) "+elementClass.getName()+" used by the collection "+collDef.getName()+" in class "+ownerClass.getName()+" doesn't match the jdbc-type of the corresponding primarykey "+primField.getName());
}
}
}
} | Checks the foreignkeys of the collection.
@param modelDef The model
@param collDef The collection descriptor
@exception ConstraintException If the value for foreignkey is invalid |
private void checkReferenceForeignkeys(ModelDef modelDef, String checkLevel) throws ConstraintException
{
if (CHECKLEVEL_NONE.equals(checkLevel))
{
return;
}
ClassDescriptorDef classDef;
ReferenceDescriptorDef refDef;
for (Iterator it = modelDef.getClasses(); it.hasNext();)
{
classDef = (ClassDescriptorDef)it.next();
for (Iterator refIt = classDef.getReferences(); refIt.hasNext();)
{
refDef = (ReferenceDescriptorDef)refIt.next();
if (!refDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))
{
checkReferenceForeignkeys(modelDef, refDef);
}
}
}
} | Checks the foreignkeys of all references in the model.
@param modelDef The model
@param checkLevel The current check level (this constraint is checked in basic and strict)
@exception ConstraintException If the value for foreignkey is invalid |
private void checkReferenceForeignkeys(ModelDef modelDef, ReferenceDescriptorDef refDef) throws ConstraintException
{
String foreignkey = refDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);
if ((foreignkey == null) || (foreignkey.length() == 0))
{
throw new ConstraintException("The reference "+refDef.getName()+" in class "+refDef.getOwner().getName()+" has no foreignkeys");
}
// we know that the class is present because the reference constraints have been checked already
ClassDescriptorDef ownerClass = (ClassDescriptorDef)refDef.getOwner();
ArrayList keyFields;
FieldDescriptorDef keyField;
try
{
keyFields = ownerClass.getFields(foreignkey);
}
catch (NoSuchFieldException ex)
{
throw new ConstraintException("The reference "+refDef.getName()+" in class "+refDef.getOwner().getName()+" specifies a foreignkey "+ex.getMessage()+" that is not a persistent field in its owner class "+ownerClass.getName());
}
for (int idx = 0; idx < keyFields.size(); idx++)
{
keyField = (FieldDescriptorDef)keyFields.get(idx);
if (keyField.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))
{
throw new ConstraintException("The reference "+refDef.getName()+" in class "+ownerClass.getName()+" uses the field "+keyField.getName()+" as foreignkey although this field is ignored in this class");
}
}
// for the referenced class and any subtype that is instantiable (i.e. not an interface or abstract class)
// there must be the same number of primary keys and the jdbc types of the primary keys must
// match the jdbc types of the foreignkeys (in the correct order)
String targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF);
ArrayList queue = new ArrayList();
ClassDescriptorDef referencedClass;
ArrayList primFields;
FieldDescriptorDef primField;
String primType;
String keyType;
queue.add(modelDef.getClass(targetClassName));
while (!queue.isEmpty())
{
referencedClass = (ClassDescriptorDef)queue.get(0);
queue.remove(0);
for (Iterator it = referencedClass.getExtentClasses(); it.hasNext();)
{
queue.add(it.next());
}
if (!referencedClass.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true))
{
continue;
}
primFields = referencedClass.getPrimaryKeys();
if (primFields.size() != keyFields.size())
{
throw new ConstraintException("The number of foreignkeys ("+keyFields.size()+") of the reference "+refDef.getName()+" in class "+refDef.getOwner().getName()+" doesn't match the number of primarykeys ("+primFields.size()+") of the referenced class (or its subclass) "+referencedClass.getName());
}
for (int idx = 0; idx < primFields.size(); idx++)
{
keyField = (FieldDescriptorDef)keyFields.get(idx);
primField = (FieldDescriptorDef)primFields.get(idx);
primType = primField.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE);
keyType = keyField.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE);
if (!primType.equals(keyType))
{
throw new ConstraintException("The jdbc-type of foreignkey "+keyField.getName()+" of the reference "+refDef.getName()+" in class "+refDef.getOwner().getName()+" doesn't match the jdbc-type of the corresponding primarykey "+primField.getName()+" of the referenced class (or its subclass) "+referencedClass.getName());
}
}
}
} | Checks the foreignkeys of a reference.
@param modelDef The model
@param refDef The reference descriptor
@exception ConstraintException If the value for foreignkey is invalid |
private void checkKeyModifications(ModelDef modelDef, String checkLevel) throws ConstraintException
{
if (CHECKLEVEL_NONE.equals(checkLevel))
{
return;
}
ClassDescriptorDef classDef;
FieldDescriptorDef fieldDef;
// we check for every inherited field
for (Iterator classIt = modelDef.getClasses(); classIt.hasNext();)
{
classDef = (ClassDescriptorDef)classIt.next();
for (Iterator fieldIt = classDef.getFields(); fieldIt.hasNext();)
{
fieldDef = (FieldDescriptorDef)fieldIt.next();
if (fieldDef.isInherited())
{
checkKeyModifications(modelDef, fieldDef);
}
}
}
} | Checks the modifications of fields used as foreignkeys in references/collections or the corresponding primarykeys,
e.g. that the jdbc-type is not changed etc.
@param modelDef The model to check
@param checkLevel The current check level (this constraint is checked in basic and strict)
@throws ConstraintException If such a field has invalid modifications |
private void checkKeyModifications(ModelDef modelDef, FieldDescriptorDef keyDef) throws ConstraintException
{
// we check the field if it changes the primarykey-status or the jdbc-type
FieldDescriptorDef baseFieldDef = (FieldDescriptorDef)keyDef.getOriginal();
boolean isIgnored = keyDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false);
boolean changesJdbcType = !baseFieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE).equals(keyDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));
boolean changesPrimary = baseFieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false) !=
keyDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false) ;
if (isIgnored || changesJdbcType || changesPrimary)
{
FeatureDescriptorDef usingFeature = null;
do
{
usingFeature = usedByReference(modelDef, baseFieldDef);
if (usingFeature != null)
{
if (isIgnored)
{
throw new ConstraintException("Cannot ignore field "+keyDef.getName()+" in class "+keyDef.getOwner().getName()+
" because it is used in class "+baseFieldDef.getOwner().getName()+
" by the reference "+usingFeature.getName()+" from class "+
usingFeature.getOwner().getName());
}
else if (changesJdbcType)
{
throw new ConstraintException("Modification of the jdbc-type for the field "+keyDef.getName()+" in class "+
keyDef.getOwner().getName()+" is not allowed because it is used in class "+
baseFieldDef.getOwner().getName()+" by the reference "+usingFeature.getName()+
" from class "+usingFeature.getOwner().getName());
}
else
{
throw new ConstraintException("Cannot change the primarykey status of field "+keyDef.getName()+" in class "+
keyDef.getOwner().getName()+" as primarykeys are used in class "+
baseFieldDef.getOwner().getName()+" by the reference "+usingFeature.getName()+
" from class "+usingFeature.getOwner().getName());
}
}
usingFeature = usedByCollection(modelDef, baseFieldDef, changesPrimary);
if (usingFeature != null)
{
if (isIgnored)
{
throw new ConstraintException("Cannot ignore field "+keyDef.getName()+" in class "+keyDef.getOwner().getName()+
" because it is used in class "+baseFieldDef.getOwner().getName()+
" as a foreignkey of the collection "+usingFeature.getName()+" from class "+
usingFeature.getOwner().getName());
}
else if (changesJdbcType)
{
throw new ConstraintException("Modification of the jdbc-type for the field "+keyDef.getName()+" in class "+
keyDef.getOwner().getName()+" is not allowed because it is used in class "+
baseFieldDef.getOwner().getName()+" as a foreignkey of the collecton "+
usingFeature.getName()+" from class "+usingFeature.getOwner().getName());
}
else
{
throw new ConstraintException("Cannot change the primarykey status of field "+keyDef.getName()+" in class "+
keyDef.getOwner().getName()+" as primarykeys are used in class "+
baseFieldDef.getOwner().getName()+" by the collection "+usingFeature.getName()+
" from class "+usingFeature.getOwner().getName());
}
}
baseFieldDef = (FieldDescriptorDef)baseFieldDef.getOriginal();
}
while (baseFieldDef != null);
}
} | Checks the modifications of the given inherited field if it is used as a foreignkey in a
reference/collection or as the corresponding primarykey, e.g. that the jdbc-type is not changed etc.
@param modelDef The model to check
@throws ConstraintException If the field has invalid modifications |
private CollectionDescriptorDef usedByCollection(ModelDef modelDef, FieldDescriptorDef fieldDef, boolean elementClassSuffices)
{
ClassDescriptorDef ownerClass = (ClassDescriptorDef)fieldDef.getOwner();
String ownerClassName = ownerClass.getQualifiedName();
String name = fieldDef.getName();
ClassDescriptorDef classDef;
CollectionDescriptorDef collDef;
String elementClassName;
for (Iterator classIt = modelDef.getClasses(); classIt.hasNext();)
{
classDef = (ClassDescriptorDef)classIt.next();
for (Iterator collIt = classDef.getCollections(); collIt.hasNext();)
{
collDef = (CollectionDescriptorDef)collIt.next();
elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF).replace('$', '.');
// if the owner class of the field is the element class of a normal collection
// and the field is a foreignkey of this collection
if (ownerClassName.equals(elementClassName))
{
if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE))
{
if (elementClassSuffices)
{
return collDef;
}
}
else if (new CommaListIterator(collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY)).contains(name))
{
// if the field is a foreignkey of this normal 1:n collection
return collDef;
}
}
}
}
return null;
} | Checks whether the given field definition is used as a remote-foreignkey in an m:n
association where the class owning the field has no collection for the association.
@param modelDef The model
@param fieldDef The current field descriptor def
@param elementClassSuffices Whether it suffices that the owner class of the field is an
element class of a collection (for primary key tests)
@return The collection that uses the field or <code>null</code> if the field is not
used in this way |
private ReferenceDescriptorDef usedByReference(ModelDef modelDef, FieldDescriptorDef fieldDef)
{
String ownerClassName = ((ClassDescriptorDef)fieldDef.getOwner()).getQualifiedName();
ClassDescriptorDef classDef;
ReferenceDescriptorDef refDef;
String targetClassName;
// only relevant for primarykey fields
if (PropertyHelper.toBoolean(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY), false))
{
for (Iterator classIt = modelDef.getClasses(); classIt.hasNext();)
{
classDef = (ClassDescriptorDef)classIt.next();
for (Iterator refIt = classDef.getReferences(); refIt.hasNext();)
{
refDef = (ReferenceDescriptorDef)refIt.next();
targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF).replace('$', '.');
if (ownerClassName.equals(targetClassName))
{
// the field is a primary key of the class referenced by this reference descriptor
return refDef;
}
}
}
}
return null;
} | Checks whether the given field definition is used as the primary key of a class referenced by
a reference.
@param modelDef The model
@param fieldDef The current field descriptor def
@return The reference that uses the field or <code>null</code> if the field is not used in this way |
public Object[] getForeignKeyValues(Object obj, ClassDescriptor mif)
throws PersistenceBrokerException
{
FieldDescriptor[] fks = getForeignKeyFieldDescriptors(mif);
// materialize object only if FK fields are declared
if(fks.length > 0) obj = ProxyHelper.getRealObject(obj);
Object[] result = new Object[fks.length];
for (int i = 0; i < result.length; i++)
{
FieldDescriptor fmd = fks[i];
PersistentField f = fmd.getPersistentField();
// BRJ: do NOT convert.
// conversion is done when binding the sql-statement
//
// FieldConversion fc = fmd.getFieldConversion();
// Object val = fc.javaToSql(f.get(obj));
result[i] = f.get(obj);
}
return result;
} | Returns an Object array of all FK field values of the specified object.
If the specified object is an unmaterialized Proxy, it will be materialized
to read the FK values.
@throws MetadataException if an error occours while accessing ForeingKey values on obj |
public void addForeignKeyField(int newId)
{
if (m_ForeignKeyFields == null)
{
m_ForeignKeyFields = new Vector();
}
m_ForeignKeyFields.add(new Integer(newId));
} | add a foreign key field ID |
public void addForeignKeyField(String newField)
{
if (m_ForeignKeyFields == null)
{
m_ForeignKeyFields = new Vector();
}
m_ForeignKeyFields.add(newField);
} | add a foreign key field |
public String toXML()
{
RepositoryTags tags = RepositoryTags.getInstance();
String eol = System.getProperty( "line.separator" );
// opening tag
StringBuffer result = new StringBuffer( 1024 );
result.append( " " );
result.append( tags.getOpeningTagNonClosingById( REFERENCE_DESCRIPTOR ) );
result.append( eol );
// attributes
// name
String name = this.getAttributeName();
if( name == null )
{
name = RepositoryElements.TAG_SUPER;
}
result.append( " " );
result.append( tags.getAttribute( FIELD_NAME, name ) );
result.append( eol );
// class-ref
result.append( " " );
result.append( tags.getAttribute( REFERENCED_CLASS, this.getItemClassName() ) );
result.append( eol );
// proxyReference is optional
if( isLazy() )
{
result.append( " " );
result.append( tags.getAttribute( PROXY_REFERENCE, "true" ) );
result.append( eol );
result.append( " " );
result.append( tags.getAttribute( PROXY_PREFETCHING_LIMIT, "" + this.getProxyPrefetchingLimit() ) );
result.append( eol );
}
//reference refresh is optional, disabled by default
if( isRefresh() )
{
result.append( " " );
result.append( tags.getAttribute( REFRESH, "true" ) );
result.append( eol );
}
//auto retrieve
result.append( " " );
result.append( tags.getAttribute( AUTO_RETRIEVE, "" + getCascadeRetrieve() ) );
result.append( eol );
//auto update
result.append( " " );
result.append( tags.getAttribute( AUTO_UPDATE, getCascadeAsString( getCascadingStore() ) ) );
result.append( eol );
//auto delete
result.append( " " );
result.append( tags.getAttribute( AUTO_DELETE, getCascadeAsString( getCascadingDelete() ) ) );
result.append( eol );
//otm-dependent is optional, disabled by default
if( getOtmDependent() )
{
result.append( " " );
result.append( tags.getAttribute( OTM_DEPENDENT, "true" ) );
result.append( eol );
}
// close opening tag
result.append( " >" );
result.append( eol );
// elements
// write foreignkey elements
for( int i = 0; i < getForeignKeyFields().size(); i++ )
{
Object obj = getForeignKeyFields().get( i );
if( obj instanceof Integer )
{
String fkId = obj.toString();
result.append( " " );
result.append( tags.getOpeningTagNonClosingById( FOREIGN_KEY ) );
result.append( " " );
result.append( tags.getAttribute( FIELD_ID_REF, fkId ) );
result.append( "/>" );
result.append( eol );
}
else
{
String fk = ( String ) obj;
result.append( " " );
result.append( tags.getOpeningTagNonClosingById( FOREIGN_KEY ) );
result.append( " " );
result.append( tags.getAttribute( FIELD_REF, fk ) );
result.append( "/>" );
result.append( eol );
}
}
// closing tag
result.append( " " );
result.append( tags.getClosingTagById( REFERENCE_DESCRIPTOR ) );
result.append( eol );
return result.toString();
} | /*
@see XmlCapable#toXML() |
final String backupTimeAsString(final String logFilename, final File baseFile) {
final Pattern pattern = this.backupCountPattern(baseFile);
final Matcher matcher = pattern.matcher(logFilename);
if (matcher.find()) {
return matcher.group(2); // date formatted part is group 2
}
return "";
} | TODO Delete and change this method's regex test for backupTimeAndCount |
private void initComponents()//GEN-BEGIN:initComponents
{
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
lblEnabled = new javax.swing.JLabel();
cbEnabled = new javax.swing.JCheckBox();
lblDisabledByParent = new javax.swing.JLabel();
cbDisabledByParent = new javax.swing.JCheckBox();
jLabel4 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
lblColumnName = new javax.swing.JLabel();
tfColumnName = new javax.swing.JTextField();
lblJavaFieldName = new javax.swing.JLabel();
tfJavaFieldName = new javax.swing.JTextField();
lblSQLTypeName = new javax.swing.JLabel();
tfSQLTypeName = new javax.swing.JTextField();
lblSQLType = new javax.swing.JLabel();
cmbSQLType = new javax.swing.JComboBox();
lblJavaType = new javax.swing.JLabel();
cmbJavaType = new javax.swing.JComboBox();
setLayout(new java.awt.GridBagLayout());
addComponentListener(new java.awt.event.ComponentAdapter()
{
public void componentShown(java.awt.event.ComponentEvent evt)
{
formComponentShown(evt);
}
public void componentHidden(java.awt.event.ComponentEvent evt)
{
formComponentHidden(evt);
}
});
addHierarchyListener(new java.awt.event.HierarchyListener()
{
public void hierarchyChanged(java.awt.event.HierarchyEvent evt)
{
formHierarchyChanged(evt);
}
});
jPanel1.setLayout(new java.awt.GridLayout(8, 2));
lblEnabled.setDisplayedMnemonic('e');
lblEnabled.setText("enabled:");
jPanel1.add(lblEnabled);
cbEnabled.setMnemonic('e');
cbEnabled.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
cbEnabledActionPerformed(evt);
}
});
jPanel1.add(cbEnabled);
lblDisabledByParent.setText("disabled by Parent:");
jPanel1.add(lblDisabledByParent);
cbDisabledByParent.setMnemonic('d');
cbDisabledByParent.setEnabled(false);
jPanel1.add(cbDisabledByParent);
jPanel1.add(jLabel4);
jPanel1.add(jLabel3);
lblColumnName.setLabelFor(tfColumnName);
lblColumnName.setText("Column Name:");
jPanel1.add(lblColumnName);
tfColumnName.setEditable(false);
tfColumnName.setText("jTextField1");
tfColumnName.setBorder(null);
tfColumnName.setDisabledTextColor((java.awt.Color) javax.swing.UIManager.getDefaults().get("windowText"));
tfColumnName.setEnabled(false);
jPanel1.add(tfColumnName);
lblJavaFieldName.setLabelFor(tfColumnName);
lblJavaFieldName.setText("Java Field Name:");
jPanel1.add(lblJavaFieldName);
tfJavaFieldName.setText("jTextField1");
tfJavaFieldName.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
tfJavaFieldNameActionPerformed(evt);
}
});
tfJavaFieldName.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusLost(java.awt.event.FocusEvent evt)
{
tfJavaFieldNameFocusLost(evt);
}
});
tfJavaFieldName.addKeyListener(new java.awt.event.KeyAdapter()
{
public void keyTyped(java.awt.event.KeyEvent evt)
{
tfJavaFieldNameKeyTyped(evt);
}
});
jPanel1.add(tfJavaFieldName);
lblSQLTypeName.setLabelFor(tfColumnName);
lblSQLTypeName.setText("SQL Type Name:");
jPanel1.add(lblSQLTypeName);
tfSQLTypeName.setEditable(false);
tfSQLTypeName.setText("jTextField1");
tfSQLTypeName.setBorder(null);
tfSQLTypeName.setDisabledTextColor((java.awt.Color) javax.swing.UIManager.getDefaults().get("windowText"));
tfSQLTypeName.setEnabled(false);
jPanel1.add(tfSQLTypeName);
lblSQLType.setText("Java SQL Type:");
jPanel1.add(lblSQLType);
cmbSQLType.setModel(new javax.swing.DefaultComboBoxModel(Utilities.vJDBCTypeNames));
cmbSQLType.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
cmbSQLTypeActionPerformed(evt);
}
});
jPanel1.add(cmbSQLType);
lblJavaType.setText("Java Type:");
jPanel1.add(lblJavaType);
cmbJavaType.setEditable(true);
cmbJavaType.setModel( new org.apache.ojb.tools.swing.SortingComboBoxModel(Utilities.vJavaTypes)
/*new javax.swing.DefaultComboBoxModel(at.citec.ojb.schemegenerator.Utilities.vJavaTypes)*/);
cmbJavaType.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
cmbJavaTypeActionPerformed(evt);
}
});
jPanel1.add(cmbJavaType);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
} | This method is called from within the constructor to
initialize the form.
WARNING: Do NOT modify this code. The content of this method is
always regenerated by the Form Editor. |
private void tfJavaFieldNameKeyTyped(java.awt.event.KeyEvent evt)//GEN-FIRST:event_tfJavaFieldNameKeyTyped
{//GEN-HEADEREND:event_tfJavaFieldNameKeyTyped
// Revert to original value if ESC is pressed.
if (evt.getKeyChar() == KeyEvent.VK_ESCAPE)
{
this.tfJavaFieldName.setText(aColumn.getJavaFieldName());
}
} | GEN-END:initComponents |
private void tfJavaFieldNameFocusLost(java.awt.event.FocusEvent evt)//GEN-FIRST:event_tfJavaFieldNameFocusLost
{//GEN-HEADEREND:event_tfJavaFieldNameFocusLost
// Commit the new value to the column if the focus is lost
aColumn.setJavaFieldName(tfJavaFieldName.getText());
} | GEN-LAST:event_tfJavaFieldNameKeyTyped |
private void tfJavaFieldNameActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_tfJavaFieldNameActionPerformed
{//GEN-HEADEREND:event_tfJavaFieldNameActionPerformed
// Commit value to column object if ENTER is pressed
aColumn.setJavaFieldName(tfJavaFieldName.getText());
} | GEN-LAST:event_tfJavaFieldNameFocusLost |
private void cmbJavaTypeActionPerformed (java.awt.event.ActionEvent evt)//GEN-FIRST:event_cmbJavaTypeActionPerformed
{//GEN-HEADEREND:event_cmbJavaTypeActionPerformed
// Add your handling code here:
aColumn.setJavaFieldType(cmbJavaType.getSelectedItem().toString());
if (cmbJavaType.getModel() instanceof org.apache.ojb.tools.swing.SortingComboBoxModel)
{
org.apache.ojb.tools.swing.SortingComboBoxModel cmbModel =
(org.apache.ojb.tools.swing.SortingComboBoxModel)this.cmbJavaType.getModel();
if (cmbModel.getIndexOf(cmbJavaType.getSelectedItem()) == -1 )
cmbJavaType.addItem(cmbJavaType.getSelectedItem());
}
else if (cmbJavaType.getModel() instanceof javax.swing.DefaultComboBoxModel)
{
javax.swing.DefaultComboBoxModel cmbModel =
(javax.swing.DefaultComboBoxModel)this.cmbJavaType.getModel();
if (cmbModel.getIndexOf(cmbJavaType.getSelectedItem()) == -1 )
cmbJavaType.addItem(cmbJavaType.getSelectedItem());
}
} | GEN-LAST:event_tfJavaFieldNameActionPerformed |
private void cmbSQLTypeActionPerformed (java.awt.event.ActionEvent evt)//GEN-FIRST:event_cmbSQLTypeActionPerformed
{//GEN-HEADEREND:event_cmbSQLTypeActionPerformed
// Add your handling code here:
// System.out.println(this.jComboBox1.getSelectedItem());
aColumn.setColumnType(this.cmbSQLType.getSelectedItem().toString());
} | GEN-LAST:event_cbEnabledActionPerformed |
public void setModel (PropertySheetModel pm)
{
if (pm instanceof org.apache.ojb.tools.mapping.reversedb.DBColumn)
{
this.aColumn = (org.apache.ojb.tools.mapping.reversedb.DBColumn)pm;
this.readValuesFromColumn();
}
else
throw new IllegalArgumentException();
} | GEN-LAST:event_formComponentShown |
public boolean isLoggable(final Level level) {
if (logger.isTraceEnabled()) {
return level.intValue() >= Level.FINEST.intValue();
} else if (logger.isDebugEnabled()) {
return level.intValue() >= Level.FINE.intValue();
} else if (logger.isInfoEnabled()) {
return level.intValue() >= Level.INFO.intValue();
} else if (logger.isWarnEnabled()) {
return level.intValue() >= Level.WARNING.intValue();
} else if (logger.isErrorEnabled()) {
return level.intValue() >= Level.SEVERE.intValue();
} else {
return false;
}
} | Returns {@code true} if the specified level is loggable. |
public boolean tryLock(Object ownerId, Object resourceId, int targetLockLevel, boolean reentrant, Object isolationId)
{
timeoutCheck(ownerId);
OJBLock lock = atomicGetOrCreateLock(resourceId, isolationId);
boolean acquired = lock.tryLock(ownerId, targetLockLevel,
reentrant ? GenericLock.COMPATIBILITY_REENTRANT : GenericLock.COMPATIBILITY_NONE,
false);
if(acquired)
{
addOwner(ownerId, lock);
}
return acquired;
} | Tries to acquire a lock on a resource. <br>
<br>
This method does not block, but immediatly returns. If a lock is not
available <code>false</code> will be returned.
@param ownerId a unique id identifying the entity that wants to acquire this
lock
@param resourceId the resource to get the level for
@param targetLockLevel the lock level to acquire
@param reentrant <code>true</code> if this request shall not be influenced by
other locks held by the same owner
@param isolationId the isolation level identity key. See {@link CommonsOJBLockManager}.
@return <code>true</code> if the lock has been acquired, <code>false</code> otherwise |
public OJBLock atomicGetOrCreateLock(Object resourceId, Object isolationId)
{
synchronized(globalLocks)
{
MultiLevelLock lock = getLock(resourceId);
if(lock == null)
{
lock = createLock(resourceId, isolationId);
}
return (OJBLock) lock;
}
} | Either gets an existing lock on the specified resource or creates one if none exists.
This methods guarantees to do this atomically.
@param resourceId the resource to get or create the lock on
@param isolationId the isolation level identity key. See {@link CommonsOJBLockManager}.
@return the lock for the specified resource |
public OJBLock createIsolationLevel(Object resourceId, Object isolationId, LoggerFacade logger)
{
OJBLock result = null;
switch(((Integer) isolationId).intValue())
{
case LockManager.IL_READ_UNCOMMITTED:
result = new ReadUncommittedLock(resourceId, logger);
break;
case LockManager.IL_READ_COMMITTED:
result = new ReadCommitedLock(resourceId, logger);
break;
case LockManager.IL_REPEATABLE_READ:
result = new RepeadableReadsLock(resourceId, logger);
break;
case LockManager.IL_SERIALIZABLE:
result = new SerializeableLock(resourceId, logger);
break;
case LockManager.IL_OPTIMISTIC:
throw new LockRuntimeException("Optimistic locking must be handled on top of this class");
default:
throw new LockRuntimeException("Unknown lock isolation level specified");
}
return result;
} | Creates {@link org.apache.commons.transaction.locking.GenericLock} based
{@link org.apache.commons.transaction.locking.MultiLevelLock2} instances
dependend on the specified isolation identity object. |
int mapLockLevelDependendOnIsolationLevel(Integer isolationId, int lockLevel)
{
int result = 0;
switch(isolationId.intValue())
{
case LockManager.IL_READ_UNCOMMITTED:
result = ReadUncommittedLock.mapLockLevel(lockLevel);
break;
case LockManager.IL_READ_COMMITTED:
result = ReadCommitedLock.mapLockLevel(lockLevel);
break;
case LockManager.IL_REPEATABLE_READ:
result = RepeadableReadsLock.mapLockLevel(lockLevel);
break;
case LockManager.IL_SERIALIZABLE:
result = SerializeableLock.mapLockLevel(lockLevel);
break;
case LockManager.IL_OPTIMISTIC:
throw new LockRuntimeException("Optimistic locking must be handled on top of this class");
default:
throw new LockRuntimeException("Unknown lock isolation level specified");
}
return result;
} | Helper method to map the specified common lock level (e.g like
{@link #COMMON_READ_LOCK}, {@link #COMMON_UPGRADE_LOCK, ...}) based
on the isolation level to the internal used lock level value by the
{@link org.apache.commons.transaction.locking.MultiLevelLock2} implementation.
@param isolationId
@param lockLevel
@return |
public void initSize(Rectangle rectangle) {
template = writer.getDirectContent().createTemplate(rectangle.getWidth(), rectangle.getHeight());
} | Initializes context size.
@param rectangle rectangle |
public Rectangle getTextSize(String text, Font font) {
template.saveState();
// get the font
DefaultFontMapper mapper = new DefaultFontMapper();
BaseFont bf = mapper.awtToPdf(font);
template.setFontAndSize(bf, font.getSize());
// calculate text width and height
float textWidth = template.getEffectiveStringWidth(text, false);
float ascent = bf.getAscentPoint(text, font.getSize());
float descent = bf.getDescentPoint(text, font.getSize());
float textHeight = ascent - descent;
template.restoreState();
return new Rectangle(0, 0, textWidth, textHeight);
} | Return the text box for the specified text and font.
@param text text
@param font font
@return text box |
public void drawText(String text, Font font, Rectangle box, Color fontColor) {
template.saveState();
// get the font
DefaultFontMapper mapper = new DefaultFontMapper();
BaseFont bf = mapper.awtToPdf(font);
template.setFontAndSize(bf, font.getSize());
// calculate descent
float descent = 0;
if (text != null) {
descent = bf.getDescentPoint(text, font.getSize());
}
// calculate the fitting size
Rectangle fit = getTextSize(text, font);
// draw text if necessary
template.setColorFill(fontColor);
template.beginText();
template.showTextAligned(PdfContentByte.ALIGN_LEFT, text, origX + box.getLeft() + 0.5f
* (box.getWidth() - fit.getWidth()), origY + box.getBottom() + 0.5f
* (box.getHeight() - fit.getHeight()) - descent, 0);
template.endText();
template.restoreState();
} | Draw text in the center of the specified box.
@param text text
@param font font
@param box box to put text int
@param fontColor colour |
public void strokeRectangle(Rectangle rect, Color color, float linewidth) {
strokeRectangle(rect, color, linewidth, null);
} | Draw a rectangular boundary with this color and linewidth.
@param rect
rectangle
@param color
color
@param linewidth
line width |
public void strokeRoundRectangle(Rectangle rect, Color color, float linewidth, float r) {
template.saveState();
setStroke(color, linewidth, null);
template.roundRectangle(origX + rect.getLeft(), origY + rect.getBottom(), rect.getWidth(), rect.getHeight(), r);
template.stroke();
template.restoreState();
} | Draw a rounded rectangular boundary.
@param rect rectangle
@param color colour
@param linewidth line width
@param r radius for rounded corners |
public void fillRectangle(Rectangle rect, Color color) {
template.saveState();
setFill(color);
template.rectangle(origX + rect.getLeft(), origY + rect.getBottom(), rect.getWidth(), rect.getHeight());
template.fill();
template.restoreState();
} | Draw a rectangle's interior with this color.
@param rect rectangle
@param color colour |
public void strokeEllipse(Rectangle rect, Color color, float linewidth) {
template.saveState();
setStroke(color, linewidth, null);
template.ellipse(origX + rect.getLeft(), origY + rect.getBottom(), origX + rect.getRight(),
origY + rect.getTop());
template.stroke();
template.restoreState();
} | Draw an elliptical exterior with this color.
@param rect rectangle in which ellipse should fit
@param color colour to use for stroking
@param linewidth line width |
public void fillEllipse(Rectangle rect, Color color) {
template.saveState();
setFill(color);
template.ellipse(origX + rect.getLeft(), origY + rect.getBottom(), origX + rect.getRight(),
origY + rect.getTop());
template.fill();
template.restoreState();
} | Draw an elliptical interior with this color.
@param rect rectangle in which ellipse should fit
@param color colour to use for filling |
public void moveRectangleTo(Rectangle rect, float x, float y) {
float width = rect.getWidth();
float height = rect.getHeight();
rect.setLeft(x);
rect.setBottom(y);
rect.setRight(rect.getLeft() + width);
rect.setTop(rect.getBottom() + height);
} | Move this rectangle to the specified bottom-left point.
@param rect rectangle to move
@param x new x origin
@param y new y origin |
public void translateRectangle(Rectangle rect, float dx, float dy) {
float width = rect.getWidth();
float height = rect.getHeight();
rect.setLeft(rect.getLeft() + dx);
rect.setBottom(rect.getBottom() + dy);
rect.setRight(rect.getLeft() + dx + width);
rect.setTop(rect.getBottom() + dy + height);
} | Translate this rectangle over the specified following distances.
@param rect rectangle to move
@param dx delta x
@param dy delta y |
public void drawImage(Image img, Rectangle rect, Rectangle clipRect) {
drawImage(img, rect, clipRect, 1);
} | Draws the specified image with the first rectangle's bounds, clipping with the second one and adding
transparency.
@param img image
@param rect rectangle
@param clipRect clipping bounds |
public void drawImage(Image img, Rectangle rect, Rectangle clipRect, float opacity) {
try {
template.saveState();
// opacity
PdfGState state = new PdfGState();
state.setFillOpacity(opacity);
state.setBlendMode(PdfGState.BM_NORMAL);
template.setGState(state);
// clipping code
if (clipRect != null) {
template.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(),
clipRect.getHeight());
template.clip();
template.newPath();
}
template.addImage(img, rect.getWidth(), 0, 0, rect.getHeight(), origX + rect.getLeft(), origY
+ rect.getBottom());
} catch (DocumentException e) {
log.warn("could not draw image", e);
} finally {
template.restoreState();
}
} | Draws the specified image with the first rectangle's bounds, clipping with the second one.
@param img image
@param rect rectangle
@param clipRect clipping bounds
@param opacity opacity of the image (1 = opaque, 0= transparent) |
public void drawRelativePath(float[] x, float[] y, Rectangle rect, Color color, float lineWidth,
float[] dashArray) {
template.saveState();
setStroke(color, lineWidth, dashArray);
template.moveTo(origX + getAbsoluteX(x[0], rect), origY + getAbsoluteY(y[0], rect));
for (int i = 1; i < x.length; i++) {
template.lineTo(origX + getAbsoluteX(x[i], rect), origY + getAbsoluteY(y[i], rect));
}
template.stroke();
template.restoreState();
} | Draw a path specified by relative coordinates in [0,1] range wrt the specified rectangle.
@param x x-ordinate
@param y y-ordinate
@param rect rectangle
@param color color to use
@param lineWidth line width
@param dashArray lengths for dashed and white area |
public void drawGeometry(Geometry geometry, SymbolInfo symbol, Color fillColor, Color strokeColor, float lineWidth,
float[] dashArray, Rectangle clipRect) {
template.saveState();
// clipping code
if (clipRect != null) {
template.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(), clipRect
.getHeight());
template.clip();
template.newPath();
}
setStroke(strokeColor, lineWidth, dashArray);
setFill(fillColor);
drawGeometry(geometry, symbol);
template.restoreState();
} | Draw the specified geometry.
@param geometry geometry to draw
@param symbol symbol for geometry
@param fillColor fill colour
@param strokeColor stroke colour
@param lineWidth line width
@param clipRect clipping rectangle |
public Rectangle toRelative(Rectangle rect) {
return new Rectangle(rect.getLeft() - origX, rect.getBottom() - origY, rect.getRight() - origX, rect.getTop()
- origY);
} | Converts an absolute rectangle to a relative one wrt to the current coordinate system.
@param rect absolute rectangle
@return relative rectangle |
public Object storeObject(Object object)
{
/* One possibility of storing objects is to use the current transaction
associated with the container */
try
{
TransactionExt tx = (TransactionExt) odmg.currentTransaction();
tx.lock(object, Transaction.WRITE);
tx.markDirty(object);
}
catch (LockNotGrantedException e)
{
log.error("Failure while storing object " + object, e);
throw new EJBException("Failure while storing object", e);
}
return object;
} | Store an object. |
public Collection storeObjects(Collection objects)
{
try
{
/* One possibility of storing objects is to use the current transaction
associated with the container */
Transaction tx = odmg.currentTransaction();
for (Iterator iterator = objects.iterator(); iterator.hasNext();)
{
tx.lock(iterator.next(), Transaction.WRITE);
}
}
catch (LockNotGrantedException e)
{
log.error("Failure while storing objects " + objects, e);
throw new EJBException("Failure while storing objects", e);
}
return objects;
} | Store a collection of objects. |
public void deleteObjects(Collection objects)
{
for (Iterator iterator = objects.iterator(); iterator.hasNext();)
{
getDatabase().deletePersistent(iterator.next());
}
} | Delete a Collection of objects. |
Subsets and Splits