code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
private void appendJoin(StringBuffer where, StringBuffer buf, Join join)
{
buf.append(",");
appendTableWithJoins(join.right, where, buf);
if (where.length() > 0)
{
where.append(" AND ");
}
join.appendJoinEqualities(where);
} | Append Join for non SQL92 Syntax |
private void appendJoinSQL92(Join join, StringBuffer where, StringBuffer buf)
{
if (join.isOuter)
{
buf.append(" LEFT OUTER JOIN ");
}
else
{
buf.append(" INNER JOIN ");
}
if (join.right.hasJoins())
{
buf.append("(");
appendTableWithJoins(join.right, where, buf);
buf.append(")");
}
else
{
appendTableWithJoins(join.right, where, buf);
}
buf.append(" ON ");
join.appendJoinEqualities(buf);
} | Append Join for SQL92 Syntax |
private void appendJoinSQL92NoParen(Join join, StringBuffer where, StringBuffer buf)
{
if (join.isOuter)
{
buf.append(" LEFT OUTER JOIN ");
}
else
{
buf.append(" INNER JOIN ");
}
buf.append(join.right.getTableAndAlias());
buf.append(" ON ");
join.appendJoinEqualities(buf);
appendTableWithJoins(join.right, where, buf);
} | Append Join for SQL92 Syntax without parentheses |
private void buildJoinTree(Criteria crit)
{
Enumeration e = crit.getElements();
while (e.hasMoreElements())
{
Object o = e.nextElement();
if (o instanceof Criteria)
{
buildJoinTree((Criteria) o);
}
else
{
SelectionCriteria c = (SelectionCriteria) o;
// BRJ skip SqlCriteria
if (c instanceof SqlCriteria)
{
continue;
}
// BRJ: Outer join for OR
boolean useOuterJoin = (crit.getType() == Criteria.OR);
// BRJ: do not build join tree for subQuery attribute
if (c.getAttribute() != null && c.getAttribute() instanceof String)
{
//buildJoinTreeForColumn((String) c.getAttribute(), useOuterJoin, c.getAlias(), c.getPathClasses());
buildJoinTreeForColumn((String) c.getAttribute(), useOuterJoin, c.getUserAlias(), c.getPathClasses());
}
if (c instanceof FieldCriteria)
{
FieldCriteria cc = (FieldCriteria) c;
buildJoinTreeForColumn((String) cc.getValue(), useOuterJoin, c.getUserAlias(), c.getPathClasses());
}
}
}
} | Build the tree of joins for the given criteria |
private void buildJoinTreeForColumn(String aColName, boolean useOuterJoin, UserAlias aUserAlias, Map pathClasses)
{
String pathName = SqlHelper.cleanPath(aColName);
int sepPos = pathName.lastIndexOf(".");
if (sepPos >= 0)
{
getTableAlias(pathName.substring(0, sepPos), useOuterJoin, aUserAlias,
new String[]{pathName.substring(sepPos + 1)}, pathClasses);
}
} | build the Join-Information for name
functions and the last segment are removed
ie: avg(accounts.amount) -> accounts |
protected void buildSuperJoinTree(TableAlias left, ClassDescriptor cld, String name, boolean useOuterJoin)
{
ClassDescriptor superCld = cld.getSuperClassDescriptor();
if (superCld != null)
{
SuperReferenceDescriptor superRef = cld.getSuperReference();
FieldDescriptor[] leftFields = superRef.getForeignKeyFieldDescriptors(cld);
TableAlias base_alias = getTableAliasForPath(name, null, null);
String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++;
TableAlias right = new TableAlias(superCld, aliasName, useOuterJoin, null);
Join join1to1 = new Join(left, leftFields, right, superCld.getPkFields(), useOuterJoin, "superClass");
base_alias.addJoin(join1to1);
buildSuperJoinTree(right, superCld, name, useOuterJoin);
}
} | build the Join-Information if a super reference exists
@param left
@param cld
@param name |
private void buildMultiJoinTree(TableAlias left, ClassDescriptor cld, String name, boolean useOuterJoin)
{
DescriptorRepository repository = cld.getRepository();
Class[] multiJoinedClasses = repository.getSubClassesMultipleJoinedTables(cld, false);
for (int i = 0; i < multiJoinedClasses.length; i++)
{
ClassDescriptor subCld = repository.getDescriptorFor(multiJoinedClasses[i]);
SuperReferenceDescriptor srd = subCld.getSuperReference();
if (srd != null)
{
FieldDescriptor[] leftFields = subCld.getPkFields();
FieldDescriptor[] rightFields = srd.getForeignKeyFieldDescriptors(subCld);
TableAlias base_alias = getTableAliasForPath(name, null, null);
String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++;
TableAlias right = new TableAlias(subCld, aliasName, false, null);
Join join1to1 = new Join(left, leftFields, right, rightFields, useOuterJoin, "subClass");
base_alias.addJoin(join1to1);
buildMultiJoinTree(right, subCld, name, useOuterJoin);
}
}
} | build the Join-Information for Subclasses having a super reference to this class
@param left
@param cld
@param name |
protected void splitCriteria()
{
Criteria whereCrit = getQuery().getCriteria();
Criteria havingCrit = getQuery().getHavingCriteria();
if (whereCrit == null || whereCrit.isEmpty())
{
getJoinTreeToCriteria().put(getRoot(), null);
}
else
{
// TODO: parameters list shold be modified when the form is reduced to DNF.
getJoinTreeToCriteria().put(getRoot(), whereCrit);
buildJoinTree(whereCrit);
}
if (havingCrit != null && !havingCrit.isEmpty())
{
buildJoinTree(havingCrit);
}
} | First reduce the Criteria to the normal disjunctive form, then
calculate the necessary tree of joined tables for each item, then group
items with the same tree of joined tables. |
private Filter getFilter(String layerFilter, String[] featureIds) throws GeomajasException {
Filter filter = null;
if (null != layerFilter) {
filter = filterService.parseFilter(layerFilter);
}
if (null != featureIds) {
Filter fidFilter = filterService.createFidFilter(featureIds);
if (null == filter) {
filter = fidFilter;
} else {
filter = filterService.createAndFilter(filter, fidFilter);
}
}
return filter;
} | Build filter for the request.
@param layerFilter layer filter
@param featureIds features to include in report (null for all)
@return filter
@throws GeomajasException filter could not be parsed/created |
public static String resolveProxyUrl(String relativeUrl, TileMap tileMap, String baseTmsUrl) {
TileCode tc = parseTileCode(relativeUrl);
return buildUrl(tc, tileMap, baseTmsUrl);
} | Replaces the proxy url with the correct url from the tileMap.
@return correct url to TMS service |
private static String buildUrl(TileCode tileCode, TileMap tileMap, String baseTmsUrl) {
if (tileCode == null || tileMap == null || baseTmsUrl == null) {
throw new IllegalArgumentException("All parameters are required");
}
StringBuilder builder;
// assuming they are ordered:
TileSet tileSet = tileMap.getTileSets().getTileSets().get(tileCode.getTileLevel());
String href = tileSet.getHref();
if (href.startsWith("http://") || href.startsWith("https://")) {
builder = new StringBuilder(href);
if (!href.endsWith("/")) {
builder.append("/");
}
} else {
builder = new StringBuilder(baseTmsUrl);
if (!baseTmsUrl.endsWith("/")) {
builder.append("/");
}
builder.append(href);
builder.append("/");
}
builder.append(tileCode.getX());
builder.append("/");
builder.append(tileCode.getY());
builder.append(".");
builder.append(tileMap.getTileFormat().getExtension());
return builder.toString();
} | ---------------------------------------------------------- |
public Object javaToSql(Object source)
{
if (source == null)
return null;
try
{
return SerializationUtils.serialize((Serializable) source);
}
catch(Throwable t)
{
throw new ConversionException(t);
}
} | /*
@see FieldConversion#javaToSql(Object) |
public Object sqlToJava(Object source)
{
if(source == null)
return null;
try
{
return SerializationUtils.deserialize((byte[]) source);
}
catch(Throwable t)
{
throw new ConversionException(t);
}
} | /*
@see FieldConversion#sqlToJava(Object) |
public AbstractGraph getModuleGraph(final String moduleId) {
final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);
final DbModule module = moduleHandler.getModule(moduleId);
final DbOrganization organization = moduleHandler.getOrganization(module);
filters.setCorporateFilter(new CorporateFilter(organization));
final AbstractGraph graph = new ModuleGraph();
addModuleToGraph(module, graph, 0);
return graph;
} | Generate a module graph regarding the filters
@param moduleId String
@return AbstractGraph |
private void addModuleToGraph(final DbModule module, final AbstractGraph graph, final int depth) {
if (graph.isTreated(graph.getId(module))) {
return;
}
final String moduleElementId = graph.getId(module);
graph.addElement(moduleElementId, module.getVersion(), depth == 0);
if (filters.getDepthHandler().shouldGoDeeper(depth)) {
for (final DbDependency dep : DataUtils.getAllDbDependencies(module)) {
if(filters.shouldBeInReport(dep)){
addDependencyToGraph(dep, graph, depth + 1, moduleElementId);
}
}
}
} | Manage the artifact add to the Module AbstractGraph
@param graph
@param depth |
private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {
// In that case of Axway artifact we will add a module to the graph
if (filters.getCorporateFilter().filter(dependency)) {
final DbModule dbTarget = repoHandler.getModuleOf(dependency.getTarget());
// if there is no module, add the artifact to the graph
if(dbTarget == null){
LOG.error("Got missing reference: " + dependency.getTarget());
final DbArtifact dbArtifact = DataUtils.createDbArtifact(dependency.getTarget());
final String targetElementId = graph.getId(dbArtifact);
graph.addElement(targetElementId, dbArtifact.getVersion(), false);
graph.addDependency(parentId, targetElementId, dependency.getScope());
return;
}
// Add the element to the graph
addModuleToGraph(dbTarget, graph, depth + 1);
//Add the dependency to the graph
final String moduleElementId = graph.getId(dbTarget);
graph.addDependency(parentId, moduleElementId, dependency.getScope());
}
// In case a third-party we will add an artifact
else {
final DbArtifact dbTarget = repoHandler.getArtifact(dependency.getTarget());
if(dbTarget == null){
LOG.error("Got missing artifact: " + dependency.getTarget());
return;
}
if(!graph.isTreated(graph.getId(dbTarget))){
final ModelMapper modelMapper = new ModelMapper(repoHandler);
final Artifact target = modelMapper.getArtifact(dbTarget);
final String targetElementId = graph.getId(target);
graph.addElement(targetElementId, target.getVersion(), false);
graph.addDependency(parentId, targetElementId, dependency.getScope());
}
}
} | Add a dependency to the graph
@param dependency
@param graph
@param depth
@param parentId |
public TreeNode getModuleTree(final String moduleId) {
final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);
final DbModule module = moduleHandler.getModule(moduleId);
final TreeNode tree = new TreeNode();
tree.setName(module.getName());
// Add submodules
for (final DbModule submodule : module.getSubmodules()) {
addModuleToTree(submodule, tree);
}
return tree;
} | Generate a groupId tree regarding the filters
@param moduleId
@return TreeNode |
private void addModuleToTree(final DbModule module, final TreeNode tree) {
final TreeNode subTree = new TreeNode();
subTree.setName(module.getName());
tree.addChild(subTree);
// Add SubsubModules
for (final DbModule subsubmodule : module.getSubmodules()) {
addModuleToTree(subsubmodule, subTree);
}
} | Add a module to a module tree
@param module
@param tree |
public static void main(String[] args) throws Exception {
Logger logger = Logger.getLogger("MASReader.main");
Properties beastConfigProperties = new Properties();
String beastConfigPropertiesFile = null;
if (args.length > 0) {
beastConfigPropertiesFile = args[0];
beastConfigProperties.load(new FileInputStream(
beastConfigPropertiesFile));
logger.info("Properties file selected -> "
+ beastConfigPropertiesFile);
} else {
logger.severe("No properties file found. Set the path of properties file as argument.");
throw new BeastException(
"No properties file found. Set the path of properties file as argument.");
}
String loggerConfigPropertiesFile;
if (args.length > 1) {
Properties loggerConfigProperties = new Properties();
loggerConfigPropertiesFile = args[1];
try {
FileInputStream loggerConfigFile = new FileInputStream(
loggerConfigPropertiesFile);
loggerConfigProperties.load(loggerConfigFile);
LogManager.getLogManager().readConfiguration(loggerConfigFile);
logger.info("Logging properties configured successfully. Logger config file: "
+ loggerConfigPropertiesFile);
} catch (IOException ex) {
logger.warning("WARNING: Could not open configuration file");
logger.warning("WARNING: Logging not configured (console output only)");
}
} else {
loggerConfigPropertiesFile = null;
}
MASReader.generateJavaFiles(
beastConfigProperties.getProperty("requirementsFolder"), "\""
+ beastConfigProperties.getProperty("MASPlatform")
+ "\"",
beastConfigProperties.getProperty("srcTestRootFolder"),
beastConfigProperties.getProperty("storiesPackage"),
beastConfigProperties.getProperty("caseManagerPackage"),
loggerConfigPropertiesFile,
beastConfigProperties.getProperty("specificationPhase"));
} | Main method to start reading the plain text given by the client
@param args
, where arg[0] is Beast configuration file (beast.properties)
and arg[1] is Logger configuration file (logger.properties)
@throws Exception |
private synchronized Constructor getIndirectionHandlerConstructor()
{
if(_indirectionHandlerConstructor == null)
{
Class[] paramType = {PBKey.class, Identity.class};
try
{
_indirectionHandlerConstructor = getIndirectionHandlerClass().getConstructor(paramType);
}
catch(NoSuchMethodException ex)
{
throw new MetadataException("The class "
+ _indirectionHandlerClass.getName()
+ " specified for IndirectionHandlerClass"
+ " is required to have a public constructor with signature ("
+ PBKey.class.getName()
+ ", "
+ Identity.class.getName()
+ ").");
}
}
return _indirectionHandlerConstructor;
} | Returns the constructor of the indirection handler class.
@return The constructor for indirection handlers |
public void setIndirectionHandlerClass(Class indirectionHandlerClass)
{
if(indirectionHandlerClass == null)
{
//throw new MetadataException("No IndirectionHandlerClass specified.");
/**
* andrew.clute
* Allow the default IndirectionHandler for the given ProxyFactory implementation
* when the parameter is not given
*/
indirectionHandlerClass = getDefaultIndirectionHandlerClass();
}
if(indirectionHandlerClass.isInterface()
|| Modifier.isAbstract(indirectionHandlerClass.getModifiers())
|| !getIndirectionHandlerBaseClass().isAssignableFrom(indirectionHandlerClass))
{
throw new MetadataException("Illegal class "
+ indirectionHandlerClass.getName()
+ " specified for IndirectionHandlerClass. Must be a concrete subclass of "
+ getIndirectionHandlerBaseClass().getName());
}
_indirectionHandlerClass = indirectionHandlerClass;
} | Sets the indirection handler class.
@param indirectionHandlerClass The class for indirection handlers |
public IndirectionHandler createIndirectionHandler(PBKey brokerKey, Identity id)
{
Object args[] = {brokerKey, id};
try
{
return (IndirectionHandler) getIndirectionHandlerConstructor().newInstance(args);
}
catch(InvocationTargetException ex)
{
throw new PersistenceBrokerException("Exception while creating a new indirection handler instance", ex);
}
catch(InstantiationException ex)
{
throw new PersistenceBrokerException("Exception while creating a new indirection handler instance", ex);
}
catch(IllegalAccessException ex)
{
throw new PersistenceBrokerException("Exception while creating a new indirection handler instance", ex);
}
} | Creates a new indirection handler instance.
@param brokerKey The associated {@link PBKey}.
@param id The subject's ids
@return The new instance |
private static Constructor retrieveCollectionProxyConstructor(Class proxyClass, Class baseType, String typeDesc)
{
if(proxyClass == null)
{
throw new MetadataException("No " + typeDesc + " specified.");
}
if(proxyClass.isInterface() || Modifier.isAbstract(proxyClass.getModifiers()) || !baseType.isAssignableFrom(proxyClass))
{
throw new MetadataException("Illegal class "
+ proxyClass.getName()
+ " specified for "
+ typeDesc
+ ". Must be a concrete subclass of "
+ baseType.getName());
}
Class[] paramType = {PBKey.class, Class.class, Query.class};
try
{
return proxyClass.getConstructor(paramType);
}
catch(NoSuchMethodException ex)
{
throw new MetadataException("The class "
+ proxyClass.getName()
+ " specified for "
+ typeDesc
+ " is required to have a public constructor with signature ("
+ PBKey.class.getName()
+ ", "
+ Class.class.getName()
+ ", "
+ Query.class.getName()
+ ").");
}
} | Retrieves the constructor that is used by OJB to create instances of the given collection proxy
class.
@param proxyClass The proxy class
@param baseType The required base type of the proxy class
@param typeDesc The type of collection proxy
@return The constructor |
public void setCollectionProxyClass(Class collectionProxyClass)
{
_collectionProxyConstructor = retrieveCollectionProxyConstructor(collectionProxyClass, Collection.class, "CollectionProxyClass");
// we also require the class to be a subclass of ManageableCollection
if(!ManageableCollection.class.isAssignableFrom(collectionProxyClass))
{
throw new MetadataException("Illegal class "
+ collectionProxyClass.getName()
+ " specified for CollectionProxyClass. Must be a concrete subclass of "
+ ManageableCollection.class.getName());
}
} | Dets the proxy class to use for generic collection classes implementing the {@link java.util.Collection} interface.
@param collectionProxyClass The proxy class |
private Constructor getCollectionProxyConstructor(Class collectionClass)
{
if(List.class.isAssignableFrom(collectionClass))
{
return getListProxyConstructor();
}
else if(Set.class.isAssignableFrom(collectionClass))
{
return getSetProxyConstructor();
}
else
{
return getCollectionProxyConstructor();
}
} | Determines which proxy to use for the given collection class (list, set or generic collection proxy).
@param collectionClass The collection class
@return The constructor of the proxy class |
public ManageableCollection createCollectionProxy(PBKey brokerKey, Query query, Class collectionClass)
{
Object args[] = {brokerKey, collectionClass, query};
try
{
return (ManageableCollection) getCollectionProxyConstructor(collectionClass).newInstance(args);
}
catch(InstantiationException ex)
{
throw new PersistenceBrokerException("Exception while creating a new collection proxy instance", ex);
}
catch(InvocationTargetException ex)
{
throw new PersistenceBrokerException("Exception while creating a new collection proxy instance", ex);
}
catch(IllegalAccessException ex)
{
throw new PersistenceBrokerException("Exception while creating a new collection proxy instance", ex);
}
} | Create a Collection Proxy for a given query.
@param brokerKey The key of the persistence broker
@param query The query
@param collectionClass The class to build the proxy for
@return The collection proxy |
public final Object getRealObject(Object objectOrProxy)
{
if(isNormalOjbProxy(objectOrProxy))
{
String msg;
try
{
return getIndirectionHandler(objectOrProxy).getRealSubject();
}
catch(ClassCastException e)
{
// shouldn't happen but still ...
msg = "The InvocationHandler for the provided Proxy was not an instance of " + IndirectionHandler.class.getName();
log.error(msg);
throw new PersistenceBrokerException(msg, e);
}
catch(IllegalArgumentException e)
{
msg = "Could not retrieve real object for given Proxy: " + objectOrProxy;
log.error(msg);
throw new PersistenceBrokerException(msg, e);
}
catch(PersistenceBrokerException e)
{
log.error("Could not retrieve real object for given Proxy: " + objectOrProxy);
throw e;
}
}
else if(isVirtualOjbProxy(objectOrProxy))
{
try
{
return ((VirtualProxy) objectOrProxy).getRealSubject();
}
catch(PersistenceBrokerException e)
{
log.error("Could not retrieve real object for VirtualProxy: " + objectOrProxy);
throw e;
}
}
else
{
return objectOrProxy;
}
} | Get the real Object
@param objectOrProxy
@return Object |
public Object getRealObjectIfMaterialized(Object objectOrProxy)
{
if(isNormalOjbProxy(objectOrProxy))
{
String msg;
try
{
IndirectionHandler handler = getIndirectionHandler(objectOrProxy);
return handler.alreadyMaterialized() ? handler.getRealSubject() : null;
}
catch(ClassCastException e)
{
// shouldn't happen but still ...
msg = "The InvocationHandler for the provided Proxy was not an instance of " + IndirectionHandler.class.getName();
log.error(msg);
throw new PersistenceBrokerException(msg, e);
}
catch(IllegalArgumentException e)
{
msg = "Could not retrieve real object for given Proxy: " + objectOrProxy;
log.error(msg);
throw new PersistenceBrokerException(msg, e);
}
catch(PersistenceBrokerException e)
{
log.error("Could not retrieve real object for given Proxy: " + objectOrProxy);
throw e;
}
}
else if(isVirtualOjbProxy(objectOrProxy))
{
try
{
VirtualProxy proxy = (VirtualProxy) objectOrProxy;
return proxy.alreadyMaterialized() ? proxy.getRealSubject() : null;
}
catch(PersistenceBrokerException e)
{
log.error("Could not retrieve real object for VirtualProxy: " + objectOrProxy);
throw e;
}
}
else
{
return objectOrProxy;
}
} | Get the real Object for already materialized Handler
@param objectOrProxy
@return Object or null if the Handel is not materialized |
public Class getRealClass(Object objectOrProxy)
{
IndirectionHandler handler;
if(isNormalOjbProxy(objectOrProxy))
{
String msg;
try
{
handler = getIndirectionHandler(objectOrProxy);
/*
arminw:
think we should return the real class
*/
// return handler.getIdentity().getObjectsTopLevelClass();
return handler.getIdentity().getObjectsRealClass();
}
catch(ClassCastException e)
{
// shouldn't happen but still ...
msg = "The InvocationHandler for the provided Proxy was not an instance of " + IndirectionHandler.class.getName();
log.error(msg);
throw new PersistenceBrokerException(msg, e);
}
catch(IllegalArgumentException e)
{
msg = "Could not retrieve real object for given Proxy: " + objectOrProxy;
log.error(msg);
throw new PersistenceBrokerException(msg, e);
}
}
else if(isVirtualOjbProxy(objectOrProxy))
{
handler = VirtualProxy.getIndirectionHandler((VirtualProxy) objectOrProxy);
/*
arminw:
think we should return the real class
*/
// return handler.getIdentity().getObjectsTopLevelClass();
return handler.getIdentity().getObjectsRealClass();
}
else
{
return objectOrProxy.getClass();
}
} | Get the real Class
@param objectOrProxy
@return Class |
public IndirectionHandler getIndirectionHandler(Object obj)
{
if(obj == null)
{
return null;
}
else if(isNormalOjbProxy(obj))
{
return getDynamicIndirectionHandler(obj);
}
else if(isVirtualOjbProxy(obj))
{
return VirtualProxy.getIndirectionHandler((VirtualProxy) obj);
}
else
{
return null;
}
} | Returns the invocation handler object of the given proxy object.
@param obj The object
@return The invocation handler if the object is an OJB proxy, or <code>null</code>
otherwise |
public boolean isMaterialized(Object object)
{
IndirectionHandler handler = getIndirectionHandler(object);
return handler == null || handler.alreadyMaterialized();
} | Determines whether the object is a materialized object, i.e. no proxy or a
proxy that has already been loaded from the database.
@param object The object to test
@return <code>true</code> if the object is materialized |
public DbOrganization getOrganization(final String organizationId) {
final DbOrganization dbOrganization = repositoryHandler.getOrganization(organizationId);
if(dbOrganization == null){
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.entity("Organization " + organizationId + " does not exist.").build());
}
return dbOrganization;
} | Returns an Organization
@param organizationId String
@return DbOrganization |
public void deleteOrganization(final String organizationId) {
final DbOrganization dbOrganization = getOrganization(organizationId);
repositoryHandler.deleteOrganization(dbOrganization.getName());
repositoryHandler.removeModulesOrganization(dbOrganization);
} | Deletes an organization
@param organizationId String |
public List<String> getCorporateGroupIds(final String organizationId) {
final DbOrganization dbOrganization = getOrganization(organizationId);
return dbOrganization.getCorporateGroupIdPrefixes();
} | Returns the list view of corporate groupIds of an organization
@param organizationId String
@return ListView |
public void addCorporateGroupId(final String organizationId, final String corporateGroupId) {
final DbOrganization dbOrganization = getOrganization(organizationId);
if(!dbOrganization.getCorporateGroupIdPrefixes().contains(corporateGroupId)){
dbOrganization.getCorporateGroupIdPrefixes().add(corporateGroupId);
repositoryHandler.store(dbOrganization);
}
repositoryHandler.addModulesOrganization(corporateGroupId, dbOrganization);
} | Adds a corporate groupId to an organization
@param organizationId String
@param corporateGroupId String |
public void removeCorporateGroupId(final String organizationId, final String corporateGroupId) {
final DbOrganization dbOrganization = getOrganization(organizationId);
if(dbOrganization.getCorporateGroupIdPrefixes().contains(corporateGroupId)){
dbOrganization.getCorporateGroupIdPrefixes().remove(corporateGroupId);
repositoryHandler.store(dbOrganization);
}
repositoryHandler.removeModulesOrganization(corporateGroupId, dbOrganization);
} | Removes a corporate groupId from an Organisation
@param organizationId String
@param corporateGroupId String |
public DbOrganization getMatchingOrganization(final DbModule dbModule) {
if(dbModule.getOrganization() != null
&& !dbModule.getOrganization().isEmpty()){
return getOrganization(dbModule.getOrganization());
}
for(final DbOrganization organization: repositoryHandler.getAllOrganizations()){
final CorporateFilter corporateFilter = new CorporateFilter(organization);
if(corporateFilter.matches(dbModule)){
return organization;
}
}
return null;
} | Returns an Organization that suits the Module or null if there is none
@param dbModule DbModule
@return DbOrganization |
private static String generateSQLSearchPattern(Object pattern)
{
if (pattern == null)
{
return null;
}
else
{
StringBuffer sqlpattern = new StringBuffer();
char[] chars = pattern.toString().toCharArray();
for (int i = 0; i < chars.length; i++)
{
if (chars[i] == escapeCharacter)
{
// for the escape character add the next char as is.
// find the next non-escape character.
int x = i + 1;
for (;(x < chars.length); x++)
{
if (chars[x] != escapeCharacter)
{
break;
}
}
boolean oddEscapes = (((x - i) % 2) > 0) ? true : false;
if (oddEscapes)
{
// only escape characters allowed are '%', '_', and '\'
// if the escaped character is a '\', then oddEscapes
// will be false.
// if the character following this last escape is not a
// '%' or an '_', eat this escape character.
if ((x < chars.length)
&& ((chars[x] == '%') || (chars[x] == '_')))
{
// leave the escape character in, along with the following char
x++;
}
else
{
// remove the escape character, will cause problems in sql statement.
i++; // removing the first escape character.
if ((x < chars.length)
&& ((chars[x] == '*') || (chars[x] == '?')))
{
// but if it is a '*' or a '?', we want to keep these
// characters as is, they were 'escaped' out.
x++; // include the first non-escape character.
}
}
}
if (i < chars.length)
{
sqlpattern.append(chars, i, x - i);
}
i = x - 1; // set index to last character copied.
}
else if (chars[i] == '*')
{
sqlpattern.append("%");
}
else if (chars[i] == '?')
{
sqlpattern.append("_");
}
else
{
sqlpattern.append(chars[i]);
}
}
return sqlpattern.toString();
}
} | Generate a SQL search string from the pattern string passed.
The pattern string is a simple pattern string using % or * as a wildcard.
So Ander* would match Anderson and Anderton. The _ or ? character is used to match a single occurence
of a character. The escapeCharacter is used to escape the wildcard characters so that we can search for
strings containing * and ?. This method converts the criteria wildcard strings to SQL wildcards.
@param pattern a criteria search pattern containing optional wildcards
@return a SQL search pattern string with all escape codes processed. |
public void executeDelete(ClassDescriptor cld, Object obj) throws PersistenceBrokerException
{
if (logger.isDebugEnabled())
{
logger.debug("executeDelete: " + obj);
}
final StatementManagerIF sm = broker.serviceStatementManager();
PreparedStatement stmt = null;
try
{
stmt = sm.getDeleteStatement(cld);
if (stmt == null)
{
logger.error("getDeleteStatement returned a null statement");
throw new PersistenceBrokerException("JdbcAccessImpl: getDeleteStatement returned a null statement");
}
sm.bindDelete(stmt, cld, obj);
if (logger.isDebugEnabled())
logger.debug("executeDelete: " + stmt);
// @todo: clearify semantics
// thma: the following check is not secure. The object could be deleted *or* changed.
// if it was deleted it makes no sense to throw an OL exception.
// does is make sense to throw an OL exception if the object was changed?
if (stmt.executeUpdate() == 0 && cld.isLocking()) //BRJ
{
/**
* Kuali Foundation modification -- 6/19/2009
*/
String objToString = "";
try {
objToString = obj.toString();
} catch (Exception ex) {}
throw new OptimisticLockException("Object has been modified or deleted by someone else: " + objToString, obj);
/**
* End of Kuali Foundation modification
*/
}
// Harvest any return values.
harvestReturnValues(cld.getDeleteProcedure(), obj, stmt);
}
catch (OptimisticLockException e)
{
// Don't log as error
if (logger.isDebugEnabled())
logger.debug("OptimisticLockException during the execution of delete: "
+ e.getMessage(), e);
throw e;
}
catch (PersistenceBrokerException e)
{
logger.error("PersistenceBrokerException during the execution of delete: "
+ e.getMessage(), e);
throw e;
}
catch (SQLException e)
{
final String sql = broker.serviceSqlGenerator().getPreparedDeleteStatement(cld).getStatement();
throw ExceptionHelper.generateException(e, sql, cld, logger, obj);
}
finally
{
sm.closeResources(stmt, null);
}
} | performs a DELETE operation against RDBMS.
@param cld ClassDescriptor providing mapping information.
@param obj The object to be deleted. |
public void executeDelete(Query query, ClassDescriptor cld) throws PersistenceBrokerException
{
if (logger.isDebugEnabled())
{
logger.debug("executeDelete (by Query): " + query);
}
final StatementManagerIF sm = broker.serviceStatementManager();
PreparedStatement stmt = null;
final String sql = this.broker.serviceSqlGenerator().getPreparedDeleteStatement(query, cld).getStatement();
try
{
stmt = sm.getPreparedStatement(cld, sql,
false, StatementManagerIF.FETCH_SIZE_NOT_APPLICABLE, cld.getDeleteProcedure()!=null);
sm.bindStatement(stmt, query, cld, 1);
if (logger.isDebugEnabled())
logger.debug("executeDelete (by Query): " + stmt);
stmt.executeUpdate();
}
catch (SQLException e)
{
throw ExceptionHelper.generateException(e, sql, cld, null, logger);
}
finally
{
sm.closeResources(stmt, null);
}
} | Performs a DELETE operation based on the given {@link Query} against RDBMS.
@param query the query string.
@param cld ClassDescriptor providing JDBC information. |
public void executeInsert(ClassDescriptor cld, Object obj) throws PersistenceBrokerException
{
if (logger.isDebugEnabled())
{
logger.debug("executeInsert: " + obj);
}
final StatementManagerIF sm = broker.serviceStatementManager();
PreparedStatement stmt = null;
try
{
stmt = sm.getInsertStatement(cld);
if (stmt == null)
{
logger.error("getInsertStatement returned a null statement");
throw new PersistenceBrokerException("getInsertStatement returned a null statement");
}
// before bind values perform autoincrement sequence columns
assignAutoincrementSequences(cld, obj);
sm.bindInsert(stmt, cld, obj);
if (logger.isDebugEnabled())
logger.debug("executeInsert: " + stmt);
stmt.executeUpdate();
// after insert read and assign identity columns
assignAutoincrementIdentityColumns(cld, obj);
// Harvest any return values.
harvestReturnValues(cld.getInsertProcedure(), obj, stmt);
}
catch (PersistenceBrokerException e)
{
logger.error("PersistenceBrokerException during the execution of the insert: " + e.getMessage(), e);
throw e;
}
catch(SequenceManagerException e)
{
throw new PersistenceBrokerException("Error while try to assign identity value", e);
}
catch (SQLException e)
{
final String sql = broker.serviceSqlGenerator().getPreparedInsertStatement(cld).getStatement();
throw ExceptionHelper.generateException(e, sql, cld, logger, obj);
}
finally
{
sm.closeResources(stmt, null);
}
} | performs an INSERT operation against RDBMS.
@param obj The Object to be inserted as a row of the underlying table.
@param cld ClassDescriptor providing mapping information. |
public ResultSetAndStatement executeQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException
{
if (logger.isDebugEnabled())
{
logger.debug("executeQuery: " + query);
}
/*
* MBAIRD: we should create a scrollable resultset if the start at
* index or end at index is set
*/
boolean scrollable = ((query.getStartAtIndex() > Query.NO_START_AT_INDEX) || (query.getEndAtIndex() > Query.NO_END_AT_INDEX));
/*
* OR if the prefetching of relationships is being used.
*/
if (query != null && query.getPrefetchedRelationships() != null && !query.getPrefetchedRelationships().isEmpty())
{
scrollable = true;
}
final StatementManagerIF sm = broker.serviceStatementManager();
final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectStatement(query, cld);
PreparedStatement stmt = null;
ResultSet rs = null;
try
{
final int queryFetchSize = query.getFetchSize();
final boolean isStoredProcedure = isStoredProcedure(sql.getStatement());
stmt = sm.getPreparedStatement(cld, sql.getStatement() ,
scrollable, queryFetchSize, isStoredProcedure);
if (isStoredProcedure)
{
// Query implemented as a stored procedure, which must return a result set.
// Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}
getPlatform().registerOutResultSet((CallableStatement) stmt, 1);
sm.bindStatement(stmt, query, cld, 2);
if (logger.isDebugEnabled())
logger.debug("executeQuery: " + stmt);
stmt.execute();
rs = (ResultSet) ((CallableStatement) stmt).getObject(1);
}
else
{
sm.bindStatement(stmt, query, cld, 1);
if (logger.isDebugEnabled())
logger.debug("executeQuery: " + stmt);
rs = stmt.executeQuery();
}
return new ResultSetAndStatement(sm, stmt, rs, sql);
}
catch (PersistenceBrokerException e)
{
// release resources on exception
sm.closeResources(stmt, rs);
logger.error("PersistenceBrokerException during the execution of the query: " + e.getMessage(), e);
throw e;
}
catch (SQLException e)
{
// release resources on exception
sm.closeResources(stmt, rs);
throw ExceptionHelper.generateException(e, sql.getStatement(), null, logger, null);
}
} | performs a SELECT operation against RDBMS.
@param query the query string.
@param cld ClassDescriptor providing JDBC information. |
public ResultSetAndStatement executeSQL(
final String sql,
ClassDescriptor cld,
ValueContainer[] values,
boolean scrollable)
throws PersistenceBrokerException
{
if (logger.isDebugEnabled()) logger.debug("executeSQL: " + sql);
final boolean isStoredprocedure = isStoredProcedure(sql);
final StatementManagerIF sm = broker.serviceStatementManager();
PreparedStatement stmt = null;
ResultSet rs = null;
try
{
stmt = sm.getPreparedStatement(cld, sql,
scrollable, StatementManagerIF.FETCH_SIZE_NOT_EXPLICITLY_SET, isStoredprocedure);
if (isStoredprocedure)
{
// Query implemented as a stored procedure, which must return a result set.
// Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}
getPlatform().registerOutResultSet((CallableStatement) stmt, 1);
sm.bindValues(stmt, values, 2);
stmt.execute();
rs = (ResultSet) ((CallableStatement) stmt).getObject(1);
}
else
{
sm.bindValues(stmt, values, 1);
rs = stmt.executeQuery();
}
// as we return the resultset for further operations, we cannot release the statement yet.
// that has to be done by the JdbcAccess-clients (i.e. RsIterator, ProxyRsIterator and PkEnumeration.)
return new ResultSetAndStatement(sm, stmt, rs, new SelectStatement()
{
public Query getQueryInstance()
{
return null;
}
public int getColumnIndex(FieldDescriptor fld)
{
return JdbcType.MIN_INT;
}
public String getStatement()
{
return sql;
}
});
}
catch (PersistenceBrokerException e)
{
// release resources on exception
sm.closeResources(stmt, rs);
logger.error("PersistenceBrokerException during the execution of the SQL query: " + e.getMessage(), e);
throw e;
}
catch (SQLException e)
{
// release resources on exception
sm.closeResources(stmt, rs);
throw ExceptionHelper.generateException(e, sql, cld, values, logger, null);
}
} | performs a SQL SELECT statement against RDBMS.
@param sql the query string.
@param cld ClassDescriptor providing meta-information. |
public int executeUpdateSQL(
String sqlStatement,
ClassDescriptor cld,
ValueContainer[] values1,
ValueContainer[] values2)
throws PersistenceBrokerException
{
if (logger.isDebugEnabled())
logger.debug("executeUpdateSQL: " + sqlStatement);
int result;
int index;
PreparedStatement stmt = null;
final StatementManagerIF sm = broker.serviceStatementManager();
try
{
stmt = sm.getPreparedStatement(cld, sqlStatement,
Query.NOT_SCROLLABLE, StatementManagerIF.FETCH_SIZE_NOT_APPLICABLE, isStoredProcedure(sqlStatement));
index = sm.bindValues(stmt, values1, 1);
sm.bindValues(stmt, values2, index);
result = stmt.executeUpdate();
}
catch (PersistenceBrokerException e)
{
logger.error("PersistenceBrokerException during the execution of the Update SQL query: " + e.getMessage(), e);
throw e;
}
catch (SQLException e)
{
ValueContainer[] tmp = addValues(values1, values2);
throw ExceptionHelper.generateException(e, sqlStatement, cld, tmp, logger, null);
}
finally
{
sm.closeResources(stmt, null);
}
return result;
} | performs a SQL UPDTE, INSERT or DELETE statement against RDBMS.
@param sqlStatement the query string.
@param cld ClassDescriptor providing meta-information.
@return int returncode |
private ValueContainer[] addValues(ValueContainer[] target, ValueContainer[] source)
{
ValueContainer[] newArray;
if(source != null && source.length > 0)
{
if(target != null)
{
newArray = new ValueContainer[target.length + source.length];
System.arraycopy(target, 0, newArray, 0, target.length);
System.arraycopy(source, 0, newArray, target.length, source.length);
}
else
{
newArray = source;
}
}
else
{
newArray = target;
}
return newArray;
} | Helper method, returns the addition of both arrays (add source to target array) |
public void executeUpdate(ClassDescriptor cld, Object obj) throws PersistenceBrokerException
{
if (logger.isDebugEnabled())
{
logger.debug("executeUpdate: " + obj);
}
// obj with nothing but key fields is not updated
if (cld.getNonPkRwFields().length == 0)
{
return;
}
final StatementManagerIF sm = broker.serviceStatementManager();
PreparedStatement stmt = null;
// BRJ: preserve current locking values
// locking values will be restored in case of exception
ValueContainer[] oldLockingValues;
oldLockingValues = cld.getCurrentLockingValues(obj);
try
{
stmt = sm.getUpdateStatement(cld);
if (stmt == null)
{
logger.error("getUpdateStatement returned a null statement");
throw new PersistenceBrokerException("getUpdateStatement returned a null statement");
}
sm.bindUpdate(stmt, cld, obj);
if (logger.isDebugEnabled())
logger.debug("executeUpdate: " + stmt);
if ((stmt.executeUpdate() == 0) && cld.isLocking()) //BRJ
{
/**
* Kuali Foundation modification -- 6/19/2009
*/
String objToString = "";
try {
objToString = obj.toString();
} catch (Exception ex) {}
throw new OptimisticLockException("Object has been modified by someone else: " + objToString, obj);
/**
* End of Kuali Foundation modification
*/
}
// Harvest any return values.
harvestReturnValues(cld.getUpdateProcedure(), obj, stmt);
}
catch (OptimisticLockException e)
{
// Don't log as error
if (logger.isDebugEnabled())
logger.debug(
"OptimisticLockException during the execution of update: " + e.getMessage(),
e);
throw e;
}
catch (PersistenceBrokerException e)
{
// BRJ: restore old locking values
setLockingValues(cld, obj, oldLockingValues);
logger.error(
"PersistenceBrokerException during the execution of the update: " + e.getMessage(),
e);
throw e;
}
catch (SQLException e)
{
final String sql = broker.serviceSqlGenerator().getPreparedUpdateStatement(cld).getStatement();
throw ExceptionHelper.generateException(e, sql, cld, logger, obj);
}
finally
{
sm.closeResources(stmt, null);
}
} | performs an UPDATE operation against RDBMS.
@param obj The Object to be updated in the underlying table.
@param cld ClassDescriptor providing mapping information. |
public Object materializeObject(ClassDescriptor cld, Identity oid)
throws PersistenceBrokerException
{
final StatementManagerIF sm = broker.serviceStatementManager();
final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectByPkStatement(cld);
Object result = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{
stmt = sm.getSelectByPKStatement(cld);
if (stmt == null)
{
logger.error("getSelectByPKStatement returned a null statement");
throw new PersistenceBrokerException("getSelectByPKStatement returned a null statement");
}
/*
arminw: currently a select by PK could never be a stored procedure,
thus we can always set 'false'. Is this correct??
*/
sm.bindSelect(stmt, oid, cld, false);
rs = stmt.executeQuery();
// data available read object, else return null
ResultSetAndStatement rs_stmt = new ResultSetAndStatement(broker.serviceStatementManager(), stmt, rs, sql);
if (rs.next())
{
Map row = new HashMap();
cld.getRowReader().readObjectArrayFrom(rs_stmt, row);
result = cld.getRowReader().readObjectFrom(row);
}
// close resources
rs_stmt.close();
}
catch (PersistenceBrokerException e)
{
// release resources on exception
sm.closeResources(stmt, rs);
logger.error("PersistenceBrokerException during the execution of materializeObject: " + e.getMessage(), e);
throw e;
}
catch (SQLException e)
{
// release resources on exception
sm.closeResources(stmt, rs);
throw ExceptionHelper.generateException(e, sql.getStatement(), cld, logger, null);
}
return result;
} | performs a primary key lookup operation against RDBMS and materializes
an object from the resulting row. Only skalar attributes are filled from
the row, references are not resolved.
@param oid contains the primary key info.
@param cld ClassDescriptor providing mapping information.
@return the materialized object, null if no matching row was found or if
any error occured. |
private void setLockingValues(ClassDescriptor cld, Object obj, ValueContainer[] oldLockingValues)
{
FieldDescriptor fields[] = cld.getLockingFields();
for (int i=0; i<fields.length; i++)
{
PersistentField field = fields[i].getPersistentField();
Object lockVal = oldLockingValues[i].getValue();
field.set(obj, lockVal);
}
} | Set the locking values
@param cld
@param obj
@param oldLockingValues |
private void harvestReturnValues(
ProcedureDescriptor proc,
Object obj,
PreparedStatement stmt)
throws PersistenceBrokerSQLException
{
// If the procedure descriptor is null or has no return values or
// if the statement is not a callable statment, then we're done.
if ((proc == null) || (!proc.hasReturnValues()))
{
return;
}
// Set up the callable statement
CallableStatement callable = (CallableStatement) stmt;
// This is the index that we'll use to harvest the return value(s).
int index = 0;
// If the proc has a return value, then try to harvest it.
if (proc.hasReturnValue())
{
// Increment the index
index++;
// Harvest the value.
this.harvestReturnValue(obj, callable, proc.getReturnValueFieldRef(), index);
}
// Check each argument. If it's returned by the procedure,
// then harvest the value.
Iterator iter = proc.getArguments().iterator();
while (iter.hasNext())
{
index++;
ArgumentDescriptor arg = (ArgumentDescriptor) iter.next();
if (arg.getIsReturnedByProcedure())
{
this.harvestReturnValue(obj, callable, arg.getFieldRef(), index);
}
}
} | Harvest any values that may have been returned during the execution
of a procedure.
@param proc the procedure descriptor that provides info about the procedure
that was invoked.
@param obj the object that was persisted
@param stmt the statement that was used to persist the object.
@throws PersistenceBrokerSQLException if a problem occurs. |
private void harvestReturnValue(
Object obj,
CallableStatement callable,
FieldDescriptor fmd,
int index)
throws PersistenceBrokerSQLException
{
try
{
// If we have a field descriptor, then we can harvest
// the return value.
if ((callable != null) && (fmd != null) && (obj != null))
{
// Get the value and convert it to it's appropriate
// java type.
Object value = fmd.getJdbcType().getObjectFromColumn(callable, index);
// Set the value of the persistent field.
fmd.getPersistentField().set(obj, fmd.getFieldConversion().sqlToJava(value));
}
}
catch (SQLException e)
{
String msg = "SQLException during the execution of harvestReturnValue"
+ " class="
+ obj.getClass().getName()
+ ","
+ " field="
+ fmd.getAttributeName()
+ " : "
+ e.getMessage();
logger.error(msg,e);
throw new PersistenceBrokerSQLException(msg, e);
}
} | Harvest a single value that was returned by a callable statement.
@param obj the object that will receive the value that is harvested.
@param callable the CallableStatement that contains the value to harvest
@param fmd the FieldDescriptor that identifies the field where the
harvested value will be stord.
@param index the parameter index.
@throws PersistenceBrokerSQLException if a problem occurs. |
protected boolean isStoredProcedure(String sql)
{
/*
Stored procedures start with
{?= call <procedure-name>[<arg1>,<arg2>, ...]}
or
{call <procedure-name>[<arg1>,<arg2>, ...]}
but also statements with white space like
{ ?= call <procedure-name>[<arg1>,<arg2>, ...]}
are possible.
*/
int k = 0, i = 0;
char c;
while(k < 3 && i < sql.length())
{
c = sql.charAt(i);
if(c != ' ')
{
switch (k)
{
case 0:
if(c != '{') return false;
break;
case 1:
if(c != '?' && c != 'c') return false;
break;
case 2:
if(c != '=' && c != 'a') return false;
break;
}
k++;
}
i++;
}
return true;
} | Check if the specified sql-string is a stored procedure
or not.
@param sql The sql query to check
@return <em>True</em> if the query is a stored procedure, else <em>false</em> is returned. |
public String get() {
synchronized (LOCK) {
if (!initialised) {
// generate the random number
Random rnd = new Random(); // @todo need a different seed, this is now time based and I
// would prefer something different, like an object address
// get the random number, instead of getting an integer and converting that to base64 later,
// we get a string and narrow that down to base64, use the top 6 bits of the characters
// as they are more random than the bottom ones...
rnd.nextBytes(value); // get some random characters
value[3] = BASE64[((value[3] >> 2) & BITS_6)]; // NOSONAR
value[4] = BASE64[((value[4] >> 2) & BITS_6)]; // NOSONAR
value[5] = BASE64[((value[5] >> 2) & BITS_6)]; // NOSONAR
value[6] = BASE64[((value[6] >> 2) & BITS_6)]; // NOSONAR
value[7] = BASE64[((value[7] >> 2) & BITS_6)]; // NOSONAR
// complete the time part in the HIGH value of the token
// this also sets the initial low value
completeToken(rnd);
initialised = true;
}
// fill in LOW value in id
int l = low;
value[0] = BASE64[(l & BITS_6)];
l >>= SHIFT_6;
value[1] = BASE64[(l & BITS_6)];
l >>= SHIFT_6;
value[2] = BASE64[(l & BITS_6)];
String res = new String(value);
// increment LOW
low++;
if (low == LOW_MAX) {
low = 0;
}
if (low == lowLast) {
time = System.currentTimeMillis();
completeToken();
}
return res;
}
} | Get a new token.
@return 14 character String |
public boolean removeReader(Object key, Object resourceId)
{
boolean result = false;
ObjectLocks objectLocks = null;
synchronized(locktable)
{
objectLocks = (ObjectLocks) locktable.get(resourceId);
if(objectLocks != null)
{
/**
* MBAIRD, last one out, close the door and turn off the lights.
* if no locks (readers or writers) exist for this object, let's remove
* it from the locktable.
*/
Map readers = objectLocks.getReaders();
result = readers.remove(key) != null;
if((objectLocks.getWriter() == null) && (readers.size() == 0))
{
locktable.remove(resourceId);
}
}
}
return result;
} | Remove an read lock. |
public boolean removeWriter(Object key, Object resourceId)
{
boolean result = false;
ObjectLocks objectLocks = null;
synchronized(locktable)
{
objectLocks = (ObjectLocks) locktable.get(resourceId);
if(objectLocks != null)
{
/**
* MBAIRD, last one out, close the door and turn off the lights.
* if no locks (readers or writers) exist for this object, let's remove
* it from the locktable.
*/
LockEntry entry = objectLocks.getWriter();
if(entry != null && entry.isOwnedBy(key))
{
objectLocks.setWriter(null);
result = true;
// no need to check if writer is null, we just set it.
if(objectLocks.getReaders().size() == 0)
{
locktable.remove(resourceId);
}
}
}
}
return result;
} | Remove an write lock. |
public void applyDefaults() {
if (getName() == null) {
setName(DEFAULT_NAME);
}
if (getFeatureStyles().size() == 0) {
getFeatureStyles().add(new FeatureStyleInfo());
}
for (FeatureStyleInfo featureStyle : getFeatureStyles()) {
featureStyle.applyDefaults();
}
if (getLabelStyle().getLabelAttributeName() == null) {
getLabelStyle().setLabelAttributeName(LabelStyleInfo.ATTRIBUTE_NAME_ID);
}
getLabelStyle().getBackgroundStyle().applyDefaults();
getLabelStyle().getFontStyle().applyDefaults();
} | Applies default values to all properties that have not been set.
@since 1.10.0 |
private List<StyleFilter> initStyleFilters(List<FeatureStyleInfo> styleDefinitions) throws GeomajasException {
List<StyleFilter> styleFilters = new ArrayList<StyleFilter>();
if (styleDefinitions == null || styleDefinitions.size() == 0) {
styleFilters.add(new StyleFilterImpl()); // use default.
} else {
for (FeatureStyleInfo styleDef : styleDefinitions) {
StyleFilterImpl styleFilterImpl = null;
String formula = styleDef.getFormula();
if (null != formula && formula.length() > 0) {
styleFilterImpl = new StyleFilterImpl(filterService.parseFilter(formula), styleDef);
} else {
styleFilterImpl = new StyleFilterImpl(Filter.INCLUDE, styleDef);
}
styleFilters.add(styleFilterImpl);
}
}
return styleFilters;
} | Build list of style filters from style definitions.
@param styleDefinitions
list of style definitions
@return list of style filters
@throws GeomajasException |
public static List<Artifact> getAllArtifacts(final Module module){
final List<Artifact> artifacts = new ArrayList<Artifact>();
for(final Module subModule: module.getSubmodules()){
artifacts.addAll(getAllArtifacts(subModule));
}
artifacts.addAll(module.getArtifacts());
return artifacts;
} | Returns all the Artifacts of the module
@param module Module
@return List<Artifact> |
public static List<Dependency> getAllDependencies(final Module module) {
final Set<Dependency> dependencies = new HashSet<Dependency>();
final List<String> producedArtifacts = new ArrayList<String>();
for(final Artifact artifact: getAllArtifacts(module)){
producedArtifacts.add(artifact.getGavc());
}
dependencies.addAll(getAllDependencies(module, producedArtifacts));
return new ArrayList<Dependency>(dependencies);
} | Returns all the dependencies of a module
@param module Module
@return List<Dependency> |
public static Set<Dependency> getAllDependencies(final Module module, final List<String> producedArtifacts) {
final Set<Dependency> dependencies = new HashSet<Dependency>();
for(final Dependency dependency: module.getDependencies()){
if(!producedArtifacts.contains(dependency.getTarget().getGavc())){
dependencies.add(dependency);
}
}
for(final Module subModule: module.getSubmodules()){
dependencies.addAll(getAllDependencies(subModule, producedArtifacts));
}
return dependencies;
} | Returns all the dependencies taken into account the artifact of the module that will be removed from the dependencies
@param module Module
@param producedArtifacts List<String>
@return Set<Dependency> |
public static List<Dependency> getCorporateDependencies(final Module module, final List<String> corporateFilters) {
final List<Dependency> corporateDependencies = new ArrayList<Dependency>();
final Pattern corporatePattern = generateCorporatePattern(corporateFilters);
for(final Dependency dependency: getAllDependencies(module)){
if(dependency.getTarget().getGavc().matches(corporatePattern.pattern())){
corporateDependencies.add(dependency);
}
}
return corporateDependencies;
} | Returns the corporate dependencies of a module
@param module Module
@param corporateFilters List<String>
@return List<Dependency> |
protected boolean _load ()
{
java.sql.ResultSet rs = null;
try
{
// This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1
// The documentation says synchronization is done within the driver, but they
// must have overlooked something. Without the lock we'd get mysterious error
// messages.
synchronized(getDbMeta())
{
getDbMetaTreeModel().setStatusBarMessage("Reading columns for table " + getSchema().getCatalog().getCatalogName() + "." + getSchema().getSchemaName() + "." + getTableName());
rs = getDbMeta().getColumns(getSchema().getCatalog().getCatalogName(),
getSchema().getSchemaName(),
getTableName(), "%");
final java.util.ArrayList alNew = new java.util.ArrayList();
while (rs.next())
{
alNew.add(new DBMetaColumnNode(getDbMeta(), getDbMetaTreeModel(), DBMetaTableNode.this, rs.getString("COLUMN_NAME")));
}
alChildren = alNew;
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
getDbMetaTreeModel().nodeStructureChanged(DBMetaTableNode.this);
}
});
rs.close();
}
}
catch (java.sql.SQLException sqlEx)
{
this.getDbMetaTreeModel().reportSqlError("Error retrieving columns", sqlEx);
try
{
if (rs != null) rs.close ();
}
catch (java.sql.SQLException sqlEx2)
{
this.getDbMetaTreeModel().reportSqlError("Error retrieving columns", sqlEx2);
}
return false;
}
return true;
} | Loads the columns for this table into the alChildren list. |
private void configureCaching(HttpServletResponse response, int seconds) {
// HTTP 1.0 header
response.setDateHeader(HTTP_EXPIRES_HEADER, System.currentTimeMillis() + seconds * 1000L);
if (seconds > 0) {
// HTTP 1.1 header
response.setHeader(HTTP_CACHE_CONTROL_HEADER, "max-age=" + seconds);
} else {
// HTTP 1.1 header
response.setHeader(HTTP_CACHE_CONTROL_HEADER, "no-cache");
}
} | Set HTTP headers to allow caching for the given number of seconds.
@param response where to set the caching settings
@param seconds number of seconds into the future that the response should be cacheable for |
public int compare(Object objA, Object objB)
{
String idAStr = ((FieldDescriptorDef)_fields.get(objA)).getProperty("id");
String idBStr = ((FieldDescriptorDef)_fields.get(objB)).getProperty("id");
int idA;
int idB;
try
{
idA = Integer.parseInt(idAStr);
}
catch (Exception ex)
{
return 1;
}
try
{
idB = Integer.parseInt(idBStr);
}
catch (Exception ex)
{
return -1;
}
return idA < idB ? -1 : (idA > idB ? 1 : 0);
} | Compares two fields given by their names.
@param objA The name of the first field
@param objB The name of the second field
@return
@see java.util.Comparator#compare(java.lang.Object, java.lang.Object) |
private Identity getIdentityFromResultSet()
{
try
{
// 1. get an empty instance of the target class
Constructor con = classDescriptor.getZeroArgumentConstructor();
Object obj = ConstructorHelper.instantiate(con);
// 2. fill only primary key values from Resultset
Object colValue;
FieldDescriptor fld;
FieldDescriptor[] pkfields = classDescriptor.getPkFields();
for (int i = 0; i < pkfields.length; i++)
{
fld = pkfields[i];
colValue = fld.getJdbcType().getObjectFromColumn(resultSetAndStatment.m_rs, fld.getColumnName());
fld.getPersistentField().set(obj, colValue);
}
// 3. return the representing identity object
return broker.serviceIdentity().buildIdentity(classDescriptor, obj);
}
catch (SQLException e)
{
throw new PersistenceBrokerSQLException("Error reading object from column", e);
}
catch (Exception e)
{
throw new PersistenceBrokerException("Error reading Identity from result set", e);
}
} | returns an Identity object representing the current resultset row |
public boolean hasMoreElements()
{
try
{
if (!hasCalledCheck)
{
hasCalledCheck = true;
hasNext = resultSetAndStatment.m_rs.next();
}
}
catch (SQLException e)
{
LoggerFactory.getDefaultLogger().error(e);
//releaseDbResources();
hasNext = false;
}
finally
{
if(!hasNext)
{
releaseDbResources();
}
}
return hasNext;
} | Tests if this enumeration contains more elements.
@return <code>true</code> if and only if this enumeration object
contains at least one more element to provide;
<code>false</code> otherwise. |
public Object nextElement()
{
try
{
if (!hasCalledCheck)
{
hasMoreElements();
}
hasCalledCheck = false;
if (hasNext)
{
Identity oid = getIdentityFromResultSet();
Identity[] args = {oid};
return this.constructor.newInstance(args);
}
else
throw new NoSuchElementException();
}
catch (Exception ex)
{
LoggerFactory.getDefaultLogger().error(ex);
throw new NoSuchElementException();
}
} | Returns the next element of this enumeration if this enumeration
object has at least one more element to provide.
@return the next element of this enumeration.
@exception NoSuchElementException if no more elements exist. |
@RequestMapping(value = "/legendgraphic", method = RequestMethod.GET)
public ModelAndView getGraphic(@RequestParam("layerId") String layerId,
@RequestParam(value = "styleName", required = false) String styleName,
@RequestParam(value = "ruleIndex", required = false) Integer ruleIndex,
@RequestParam(value = "format", required = false) String format,
@RequestParam(value = "width", required = false) Integer width,
@RequestParam(value = "height", required = false) Integer height,
@RequestParam(value = "scale", required = false) Double scale,
@RequestParam(value = "allRules", required = false) Boolean allRules, HttpServletRequest request)
throws GeomajasException {
if (!allRules) {
return getGraphic(layerId, styleName, ruleIndex, format, width, height, scale);
} else {
return getGraphics(layerId, styleName, format, width, height, scale);
}
} | Gets a legend graphic with the specified metadata parameters. All parameters are passed as request parameters.
@param layerId
the layer id
@param styleName
the style name
@param ruleIndex
the rule index
@param format
the image format ('png','jpg','gif')
@param width
the graphic's width
@param height
the graphic's height
@param scale
the scale denominator (not supported yet)
@param allRules
if true the image will contain all rules stacked vertically
@param request
the servlet request object
@return the model and view
@throws GeomajasException
when a style or rule does not exist or is not renderable |
@RequestMapping(value = "/legendgraphic/{layerId}/{styleName}/{ruleIndex}.{format}", method = RequestMethod.GET)
public ModelAndView getRuleGraphic(@PathVariable("layerId") String layerId,
@PathVariable("styleName") String styleName, @PathVariable("ruleIndex") Integer ruleIndex,
@PathVariable("format") String format, @RequestParam(value = "width", required = false) Integer width,
@RequestParam(value = "height", required = false) Integer height,
@RequestParam(value = "scale", required = false) Double scale, HttpServletRequest request)
throws GeomajasException {
return getGraphic(layerId, styleName, ruleIndex, format, width, height, scale, false, request);
} | Gets a legend graphic with the specified metadata parameters. Assumes REST URL style:
/legendgraphic/{layerId}/{styleName}/{ruleIndex}.{format}
@param layerId
the layer id
@param styleName
the style name
@param ruleIndex
the rule index, all for a combined image
@param format
the image format ('png','jpg','gif')
@param width
the graphic's width
@param height
the graphic's height
@param scale
the scale denominator (not supported yet)
@param request
the servlet request object
@return the model and view
@throws GeomajasException
when a style or rule does not exist or is not renderable |
public boolean readLock(TransactionImpl tx, Object obj)
{
LockEntry writer = getWriter(obj);
if (writer == null)
{
addReader(tx, obj);
// if there has been a successful write locking, try again
if (getWriter(obj) == null)
return true;
else
{
removeReader(tx, obj);
return readLock(tx, obj);
}
}
if (writer.isOwnedBy(tx))
{
return true; // If I'm the writer, I can read.
}
else
{
return false;
}
} | acquire a read lock on Object obj for Transaction tx.
@param tx the transaction requesting the lock
@param obj the Object to be locked
@return true if successful, else false |
public boolean checkRead(TransactionImpl tx, Object obj)
{
if (hasReadLock(tx, obj))
{
return true;
}
LockEntry writer = getWriter(obj);
if (writer.isOwnedBy(tx))
{
return true;
}
return false;
} | checks whether the specified Object obj is read-locked by Transaction tx.
@param tx the transaction
@param obj the Object to be checked
@return true if lock exists, else false |
public boolean checkWrite(TransactionImpl tx, Object obj)
{
LockEntry writer = getWriter(obj);
if (writer == null)
return false;
else if (writer.isOwnedBy(tx))
return true;
else
return false;
} | checks whether the specified Object obj is write-locked by Transaction tx.
@param tx the transaction
@param obj the Object to be checked
@return true if lock exists, else false |
public void ejbCreate()
{
log.info("ejbCreate was called");
odmg = ODMGHelper.getODMG();
db = odmg.getDatabase(null);
} | Lookup the OJB ODMG implementation.
It's recommended to bind an instance of the Implementation class in JNDI
(at appServer start), open the database and lookup this instance via JNDI in
ejbCreate(). |
private Class getDynamicProxyClass(Class baseClass) {
Class[] m_dynamicProxyClassInterfaces;
if (foundInterfaces.containsKey(baseClass)) {
m_dynamicProxyClassInterfaces = (Class[])foundInterfaces.get(baseClass);
} else {
m_dynamicProxyClassInterfaces = getInterfaces(baseClass);
foundInterfaces.put(baseClass, m_dynamicProxyClassInterfaces);
}
// return dynymic Proxy Class implementing all interfaces
Class proxyClazz = Proxy.getProxyClass(baseClass.getClassLoader(), m_dynamicProxyClassInterfaces);
return proxyClazz;
} | returns a dynamic Proxy that implements all interfaces of the
class described by this ClassDescriptor.
@return Class the dynamically created proxy class |
private Class[] getInterfaces(Class clazz) {
Class superClazz = clazz;
Class[] interfaces = clazz.getInterfaces();
// clazz can be an interface itself and when getInterfaces()
// is called on an interface it returns only the extending
// interfaces, not the interface itself.
if (clazz.isInterface()) {
Class[] tempInterfaces = new Class[interfaces.length + 1];
tempInterfaces[0] = clazz;
System.arraycopy(interfaces, 0, tempInterfaces, 1, interfaces.length);
interfaces = tempInterfaces;
}
// add all interfaces implemented by superclasses to the interfaces array
while ((superClazz = superClazz.getSuperclass()) != null) {
Class[] superInterfaces = superClazz.getInterfaces();
Class[] combInterfaces = new Class[interfaces.length + superInterfaces.length];
System.arraycopy(interfaces, 0, combInterfaces, 0, interfaces.length);
System.arraycopy(superInterfaces, 0, combInterfaces, interfaces.length, superInterfaces.length);
interfaces = combInterfaces;
}
/**
* Must remove duplicate interfaces before calling Proxy.getProxyClass().
* Duplicates can occur if a subclass re-declares that it implements
* the same interface as one of its ancestor classes.
**/
HashMap unique = new HashMap();
for (int i = 0; i < interfaces.length; i++) {
unique.put(interfaces[i].getName(), interfaces[i]);
}
/* Add the OJBProxy interface as well */
unique.put(OJBProxy.class.getName(), OJBProxy.class);
interfaces = (Class[])unique.values().toArray(new Class[unique.size()]);
return interfaces;
} | Get interfaces implemented by clazz
@param clazz
@return |
public void storeUsingNestedPB(List articles, List persons)
{
PersistenceBroker broker = pbf.defaultPersistenceBroker();
try
{
// do something with broker
Query q = new QueryByCriteria(PersonVO.class);
broker.getCollectionByQuery(q);
// System.out.println("## broker1: con=" + broker.serviceConnectionManager().getConnection());
//now use nested bean call
// System.out.println("####### DO nested bean call");
ArticleManagerPBLocal am = getArticleManager();
am.storeArticles(articles);
// System.out.println("####### END nested bean call");
// do more with broker
// System.out.println("## broker1: now store objects");
storeObjects(broker, persons);
// System.out.println("## broker1: end store, con=" + broker.serviceConnectionManager().getConnection());
}
// catch(LookupException e)
// {
// throw new EJBException(e);
// }
finally
{
// System.out.println("## close broker1 now");
if(broker != null) broker.close();
}
} | Stores article and persons using other beans.
@ejb:interface-method |
public void storeUsingSubBeans(List articles, List persons)
{
//store all objects
ArticleManagerPBLocal am = getArticleManager();
PersonManagerPBLocal pm = getPersonManager();
am.storeArticles(articles);
pm.storePersons(persons);
} | Stores article and persons using other beans.
@ejb:interface-method |
public Object getRealKey()
{
if(keyRealSubject != null)
{
return keyRealSubject;
}
else
{
TransactionExt tx = getTransaction();
if((tx != null) && tx.isOpen())
{
prepareKeyRealSubject(tx.getBroker());
}
else
{
if(getPBKey() != null)
{
PBCapsule capsule = new PBCapsule(getPBKey(), null);
try
{
prepareKeyRealSubject(capsule.getBroker());
}
finally
{
capsule.destroy();
}
}
else
{
getLog().warn("No tx, no PBKey - can't materialise key with Identity " + getKeyOid());
}
}
}
return keyRealSubject;
} | Returns the real key object. |
public Object getRealValue()
{
if(valueRealSubject != null)
{
return valueRealSubject;
}
else
{
TransactionExt tx = getTransaction();
if((tx != null) && tx.isOpen())
{
prepareValueRealSubject(tx.getBroker());
}
else
{
if(getPBKey() != null)
{
PBCapsule capsule = new PBCapsule(getPBKey(), null);
try
{
prepareValueRealSubject(capsule.getBroker());
}
finally
{
capsule.destroy();
}
}
else
{
getLog().warn("No tx, no PBKey - can't materialise value with Identity " + getKeyOid());
}
}
}
return valueRealSubject;
} | Returns the real value object. |
public Object setValue(Object obj)
{
Object old = valueRealSubject;
valueRealSubject = obj;
return old;
} | /*
(non-Javadoc)
@see java.util.Map.Entry#setValue(java.lang.Object) |
public void writeToFile(DescriptorRepository repository, ConnectionRepository conRepository, OutputStream out)
{
RepositoryTags tags = RepositoryTags.getInstance();
try
{
if (log.isDebugEnabled())
log.debug("## Write repository file ##" +
repository.toXML() +
"## End of repository file ##");
String eol = SystemUtils.LINE_SEPARATOR;
StringBuffer buf = new StringBuffer();
// 1. write XML header
buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + eol);
buf.append("<!DOCTYPE descriptor-repository SYSTEM \"repository.dtd\" >" + eol + eol);
// strReturn += "<!DOCTYPE descriptor-repository SYSTEM \"repository.dtd\" [" + eol;
// strReturn += "<!ENTITY database-metadata SYSTEM \""+ConnectionRepository.DATABASE_METADATA_FILENAME+"\">" + eol;
// strReturn += "<!ENTITY user SYSTEM \"repository_user.xml\">" + eol;
// strReturn += "<!ENTITY junit SYSTEM \"repository_junit.xml\">" + eol;
// strReturn += "<!ENTITY internal SYSTEM \"repository_internal.xml\"> ]>" + eol + eol;
buf.append("<!-- OJB RepositoryPersistor generated this file on " + new Date().toString() + " -->" + eol);
buf.append(tags.getOpeningTagNonClosingById(RepositoryElements.MAPPING_REPOSITORY) + eol);
buf.append(" " + tags.getAttribute(RepositoryElements.REPOSITORY_VERSION, DescriptorRepository.getVersion()) + eol);
buf.append(" " + tags.getAttribute(RepositoryElements.ISOLATION_LEVEL, repository.getIsolationLevelAsString()) + eol);
buf.append(">" + eol);
if(conRepository != null) buf.append(eol + eol + conRepository.toXML() + eol + eol);
if(repository != null) buf.append(repository.toXML());
buf.append(tags.getClosingTagById(RepositoryElements.MAPPING_REPOSITORY));
PrintWriter pw = new PrintWriter(out);
pw.print(buf.toString());
pw.flush();
pw.close();
}
catch (Exception e)
{
log.error("Could not write to output stream" + out, e);
}
} | Write the {@link DescriptorRepository} to the given output object. |
public DescriptorRepository readDescriptorRepository(String filename)
throws MalformedURLException, ParserConfigurationException, SAXException, IOException
{
DescriptorRepository result;
if (useSerializedRepository)
// use serialized repository
{
// build File object pointing to serialized repository location
Configuration config = OjbConfigurator.getInstance().getConfigurationFor(null);
String pathPrefix = config.getString(SERIALIZED_REPOSITORY_PATH, ".");
File serFile = new File(pathPrefix + File.separator + filename + "." + SER_FILE_SUFFIX);
if (serFile.exists() && serFile.length() > 0)
// if file exists load serialized version of repository
{
try
{
long duration = System.currentTimeMillis();
result = deserialize(serFile);
log.info("Read serialized repository in " + (System.currentTimeMillis() - duration) + " ms");
}
catch (Exception e)
{
log.error("error in loading serialized repository. Will try to use XML version.", e);
result = (DescriptorRepository) buildRepository(filename, DescriptorRepository.class);
}
}
else
// if no serialized version exists, read it from xml and write serialized file
{
long duration = System.currentTimeMillis();
result = (DescriptorRepository) buildRepository(filename, DescriptorRepository.class);
log.info("Read repository from file took " + (System.currentTimeMillis() - duration) + " ms");
serialize(result, serFile);
}
}
// don't use serialized repository
else
{
long duration = System.currentTimeMillis();
result = (DescriptorRepository) buildRepository(filename, DescriptorRepository.class);
log.info("Read class descriptors took " + (System.currentTimeMillis() - duration) + " ms");
}
return result;
} | Read the repository configuration file.
<br>
If configuration property <code>useSerializedRepository</code> is <code>true</code>
all subsequent calls read a serialized version of the repository.
The directory where the serialized repository is stored can be specified
with the <code>serializedRepositoryPath</code> entry in OJB.properties.
Once a serialized repository is found changes to repository.xml will be
ignored. To force consideration of these changes the serialized repository
must be deleted manually. |
public ConnectionRepository readConnectionRepository(String filename)
throws MalformedURLException, ParserConfigurationException, SAXException, IOException
{
long duration = System.currentTimeMillis();
ConnectionRepository result = (ConnectionRepository) buildRepository(filename, ConnectionRepository.class);
log.info("Read connection repository took " + (System.currentTimeMillis() - duration) + " ms");
return result;
} | Read the repository configuration file and extract connection handling information. |
public ConnectionRepository readConnectionRepository(InputStream inst)
throws MalformedURLException, ParserConfigurationException, SAXException, IOException
{
long duration = System.currentTimeMillis();
InputSource inSource = new InputSource(inst);
ConnectionRepository result = (ConnectionRepository) readMetadataFromXML(inSource, ConnectionRepository.class);
log.info("Read connection repository took " + (System.currentTimeMillis() - duration) + " ms");
return result;
} | Read the repository configuration file and extract connection handling information. |
private Object readMetadataFromXML(InputSource source, Class target)
throws MalformedURLException, ParserConfigurationException, SAXException, IOException
{
// TODO: make this configurable
boolean validate = false;
// get a xml reader instance:
SAXParserFactory factory = SAXParserFactory.newInstance();
log.info("RepositoryPersistor using SAXParserFactory : " + factory.getClass().getName());
if (validate)
{
factory.setValidating(true);
}
SAXParser p = factory.newSAXParser();
XMLReader reader = p.getXMLReader();
if (validate)
{
reader.setErrorHandler(new OJBErrorHandler());
}
Object result;
if (DescriptorRepository.class.equals(target))
{
// create an empty repository:
DescriptorRepository repository = new DescriptorRepository();
// create handler for building the repository structure
ContentHandler handler = new RepositoryXmlHandler(repository);
// tell parser to use our handler:
reader.setContentHandler(handler);
reader.parse(source);
result = repository;
}
else if (ConnectionRepository.class.equals(target))
{
// create an empty repository:
ConnectionRepository repository = new ConnectionRepository();
// create handler for building the repository structure
ContentHandler handler = new ConnectionDescriptorXmlHandler(repository);
// tell parser to use our handler:
reader.setContentHandler(handler);
reader.parse(source);
//LoggerFactory.getBootLogger().info("loading XML took " + (stop - start) + " msecs");
result = repository;
}
else
throw new MetadataException("Could not build a repository instance for '" + target +
"', using source " + source);
return result;
} | Read metadata by populating an instance of the target class
using SAXParser. |
public Criteria copy(boolean includeGroupBy, boolean includeOrderBy, boolean includePrefetchedRelationships)
{
Criteria copy = new Criteria();
copy.m_criteria = new Vector(this.m_criteria);
copy.m_negative = this.m_negative;
if (includeGroupBy)
{
copy.groupby = this.groupby;
}
if (includeOrderBy)
{
copy.orderby = this.orderby;
}
if (includePrefetchedRelationships)
{
copy.prefetchedRelationships = this.prefetchedRelationships;
}
return copy;
} | make a copy of the criteria
@param includeGroupBy if true
@param includeOrderBy if ture
@param includePrefetchedRelationships if true
@return a copy of the criteria |
protected List splitInCriteria(Object attribute, Collection values, boolean negative, int inLimit)
{
List result = new ArrayList();
Collection inCollection = new ArrayList();
if (values == null || values.isEmpty())
{
// OQL creates empty Criteria for late binding
result.add(buildInCriteria(attribute, negative, values));
}
else
{
Iterator iter = values.iterator();
while (iter.hasNext())
{
inCollection.add(iter.next());
if (inCollection.size() == inLimit || !iter.hasNext())
{
result.add(buildInCriteria(attribute, negative, inCollection));
inCollection = new ArrayList();
}
}
}
return result;
} | Answer a List of InCriteria based on values, each InCriteria
contains only inLimit values
@param attribute
@param values
@param negative
@param inLimit the maximum number of values for IN (-1 for no limit)
@return List of InCriteria |
public void addEqualTo(String attribute, Object value)
{
// PAW
// addSelectionCriteria(ValueCriteria.buildEqualToCriteria(attribute, value, getAlias()));
addSelectionCriteria(ValueCriteria.buildEqualToCriteria(attribute, value, getUserAlias(attribute)));
} | Adds and equals (=) criteria,
customer_id = 10034
@param attribute The field name to be used
@param value An object representing the value of the field |
public void addColumnEqualTo(String column, Object value)
{
// PAW
// SelectionCriteria c = ValueCriteria.buildEqualToCriteria(column, value, getAlias());
SelectionCriteria c = ValueCriteria.buildEqualToCriteria(column, value, getUserAlias(column));
c.setTranslateAttribute(false);
addSelectionCriteria(c);
} | Adds and equals (=) criteria,
CUST_ID = 10034
attribute will NOT be translated into column name
@param column The column name to be used without translation
@param value An object representing the value of the column |
public void addColumnEqualToField(String column, Object fieldName)
{
// PAW
//SelectionCriteria c = FieldCriteria.buildEqualToCriteria(column, fieldName, getAlias());
SelectionCriteria c = FieldCriteria.buildEqualToCriteria(column, fieldName, getUserAlias(column));
c.setTranslateAttribute(false);
addSelectionCriteria(c);
} | Adds and equals (=) criteria for field comparison.
The field name will be translated into the appropriate columnName by SqlStatement.
The attribute will NOT be translated into column name
@param column The column name to be used without translation
@param fieldName An object representing the value of the field |
public void addEqualToField(String attribute, String fieldName)
{
// PAW
// FieldCriteria c = FieldCriteria.buildEqualToCriteria(attribute, fieldName, getAlias());
FieldCriteria c = FieldCriteria.buildEqualToCriteria(attribute, fieldName, getUserAlias(attribute));
addSelectionCriteria(c);
} | Adds and equals (=) criteria for field comparison.
The field name will be translated into the appropriate columnName by SqlStatement.
<br>
name = boss.name
@param attribute The field name to be used
@param fieldName The field name to compare with |
public void addNotEqualToField(String attribute, String fieldName)
{
// PAW
// SelectionCriteria c = FieldCriteria.buildNotEqualToCriteria(attribute, fieldName, getAlias());
SelectionCriteria c = FieldCriteria.buildNotEqualToCriteria(attribute, fieldName, getUserAlias(attribute));
addSelectionCriteria(c);
} | Adds and equals (=) criteria for field comparison.
The field name will be translated into the appropriate columnName by SqlStatement.
<br>
name <> boss.name
@param attribute The field name to be used
@param fieldName The field name to compare with |
public void addNotEqualToColumn(String attribute, String colName)
{
// PAW
// FieldCriteria c = FieldCriteria.buildNotEqualToCriteria(attribute, colName, getAlias());
FieldCriteria c = FieldCriteria.buildNotEqualToCriteria(attribute, colName, getUserAlias(attribute));
c.setTranslateField(false);
addSelectionCriteria(c);
} | Adds and equals (<>) criteria for column comparison.
The column Name will NOT be translated.
<br>
name <> T_BOSS.LASTNMAE
@param attribute The field name to be used
@param colName The name of the column to compare with |
public void addEqualToColumn(String attribute, String colName)
{
// FieldCriteria c = FieldCriteria.buildEqualToCriteria(attribute, colName, getAlias());
FieldCriteria c = FieldCriteria.buildEqualToCriteria(attribute, colName, getUserAlias(attribute));
c.setTranslateField(false);
addSelectionCriteria(c);
} | Adds and equals (=) criteria for column comparison.
The column Name will NOT be translated.
<br>
name = T_BOSS.LASTNMAE
@param attribute The field name to be used
@param colName The name of the column to compare with |
public void addGreaterOrEqualThan(Object attribute, Object value)
{
// PAW
// addSelectionCriteria(ValueCriteria.buildNotLessCriteria(attribute, value, getAlias()));
addSelectionCriteria(ValueCriteria.buildNotLessCriteria(attribute, value, getUserAlias(attribute)));
} | Adds GreaterOrEqual Than (>=) criteria,
customer_id >= 10034
@param attribute The field name to be used
@param value An object representing the value of the field |
public void addGreaterOrEqualThanField(String attribute, Object value)
{
// PAW
// addSelectionCriteria(FieldCriteria.buildNotLessCriteria(attribute, value, getAlias()));
addSelectionCriteria(FieldCriteria.buildNotLessCriteria(attribute, value, getUserAlias(attribute)));
} | Adds GreaterOrEqual Than (>=) criteria,
customer_id >= person_id
@param attribute The field name to be used
@param value The field name to compare with |
public void addLessOrEqualThan(Object attribute, Object value)
{
// PAW
// addSelectionCriteria(ValueCriteria.buildNotGreaterCriteria(attribute, value, getAlias()));
addSelectionCriteria(ValueCriteria.buildNotGreaterCriteria(attribute, value, getUserAlias(attribute)));
} | Adds LessOrEqual Than (<=) criteria,
customer_id <= 10034
@param attribute The field name to be used
@param value An object representing the value of the field |
public void addLessOrEqualThanField(String attribute, Object value)
{
// PAW
// addSelectionCriteria(FieldCriteria.buildNotGreaterCriteria(attribute, value, getAlias()));
addSelectionCriteria(FieldCriteria.buildNotGreaterCriteria(attribute, value, getUserAlias(attribute)));
} | Adds LessOrEqual Than (<=) criteria,
customer_id <= person_id
@param attribute The field name to be used
@param value The field name to compare with |
public void addLike(Object attribute, Object value)
{
// PAW
// addSelectionCriteria(ValueCriteria.buildLikeCriteria(attribute, value, getAlias()));
addSelectionCriteria(ValueCriteria.buildLikeCriteria(attribute, value, getUserAlias(attribute)));
} | Adds Like (LIKE) criteria,
customer_name LIKE "m%ller"
@see LikeCriteria
@param attribute The field name to be used
@param value An object representing the value of the field |
public void addNotLike(String attribute, Object value)
{
// PAW
// addSelectionCriteria(ValueCriteria.buildNotLikeCriteria(attribute, value, getAlias()));
addSelectionCriteria(ValueCriteria.buildNotLikeCriteria(attribute, value, getUserAlias(attribute)));
} | Adds Like (NOT LIKE) criteria,
customer_id NOT LIKE 10034
@see LikeCriteria
@param attribute The field name to be used
@param value An object representing the value of the field |
public void addNotEqualTo(Object attribute, Object value)
{
// PAW
// addSelectionCriteria(ValueCriteria.buildNotEqualToCriteria(attribute, value, getAlias()));
addSelectionCriteria(ValueCriteria.buildNotEqualToCriteria(attribute, value, getUserAlias(attribute)));
} | Adds NotEqualTo (<>) criteria,
customer_id <> 10034
@param attribute The field name to be used
@param value An object representing the value of the field |
Subsets and Splits