code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
public int getCount(Class target)
{
PersistenceBroker broker = ((HasBroker) odmg.currentTransaction()).getBroker();
int result = broker.getCount(new QueryByCriteria(target));
return result;
} | Return the count of all objects found
for given class, using the PB-api within
ODMG - this may change in further versions. |
public boolean close()
{
if (getDelegate() == null) return true;
try
{
PersistenceBrokerThreadMapping.unsetCurrentPersistenceBroker(getPBKey(), this);
super.close();
}
finally
{
/*
here we destroy the handle. set the
underlying PB instance 'null', thus it's not
possible to corrupt a closed PB instance.
*/
setDelegate(null);
}
return true;
} | Destroy this handle and return the underlying (wrapped) PB instance
to pool (when using default implementation of PersistenceBrokerFactory),
unset this instance from {@link PersistenceBrokerThreadMapping}. |
@Override
public void format(final LoggingEvent event, final StringBuffer toAppendTo) {
ThrowableInformation throwableInformation = event.getThrowableInformation();
if (throwableInformation != null) {
Throwable throwable = throwableInformation.getThrowable();
if (throwable instanceof ApplicationExceptionInterface) {// NOPMD
final ApplicationExceptionInterface ApplicationExceptionInterface = (ApplicationExceptionInterface) throwable;
toAppendTo.append("[Error code: ");
toAppendTo.append(ApplicationExceptionInterface.getErrorCode() == null ? "%NO_ERROR_CODE%" : ApplicationExceptionInterface.getErrorCode().toString());
toAppendTo.append("] ");
}
}
} | {@inheritDoc} |
public void setClasspath(Path classpath)
{
if (_classpath == null)
{
_classpath = classpath;
}
else
{
_classpath.append(classpath);
}
log("Verification classpath is "+ _classpath,
Project.MSG_VERBOSE);
} | Set the classpath for loading the driver.
@param classpath the classpath |
public void setClasspathRef(Reference r)
{
createClasspath().setRefid(r);
log("Verification classpath is "+ _classpath,
Project.MSG_VERBOSE);
} | Set the classpath for loading the driver using the classpath reference.
@param r reference to the classpath |
public Class getPersistentFieldClass()
{
if (m_persistenceClass == null)
{
Properties properties = new Properties();
try
{
this.logWarning("Loading properties file: " + getPropertiesFile());
properties.load(new FileInputStream(getPropertiesFile()));
}
catch (IOException e)
{
this.logWarning("Could not load properties file '" + getPropertiesFile()
+ "'. Using PersistentFieldDefaultImpl.");
e.printStackTrace();
}
try
{
String className = properties.getProperty("PersistentFieldClass");
m_persistenceClass = loadClass(className);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
m_persistenceClass = PersistentFieldPrivilegedImpl.class;
}
logWarning("PersistentFieldClass: " + m_persistenceClass.toString());
}
return m_persistenceClass;
} | Returns the Class object of the class specified in the OJB.properties
file for the "PersistentFieldClass" property.
@return Class The Class object of the "PersistentFieldClass" class
specified in the OJB.properties file. |
@Override
public void visit(FeatureTypeStyle fts) {
FeatureTypeStyle copy = new FeatureTypeStyleImpl(
(FeatureTypeStyleImpl) fts);
Rule[] rules = fts.getRules();
int length = rules.length;
Rule[] rulesCopy = new Rule[length];
for (int i = 0; i < length; i++) {
if (rules[i] != null) {
rules[i].accept(this);
rulesCopy[i] = (Rule) pages.pop();
}
}
copy.setRules(rulesCopy);
if (fts.getTransformation() != null) {
copy.setTransformation(copy(fts.getTransformation()));
}
if (STRICT && !copy.equals(fts)) {
throw new IllegalStateException(
"Was unable to duplicate provided FeatureTypeStyle:" + fts);
}
pages.push(copy);
} | Overridden to add transform. |
@Override
public void visit(Rule rule) {
Rule copy = null;
Filter filterCopy = null;
if (rule.getFilter() != null) {
Filter filter = rule.getFilter();
filterCopy = copy(filter);
}
List<Symbolizer> symsCopy = new ArrayList<Symbolizer>();
for (Symbolizer sym : rule.symbolizers()) {
if (!skipSymbolizer(sym)) {
Symbolizer symCopy = copy(sym);
symsCopy.add(symCopy);
}
}
Graphic[] legendCopy = rule.getLegendGraphic();
for (int i = 0; i < legendCopy.length; i++) {
legendCopy[i] = copy(legendCopy[i]);
}
Description descCopy = rule.getDescription();
descCopy = copy(descCopy);
copy = sf.createRule();
copy.symbolizers().addAll(symsCopy);
copy.setDescription(descCopy);
copy.setLegendGraphic(legendCopy);
copy.setName(rule.getName());
copy.setFilter(filterCopy);
copy.setElseFilter(rule.isElseFilter());
copy.setMaxScaleDenominator(rule.getMaxScaleDenominator());
copy.setMinScaleDenominator(rule.getMinScaleDenominator());
if (STRICT && !copy.equals(rule)) {
throw new IllegalStateException(
"Was unable to duplicate provided Rule:" + rule);
}
pages.push(copy);
} | Overridden to skip some symbolizers. |
private void initComponents()//GEN-BEGIN:initComponents
{
jSplitPane1 = new javax.swing.JSplitPane();
jScrlTree = new javax.swing.JScrollPane();
jTreeDatabase = new javax.swing.JTree();
jScrlProperty = new javax.swing.JScrollPane();
jToolBar1 = new javax.swing.JToolBar();
jTextField1 = new javax.swing.JTextField();
setClosable(true);
setIconifiable(true);
setMaximizable(true);
setResizable(true);
setTitle("Database");
setPreferredSize(new java.awt.Dimension(300, 300));
jTreeDatabase.setRootVisible(false);
jTreeDatabase.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener()
{
public void valueChanged(javax.swing.event.TreeSelectionEvent evt)
{
jTreeDatabaseValueChanged(evt);
}
});
jScrlTree.setViewportView(jTreeDatabase);
jSplitPane1.setLeftComponent(jScrlTree);
jSplitPane1.setRightComponent(jScrlProperty);
getContentPane().add(jSplitPane1, java.awt.BorderLayout.CENTER);
jTextField1.setEditable(false);
jTextField1.setText("jTextField1");
jTextField1.setBorder(null);
jTextField1.setOpaque(false);
jToolBar1.add(jTextField1);
getContentPane().add(jToolBar1, java.awt.BorderLayout.SOUTH);
pack();
} | 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 jTreeDatabaseValueChanged (javax.swing.event.TreeSelectionEvent evt)//GEN-FIRST:event_jTreeDatabaseValueChanged
{//GEN-HEADEREND:event_jTreeDatabaseValueChanged
// Add your handling code here:
Object selectedObject = evt.getPath().getLastPathComponent();
if (selectedObject instanceof PropertyEditorTarget)
{
PropertyEditorTarget p = (PropertyEditorTarget)selectedObject;
if (p.getPropertyEditorClass() != null)
{
try
{
if(!this.hmPropertyEditors.containsKey(p.getPropertyEditorClass()))
{
this.hmPropertyEditors.put(p.getPropertyEditorClass(), p.getPropertyEditorClass().newInstance());
}
PropertyEditor propertyEditor = (PropertyEditor)hmPropertyEditors.get(p.getPropertyEditorClass());
this.jScrlProperty.setViewportView(propertyEditor);
propertyEditor.setEditorTarget(p);
}
catch (Throwable t)
{
t.printStackTrace();
this.jScrlProperty.setViewportView(null);
}
}
else
{
this.jScrlProperty.setViewportView(null);
}
}
else
{
this.jScrlProperty.setViewportView(null);
}
} | GEN-END:initComponents |
private void registerSynchronization(TransactionImpl odmgTrans, Transaction transaction)
{
// todo only need for development
if (odmgTrans == null || transaction == null)
{
log.error("One of the given parameters was null --> cannot do synchronization!" +
" omdg transaction was null: " + (odmgTrans == null) +
", external transaction was null: " + (transaction == null));
return;
}
int status = -1; // default status.
try
{
status = transaction.getStatus();
if (status != Status.STATUS_ACTIVE)
{
throw new OJBRuntimeException(
"Transaction synchronization failed - wrong status of external container tx: " +
getStatusString(status));
}
}
catch (SystemException e)
{
throw new OJBRuntimeException("Can't read status of external tx", e);
}
try
{
//Sequence of the following method calls is significant
// 1. register the synchronization with the ODMG notion of a transaction.
transaction.registerSynchronization((J2EETransactionImpl) odmgTrans);
// 2. mark the ODMG transaction as being in a JTA Transaction
// Associate external transaction with the odmg transaction.
txRepository.set(new TxBuffer(odmgTrans, transaction));
}
catch (Exception e)
{
log.error("Cannot associate PersistenceBroker with running Transaction", e);
throw new OJBRuntimeException(
"Transaction synchronization failed - wrong status of external container tx", e);
}
} | Do synchronization of the given J2EE ODMG Transaction |
private TransactionManager getTransactionManager()
{
TransactionManager retval = null;
try
{
if (log.isDebugEnabled()) log.debug("getTransactionManager called");
retval = TransactionManagerFactoryFactory.instance().getTransactionManager();
}
catch (TransactionManagerFactoryException e)
{
log.warn("Exception trying to obtain TransactionManager from Factory", e);
e.printStackTrace();
}
return retval;
} | Return the TransactionManager of the external app |
public TransactionImpl getTransaction()
{
TxBuffer buf = (TxBuffer) txRepository.get();
return buf != null ? buf.getInternTx() : null;
} | Returns the current transaction based on the JTA Transaction or <code>null</code>
if no transaction was found. |
public void abortExternalTx(TransactionImpl odmgTrans)
{
if (log.isDebugEnabled()) log.debug("abortExternTransaction was called");
if (odmgTrans == null) return;
TxBuffer buf = (TxBuffer) txRepository.get();
Transaction extTx = buf != null ? buf.getExternTx() : null;
try
{
if (extTx != null && extTx.getStatus() == Status.STATUS_ACTIVE)
{
if(log.isDebugEnabled())
{
log.debug("Set extern transaction to rollback");
}
extTx.setRollbackOnly();
}
}
catch (Exception ignore)
{
}
txRepository.set(null);
} | Abort an active extern transaction associated with the given PB. |
public void check(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException
{
ensureColumn(fieldDef, checkLevel);
ensureJdbcType(fieldDef, checkLevel);
ensureConversion(fieldDef, checkLevel);
ensureLength(fieldDef, checkLevel);
ensurePrecisionAndScale(fieldDef, checkLevel);
checkLocking(fieldDef, checkLevel);
checkSequenceName(fieldDef, checkLevel);
checkId(fieldDef, checkLevel);
if (fieldDef.isAnonymous())
{
checkAnonymous(fieldDef, checkLevel);
}
else
{
checkReadonlyAccessForNativePKs(fieldDef, checkLevel);
}
} | Checks the given field descriptor.
@param fieldDef The field descriptor
@param checkLevel The amount of checks to perform
@exception ConstraintException If a constraint has been violated |
private void ensureColumn(FieldDescriptorDef fieldDef, String checkLevel)
{
if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN))
{
String javaname = fieldDef.getName();
if (fieldDef.isNested())
{
int pos = javaname.indexOf("::");
// we convert nested names ('_' for '::')
if (pos > 0)
{
StringBuffer newJavaname = new StringBuffer(javaname.substring(0, pos));
int lastPos = pos + 2;
do
{
pos = javaname.indexOf("::", lastPos);
newJavaname.append("_");
if (pos > 0)
{
newJavaname.append(javaname.substring(lastPos, pos));
lastPos = pos + 2;
}
else
{
newJavaname.append(javaname.substring(lastPos));
}
}
while (pos > 0);
javaname = newJavaname.toString();
}
}
fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN, javaname);
}
} | Constraint that ensures that the field has a column property. If none is specified, then
the name of the field is used.
@param fieldDef The field descriptor
@param checkLevel The current check level (this constraint is checked in all levels) |
private void ensureJdbcType(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException
{
if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE))
{
if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_JDBC_TYPE))
{
throw new ConstraintException("No jdbc-type specified for the field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName());
}
fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_JDBC_TYPE));
if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_CONVERSION) && fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION))
{
fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_CONVERSION, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION));
}
}
else
{
// we could let XDoclet check the type for field declarations but not for modifications (as we could
// not specify the empty string anymore)
String jdbcType = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE);
if (!_jdbcTypes.containsKey(jdbcType))
{
throw new ConstraintException("The field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName()+" specifies the invalid jdbc type "+jdbcType);
}
}
} | Constraint that ensures that the field has a jdbc type. If none is specified, then
the default type is used (which has been determined when the field descriptor was added)
and - if necessary - the default conversion is set.
@param fieldDef The field descriptor
@param checkLevel The current check level (this constraint is checked in all levels)
@exception ConstraintException If the constraint has been violated |
private void ensureConversion(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException
{
if (CHECKLEVEL_NONE.equals(checkLevel))
{
return;
}
// we issue a warning if we encounter a field with a java.util.Date java type without a conversion
if ("java.util.Date".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JAVA_TYPE)) &&
!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_CONVERSION))
{
LogHelper.warn(true,
FieldDescriptorConstraints.class,
"ensureConversion",
"The field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName()+
" of type java.util.Date is directly mapped to jdbc-type "+
fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)+
". However, most JDBC drivers can't handle java.util.Date directly so you might want to "+
" use a conversion for converting it to a JDBC datatype like TIMESTAMP.");
}
String conversionClass = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_CONVERSION);
if (((conversionClass == null) || (conversionClass.length() == 0)) &&
fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION) &&
fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_JDBC_TYPE).equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)))
{
conversionClass = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_CONVERSION);
fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_CONVERSION, conversionClass);
}
// now checking
if (CHECKLEVEL_STRICT.equals(checkLevel) && (conversionClass != null) && (conversionClass.length() > 0))
{
InheritanceHelper helper = new InheritanceHelper();
try
{
if (!helper.isSameOrSubTypeOf(conversionClass, CONVERSION_INTERFACE))
{
throw new ConstraintException("The conversion class specified for field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName()+" does not implement the necessary interface "+CONVERSION_INTERFACE);
}
}
catch (ClassNotFoundException ex)
{
throw new ConstraintException("The class "+ex.getMessage()+" hasn't been found on the classpath while checking the conversion class specified for field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName());
}
}
} | Constraint that ensures that the field has a conversion if the java type requires it. Also checks the conversion class.
@param fieldDef The field descriptor
@param checkLevel The current check level (this constraint is checked in basic (partly) and strict)
@exception ConstraintException If the conversion class is invalid |
private void ensureLength(FieldDescriptorDef fieldDef, String checkLevel)
{
if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_LENGTH))
{
String defaultLength = JdbcTypeHelper.getDefaultLengthFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));
if (defaultLength != null)
{
LogHelper.warn(true,
FieldDescriptorConstraints.class,
"ensureLength",
"The field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName()+" has no length setting though its jdbc type requires it (in most databases); using default length of "+defaultLength);
fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_LENGTH, defaultLength);
}
}
} | Constraint that ensures that the field has a length if the jdbc type requires it.
@param fieldDef The field descriptor
@param checkLevel The current check level (this constraint is checked in all levels) |
private void ensurePrecisionAndScale(FieldDescriptorDef fieldDef, String checkLevel)
{
fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, null);
fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, null);
if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_PRECISION))
{
String defaultPrecision = JdbcTypeHelper.getDefaultPrecisionFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));
if (defaultPrecision != null)
{
LogHelper.warn(true,
FieldDescriptorConstraints.class,
"ensureLength",
"The field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName()+" has no precision setting though its jdbc type requires it (in most databases); using default precision of "+defaultPrecision);
fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, defaultPrecision);
}
else if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_SCALE))
{
fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION, "1");
}
}
if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_SCALE))
{
String defaultScale = JdbcTypeHelper.getDefaultScaleFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));
if (defaultScale != null)
{
LogHelper.warn(true,
FieldDescriptorConstraints.class,
"ensureLength",
"The field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName()+" has no scale setting though its jdbc type requires it (in most databases); using default scale of "+defaultScale);
fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, defaultScale);
}
else if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_PRECISION) || fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION))
{
fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE, "0");
}
}
} | Constraint that ensures that the field has precision and scale settings if the jdbc type requires it.
@param fieldDef The field descriptor
@param checkLevel The current check level (this constraint is checked in all levels) |
private void checkLocking(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException
{
if (CHECKLEVEL_NONE.equals(checkLevel))
{
return;
}
String jdbcType = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE);
if (!"TIMESTAMP".equals(jdbcType) && !"INTEGER".equals(jdbcType))
{
if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_LOCKING, false))
{
throw new ConstraintException("The field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName()+" has locking set to true though it is not of TIMESTAMP or INTEGER type");
}
if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UPDATE_LOCK, false))
{
throw new ConstraintException("The field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName()+" has update-lock set to true though it is not of TIMESTAMP or INTEGER type");
}
}
} | Checks that locking and update-lock are only used for fields of TIMESTAMP or INTEGER type.
@param fieldDef The field descriptor
@param checkLevel The current check level (this constraint is checked in basic and strict)
@exception ConstraintException If the constraint has been violated |
private void checkSequenceName(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException
{
if (CHECKLEVEL_NONE.equals(checkLevel))
{
return;
}
String autoIncr = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT);
String seqName = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_SEQUENCE_NAME);
if ((seqName != null) && (seqName.length() > 0))
{
if (!"ojb".equals(autoIncr) && !"database".equals(autoIncr))
{
throw new ConstraintException("The field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName()+" has sequence-name set though it's autoincrement value is not set to 'ojb'");
}
}
} | Checks that sequence-name is only used with autoincrement='ojb'
@param fieldDef The field descriptor
@param checkLevel The current check level (this constraint is checked in basic and strict)
@exception ConstraintException If the constraint has been violated |
private void checkId(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException
{
if (CHECKLEVEL_NONE.equals(checkLevel))
{
return;
}
String id = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID);
if ((id != null) && (id.length() > 0))
{
try
{
Integer.parseInt(id);
}
catch (NumberFormatException ex)
{
throw new ConstraintException("The id attribute of field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName()+" is not a valid number");
}
}
} | Checks the id value.
@param fieldDef The field descriptor
@param checkLevel The current check level (this constraint is checked in basic and strict)
@exception ConstraintException If the constraint has been violated |
private void checkReadonlyAccessForNativePKs(FieldDescriptorDef fieldDef, String checkLevel)
{
if (CHECKLEVEL_NONE.equals(checkLevel))
{
return;
}
String access = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ACCESS);
String autoInc = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT);
if ("database".equals(autoInc) && !"readonly".equals(access))
{
LogHelper.warn(true,
FieldDescriptorConstraints.class,
"checkAccess",
"The field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName()+" is set to database auto-increment. Therefore the field's access is set to 'readonly'.");
fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_ACCESS, "readonly");
}
} | Checks that native primarykey fields have readonly access, and warns if not.
@param fieldDef The field descriptor
@param checkLevel The current check level (this constraint is checked in basic and strict) |
private void checkAnonymous(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException
{
if (CHECKLEVEL_NONE.equals(checkLevel))
{
return;
}
String access = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ACCESS);
if (!"anonymous".equals(access))
{
throw new ConstraintException("The access property of the field "+fieldDef.getName()+" defined in class "+fieldDef.getOwner().getName()+" cannot be changed");
}
if ((fieldDef.getName() == null) || (fieldDef.getName().length() == 0))
{
throw new ConstraintException("An anonymous field defined in class "+fieldDef.getOwner().getName()+" has no name");
}
} | Checks anonymous fields.
@param fieldDef The field descriptor
@param checkLevel The current check level (this constraint is checked in basic and strict)
@exception ConstraintException If the constraint has been violated |
public void endDocument()
{
logger.debug("**** endDoc ****");
for (Iterator iterator = conDesList.iterator(); iterator.hasNext();)
{
JdbcConnectionDescriptor jcd = (JdbcConnectionDescriptor) iterator.next();
con_repository.addDescriptor(jcd);
}
} | Here we overgive the found descriptors to {@link ConnectionRepository}. |
public void startElement(String uri, String name, String qName, Attributes atts)
{
boolean isDebug = logger.isDebugEnabled();
try
{
switch (getLiteralId(qName))
{
case JDBC_CONNECTION_DESCRIPTOR:
{
if (isDebug) logger.debug(" > " + tags.getTagById(JDBC_CONNECTION_DESCRIPTOR));
JdbcConnectionDescriptor newJcd = new JdbcConnectionDescriptor();
currentAttributeContainer = newJcd;
conDesList.add(newJcd);
m_CurrentJCD = newJcd;
// set the jcdAlias attribute
String jcdAlias = atts.getValue(tags.getTagById(JCD_ALIAS));
if (isDebug) logger.debug(" " + tags.getTagById(JCD_ALIAS) + ": " + jcdAlias);
m_CurrentJCD.setJcdAlias(jcdAlias);
// set the jcdAlias attribute
String defaultConnection = atts.getValue(tags.getTagById(DEFAULT_CONNECTION));
if (isDebug) logger.debug(" " + tags.getTagById(DEFAULT_CONNECTION) + ": " + defaultConnection);
m_CurrentJCD.setDefaultConnection(Boolean.valueOf(defaultConnection).booleanValue());
if (m_CurrentJCD.isDefaultConnection())
{
if (defaultConnectionFound)
{
throw new MetadataException("Found two jdbc-connection-descriptor elements with default-connection=\"true\"");
}
else
{
defaultConnectionFound = true;
}
}
// set platform attribute
String platform = atts.getValue(tags.getTagById(DBMS_NAME));
if (isDebug) logger.debug(" " + tags.getTagById(DBMS_NAME) + ": " + platform);
m_CurrentJCD.setDbms(platform);
// set jdbc-level attribute
String level = atts.getValue(tags.getTagById(JDBC_LEVEL));
if (isDebug) logger.debug(" " + tags.getTagById(JDBC_LEVEL) + ": " + level);
m_CurrentJCD.setJdbcLevel(level);
// set driver attribute
String driver = atts.getValue(tags.getTagById(DRIVER_NAME));
if (isDebug) logger.debug(" " + tags.getTagById(DRIVER_NAME) + ": " + driver);
m_CurrentJCD.setDriver(driver);
// set protocol attribute
String protocol = atts.getValue(tags.getTagById(URL_PROTOCOL));
if (isDebug) logger.debug(" " + tags.getTagById(URL_PROTOCOL) + ": " + protocol);
m_CurrentJCD.setProtocol(protocol);
// set subprotocol attribute
String subprotocol = atts.getValue(tags.getTagById(URL_SUBPROTOCOL));
if (isDebug) logger.debug(" " + tags.getTagById(URL_SUBPROTOCOL) + ": " + subprotocol);
m_CurrentJCD.setSubProtocol(subprotocol);
// set the dbalias attribute
String dbalias = atts.getValue(tags.getTagById(URL_DBALIAS));
if (isDebug) logger.debug(" " + tags.getTagById(URL_DBALIAS) + ": " + dbalias);
m_CurrentJCD.setDbAlias(dbalias);
// set the datasource attribute
String datasource = atts.getValue(tags.getTagById(DATASOURCE_NAME));
// check for empty String
if(datasource != null && datasource.trim().equals("")) datasource = null;
if (isDebug) logger.debug(" " + tags.getTagById(DATASOURCE_NAME) + ": " + datasource);
m_CurrentJCD.setDatasourceName(datasource);
// set the user attribute
String user = atts.getValue(tags.getTagById(USER_NAME));
if (isDebug) logger.debug(" " + tags.getTagById(USER_NAME) + ": " + user);
m_CurrentJCD.setUserName(user);
// set the password attribute
String password = atts.getValue(tags.getTagById(USER_PASSWD));
if (isDebug) logger.debug(" " + tags.getTagById(USER_PASSWD) + ": " + password);
m_CurrentJCD.setPassWord(password);
// set eager-release attribute
String eagerRelease = atts.getValue(tags.getTagById(EAGER_RELEASE));
if (isDebug) logger.debug(" " + tags.getTagById(EAGER_RELEASE) + ": " + eagerRelease);
m_CurrentJCD.setEagerRelease(Boolean.valueOf(eagerRelease).booleanValue());
// set batch-mode attribute
String batchMode = atts.getValue(tags.getTagById(BATCH_MODE));
if (isDebug) logger.debug(" " + tags.getTagById(BATCH_MODE) + ": " + batchMode);
m_CurrentJCD.setBatchMode(Boolean.valueOf(batchMode).booleanValue());
// set useAutoCommit attribute
String useAutoCommit = atts.getValue(tags.getTagById(USE_AUTOCOMMIT));
if (isDebug) logger.debug(" " + tags.getTagById(USE_AUTOCOMMIT) + ": " + useAutoCommit);
m_CurrentJCD.setUseAutoCommit(Integer.valueOf(useAutoCommit).intValue());
// set ignoreAutoCommitExceptions attribute
String ignoreAutoCommitExceptions = atts.getValue(tags.getTagById(IGNORE_AUTOCOMMIT_EXCEPTION));
if (isDebug) logger.debug(" " + tags.getTagById(IGNORE_AUTOCOMMIT_EXCEPTION) + ": " + ignoreAutoCommitExceptions);
m_CurrentJCD.setIgnoreAutoCommitExceptions(Boolean.valueOf(ignoreAutoCommitExceptions).booleanValue());
break;
}
case CONNECTION_POOL:
{
if (m_CurrentJCD != null)
{
if (isDebug) logger.debug(" > " + tags.getTagById(CONNECTION_POOL));
final ConnectionPoolDescriptor m_CurrentCPD = m_CurrentJCD.getConnectionPoolDescriptor();
this.currentAttributeContainer = m_CurrentCPD;
String maxActive = atts.getValue(tags.getTagById(CON_MAX_ACTIVE));
if (isDebug) logger.debug(" " + tags.getTagById(CON_MAX_ACTIVE) + ": " + maxActive);
if (checkString(maxActive)) m_CurrentCPD.setMaxActive(Integer.parseInt(maxActive));
String maxIdle = atts.getValue(tags.getTagById(CON_MAX_IDLE));
if (isDebug) logger.debug(" " + tags.getTagById(CON_MAX_IDLE) + ": " + maxIdle);
if (checkString(maxIdle)) m_CurrentCPD.setMaxIdle(Integer.parseInt(maxIdle));
String maxWait = atts.getValue(tags.getTagById(CON_MAX_WAIT));
if (isDebug) logger.debug(" " + tags.getTagById(CON_MAX_WAIT) + ": " + maxWait);
if (checkString(maxWait)) m_CurrentCPD.setMaxWait(Integer.parseInt(maxWait));
String minEvictableIdleTimeMillis = atts.getValue(tags.getTagById(CON_MIN_EVICTABLE_IDLE_TIME_MILLIS));
if (isDebug) logger.debug(" " + tags.getTagById(CON_MIN_EVICTABLE_IDLE_TIME_MILLIS) + ": " + minEvictableIdleTimeMillis);
if (checkString(minEvictableIdleTimeMillis)) m_CurrentCPD.setMinEvictableIdleTimeMillis(Long.parseLong(minEvictableIdleTimeMillis));
String numTestsPerEvictionRun = atts.getValue(tags.getTagById(CON_NUM_TESTS_PER_EVICTION_RUN));
if (isDebug) logger.debug(" " + tags.getTagById(CON_NUM_TESTS_PER_EVICTION_RUN) + ": " + numTestsPerEvictionRun);
if (checkString(numTestsPerEvictionRun)) m_CurrentCPD.setNumTestsPerEvictionRun(Integer.parseInt(numTestsPerEvictionRun));
String testOnBorrow = atts.getValue(tags.getTagById(CON_TEST_ON_BORROW));
if (isDebug) logger.debug(" " + tags.getTagById(CON_TEST_ON_BORROW) + ": " + testOnBorrow);
if (checkString(testOnBorrow)) m_CurrentCPD.setTestOnBorrow(Boolean.valueOf(testOnBorrow).booleanValue());
String testOnReturn = atts.getValue(tags.getTagById(CON_TEST_ON_RETURN));
if (isDebug) logger.debug(" " + tags.getTagById(CON_TEST_ON_RETURN) + ": " + testOnReturn);
if (checkString(testOnReturn)) m_CurrentCPD.setTestOnReturn(Boolean.valueOf(testOnReturn).booleanValue());
String testWhileIdle = atts.getValue(tags.getTagById(CON_TEST_WHILE_IDLE));
if (isDebug) logger.debug(" " + tags.getTagById(CON_TEST_WHILE_IDLE) + ": " + testWhileIdle);
if (checkString(testWhileIdle)) m_CurrentCPD.setTestWhileIdle(Boolean.valueOf(testWhileIdle).booleanValue());
String timeBetweenEvictionRunsMillis = atts.getValue(tags.getTagById(CON_TIME_BETWEEN_EVICTION_RUNS_MILLIS));
if (isDebug) logger.debug(" " + tags.getTagById(CON_TIME_BETWEEN_EVICTION_RUNS_MILLIS) + ": " + timeBetweenEvictionRunsMillis);
if (checkString(timeBetweenEvictionRunsMillis)) m_CurrentCPD.setTimeBetweenEvictionRunsMillis(Long.parseLong(timeBetweenEvictionRunsMillis));
String whenExhaustedAction = atts.getValue(tags.getTagById(CON_WHEN_EXHAUSTED_ACTION));
if (isDebug) logger.debug(" " + tags.getTagById(CON_WHEN_EXHAUSTED_ACTION) + ": " + whenExhaustedAction);
if (checkString(whenExhaustedAction)) m_CurrentCPD.setWhenExhaustedAction(Byte.parseByte(whenExhaustedAction));
String connectionFactoryStr = atts.getValue(tags.getTagById(CONNECTION_FACTORY));
if (isDebug) logger.debug(" " + tags.getTagById(CONNECTION_FACTORY) + ": " + connectionFactoryStr);
if (checkString(connectionFactoryStr)) m_CurrentCPD.setConnectionFactory(ClassHelper.getClass(connectionFactoryStr));
String validationQuery = atts.getValue(tags.getTagById(VALIDATION_QUERY));
if (isDebug) logger.debug(" " + tags.getTagById(VALIDATION_QUERY) + ": " + validationQuery);
if (checkString(validationQuery)) m_CurrentCPD.setValidationQuery(validationQuery);
// abandoned connection properties
String logAbandoned = atts.getValue(tags.getTagById(CON_LOG_ABANDONED));
if (isDebug) logger.debug(" " + tags.getTagById(CON_LOG_ABANDONED) + ": " + logAbandoned);
if (checkString(logAbandoned)) m_CurrentCPD.setLogAbandoned(Boolean.valueOf(logAbandoned).booleanValue());
String removeAbandoned = atts.getValue(tags.getTagById(CON_REMOVE_ABANDONED));
if (isDebug) logger.debug(" " + tags.getTagById(CON_REMOVE_ABANDONED) + ": " + removeAbandoned);
if (checkString(removeAbandoned)) m_CurrentCPD.setRemoveAbandoned(Boolean.valueOf(removeAbandoned).booleanValue());
String removeAbandonedTimeout = atts.getValue(tags.getTagById(CON_REMOVE_ABANDONED_TIMEOUT));
if (isDebug) logger.debug(" " + tags.getTagById(CON_REMOVE_ABANDONED_TIMEOUT) + ": " + removeAbandonedTimeout);
if (checkString(removeAbandonedTimeout)) m_CurrentCPD.setRemoveAbandonedTimeout(Integer.parseInt(removeAbandonedTimeout));
}
break;
}
case OBJECT_CACHE:
{
String className = atts.getValue(tags.getTagById(CLASS_NAME));
if(checkString(className) && m_CurrentJCD != null)
{
ObjectCacheDescriptor ocd = m_CurrentJCD.getObjectCacheDescriptor();
this.currentAttributeContainer = ocd;
ocd.setObjectCache(ClassHelper.getClass(className));
if (isDebug) logger.debug(" > " + tags.getTagById(OBJECT_CACHE));
if (isDebug) logger.debug(" " + tags.getTagById(CLASS_NAME) + ": " + className);
}
break;
}
case SEQUENCE_MANAGER:
{
String className = atts.getValue(tags.getTagById(SEQUENCE_MANAGER_CLASS));
if(checkString(className))
{
this.currentSequenceDescriptor = new SequenceDescriptor(this.m_CurrentJCD);
this.currentAttributeContainer = currentSequenceDescriptor;
this.m_CurrentJCD.setSequenceDescriptor(this.currentSequenceDescriptor);
if (isDebug) logger.debug(" > " + tags.getTagById(SEQUENCE_MANAGER));
if (isDebug) logger.debug(" " + tags.getTagById(SEQUENCE_MANAGER_CLASS) + ": " + className);
if (checkString(className)) currentSequenceDescriptor.setSequenceManagerClass(ClassHelper.getClass(className));
}
break;
}
case ATTRIBUTE:
{
//handle custom attributes
String attributeName = atts.getValue(tags.getTagById(ATTRIBUTE_NAME));
String attributeValue = atts.getValue(tags.getTagById(ATTRIBUTE_VALUE));
// If we have a container to store this attribute in, then do so.
if (this.currentAttributeContainer != null)
{
if (checkString(attributeName))
{
if (isDebug) logger.debug(" > " + tags.getTagById(ATTRIBUTE));
if (isDebug) logger.debug(" " + tags.getTagById(ATTRIBUTE_NAME) + ": " + attributeName
+ " "+tags.getTagById(ATTRIBUTE_VALUE) + ": " + attributeValue);
this.currentAttributeContainer.addAttribute(attributeName, attributeValue);
// logger.info("attribute ["+attributeName+"="+attributeValue+"] add to "+currentAttributeContainer.getClass());
}
else
{
logger.info("Found 'null' or 'empty' attribute object for element "+currentAttributeContainer.getClass() +
" attribute-name=" + attributeName + ", attribute-value=" + attributeValue+
" See jdbc-connection-descriptor with jcdAlias '"+m_CurrentJCD.getJcdAlias()+"'");
}
}
// else
// {
// logger.info("Found attribute (name="+attributeName+", value="+attributeValue+
// ") but I could not assign them to a descriptor");
// }
break;
}
default :
{
// noop
}
}
}
catch (Exception ex)
{
logger.error(ex);
throw new PersistenceBrokerException(ex);
}
} | startElement callback.
Only some Elements need special start operations.
@throws MetadataException indicating mapping errors |
public void endElement(String uri, String name, String qName)
{
boolean isDebug = logger.isDebugEnabled();
try
{
switch (getLiteralId(qName))
{
case MAPPING_REPOSITORY:
{
currentAttributeContainer = null;
break;
}
case CLASS_DESCRIPTOR:
{
currentAttributeContainer = null;
break;
}
case JDBC_CONNECTION_DESCRIPTOR:
{
logger.debug(" < " + tags.getTagById(JDBC_CONNECTION_DESCRIPTOR));
m_CurrentJCD = null;
currentAttributeContainer = null;
break;
}
case CONNECTION_POOL:
{
logger.debug(" < " + tags.getTagById(CONNECTION_POOL));
currentAttributeContainer = m_CurrentJCD;
break;
}
case SEQUENCE_MANAGER:
{
if (isDebug) logger.debug(" < " + tags.getTagById(SEQUENCE_MANAGER));
// set to null at the end of the tag!!
this.currentSequenceDescriptor = null;
currentAttributeContainer = m_CurrentJCD;
break;
}
case OBJECT_CACHE:
{
if(currentAttributeContainer != null)
{
if (isDebug) logger.debug(" < " + tags.getTagById(OBJECT_CACHE));
// set to null or previous element level at the end of the tag!!
currentAttributeContainer = m_CurrentJCD;
}
break;
}
case ATTRIBUTE:
{
if(currentAttributeContainer != null)
{
if (isDebug) logger.debug(" < " + tags.getTagById(ATTRIBUTE));
}
break;
}
default :
{
// noop
}
}
}
catch (Exception ex)
{
logger.error(ex);
throw new PersistenceBrokerException(ex);
}
} | endElement callback. most elements are build up from here. |
protected String sendRequestToDF(String df_service, Object msgContent) {
IDFComponentDescription[] receivers = getReceivers(df_service);
if (receivers.length > 0) {
IMessageEvent mevent = createMessageEvent("send_request");
mevent.getParameter(SFipa.CONTENT).setValue(msgContent);
for (int i = 0; i < receivers.length; i++) {
mevent.getParameterSet(SFipa.RECEIVERS).addValue(
receivers[i].getName());
logger.info("The receiver is " + receivers[i].getName());
}
sendMessage(mevent);
}
logger.info("Message sended to " + df_service + " to "
+ receivers.length + " receivers");
return ("Message sended to " + df_service);
} | Method to send Request messages to a specific df_service
@param df_service
The name of the df_service
@param msgContent
The content of the message to be sent
@return Message sent to + the name of the df_service |
protected IDFComponentDescription[] getReceivers(String target_service) {
// Search for X_Service
// Create a service description to search for.
IDF df = (IDF) SServiceProvider.getService(getServiceContainer(),
IDF.class, RequiredServiceInfo.SCOPE_PLATFORM).get(this);
IDFServiceDescription sd = df.createDFServiceDescription(
target_service, null, null);
IDFComponentDescription dfadesc = df.createDFComponentDescription(null,
sd);
ISearchConstraints constraints = df.createSearchConstraints(-1, 0);
// Use a subgoal to search
IGoal ft = createGoal("dfcap.df_search");
ft.getParameter("description").setValue(dfadesc);
ft.getParameter("constraints").setValue(constraints);
ft.getParameter("leasetime").setValue(new Long(LEASE_TIME));
dispatchSubgoalAndWait(ft);
return (IDFComponentDescription[]) ft.getParameterSet("result")
.getValues();
} | This method will be used to know the IDFComponentDescription of all the
agents that own a df_service. Given the IDFComponentDescription, the name
of the agent is known using getName()
@param target_service
The name of the df_service
@return Its agent IDFComponentDescription |
public void setObjectForStatement(PreparedStatement ps, int index, Object value, int jdbcType) throws SQLException
{
if (((jdbcType == Types.CHAR) || (jdbcType == Types.VARCHAR)) &&
(value instanceof Character))
{
// [tomdz]
// Currently, Derby doesn't like Character objects in the PreparedStatement
// when using PreparedStatement#setObject(index, value, jdbcType) method
// (see issue DERBY-773)
// So we make a String object out of the Character object and use that instead
super.setObjectForStatement(ps, index, value.toString(), jdbcType);
}
else
{
super.setObjectForStatement(ps, index, value, jdbcType);
}
} | {@inheritDoc} |
@Action(
semantics = SemanticsOf.IDEMPOTENT,
invokeOn = InvokeOn.OBJECT_AND_COLLECTION
)
public ExcelModuleDemoToDoItem apply() {
ExcelModuleDemoToDoItem item = getToDoItem();
if(item == null) {
// description must be unique, so check
item = toDoItems.findByDescription(getDescription());
if(item != null) {
getContainer().warnUser("Item already exists with description '" + getDescription() + "'");
} else {
// create new item
// (since this is just a demo, haven't bothered to validate new values)
item = toDoItems.newToDo(getDescription(), getCategory(), getSubcategory(), getDueBy(), getCost());
item.setNotes(getNotes());
item.setOwnedBy(getOwnedBy());
item.setComplete(isComplete());
}
} else {
// copy over new values
// (since this is just a demo, haven't bothered to validate new values)
item.setDescription(getDescription());
item.setCategory(getCategory());
item.setSubcategory(getSubcategory());
item.setDueBy(getDueBy());
item.setCost(getCost());
item.setNotes(getNotes());
item.setOwnedBy(getOwnedBy());
item.setComplete(isComplete());
}
return actionInvocationContext.getInvokedOn().isCollection()? null: item;
} | ////////////////////////////////////// |
public Object copy(Object obj, PersistenceBroker broker)
throws ObjectCopyException
{
if (obj instanceof OjbCloneable)
{
try
{
return ((OjbCloneable) obj).ojbClone();
}
catch (Exception e)
{
throw new ObjectCopyException(e);
}
}
else
{
throw new ObjectCopyException("Object must implement OjbCloneable in order to use the"
+ " CloneableObjectCopyStrategy");
}
} | If users want to implement clone on all their objects, we can use this
to make copies. This is hazardous as user may mess it up, but it is also
potentially the fastest way of making a copy.
Usually the OjbCloneable interface should just be delegating to the clone()
operation that the user has implemented.
@see org.apache.ojb.otm.copy.ObjectCopyStrategy#copy(Object) |
public void addColumn(ColumnDef columnDef)
{
columnDef.setOwner(this);
_columns.put(columnDef.getName(), columnDef);
} | Adds a column to this table definition.
@param columnDef The new column |
public IndexDef getIndex(String name)
{
String realName = (name == null ? "" : name);
IndexDef def = null;
for (Iterator it = getIndices(); it.hasNext();)
{
def = (IndexDef)it.next();
if (def.getName().equals(realName))
{
return def;
}
}
return null;
} | Returns the index of the given name.
@param name The name of the index (null or empty string for the default index)
@return The index def or <code>null</code> if it does not exist |
public void addForeignkey(String relationName, String remoteTable, List localColumns, List remoteColumns)
{
ForeignkeyDef foreignkeyDef = new ForeignkeyDef(relationName, remoteTable);
// the field arrays have the same length if we already checked the constraints
for (int idx = 0; idx < localColumns.size(); idx++)
{
foreignkeyDef.addColumnPair((String)localColumns.get(idx),
(String)remoteColumns.get(idx));
}
// we got to determine whether this foreignkey is already present
ForeignkeyDef def = null;
for (Iterator it = getForeignkeys(); it.hasNext();)
{
def = (ForeignkeyDef)it.next();
if (foreignkeyDef.equals(def))
{
return;
}
}
foreignkeyDef.setOwner(this);
_foreignkeys.add(foreignkeyDef);
} | Adds a foreignkey to this table.
@param relationName The name of the relation represented by the foreignkey
@param remoteTable The referenced table
@param localColumns The local columns
@param remoteColumns The remote columns |
public boolean hasForeignkey(String name)
{
String realName = (name == null ? "" : name);
ForeignkeyDef def = null;
for (Iterator it = getForeignkeys(); it.hasNext();)
{
def = (ForeignkeyDef)it.next();
if (realName.equals(def.getName()))
{
return true;
}
}
return false;
} | Determines whether this table has a foreignkey of the given name.
@param name The name of the foreignkey
@return <code>true</code> if there is a foreignkey of that name |
public ForeignkeyDef getForeignkey(String name, String tableName)
{
String realName = (name == null ? "" : name);
ForeignkeyDef def = null;
for (Iterator it = getForeignkeys(); it.hasNext();)
{
def = (ForeignkeyDef)it.next();
if (realName.equals(def.getName()) &&
def.getTableName().equals(tableName))
{
return def;
}
}
return null;
} | Returns the foreignkey to the specified table.
@param name The name of the foreignkey
@param tableName The name of the referenced table
@return The foreignkey def or <code>null</code> if it does not exist |
protected static PropertyDescriptor findPropertyDescriptor(Class aClass, String aPropertyName)
{
BeanInfo info;
PropertyDescriptor[] pd;
PropertyDescriptor descriptor = null;
try
{
info = Introspector.getBeanInfo(aClass);
pd = info.getPropertyDescriptors();
for (int i = 0; i < pd.length; i++)
{
if (pd[i].getName().equals(aPropertyName))
{
descriptor = pd[i];
break;
}
}
if (descriptor == null)
{
/*
* Daren Drummond: Throw here so we are consistent
* with PersistentFieldDefaultImpl.
*/
throw new MetadataException("Can't find property " + aPropertyName + " in " + aClass.getName());
}
return descriptor;
}
catch (IntrospectionException ex)
{
/*
* Daren Drummond: Throw here so we are consistent
* with PersistentFieldDefaultImpl.
*/
throw new MetadataException("Can't find property " + aPropertyName + " in " + aClass.getName(), ex);
}
} | Get the PropertyDescriptor for aClass and aPropertyName |
protected void logProblem(PropertyDescriptor pd, Object anObject, Object aValue, String msg)
{
Logger logger = getLog();
logger.error("Error in [PersistentFieldPropertyImpl], " + msg);
logger.error("Declaring class [" + getDeclaringClass().getName() + "]");
logger.error("Property Name [" + getName() + "]");
logger.error("Property Type [" + pd.getPropertyType().getName() + "]");
if (anObject != null)
{
logger.error("anObject was class [" + anObject.getClass().getName() + "]");
}
else
{
logger.error("anObject was null");
}
if (aValue != null)
{
logger.error("aValue was class [" + aValue.getClass().getName() + "]");
}
else
{
logger.error("aValue was null");
}
} | Let's give the user some hints as to what could be wrong. |
private Expression getExpression(String expressionString) throws ParseException {
if (!expressionCache.containsKey(expressionString)) {
Expression expression;
expression = parser.parseExpression(expressionString);
expressionCache.put(expressionString, expression);
}
return expressionCache.get(expressionString);
} | Fetch the specified expression from the cache or create it if necessary.
@param expressionString the expression string
@return the expression
@throws ParseException oops |
static final TimeBasedRollStrategy findRollStrategy(
final AppenderRollingProperties properties) {
if (properties.getDatePattern() == null) {
LogLog.error("null date pattern");
return ROLL_ERROR;
}
// Strip out quoted sections so that we may safely scan the undecorated
// pattern for characters that are meaningful to SimpleDateFormat.
final LocalizedDateFormatPatternHelper localizedDateFormatPatternHelper = new LocalizedDateFormatPatternHelper(
properties.getDatePatternLocale());
final String undecoratedDatePattern = localizedDateFormatPatternHelper
.excludeQuoted(properties.getDatePattern());
if (ROLL_EACH_MINUTE.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_MINUTE;
}
if (ROLL_EACH_HOUR.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_HOUR;
}
if (ROLL_EACH_HALF_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_HALF_DAY;
}
if (ROLL_EACH_DAY.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_DAY;
}
if (ROLL_EACH_WEEK.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_WEEK;
}
if (ROLL_EACH_MONTH.isRequiredStrategy(localizedDateFormatPatternHelper,
undecoratedDatePattern)) {
return ROLL_EACH_MONTH;
}
return ROLL_ERROR;
} | Checks each available roll strategy in turn, starting at the per-minute
strategy, next per-hour, and so on for increasing units of time until a
match is found. If no match is found, the error strategy is returned.
@param properties
@return The appropriate roll strategy. |
protected void logGetProblem(Object anObject, String msg)
{
Logger logger = LoggerFactory.getDefaultLogger();
logger.error("Error in operation [get of object [" + this.getClass().getName() + "], " + msg);
logger.error("Property Name [" + getName() + "]");
if (anObject instanceof DynaBean)
{
DynaBean dynaBean = (DynaBean) anObject;
logger.error("anObject was DynaClass [" + dynaBean.getDynaClass().getName() + "]");
}
else if (anObject != null)
{
logger.error("anObject was class [" + anObject.getClass().getName() + "]");
}
else
{
logger.error("anObject was null");
}
} | Let's give the user some hints as to what could be wrong. |
private void initComponents()//GEN-BEGIN:initComponents
{
menuBar = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
exitMenuItem = new javax.swing.JMenuItem();
editMenu = new javax.swing.JMenu();
cutMenuItem = new javax.swing.JMenuItem();
copyMenuItem = new javax.swing.JMenuItem();
pasteMenuItem = new javax.swing.JMenuItem();
deleteMenuItem = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
contentMenuItem = new javax.swing.JMenuItem();
aboutMenuItem = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter()
{
public void windowClosing(java.awt.event.WindowEvent evt)
{
exitForm(evt);
}
});
fileMenu.setText("File");
fileMenu.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
fileMenuActionPerformed(evt);
}
});
exitMenuItem.setText("Exit");
exitMenuItem.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
exitMenuItemActionPerformed(evt);
}
});
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
editMenu.setText("Edit");
cutMenuItem.setText("Cut");
editMenu.add(cutMenuItem);
copyMenuItem.setText("Copy");
editMenu.add(copyMenuItem);
pasteMenuItem.setText("Paste");
editMenu.add(pasteMenuItem);
deleteMenuItem.setText("Delete");
editMenu.add(deleteMenuItem);
menuBar.add(editMenu);
helpMenu.setText("Help");
contentMenuItem.setText("Contents");
helpMenu.add(contentMenuItem);
aboutMenuItem.setText("About");
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
pack();
} | 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 exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
Main.getProperties().setProperty(Main.PROPERTY_MAINFRAME_HEIGHT, "" + this.getHeight());
Main.getProperties().setProperty(Main.PROPERTY_MAINFRAME_WIDTH, "" + this.getWidth());
Main.getProperties().setProperty(Main.PROPERTY_MAINFRAME_POSX, "" + this.getBounds().x);
Main.getProperties().setProperty(Main.PROPERTY_MAINFRAME_POSY, "" + this.getBounds().y);
Main.getProperties().storeProperties("");
System.exit(0);
} | Exit the Application |
public String getPrototypeName() {
String name = getClass().getName();
if (name.startsWith(ORG_GEOMAJAS)) {
name = name.substring(ORG_GEOMAJAS.length());
}
name = name.replace(".dto.", ".impl.");
return name.substring(0, name.length() - 4) + "Impl";
} | Get prototype name.
@return prototype name |
@Programmatic
public Blob toExcel(final List<WorksheetContent> worksheetContents, final String fileName) {
try {
final File file = newExcelConverter().appendSheet(worksheetContents);
return excelFileBlobConverter.toBlob(fileName, file);
} catch (final IOException ex) {
throw new ExcelService.Exception(ex);
}
} | As {@link #toExcel(WorksheetContent, String)}, but with multiple sheets. |
@Programmatic
public <T> Blob toExcelPivot(
final List<T> domainObjects,
final Class<T> cls,
final String fileName) throws ExcelService.Exception {
return toExcelPivot(domainObjects, cls, null, fileName);
} | Creates a Blob holding a single-sheet spreadsheet with a pivot of the domain objects. The sheet name is derived from the
class name.
<p>
Minimal requirements for the domain object are:
</p>
<ul>
<li>
One property has annotation {@link PivotRow} and will be used as row identifier in left column of pivot.
Empty values are supported.
</li>
<li>
At least one property has annotation {@link PivotColumn}. Its values will be used in columns of pivot.
Empty values are supported.
</li>
<li>
At least one property has annotation {@link PivotValue}. Its values will be distributed in the pivot.
</li>
</ul> |
@Programmatic
public <T> List<T> fromExcel(
final Blob excelBlob,
final WorksheetSpec worksheetSpec) throws ExcelService.Exception {
final List<List<?>> listOfList =
fromExcel(excelBlob, Collections.singletonList(worksheetSpec));
return (List<T>) listOfList.get(0);
} | As {@link #fromExcel(Blob, Class, String)}, but specifying the class name and sheet name by way of a
{@link WorksheetSpec}. |
@Programmatic
public List<List<?>> fromExcel(
final Blob excelBlob,
final List<WorksheetSpec> worksheetSpecs) throws ExcelService.Exception {
try {
return newExcelConverter().fromBytes(worksheetSpecs, excelBlob.getBytes());
} catch (final IOException | InvalidFormatException e) {
throw new ExcelService.Exception(e);
}
} | As {@link #fromExcel(Blob, WorksheetSpec)}, but reading multiple sheets (and returning a list of lists of
domain objects). |
protected void checkProxyPrefetchingLimit(DefBase def, String checkLevel) throws ConstraintException
{
if (CHECKLEVEL_NONE.equals(checkLevel))
{
return;
}
if (def.hasProperty(PropertyHelper.OJB_PROPERTY_PROXY_PREFETCHING_LIMIT))
{
if (!def.hasProperty(PropertyHelper.OJB_PROPERTY_PROXY))
{
if (def instanceof ClassDescriptorDef)
{
LogHelper.warn(true,
ConstraintsBase.class,
"checkProxyPrefetchingLimit",
"The class "+def.getName()+" has a proxy-prefetching-limit property but no proxy property");
}
else
{
LogHelper.warn(true,
ConstraintsBase.class,
"checkProxyPrefetchingLimit",
"The feature "+def.getName()+" in class "+def.getOwner().getName()+" has a proxy-prefetching-limit property but no proxy property");
}
}
String propValue = def.getProperty(PropertyHelper.OJB_PROPERTY_PROXY_PREFETCHING_LIMIT);
try
{
int value = Integer.parseInt(propValue);
if (value < 0)
{
if (def instanceof ClassDescriptorDef)
{
throw new ConstraintException("The proxy-prefetching-limit value of class "+def.getName()+" must be a non-negative number");
}
else
{
throw new ConstraintException("The proxy-prefetching-limit value of the feature "+def.getName()+" in class "+def.getOwner().getName()+" must be a non-negative number");
}
}
}
catch (NumberFormatException ex)
{
if (def instanceof ClassDescriptorDef)
{
throw new ConstraintException("The proxy-prefetching-limit value of the class "+def.getName()+" is not a number");
}
else
{
throw new ConstraintException("The proxy-prefetching-limit value of the feature "+def.getName()+" in class "+def.getOwner().getName()+" is not a number");
}
}
}
} | Constraint that ensures that the proxy-prefetching-limit has a valid value.
@param def The descriptor (class, reference, collection)
@param checkLevel The current check level (this constraint is checked in basic and strict) |
public void pivot(final Sheet pivotSourceSheet, final Sheet pivotTargetSheet) {
sourceSheet = pivotSourceSheet;
targetSheet = pivotTargetSheet;
annotations = new AnnotationList(new ArrayList<AnnotationTriplet>());
getAnnotationsFromSource();
setOffsets();
validateAndAdaptSourceDataIfNeeded();
defineSomeCellStyles();
createEmptyHeaderRowsAndCells();
fillInHeaderRows();
pivotSourceRows();
addSummations();
} | Takes the values of the source sheet and creates a pivot in the target sheet based on the information of
the first couple of rows. Only cells of type CELL_TYPE_NUMERIC will be handled and summed in the pivot.
<p>
The source sheet has to honour the following conventions for pivot to be successful and meaningful:
</p>
<ul>
<li>
{@link Row}(0) contains at least a {@link Cell} of type CELL_TYPE_STRING with the value "row".
</li>
<li>
Likewise {@link Row}(0) contains at least one {@link Cell} with value "column" and "value".
</li>
<li>
{@link Row}(0) may contain one or more {@link Cell}'s with value "deco". The values in this column are expected (but not enforced) to
have the same value for each distinct value found in the column marked "row".
</li>
<li>
{@link Row}(1) may contain one or more {@link Cell}'s of type CELL_TYPE_NUMERIC that specifies an order for the value on top of it.
</li>
<li>
{@link Row}(2) contains the aggregation types.
</li>
<li>
{@link Row}(3) contains the field labels.
</li>
<li>
All other {@link Row}'s, if present, contain the data for the pivot. Only numeric values in the column(s) annoted "value" will be summed.
</li>
</ul>
<p>
The pivot will use the distinct values of the first column marked "row" (left-to-right) as row labels. The distinct values of the columns marked as
"column" as column labels (in the order of the specified order - if present.
Otherwise in the order in which they appear in {@link Row}(0) left-to-right.)
The values of the pivot are taken from the column(s) marked "value" (in the order of the specified order - if present.
Otherwise in the order in which they appear in {@link Row}(0) left-to-right.) They have to be of type CELL_TYPE_NUMERIC and will me ignored otherwise.
The values found in the column(s) marked "deco" are put in the column(s) 1 .. following the row label and are meant as decoration.
Since the assumption is that every distinct row label has the same decoration(s) only the first found value for each row will be added.
</p> |
public String getSizeConstraint()
{
String constraint = getProperty(PropertyHelper.OJB_PROPERTY_LENGTH);
if ((constraint == null) || (constraint.length() == 0))
{
String precision = getProperty(PropertyHelper.OJB_PROPERTY_PRECISION);
String scale = getProperty(PropertyHelper.OJB_PROPERTY_SCALE);
if ((precision == null) || (precision.length() == 0))
{
precision = getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_PRECISION);
}
if ((scale == null) || (scale.length() == 0))
{
scale = getProperty(PropertyHelper.OJB_PROPERTY_DEFAULT_SCALE);
}
if (((precision != null) && (precision.length() > 0)) ||
((scale != null) && (scale.length() > 0)))
{
if ((precision == null) || (precision.length() == 0))
{
precision = "1";
}
if ((scale == null) || (scale.length() == 0))
{
scale = "0";
}
constraint = precision + "," + scale;
}
}
return constraint;
} | Determines the size constraint (length or precision+scale).
@return The size constraint |
@Override
public List<Class<? extends FixtureScript>> getFixtures() {
return Lists.<Class<? extends FixtureScript>>newArrayList(org.isisaddons.module.excel.fixture.scripts.RecreateToDoItems.class);
} | Fixtures to be installed. |
public boolean shouldCache(String requestUri) {
String uri = requestUri.toLowerCase();
return checkContains(uri, cacheIdentifiers) || checkSuffixes(uri, cacheSuffixes);
} | Should the URI be cached?
@param requestUri request URI
@return true when caching is needed |
public boolean shouldNotCache(String requestUri) {
String uri = requestUri.toLowerCase();
return checkContains(uri, noCacheIdentifiers) || checkSuffixes(uri, noCacheSuffixes);
} | Should the URI explicitly not be cached.
@param requestUri request URI
@return true when caching is prohibited |
public boolean shouldCompress(String requestUri) {
String uri = requestUri.toLowerCase();
return checkSuffixes(uri, zipSuffixes);
} | Should this request URI be compressed?
@param requestUri request URI
@return true when should be compressed |
public boolean checkContains(String uri, String[] patterns) {
for (String pattern : patterns) {
if (pattern.length() > 0) {
if (uri.contains(pattern)) {
return true;
}
}
}
return false;
} | Check whether the URL contains one of the patterns.
@param uri URI
@param patterns possible patterns
@return true when URL contains one of the patterns |
public boolean checkSuffixes(String uri, String[] patterns) {
for (String pattern : patterns) {
if (pattern.length() > 0) {
if (uri.endsWith(pattern)) {
return true;
}
}
}
return false;
} | Check whether the URL end with one of the given suffixes.
@param uri URI
@param patterns possible suffixes
@return true when URL ends with one of the suffixes |
public boolean checkPrefixes(String uri, String[] patterns) {
for (String pattern : patterns) {
if (pattern.length() > 0) {
if (uri.startsWith(pattern)) {
return true;
}
}
}
return false;
} | Check whether the URL start with one of the given prefixes.
@param uri URI
@param patterns possible prefixes
@return true when URL starts with one of the prefixes |
@Api
public static void configureNoCaching(HttpServletResponse response) {
// HTTP 1.0 header:
response.setHeader(HTTP_EXPIRES_HEADER, HTTP_EXPIRES_HEADER_NOCACHE_VALUE);
response.setHeader(HTTP_CACHE_PRAGMA, HTTP_CACHE_PRAGMA_VALUE);
// HTTP 1.1 header:
response.setHeader(HTTP_CACHE_CONTROL_HEADER, HTTP_CACHE_CONTROL_HEADER_NOCACHE_VALUE);
} | Configure the HTTP response to switch off caching.
@param response response to configure
@since 1.9.0 |
public static Context getContext()
{
if (ctx == null)
{
try
{
setContext(null);
}
catch (Exception e)
{
log.error("Cannot instantiate the InitialContext", e);
throw new OJBRuntimeException(e);
}
}
return ctx;
} | Returns the naming context. |
public static Object lookup(String jndiName)
{
if(log.isDebugEnabled()) log.debug("lookup("+jndiName+") was called");
try
{
return getContext().lookup(jndiName);
}
catch (NamingException e)
{
throw new OJBRuntimeException("Lookup failed for: " + jndiName, e);
}
catch(OJBRuntimeException e)
{
throw e;
}
} | Lookup an object instance from JNDI context.
@param jndiName JNDI lookup name
@return Matching object or <em>null</em> if none found. |
public static void refresh()
{
try
{
setContext(prop);
}
catch (NamingException e)
{
log.error("Unable to refresh the naming context");
throw new OJBRuntimeException("Refresh of context failed, used properties: "
+ (prop != null ? prop.toString() : "none"), e);
}
} | Refresh the used {@link InitialContext} instance. |
public static synchronized void setContext(Properties properties) throws NamingException
{
log.info("Instantiate naming context, properties: " + properties);
if(properties != null)
{
ctx = new InitialContext(properties);
}
else
{
ctx = new InitialContext();
}
prop = properties;
} | Set the used {@link InitialContext}. If properties argument is <em>null</em>, the default
initial context was used.
@param properties The properties used for context instantiation - the properties are:
{@link Context#INITIAL_CONTEXT_FACTORY}, {@link Context#PROVIDER_URL}, {@link Context#URL_PKG_PREFIXES}
@throws NamingException |
public Authentication getAuthentication(String token) {
if (null != token) {
TokenContainer container = tokens.get(token);
if (null != container) {
if (container.isValid()) {
return container.getAuthentication();
} else {
logout(token);
}
}
}
return null;
} | Get the authentication for a specific token.
@param token token
@return authentication if any |
public String login(Authentication authentication) {
String token = getToken();
return login(token, authentication);
} | Login for a specific authentication, creating a new token.
@param authentication authentication to assign to token
@return token |
public String login(String token, Authentication authentication) {
if (null == token) {
return login(authentication);
}
tokens.put(token, new TokenContainer(authentication));
return token;
} | Login for a specific authentication, creating a specific token if given.
@param token token to use
@param authentication authentication to assign to token
@return token |
@Scheduled(fixedRate = 60000) // run every minute
public void invalidateOldTokens() {
List<String> invalidTokens = new ArrayList<String>(); // tokens to invalidate
for (Map.Entry<String, TokenContainer> entry : tokens.entrySet()) {
if (!entry.getValue().isValid()) {
invalidTokens.add(entry.getKey());
}
}
for (String token : invalidTokens) {
logout(token);
}
} | Invalidate tokens which have passed their lifetime. Note that tokens are also checked when the authentication is
fetched in {@link #getAuthentication(String)}. |
public PersistenceBrokerInternal createPersistenceBroker(PBKey pbKey) throws PBFactoryException
{
if (log.isDebugEnabled()) log.debug("Obtain broker from pool, used PBKey is " + pbKey);
PersistenceBrokerInternal broker = null;
/*
try to find a valid PBKey, if given key does not full match
*/
pbKey = BrokerHelper.crossCheckPBKey(pbKey);
try
{
/*
get a pooled PB instance, the pool is reponsible to create new
PB instances if not found in pool
*/
broker = ((PersistenceBrokerInternal) brokerPool.borrowObject(pbKey));
/*
now warp pooled PB instance with a handle to avoid PB corruption
of closed PB instances.
*/
broker = wrapRequestedBrokerInstance(broker);
}
catch (Exception e)
{
try
{
// if something going wrong, tryto close broker
if(broker != null) broker.close();
}
catch (Exception ignore)
{
//ignore it
}
throw new PBFactoryException("Borrow broker from pool failed, using PBKey " + pbKey, e);
}
return broker;
} | Return broker instance from pool. If given {@link PBKey} was not found in pool
a new pool for given
@param pbKey
@return
@throws PBFactoryException |
public void setPoolConfiguration(Properties prop)
{
poolConfig = new PBPoolInfo(prop);
log.info("Change pooling configuration properties: " + poolConfig.getKeyedObjectPoolConfig());
brokerPool.setConfig(poolConfig.getKeyedObjectPoolConfig());
} | could be used for runtime configuration
TODO: is this useful? |
private GenericKeyedObjectPool createPool()
{
GenericKeyedObjectPool.Config conf = poolConfig.getKeyedObjectPoolConfig();
if (log.isDebugEnabled())
log.debug("PersistenceBroker pool will be setup with the following configuration " +
ToStringBuilder.reflectionToString(conf, ToStringStyle.MULTI_LINE_STYLE));
GenericKeyedObjectPool pool = new GenericKeyedObjectPool(null, conf);
pool.setFactory(new PersistenceBrokerFactoryDefaultImpl.PBKeyedPoolableObjectFactory(this, pool));
return pool;
} | Create the {@link org.apache.commons.pool.KeyedObjectPool}, pooling
the {@link PersistenceBroker} instances - override this method to
implement your own pool and {@link org.apache.commons.pool.KeyedPoolableObjectFactory}. |
protected <T> WorksheetSpec.RowFactory<T> rowFactoryFor(
final Class<T> rowClass,
final ExecutionContext ec) {
return new WorksheetSpec.RowFactory<T>() {
@Override
public T create() {
final T importLine =
factoryService.instantiate(rowClass);
// allow the line to interact with the calling fixture
if(importLine instanceof FixtureAwareRowHandler<?>) {
final FixtureAwareRowHandler<?> farh = (FixtureAwareRowHandler<?>) importLine;
farh.setExecutionContext(ec);
farh.setExcelFixture2(ExcelFixture2.this);
}
return importLine;
}
@Override
public Class<?> getCls() {
return rowClass;
}
};
} | endregion |
public Geometry convert2JTS(Object object) {
if (object == null) {
return null;
}
String data = (String) object;
int srid = Integer.parseInt(data.substring(0, data.indexOf("|")));
Geometry geom;
try {
WKTReader reader = new WKTReader();
geom = reader.read(data.substring(data.indexOf("|") + 1));
} catch (Exception e) { // NOSONAR
throw new RuntimeException("Couldn't parse incoming wkt geometry.", e);
}
geom.setSRID(srid);
return geom;
} | Converts the native geometry object to a JTS <code>Geometry</code>.
@param object
native database geometry object (depends on the JDBC spatial
extension of the database)
@return JTS geometry corresponding to geomObj. |
public Object conv2DBGeometry(Geometry jtsGeom, Connection connection) {
int srid = jtsGeom.getSRID();
WKTWriter writer = new WKTWriter();
String wkt = writer.write(jtsGeom);
return srid + "|" + wkt;
} | Converts a JTS <code>Geometry</code> to a native geometry object.
@param jtsGeom
JTS Geometry to convert
@param connection
the current database connection
@return native database geometry object corresponding to jtsGeom. |
public boolean getBooleanProperty(String name, boolean defaultValue)
{
return PropertyHelper.toBoolean(_properties.getProperty(name), defaultValue);
} | Returns the boolean value of the specified property.
@param name The name of the property
@param defaultValue The value to use if the property is not set or not a boolean
@return The value |
public void setProperty(String name, String value)
{
if ((value == null) || (value.length() == 0))
{
_properties.remove(name);
}
else
{
_properties.setProperty(name, value);
}
} | Sets a property.
@param name The property name
@param value The property value |
public void applyModifications(Properties mods)
{
String key;
String value;
for (Iterator it = mods.keySet().iterator(); it.hasNext();)
{
key = (String)it.next();
value = mods.getProperty(key);
setProperty(key, value);
}
} | Applies the modifications contained in the given properties object.
Properties are removed by having a <code>null</code> entry in the mods object.
Properties that are new in mods object, are added to this def object.
@param mods The modifications |
public SimpleFeatureSource getFeatureSource() throws LayerException {
try {
if (dataStore instanceof WFSDataStore) {
return dataStore.getFeatureSource(featureSourceName.replace(":", "_"));
} else {
return dataStore.getFeatureSource(featureSourceName);
}
} catch (IOException e) {
throw new LayerException(e, ExceptionCode.FEATURE_MODEL_PROBLEM,
"Cannot find feature source " + featureSourceName);
} catch (NullPointerException e) {
throw new LayerException(e, ExceptionCode.FEATURE_MODEL_PROBLEM,
"Cannot find feature source " + featureSourceName);
}
} | Retrieve the FeatureSource object from the data store.
@return An OpenGIS FeatureSource object;
@throws LayerException
oops |
protected SimpleFeature asFeature(Object possibleFeature) throws LayerException {
if (possibleFeature instanceof SimpleFeature) {
return (SimpleFeature) possibleFeature;
} else {
throw new LayerException(ExceptionCode.INVALID_FEATURE_OBJECT, possibleFeature.getClass().getName());
}
} | Convert the given feature object to a {@link SimpleFeature}.
@param possibleFeature feature object to convert
@return converted feature
@throws LayerException object could not be converted |
public void setAttributes(Object feature, Map<String, Attribute> attributes) throws LayerException {
for (Map.Entry<String, Attribute> entry : attributes.entrySet()) {
String name = entry.getKey();
if (!name.equals(getGeometryAttributeName())) {
asFeature(feature).setAttribute(name, entry.getValue());
}
}
} | Set the attributes of a feature.
@param feature the feature
@param attributes the attributes
@throws LayerException oops |
@Override
public void setLayerInfo(VectorLayerInfo layerInfo) throws LayerException {
super.setLayerInfo(layerInfo);
srid = geoService.getSridFromCrs(layerInfo.getCrs());
entityMapper = new HibernateEntityMapper(getSessionFactory());
} | ------------------------------------------------------------------------- |
private String fixName(String name) {
return name.replace(HibernateLayerUtil.XPATH_SEPARATOR, HibernateLayerUtil.SEPARATOR);
} | ------------------------------------------------------------------------- |
private Object getAttributeRecursively(Object feature, String name) throws LayerException {
if (feature == null) {
return null;
}
// Split up properties: the first and the rest.
String[] properties = name.split(SEPARATOR_REGEXP, 2);
Object tempFeature;
// If the first property is the identifier:
if (properties[0].equals(getFeatureInfo().getIdentifier().getName())) {
tempFeature = getId(feature);
} else {
Entity entity = entityMapper.asEntity(feature);
HibernateEntity child = (HibernateEntity) entity.getChild(properties[0]);
tempFeature = child == null ? null : child.getObject();
}
// Detect if the first property is a collection (one-to-many):
if (tempFeature instanceof Collection<?>) {
Collection<?> features = (Collection<?>) tempFeature;
Object[] values = new Object[features.size()];
int count = 0;
for (Object value : features) {
if (properties.length == 1) {
values[count++] = value;
} else {
values[count++] = getAttributeRecursively(value, properties[1]);
}
}
return values;
} else { // Else first property is not a collection (one-to-many):
if (properties.length == 1 || tempFeature == null) {
return tempFeature;
} else {
return getAttributeRecursively(tempFeature, properties[1]);
}
}
} | A recursive getAttribute method. In case a one-to-many is passed, an array will be returned.
@param feature The feature wherein to search for the attribute
@param name The attribute's full name. (can be attr1.attr2)
@return Returns the value. In case a one-to-many is passed along the way, an array will be returned.
@throws LayerException oops |
public OTMConnection acquireConnection(PBKey pbkey)
{
Util.log("In JCAKit.getConnection,1");
try
{
OTMConnectionRequestInfo info = new OTMConnectionRequestInfo(pbkey);
return (OTMConnection) m_connectionManager.allocateConnection(m_managedConnectionFactory, info);
}
catch (ResourceException ex)
{
throw new OTMConnectionRuntimeException(ex);
}
} | Kit implementation |
public boolean shouldBeInReport(final DbDependency dependency) {
if(dependency == null){
return false;
}
if(dependency.getTarget() == null){
return false;
}
if(corporateFilter != null){
if(!decorator.getShowThirdparty() && !corporateFilter.filter(dependency)){
return false;
}
if(!decorator.getShowCorporate() && corporateFilter.filter(dependency)){
return false;
}
}
if(!scopeHandler.filter(dependency)){
return false;
}
return true;
} | Check if a dependency matches the filters
@param dependency
@return boolean |
public Map<String, Object> getArtifactFieldsFilters() {
final Map<String, Object> params = new HashMap<String, Object>();
for(final Filter filter: filters){
params.putAll(filter.artifactFilterFields());
}
return params;
} | Generates a Map of query parameters for Artifact regarding the filters
@return Map<String, Object> |
public Map<String, Object> getModuleFieldsFilters() {
final Map<String, Object> params = new HashMap<String, Object>();
for(final Filter filter: filters){
params.putAll(filter.moduleFilterFields());
}
return params;
} | Generates a Map of query parameters for Module regarding the filters
@return Map<String, Object> |
public void execute() throws BuildException
{
if ((_commands == null) || (_commands.length() == 0))
{
return;
}
DBHandling handling = createDBHandling();
try
{
if ((_workDir != null) && (_workDir.length() > 0))
{
handling.setWorkDir(_workDir);
System.setProperty("user.dir", _workDir);
}
for (Iterator it = _fileSets.iterator(); it.hasNext();)
{
addIncludes(handling, (FileSet)it.next());
}
if ((_propertiesFile != null) && (_propertiesFile.length() > 0))
{
System.setProperty("OJB.properties", _propertiesFile);
}
ConnectionRepository connRep = MetadataManager.getInstance().connectionRepository();
PBKey pbKey = null;
if ((_jcdAlias == null) || (_jcdAlias.length() == 0))
{
pbKey = PersistenceBrokerFactory.getDefaultKey();
}
else
{
pbKey = connRep.getStandardPBKeyForJcdAlias(_jcdAlias);
if (pbKey == null)
{
throw new BuildException("Undefined jcdAlias "+_jcdAlias);
}
}
handling.setConnection(connRep.getDescriptor(pbKey));
String command;
for (StringTokenizer tokenizer = new StringTokenizer(_commands, ","); tokenizer.hasMoreTokens();)
{
command = tokenizer.nextToken().toLowerCase().trim();
if (COMMAND_CREATE.equals(command))
{
handling.createDB();
}
else if (COMMAND_INIT.equals(command))
{
handling.initDB();
}
else
{
throw new BuildException("Unknown command "+command);
}
}
}
catch (Exception ex)
{
throw new BuildException(ex);
}
} | /* (non-Javadoc)
@see org.apache.tools.ant.Task#execute() |
private DBHandling createDBHandling() throws BuildException
{
if ((_handling == null) || (_handling.length() == 0))
{
throw new BuildException("No handling specified");
}
try
{
String className = "org.apache.ojb.broker.platforms."+
Character.toTitleCase(_handling.charAt(0))+_handling.substring(1)+
"DBHandling";
Class handlingClass = ClassHelper.getClass(className);
return (DBHandling)handlingClass.newInstance();
}
catch (Exception ex)
{
throw new BuildException("Invalid handling '"+_handling+"' specified");
}
} | Creates a db handling object.
@return The db handling object
@throws BuildException If the handling is invalid |
private void addIncludes(DBHandling handling, FileSet fileSet) throws BuildException
{
DirectoryScanner scanner = fileSet.getDirectoryScanner(getProject());
String[] files = scanner.getIncludedFiles();
StringBuffer includes = new StringBuffer();
for (int idx = 0; idx < files.length; idx++)
{
if (idx > 0)
{
includes.append(",");
}
includes.append(files[idx]);
}
try
{
handling.addDBDefinitionFiles(fileSet.getDir(getProject()).getAbsolutePath(), includes.toString());
}
catch (IOException ex)
{
throw new BuildException(ex);
}
} | Adds the includes of the fileset to the handling.
@param handling The handling
@param fileSet The fileset |
public void setModel(Database databaseModel, DescriptorRepository objModel)
{
_dbModel = databaseModel;
_preparedModel = new PreparedModel(objModel, databaseModel);
} | Sets the model that the handling works on.
@param databaseModel The database model
@param objModel The object model |
public void getDataDTD(Writer output) throws DataTaskException
{
try
{
output.write("<!ELEMENT dataset (\n");
for (Iterator it = _preparedModel.getElementNames(); it.hasNext();)
{
String elementName = (String)it.next();
output.write(" ");
output.write(elementName);
output.write("*");
output.write(it.hasNext() ? " |\n" : "\n");
}
output.write(")>\n<!ATTLIST dataset\n name CDATA #REQUIRED\n>\n");
for (Iterator it = _preparedModel.getElementNames(); it.hasNext();)
{
String elementName = (String)it.next();
List classDescs = _preparedModel.getClassDescriptorsMappingTo(elementName);
if (classDescs == null)
{
output.write("\n<!-- Indirection table");
}
else
{
output.write("\n<!-- Mapped to : ");
for (Iterator classDescIt = classDescs.iterator(); classDescIt.hasNext();)
{
ClassDescriptor classDesc = (ClassDescriptor)classDescIt.next();
output.write(classDesc.getClassNameOfObject());
if (classDescIt.hasNext())
{
output.write("\n ");
}
}
}
output.write(" -->\n<!ELEMENT ");
output.write(elementName);
output.write(" EMPTY>\n<!ATTLIST ");
output.write(elementName);
output.write("\n");
for (Iterator attrIt = _preparedModel.getAttributeNames(elementName); attrIt.hasNext();)
{
String attrName = (String)attrIt.next();
output.write(" ");
output.write(attrName);
output.write(" CDATA #");
output.write(_preparedModel.isRequired(elementName, attrName) ? "REQUIRED" : "IMPLIED");
output.write("\n");
}
output.write(">\n");
}
}
catch (IOException ex)
{
throw new DataTaskException(ex);
}
} | Writes a DTD that can be used for data XML files matching the current model to the given writer.
@param output The writer to write the DTD to |
public void getInsertDataSql(Reader input, Writer output) throws DataTaskException
{
try
{
DataSet set = (DataSet)_digester.parse(input);
set.createInsertionSql(_dbModel, _platform, output);
}
catch (Exception ex)
{
if (ex instanceof DataTaskException)
{
// is not declared by digester, but may be thrown
throw (DataTaskException)ex;
}
else
{
throw new DataTaskException(ex);
}
}
} | Returns the sql necessary to add the data XML contained in the given input stream.
Note that the data is expected to match the repository metadata (not the table schema).
Also note that you should not use the reader after passing it to this method except closing
it (which is not done automatically).
@param input A reader returning the content of the data file
@param output The writer to write the sql to |
public void insertData(Reader input, int batchSize) throws DataTaskException
{
try
{
DataSet set = (DataSet)_digester.parse(input);
set.insert(_platform, _dbModel, batchSize);
}
catch (Exception ex)
{
if (ex instanceof DataTaskException)
{
// is not declared by digester, but may be thrown
throw (DataTaskException)ex;
}
else
{
throw new DataTaskException(ex);
}
}
} | Returns the sql necessary to add the data XML contained in the given input stream.
Note that the data is expected to match the repository metadata (not the table schema).
Also note that you should not use the reader after passing it to this method except closing
it (which is not done automatically).
@param input A reader returning the content of the data file
@param batchSize The batch size; use 1 for not batch insertion |
public static Object instantiate(Class clazz) throws InstantiationException
{
Object result = null;
try
{
result = ClassHelper.newInstance(clazz);
}
catch(IllegalAccessException e)
{
try
{
result = ClassHelper.newInstance(clazz, true);
}
catch(Exception e1)
{
throw new ClassNotPersistenceCapableException("Can't instantiate class '"
+ (clazz != null ? clazz.getName() : "null")
+ "', message was: " + e1.getMessage() + ")", e1);
}
}
return result;
} | create a new instance of class clazz.
first use the public default constructor.
If this fails also try to use protected an private constructors.
@param clazz the class to instantiate
@return the fresh instance of class clazz
@throws InstantiationException |
public static Object instantiate(Constructor constructor) throws InstantiationException
{
if(constructor == null)
{
throw new ClassNotPersistenceCapableException(
"A zero argument constructor was not provided!");
}
Object result = null;
try
{
result = constructor.newInstance(NO_ARGS);
}
catch(InstantiationException e)
{
throw e;
}
catch(Exception e)
{
throw new ClassNotPersistenceCapableException("Can't instantiate class '"
+ (constructor != null ? constructor.getDeclaringClass().getName() : "null")
+ "' with given constructor: " + e.getMessage(), e);
}
return result;
} | create a new instance of the class represented by the no-argument constructor provided
@param constructor the zero argument constructor for the class
@return a new instance of the class
@throws InstantiationException
@throws ClassNotPersistenceCapableException if the constructor is null or there is an
exception while trying to create a new instance |
public void synchTransaction(SimpleFeatureStore featureStore) {
// check if transaction is active, otherwise do nothing (auto-commit mode)
if (TransactionSynchronizationManager.isActualTransactionActive()) {
DataAccess<SimpleFeatureType, SimpleFeature> dataStore = featureStore.getDataStore();
if (!transactions.containsKey(dataStore)) {
Transaction transaction = null;
if (dataStore instanceof JDBCDataStore) {
JDBCDataStore jdbcDataStore = (JDBCDataStore) dataStore;
transaction = jdbcDataStore.buildTransaction(DataSourceUtils
.getConnection(jdbcDataStore.getDataSource()));
} else {
transaction = new DefaultTransaction();
}
transactions.put(dataStore, transaction);
}
featureStore.setTransaction(transactions.get(dataStore));
}
} | Synchronize the geotools transaction with the platform transaction, if such a transaction is active.
@param featureStore
@param dataSource |
@Override
public void afterCompletion(int status) {
// clean up transactions that aren't managed by Spring
for (DataAccess<SimpleFeatureType, SimpleFeature> dataStore : transactions.keySet()) {
// we must manage transaction ourselves for non-JDBC !
if (!(dataStore instanceof JDBCDataStore)) {
Transaction transaction = transactions.get(dataStore);
try {
switch (status) {
case TransactionSynchronization.STATUS_COMMITTED:
transaction.commit();
break;
case TransactionSynchronization.STATUS_ROLLED_BACK:
transaction.rollback();
break;
case TransactionSynchronization.STATUS_UNKNOWN:
}
} catch (IOException e) {
try {
transaction.rollback();
} catch (IOException e1) {
log.debug("Could not rollback geotools transaction", e1);
}
} finally {
try {
transaction.close();
} catch (IOException e) {
log.debug("Could not close geotools transaction", e);
}
}
}
}
transactions.clear();
} | Called when the transaction manager has committed/rolled back. We should copy this behavior at the geotools
level, except for the JDBC case, which has already been handled. |
public Object javaToSql(Object source)
{
if (source instanceof String)
{
if (((String)source).trim().length() == 0)
return null;
}
return source;
} | /*
@see FieldConversion#javaToSql(Object) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.