code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
protected Query[] buildPrefetchQueries(Collection owners, Collection children)
{
ClassDescriptor cld = getOwnerClassDescriptor();
ObjectReferenceDescriptor ord = getObjectReferenceDescriptor();
Collection queries = new ArrayList(owners.size());
Collection idsSubset = new HashSet(owners.size());
Iterator iter = owners.iterator();
Class topLevelClass = getBroker().getTopLevelClass(ord.getItemClass());
Object[] fkValues;
Object owner;
Identity id;
PersistenceBroker pb = getBroker();
ObjectCache cache = pb.serviceObjectCache();
while (iter.hasNext())
{
owner = iter.next();
fkValues = ord.getForeignKeyValues(owner,cld);
if (isNull(fkValues))
{
continue;
}
id = pb.serviceIdentity().buildIdentity(null, topLevelClass, fkValues);
if (cache.lookup(id) != null)
{
children.add(pb.getObjectByIdentity(id));
continue;
}
idsSubset.add(id);
if (idsSubset.size() == pkLimit)
{
queries.add(buildPrefetchQuery(idsSubset));
idsSubset.clear();
}
}
if (idsSubset.size() > 0)
{
queries.add(buildPrefetchQuery(idsSubset));
}
return (Query[]) queries.toArray(new Query[queries.size()]);
} | Build the multiple queries for one relationship because of limitation of IN(...)
@param owners Collection containing all objects of the ONE side
@param children Collection where related objects found in the cache should be added. |
protected boolean _load ()
{
java.util.ArrayList newChildren = new java.util.ArrayList();
/* @todo make this work */
// if (cld.getConnectionDescriptor() != null)
// {
// newChildren.add(new OjbMetaJdbcConnectionDescriptorNode(
// this.getOjbMetaTreeModel().getRepository(),
// this.getOjbMetaTreeModel(),
// this,
// cld.getConnectionDescriptor()));
// }
//
// Add collection descriptors
java.util.Iterator it = cld.getCollectionDescriptors().iterator();
while (it.hasNext())
{
CollectionDescriptor collDesc = (CollectionDescriptor)it.next();
newChildren.add(new OjbMetaCollectionDescriptorNode(
this.getOjbMetaTreeModel().getRepository(),
this.getOjbMetaTreeModel(),
this,
collDesc));
}
// Add extent classes Class
it = cld.getExtentClassNames().iterator();
while (it.hasNext())
{
String extentClassName = (String)it.next();
newChildren.add(new OjbMetaExtentClassNode(
this.getOjbMetaTreeModel().getRepository(),
this.getOjbMetaTreeModel(),
this,
extentClassName));
}
// Get Field descriptors FieldDescriptor
if (cld.getFieldDescriptions() != null)
{
it = new ArrayIterator(cld.getFieldDescriptions());
while (it.hasNext())
{
FieldDescriptor fieldDesc = (FieldDescriptor)it.next();
newChildren.add(new OjbMetaFieldDescriptorNode(
this.getOjbMetaTreeModel().getRepository(),
this.getOjbMetaTreeModel(),
this,
fieldDesc));
}
}
else
{
System.out.println(cld.getClassNameOfObject() + " does not have field descriptors");
}
// Get Indices IndexDescriptor
it = cld.getIndexes().iterator();
while (it.hasNext())
{
IndexDescriptor indexDesc = (IndexDescriptor)it.next();
newChildren.add(new OjbMetaIndexDescriptorNode(
this.getOjbMetaTreeModel().getRepository(),
this.getOjbMetaTreeModel(),
this,
indexDesc));
}
// Get references ObjectReferenceDescriptor
it = cld.getObjectReferenceDescriptors().iterator();
while (it.hasNext())
{
ObjectReferenceDescriptor objRefDesc = (ObjectReferenceDescriptor)it.next();
newChildren.add(new OjbMetaObjectReferenceDescriptorNode(
this.getOjbMetaTreeModel().getRepository(),
this.getOjbMetaTreeModel(),
this,
objRefDesc));
}
// Add
this.alChildren = newChildren;
this.getOjbMetaTreeModel().nodeStructureChanged(this);
return true;
} | Purpose of this method is to fill the children of the node. It should
replace all children in alChildren (the arraylist containing the children)
of this node and notify the TreeModel that a change has occurred. |
@Action(
semantics = SemanticsOf.IDEMPOTENT
)
@MemberOrder(name="ToDos", sequence="90.1")
public ExcelModuleDemoToDoItemBulkUpdateManager bulkUpdateManager() {
ExcelModuleDemoToDoItemBulkUpdateManager template = new ExcelModuleDemoToDoItemBulkUpdateManager();
template.setFileName("toDoItems.xlsx");
template.setCategory(Category.Domestic);
template.setSubcategory(Subcategory.Shopping);
template.setComplete(false);
return newBulkUpdateManager(template);
} | ////////////////////////////////////// |
String mementoFor(final ExcelModuleDemoToDoItemBulkUpdateManager tdieim) {
final Memento memento = mementoService.create();
memento.set("fileName", tdieim.getFileName());
memento.set("category", tdieim.getCategory());
memento.set("subcategory", tdieim.getSubcategory());
memento.set("completed", tdieim.isComplete());
return memento.asString();
} | ////////////////////////////////////// |
String mementoFor(ExcelModuleDemoToDoItemBulkUpdateLineItem lineItem) {
final Memento memento = mementoService.create();
memento.set("toDoItem", bookmarkService.bookmarkFor(lineItem.getToDoItem()));
memento.set("description", lineItem.getDescription());
memento.set("category", lineItem.getCategory());
memento.set("subcategory", lineItem.getSubcategory());
memento.set("cost", lineItem.getCost());
memento.set("complete", lineItem.isComplete());
memento.set("dueBy", lineItem.getDueBy());
memento.set("notes", lineItem.getNotes());
memento.set("ownedBy", lineItem.getOwnedBy());
return memento.asString();
} | ////////////////////////////////////// |
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();
lblPKTableName = new javax.swing.JLabel();
tfPKTableName = new javax.swing.JTextField();
lblFKTableName = new javax.swing.JLabel();
tfFKTableName = new javax.swing.JTextField();
lblReferenceType = new javax.swing.JLabel();
tfReferenceType = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
lblAutoRetrieve = new javax.swing.JLabel();
cbAutoRetrieve = new javax.swing.JCheckBox();
lblAutoUpdate = new javax.swing.JLabel();
cbAutoUpdate = new javax.swing.JCheckBox();
lblAutoDelete = new javax.swing.JLabel();
cbAutoDelete = new javax.swing.JCheckBox();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
lblJavaFieldName = new javax.swing.JLabel();
tfJavaFieldName = new javax.swing.JTextField();
lblJavaFieldType = new javax.swing.JLabel();
tfJavaFieldType = new javax.swing.JTextField();
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(15, 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.setEnabled(false);
jPanel1.add(cbDisabledByParent);
jPanel1.add(jLabel4);
jPanel1.add(jLabel3);
lblPKTableName.setLabelFor(tfPKTableName);
lblPKTableName.setText("Primary Key Table:");
jPanel1.add(lblPKTableName);
tfPKTableName.setEditable(false);
tfPKTableName.setText("jTextField1");
tfPKTableName.setBorder(null);
tfPKTableName.setDisabledTextColor((java.awt.Color) javax.swing.UIManager.getDefaults().get("TextField.foreground"));
tfPKTableName.setEnabled(false);
jPanel1.add(tfPKTableName);
lblFKTableName.setLabelFor(tfFKTableName);
lblFKTableName.setText("Foreign Key Table:");
jPanel1.add(lblFKTableName);
tfFKTableName.setEditable(false);
tfFKTableName.setText("jTextField1");
tfFKTableName.setBorder(null);
tfFKTableName.setDisabledTextColor((java.awt.Color) javax.swing.UIManager.getDefaults().get("TextField.foreground"));
tfFKTableName.setEnabled(false);
jPanel1.add(tfFKTableName);
lblReferenceType.setLabelFor(tfReferenceType);
lblReferenceType.setText("Type:");
jPanel1.add(lblReferenceType);
tfReferenceType.setEditable(false);
tfReferenceType.setText("jTextField1");
tfReferenceType.setBorder(null);
tfReferenceType.setDisabledTextColor((java.awt.Color) javax.swing.UIManager.getDefaults().get("TextField.foreground"));
tfReferenceType.setEnabled(false);
jPanel1.add(tfReferenceType);
jPanel1.add(jLabel5);
jPanel1.add(jLabel6);
lblAutoRetrieve.setDisplayedMnemonic('r');
lblAutoRetrieve.setText("Auto retrieve:");
jPanel1.add(lblAutoRetrieve);
cbAutoRetrieve.setMnemonic('r');
cbAutoRetrieve.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
cbAutoRetrieveActionPerformed(evt);
}
});
jPanel1.add(cbAutoRetrieve);
lblAutoUpdate.setDisplayedMnemonic('u');
lblAutoUpdate.setText("Auto update:");
jPanel1.add(lblAutoUpdate);
cbAutoUpdate.setMnemonic('u');
cbAutoUpdate.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
cbAutoUpdateActionPerformed(evt);
}
});
jPanel1.add(cbAutoUpdate);
lblAutoDelete.setDisplayedMnemonic('d');
lblAutoDelete.setText("Auto delete:");
jPanel1.add(lblAutoDelete);
cbAutoDelete.setMnemonic('d');
cbAutoDelete.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
cbAutoDeleteActionPerformed(evt);
}
});
jPanel1.add(cbAutoDelete);
jPanel1.add(jLabel10);
jPanel1.add(jLabel11);
lblJavaFieldName.setDisplayedMnemonic('n');
lblJavaFieldName.setLabelFor(tfJavaFieldName);
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);
lblJavaFieldType.setDisplayedMnemonic('t');
lblJavaFieldType.setLabelFor(tfJavaFieldType);
lblJavaFieldType.setText("Java Field Type:");
jPanel1.add(lblJavaFieldType);
tfJavaFieldType.setText("jTextField2");
tfJavaFieldType.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
tfJavaFieldTypeActionPerformed(evt);
}
});
tfJavaFieldType.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusLost(java.awt.event.FocusEvent evt)
{
tfJavaFieldTypeFocusLost(evt);
}
});
tfJavaFieldType.addKeyListener(new java.awt.event.KeyAdapter()
{
public void keyTyped(java.awt.event.KeyEvent evt)
{
tfJavaFieldTypeKeyTyped(evt);
}
});
jPanel1.add(tfJavaFieldType);
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 tfJavaFieldTypeKeyTyped(java.awt.event.KeyEvent evt)//GEN-FIRST:event_tfJavaFieldTypeKeyTyped
{//GEN-HEADEREND:event_tfJavaFieldTypeKeyTyped
// Revert on ESC
if (evt.getKeyChar() == KeyEvent.VK_ESCAPE)
{
this.tfJavaFieldType.setText(aRelation.getFieldType());
}
} | GEN-END:initComponents |
private void tfJavaFieldTypeFocusLost(java.awt.event.FocusEvent evt)//GEN-FIRST:event_tfJavaFieldTypeFocusLost
{//GEN-HEADEREND:event_tfJavaFieldTypeFocusLost
// Commit on lost focus
this.aRelation.setFieldType(tfJavaFieldType.getText());
} | GEN-LAST:event_tfJavaFieldTypeKeyTyped |
private void tfJavaFieldTypeActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_tfJavaFieldTypeActionPerformed
{//GEN-HEADEREND:event_tfJavaFieldTypeActionPerformed
// Commit on ENTER
this.aRelation.setFieldType(tfJavaFieldType.getText());
} | GEN-LAST:event_tfJavaFieldTypeFocusLost |
private void tfJavaFieldNameKeyTyped(java.awt.event.KeyEvent evt)//GEN-FIRST:event_tfJavaFieldNameKeyTyped
{//GEN-HEADEREND:event_tfJavaFieldNameKeyTyped
// Revert to original value if ESC is typed
if (evt.getKeyChar() == KeyEvent.VK_ESCAPE)
{
this.tfJavaFieldName.setText(aRelation.getFieldName());
}
} | GEN-LAST:event_tfJavaFieldTypeActionPerformed |
private void tfJavaFieldNameFocusLost(java.awt.event.FocusEvent evt)//GEN-FIRST:event_tfJavaFieldNameFocusLost
{//GEN-HEADEREND:event_tfJavaFieldNameFocusLost
// Commit value if focus is lost
aRelation.setFieldName(tfJavaFieldName.getText());
} | GEN-LAST:event_tfJavaFieldNameKeyTyped |
private void tfJavaFieldNameActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_tfJavaFieldNameActionPerformed
{//GEN-HEADEREND:event_tfJavaFieldNameActionPerformed
// Commit value if ENTER is typed
aRelation.setFieldName(tfJavaFieldName.getText());
} | GEN-LAST:event_tfJavaFieldNameFocusLost |
private void cbAutoDeleteActionPerformed (java.awt.event.ActionEvent evt)//GEN-FIRST:event_cbAutoDeleteActionPerformed
{//GEN-HEADEREND:event_cbAutoDeleteActionPerformed
// Add your handling code here:
this.aRelation.setAutoDelete(this.cbAutoDelete.isSelected());
} | GEN-LAST:event_tfJavaFieldNameActionPerformed |
private void cbAutoUpdateActionPerformed (java.awt.event.ActionEvent evt)//GEN-FIRST:event_cbAutoUpdateActionPerformed
{//GEN-HEADEREND:event_cbAutoUpdateActionPerformed
// Add your handling code here:
this.aRelation.setAutoUpdate(this.cbAutoUpdate.isSelected());
} | GEN-LAST:event_cbAutoDeleteActionPerformed |
private void cbAutoRetrieveActionPerformed (java.awt.event.ActionEvent evt)//GEN-FIRST:event_cbAutoRetrieveActionPerformed
{//GEN-HEADEREND:event_cbAutoRetrieveActionPerformed
// Add your handling code here:
aRelation.setAutoRetrieve(cbAutoRetrieve.isSelected());
} | GEN-LAST:event_cbAutoUpdateActionPerformed |
public void setModel (PropertySheetModel pm)
{
if (pm instanceof org.apache.ojb.tools.mapping.reversedb.DBFKRelation)
{
this.aRelation = (org.apache.ojb.tools.mapping.reversedb.DBFKRelation)pm;
this.readValuesFromReference();
}
else
throw new IllegalArgumentException();
} | GEN-LAST:event_formComponentShown |
public void add(int index, Object element)
{
DListEntry entry = prepareEntry(element);
elements.add(index, entry);
// if we are in a transaction: acquire locks !
TransactionImpl tx = getTransaction();
if (checkForOpenTransaction(tx))
{
RuntimeObject rt = new RuntimeObject(this, tx);
List regList = tx.getRegistrationList();
tx.lockAndRegister(rt, Transaction.WRITE, false, regList);
rt = new RuntimeObject(element, tx);
tx.lockAndRegister(rt, Transaction.READ, regList);
rt = new RuntimeObject(entry, tx, true);
tx.lockAndRegister(rt, Transaction.WRITE, false, regList);
}
// changing the position markers of entries:
int offset = 0;
try
{
offset = ((DListEntry) elements.get(index - 1)).getPosition();
}
catch (Exception ignored)
{
}
for (int i = offset; i < elements.size(); i++)
{
entry = (DListEntry) elements.get(i);
entry.setPosition(i);
}
} | Inserts the specified element at the specified position in this list
(optional operation). Shifts the element currently at that position
(if any) and any subsequent elements to the right (adds one to their
indices).
@param index index at which the specified element is to be inserted.
@param element element to be inserted.
@throws UnsupportedOperationException if the <tt>add</tt> method is not
supported by this list.
@throws ClassCastException if the class of the specified element
prevents it from being added to this list.
@throws IllegalArgumentException if some aspect of the specified
element prevents it from being added to this list.
@throws IndexOutOfBoundsException if the index is out of range
(index < 0 || index > size()). |
public Object remove(int index)
{
DListEntry entry = (DListEntry) elements.get(index);
// if we are in a transaction: acquire locks !
TransactionImpl tx = getTransaction();
if (checkForOpenTransaction(tx))
{
tx.deletePersistent(new RuntimeObject(entry, tx));
}
elements.remove(index);
// changing the position markers of entries:
int offset = 0;
try
{
offset = ((DListEntry) elements.get(index)).getPosition();
}
catch (Exception ignored)
{
}
for (int i = offset; i < elements.size(); i++)
{
entry = (DListEntry) elements.get(i);
entry.setPosition(i);
}
return entry.getRealSubject();
} | Removes the element at the specified position in this list (optional
operation). Shifts any subsequent elements to the left (subtracts one
from their indices). Returns the element that was removed from the
list.<p>
This implementation always throws an
<tt>UnsupportedOperationException</tt>.
@param index the index of the element to remove.
@return the element previously at the specified position.
@throws UnsupportedOperationException if the <tt>remove</tt> method is
not supported by this list.
@throws IndexOutOfBoundsException if the specified index is out of
range (<tt>index < 0 || index >= size()</tt>). |
public DList concat(DList otherList)
{
DListImpl result = new DListImpl(pbKey);
result.addAll(this);
result.addAll(otherList);
return result;
} | Creates a new <code>DList</code> object that contains the contents of this
<code>DList</code> object concatenated
with the contents of the <code>otherList</code> object.
@param otherList The list whose elements are placed at the end of the list
returned by this method.
@return A new <code>DList</code> that is the concatenation of this list and
the list referenced by <code>otherList</code>. |
public boolean existsElement(String predicate) throws org.odmg.QueryInvalidException
{
DList results = (DList) this.query(predicate);
if (results == null || results.size() == 0)
return false;
else
return true;
} | Determines whether there is an element of the collection that evaluates to true
for the predicate.
@param predicate An OQL boolean query predicate.
@return True if there is an element of the collection that evaluates to true
for the predicate, otherwise false.
@exception org.odmg.QueryInvalidException The query predicate is invalid. |
public Object get(int index)
{
DListEntry entry = (DListEntry) elements.get(index);
return entry.getRealSubject();
} | Returns the element at the specified position in this list.
@param index index of element to return.
@return the element at the specified position in this list.
@throws IndexOutOfBoundsException if the index is out of range (index
< 0 || index >= size()). |
public DCollection query(String predicate) throws QueryInvalidException
{
// 1.build complete OQL statement
String oql = "select all from java.lang.Object where " + predicate;
TransactionImpl tx = getTransaction();
if (tx == null) throw new QueryInvalidException("Need running transaction to do query");
OQLQuery predicateQuery = tx.getImplementation().newOQLQuery();
predicateQuery.create(oql);
Query pQ = ((OQLQueryImpl) predicateQuery).getQuery();
Criteria pCrit = pQ.getCriteria();
PBCapsule handle = new PBCapsule(pbKey, tx);
DList result;
try
{
PersistenceBroker broker = handle.getBroker();
Criteria allElementsCriteria = this.getPkCriteriaForAllElements(broker);
// join selection of elements with predicate criteria:
allElementsCriteria.addAndCriteria(pCrit);
Class clazz = null;
try
{
clazz = this.getElementsExtentClass(broker);
}
catch (PersistenceBrokerException e)
{
getLog().error(e);
throw new ODMGRuntimeException(e.getMessage());
}
Query q = new QueryByCriteria(clazz, allElementsCriteria);
if (getLog().isDebugEnabled()) getLog().debug(q.toString());
result = null;
try
{
result = (DList) broker.getCollectionByQuery(DListImpl.class, q);
}
catch (PersistenceBrokerException e)
{
getLog().error("Query failed", e);
throw new OJBRuntimeException(e);
}
}
finally
{
// cleanup stuff
if (handle != null) handle.destroy();
}
// 3. return resulting collection
return result;
} | Evaluate the boolean query predicate for each element of the collection and
return a new collection that contains each element that evaluated to true.
@param predicate An OQL boolean query predicate.
@return A new collection containing the elements that evaluated true for the predicate.
@exception org.odmg.QueryInvalidException The query predicate is invalid. |
public Iterator select(String predicate) throws org.odmg.QueryInvalidException
{
return this.query(predicate).iterator();
} | Access all of the elements of the collection that evaluate to true for the
provided query predicate.
@param predicate An OQL boolean query predicate.
@return An iterator used to iterate over the elements that evaluated true for the predicate.
@exception org.odmg.QueryInvalidException The query predicate is invalid. |
public Object selectElement(String predicate) throws org.odmg.QueryInvalidException
{
return ((DList) this.query(predicate)).get(0);
} | Selects the single element of the collection for which the provided OQL query
predicate is true.
@param predicate An OQL boolean query predicate.
@return The element that evaluates to true for the predicate. If no element
evaluates to true, null is returned.
@exception org.odmg.QueryInvalidException The query predicate is invalid. |
public boolean hasNext()
{
while (_list.hasMoreTokens() && (_current.length() == 0))
{
_current = _list.nextToken();
}
return (_current.length() > 0);
} | /* (non-Javadoc)
@see java.util.Iterator#hasNext() |
public static boolean sameLists(String list1, String list2)
{
return new CommaListIterator(list1).equals(new CommaListIterator(list2));
} | Compares the two comma-separated lists.
@param list1 The first list
@param list2 The second list
@return <code>true</code> if the lists are equal |
public static void startTimer(final String type) {
TransactionLogger instance = getInstance();
if (instance == null) {
return;
}
instance.components.putIfAbsent(type, new Component(type));
instance.components.get(type).startTimer();
} | Start component timer for current instance
@param type - of component |
public static void pauseTimer(final String type) {
TransactionLogger instance = getInstance();
if (instance == null) {
return;
}
instance.components.get(type).pauseTimer();
} | Pause component timer for current instance
@param type - of component |
public static void logComponent(final String type, final String details) {
TransactionLogger instance = getInstance();
logComponent(type, details, instance);
} | Log details of component processing (including processing time) to debug for current instance
@param type - of component
@param details - of component processing |
public static ComponentsMultiThread getComponentsMultiThread() {
TransactionLogger instance = getInstance();
if (instance == null) {
return null;
}
return instance.componentsMultiThread;
} | Get ComponentsMultiThread of current instance
@return componentsMultiThread |
public static Collection<Component> getComponentsList() {
TransactionLogger instance = getInstance();
if (instance == null) {
return null;
}
return instance.components.values();
} | Get components list for current instance
@return components |
public static String getFlowContext() {
TransactionLogger instance = getInstance();
if (instance == null) {
return null;
}
return instance.flowContext;
} | Get string value of flow context for current instance
@return string value of flow context |
public static void addProperty(String key, String value) {
TransactionLogger instance = getInstance();
if (instance != null) {
instance.properties.put(key, value);
}
} | Add property to 'properties' map on transaction
@param key - of property
@param value - of property |
public static void addAsyncProperty(String key, String value, TransactionLogger transactionLogger) {
FlowContextFactory.deserializeNativeFlowContext(transactionLogger.getFlowContextAsync(transactionLogger));
transactionLogger.properties.put(key, value);
} | Add property to 'properties' map on transaction
@param key - of property
@param value - of property
@param transactionLogger |
protected static boolean createLoggingAction(final Logger logger, final Logger auditor, final TransactionLogger instance) {
TransactionLogger oldInstance = getInstance();
if (oldInstance == null || oldInstance.finished) {
if(loggingKeys == null) {
synchronized (TransactionLogger.class) {
if (loggingKeys == null) {
logger.info("Initializing 'LoggingKeysHandler' class");
loggingKeys = new LoggingKeysHandler(keysPropStream);
}
}
}
initInstance(instance, logger, auditor);
setInstance(instance);
return true;
}
return false; // Really not sure it can happen - since we arrive here in a new thread of transaction I think it's ThreadLocal should be empty. But leaving this code just in case...
} | Create new logging action
This method check if there is an old instance for this thread-local
If not - Initialize new instance and set it as this thread-local's instance
@param logger
@param auditor
@param instance
@return whether new instance was set to thread-local |
protected void addPropertiesStart(String type) {
putProperty(PropertyKey.Host.name(), IpUtils.getHostName());
putProperty(PropertyKey.Type.name(), type);
putProperty(PropertyKey.Status.name(), Status.Start.name());
} | Add properties to 'properties' map on transaction start
@param type - of transaction |
protected void addPropertiesProcessingTime() {
HashMap<String, Long> mapComponentTimes = new HashMap<>();
HashMap<String, Long> mapComponentInvocations = new HashMap<>();
// For multi-threaded transaction: will calculate the sum of the time spent by all components in all threads
if (this.componentsMultiThread != null) {
for (Component component : this.componentsMultiThread.getComponents()) {
addTimePerComponent(mapComponentTimes, component);
addInvocationPerComponent(mapComponentInvocations, component);
}
}
for (Component component : this.components.values()) {
addTimePerComponent(mapComponentTimes, component);
}
for (Entry<String, Long> entry : mapComponentTimes.entrySet()) {
putProperty(entry.getKey(), addDuration(entry.getValue()));
}
for (Entry<String, Long> entry : mapComponentInvocations.entrySet()) {
putProperty(entry.getKey(), entry.getValue().toString());
}
putProperty(TOTAL_COMPONENT, addDuration(this.total.getTime()));
} | Add components processing time to 'properties' map:
key = componentType
value = time + "ms" |
protected void writePropertiesToLog(Logger logger, Level level) {
writeToLog(logger, level, getMapAsString(this.properties, separator), null);
if (this.exception != null) {
writeToLog(this.logger, Level.ERROR, "Error:", this.exception);
}
} | Write 'properties' map to given log in given level - with pipe separator between each entry
Write exception stack trace to 'logger' in 'error' level, if not empty
@param logger
@param level - of logging |
protected static String getMapAsString(Map<String, String> map, String separator) {
if (map != null && !map.isEmpty()) {
StringBuilder str = new StringBuilder();
boolean isFirst = true;
for (Entry<String, String> entry : map.entrySet() ) {
if (!isFirst) {
str.append(separator);
} else {
isFirst = false;
}
str.append(entry.getKey()).append(":").append(entry.getValue());
}
return str.toString();
}
return null;
} | Get string representation of the given map:
key:value separator key:value separator ...
@param map
@param separator
@return string representation of the given map |
private static void initInstance(final TransactionLogger instance, final Logger logger, final Logger auditor) {
instance.logger = logger;
instance.auditor = auditor;
instance.components = new LinkedHashMap<>();
instance.properties = new LinkedHashMap<>();
instance.total = new Component(TOTAL_COMPONENT);
instance.total.startTimer();
instance.componentsMultiThread = new ComponentsMultiThread();
instance.flowContext = FlowContextFactory.serializeNativeFlowContext();
} | Initialize new instance
@param instance
@param logger
@param auditor |
private static void writeToLog(Logger logger, Level level, String pattern, Exception exception) {
if (level == Level.ERROR) {
logger.error(pattern, exception);
} else if (level == Level.INFO) {
logger.info(pattern);
} else if (level == Level.DEBUG) {
logger.debug(pattern);
}
} | Write the given pattern to given log in given logging level
@param logger
@param level
@param pattern
@param exception |
private static void addTimePerComponent(HashMap<String, Long> mapComponentTimes, Component component) {
Long currentTimeOfComponent = 0L;
String key = component.getComponentType();
if (mapComponentTimes.containsKey(key)) {
currentTimeOfComponent = mapComponentTimes.get(key);
}
//when transactions are run in parallel, we should log the longest transaction only to avoid that
//for ex 'Total time' would be 100ms and transactions in parallel to hornetQ will be 2000ms
Long maxTime = Math.max(component.getTime(), currentTimeOfComponent);
mapComponentTimes.put(key, maxTime);
} | Add component processing time to given map
@param mapComponentTimes
@param component |
public static String convertToSQL92(char escape, char multi, char single, String pattern)
throws IllegalArgumentException {
if ((escape == '\'') || (multi == '\'') || (single == '\'')) {
throw new IllegalArgumentException("do not use single quote (') as special char!");
}
StringBuilder result = new StringBuilder(pattern.length() + 5);
int i = 0;
while (i < pattern.length()) {
char chr = pattern.charAt(i);
if (chr == escape) {
// emit the next char and skip it
if (i != (pattern.length() - 1)) {
result.append(pattern.charAt(i + 1));
}
i++; // skip next char
} else if (chr == single) {
result.append('_');
} else if (chr == multi) {
result.append('%');
} else if (chr == '\'') {
result.append('\'');
result.append('\'');
} else {
result.append(chr);
}
i++;
}
return result.toString();
} | Given OGC PropertyIsLike Filter information, construct an SQL-compatible 'like' pattern.
SQL % --> match any number of characters _ --> match a single character
NOTE; the SQL command is 'string LIKE pattern [ESCAPE escape-character]' We could re-define the escape character,
but I'm not doing to do that in this code since some databases will not handle this case.
Method: 1.
Examples: ( escape ='!', multi='*', single='.' ) broadway* -> 'broadway%' broad_ay -> 'broad_ay' broadway ->
'broadway'
broadway!* -> 'broadway*' (* has no significance and is escaped) can't -> 'can''t' ( ' escaped for SQL
compliance)
NOTE: we also handle "'" characters as special because they are end-of-string characters. SQL will convert ' to
'' (double single quote).
NOTE: we don't handle "'" as a 'special' character because it would be too confusing to have a special char as
another special char. Using this will throw an error (IllegalArgumentException).
@param escape escape character
@param multi ?????
@param single ?????
@param pattern pattern to match
@return SQL like sub-expression
@throws IllegalArgumentException oops |
public String getSQL92LikePattern() throws IllegalArgumentException {
if (escape.length() != 1) {
throw new IllegalArgumentException("Like Pattern --> escape char should be of length exactly 1");
}
if (wildcardSingle.length() != 1) {
throw new IllegalArgumentException("Like Pattern --> wildcardSingle char should be of length exactly 1");
}
if (wildcardMulti.length() != 1) {
throw new IllegalArgumentException("Like Pattern --> wildcardMulti char should be of length exactly 1");
}
return LikeFilterImpl.convertToSQL92(escape.charAt(0), wildcardMulti.charAt(0), wildcardSingle.charAt(0),
isMatchingCase(), pattern);
} | See convertToSQL92.
@return SQL like sub-expression
@throws IllegalArgumentException oops |
@Deprecated
public final void setPattern(Expression p, String wildcardMultiChar, String wildcardOneChar, String escapeString) {
setPattern(p.toString(), wildcardMultiChar, wildcardOneChar, escapeString);
} | Set the match pattern for this FilterLike.
@param p
the expression which evaluates to the match pattern for this filter
@param wildcardMultiChar
the string that represents a multiple character (1->n) wildcard
@param wildcardOneChar
the string that represents a single character (1) wildcard
@param escapeString
the string that represents an escape character
@deprecated use one of {@link org.opengis.filter.PropertyIsLike#setExpression(Expression)}
{@link org.opengis.filter.PropertyIsLike#setWildCard(String)}
{@link org.opengis.filter.PropertyIsLike#setSingleChar(String)}
{@link org.opengis.filter.PropertyIsLike#setEscape(String)} |
@Deprecated
public final void setPattern(String matchPattern, String wildcardMultiChar, String wildcardOneChar,
String escapeString) {
setLiteral(matchPattern);
setWildCard(wildcardMultiChar);
setSingleChar(wildcardOneChar);
setEscape(escapeString);
} | Set the match pattern for this FilterLike.
@param matchPattern
the string which contains the match pattern for this filter
@param wildcardMultiChar
the string that represents a multiple character (1->n) wildcard
@param wildcardOneChar
the string that represents a single character (1) wildcard
@param escapeString
the string that represents an escape character
@deprecated use one of {@link org.opengis.filter.PropertyIsLike#setLiteral(String)}
{@link org.opengis.filter.PropertyIsLike#setWildCard(String)}
{@link org.opengis.filter.PropertyIsLike#setSingleChar(String)}
{@link org.opengis.filter.PropertyIsLike#setEscape(String)} |
public boolean evaluate(Object feature) {
// Checks to ensure that the attribute has been set
if (attribute == null) {
return false;
}
// Note that this converts the attribute to a string
// for comparison. Unlike the math or geometry filters, which
// require specific types to function correctly, this filter
// using the mandatory string representation in Java
// Of course, this does not guarantee a meaningful result, but it
// does guarantee a valid result.
// LOGGER.finest("pattern: " + pattern);
// LOGGER.finest("string: " + attribute.getValue(feature));
// return attribute.getValue(feature).toString().matches(pattern);
Object value = attribute.evaluate(feature);
if (null == value) {
return false;
}
Matcher matcher = getMatcher();
matcher.reset(value.toString());
return matcher.matches();
} | Determines whether or not a given feature matches this pattern.
@param feature
Specified feature to examine.
@return Flag confirming whether or not this feature is inside the filter. |
private boolean isSpecial(final char chr) {
return ((chr == '.') || (chr == '?') || (chr == '*') || (chr == '^') || (chr == '$') || (chr == '+')
|| (chr == '[') || (chr == ']') || (chr == '(') || (chr == ')') || (chr == '|') || (chr == '\\')
|| (chr == '&'));
} | Convenience method to determine if a character is special to the regex system.
@param chr
the character to test
@return is the character a special character. |
private String fixSpecials(final String inString) {
StringBuilder tmp = new StringBuilder();
for (int i = 0; i < inString.length(); i++) {
char chr = inString.charAt(i);
if (isSpecial(chr)) {
tmp.append(this.escape);
tmp.append(chr);
} else {
tmp.append(chr);
}
}
return tmp.toString();
} | Convenience method to escape any character that is special to the regex system.
@param inString
the string to fix
@return the fixed string |
protected PreparedStatement prepareStatement(Connection con,
String sql,
boolean scrollable,
boolean createPreparedStatement,
int explicitFetchSizeHint)
throws SQLException
{
PreparedStatement result;
// if a JDBC1.0 driver is used the signature
// prepareStatement(String, int, int) is not defined.
// we then call the JDBC1.0 variant prepareStatement(String)
try
{
// if necessary use JDB1.0 methods
if (!FORCEJDBC1_0)
{
if (createPreparedStatement)
{
result =
con.prepareStatement(
sql,
scrollable
? ResultSet.TYPE_SCROLL_INSENSITIVE
: ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
afterJdbc2CapableStatementCreate(result, explicitFetchSizeHint);
}
else
{
result =
con.prepareCall(
sql,
scrollable
? ResultSet.TYPE_SCROLL_INSENSITIVE
: ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
}
else
{
if (createPreparedStatement)
{
result = con.prepareStatement(sql);
}
else
{
result = con.prepareCall(sql);
}
}
}
catch (AbstractMethodError err)
{
// this exception is raised if Driver is not JDBC 2.0 compliant
log.warn("Used driver seems not JDBC 2.0 compatible, use the JDBC 1.0 mode", err);
if (createPreparedStatement)
{
result = con.prepareStatement(sql);
}
else
{
result = con.prepareCall(sql);
}
FORCEJDBC1_0 = true;
}
catch (SQLException eSql)
{
// there are JDBC Driver that nominally implement JDBC 2.0, but
// throw DriverNotCapableExceptions. If we catch one of these
// we force usage of JDBC 1.0
if (eSql
.getClass()
.getName()
.equals("interbase.interclient.DriverNotCapableException"))
{
log.warn("JDBC 2.0 problems with this interbase driver, we use the JDBC 1.0 mode");
if (createPreparedStatement)
{
result = con.prepareStatement(sql);
}
else
{
result = con.prepareCall(sql);
}
FORCEJDBC1_0 = true;
}
else
{
throw eSql;
}
}
try
{
if (!ProxyHelper.isNormalOjbProxy(result)) // tomdz: What about VirtualProxy
{
platform.afterStatementCreate(result);
}
}
catch (PlatformException e)
{
log.error("Platform dependend failure", e);
}
return result;
} | Prepares a statement with parameters that should work with most RDBMS.
@param con the connection to utilize
@param sql the sql syntax to use when creating the statement.
@param scrollable determines if the statement will be scrollable.
@param createPreparedStatement if <code>true</code>, then a
{@link PreparedStatement} will be created. If <code>false</code>, then
a {@link java.sql.CallableStatement} will be created.
@param explicitFetchSizeHint will be used as fetchSize hint
(if applicable) if > 0
@return a statement that can be used to execute the syntax contained in
the <code>sql</code> argument. |
private Statement createStatement(Connection con, boolean scrollable, int explicitFetchSizeHint)
throws java.sql.SQLException
{
Statement result;
try
{
// if necessary use JDBC1.0 methods
if (!FORCEJDBC1_0)
{
result =
con.createStatement(
scrollable
? ResultSet.TYPE_SCROLL_INSENSITIVE
: ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
afterJdbc2CapableStatementCreate(result, explicitFetchSizeHint);
}
else
{
result = con.createStatement();
}
}
catch (AbstractMethodError err)
{
// if a JDBC1.0 driver is used, the signature
// createStatement(int, int) is not defined.
// we then call the JDBC1.0 variant createStatement()
log.warn("Used driver seems not JDBC 2.0 compatible, use the JDBC 1.0 mode", err);
result = con.createStatement();
FORCEJDBC1_0 = true;
}
catch (SQLException eSql)
{
// there are JDBC Driver that nominally implement JDBC 2.0, but
// throw DriverNotCapableExceptions. If we catch one of these
// we force usage of JDBC 1.0
if (eSql.getClass().getName()
.equals("interbase.interclient.DriverNotCapableException"))
{
log.warn("JDBC 2.0 problems with this interbase driver, we use the JDBC 1.0 mode");
FORCEJDBC1_0 = true;
result = con.createStatement();
}
else
{
throw eSql;
}
}
try
{
platform.afterStatementCreate(result);
}
catch (PlatformException e)
{
log.error("Platform dependend failure", e);
}
return result;
} | Creates a statement with parameters that should work with most RDBMS. |
public void propertyChange(java.beans.PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(this.editorKey))
{
this.setValue(evt.getNewValue());
}
} | This method gets called when a bound property is changed.
@param evt A PropertyChangeEvent object describing the event source
and the property that has changed. |
public int compareTo(InternalFeature o) {
if (null == o) {
return -1; // avoid NPE, put null objects at the end
}
if (null != styleDefinition && null != o.getStyleInfo()) {
if (styleDefinition.getIndex() > o.getStyleInfo().getIndex()) {
return 1;
}
if (styleDefinition.getIndex() < o.getStyleInfo().getIndex()) {
return -1;
}
}
return 0;
} | This function compares style ID's between features. Features are usually sorted by style. |
public final void begin() {
this.file = this.getAppender().getIoFile();
if (this.file == null) {
this.getAppender().getErrorHandler()
.error("Scavenger not started: missing log file name");
return;
}
if (this.getProperties().getScavengeInterval() > -1) {
final Thread thread = new Thread(this, "Log4J File Scavenger");
thread.setDaemon(true);
thread.start();
this.threadRef = thread;
}
} | Starts the scavenger. |
public final void end() {
final Thread thread = threadRef;
if (thread != null) {
thread.interrupt();
try {
thread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
this.threadRef = null;
} | Stops the scavenger. |
public static boolean isPropertyAllowed(Class defClass, String propertyName)
{
HashMap props = (HashMap)_properties.get(defClass);
return (props == null ? true : props.containsKey(propertyName));
} | Checks whether the property of the given name is allowed for the model element.
@param defClass The class of the model element
@param propertyName The name of the property
@return <code>true</code> if the property is allowed for this type of model elements |
public static boolean toBoolean(String value, boolean defaultValue)
{
return "true".equals(value) ? true : ("false".equals(value) ? false : defaultValue);
} | Determines whether the boolean value of the given string value.
@param value The value
@param defaultValue The boolean value to use if the string value is neither 'true' nor 'false'
@return The boolean value of the string |
@Override
public void format(final LoggingEvent event, final StringBuffer toAppendTo) {
if(event instanceof FoundationLof4jLoggingEvent){
FoundationLof4jLoggingEvent foundationLof4jLoggingEvent = (FoundationLof4jLoggingEvent)event;
Marker marker = foundationLof4jLoggingEvent.getSlf4jMarker();
marker.getName();
if(marker instanceof FoundationLoggingMarker){
FoundationLoggingMarker foundationLoggingMarker = (FoundationLoggingMarker)marker;
String userFieldValue = foundationLoggingMarker.valueOf(key);
if(FoundationLoggingMarker.NO_OPERATION.equals(userFieldValue)){
toAppendTo.append("");
}else{
toAppendTo.append(userFieldValue);
}
}
}
} | {@inheritDoc} |
protected AttributeInfo getAttributeInfo(String attr, boolean useOuterJoins, UserAlias aUserAlias, Map pathClasses)
{
AttributeInfo result = new AttributeInfo();
TableAlias tableAlias;
SqlHelper.PathInfo pathInfo = SqlHelper.splitPath(attr);
String colName = pathInfo.column;
int sp;
// BRJ:
// check if we refer to an attribute in the parent query
// this prefix is temporary !
if (colName.startsWith(Criteria.PARENT_QUERY_PREFIX) && m_parentStatement != null)
{
String[] fieldNameRef = {colName.substring(Criteria.PARENT_QUERY_PREFIX.length())};
return m_parentStatement.getAttributeInfo(fieldNameRef[0], useOuterJoins, aUserAlias, pathClasses);
}
sp = colName.lastIndexOf(".");
if (sp == -1)
{
tableAlias = getRoot();
}
else
{
String pathName = colName.substring(0, sp);
String[] fieldNameRef = {colName.substring(sp + 1)};
tableAlias = getTableAlias(pathName, useOuterJoins, aUserAlias, fieldNameRef, pathClasses);
/**
* if we have not found an alias by the pathName or
* aliasName (if given), try again because pathName
* may be an aliasname. it can be only and only if it is not
* a path, which means there may be no path separators (,)
* in the pathName.
*/
if ((tableAlias == null) && (colName.lastIndexOf(".") == -1))
{
/**
* pathName might be an alias, so check this first
*/
tableAlias = getTableAlias(pathName, useOuterJoins, new UserAlias(pathName, pathName, pathName), null, pathClasses);
}
if (tableAlias != null)
{
// correct column name to match the alias
// productGroup.groupName -> groupName
pathInfo.column = fieldNameRef[0];
}
}
result.tableAlias = tableAlias;
result.pathInfo = pathInfo;
return result;
} | Return the TableAlias and the PathInfo for an Attribute name<br>
field names in functions (ie: sum(name) ) are tried to resolve ie: name
from FIELDDESCRIPTOR , UPPER(name_test) from Criteria<br>
also resolve pathExpression adress.city or owner.konti.saldo
@param attr
@param useOuterJoins
@param aUserAlias
@param pathClasses
@return ColumnInfo |
protected String getColName(TableAlias aTableAlias, PathInfo aPathInfo, boolean translate)
{
String result = null;
// no translation required, use attribute name
if (!translate)
{
return aPathInfo.column;
}
// BRJ: special alias for the indirection table has no ClassDescriptor
if (aTableAlias.cld == null && M_N_ALIAS.equals(aTableAlias.alias))
{
return getIndirectionTableColName(aTableAlias, aPathInfo.path);
}
// translate attribute name into column name
FieldDescriptor fld = getFieldDescriptor(aTableAlias, aPathInfo);
if (fld != null)
{
m_attrToFld.put(aPathInfo.path, fld);
// added to suport the super reference descriptor
if (!fld.getClassDescriptor().getFullTableName().equals(aTableAlias.table) && aTableAlias.hasJoins())
{
Iterator itr = aTableAlias.joins.iterator();
while (itr.hasNext())
{
Join join = (Join) itr.next();
if (join.right.table.equals(fld.getClassDescriptor().getFullTableName()))
{
result = join.right.alias + "." + fld.getColumnName();
break;
}
}
if (result == null)
{
result = aPathInfo.column;
}
}
else
{
result = aTableAlias.alias + "." + fld.getColumnName();
}
}
else if ("*".equals(aPathInfo.column))
{
result = aPathInfo.column;
}
else
{
// throw new IllegalArgumentException("No Field found for : " + aPathInfo.column);
result = aPathInfo.column;
}
return result;
} | Answer the column name for alias and path info<br>
if translate try to convert attribute name into column name otherwise use attribute name<br>
if a FieldDescriptor is found for the attribute name the column name is taken from
there prefixed with the alias (firstname -> A0.F_NAME). |
protected boolean appendColName(TableAlias aTableAlias, PathInfo aPathInfo, boolean translate, StringBuffer buf)
{
String prefix = aPathInfo.prefix;
String suffix = aPathInfo.suffix;
String colName = getColName(aTableAlias, aPathInfo, translate);
if (prefix != null) // rebuild function contains (
{
buf.append(prefix);
}
buf.append(colName);
if (suffix != null) // rebuild function
{
buf.append(suffix);
}
return true;
} | Add the Column to the StringBuffer <br>
@param aTableAlias
@param aPathInfo
@param translate flag to indicate translation of pathInfo
@param buf
@return true if appended |
protected FieldDescriptor getFieldDescriptor(TableAlias aTableAlias, PathInfo aPathInfo)
{
FieldDescriptor fld = null;
String colName = aPathInfo.column;
if (aTableAlias != null)
{
fld = aTableAlias.cld.getFieldDescriptorByName(colName);
if (fld == null)
{
ObjectReferenceDescriptor ord = aTableAlias.cld.getObjectReferenceDescriptorByName(colName);
if (ord != null)
{
fld = getFldFromReference(aTableAlias, ord);
}
else
{
fld = getFldFromJoin(aTableAlias, colName);
}
}
}
return fld;
} | Get the FieldDescriptor for the PathInfo
@param aTableAlias
@param aPathInfo
@return FieldDescriptor |
private FieldDescriptor getFldFromJoin(TableAlias aTableAlias, String aColName)
{
FieldDescriptor fld = null;
// Search Join Structure for attribute
if (aTableAlias.joins != null)
{
Iterator itr = aTableAlias.joins.iterator();
while (itr.hasNext())
{
Join join = (Join) itr.next();
ClassDescriptor cld = join.right.cld;
if (cld != null)
{
fld = cld.getFieldDescriptorByName(aColName);
if (fld != null)
{
break;
}
}
}
}
return fld;
} | Get FieldDescriptor from joined superclass. |
private FieldDescriptor getFldFromReference(TableAlias aTableAlias, ObjectReferenceDescriptor anOrd)
{
FieldDescriptor fld = null;
if (aTableAlias == getRoot())
{
// no path expression
FieldDescriptor[] fk = anOrd.getForeignKeyFieldDescriptors(aTableAlias.cld);
if (fk.length > 0)
{
fld = fk[0];
}
}
else
{
// attribute with path expression
/**
* MBAIRD
* potentially people are referring to objects, not to the object's primary key,
* and then we need to take the primary key attribute of the referenced object
* to help them out.
*/
ClassDescriptor cld = aTableAlias.cld.getRepository().getDescriptorFor(anOrd.getItemClass());
if (cld != null)
{
fld = aTableAlias.cld.getFieldDescriptorByName(cld.getPkFields()[0].getPersistentField().getName());
}
}
return fld;
} | Get FieldDescriptor from Reference |
protected boolean appendColName(String attr, boolean useOuterJoins, UserAlias aUserAlias, StringBuffer buf)
{
AttributeInfo attrInfo = getAttributeInfo(attr, useOuterJoins, aUserAlias, getQuery().getPathClasses());
TableAlias tableAlias = attrInfo.tableAlias;
return appendColName(tableAlias, attrInfo.pathInfo, (tableAlias != null), buf);
} | Append the appropriate ColumnName to the buffer<br>
if a FIELDDESCRIPTOR is found for the Criteria the colName is taken from
there otherwise its taken from Criteria. <br>
field names in functions (ie: sum(name) ) are tried to resolve
ie: name from FIELDDESCRIPTOR , UPPER(name_test) from Criteria<br>
also resolve pathExpression adress.city or owner.konti.saldo |
protected boolean appendColName(String attr, String attrAlias, boolean useOuterJoins, UserAlias aUserAlias,
StringBuffer buf)
{
AttributeInfo attrInfo = getAttributeInfo(attr, useOuterJoins, aUserAlias, getQuery().getPathClasses());
TableAlias tableAlias = attrInfo.tableAlias;
PathInfo pi = attrInfo.pathInfo;
if (pi.suffix != null)
{
pi.suffix = pi.suffix + " as " + attrAlias;
}
else
{
pi.suffix = " as " + attrAlias;
}
return appendColName(tableAlias, pi, true, buf);
} | Append the appropriate ColumnName to the buffer<br>
if a FIELDDESCRIPTOR is found for the Criteria the colName is taken from
there otherwise its taken from Criteria. <br>
field names in functions (ie: sum(name) ) are tried to resolve
ie: name from FIELDDESCRIPTOR , UPPER(name_test) from Criteria<br>
also resolve pathExpression adress.city or owner.konti.saldo |
protected void ensureColumns(List columns, List existingColumns)
{
if (columns == null || columns.isEmpty())
{
return;
}
Iterator iter = columns.iterator();
while (iter.hasNext())
{
FieldHelper cf = (FieldHelper) iter.next();
if (!existingColumns.contains(cf.name))
{
getAttributeInfo(cf.name, false, null, getQuery().getPathClasses());
}
}
} | Builds the Join for columns if they are not found among the existingColumns.
@param columns the list of columns represented by Criteria.Field to ensure
@param existingColumns the list of column names (String) that are already appended |
protected List ensureColumns(List columns, List existingColumns, StringBuffer buf)
{
if (columns == null || columns.isEmpty())
{
return existingColumns;
}
Iterator iter = columns.iterator();
int ojb_col = existingColumns.size() + 1;
while (iter.hasNext())
{
FieldHelper cf = (FieldHelper) iter.next();
if (!existingColumns.contains(cf.name))
{
existingColumns.add(cf.name);
buf.append(",");
appendColName(cf.name, "ojb_col_" + ojb_col, false, null, buf);
ojb_col++;
}
}
return existingColumns;
} | Builds the Join for columns if they are not found among the existingColumns.
These <b>columns are added to the statement</b> using a column-alias "ojb_col_x",
x being the number of existing columns
@param columns the list of columns represented by Criteria.Field to ensure
@param existingColumns the list of column names (String) that are already appended
@param buf the statement
@return List of existingColumns including ojb_col_x |
protected void appendWhereClause(StringBuffer where, Criteria crit, StringBuffer stmt)
{
if (where.length() == 0)
{
where = null;
}
if (where != null || (crit != null && !crit.isEmpty()))
{
stmt.append(" WHERE ");
appendClause(where, crit, stmt);
}
} | appends a WHERE-clause to the Statement
@param where
@param crit
@param stmt |
protected void appendHavingClause(StringBuffer having, Criteria crit, StringBuffer stmt)
{
if (having.length() == 0)
{
having = null;
}
if (having != null || crit != null)
{
stmt.append(" HAVING ");
appendClause(having, crit, stmt);
}
} | appends a HAVING-clause to the Statement
@param having
@param crit
@param stmt |
protected void appendClause(StringBuffer clause, Criteria crit, StringBuffer stmt)
{
/**
* MBAIRD
* when generating the "WHERE/HAVING" clause we need to append the criteria for multi-mapped
* tables. We only need to do this for the root classdescriptor and not for joined tables
* because we assume you cannot make a relation of the wrong type upon insertion. Of course,
* you COULD mess the data up manually and this would cause a problem.
*/
if (clause != null)
{
stmt.append(clause.toString());
}
if (crit != null)
{
if (clause == null)
{
stmt.append(asSQLStatement(crit));
}
else
{
stmt.append(" AND (");
stmt.append(asSQLStatement(crit));
stmt.append(")");
}
}
} | appends a WHERE/HAVING-clause to the Statement
@param clause
@param crit
@param stmt |
private void appendBetweenCriteria(TableAlias alias, PathInfo pathInfo, BetweenCriteria c, StringBuffer buf)
{
appendColName(alias, pathInfo, c.isTranslateAttribute(), buf);
buf.append(c.getClause());
appendParameter(c.getValue(), buf);
buf.append(" AND ");
appendParameter(c.getValue2(), buf);
} | Answer the SQL-Clause for a BetweenCriteria
@param alias
@param pathInfo
@param c BetweenCriteria
@param buf |
private void appendExistsCriteria(ExistsCriteria c, StringBuffer buf)
{
Query subQuery = (Query) c.getValue();
buf.append(c.getClause());
appendSubQuery(subQuery, buf);
} | Answer the SQL-Clause for an ExistsCriteria
@param c ExistsCriteria |
private void appendFieldCriteria(TableAlias alias, PathInfo pathInfo, FieldCriteria c, StringBuffer buf)
{
appendColName(alias, pathInfo, c.isTranslateAttribute(), buf);
buf.append(c.getClause());
if (c.isTranslateField())
{
appendColName((String) c.getValue(), false, c.getUserAlias(), buf);
}
else
{
buf.append(c.getValue());
}
} | Answer the SQL-Clause for a FieldCriteria<br>
The value of the FieldCriteria will be translated
@param alias
@param pathInfo
@param c ColumnCriteria
@param buf |
private String getIndirectionTableColName(TableAlias mnAlias, String path)
{
int dotIdx = path.lastIndexOf(".");
String column = path.substring(dotIdx);
return mnAlias.alias + column;
} | Get the column name from the indirection table.
@param mnAlias
@param path |
private void appendInCriteria(TableAlias alias, PathInfo pathInfo, InCriteria c, StringBuffer buf)
{
appendColName(alias, pathInfo, c.isTranslateAttribute(), buf);
buf.append(c.getClause());
if (c.getValue() instanceof Collection)
{
Object[] values = ((Collection) c.getValue()).toArray();
int size = ((Collection) c.getValue()).size();
buf.append("(");
if (size > 0)
{
for (int i = 0; i < size - 1; i++)
{
appendParameter(values[i], buf);
buf.append(",");
}
appendParameter(values[size - 1], buf);
}
buf.append(")");
}
else
{
appendParameter(c.getValue(), buf);
}
} | Answer the SQL-Clause for an InCriteria
@param alias
@param pathInfo
@param c InCriteria
@param buf |
private void appendNullCriteria(TableAlias alias, PathInfo pathInfo, NullCriteria c, StringBuffer buf)
{
appendColName(alias, pathInfo, c.isTranslateAttribute(), buf);
buf.append(c.getClause());
} | Answer the SQL-Clause for a NullCriteria
@param alias
@param pathInfo
@param c NullCriteria
@param buf |
private void appendSelectionCriteria(TableAlias alias, PathInfo pathInfo, SelectionCriteria c, StringBuffer buf)
{
appendColName(alias, pathInfo, c.isTranslateAttribute(), buf);
buf.append(c.getClause());
appendParameter(c.getValue(), buf);
} | Answer the SQL-Clause for a SelectionCriteria
@param c
@param buf |
private void appendLikeCriteria(TableAlias alias, PathInfo pathInfo, LikeCriteria c, StringBuffer buf)
{
appendColName(alias, pathInfo, c.isTranslateAttribute(), buf);
buf.append(c.getClause());
appendParameter(c.getValue(), buf);
buf.append(m_platform.getEscapeClause(c));
} | Answer the SQL-Clause for a LikeCriteria
@param c
@param buf |
protected void appendCriteria(TableAlias alias, PathInfo pathInfo, SelectionCriteria c, StringBuffer buf)
{
if (c instanceof FieldCriteria)
{
appendFieldCriteria(alias, pathInfo, (FieldCriteria) c, buf);
}
else if (c instanceof NullCriteria)
{
appendNullCriteria(alias, pathInfo, (NullCriteria) c, buf);
}
else if (c instanceof BetweenCriteria)
{
appendBetweenCriteria(alias, pathInfo, (BetweenCriteria) c, buf);
}
else if (c instanceof InCriteria)
{
appendInCriteria(alias, pathInfo, (InCriteria) c, buf);
}
else if (c instanceof SqlCriteria)
{
appendSQLCriteria((SqlCriteria) c, buf);
}
else if (c instanceof ExistsCriteria)
{
appendExistsCriteria((ExistsCriteria) c, buf);
}
else if (c instanceof LikeCriteria)
{
appendLikeCriteria(alias, pathInfo, (LikeCriteria) c, buf);
}
else
{
appendSelectionCriteria(alias, pathInfo, c, buf);
}
} | Answer the SQL-Clause for a SelectionCriteria
@param alias
@param pathInfo
@param c SelectionCriteria
@param buf |
protected void appendSQLClause(SelectionCriteria c, StringBuffer buf)
{
// BRJ : handle SqlCriteria
if (c instanceof SqlCriteria)
{
buf.append(c.getAttribute());
return;
}
// BRJ : criteria attribute is a query
if (c.getAttribute() instanceof Query)
{
Query q = (Query) c.getAttribute();
buf.append("(");
buf.append(getSubQuerySQL(q));
buf.append(")");
buf.append(c.getClause());
appendParameter(c.getValue(), buf);
return;
}
AttributeInfo attrInfo = getAttributeInfo((String) c.getAttribute(), false, c.getUserAlias(), c.getPathClasses());
TableAlias alias = attrInfo.tableAlias;
if (alias != null)
{
boolean hasExtents = alias.hasExtents();
if (hasExtents)
{
// BRJ : surround with braces if alias has extents
buf.append("(");
appendCriteria(alias, attrInfo.pathInfo, c, buf);
c.setNumberOfExtentsToBind(alias.extents.size());
Iterator iter = alias.iterateExtents();
while (iter.hasNext())
{
TableAlias tableAlias = (TableAlias) iter.next();
buf.append(" OR ");
appendCriteria(tableAlias, attrInfo.pathInfo, c, buf);
}
buf.append(")");
}
else
{
// no extents
appendCriteria(alias, attrInfo.pathInfo, c, buf);
}
}
else
{
// alias null
appendCriteria(alias, attrInfo.pathInfo, c, buf);
}
} | Answer the SQL-Clause for a SelectionCriteria
If the Criteria references a class with extents an OR-Clause is
added for each extent
@param c SelectionCriteria |
private void appendParameter(Object value, StringBuffer buf)
{
if (value instanceof Query)
{
appendSubQuery((Query) value, buf);
}
else
{
buf.append("?");
}
} | Append the Parameter
Add the place holder ? or the SubQuery
@param value the value of the criteria |
private void appendSubQuery(Query subQuery, StringBuffer buf)
{
buf.append(" (");
buf.append(getSubQuerySQL(subQuery));
buf.append(") ");
} | Append a SubQuery the SQL-Clause
@param subQuery the subQuery value of SelectionCriteria |
private String getSubQuerySQL(Query subQuery)
{
ClassDescriptor cld = getRoot().cld.getRepository().getDescriptorFor(subQuery.getSearchClass());
String sql;
if (subQuery instanceof QueryBySQL)
{
sql = ((QueryBySQL) subQuery).getSql();
}
else
{
sql = new SqlSelectStatement(this, m_platform, cld, subQuery, m_logger).getStatement();
}
return sql;
} | Convert subQuery to SQL
@param subQuery the subQuery value of SelectionCriteria |
private TableAlias getTableAlias(String aPath, boolean useOuterJoins, UserAlias aUserAlias, String[] fieldRef, Map pathClasses)
{
TableAlias curr, prev, indirect;
String attr, attrPath = null;
ObjectReferenceDescriptor ord;
CollectionDescriptor cod;
ClassDescriptor cld;
Object[] prevKeys;
Object[] keys;
ArrayList descriptors;
boolean outer = useOuterJoins;
int pathLength;
List hintClasses = null;
String pathAlias = aUserAlias == null ? null : aUserAlias.getAlias(aPath);
if (pathClasses != null)
{
hintClasses = (List) pathClasses.get(aPath);
}
curr = getTableAliasForPath(aPath, pathAlias, hintClasses);
if (curr != null)
{
return curr;
}
descriptors = getRoot().cld.getAttributeDescriptorsForPath(aPath, pathClasses);
prev = getRoot();
if (descriptors == null || descriptors.size() == 0)
{
if (prev.hasJoins())
{
for (Iterator itr = prev.iterateJoins(); itr.hasNext();)
{
prev = ((Join) itr.next()).left;
descriptors = prev.cld.getAttributeDescriptorsForPath(aPath, pathClasses);
if (descriptors.size() > 0)
{
break;
}
}
}
}
pathLength = descriptors.size();
for (int i = 0; i < pathLength; i++)
{
if (!(descriptors.get(i) instanceof ObjectReferenceDescriptor))
{
// only use Collection- and ObjectReferenceDescriptor
continue;
}
ord = (ObjectReferenceDescriptor) descriptors.get(i);
attr = ord.getAttributeName();
if (attrPath == null)
{
attrPath = attr;
}
else
{
attrPath = attrPath + "." + attr;
}
// use clas hints for path
if (pathClasses != null)
{
hintClasses = (List) pathClasses.get(attrPath);
}
// look for outer join hint
outer = outer || getQuery().isPathOuterJoin(attrPath);
// look for 1:n or m:n
if (ord instanceof CollectionDescriptor)
{
cod = (CollectionDescriptor) ord;
cld = getItemClassDescriptor(cod, hintClasses);
if (!cod.isMtoNRelation())
{
prevKeys = prev.cld.getPkFields();
keys = cod.getForeignKeyFieldDescriptors(cld);
}
else
{
String mnAttrPath = attrPath + "*";
String mnUserAlias = (aUserAlias == null ? null : aUserAlias + "*");
indirect = getTableAliasForPath(mnAttrPath, mnUserAlias, null);
if (indirect == null)
{
indirect = createTableAlias(cod.getIndirectionTable(), mnAttrPath, mnUserAlias);
// we need two Joins for m:n
// 1.) prev class to indirectionTable
prevKeys = prev.cld.getPkFields();
keys = cod.getFksToThisClass();
addJoin(prev, prevKeys, indirect, keys, outer, attr + "*");
}
// 2.) indirectionTable to the current Class
prev = indirect;
prevKeys = cod.getFksToItemClass();
keys = cld.getPkFields();
}
}
else
{
// must be n:1 or 1:1
cld = getItemClassDescriptor(ord, hintClasses);
// BRJ : if ord is taken from 'super' we have to change prev accordingly
if (!prev.cld.equals(ord.getClassDescriptor()))
{
TableAlias ordAlias = getTableAliasForClassDescriptor(ord.getClassDescriptor());
Join join = prev.getJoin(ordAlias);
if (join != null)
{
join.isOuter = join.isOuter || outer;
}
prev = ordAlias;
}
prevKeys = ord.getForeignKeyFieldDescriptors(prev.cld);
keys = cld.getPkFields();
// [olegnitz]
// a special case: the last element of the path is
// reference and the field is one of PK fields =>
// use the correspondent foreign key field, don't add the join
if ((fieldRef != null) && (i == (pathLength - 1)))
{
FieldDescriptor[] pk = cld.getPkFields();
for (int j = 0; j < pk.length; j++)
{
if (pk[j].getAttributeName().equals(fieldRef[0]))
{
fieldRef[0] = ((FieldDescriptor) prevKeys[j]).getAttributeName();
return prev;
}
}
}
}
pathAlias = aUserAlias == null ? null : aUserAlias.getAlias(attrPath);
curr = getTableAliasForPath(attrPath, pathAlias, hintClasses);
if (curr == null)
{
curr = createTableAlias(cld, attrPath, pathAlias, hintClasses);
outer = outer || (curr.cld == prev.cld) || curr.hasExtents() || useOuterJoins;
addJoin(prev, prevKeys, curr, keys, outer, attr);
buildSuperJoinTree(curr, cld, aPath, outer);
}
prev = curr;
}
m_logger.debug("Result of getTableAlias(): " + curr);
return curr;
} | Get TableAlias by the path from the target table of the query.
@param aPath the path from the target table of the query to this TableAlias.
@param useOuterJoins use outer join to join this table with the previous
table in the path.
@param aUserAlias if specified, overrides alias in crit
@param fieldRef String[1] contains the field name.
In the case of related table's primary key the "related.pk" attribute
must not add new join, but use the value of foreign key
@param pathClasses the hints |
private void addJoin(TableAlias left, Object[] leftKeys, TableAlias right, Object[] rightKeys, boolean outer,
String name)
{
TableAlias extAlias, rightCopy;
left.addJoin(new Join(left, leftKeys, right, rightKeys, outer, name));
// build join between left and extents of right
if (right.hasExtents())
{
for (int i = 0; i < right.extents.size(); i++)
{
extAlias = (TableAlias) right.extents.get(i);
FieldDescriptor[] extKeys = getExtentFieldDescriptors(extAlias, (FieldDescriptor[]) rightKeys);
left.addJoin(new Join(left, leftKeys, extAlias, extKeys, true, name));
}
}
// we need to copy the alias on the right for each extent on the left
if (left.hasExtents())
{
for (int i = 0; i < left.extents.size(); i++)
{
extAlias = (TableAlias) left.extents.get(i);
FieldDescriptor[] extKeys = getExtentFieldDescriptors(extAlias, (FieldDescriptor[]) leftKeys);
rightCopy = right.copy("C" + i);
// copies are treated like normal extents
right.extents.add(rightCopy);
right.extents.addAll(rightCopy.extents);
addJoin(extAlias, extKeys, rightCopy, rightKeys, true, name);
}
}
} | add a join between two aliases
TODO BRJ : This needs refactoring, it looks kind of weird
no extents
A1 -> A2
extents on the right
A1 -> A2
A1 -> A2E0
extents on the left : copy alias on right, extents point to copies
A1 -> A2
A1E0 -> A2C0
extents on the left and right
A1 -> A2
A1 -> A2E0
A1E0 -> A2C0
A1E0 -> A2E0C0
@param left
@param leftKeys
@param right
@param rightKeys
@param outer
@param name |
private FieldDescriptor[] getExtentFieldDescriptors(TableAlias extAlias, FieldDescriptor[] fds)
{
FieldDescriptor[] result = new FieldDescriptor[fds.length];
for (int i = 0; i < fds.length; i++)
{
result[i] = extAlias.cld.getFieldDescriptorByName(fds[i].getAttributeName());
}
return result;
} | Get the FieldDescriptors of the extent based on the FieldDescriptors of the parent. |
private TableAlias createTableAlias(ClassDescriptor aCld, String aPath, String aUserAlias, List hints)
{
if (aUserAlias == null)
{
return createTableAlias(aCld, hints, aPath);
}
else
{
return createTableAlias(aCld, hints, aUserAlias + ALIAS_SEPARATOR + aPath);
}
} | Create a TableAlias for path or userAlias
@param aCld
@param aPath
@param aUserAlias
@param hints a List os Class objects to be used as hints for path expressions
@return TableAlias |
private TableAlias createTableAlias(ClassDescriptor cld, List hints, String path)
{
TableAlias alias;
boolean lookForExtents = false;
if (!cld.getExtentClasses().isEmpty() && path.length() > 0)
{
lookForExtents = true;
}
String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++; // m_pathToAlias.size();
alias = new TableAlias(cld, aliasName, lookForExtents, hints);
setTableAliasForPath(path, hints, alias);
return alias;
} | Create new TableAlias for path
@param cld the class descriptor for the TableAlias
@param path the path from the target table of the query to this TableAlias.
@param hints a List of Class objects to be used on path expressions |
private TableAlias createTableAlias(String aTable, String aPath, String aUserAlias)
{
if (aUserAlias == null)
{
return createTableAlias(aTable, aPath);
}
else
{
return createTableAlias(aTable, aUserAlias + ALIAS_SEPARATOR + aPath);
}
} | Create a TableAlias for path or userAlias
@param aTable
@param aPath
@param aUserAlias
@return TableAlias |
private TableAlias createTableAlias(String table, String path)
{
TableAlias alias;
if (table == null)
{
getLogger().warn("Creating TableAlias without table for path: " + path);
}
String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++; // + m_pathToAlias.size();
alias = new TableAlias(table, aliasName);
setTableAliasForPath(path, null, alias);
m_logger.debug("createTableAlias2: path: " + path + " tableAlias: " + alias);
return alias;
} | Create new TableAlias for path
@param table the table name
@param path the path from the target table of the query to this TableAlias. |
private TableAlias getTableAliasForPath(String aPath, List hintClasses)
{
return (TableAlias) m_pathToAlias.get(buildAliasKey(aPath, hintClasses));
} | Answer the TableAlias for aPath
@param aPath
@param hintClasses
@return TableAlias, null if none |
private void setTableAliasForPath(String aPath, List hintClasses, TableAlias anAlias)
{
m_pathToAlias.put(buildAliasKey(aPath, hintClasses), anAlias);
} | Set the TableAlias for aPath
@param aPath
@param hintClasses
@param TableAlias |
private String buildAliasKey(String aPath, List hintClasses)
{
if (hintClasses == null || hintClasses.isEmpty())
{
return aPath;
}
StringBuffer buf = new StringBuffer(aPath);
for (Iterator iter = hintClasses.iterator(); iter.hasNext();)
{
Class hint = (Class) iter.next();
buf.append(" ");
buf.append(hint.getName());
}
return buf.toString();
} | Build the key for the TableAlias based on the path and the hints
@param aPath
@param hintClasses
@return the key for the TableAlias |
private void setTableAliasForClassDescriptor(ClassDescriptor aCld, TableAlias anAlias)
{
if (m_cldToAlias.get(aCld) == null)
{
m_cldToAlias.put(aCld, anAlias);
}
} | Set the TableAlias for ClassDescriptor |
private TableAlias getTableAliasForPath(String aPath, String aUserAlias, List hintClasses)
{
if (aUserAlias == null)
{
return getTableAliasForPath(aPath, hintClasses);
}
else
{
return getTableAliasForPath(aUserAlias + ALIAS_SEPARATOR + aPath, hintClasses);
}
} | Answer the TableAlias for aPath or aUserAlias
@param aPath
@param aUserAlias
@param hintClasses
@return TableAlias, null if none |
private ClassDescriptor getItemClassDescriptor(ObjectReferenceDescriptor ord, List hintClasses)
{
DescriptorRepository repo = ord.getClassDescriptor().getRepository();
if (hintClasses == null || hintClasses.isEmpty())
{
return repo.getDescriptorFor(ord.getItemClass());
}
Class resultClass = (Class) hintClasses.get(0);
for (Iterator iter = hintClasses.iterator(); iter.hasNext();)
{
Class clazz = (Class) iter.next();
Class superClazz = clazz.getSuperclass();
if (superClazz != null && resultClass.equals(superClazz.getSuperclass()))
{
continue; // skip if we already have a super superclass
}
if (hintClasses.contains(superClazz))
{
resultClass = superClazz; // use superclass if it's in the hints
}
}
return repo.getDescriptorFor(resultClass);
} | Answer the ClassDescriptor for itemClass for an ObjectReferenceDescriptor
check optional hint. The returned Class is to highest superclass contained in the hint list.
TODO: add super ClassDescriptor |
protected void appendOrderByClause(List orderByFields, List selectedFields, StringBuffer buf)
{
if (orderByFields == null || orderByFields.size() == 0)
{
return;
}
buf.append(" ORDER BY ");
for (int i = 0; i < orderByFields.size(); i++)
{
FieldHelper cf = (FieldHelper) orderByFields.get(i);
int colNumber = selectedFields.indexOf(cf.name);
if (i > 0)
{
buf.append(",");
}
if (colNumber >= 0)
{
buf.append(colNumber + 1);
}
else
{
appendColName(cf.name, false, null, buf);
}
if (!cf.isAscending)
{
buf.append(" DESC");
}
}
} | Appends the ORDER BY clause for the Query.
<br>
If the orderByField is found in the list of selected fields it's index is added.
Otherwise it's name is added.
@param orderByFields
@param selectedFields the names of the fields in the SELECT clause
@param buf |
protected void appendGroupByClause(List groupByFields, StringBuffer buf)
{
if (groupByFields == null || groupByFields.size() == 0)
{
return;
}
buf.append(" GROUP BY ");
for (int i = 0; i < groupByFields.size(); i++)
{
FieldHelper cf = (FieldHelper) groupByFields.get(i);
if (i > 0)
{
buf.append(",");
}
appendColName(cf.name, false, null, buf);
}
} | Appends the GROUP BY clause for the Query
@param groupByFields
@param buf |
protected void appendTableWithJoins(TableAlias alias, StringBuffer where, StringBuffer buf)
{
int stmtFromPos = 0;
byte joinSyntax = getJoinSyntaxType();
if (joinSyntax == SQL92_JOIN_SYNTAX)
{
stmtFromPos = buf.length(); // store position of join (by: Terry Dexter)
}
if (alias == getRoot())
{
// BRJ: also add indirection table to FROM-clause for MtoNQuery
if (getQuery() instanceof MtoNQuery)
{
MtoNQuery mnQuery = (MtoNQuery)m_query;
buf.append(getTableAliasForPath(mnQuery.getIndirectionTable(), null).getTableAndAlias());
buf.append(", ");
}
buf.append(alias.getTableAndAlias());
}
else if (joinSyntax != SQL92_NOPAREN_JOIN_SYNTAX)
{
buf.append(alias.getTableAndAlias());
}
if (!alias.hasJoins())
{
return;
}
for (Iterator it = alias.iterateJoins(); it.hasNext();)
{
Join join = (Join) it.next();
if (joinSyntax == SQL92_JOIN_SYNTAX)
{
appendJoinSQL92(join, where, buf);
if (it.hasNext())
{
buf.insert(stmtFromPos, "(");
buf.append(")");
}
}
else if (joinSyntax == SQL92_NOPAREN_JOIN_SYNTAX)
{
appendJoinSQL92NoParen(join, where, buf);
}
else
{
appendJoin(where, buf, join);
}
}
} | Appends to the statement table and all tables joined to it.
@param alias the table alias
@param where append conditions for WHERE clause here |
Subsets and Splits