Migrate ALL java files from /src to /src/main/java - OFBIZ-7790
This is the first of two steps in the above mentioned JIRA. This first step changes the java source directory for every component from /src to /src/main/java. The next step will be adding unit tests to every component in /src/test/java Thank you to Deepak Dixit for tips on how to use the SVN commands to make the appropriate file moving. git-svn-id: https://svn.apache.org/repos/asf/ofbiz/trunk@1752838 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
+25
@@ -0,0 +1,25 @@
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
org.ofbiz.entity.util.Converters
|
||||
org.ofbiz.base.conversion.BooleanConverters
|
||||
org.ofbiz.base.conversion.CollectionConverters
|
||||
org.ofbiz.base.conversion.DateTimeConverters
|
||||
org.ofbiz.base.conversion.JSONConverters
|
||||
org.ofbiz.base.conversion.MiscConverters
|
||||
org.ofbiz.base.conversion.NetConverters
|
||||
org.ofbiz.base.conversion.NumberConverters
|
||||
@@ -0,0 +1,18 @@
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
org.ofbiz.entity.DelegatorFactoryImpl
|
||||
@@ -0,0 +1,917 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import org.ofbiz.entity.cache.Cache;
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
import org.ofbiz.entity.datasource.GenericHelper;
|
||||
import org.ofbiz.entity.datasource.GenericHelperInfo;
|
||||
import org.ofbiz.entity.eca.EntityEcaHandler;
|
||||
import org.ofbiz.entity.model.DynamicViewEntity;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelField;
|
||||
import org.ofbiz.entity.model.ModelFieldType;
|
||||
import org.ofbiz.entity.model.ModelFieldTypeReader;
|
||||
import org.ofbiz.entity.model.ModelGroupReader;
|
||||
import org.ofbiz.entity.model.ModelReader;
|
||||
import org.ofbiz.entity.util.DistributedCacheClear;
|
||||
import org.ofbiz.entity.util.EntityCrypto;
|
||||
import org.ofbiz.entity.util.EntityFindOptions;
|
||||
import org.ofbiz.entity.util.EntityListIterator;
|
||||
import org.ofbiz.entity.util.EntityStoreOptions;
|
||||
import org.ofbiz.entity.util.SequenceUtil;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
public interface Delegator {
|
||||
|
||||
enum OperationType {INSERT, UPDATE, DELETE}
|
||||
|
||||
void clearAllCacheLinesByDummyPK(Collection<GenericPK> dummyPKs);
|
||||
|
||||
void clearAllCacheLinesByValue(Collection<GenericValue> values);
|
||||
|
||||
/**
|
||||
* This method is a shortcut to completely clear all entity engine caches.
|
||||
* For performance reasons this should not be called very often.
|
||||
*/
|
||||
void clearAllCaches();
|
||||
|
||||
void clearAllCaches(boolean distribute);
|
||||
|
||||
/**
|
||||
* Remove a CACHED Generic Entity from the cache by its primary key, does
|
||||
* NOT check to see if the passed GenericPK is a complete primary key. Also
|
||||
* tries to clear the corresponding all cache entry.
|
||||
*
|
||||
* @param primaryKey
|
||||
* The primary key to clear by.
|
||||
*/
|
||||
void clearCacheLine(GenericPK primaryKey);
|
||||
|
||||
void clearCacheLine(GenericPK primaryKey, boolean distribute);
|
||||
|
||||
/**
|
||||
* Remove a CACHED GenericValue from as many caches as it can. Automatically
|
||||
* tries to remove entries from the all cache, the by primary key cache, and
|
||||
* the by and cache. This is the ONLY method that tries to clear
|
||||
* automatically from the by and cache.
|
||||
*
|
||||
* @param value
|
||||
* The GenericValue to clear by.
|
||||
*/
|
||||
void clearCacheLine(GenericValue value);
|
||||
|
||||
void clearCacheLine(GenericValue value, boolean distribute);
|
||||
|
||||
/**
|
||||
* Remove all CACHED Generic Entity (List) from the cache
|
||||
*
|
||||
* @param entityName
|
||||
* The Name of the Entity as defined in the entity XML file
|
||||
*/
|
||||
void clearCacheLine(String entityName);
|
||||
|
||||
/**
|
||||
* Remove a CACHED Generic Entity (List) from the cache, either a PK, ByAnd,
|
||||
* or All
|
||||
*
|
||||
* @param entityName
|
||||
* The Name of the Entity as defined in the entity XML file
|
||||
* @param fields
|
||||
* The fields of the named entity to query by with their
|
||||
* corresponding values
|
||||
*/
|
||||
void clearCacheLine(String entityName, Map<String, ? extends Object> fields);
|
||||
|
||||
/**
|
||||
* Remove a CACHED Generic Entity (List) from the cache, either a PK, ByAnd,
|
||||
* or All
|
||||
*
|
||||
* @param entityName
|
||||
* The Name of the Entity as defined in the entity XML file
|
||||
* @param fields
|
||||
* The fields of the named entity to query by with their
|
||||
* corresponding values
|
||||
*/
|
||||
void clearCacheLine(String entityName, Object... fields);
|
||||
|
||||
void clearCacheLineByCondition(String entityName, EntityCondition condition);
|
||||
|
||||
void clearCacheLineByCondition(String entityName, EntityCondition condition, boolean distribute);
|
||||
|
||||
/**
|
||||
* Remove a CACHED Generic Entity from the cache by its primary key. Checks
|
||||
* to see if the passed GenericPK is a complete primary key, if it is then
|
||||
* the cache line will be removed from the primaryKeyCache; if it is NOT a
|
||||
* complete primary key it will remove the cache line from the andCache. If
|
||||
* the fields map is empty, then the allCache for the entity will be
|
||||
* cleared.
|
||||
*
|
||||
* @param dummyPK
|
||||
* The dummy primary key to clear by.
|
||||
*/
|
||||
void clearCacheLineFlexible(GenericEntity dummyPK);
|
||||
|
||||
void clearCacheLineFlexible(GenericEntity dummyPK, boolean distribute);
|
||||
|
||||
Delegator cloneDelegator();
|
||||
|
||||
Delegator cloneDelegator(String delegatorName);
|
||||
|
||||
/**
|
||||
* Creates a Entity in the form of a GenericValue and write it to the
|
||||
* datasource
|
||||
*
|
||||
* @param primaryKey
|
||||
* The GenericPK to create a value in the datasource from
|
||||
* @return GenericValue instance containing the new instance
|
||||
*/
|
||||
GenericValue create(GenericPK primaryKey) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Creates a Entity in the form of a GenericValue and write it to the
|
||||
* datasource
|
||||
*
|
||||
* @param value
|
||||
* The GenericValue to create a value in the datasource from
|
||||
* @return GenericValue instance containing the new instance
|
||||
*/
|
||||
GenericValue create(GenericValue value) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Creates a Entity in the form of a GenericValue and write it to the
|
||||
* database
|
||||
*
|
||||
* @return GenericValue instance containing the new instance
|
||||
*/
|
||||
GenericValue create(String entityName, Map<String, ? extends Object> fields) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Creates a Entity in the form of a GenericValue and write it to the
|
||||
* database
|
||||
*
|
||||
* @return GenericValue instance containing the new instance
|
||||
*/
|
||||
GenericValue create(String entityName, Object... fields) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Creates or stores an Entity
|
||||
*
|
||||
* @param value
|
||||
* The GenericValue instance containing the new or existing
|
||||
* instance
|
||||
* @return GenericValue instance containing the new or updated instance
|
||||
*/
|
||||
GenericValue createOrStore(GenericValue value) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Sets the sequenced ID (for entity with one primary key field ONLY), and
|
||||
* then does a create in the database as normal. The reason to do it this
|
||||
* way is that it will retry and fix the sequence if somehow the sequencer
|
||||
* is in a bad state and returning a value that already exists.
|
||||
*
|
||||
* @param value
|
||||
* The GenericValue to create a value in the datasource from
|
||||
* @return GenericValue instance containing the new instance
|
||||
*/
|
||||
GenericValue createSetNextSeqId(GenericValue value) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Creates a Entity in the form of a GenericValue and write it to the
|
||||
* database
|
||||
*
|
||||
* @return GenericValue instance containing the new instance
|
||||
*/
|
||||
GenericValue createSingle(String entityName, Object singlePkValue) throws GenericEntityException;
|
||||
|
||||
@Deprecated
|
||||
Object decryptFieldValue(String entityName, String encValue) throws EntityCryptoException;
|
||||
|
||||
Object decryptFieldValue(String entityName, ModelField.EncryptMethod encryptMethod, String encValue) throws EntityCryptoException;
|
||||
|
||||
Object encryptFieldValue(String entityName, ModelField.EncryptMethod encryptMethod, Object fieldValue) throws EntityCryptoException;
|
||||
|
||||
/**
|
||||
* Finds GenericValues by the conditions specified in the EntityCondition
|
||||
* object, the the EntityCondition javadoc for more details.
|
||||
*
|
||||
* @param entityName
|
||||
* The name of the Entity as defined in the entity XML file
|
||||
* @param whereEntityCondition
|
||||
* The EntityCondition object that specifies how to constrain
|
||||
* this query before any groupings are done (if this is a view
|
||||
* entity with group-by aliases)
|
||||
* @param havingEntityCondition
|
||||
* The EntityCondition object that specifies how to constrain
|
||||
* this query after any groupings are done (if this is a view
|
||||
* entity with group-by aliases)
|
||||
* @param fieldsToSelect
|
||||
* The fields of the named entity to get from the database; if
|
||||
* empty or null all fields will be retreived
|
||||
* @param orderBy
|
||||
* The fields of the named entity to order the query by;
|
||||
* optionally add a " ASC" for ascending or " DESC" for
|
||||
* descending
|
||||
* @param findOptions
|
||||
* An instance of EntityFindOptions that specifies advanced query
|
||||
* options. See the EntityFindOptions JavaDoc for more details.
|
||||
* @return EntityListIterator representing the result of the query: NOTE
|
||||
* THAT THIS MUST BE CLOSED (preferably in a finally block) WHEN YOU
|
||||
* ARE DONE WITH IT, AND DON'T LEAVE IT OPEN TOO LONG BEACUSE IT
|
||||
* WILL MAINTAIN A DATABASE CONNECTION.
|
||||
*/
|
||||
EntityListIterator find(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Set<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Finds all Generic entities
|
||||
*
|
||||
* @param entityName
|
||||
* The Name of the Entity as defined in the entity XML file
|
||||
* @param useCache
|
||||
* Whether to cache the results
|
||||
* @return List containing all Generic entities
|
||||
*/
|
||||
List<GenericValue> findAll(String entityName, boolean useCache) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Finds Generic Entity records by all of the specified fields (ie: combined
|
||||
* using AND), looking first in the cache; uses orderBy for lookup, but only
|
||||
* keys results on the entityName and fields
|
||||
*
|
||||
* @param entityName
|
||||
* The Name of the Entity as defined in the entity XML file
|
||||
* @param fields
|
||||
* The fields of the named entity to query by with their
|
||||
* corresponding values
|
||||
* @param orderBy
|
||||
* The fields of the named entity to order the query by;
|
||||
* optionally add a " ASC" for ascending or " DESC" for
|
||||
* descending
|
||||
* @param useCache
|
||||
* Whether to cache the results
|
||||
* @return List of GenericValue instances that match the query
|
||||
*/
|
||||
List<GenericValue> findByAnd(String entityName, Map<String, ? extends Object> fields, List<String> orderBy, boolean useCache) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Find a Generic Entity by its Primary Key and only returns the values
|
||||
* requested by the passed keys (names).
|
||||
*
|
||||
* @param primaryKey
|
||||
* The primary key to find by.
|
||||
* @param keys
|
||||
* The keys, or names, of the values to retrieve; only these
|
||||
* values will be retrieved
|
||||
* @return The GenericValue corresponding to the primaryKey
|
||||
*/
|
||||
GenericValue findByPrimaryKeyPartial(GenericPK primaryKey, Set<String> keys) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Gets the hit count of GenericValues for the given EntityCondition objects.
|
||||
*
|
||||
* @param entityName
|
||||
* @param whereEntityCondition
|
||||
* @param havingEntityCondition
|
||||
* @param findOptions
|
||||
* @return long value with hit count
|
||||
* @throws GenericEntityException
|
||||
*/
|
||||
long findCountByCondition(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, EntityFindOptions findOptions) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Finds GenericValues by the conditions specified in the EntityCondition
|
||||
* object, the the EntityCondition javadoc for more details.
|
||||
*
|
||||
* @param entityName
|
||||
* The name of the Entity as defined in the entity XML file
|
||||
* @param entityCondition
|
||||
* The EntityCondition object that specifies how to constrain
|
||||
* this query before any groupings are done (if this is a view
|
||||
* entity with group-by aliases)
|
||||
* @param fieldsToSelect
|
||||
* The fields of the named entity to get from the database; if
|
||||
* empty or null all fields will be retrieved
|
||||
* @param orderBy
|
||||
* The fields of the named entity to order the query by;
|
||||
* optionally add a " ASC" for ascending or " DESC" for
|
||||
* descending
|
||||
* @param findOptions
|
||||
* An instance of EntityFindOptions that specifies advanced query
|
||||
* options. See the EntityFindOptions JavaDoc for more details.
|
||||
* @return List of GenericValue objects representing the result
|
||||
*/
|
||||
List<GenericValue> findList(String entityName, EntityCondition entityCondition, Set<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions, boolean useCache) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Finds GenericValues by the conditions specified in the EntityCondition
|
||||
* object, the the EntityCondition javadoc for more details.
|
||||
*
|
||||
* @param dynamicViewEntity
|
||||
* The DynamicViewEntity to use for the entity model for this
|
||||
* query; generally created on the fly for limited use
|
||||
* @param whereEntityCondition
|
||||
* The EntityCondition object that specifies how to constrain
|
||||
* this query before any groupings are done (if this is a view
|
||||
* entity with group-by aliases)
|
||||
* @param havingEntityCondition
|
||||
* The EntityCondition object that specifies how to constrain
|
||||
* this query after any groupings are done (if this is a view
|
||||
* entity with group-by aliases)
|
||||
* @param fieldsToSelect
|
||||
* The fields of the named entity to get from the database; if
|
||||
* empty or null all fields will be retreived
|
||||
* @param orderBy
|
||||
* The fields of the named entity to order the query by;
|
||||
* optionally add a " ASC" for ascending or " DESC" for
|
||||
* descending
|
||||
* @param findOptions
|
||||
* An instance of EntityFindOptions that specifies advanced query
|
||||
* options. See the EntityFindOptions JavaDoc for more details.
|
||||
* @return EntityListIterator representing the result of the query: NOTE
|
||||
* THAT THIS MUST BE CLOSED WHEN YOU ARE DONE WITH IT, AND DON'T
|
||||
* LEAVE IT OPEN TOO LONG BEACUSE IT WILL MAINTAIN A DATABASE
|
||||
* CONNECTION.
|
||||
*/
|
||||
EntityListIterator findListIteratorByCondition(DynamicViewEntity dynamicViewEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Collection<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Find a Generic Entity by its primary key.
|
||||
*
|
||||
* @param entityName The Name of the Entity as defined in the entity XML file
|
||||
* @param useCache Retrieve the Generic Entity from the cache when <code>true</code>
|
||||
* @param fields The fields of the named entity to query by with their corresponding values
|
||||
* @return The Generic Entity corresponding to the primary key
|
||||
* @throws GenericEntityException
|
||||
*/
|
||||
GenericValue findOne(String entityName, boolean useCache, Object... fields) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Find a Generic Entity by its Primary Key
|
||||
*
|
||||
* @param entityName
|
||||
* The Name of the Entity as defined in the entity XML file
|
||||
* @param fields
|
||||
* The fields of the named entity to query by with their
|
||||
* corresponding values
|
||||
* @return The GenericValue corresponding to the primaryKey
|
||||
*/
|
||||
GenericValue findOne(String entityName, Map<String, ? extends Object> fields, boolean useCache) throws GenericEntityException;
|
||||
|
||||
Cache getCache();
|
||||
|
||||
String getCurrentSessionIdentifier();
|
||||
|
||||
String getCurrentUserIdentifier();
|
||||
|
||||
String getDelegatorName();
|
||||
|
||||
String getDelegatorBaseName();
|
||||
|
||||
String getDelegatorTenantId();
|
||||
|
||||
<T> EntityEcaHandler<T> getEntityEcaHandler();
|
||||
|
||||
/**
|
||||
* Gets a field type instance by name from the helper that corresponds to
|
||||
* the specified entity
|
||||
*
|
||||
* @param entity
|
||||
* The entity
|
||||
* @param type
|
||||
* The name of the type
|
||||
* @return ModelFieldType instance for the named type from the helper that
|
||||
* corresponds to the specified entity
|
||||
*/
|
||||
ModelFieldType getEntityFieldType(ModelEntity entity, String type) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Gets field type names from the helper that corresponds to the specified
|
||||
* entity
|
||||
*
|
||||
* @param entity
|
||||
* The entity
|
||||
* @return Collection of field type names from the helper that corresponds
|
||||
* to the specified entity
|
||||
*/
|
||||
Collection<String> getEntityFieldTypeNames(ModelEntity entity) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Gets the helper name that corresponds to this delegator and the specified
|
||||
* entityName
|
||||
*
|
||||
* @param entityName
|
||||
* The name of the entity to get the helper for
|
||||
* @return String with the helper name that corresponds to this delegator
|
||||
* and the specified entityName
|
||||
*/
|
||||
String getEntityGroupName(String entityName);
|
||||
|
||||
/**
|
||||
* Gets the an instance of helper that corresponds to this delegator and the
|
||||
* specified entity
|
||||
*
|
||||
* @param entity
|
||||
* The entity to get the helper for
|
||||
* @return GenericHelper that corresponds to this delegator and the
|
||||
* specified entity
|
||||
*/
|
||||
GenericHelper getEntityHelper(ModelEntity entity) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Gets the an instance of helper that corresponds to this delegator and the
|
||||
* specified entityName
|
||||
*
|
||||
* @param entityName
|
||||
* The name of the entity to get the helper for
|
||||
* @return GenericHelper that corresponds to this delegator and the
|
||||
* specified entityName
|
||||
*/
|
||||
GenericHelper getEntityHelper(String entityName) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Gets the helper name that corresponds to this delegator and the specified
|
||||
* entity
|
||||
*
|
||||
* @param entity
|
||||
* The entity to get the helper for
|
||||
* @return String with the helper name that corresponds to this delegator
|
||||
* and the specified entity
|
||||
*/
|
||||
String getEntityHelperName(ModelEntity entity);
|
||||
|
||||
/**
|
||||
* Gets the helper name that corresponds to this delegator and the specified
|
||||
* entityName
|
||||
*
|
||||
* @param entityName
|
||||
* The name of the entity to get the helper name for
|
||||
* @return String with the helper name that corresponds to this delegator
|
||||
* and the specified entityName
|
||||
*/
|
||||
String getEntityHelperName(String entityName);
|
||||
|
||||
GenericValue getFromPrimaryKeyCache(GenericPK primaryKey);
|
||||
|
||||
/**
|
||||
* Gets the helper name that corresponds to this delegator and the specified
|
||||
* entityName
|
||||
*
|
||||
* @param groupName
|
||||
* The name of the group to get the helper name for
|
||||
* @return String with the helper name that corresponds to this delegator
|
||||
* and the specified entityName
|
||||
*/
|
||||
String getGroupHelperName(String groupName);
|
||||
|
||||
GenericHelperInfo getGroupHelperInfo(String entityGroupName);
|
||||
|
||||
/**
|
||||
* Gets the instance of ModelEntity that corresponds to this delegator and
|
||||
* the specified entityName
|
||||
*
|
||||
* @param entityName
|
||||
* The name of the entity to get
|
||||
* @return ModelEntity that corresponds to this delegator and the specified
|
||||
* entityName
|
||||
*/
|
||||
ModelEntity getModelEntity(String entityName);
|
||||
|
||||
/**
|
||||
* Gets a Map of entity name & entity model pairs that are in the named
|
||||
* group
|
||||
*
|
||||
* @param groupName
|
||||
* The name of the group
|
||||
* @return Map of entityName String keys and ModelEntity instance values
|
||||
*/
|
||||
Map<String, ModelEntity> getModelEntityMapByGroup(String groupName) throws GenericEntityException;
|
||||
|
||||
ModelFieldTypeReader getModelFieldTypeReader(ModelEntity entity);
|
||||
|
||||
/**
|
||||
* Gets the instance of ModelGroupReader that corresponds to this delegator
|
||||
*
|
||||
* @return ModelGroupReader that corresponds to this delegator
|
||||
*/
|
||||
ModelGroupReader getModelGroupReader();
|
||||
|
||||
/**
|
||||
* Gets the instance of ModelReader that corresponds to this delegator
|
||||
*
|
||||
* @return ModelReader that corresponds to this delegator
|
||||
*/
|
||||
ModelReader getModelReader();
|
||||
|
||||
/**
|
||||
* Get the named Related Entity for the GenericValue from the persistent
|
||||
* store across another Relation. Helps to get related Values in a
|
||||
* multi-to-multi relationship.
|
||||
*
|
||||
* @param relationNameOne
|
||||
* String containing the relation name which is the combination
|
||||
* of relation.title and relation.rel-entity-name as specified in
|
||||
* the entity XML definition file, for first relation
|
||||
* @param relationNameTwo
|
||||
* String containing the relation name for second relation
|
||||
* @param value
|
||||
* GenericValue instance containing the entity
|
||||
* @param orderBy
|
||||
* The fields of the named entity to order the query by; may be
|
||||
* null; optionally add a " ASC" for ascending or " DESC" for
|
||||
* descending
|
||||
* @return List of GenericValue instances as specified in the relation
|
||||
* definition
|
||||
*/
|
||||
List<GenericValue> getMultiRelation(GenericValue value, String relationNameOne, String relationNameTwo, List<String> orderBy) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Get the next guaranteed unique seq id from the sequence with the given
|
||||
* sequence name; if the named sequence doesn't exist, it will be created
|
||||
*
|
||||
* @param seqName
|
||||
* The name of the sequence to get the next seq id from
|
||||
* @return String with the next sequenced id for the given sequence name
|
||||
*/
|
||||
String getNextSeqId(String seqName);
|
||||
|
||||
/**
|
||||
* Get the next guaranteed unique seq id from the sequence with the given
|
||||
* sequence name; if the named sequence doesn't exist, it will be created
|
||||
*
|
||||
* @param seqName
|
||||
* The name of the sequence to get the next seq id from
|
||||
* @param staggerMax
|
||||
* The maximum amount to stagger the sequenced ID, if 1 the
|
||||
* sequence will be incremented by 1, otherwise the current
|
||||
* sequence ID will be incremented by a value between 1 and
|
||||
* staggerMax
|
||||
* @return Long with the next seq id for the given sequence name
|
||||
*/
|
||||
String getNextSeqId(String seqName, long staggerMax);
|
||||
|
||||
/**
|
||||
* Get the next guaranteed unique seq id from the sequence with the given
|
||||
* sequence name; if the named sequence doesn't exist, it will be created
|
||||
*
|
||||
* @param seqName
|
||||
* The name of the sequence to get the next seq id from
|
||||
* @return Long with the next sequenced id for the given sequence name
|
||||
*/
|
||||
Long getNextSeqIdLong(String seqName);
|
||||
|
||||
/**
|
||||
* Get the next guaranteed unique seq id from the sequence with the given
|
||||
* sequence name; if the named sequence doesn't exist, it will be created
|
||||
*
|
||||
* @param seqName
|
||||
* The name of the sequence to get the next seq id from
|
||||
* @param staggerMax
|
||||
* The maximum amount to stagger the sequenced ID, if 1 the
|
||||
* sequence will be incremented by 1, otherwise the current
|
||||
* sequence ID will be incremented by a value between 1 and
|
||||
* staggerMax
|
||||
* @return Long with the next seq id for the given sequence name
|
||||
*/
|
||||
Long getNextSeqIdLong(String seqName, long staggerMax);
|
||||
|
||||
/**
|
||||
* Gets the name of the server configuration that corresponds to this
|
||||
* delegator
|
||||
*
|
||||
* @return server configuration name
|
||||
*/
|
||||
String getOriginalDelegatorName();
|
||||
|
||||
/**
|
||||
* Get the named Related Entity for the GenericValue from the persistent
|
||||
* store
|
||||
*
|
||||
* @param relationName
|
||||
* String containing the relation name which is the combination
|
||||
* of relation.title and relation.rel-entity-name as specified in
|
||||
* the entity XML definition file
|
||||
* @param byAndFields
|
||||
* the fields that must equal in order to keep; may be null
|
||||
* @param orderBy
|
||||
* The fields of the named entity to order the query by; may be
|
||||
* null; optionally add a " ASC" for ascending or " DESC" for
|
||||
* descending
|
||||
* @param value
|
||||
* GenericValue instance containing the entity
|
||||
* @param useCache
|
||||
* Whether to cache the results
|
||||
* @return List of GenericValue instances as specified in the relation
|
||||
* definition
|
||||
*/
|
||||
List<GenericValue> getRelated(String relationName, Map<String, ? extends Object> byAndFields, List<String> orderBy, GenericValue value, boolean useCache) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Get a dummy primary key for the named Related Entity for the GenericValue.
|
||||
*
|
||||
* @param relationName
|
||||
* String containing the relation name which is the combination
|
||||
* of relation.title and relation.rel-entity-name as specified in
|
||||
* the entity XML definition file
|
||||
* @param byAndFields
|
||||
* the fields that must equal in order to keep; may be null
|
||||
* @param value
|
||||
* GenericValue instance containing the entity
|
||||
* @return GenericPK containing a possibly incomplete PrimaryKey object
|
||||
* representing the related entity or entities
|
||||
*/
|
||||
GenericPK getRelatedDummyPK(String relationName, Map<String, ? extends Object> byAndFields, GenericValue value) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Get related entity where relation is of type one, uses findByPrimaryKey
|
||||
*
|
||||
* @param relationName
|
||||
* String containing the relation name which is the combination
|
||||
* of relation.title and relation.rel-entity-name as specified in
|
||||
* the entity XML definition file
|
||||
* @param value
|
||||
* GenericValue instance containing the entity
|
||||
* @param useCache
|
||||
* Whether to cache the results
|
||||
* @return GenericValue that is the related entity
|
||||
* @throws IllegalArgumentException
|
||||
* if the list found has more than one item
|
||||
*/
|
||||
GenericValue getRelatedOne(String relationName, GenericValue value, boolean useCache) throws GenericEntityException;
|
||||
|
||||
void initEntityEcaHandler();
|
||||
|
||||
void initDistributedCacheClear();
|
||||
|
||||
GenericPK makePK(Element element);
|
||||
|
||||
/** Creates a Primary Key in the form of a GenericPK without persisting it */
|
||||
GenericPK makePK(String entityName);
|
||||
|
||||
/** Creates a Primary Key in the form of a GenericPK without persisting it */
|
||||
GenericPK makePK(String entityName, Map<String, ? extends Object> fields);
|
||||
|
||||
/** Creates a Primary Key in the form of a GenericPK without persisting it */
|
||||
GenericPK makePK(String entityName, Object... fields);
|
||||
|
||||
/** Creates a Primary Key in the form of a GenericPK without persisting it */
|
||||
GenericPK makePKSingle(String entityName, Object singlePkValue);
|
||||
|
||||
Delegator makeTestDelegator(String delegatorName);
|
||||
|
||||
/**
|
||||
* Creates a Entity in the form of a GenericValue without persisting it;
|
||||
* only valid fields will be pulled from the fields Map
|
||||
*/
|
||||
GenericValue makeValidValue(String entityName, Map<String, ? extends Object> fields);
|
||||
|
||||
/**
|
||||
* Creates a Entity in the form of a GenericValue without persisting it;
|
||||
* only valid fields will be pulled from the fields Map
|
||||
*/
|
||||
GenericValue makeValidValue(String entityName, Object... fields);
|
||||
|
||||
GenericValue makeValue(Element element);
|
||||
|
||||
/** Creates a Entity in the form of a GenericValue without persisting it */
|
||||
GenericValue makeValue(String entityName);
|
||||
|
||||
/** Creates a Entity in the form of a GenericValue without persisting it */
|
||||
GenericValue makeValue(String entityName, Map<String, ? extends Object> fields);
|
||||
|
||||
/** Creates a Entity in the form of a GenericValue without persisting it */
|
||||
GenericValue makeValue(String entityName, Object... fields);
|
||||
|
||||
List<GenericValue> makeValues(Document document);
|
||||
|
||||
/** Creates a Entity in the form of a GenericValue without persisting it */
|
||||
GenericValue makeValueSingle(String entityName, Object singlePkValue);
|
||||
|
||||
void putAllInPrimaryKeyCache(List<GenericValue> values);
|
||||
|
||||
void putInPrimaryKeyCache(GenericPK primaryKey, GenericValue value);
|
||||
|
||||
// ======= XML Related Methods ========
|
||||
List<GenericValue> readXmlDocument(URL url) throws SAXException, ParserConfigurationException, java.io.IOException;
|
||||
|
||||
/**
|
||||
* Refresh the Entity for the GenericValue from the persistent store
|
||||
*
|
||||
* @param value
|
||||
* GenericValue instance containing the entity to refresh
|
||||
*/
|
||||
void refresh(GenericValue value) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Refresh the Entity for the GenericValue from the cache
|
||||
*
|
||||
* @param value
|
||||
* GenericValue instance containing the entity to refresh
|
||||
*/
|
||||
void refreshFromCache(GenericValue value) throws GenericEntityException;
|
||||
|
||||
/** Refreshes the ID sequencer clearing all cached bank values. */
|
||||
void refreshSequencer();
|
||||
|
||||
/**
|
||||
* Remove the Entities from the List from the persistent store. <br/>The
|
||||
* List contains GenericEntity objects, can be either GenericPK or
|
||||
* GenericValue. <br/>If a certain entity contains a complete primary key,
|
||||
* the entity in the datasource corresponding to that primary key will be
|
||||
* removed, this is like a removeByPrimary Key. <br/>On the other hand, if a
|
||||
* certain entity is an incomplete or non primary key, if will behave like
|
||||
* the removeByAnd method. <br/>These updates all happen in one transaction,
|
||||
* so they will either all succeed or all fail, if the data source supports
|
||||
* transactions.
|
||||
*
|
||||
* @param dummyPKs
|
||||
* Collection of GenericEntity instances containing the entities
|
||||
* or by and fields to remove
|
||||
* @return int representing number of rows effected by this operation
|
||||
*/
|
||||
int removeAll(List<? extends GenericEntity> dummyPKs) throws GenericEntityException;
|
||||
|
||||
int removeAll(String entityName) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Removes/deletes Generic Entity records found by all of the specified
|
||||
* fields (ie: combined using AND)
|
||||
*
|
||||
* @param entityName
|
||||
* The Name of the Entity as defined in the entity XML file
|
||||
* @param fields
|
||||
* The fields of the named entity to query by with their
|
||||
* corresponding values
|
||||
* @return int representing number of rows effected by this operation
|
||||
*/
|
||||
int removeByAnd(String entityName, Map<String, ? extends Object> fields) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Removes/deletes Generic Entity records found by all of the specified
|
||||
* fields (ie: combined using AND)
|
||||
*
|
||||
* @param entityName
|
||||
* The Name of the Entity as defined in the entity XML file
|
||||
* @param fields
|
||||
* The fields of the named entity to query by with their
|
||||
* corresponding values
|
||||
* @return int representing number of rows effected by this operation
|
||||
*/
|
||||
int removeByAnd(String entityName, Object... fields) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Removes/deletes Generic Entity records found by the condition
|
||||
*
|
||||
* @param entityName
|
||||
* The Name of the Entity as defined in the entity XML file
|
||||
* @param condition
|
||||
* The condition used to restrict the removing
|
||||
* @return int representing number of rows effected by this operation
|
||||
*/
|
||||
int removeByCondition(String entityName, EntityCondition condition) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Remove a Generic Entity corresponding to the primaryKey
|
||||
*
|
||||
* @param primaryKey
|
||||
* The primary key of the entity to remove.
|
||||
* @return int representing number of rows effected by this operation
|
||||
*/
|
||||
int removeByPrimaryKey(GenericPK primaryKey) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Remove the named Related Entity for the GenericValue from the persistent
|
||||
* store
|
||||
*
|
||||
* @param relationName
|
||||
* String containing the relation name which is the combination
|
||||
* of relation.title and relation.rel-entity-name as specified in
|
||||
* the entity XML definition file
|
||||
* @param value
|
||||
* GenericValue instance containing the entity
|
||||
* @return int representing number of rows effected by this operation
|
||||
*/
|
||||
int removeRelated(String relationName, GenericValue value) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Remove a Generic Value from the database
|
||||
*
|
||||
* @param value
|
||||
* The GenericValue object of the entity to remove.
|
||||
* @return int representing number of rows effected by this operation
|
||||
*/
|
||||
int removeValue(GenericValue value) throws GenericEntityException;
|
||||
|
||||
void rollback();
|
||||
|
||||
void setDistributedCacheClear(DistributedCacheClear distributedCacheClear);
|
||||
|
||||
void setEntityCrypto(EntityCrypto crypto);
|
||||
|
||||
<T> void setEntityEcaHandler(EntityEcaHandler<T> entityEcaHandler);
|
||||
|
||||
/**
|
||||
* Look at existing values for a sub-entity with a sequenced secondary ID,
|
||||
* and get the highest plus 1
|
||||
*/
|
||||
void setNextSubSeqId(GenericValue value, String seqFieldName, int numericPadding, int incrementBy);
|
||||
|
||||
/**
|
||||
* Allows you to pass a SequenceUtil class (possibly one that overrides the
|
||||
* getNextSeqId method); if null is passed will effectively refresh the
|
||||
* sequencer.
|
||||
*/
|
||||
void setSequencer(SequenceUtil sequencer);
|
||||
|
||||
/**
|
||||
* Store the Entity from the GenericValue to the persistent store
|
||||
*
|
||||
* @param value
|
||||
* GenericValue instance containing the entity
|
||||
* @return int representing number of rows effected by this operation
|
||||
*/
|
||||
int store(GenericValue value) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Store the Entities from the List GenericValue instances to the persistent
|
||||
* store. <br/>This is different than the normal store method in that the
|
||||
* store method only does an update, while the storeAll method checks to see
|
||||
* if each entity exists, then either does an insert or an update as
|
||||
* appropriate. <br/>These updates all happen in one transaction, so they
|
||||
* will either all succeed or all fail, if the data source supports
|
||||
* transactions. This is just like to othersToStore feature of the
|
||||
* GenericEntity on a create or store.
|
||||
*
|
||||
* @param values
|
||||
* List of GenericValue instances containing the entities to
|
||||
* store
|
||||
* @return int representing number of rows effected by this operation
|
||||
*/
|
||||
int storeAll(List<GenericValue> values) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Store the Entities from the List GenericValue instances to the persistent
|
||||
* store. <br/>This is different than the normal store method in that the
|
||||
* store method only does an update, while the storeAll method checks to see
|
||||
* if each entity exists, then either does an insert or an update as
|
||||
* appropriate. <br/>These updates all happen in one transaction, so they
|
||||
* will either all succeed or all fail, if the data source supports
|
||||
* transactions. This is just like to othersToStore feature of the
|
||||
* GenericEntity on a create or store.
|
||||
*
|
||||
* @param storeOptions
|
||||
* An instance of EntityStoreOptions that specifies advanced store
|
||||
* options or null for default values.
|
||||
* See the EntityStoreOptions JavaDoc for more details.
|
||||
* @param values
|
||||
* List of GenericValue instances containing the entities to
|
||||
* store
|
||||
* @return int representing number of rows effected by this operation
|
||||
*/
|
||||
int storeAll(List<GenericValue> values, EntityStoreOptions storeOptions) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Store a group of values
|
||||
*
|
||||
* @param entityName
|
||||
* The name of the Entity as defined in the entity XML file
|
||||
* @param fieldsToSet
|
||||
* The fields of the named entity to set in the database
|
||||
* @param condition
|
||||
* The condition that restricts the list of stored values
|
||||
* @return int representing number of rows effected by this operation
|
||||
* @throws GenericEntityException
|
||||
*/
|
||||
int storeByCondition(String entityName, Map<String, ? extends Object> fieldsToSet, EntityCondition condition) throws GenericEntityException;
|
||||
|
||||
/**
|
||||
* Get use of Distributed Cache Clear mechanism status
|
||||
* @return boolean true if this delegator uses a Distributed Cache Clear mechanism
|
||||
*/
|
||||
boolean useDistributedCacheClear();
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import org.ofbiz.base.concurrent.ExecutionPool;
|
||||
import org.ofbiz.base.container.Container;
|
||||
import org.ofbiz.base.container.ContainerConfig;
|
||||
import org.ofbiz.base.container.ContainerException;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.base.util.StringUtil;
|
||||
|
||||
public class DelegatorContainer implements Container {
|
||||
private String name;
|
||||
private List<String> preloadedDelegatorNames;
|
||||
|
||||
@Override
|
||||
public void init(String[] args, String name, String configFile) throws ContainerException {
|
||||
this.name = name;
|
||||
|
||||
ContainerConfig.Container cc = ContainerConfig.getContainer(name, configFile);
|
||||
|
||||
preloadedDelegatorNames = StringUtil.split(ContainerConfig.getPropertyValue(cc, "preloaded-delegators", "default"), ", ");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean start() throws ContainerException {
|
||||
if (UtilValidate.isEmpty(preloadedDelegatorNames)) {
|
||||
return true;
|
||||
}
|
||||
List<Future<Delegator>> futures = new ArrayList<Future<Delegator>>();
|
||||
for (String preloadedDelegatorName: preloadedDelegatorNames) {
|
||||
futures.add(DelegatorFactory.getDelegatorFuture(preloadedDelegatorName));
|
||||
}
|
||||
ExecutionPool.getAllFutures(futures);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() throws ContainerException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.FutureTask;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
|
||||
import org.ofbiz.base.concurrent.ExecutionPool;
|
||||
|
||||
import org.ofbiz.base.lang.Factory;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilObject;
|
||||
|
||||
/** <code>Delegator</code> factory abstract class. */
|
||||
public abstract class DelegatorFactory implements Factory<Delegator, String> {
|
||||
public static final String module = DelegatorFactoryImpl.class.getName();
|
||||
private static final ConcurrentHashMap<String, Future<Delegator>> delegators = new ConcurrentHashMap<String, Future<Delegator>>();
|
||||
private static final ThreadGroup DELEGATOR_THREAD_GROUP = new ThreadGroup("DelegatorFactory");
|
||||
private static final ScheduledExecutorService executor = ExecutionPool.getScheduledExecutor(DELEGATOR_THREAD_GROUP, "delegator-startup", Runtime.getRuntime().availableProcessors(), 10, true);
|
||||
|
||||
public static Delegator getDelegator(String delegatorName) {
|
||||
Future<Delegator> future = getDelegatorFuture(delegatorName);
|
||||
try {
|
||||
return future.get();
|
||||
} catch (ExecutionException e) {
|
||||
Debug.logError(e, module);
|
||||
return null;
|
||||
} catch (InterruptedException e) {
|
||||
Debug.logError(e, module);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Future<Delegator> getDelegatorFuture(String delegatorName) {
|
||||
if (delegatorName == null) {
|
||||
delegatorName = "default";
|
||||
//Debug.logWarning(new Exception("Location where getting delegator with null name"), "Got a getGenericDelegator call with a null delegatorName, assuming default for the name.", module);
|
||||
}
|
||||
do {
|
||||
Future<Delegator> future = delegators.get(delegatorName);
|
||||
if (future != null) {
|
||||
//Debug.logInfo("got delegator(future(" + delegatorName + ")) from cache", module);
|
||||
return future;
|
||||
}
|
||||
FutureTask<Delegator> futureTask = new FutureTask<Delegator>(new DelegatorConfigurable(delegatorName));
|
||||
//Debug.logInfo("putting delegator(future(" + delegatorName + ")) into cache", module);
|
||||
if (delegators.putIfAbsent(delegatorName, futureTask) != null) {
|
||||
continue;
|
||||
}
|
||||
executor.submit(futureTask);
|
||||
} while (true);
|
||||
}
|
||||
|
||||
public static final class DelegatorConfigurable implements Callable<Delegator> {
|
||||
private final String delegatorName;
|
||||
|
||||
public DelegatorConfigurable(String delegatorName) {
|
||||
this.delegatorName = delegatorName;
|
||||
}
|
||||
|
||||
public Delegator call() throws ClassNotFoundException {
|
||||
try {
|
||||
Delegator delegator = UtilObject.getObjectFromFactory(DelegatorFactory.class, delegatorName);
|
||||
|
||||
// setup the Entity ECA Handler
|
||||
delegator.initEntityEcaHandler();
|
||||
|
||||
// setup the distributed CacheClear
|
||||
delegator.initDistributedCacheClear();
|
||||
|
||||
return delegator;
|
||||
} catch (ClassNotFoundException e) {
|
||||
Debug.logError(e, module);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
|
||||
/** A <code>DelegatorFactory</code> implementation that returns an
|
||||
* instance of <code>GenericDelegator</code>. */
|
||||
public class DelegatorFactoryImpl extends DelegatorFactory {
|
||||
|
||||
public static final String module = DelegatorFactoryImpl.class.getName();
|
||||
|
||||
public Delegator getInstance(String delegatorName) {
|
||||
if (Debug.infoOn()) Debug.logInfo("Creating new delegator [" + delegatorName + "] (" + Thread.currentThread().getName() + ")", module);
|
||||
//Debug.logInfo(new Exception(), "Showing stack where new delegator is being created...", module);
|
||||
try {
|
||||
return new GenericDelegator(delegatorName);
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logError(e, "Error creating delegator", module);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class EntityCryptoException extends GenericEntityException {
|
||||
|
||||
public EntityCryptoException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public EntityCryptoException(Throwable nested) {
|
||||
super(nested);
|
||||
}
|
||||
|
||||
public EntityCryptoException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public EntityCryptoException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
/**
|
||||
* EntityLockedException
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class EntityLockedException extends GenericEntityException {
|
||||
|
||||
public EntityLockedException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public EntityLockedException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public EntityLockedException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
/**
|
||||
* GenericCreateException
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericCreateException extends GenericEntityException {
|
||||
|
||||
public GenericCreateException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GenericCreateException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public GenericCreateException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
/**
|
||||
* GenericDataSourceException
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericDataSourceException extends GenericEntityException {
|
||||
|
||||
public GenericDataSourceException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GenericDataSourceException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public GenericDataSourceException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
/**
|
||||
* GenericDuplicateKeyException.java
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericDuplicateKeyException extends GenericEntityException {
|
||||
|
||||
public GenericDuplicateKeyException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GenericDuplicateKeyException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public GenericDuplicateKeyException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,40 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
/**
|
||||
* Thrown when there is a problem with the entity engine configuration.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericEntityConfException extends GenericEntityException {
|
||||
|
||||
public GenericEntityConfException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GenericEntityConfException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public GenericEntityConfException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
import org.ofbiz.base.util.GeneralException;
|
||||
|
||||
/**
|
||||
* GenericEntityException
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericEntityException extends GeneralException {
|
||||
|
||||
public GenericEntityException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GenericEntityException(Throwable nested) {
|
||||
super(nested);
|
||||
}
|
||||
|
||||
public GenericEntityException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public GenericEntityException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
/**
|
||||
* GenericEntityNotFoundException
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericEntityNotFoundException extends GenericEntityException {
|
||||
|
||||
public GenericEntityNotFoundException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GenericEntityNotFoundException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public GenericEntityNotFoundException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
/**
|
||||
* GenericFindException
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericFindException extends GenericEntityException {
|
||||
|
||||
public GenericFindException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GenericFindException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public GenericFindException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
/**
|
||||
* GenericModelException
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericModelException extends GenericEntityException {
|
||||
|
||||
public GenericModelException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GenericModelException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public GenericModelException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
/**
|
||||
* GenericNoSuchEntityException.java
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericNoSuchEntityException extends GenericEntityException {
|
||||
|
||||
public GenericNoSuchEntityException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GenericNoSuchEntityException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public GenericNoSuchEntityException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
/**
|
||||
* GenericNotImplementedException
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericNotImplementedException extends GenericEntityException {
|
||||
|
||||
public GenericNotImplementedException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GenericNotImplementedException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public GenericNotImplementedException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
|
||||
/**
|
||||
* Generic Entity Primary Key Object
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericPK extends GenericEntity {
|
||||
|
||||
protected GenericPK() { }
|
||||
|
||||
/** Creates new GenericPK */
|
||||
public static GenericPK create(ModelEntity modelEntity) {
|
||||
GenericPK newPK = new GenericPK();
|
||||
newPK.init(modelEntity);
|
||||
return newPK;
|
||||
}
|
||||
|
||||
/** Creates new GenericPK from existing Map */
|
||||
public static GenericPK create(Delegator delegator, ModelEntity modelEntity, Map<String, ? extends Object> fields) {
|
||||
GenericPK newPK = new GenericPK();
|
||||
newPK.init(delegator, modelEntity, fields);
|
||||
return newPK;
|
||||
}
|
||||
|
||||
/** Creates new GenericPK from existing Map */
|
||||
public static GenericPK create(Delegator delegator, ModelEntity modelEntity, Object singlePkValue) {
|
||||
GenericPK newPK = new GenericPK();
|
||||
newPK.init(delegator, modelEntity, singlePkValue);
|
||||
return newPK;
|
||||
}
|
||||
|
||||
/** Creates new GenericPK from existing GenericPK */
|
||||
public static GenericPK create(GenericPK value) {
|
||||
GenericPK newPK = new GenericPK();
|
||||
newPK.init(value);
|
||||
return newPK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof GenericPK) {
|
||||
return super.equals(obj);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Clones this GenericPK, this is a shallow clone & uses the default shallow HashMap clone
|
||||
*@return Object that is a clone of this GenericPK
|
||||
*/
|
||||
@Override
|
||||
public Object clone() {
|
||||
return GenericPK.create(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
/**
|
||||
* GenericRemoveException
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericRemoveException extends GenericEntityException {
|
||||
|
||||
public GenericRemoveException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GenericRemoveException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public GenericRemoveException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
/**
|
||||
* GenericResultSetClosedException
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericResultSetClosedException extends GenericEntityException {
|
||||
|
||||
public GenericResultSetClosedException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GenericResultSetClosedException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public GenericResultSetClosedException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity;
|
||||
|
||||
/**
|
||||
* GenericStoreException
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericStoreException extends GenericEntityException {
|
||||
|
||||
public GenericStoreException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GenericStoreException(String str) {
|
||||
super(str);
|
||||
}
|
||||
|
||||
public GenericStoreException(String str, Throwable nested) {
|
||||
super(str, nested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
|
||||
/**
|
||||
* Generic Entity Value Object - Handles persistence for any defined entity.
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class GenericValue extends GenericEntity {
|
||||
|
||||
public static final GenericValue NULL_VALUE = new NullGenericValue();
|
||||
|
||||
/** Creates new GenericValue */
|
||||
public static GenericValue create(ModelEntity modelEntity) {
|
||||
GenericValue newValue = new GenericValue();
|
||||
newValue.init(modelEntity);
|
||||
return newValue;
|
||||
}
|
||||
|
||||
/** Creates new GenericValue from existing Map */
|
||||
public static GenericValue create(Delegator delegator, ModelEntity modelEntity, Map<String, ? extends Object> fields) {
|
||||
GenericValue newValue = new GenericValue();
|
||||
newValue.init(delegator, modelEntity, fields);
|
||||
return newValue;
|
||||
}
|
||||
|
||||
/** Creates new GenericValue from existing Map */
|
||||
public static GenericValue create(Delegator delegator, ModelEntity modelEntity, Object singlePkValue) {
|
||||
GenericValue newValue = new GenericValue();
|
||||
newValue.init(delegator, modelEntity, singlePkValue);
|
||||
return newValue;
|
||||
}
|
||||
|
||||
/** Creates new GenericValue from existing GenericValue */
|
||||
public static GenericValue create(GenericValue value) {
|
||||
GenericValue newValue = new GenericValue();
|
||||
newValue.init(value);
|
||||
return newValue;
|
||||
}
|
||||
|
||||
/** Creates new GenericValue from existing GenericValue */
|
||||
public static GenericValue create(GenericPK primaryKey) {
|
||||
GenericValue newValue = new GenericValue();
|
||||
newValue.init(primaryKey);
|
||||
return newValue;
|
||||
}
|
||||
|
||||
public GenericValue create() throws GenericEntityException {
|
||||
return this.getDelegator().create(this);
|
||||
}
|
||||
|
||||
public void store() throws GenericEntityException {
|
||||
this.getDelegator().store(this);
|
||||
}
|
||||
|
||||
public void remove() throws GenericEntityException {
|
||||
this.getDelegator().removeValue(this);
|
||||
}
|
||||
|
||||
public void refresh() throws GenericEntityException {
|
||||
this.getDelegator().refresh(this);
|
||||
}
|
||||
|
||||
public void refreshFromCache() throws GenericEntityException {
|
||||
this.getDelegator().refreshFromCache(this);
|
||||
}
|
||||
|
||||
/** Get the named Related Entity for the GenericValue from the persistent store
|
||||
*@param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified in the entity XML definition file
|
||||
*@return List of GenericValue instances as specified in the relation definition
|
||||
*@deprecated use {@link #getRelated(String, Map, List, boolean)}
|
||||
*/
|
||||
@Deprecated
|
||||
public List<GenericValue> getRelated(String relationName) throws GenericEntityException {
|
||||
Debug.logWarning("deprecated method, please replace as suggested in API Java Doc, and link to OFBIZ-6651", getStackTraceAsString());
|
||||
return this.getDelegator().getRelated(relationName, null, null, this, false);
|
||||
}
|
||||
|
||||
/** Get the named Related Entity for the GenericValue from the persistent store
|
||||
*@param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified in the entity XML definition file
|
||||
* @param orderBy The fields of the named entity to order the query by; may be null;
|
||||
* optionally add a " ASC" for ascending or " DESC" for descending
|
||||
*@return List of GenericValue instances as specified in the relation definition
|
||||
*@deprecated use {@link #getRelated(String, Map, List, boolean)}
|
||||
*/
|
||||
@Deprecated
|
||||
public List<GenericValue> getRelated(String relationName, List<String> orderBy) throws GenericEntityException {
|
||||
Debug.logWarning("deprecated method, please replace as suggested in API Java Doc, and link to OFBIZ-6651", getStackTraceAsString());
|
||||
return this.getDelegator().getRelated(relationName, null, orderBy, this, false);
|
||||
}
|
||||
|
||||
/** Get the named Related Entity for the GenericValue from the persistent store
|
||||
*@param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified in the entity XML definition file
|
||||
* @param byAndFields the fields that must equal in order to keep; may be null
|
||||
* @param orderBy The fields of the named entity to order the query by; may be null;
|
||||
* optionally add a " ASC" for ascending or " DESC" for descending
|
||||
*@return List of GenericValue instances as specified in the relation definition
|
||||
*@deprecated use {@link #getRelated(String, Map, List, boolean)}
|
||||
*/
|
||||
@Deprecated
|
||||
public List<GenericValue> getRelated(String relationName, Map<String, ? extends Object> byAndFields, List<String> orderBy) throws GenericEntityException {
|
||||
Debug.logWarning("deprecated method, please replace as suggested in API Java Doc, and link to OFBIZ-6651", getStackTraceAsString());
|
||||
return this.getDelegator().getRelated(relationName, byAndFields, orderBy, this, false);
|
||||
}
|
||||
|
||||
/** Get the named Related Entity for the GenericValue from the persistent store
|
||||
*@param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified in the entity XML definition file
|
||||
* @param byAndFields the fields that must equal in order to keep; may be null
|
||||
* @param orderBy The fields of the named entity to order the query by; may be null;
|
||||
* optionally add a " ASC" for ascending or " DESC" for descending
|
||||
* @param useCache Whether to cache the results
|
||||
*@return List of GenericValue instances as specified in the relation definition
|
||||
*/
|
||||
public List<GenericValue> getRelated(String relationName, Map<String, ? extends Object> byAndFields, List<String> orderBy, boolean useCache) throws GenericEntityException {
|
||||
return this.getDelegator().getRelated(relationName, byAndFields, orderBy, this, useCache);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the named Related Entity for the GenericValue from the persistent store across another Relation.
|
||||
* Helps to get related Values in a multi-to-multi relationship.
|
||||
* @param relationNameOne String containing the relation name which is the
|
||||
* combination of relation.title and relation.rel-entity-name as
|
||||
* specified in the entity XML definition file, for first relation
|
||||
* @param relationNameTwo String containing the relation name for second relation
|
||||
* @param orderBy The fields of the named entity to order the query by; may be null;
|
||||
* optionally add a " ASC" for ascending or " DESC" for descending
|
||||
* @return List of GenericValue instances as specified in the relation definition
|
||||
*/
|
||||
public List<GenericValue> getRelatedMulti(String relationNameOne, String relationNameTwo, List<String> orderBy) throws GenericEntityException {
|
||||
return this.getDelegator().getMultiRelation(this, relationNameOne, relationNameTwo, orderBy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the named Related Entity for the GenericValue from the persistent store across another Relation.
|
||||
* Helps to get related Values in a multi-to-multi relationship.
|
||||
* @param relationNameOne String containing the relation name which is the
|
||||
* combination of relation.title and relation.rel-entity-name as
|
||||
* specified in the entity XML definition file, for first relation
|
||||
* @param relationNameTwo String containing the relation name for second relation
|
||||
* @return List of GenericValue instances as specified in the relation definition
|
||||
*/
|
||||
public List<GenericValue> getRelatedMulti(String relationNameOne, String relationNameTwo) throws GenericEntityException {
|
||||
return this.getDelegator().getMultiRelation(this, relationNameOne, relationNameTwo, null);
|
||||
}
|
||||
|
||||
/** Get the named Related Entity for the GenericValue from the persistent store
|
||||
*@param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified in the entity XML definition file
|
||||
*@return List of GenericValue instances as specified in the relation definition
|
||||
*@deprecated use {@link #getRelatedOne(String, boolean)}
|
||||
*/
|
||||
@Deprecated
|
||||
public GenericValue getRelatedOne(String relationName) throws GenericEntityException {
|
||||
Debug.logWarning("deprecated method, please replace as suggested in API Java Doc, and link to OFBIZ-6651", getStackTraceAsString());
|
||||
return this.getDelegator().getRelatedOne(relationName, this, false);
|
||||
}
|
||||
|
||||
/** Get the named Related Entity for the GenericValue from the persistent store
|
||||
*@param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified in the entity XML definition file
|
||||
*@param useCache Whether to cache the results
|
||||
*@return The single related GenericValue instance
|
||||
*/
|
||||
public GenericValue getRelatedOne(String relationName, boolean useCache) throws GenericEntityException {
|
||||
return this.getDelegator().getRelatedOne(relationName, this, useCache);
|
||||
}
|
||||
|
||||
/** Remove the named Related Entity for the GenericValue from the persistent store
|
||||
*@param relationName String containing the relation name which is the combination of relation.title and relation.rel-entity-name as specified in the entity XML definition file
|
||||
*/
|
||||
public void removeRelated(String relationName) throws GenericEntityException {
|
||||
this.getDelegator().removeRelated(relationName, this);
|
||||
}
|
||||
|
||||
/** Get a dummy primary key for the named Related Entity for the GenericValue
|
||||
* @param relationName String containing the relation name which is the
|
||||
* combination of relation.title and relation.rel-entity-name as
|
||||
* specified in the entity XML definition file
|
||||
* @return GenericPK containing a possibly incomplete PrimaryKey object representing the related entity or entities
|
||||
*/
|
||||
public GenericPK getRelatedDummyPK(String relationName) throws GenericEntityException {
|
||||
return this.getDelegator().getRelatedDummyPK(relationName, null, this);
|
||||
}
|
||||
|
||||
/** Get a dummy primary key for the named Related Entity for the GenericValue
|
||||
* @param relationName String containing the relation name which is the
|
||||
* combination of relation.title and relation.rel-entity-name as
|
||||
* specified in the entity XML definition file
|
||||
* @param byAndFields the fields that must equal in order to keep; may be null
|
||||
* @return GenericPK containing a possibly incomplete PrimaryKey object representing the related entity or entities
|
||||
*/
|
||||
public GenericPK getRelatedDummyPK(String relationName, Map<String, ? extends Object> byAndFields) throws GenericEntityException {
|
||||
return this.getDelegator().getRelatedDummyPK(relationName, byAndFields, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof GenericValue) {
|
||||
return super.equals(obj);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Clones this GenericValue, this is a shallow clone & uses the default shallow HashMap clone
|
||||
*@return Object that is a clone of this GenericValue
|
||||
*/
|
||||
@Override
|
||||
public Object clone() {
|
||||
return GenericValue.create(this);
|
||||
}
|
||||
|
||||
protected static class NullGenericValue extends GenericValue implements NULL {
|
||||
@Override
|
||||
public String getEntityName() {
|
||||
return "[null-entity-value]";
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "[null-entity-value]";
|
||||
}
|
||||
}
|
||||
|
||||
public static String getStackTraceAsString() {
|
||||
return Thread.currentThread().getStackTrace().toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.cache;
|
||||
|
||||
import org.ofbiz.base.util.cache.UtilCache;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.DelegatorFactory;
|
||||
|
||||
public abstract class AbstractCache<K, V> {
|
||||
|
||||
protected final String delegatorName, id, cacheNamePrefix;
|
||||
|
||||
protected AbstractCache(String delegatorName, String id) {
|
||||
this.delegatorName = delegatorName;
|
||||
this.id = id;
|
||||
this.cacheNamePrefix = "entitycache.".concat(id).concat(".").concat(delegatorName).concat(".");
|
||||
}
|
||||
|
||||
public Delegator getDelegator() {
|
||||
return DelegatorFactory.getDelegator(this.delegatorName);
|
||||
}
|
||||
|
||||
public void remove(String entityName) {
|
||||
UtilCache.clearCache(getCacheName(entityName));
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
UtilCache.clearCachesThatStartWith(getCacheNamePrefix());
|
||||
}
|
||||
|
||||
public String getCacheNamePrefix() {
|
||||
return cacheNamePrefix;
|
||||
}
|
||||
|
||||
public String[] getCacheNamePrefixes() {
|
||||
return new String[] {
|
||||
"entitycache." + id + ".${delegator-name}.",
|
||||
cacheNamePrefix
|
||||
};
|
||||
}
|
||||
|
||||
public String getCacheName(String entityName) {
|
||||
return getCacheNamePrefix() + entityName;
|
||||
}
|
||||
|
||||
public String[] getCacheNames(String entityName) {
|
||||
String[] prefixes = getCacheNamePrefixes();
|
||||
String[] names = new String[prefixes.length * 2];
|
||||
for (int i = 0; i < prefixes.length; i++) {
|
||||
names[i] = prefixes[i] + "${entity-name}";
|
||||
}
|
||||
for (int i = prefixes.length, j = 0; j < prefixes.length; i++, j++) {
|
||||
names[i] = prefixes[j] + entityName;
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
protected UtilCache<K, V> getCache(String entityName) {
|
||||
return UtilCache.findCache(getCacheName(entityName));
|
||||
}
|
||||
|
||||
protected UtilCache<K, V> getOrCreateCache(String entityName) {
|
||||
String name = getCacheName(entityName);
|
||||
return UtilCache.getOrCreateUtilCache(name, 0, 0, 0, true, getCacheNames(entityName));
|
||||
}
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.cache;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.base.util.cache.UtilCache;
|
||||
import org.ofbiz.entity.GenericEntity;
|
||||
import org.ofbiz.entity.GenericPK;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
|
||||
public abstract class AbstractEntityConditionCache<K, V> extends AbstractCache<EntityCondition, ConcurrentMap<K, V>> {
|
||||
|
||||
public static final String module = AbstractEntityConditionCache.class.getName();
|
||||
|
||||
protected AbstractEntityConditionCache(String delegatorName, String id) {
|
||||
super(delegatorName, id);
|
||||
}
|
||||
|
||||
protected V get(String entityName, EntityCondition condition, K key) {
|
||||
ConcurrentMap<K, V> conditionCache = getConditionCache(entityName, condition);
|
||||
if (conditionCache == null) return null;
|
||||
return conditionCache.get(key);
|
||||
}
|
||||
|
||||
protected V put(String entityName, EntityCondition condition, K key, V value) {
|
||||
ModelEntity entity = this.getDelegator().getModelEntity(entityName);
|
||||
if (entity.getNeverCache()) {
|
||||
Debug.logWarning("Tried to put a value of the " + entityName + " entity in the cache but this entity has never-cache set to true, not caching.", module);
|
||||
return null;
|
||||
}
|
||||
|
||||
Map<K, V> conditionCache = getOrCreateConditionCache(entityName, condition);
|
||||
return conditionCache.put(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all condition caches that include the specified entity.
|
||||
*/
|
||||
public void remove(GenericEntity entity) {
|
||||
UtilCache.clearCache(getCacheName(entity.getEntityName()));
|
||||
ModelEntity model = entity.getModelEntity();
|
||||
if (model != null) {
|
||||
Iterator<String> it = model.getViewConvertorsIterator();
|
||||
while (it.hasNext()) {
|
||||
String targetEntityName = it.next();
|
||||
UtilCache.clearCache(getCacheName(targetEntityName));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void remove(String entityName, EntityCondition condition) {
|
||||
UtilCache<EntityCondition, ConcurrentMap<K, V>> cache = getCache(entityName);
|
||||
if (cache == null) return;
|
||||
cache.remove(condition);
|
||||
}
|
||||
|
||||
protected V remove(String entityName, EntityCondition condition, K key) {
|
||||
ConcurrentMap<K, V> conditionCache = getConditionCache(entityName, condition);
|
||||
if (conditionCache == null) return null;
|
||||
return conditionCache.remove(key);
|
||||
}
|
||||
|
||||
public static final EntityCondition getConditionKey(EntityCondition condition) {
|
||||
return condition != null ? condition : null;
|
||||
}
|
||||
|
||||
public static final EntityCondition getFrozenConditionKey(EntityCondition condition) {
|
||||
EntityCondition frozenCondition = condition != null ? condition.freeze() : null;
|
||||
// This is no longer needed, fixed issue with unequal conditions after freezing
|
||||
//if (condition != null) {
|
||||
// if (!condition.equals(frozenCondition)) {
|
||||
// Debug.logWarning("Frozen condition does not equal condition:\n -=-=-=-Original=" + condition + "\n -=-=-=-Frozen=" + frozenCondition, module);
|
||||
// Debug.logWarning("Frozen condition not equal info: condition class=" + condition.getClass().getName() + "; frozenCondition class=" + frozenCondition.getClass().getName(), module);
|
||||
// }
|
||||
//}
|
||||
return frozenCondition;
|
||||
}
|
||||
|
||||
protected ConcurrentMap<K, V> getConditionCache(String entityName, EntityCondition condition) {
|
||||
UtilCache<EntityCondition, ConcurrentMap<K, V>> cache = getCache(entityName);
|
||||
if (cache == null) return null;
|
||||
return cache.get(getConditionKey(condition));
|
||||
}
|
||||
|
||||
protected Map<K, V> getOrCreateConditionCache(String entityName, EntityCondition condition) {
|
||||
UtilCache<EntityCondition, ConcurrentMap<K, V>> utilCache = getOrCreateCache(entityName);
|
||||
EntityCondition conditionKey = getConditionKey(condition);
|
||||
ConcurrentMap<K, V> conditionCache = utilCache.get(conditionKey);
|
||||
if (conditionCache == null) {
|
||||
conditionCache = new ConcurrentHashMap<K, V>();
|
||||
utilCache.put(conditionKey, conditionCache);
|
||||
}
|
||||
return conditionCache;
|
||||
}
|
||||
|
||||
protected static final <K,V> boolean isNull(Map<K,V> value) {
|
||||
return value == null || value == GenericEntity.NULL_ENTITY || value == GenericValue.NULL_VALUE;
|
||||
}
|
||||
|
||||
protected ModelEntity getModelCheckValid(GenericEntity oldEntity, GenericEntity newEntity) {
|
||||
ModelEntity model;
|
||||
if (!isNull(newEntity)) {
|
||||
model = newEntity.getModelEntity();
|
||||
String entityName = model.getEntityName();
|
||||
if (oldEntity != null && !entityName.equals(oldEntity.getEntityName())) {
|
||||
throw new IllegalArgumentException("internal error: storeHook called with 2 different entities(old=" + oldEntity.getEntityName() + ", new=" + entityName + ")");
|
||||
}
|
||||
} else {
|
||||
if (!isNull(oldEntity)) {
|
||||
model = oldEntity.getModelEntity();
|
||||
} else {
|
||||
throw new IllegalArgumentException("internal error: storeHook called with 2 null arguments");
|
||||
}
|
||||
}
|
||||
return model;
|
||||
}
|
||||
|
||||
public void storeHook(GenericEntity newEntity) {
|
||||
storeHook(null, newEntity);
|
||||
}
|
||||
|
||||
// if oldValue == null, then this is a new entity
|
||||
// if newValue == null, then
|
||||
public void storeHook(GenericEntity oldEntity, GenericEntity newEntity) {
|
||||
storeHook(false, oldEntity, newEntity);
|
||||
}
|
||||
|
||||
// if oldValue == null, then this is a new entity
|
||||
// if newValue == null, then
|
||||
public void storeHook(GenericPK oldPK, GenericEntity newEntity) {
|
||||
storeHook(true, oldPK, newEntity);
|
||||
}
|
||||
|
||||
protected List<? extends Map<String, Object>> convert(boolean isPK, String targetEntityName, GenericEntity entity) {
|
||||
if (isNull(entity)) return null;
|
||||
if (isPK) {
|
||||
return entity.getModelEntity().convertToViewValues(targetEntityName, entity);
|
||||
} else {
|
||||
return entity.getModelEntity().convertToViewValues(targetEntityName, entity);
|
||||
}
|
||||
}
|
||||
|
||||
public void storeHook(boolean isPK, GenericEntity oldEntity, GenericEntity newEntity) {
|
||||
ModelEntity model = getModelCheckValid(oldEntity, newEntity);
|
||||
String entityName = model.getEntityName();
|
||||
// for info about cache clearing
|
||||
if (newEntity == null) {
|
||||
//Debug.logInfo("In storeHook calling sub-storeHook for entity name [" + entityName + "] for the oldEntity: " + oldEntity, module);
|
||||
}
|
||||
storeHook(entityName, isPK, UtilMisc.toList(oldEntity), UtilMisc.toList(newEntity));
|
||||
Iterator<String> it = model.getViewConvertorsIterator();
|
||||
while (it.hasNext()) {
|
||||
String targetEntityName = it.next();
|
||||
storeHook(targetEntityName, isPK, convert(isPK, targetEntityName, oldEntity), convert(false, targetEntityName, newEntity));
|
||||
}
|
||||
}
|
||||
|
||||
protected <T1 extends Map<String, Object>, T2 extends Map<String, Object>> void storeHook(String entityName, boolean isPK, List<T1> oldValues, List<T2> newValues) {
|
||||
UtilCache<EntityCondition, Map<K, V>> entityCache = UtilCache.findCache(getCacheName(entityName));
|
||||
// for info about cache clearing
|
||||
if (UtilValidate.isEmpty(newValues) || newValues.get(0) == null) {
|
||||
//Debug.logInfo("In storeHook (cache clear) for entity name [" + entityName + "], got entity cache with name: " + (entityCache == null ? "[No cache found to remove from]" : entityCache.getName()), module);
|
||||
}
|
||||
if (entityCache == null) {
|
||||
return;
|
||||
}
|
||||
for (EntityCondition condition: entityCache.getCacheLineKeys()) {
|
||||
//Debug.logInfo("In storeHook entityName [" + entityName + "] checking against condition: " + condition, module);
|
||||
boolean shouldRemove = false;
|
||||
if (condition == null) {
|
||||
shouldRemove = true;
|
||||
} else if (oldValues == null) {
|
||||
Iterator<T2> newValueIter = newValues.iterator();
|
||||
while (newValueIter.hasNext() && !shouldRemove) {
|
||||
T2 newValue = newValueIter.next();
|
||||
shouldRemove |= condition.mapMatches(getDelegator(), newValue);
|
||||
}
|
||||
} else {
|
||||
boolean oldMatched = false;
|
||||
Iterator<T1> oldValueIter = oldValues.iterator();
|
||||
while (oldValueIter.hasNext() && !shouldRemove) {
|
||||
T1 oldValue = oldValueIter.next();
|
||||
if (condition.mapMatches(getDelegator(), oldValue)) {
|
||||
oldMatched = true;
|
||||
//Debug.logInfo("In storeHook, oldMatched for entityName [" + entityName + "]; shouldRemove is false", module);
|
||||
if (newValues != null) {
|
||||
Iterator<T2> newValueIter = newValues.iterator();
|
||||
while (newValueIter.hasNext() && !shouldRemove) {
|
||||
T2 newValue = newValueIter.next();
|
||||
shouldRemove |= isNull(newValue) || condition.mapMatches(getDelegator(), newValue);
|
||||
//Debug.logInfo("In storeHook, for entityName [" + entityName + "] shouldRemove is now " + shouldRemove, module);
|
||||
}
|
||||
} else {
|
||||
shouldRemove = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// QUESTION: what is this? why would we do this?
|
||||
if (!oldMatched && isPK) {
|
||||
//Debug.logInfo("In storeHook, for entityName [" + entityName + "] oldMatched is false and isPK is true, so setting shouldRemove to true (will remove from cache)", module);
|
||||
shouldRemove = true;
|
||||
}
|
||||
}
|
||||
if (shouldRemove) {
|
||||
if (Debug.verboseOn()) Debug.logVerbose("In storeHook, matched condition, removing from cache for entityName [" + entityName + "] in cache with name [" + entityCache.getName() + "] entry with condition: " + condition, module);
|
||||
// doesn't work anymore since this is a copy of the cache keySet, can call remove directly though with a concurrent mod exception: cacheKeyIter.remove();
|
||||
entityCache.remove(condition);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.cache;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.entity.GenericEntity;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.GenericPK;
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
|
||||
public class Cache {
|
||||
|
||||
public static final String module = Cache.class.getName();
|
||||
|
||||
protected EntityCache entityCache;
|
||||
protected EntityListCache entityListCache;
|
||||
protected EntityObjectCache entityObjectCache;
|
||||
|
||||
protected String delegatorName;
|
||||
|
||||
public Cache(String delegatorName) {
|
||||
this.delegatorName = delegatorName;
|
||||
entityCache = new EntityCache(delegatorName);
|
||||
entityObjectCache = new EntityObjectCache(delegatorName);
|
||||
entityListCache = new EntityListCache(delegatorName);
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
entityCache.clear();
|
||||
entityListCache.clear();
|
||||
entityObjectCache.clear();
|
||||
}
|
||||
|
||||
public void remove(String entityName) {
|
||||
entityCache.remove(entityName);
|
||||
entityListCache.remove(entityName);
|
||||
}
|
||||
|
||||
public GenericValue get(GenericPK pk) {
|
||||
return entityCache.get(pk);
|
||||
}
|
||||
|
||||
public List<GenericValue> get(String entityName, EntityCondition condition, List<String> orderBy) {
|
||||
return entityListCache.get(entityName, condition, orderBy);
|
||||
}
|
||||
|
||||
public <T> T get(String entityName, EntityCondition condition, String name) {
|
||||
return UtilGenerics.<T>cast(entityObjectCache.get(entityName, condition, name));
|
||||
}
|
||||
|
||||
public List<GenericValue> put(String entityName, EntityCondition condition, List<String> orderBy, List<GenericValue> entities) {
|
||||
return entityListCache.put(entityName, condition, orderBy, entities);
|
||||
}
|
||||
|
||||
public <T> T put(String entityName, EntityCondition condition, String name, T value) {
|
||||
return UtilGenerics.<T>cast(entityObjectCache.put(entityName, condition, name, value));
|
||||
}
|
||||
|
||||
public GenericValue put(GenericValue entity) {
|
||||
GenericValue oldEntity = entityCache.put(entity.getPrimaryKey(), entity);
|
||||
if (entity.getModelEntity().getAutoClearCache()) {
|
||||
entityListCache.storeHook(entity);
|
||||
entityObjectCache.storeHook(entity);
|
||||
}
|
||||
return oldEntity;
|
||||
}
|
||||
|
||||
public GenericValue put(GenericPK pk, GenericValue entity) {
|
||||
GenericValue oldEntity = entityCache.put(pk, entity);
|
||||
if (pk.getModelEntity().getAutoClearCache()) {
|
||||
entityListCache.storeHook(pk, entity);
|
||||
entityObjectCache.storeHook(pk, entity);
|
||||
}
|
||||
return oldEntity;
|
||||
}
|
||||
|
||||
public List<GenericValue> remove(String entityName, EntityCondition condition, List<String> orderBy) {
|
||||
entityCache.remove(entityName, condition);
|
||||
entityObjectCache.remove(entityName, condition);
|
||||
return entityListCache.remove(entityName, condition, orderBy);
|
||||
}
|
||||
|
||||
public void remove(String entityName, EntityCondition condition) {
|
||||
entityCache.remove(entityName, condition);
|
||||
entityListCache.remove(entityName, condition);
|
||||
entityObjectCache.remove(entityName, condition);
|
||||
}
|
||||
|
||||
public <T> T remove(String entityName, EntityCondition condition, String name) {
|
||||
return UtilGenerics.<T>cast(entityObjectCache.remove(entityName, condition, name));
|
||||
}
|
||||
|
||||
public GenericValue remove(GenericEntity entity) {
|
||||
if (Debug.verboseOn()) Debug.logVerbose("Cache remove GenericEntity: " + entity, module);
|
||||
GenericValue oldEntity = entityCache.remove(entity.getPrimaryKey());
|
||||
// Workaround because AbstractEntityConditionCache.storeHook doesn't work.
|
||||
entityListCache.remove(entity);
|
||||
entityObjectCache.remove(entity);
|
||||
// entityListCache.storeHook(entity, null);
|
||||
// entityObjectCache.storeHook(entity, null);
|
||||
return oldEntity;
|
||||
}
|
||||
|
||||
public GenericValue remove(GenericPK pk) {
|
||||
if (Debug.verboseOn()) Debug.logVerbose("Cache remove GenericPK: " + pk, module);
|
||||
GenericValue oldEntity = entityCache.remove(pk);
|
||||
// Workaround because AbstractEntityConditionCache.storeHook doesn't work.
|
||||
entityListCache.remove(pk);
|
||||
entityObjectCache.remove(pk);
|
||||
// entityListCache.storeHook(pk, null);
|
||||
// entityObjectCache.storeHook(pk, null);
|
||||
return oldEntity;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.cache;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.cache.UtilCache;
|
||||
import org.ofbiz.entity.GenericPK;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
|
||||
public class EntityCache extends AbstractCache<GenericPK, GenericValue> {
|
||||
public static final String module = EntityCache.class.getName();
|
||||
|
||||
public EntityCache(String delegatorName) {
|
||||
super(delegatorName, "entity");
|
||||
}
|
||||
|
||||
public GenericValue get(GenericPK pk) {
|
||||
UtilCache<GenericPK, GenericValue> entityCache = getCache(pk.getEntityName());
|
||||
if (entityCache == null) return null;
|
||||
return entityCache.get(pk);
|
||||
}
|
||||
|
||||
public GenericValue put(GenericValue entity) {
|
||||
if (entity == null) return null;
|
||||
return put(entity.getPrimaryKey(), entity);
|
||||
}
|
||||
|
||||
public GenericValue put(GenericPK pk, GenericValue entity) {
|
||||
if (pk.getModelEntity().getNeverCache()) {
|
||||
Debug.logWarning("Tried to put a value of the " + pk.getEntityName() + " entity in the BY PRIMARY KEY cache but this entity has never-cache set to true, not caching.", module);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (entity == null) {
|
||||
entity = GenericValue.NULL_VALUE;
|
||||
} else {
|
||||
// before going into the cache, make this value immutable
|
||||
entity.setImmutable();
|
||||
}
|
||||
UtilCache<GenericPK, GenericValue> entityCache = getOrCreateCache(pk.getEntityName());
|
||||
return entityCache.put(pk, entity);
|
||||
}
|
||||
|
||||
public void remove(String entityName, EntityCondition condition) {
|
||||
UtilCache<GenericPK, GenericValue> entityCache = getCache(entityName);
|
||||
if (entityCache == null) return;
|
||||
for (GenericPK pk: entityCache.getCacheLineKeys()) {
|
||||
GenericValue entity = entityCache.get(pk);
|
||||
if (entity == null) continue;
|
||||
if (condition.entityMatches(entity)) entityCache.remove(pk);
|
||||
}
|
||||
}
|
||||
|
||||
public GenericValue remove(GenericValue entity) {
|
||||
return remove(entity.getPrimaryKey());
|
||||
}
|
||||
|
||||
public GenericValue remove(GenericPK pk) {
|
||||
UtilCache<GenericPK, GenericValue> entityCache = getCache(pk.getEntityName());
|
||||
if (Debug.verboseOn()) Debug.logVerbose("Removing from EntityCache with PK [" + pk + "], will remove from this cache: " + (entityCache == null ? "[No cache found to remove from]" : entityCache.getName()), module);
|
||||
if (entityCache == null) return null;
|
||||
GenericValue retVal = entityCache.remove(pk);
|
||||
ModelEntity model = pk.getModelEntity();
|
||||
if (model != null) {
|
||||
Iterator<String> it = model.getViewConvertorsIterator();
|
||||
while (it.hasNext()) {
|
||||
String targetEntityName = it.next();
|
||||
UtilCache.clearCache(getCacheName(targetEntityName));
|
||||
}
|
||||
}
|
||||
if (Debug.verboseOn()) Debug.logVerbose("Removing from EntityCache with PK [" + pk + "], found this in the cache: " + retVal, module);
|
||||
return retVal;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.cache;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.util.EntityUtil;
|
||||
|
||||
|
||||
public class EntityListCache extends AbstractEntityConditionCache<Object, List<GenericValue>> {
|
||||
|
||||
public static final String module = EntityListCache.class.getName();
|
||||
|
||||
public EntityListCache(String delegatorName) {
|
||||
super(delegatorName, "entity-list");
|
||||
}
|
||||
|
||||
public List<GenericValue> get(String entityName, EntityCondition condition) {
|
||||
return this.get(entityName, condition, null);
|
||||
}
|
||||
|
||||
public List<GenericValue> get(String entityName, EntityCondition condition, List<String> orderBy) {
|
||||
ConcurrentMap<Object, List<GenericValue>> conditionCache = getConditionCache(entityName, condition);
|
||||
if (conditionCache == null) return null;
|
||||
Object orderByKey = getOrderByKey(orderBy);
|
||||
List<GenericValue> valueList = conditionCache.get(orderByKey);
|
||||
if (valueList == null) {
|
||||
// the valueList was not found for the given ordering, so grab the first one and order it in memory
|
||||
Iterator<List<GenericValue>> it = conditionCache.values().iterator();
|
||||
if (it.hasNext()) valueList = it.next();
|
||||
|
||||
if (valueList != null) {
|
||||
// Does not need to be synchronized; if 2 threads do the same ordering,
|
||||
// the result will be exactly the same, and won't actually cause any
|
||||
// incorrect results.
|
||||
valueList = EntityUtil.orderBy(valueList, orderBy);
|
||||
conditionCache.put(orderByKey, valueList);
|
||||
}
|
||||
}
|
||||
return valueList;
|
||||
}
|
||||
|
||||
public void put(String entityName, EntityCondition condition, List<GenericValue> entities) {
|
||||
this.put(entityName, condition, null, entities);
|
||||
}
|
||||
|
||||
public List<GenericValue> put(String entityName, EntityCondition condition, List<String> orderBy, List<GenericValue> entities) {
|
||||
ModelEntity entity = this.getDelegator().getModelEntity(entityName);
|
||||
if (entity.getNeverCache()) {
|
||||
Debug.logWarning("Tried to put a value of the " + entityName + " entity in the cache but this entity has never-cache set to true, not caching.", module);
|
||||
return null;
|
||||
}
|
||||
for (GenericValue memberValue : entities) {
|
||||
memberValue.setImmutable();
|
||||
}
|
||||
Map<Object, List<GenericValue>> conditionCache = getOrCreateConditionCache(entityName, getFrozenConditionKey(condition));
|
||||
return conditionCache.put(getOrderByKey(orderBy), entities);
|
||||
}
|
||||
|
||||
public List<GenericValue> remove(String entityName, EntityCondition condition, List<String> orderBy) {
|
||||
return super.remove(entityName, condition, getOrderByKey(orderBy));
|
||||
}
|
||||
|
||||
public static final Object getOrderByKey(List<String> orderBy) {
|
||||
return orderBy != null ? (Object) orderBy : "{null}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.cache;
|
||||
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
|
||||
public class EntityObjectCache extends AbstractEntityConditionCache<String, Object> {
|
||||
|
||||
public static final String module = EntityObjectCache.class.getName();
|
||||
|
||||
public EntityObjectCache(String delegatorName) {
|
||||
super(delegatorName, "object-list");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String entityName, EntityCondition condition, String name) {
|
||||
return super.get(entityName, condition, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object put(String entityName, EntityCondition condition, String name, Object value) {
|
||||
return super.put(entityName, getFrozenConditionKey(condition), name, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object remove(String entityName, EntityCondition condition, String name) {
|
||||
return super.remove(entityName, condition, name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelReader;
|
||||
|
||||
|
||||
/**
|
||||
* Generic Entity Clause - Used to string together entities to make a find clause
|
||||
*/
|
||||
public class EntityClause {
|
||||
|
||||
private String firstEntity = "";
|
||||
private String secondEntity = "";
|
||||
private String firstField = "";
|
||||
private String secondField = "";
|
||||
private ModelEntity firstModelEntity = null;
|
||||
private ModelEntity secondModelEntity = null;
|
||||
private EntityOperator<?,?,?> interFieldOperation = null;
|
||||
private EntityOperator<?,?,?> intraFieldOperation = null;
|
||||
|
||||
private Object value = null;
|
||||
public EntityClause() {}
|
||||
|
||||
public EntityClause(String firstEntity, String secondEntity, String firstField, String secondField, EntityOperator<?, ?, ?> interFieldOperation, EntityOperator<?, ?, ?> intraFieldOperation) {
|
||||
this.firstEntity = firstEntity;
|
||||
this.secondEntity = secondEntity;
|
||||
this.firstField = firstField;
|
||||
this.secondField = secondField;
|
||||
this.interFieldOperation = interFieldOperation;
|
||||
this.intraFieldOperation = intraFieldOperation;
|
||||
}
|
||||
|
||||
public EntityClause(String firstEntity, String firstField, Object value, EntityOperator<?, ?, ?> interFieldOperation, EntityOperator<?, ?, ?> intraFieldOperation) {
|
||||
this.firstEntity = firstEntity;
|
||||
this.firstField = firstField;
|
||||
this.value = value;
|
||||
this.interFieldOperation = interFieldOperation;
|
||||
this.intraFieldOperation = intraFieldOperation;
|
||||
}
|
||||
|
||||
public String getFirstEntity() {
|
||||
return firstEntity;
|
||||
}
|
||||
|
||||
public String getSecondEntity() {
|
||||
return secondEntity;
|
||||
}
|
||||
|
||||
public String getFirstField() {
|
||||
return firstField;
|
||||
}
|
||||
|
||||
public String getSecondField() {
|
||||
return secondField;
|
||||
}
|
||||
|
||||
public Object getValue() {
|
||||
if (value == null) value = new Object();
|
||||
return value;
|
||||
}
|
||||
|
||||
public <L,R,T> EntityOperator<L,R,T> getInterFieldOperation() {
|
||||
return UtilGenerics.cast(interFieldOperation);
|
||||
}
|
||||
|
||||
public <L,R,T> EntityOperator<L,R,T> getIntraFieldOperation() {
|
||||
return UtilGenerics.cast(intraFieldOperation);
|
||||
}
|
||||
|
||||
public void setFirstEntity(String firstEntity) {
|
||||
this.firstEntity = firstEntity;
|
||||
}
|
||||
|
||||
public void setSecondEntity(String secondEntity) {
|
||||
this.secondEntity = secondEntity;
|
||||
}
|
||||
|
||||
public void setFirstField(String firstField) {
|
||||
this.firstField = firstField;
|
||||
}
|
||||
|
||||
public void setSecondField(String secondField) {
|
||||
this.secondField = secondField;
|
||||
}
|
||||
|
||||
public <L,R,T> void setInterFieldOperation(EntityOperator<L,R,T> interFieldOperation) {
|
||||
this.interFieldOperation = interFieldOperation;
|
||||
}
|
||||
|
||||
public <L,R,T> void setIntraFieldOperation(EntityOperator<L,R,T> intraFieldOperation) {
|
||||
this.intraFieldOperation = intraFieldOperation;
|
||||
}
|
||||
|
||||
// -- Protected Methods - for internal use only --//
|
||||
protected void setModelEntities(ModelReader modelReader) throws GenericEntityException {
|
||||
firstModelEntity = modelReader.getModelEntity(firstEntity);
|
||||
if (secondEntity != null && !secondEntity.equals("")) {
|
||||
secondModelEntity = modelReader.getModelEntity(secondEntity);
|
||||
}
|
||||
}
|
||||
|
||||
protected ModelEntity getFirstModelEntity() {
|
||||
return firstModelEntity;
|
||||
}
|
||||
|
||||
protected ModelEntity getSecondModelEntity() {
|
||||
return secondModelEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder outputBuffer = new StringBuilder();
|
||||
|
||||
outputBuffer.append("[firstEntity,").append(firstEntity == null ? "null" : firstEntity).append("]");
|
||||
outputBuffer.append("[secondEntity,").append(secondEntity == null ? "null" : secondEntity).append("]");
|
||||
outputBuffer.append("[firstField,").append(firstField == null ? "null" : firstField).append("]");
|
||||
outputBuffer.append("[secondField,").append(secondField == null ? "null" : secondField).append("]");
|
||||
outputBuffer.append("[firstModelEntity,").append(firstModelEntity == null ? "null" : (firstModelEntity.getEntityName() == null ? "null" : firstModelEntity.getEntityName())).append("]");
|
||||
outputBuffer.append("[secondModelEntity,").append(secondModelEntity == null ? "null" : (secondModelEntity.getEntityName() == null ? "null" : secondModelEntity.getEntityName())).append("]");
|
||||
outputBuffer.append("[interFieldOperation,").append(interFieldOperation == null ? "null" : (interFieldOperation.getCode() == null ? "null" : interFieldOperation.getCode())).append("]");
|
||||
outputBuffer.append("[intraFieldOperation,").append(intraFieldOperation == null ? "null" : (intraFieldOperation.getCode() == null ? "null" : intraFieldOperation.getCode())).append("]");
|
||||
outputBuffer.append("[value,").append(getValue().toString() == null ? "null" : getValue().toString()).append("]");
|
||||
return outputBuffer.toString();
|
||||
}
|
||||
|
||||
}
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.oro.text.perl.Perl5Util;
|
||||
import org.apache.oro.text.regex.MalformedPatternException;
|
||||
import org.apache.oro.text.regex.Pattern;
|
||||
import org.apache.oro.text.regex.PatternMatcher;
|
||||
import org.apache.oro.text.regex.Perl5Matcher;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.PatternFactory;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelField;
|
||||
|
||||
/**
|
||||
* Base class for comparisons.
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public abstract class EntityComparisonOperator<L, R> extends EntityOperator<L, R, Boolean> {
|
||||
|
||||
public static final String module = EntityComparisonOperator.class.getName();
|
||||
|
||||
public static Pattern makeOroPattern(String sqlLike) {
|
||||
Perl5Util perl5Util = new Perl5Util();
|
||||
try {
|
||||
sqlLike = perl5Util.substitute("s/([$^.+*?])/\\\\$1/g", sqlLike);
|
||||
sqlLike = perl5Util.substitute("s/%/.*/g", sqlLike);
|
||||
sqlLike = perl5Util.substitute("s/_/./g", sqlLike);
|
||||
} catch (Throwable t) {
|
||||
String errMsg = "Error in ORO pattern substitution for SQL like clause [" + sqlLike + "]: " + t.toString();
|
||||
Debug.logError(t, errMsg, module);
|
||||
throw new IllegalArgumentException(errMsg);
|
||||
}
|
||||
try {
|
||||
return PatternFactory.createOrGetPerl5CompiledPattern(sqlLike, true);
|
||||
} catch (MalformedPatternException e) {
|
||||
Debug.logError(e, module);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validateSql(ModelEntity entity, L lhs, R rhs) throws GenericModelException {
|
||||
if (lhs instanceof EntityConditionValue) {
|
||||
EntityConditionValue ecv = (EntityConditionValue) lhs;
|
||||
ecv.validateSql(entity);
|
||||
}
|
||||
if (rhs instanceof EntityConditionValue) {
|
||||
EntityConditionValue ecv = (EntityConditionValue) rhs;
|
||||
ecv.validateSql(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(EntityConditionVisitor visitor, L lhs, R rhs) {
|
||||
visitor.accept(lhs);
|
||||
visitor.accept(rhs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addSqlValue(StringBuilder sql, ModelEntity entity, List<EntityConditionParam> entityConditionParams, boolean compat, L lhs, R rhs, Datasource datasourceInfo) {
|
||||
//Debug.logInfo("EntityComparisonOperator.addSqlValue field=" + lhs + ", value=" + rhs + ", value type=" + (rhs == null ? "null object" : rhs.getClass().getName()), module);
|
||||
|
||||
// if this is an IN operator and the rhs Object isEmpty, add "1=0" instead of the normal SQL. Note that "FALSE" does not work with all databases.
|
||||
if (this.idInt == EntityOperator.ID_IN && UtilValidate.isEmpty(rhs)) {
|
||||
sql.append("1=0");
|
||||
return;
|
||||
}
|
||||
|
||||
ModelField field;
|
||||
if (lhs instanceof EntityConditionValue) {
|
||||
EntityConditionValue ecv = (EntityConditionValue) lhs;
|
||||
ecv.addSqlValue(sql, entity, entityConditionParams, false, datasourceInfo);
|
||||
field = ecv.getModelField(entity);
|
||||
} else if (compat && lhs instanceof String) {
|
||||
field = getField(entity, (String) lhs);
|
||||
if (field == null) {
|
||||
sql.append(lhs);
|
||||
} else {
|
||||
sql.append(field.getColName());
|
||||
}
|
||||
} else {
|
||||
addValue(sql, null, lhs, entityConditionParams);
|
||||
field = null;
|
||||
}
|
||||
|
||||
makeRHSWhereString(entity, entityConditionParams, sql, field, rhs, datasourceInfo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty(L lhs, R rhs) {
|
||||
return false;
|
||||
}
|
||||
|
||||
protected void makeRHSWhereString(ModelEntity entity, List<EntityConditionParam> entityConditionParams, StringBuilder sql, ModelField field, R rhs, Datasource datasourceInfo) {
|
||||
sql.append(' ').append(getCode()).append(' ');
|
||||
makeRHSWhereStringValue(entity, entityConditionParams, sql, field, rhs, datasourceInfo);
|
||||
}
|
||||
|
||||
protected void makeRHSWhereStringValue(ModelEntity entity, List<EntityConditionParam> entityConditionParams, StringBuilder sql, ModelField field, R rhs, Datasource datasourceInfo) {
|
||||
if (rhs instanceof EntityConditionValue) {
|
||||
EntityConditionValue ecv = (EntityConditionValue) rhs;
|
||||
if (ecv.getModelField(entity) == null) {
|
||||
ecv.setModelField(field);
|
||||
}
|
||||
ecv.addSqlValue(sql, entity, entityConditionParams, false, datasourceInfo);
|
||||
} else {
|
||||
addValue(sql, field, rhs, entityConditionParams);
|
||||
}
|
||||
}
|
||||
|
||||
public abstract boolean compare(L lhs, R rhs);
|
||||
|
||||
public Boolean eval(Delegator delegator, Map<String, ? extends Object> map, L lhs, R rhs) {
|
||||
return Boolean.valueOf(mapMatches(delegator, map, lhs, rhs));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mapMatches(Delegator delegator, Map<String, ? extends Object> map, L lhs, R rhs) {
|
||||
Object leftValue;
|
||||
if (lhs instanceof EntityConditionValue) {
|
||||
EntityConditionValue ecv = (EntityConditionValue) lhs;
|
||||
leftValue = ecv.getValue(delegator, map);
|
||||
} else if (lhs instanceof String) {
|
||||
leftValue = map.get(lhs);
|
||||
} else {
|
||||
leftValue = lhs;
|
||||
}
|
||||
Object rightValue;
|
||||
if (rhs instanceof EntityConditionValue) {
|
||||
EntityConditionValue ecv = (EntityConditionValue) rhs;
|
||||
rightValue = ecv.getValue(delegator, map);
|
||||
} else {
|
||||
rightValue = rhs;
|
||||
}
|
||||
|
||||
if (leftValue == WILDCARD || rightValue == WILDCARD) return true;
|
||||
return compare(UtilGenerics.<L>cast(leftValue), UtilGenerics.<R>cast(rightValue));
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityCondition freeze(L lhs, R rhs) {
|
||||
return EntityCondition.makeCondition(freeze(lhs), this, freeze(rhs));
|
||||
}
|
||||
|
||||
protected Object freeze(Object item) {
|
||||
if (item instanceof EntityConditionValue) {
|
||||
EntityConditionValue ecv = (EntityConditionValue) item;
|
||||
return ecv.freeze();
|
||||
} else {
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
public EntityComparisonOperator(int id, String code) {
|
||||
super(id, code);
|
||||
}
|
||||
|
||||
public static final <T> boolean compareEqual(Comparable<T> lhs, T rhs) {
|
||||
if (lhs == null) {
|
||||
if (rhs != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!lhs.equals(rhs)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static final <T> boolean compareNotEqual(Comparable<T> lhs, T rhs) {
|
||||
if (lhs == null) {
|
||||
if (rhs == null) {
|
||||
return false;
|
||||
}
|
||||
} else if (lhs.equals(rhs)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static final <T> boolean compareGreaterThan(Comparable<T> lhs, T rhs) {
|
||||
if (lhs == null) {
|
||||
if (rhs != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (lhs.compareTo(rhs) <= 0) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static final <T> boolean compareGreaterThanEqualTo(Comparable<T> lhs, T rhs) {
|
||||
if (lhs == null) {
|
||||
if (rhs != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (lhs.compareTo(rhs) < 0) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static final <T> boolean compareLessThan(Comparable<T> lhs, T rhs) {
|
||||
if (lhs == null) {
|
||||
if (rhs != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (lhs.compareTo(rhs) >= 0) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static final <T> boolean compareLessThanEqualTo(Comparable<T> lhs, T rhs) {
|
||||
if (lhs == null) {
|
||||
if (rhs != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (lhs.compareTo(rhs) > 0) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static final <L,R> boolean compareIn(L lhs, R rhs) {
|
||||
if (lhs == null) {
|
||||
if (rhs != null) {
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
} else if (rhs instanceof Collection<?>) {
|
||||
if (((Collection<?>) rhs).contains(lhs)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else if (lhs.equals(rhs)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static final <L,R> boolean compareLike(L lhs, R rhs) {
|
||||
PatternMatcher matcher = new Perl5Matcher();
|
||||
if (lhs == null) {
|
||||
if (rhs != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (lhs instanceof String && rhs instanceof String) {
|
||||
//see if the lhs value is like the rhs value, rhs will have the pattern characters in it...
|
||||
return matcher.matches((String) lhs, makeOroPattern((String) rhs));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.lang.IsEmpty;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntity;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
|
||||
/**
|
||||
* Represents the conditions to be used to constrain a query
|
||||
* <br/>An EntityCondition can represent various type of constraints, including:
|
||||
* <ul>
|
||||
* <li>EntityConditionList: a list of EntityConditions, combined with the operator specified
|
||||
* <li>EntityExpr: for simple expressions or expressions that combine EntityConditions
|
||||
* <li>EntityFieldMap: a map of fields where the field (key) equals the value, combined with the operator specified
|
||||
* </ul>
|
||||
* These can be used in various combinations using the EntityConditionList and EntityExpr objects.
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public abstract class EntityCondition extends EntityConditionBase implements IsEmpty {
|
||||
|
||||
public static <L,R,LL,RR> EntityExpr makeCondition(L lhs, EntityComparisonOperator<LL,RR> operator, R rhs) {
|
||||
return new EntityExpr(lhs, operator, rhs);
|
||||
}
|
||||
|
||||
public static <R> EntityExpr makeCondition(String fieldName, R value) {
|
||||
return new EntityExpr(fieldName, EntityOperator.EQUALS, value);
|
||||
}
|
||||
|
||||
public static EntityExpr makeCondition(EntityCondition lhs, EntityJoinOperator operator, EntityCondition rhs) {
|
||||
return new EntityExpr(lhs, operator, rhs);
|
||||
}
|
||||
|
||||
public static <T extends EntityCondition> EntityConditionList<T> makeCondition(EntityJoinOperator operator, T... conditionList) {
|
||||
return new EntityConditionList<T>(Arrays.<T>asList(conditionList), operator);
|
||||
}
|
||||
|
||||
public static <T extends EntityCondition> EntityConditionList<T> makeCondition(T... conditionList) {
|
||||
return new EntityConditionList<T>(Arrays.<T>asList(conditionList), EntityOperator.AND);
|
||||
}
|
||||
|
||||
public static <T extends EntityCondition> EntityConditionList<T> makeCondition(List<T> conditionList, EntityJoinOperator operator) {
|
||||
return new EntityConditionList<T>(conditionList, operator);
|
||||
}
|
||||
|
||||
public static <T extends EntityCondition> EntityConditionList<T> makeCondition(List<T> conditionList) {
|
||||
return new EntityConditionList<T>(conditionList, EntityOperator.AND);
|
||||
}
|
||||
|
||||
public static <L,R> EntityFieldMap makeCondition(Map<String, ? extends Object> fieldMap, EntityComparisonOperator<L,R> compOp, EntityJoinOperator joinOp) {
|
||||
return new EntityFieldMap(fieldMap, compOp, joinOp);
|
||||
}
|
||||
|
||||
public static EntityFieldMap makeCondition(Map<String, ? extends Object> fieldMap, EntityJoinOperator joinOp) {
|
||||
return new EntityFieldMap(fieldMap, EntityOperator.EQUALS, joinOp);
|
||||
}
|
||||
|
||||
public static EntityFieldMap makeCondition(Map<String, ? extends Object> fieldMap) {
|
||||
return new EntityFieldMap(fieldMap, EntityOperator.EQUALS, EntityOperator.AND);
|
||||
}
|
||||
|
||||
public static <L,R> EntityFieldMap makeCondition(EntityComparisonOperator<L,R> compOp, EntityJoinOperator joinOp, Object... keysValues) {
|
||||
return new EntityFieldMap(compOp, joinOp, keysValues);
|
||||
}
|
||||
|
||||
public static EntityFieldMap makeCondition(EntityJoinOperator joinOp, Object... keysValues) {
|
||||
return new EntityFieldMap(EntityOperator.EQUALS, joinOp, keysValues);
|
||||
}
|
||||
|
||||
public static EntityFieldMap makeConditionMap(Object... keysValues) {
|
||||
return new EntityFieldMap(EntityOperator.EQUALS, EntityOperator.AND, keysValues);
|
||||
}
|
||||
|
||||
public static EntityDateFilterCondition makeConditionDate(String fromDateName, String thruDateName) {
|
||||
return new EntityDateFilterCondition(fromDateName, thruDateName);
|
||||
}
|
||||
|
||||
public static EntityWhereString makeConditionWhere(String sqlString) {
|
||||
return new EntityWhereString(sqlString);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return makeWhereString(null, new ArrayList<EntityConditionParam>(), null);
|
||||
}
|
||||
|
||||
public void accept(EntityConditionVisitor visitor) {
|
||||
throw new IllegalArgumentException(getClass().getName() + ".accept not implemented");
|
||||
}
|
||||
|
||||
abstract public String makeWhereString(ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, Datasource datasourceInfo);
|
||||
|
||||
abstract public void checkCondition(ModelEntity modelEntity) throws GenericModelException;
|
||||
|
||||
public boolean entityMatches(GenericEntity entity) {
|
||||
return mapMatches(entity.getDelegator(), entity);
|
||||
}
|
||||
|
||||
public Boolean eval(GenericEntity entity) {
|
||||
return eval(entity.getDelegator(), entity);
|
||||
}
|
||||
|
||||
public Boolean eval(Delegator delegator, Map<String, ? extends Object> map) {
|
||||
return mapMatches(delegator, map) ? Boolean.TRUE : Boolean.FALSE;
|
||||
}
|
||||
|
||||
abstract public boolean mapMatches(Delegator delegator, Map<String, ? extends Object> map);
|
||||
|
||||
abstract public EntityCondition freeze();
|
||||
|
||||
public void visit(EntityConditionVisitor visitor) {
|
||||
throw new IllegalArgumentException(getClass().getName() + ".visit not implemented");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.jdbc.SqlJdbcUtil;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelField;
|
||||
import org.ofbiz.entity.model.ModelViewEntity;
|
||||
import org.ofbiz.entity.model.ModelViewEntity.ModelAlias;
|
||||
|
||||
/**
|
||||
* Represents the conditions to be used to constrain a query
|
||||
* <br/>An EntityCondition can represent various type of constraints, including:
|
||||
* <ul>
|
||||
* <li>EntityConditionList: a list of EntityConditions, combined with the operator specified
|
||||
* <li>EntityExpr: for simple expressions or expressions that combine EntityConditions
|
||||
* <li>EntityFieldMap: a map of fields where the field (key) equals the value, combined with the operator specified
|
||||
* </ul>
|
||||
* These can be used in various combinations using the EntityConditionList and EntityExpr objects.
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public abstract class EntityConditionBase implements Serializable {
|
||||
|
||||
public static final List<?> emptyList = Collections.emptyList();
|
||||
public static final Map<?,?> _emptyMap = Collections.emptyMap();
|
||||
public static final Map<String, String> emptyAliases = Collections.unmodifiableMap(new HashMap<String, String>());
|
||||
|
||||
protected ModelField getField(ModelEntity modelEntity, String fieldName) {
|
||||
ModelField modelField = null;
|
||||
if (modelEntity != null) {
|
||||
modelField = modelEntity.getField(fieldName);
|
||||
}
|
||||
return modelField;
|
||||
}
|
||||
|
||||
protected String getColName(Map<String, String> tableAliases, ModelEntity modelEntity, String fieldName, boolean includeTableNamePrefix, Datasource datasourceInfo) {
|
||||
if (modelEntity == null) return fieldName;
|
||||
return getColName(tableAliases, modelEntity, getField(modelEntity, fieldName), fieldName, includeTableNamePrefix, datasourceInfo);
|
||||
}
|
||||
|
||||
protected String getColName(ModelField modelField, String fieldName) {
|
||||
String colName = null;
|
||||
if (modelField != null) {
|
||||
colName = modelField.getColValue();
|
||||
} else {
|
||||
colName = fieldName;
|
||||
}
|
||||
return colName;
|
||||
}
|
||||
|
||||
protected String getColName(Map<String, String> tableAliases, ModelEntity modelEntity, ModelField modelField, String fieldName, boolean includeTableNamePrefix, Datasource datasourceInfo) {
|
||||
if (modelEntity == null || modelField == null) return fieldName;
|
||||
|
||||
// if this is a view entity and we are configured to alias the views, use the alias here instead of the composite (ie table.column) field name
|
||||
if (datasourceInfo != null && datasourceInfo.getAliasViewColumns() && modelEntity instanceof ModelViewEntity) {
|
||||
ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntity;
|
||||
ModelAlias modelAlias = modelViewEntity.getAlias(fieldName);
|
||||
if (modelAlias != null) {
|
||||
return modelAlias.getColAlias();
|
||||
}
|
||||
}
|
||||
|
||||
String colName = getColName(modelField, fieldName);
|
||||
if (includeTableNamePrefix && datasourceInfo != null) {
|
||||
String tableName = modelEntity.getTableName(datasourceInfo);
|
||||
if (tableAliases.containsKey(tableName)) {
|
||||
tableName = tableAliases.get(tableName);
|
||||
}
|
||||
colName = tableName + "." + colName;
|
||||
}
|
||||
return colName;
|
||||
}
|
||||
|
||||
protected void addValue(StringBuilder buffer, ModelField field, Object value, List<EntityConditionParam> params) {
|
||||
SqlJdbcUtil.addValue(buffer, params == null ? null : field, value, params);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
throw new UnsupportedOperationException("equals:" + getClass().getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
throw new UnsupportedOperationException("hashCode: " + getClass().getName());
|
||||
}
|
||||
|
||||
protected static boolean equals(Object o1, Object o2) {
|
||||
return o1 == null ? o2 == null : o1.equals(o2);
|
||||
}
|
||||
|
||||
protected static int hashCode(Object o) {
|
||||
return o != null ? o.hashCode() : 0;
|
||||
}
|
||||
|
||||
public static Boolean castBoolean(boolean result) {
|
||||
return result ? Boolean.TRUE : Boolean.FALSE;
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import groovy.util.BuilderSupport;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
|
||||
public class EntityConditionBuilder extends BuilderSupport {
|
||||
public static final String module = EntityConditionBuilder.class.getName();
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
private static class ConditionHolder extends EntityCondition {
|
||||
protected EntityCondition condition;
|
||||
|
||||
protected ConditionHolder(EntityCondition condition) {
|
||||
this.condition = condition;
|
||||
}
|
||||
|
||||
public Object asType(Class clz) {
|
||||
Debug.logInfo("asType(%s): %s", module, clz, condition);
|
||||
if (clz == EntityCondition.class) {
|
||||
return condition;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public EntityCondition build() {
|
||||
return condition;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return condition.isEmpty();
|
||||
}
|
||||
|
||||
public String makeWhereString(ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, Datasource datasourceInfo) {
|
||||
return condition.makeWhereString(modelEntity, entityConditionParams, datasourceInfo);
|
||||
}
|
||||
|
||||
public void checkCondition(ModelEntity modelEntity) throws GenericModelException {
|
||||
condition.checkCondition(modelEntity);
|
||||
}
|
||||
|
||||
public boolean mapMatches(Delegator delegator, Map<String, ? extends Object> map) {
|
||||
return condition.mapMatches(delegator, map);
|
||||
}
|
||||
|
||||
public EntityCondition freeze() {
|
||||
return condition.freeze();
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return condition.hashCode();
|
||||
}
|
||||
public boolean equals(Object obj) {
|
||||
return condition.equals(obj);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object createNode(Object methodName) {
|
||||
String operatorName = ((String)methodName).toLowerCase();
|
||||
EntityJoinOperator operator = EntityOperator.lookupJoin(operatorName);
|
||||
List<EntityCondition> condList = new LinkedList<EntityCondition>();
|
||||
return new ConditionHolder(EntityCondition.makeCondition(condList, operator));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object createNode(Object methodName, Object objArg) {
|
||||
Object node = createNode(methodName);
|
||||
setParent(node, objArg);
|
||||
return node;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object createNode(Object methodName, Map mapArg) {
|
||||
Map<String, Object> fieldValueMap = UtilGenerics.checkMap(mapArg);
|
||||
String operatorName = ((String)methodName).toLowerCase();
|
||||
EntityComparisonOperator<String, Object> operator = EntityOperator.lookupComparison(operatorName);
|
||||
List<EntityCondition> conditionList = new LinkedList<EntityCondition>();
|
||||
for (Map.Entry<String, Object> entry : fieldValueMap.entrySet()) {
|
||||
conditionList.add(EntityCondition.makeCondition(entry.getKey(), operator, entry.getValue()));
|
||||
}
|
||||
if (conditionList.size() == 1) {
|
||||
return new ConditionHolder(conditionList.get(0));
|
||||
} else {
|
||||
return new ConditionHolder(EntityCondition.makeCondition(conditionList));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object createNode(Object methodName, Map mapArg, Object objArg) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setParent(Object parent, Object child) {
|
||||
ConditionHolder holder = (ConditionHolder) parent;
|
||||
EntityConditionList<EntityCondition> parentConList = UtilGenerics.cast(holder.condition);
|
||||
Iterator<EntityCondition> iterator = parentConList.getConditionIterator();
|
||||
List<EntityCondition> tempList = new LinkedList<EntityCondition>();
|
||||
while (iterator.hasNext()) {
|
||||
tempList.add(iterator.next());
|
||||
}
|
||||
if (child instanceof EntityCondition) {
|
||||
tempList.add((EntityCondition)child);
|
||||
} else if (child instanceof ConditionHolder) {
|
||||
tempList.add(((ConditionHolder)child).condition);
|
||||
} else {
|
||||
tempList.addAll(UtilGenerics.<EntityCondition>checkList(child));
|
||||
}
|
||||
holder.condition = EntityCondition.makeCondition(tempList, parentConList.getOperator());
|
||||
}
|
||||
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
|
||||
/**
|
||||
* Base class for entity condition functions.
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public abstract class EntityConditionFunction extends EntityCondition {
|
||||
|
||||
public static final int ID_NOT = 1;
|
||||
|
||||
public static class NOT extends EntityConditionFunction {
|
||||
public NOT(EntityCondition nested) { super(ID_NOT, "NOT", nested); }
|
||||
@Override
|
||||
public boolean mapMatches(Delegator delegator, Map<String, ? extends Object> map) {
|
||||
return !condition.mapMatches(delegator, map);
|
||||
}
|
||||
@Override
|
||||
public EntityCondition freeze() {
|
||||
return new NOT(condition.freeze());
|
||||
}
|
||||
}
|
||||
|
||||
protected Integer idInt = null;
|
||||
protected String codeString = null;
|
||||
protected EntityCondition condition = null;
|
||||
|
||||
protected EntityConditionFunction(int id, String code, EntityCondition condition) {
|
||||
init(id, code, condition);
|
||||
}
|
||||
|
||||
public void init(int id, String code, EntityCondition condition) {
|
||||
idInt = id;
|
||||
codeString = code;
|
||||
this.condition = condition;
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
idInt = null;
|
||||
codeString = null;
|
||||
this.condition = null;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
if (codeString == null)
|
||||
return "null";
|
||||
else
|
||||
return codeString;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return idInt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(EntityConditionVisitor visitor) {
|
||||
visitor.acceptEntityConditionFunction(this, condition);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof EntityConditionFunction)) return false;
|
||||
EntityConditionFunction otherFunc = (EntityConditionFunction) obj;
|
||||
return this.idInt == otherFunc.idInt && (this.condition != null ? condition.equals(otherFunc.condition) : otherFunc.condition != null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return idInt.hashCode() ^ condition.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String makeWhereString(ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, Datasource datasourceInfo) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(codeString).append('(');
|
||||
sb.append(condition.makeWhereString(modelEntity, entityConditionParams, datasourceInfo));
|
||||
sb.append(')');
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkCondition(ModelEntity modelEntity) throws GenericModelException {
|
||||
condition.checkCondition(modelEntity);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Encapsulates a list of EntityConditions to be used as a single EntityCondition combined as specified
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class EntityConditionList<T extends EntityCondition> extends EntityConditionListBase<T> {
|
||||
public EntityConditionList(List<T> conditionList, EntityJoinOperator operator) {
|
||||
super(conditionList, operator);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getConditionListSize() {
|
||||
return super.getConditionListSize();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<T> getConditionIterator() {
|
||||
return super.getConditionIterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(EntityConditionVisitor visitor) {
|
||||
visitor.acceptEntityConditionList(this);
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
|
||||
/**
|
||||
* Encapsulates a list of EntityConditions to be used as a single EntityCondition combined as specified
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public abstract class EntityConditionListBase<T extends EntityCondition> extends EntityCondition {
|
||||
public static final String module = EntityConditionListBase.class.getName();
|
||||
|
||||
protected final List<T> conditionList;
|
||||
protected final EntityJoinOperator operator;
|
||||
|
||||
protected EntityConditionListBase(List<T> conditionList, EntityJoinOperator operator) {
|
||||
this.conditionList = conditionList;
|
||||
this.operator = operator;
|
||||
}
|
||||
|
||||
public EntityJoinOperator getOperator() {
|
||||
return this.operator;
|
||||
}
|
||||
|
||||
public T getCondition(int index) {
|
||||
return this.conditionList.get(index);
|
||||
}
|
||||
|
||||
protected int getConditionListSize() {
|
||||
return this.conditionList.size();
|
||||
}
|
||||
|
||||
protected Iterator<T> getConditionIterator() {
|
||||
return this.conditionList.iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(EntityConditionVisitor visitor) {
|
||||
visitor.acceptEntityJoinOperator(operator, conditionList);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return operator.isEmpty(conditionList);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String makeWhereString(ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, Datasource datasourceInfo) {
|
||||
// if (Debug.verboseOn()) Debug.logVerbose("makeWhereString for entity " + modelEntity.getEntityName(), module);
|
||||
StringBuilder sql = new StringBuilder();
|
||||
operator.addSqlValue(sql, modelEntity, entityConditionParams, conditionList, datasourceInfo);
|
||||
return sql.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkCondition(ModelEntity modelEntity) throws GenericModelException {
|
||||
// if (Debug.verboseOn()) Debug.logVerbose("checkCondition for entity " + modelEntity.getEntityName(), module);
|
||||
operator.validateSql(modelEntity, conditionList);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mapMatches(Delegator delegator, Map<String, ? extends Object> map) {
|
||||
return operator.mapMatches(delegator, map, conditionList);
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityCondition freeze() {
|
||||
return operator.freeze(conditionList);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof EntityConditionListBase<?>)) return false;
|
||||
EntityConditionListBase<?> other = UtilGenerics.cast(obj);
|
||||
|
||||
boolean isEqual = conditionList.equals(other.conditionList) && operator.equals(other.operator);
|
||||
//if (!isEqual) {
|
||||
// Debug.logWarning("EntityConditionListBase.equals is false:\n this.operator=" + this.operator + "; other.operator=" + other.operator +
|
||||
// "\nthis.conditionList=" + this.conditionList +
|
||||
// "\nother.conditionList=" + other.conditionList, module);
|
||||
//}
|
||||
return isEqual;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return conditionList.hashCode() + operator.hashCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.ofbiz.entity.model.ModelField;
|
||||
|
||||
/**
|
||||
* Represents a single parameter to be used in the preparedStatement
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class EntityConditionParam implements Serializable {
|
||||
protected ModelField modelField;
|
||||
protected Object fieldValue;
|
||||
|
||||
protected EntityConditionParam() {}
|
||||
|
||||
public EntityConditionParam(ModelField modelField, Object fieldValue) {
|
||||
if (modelField == null) {
|
||||
throw new IllegalArgumentException("modelField cannot be null");
|
||||
}
|
||||
this.modelField = modelField;
|
||||
this.fieldValue = fieldValue;
|
||||
}
|
||||
|
||||
public ModelField getModelField() {
|
||||
return modelField;
|
||||
}
|
||||
|
||||
public Object getFieldValue() {
|
||||
return fieldValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return modelField.getColName() + "=" + fieldValue.toString();
|
||||
}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.jdbc.SqlJdbcUtil;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelField;
|
||||
import org.ofbiz.entity.model.ModelViewEntity;
|
||||
|
||||
/**
|
||||
* Sub-query action.
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class EntityConditionSubSelect extends EntityConditionValue {
|
||||
public static final String module = EntityConditionSubSelect.class.getName();
|
||||
|
||||
protected ModelEntity localModelEntity = null;
|
||||
protected String keyFieldName = null;
|
||||
protected EntityCondition whereCond = null;
|
||||
protected Boolean requireAll = null;
|
||||
|
||||
protected EntityConditionSubSelect() { }
|
||||
|
||||
public EntityConditionSubSelect(String entityName, String keyFieldName, EntityCondition whereCond, boolean requireAll, Delegator delegator) {
|
||||
this(delegator.getModelEntity(entityName), keyFieldName, whereCond, requireAll);
|
||||
}
|
||||
public EntityConditionSubSelect(ModelEntity localModelEntity, String keyFieldName, EntityCondition whereCond, boolean requireAll) {
|
||||
this.localModelEntity = localModelEntity;
|
||||
this.keyFieldName = keyFieldName;
|
||||
this.whereCond = whereCond;
|
||||
this.requireAll = requireAll;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addSqlValue(StringBuilder sql, Map<String, String> tableAliases, ModelEntity parentModelEntity, List<EntityConditionParam> entityConditionParams,
|
||||
boolean includeTableNamePrefix, Datasource datasourceInfo) {
|
||||
if (localModelEntity instanceof ModelViewEntity && datasourceInfo == null) {
|
||||
throw new IllegalArgumentException("Call to EntityConditionSubSelect.addSqlValue with datasourceInfo=null which is not allowed because the local entity [" + this.localModelEntity.getEntityName() + "] is a view entity");
|
||||
}
|
||||
try {
|
||||
// add select and where and such, based on local entity not on the main entity
|
||||
ModelField localModelField = localModelEntity.getField(this.keyFieldName);
|
||||
|
||||
if (this.requireAll) {
|
||||
sql.append(" ALL(");
|
||||
} else {
|
||||
sql.append(" ANY(");
|
||||
}
|
||||
sql.append("SELECT ");
|
||||
|
||||
sql.append(localModelField.getColName());
|
||||
|
||||
// FROM clause and when necessary the JOIN or LEFT JOIN clause(s) as well
|
||||
sql.append(SqlJdbcUtil.makeFromClause(localModelEntity, null, datasourceInfo));
|
||||
|
||||
// WHERE clause
|
||||
StringBuilder whereString = new StringBuilder();
|
||||
String entityCondWhereString = "";
|
||||
if (this.whereCond != null) {
|
||||
entityCondWhereString = this.whereCond.makeWhereString(localModelEntity, entityConditionParams, datasourceInfo);
|
||||
}
|
||||
|
||||
String viewClause = SqlJdbcUtil.makeViewWhereClause(localModelEntity, (datasourceInfo != null ? datasourceInfo.getJoinStyle() : null));
|
||||
if (viewClause.length() > 0) {
|
||||
if (entityCondWhereString.length() > 0) {
|
||||
whereString.append("(");
|
||||
whereString.append(entityCondWhereString);
|
||||
whereString.append(") AND ");
|
||||
}
|
||||
|
||||
whereString.append(viewClause);
|
||||
} else {
|
||||
whereString.append(entityCondWhereString);
|
||||
}
|
||||
|
||||
if (whereString.length() > 0) {
|
||||
sql.append(" WHERE ");
|
||||
sql.append(whereString.toString());
|
||||
}
|
||||
|
||||
sql.append(")");
|
||||
} catch (GenericEntityException e) {
|
||||
String errMsg = "Could not generate sub-select SQL: " + e.toString();
|
||||
Debug.logError(e, errMsg, module);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public EntityConditionValue freeze() {
|
||||
return new EntityConditionSubSelect(localModelEntity, keyFieldName, (whereCond != null ? whereCond.freeze() : null), requireAll);
|
||||
}
|
||||
|
||||
public String getKeyFieldName() {
|
||||
return this.keyFieldName;
|
||||
}
|
||||
|
||||
public ModelEntity getModelEntity() {
|
||||
return this.localModelEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModelField getModelField(ModelEntity modelEntity) {
|
||||
// do nothing for now
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setModelField(ModelField modelEntity) {
|
||||
// do nothing for now
|
||||
}
|
||||
|
||||
@Override
|
||||
public Comparable<?> getValue(Delegator delegator, Map<String, ? extends Object> map) {
|
||||
// do nothing for now
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validateSql(ModelEntity modelEntity) throws GenericModelException {
|
||||
// do nothing for now
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(EntityConditionVisitor visitor) {
|
||||
if (whereCond != null) whereCond.visit(visitor);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntity;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelField;
|
||||
|
||||
/**
|
||||
* Base class for condition expression values.
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public abstract class EntityConditionValue extends EntityConditionBase {
|
||||
|
||||
public static EntityConditionValue CONSTANT_NUMBER(Number value) { return new ConstantNumberValue(value); }
|
||||
public static final class ConstantNumberValue extends EntityConditionValue {
|
||||
private Number value;
|
||||
|
||||
private ConstantNumberValue(Number value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(EntityConditionVisitor visitor) {
|
||||
visitor.acceptEntityConditionValue(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addSqlValue(StringBuilder sql, Map<String, String> tableAliases, ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, boolean includeTableNamePrefix, Datasource datasourceinfo) {
|
||||
sql.append(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityConditionValue freeze() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModelField getModelField(ModelEntity modelEntity) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setModelField(ModelField field) {
|
||||
// Do nothing;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getValue(Delegator delegator, Map<String, ? extends Object> map) {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validateSql(org.ofbiz.entity.model.ModelEntity modelEntity) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(EntityConditionVisitor visitor) {
|
||||
visitor.acceptObject(value);
|
||||
}
|
||||
}
|
||||
|
||||
public abstract ModelField getModelField(ModelEntity modelEntity);
|
||||
|
||||
public abstract void setModelField(ModelField modelEntity);
|
||||
|
||||
public void addSqlValue(StringBuilder sql, ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, boolean includeTableNamePrefix,
|
||||
Datasource datasourceinfo) {
|
||||
addSqlValue(sql, emptyAliases, modelEntity, entityConditionParams, includeTableNamePrefix, datasourceinfo);
|
||||
}
|
||||
|
||||
public abstract void addSqlValue(StringBuilder sql, Map<String, String> tableAliases, ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams,
|
||||
boolean includeTableNamePrefix, Datasource datasourceinfo);
|
||||
|
||||
public abstract void validateSql(ModelEntity modelEntity) throws GenericModelException;
|
||||
|
||||
public Object getValue(GenericEntity entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
return getValue(entity.getDelegator(), entity);
|
||||
}
|
||||
|
||||
public abstract Object getValue(Delegator delegator, Map<String, ? extends Object> map);
|
||||
|
||||
public abstract EntityConditionValue freeze();
|
||||
|
||||
public abstract void visit(EntityConditionVisitor visitor);
|
||||
|
||||
public void accept(EntityConditionVisitor visitor) {
|
||||
throw new IllegalArgumentException("accept not implemented");
|
||||
}
|
||||
|
||||
public void toString(StringBuilder sb) {
|
||||
addSqlValue(sb, null, new ArrayList<EntityConditionParam>(), false, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sql = new StringBuilder();
|
||||
toString(sql);
|
||||
return sql.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Represents the conditions to be used to constrain a query
|
||||
* <br/>An EntityCondition can represent various type of constraints, including:
|
||||
* <ul>
|
||||
* <li>EntityConditionList: a list of EntityConditions, combined with the operator specified
|
||||
* <li>EntityExpr: for simple expressions or expressions that combine EntityConditions
|
||||
* <li>EntityFieldMap: a map of fields where the field (key) equals the value, combined with the operator specified
|
||||
* </ul>
|
||||
* These can be used in various combinations using the EntityConditionList and EntityExpr objects.
|
||||
*
|
||||
*/
|
||||
public interface EntityConditionVisitor {
|
||||
<T> void visit(T obj);
|
||||
<T> void accept(T obj);
|
||||
void acceptObject(Object obj);
|
||||
void acceptEntityCondition(EntityCondition condition);
|
||||
<T extends EntityCondition> void acceptEntityJoinOperator(EntityJoinOperator op, List<T> conditions);
|
||||
<L,R,T> void acceptEntityOperator(EntityOperator<L, R, T> op, L lhs, R rhs);
|
||||
<L,R> void acceptEntityComparisonOperator(EntityComparisonOperator<L, R> op, L lhs, R rhs);
|
||||
void acceptEntityConditionValue(EntityConditionValue value);
|
||||
void acceptEntityFieldValue(EntityFieldValue value);
|
||||
|
||||
void acceptEntityExpr(EntityExpr expr);
|
||||
<T extends EntityCondition> void acceptEntityConditionList(EntityConditionList<T> list);
|
||||
void acceptEntityFieldMap(EntityFieldMap fieldMap);
|
||||
void acceptEntityConditionFunction(EntityConditionFunction func, EntityCondition nested);
|
||||
<T extends Comparable<?>> void acceptEntityFunction(EntityFunction<T> func);
|
||||
void acceptEntityWhereString(EntityWhereString condition);
|
||||
|
||||
void acceptEntityDateFilterCondition(EntityDateFilterCondition condition);
|
||||
}
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.UtilDateTime;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
|
||||
/**
|
||||
* Date-range condition.
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public final class EntityDateFilterCondition extends EntityCondition {
|
||||
|
||||
protected final String fromDateName;
|
||||
protected final String thruDateName;
|
||||
|
||||
public EntityDateFilterCondition(String fromDateName, String thruDateName) {
|
||||
this.fromDateName = fromDateName;
|
||||
this.thruDateName = thruDateName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String makeWhereString(ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, Datasource datasourceInfo) {
|
||||
EntityCondition condition = makeCondition();
|
||||
return condition.makeWhereString(modelEntity, entityConditionParams, datasourceInfo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkCondition(ModelEntity modelEntity) throws GenericModelException {
|
||||
EntityCondition condition = makeCondition();
|
||||
condition.checkCondition(modelEntity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mapMatches(Delegator delegator, Map<String, ? extends Object> map) {
|
||||
EntityCondition condition = makeCondition();
|
||||
return condition.mapMatches(delegator, map);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof EntityDateFilterCondition)) return false;
|
||||
EntityDateFilterCondition other = (EntityDateFilterCondition) obj;
|
||||
return equals(fromDateName, other.fromDateName) && equals(thruDateName, other.thruDateName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return hashCode(fromDateName) ^ hashCode(thruDateName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(EntityConditionVisitor visitor) {
|
||||
visitor.acceptEntityDateFilterCondition(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(EntityConditionVisitor visitor) {
|
||||
visitor.acceptEntityDateFilterCondition(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityCondition freeze() {
|
||||
return this;
|
||||
}
|
||||
|
||||
protected EntityCondition makeCondition() {
|
||||
return makeCondition(UtilDateTime.nowTimestamp(), fromDateName, thruDateName);
|
||||
}
|
||||
|
||||
public static EntityExpr makeCondition(Timestamp moment, String fromDateName, String thruDateName) {
|
||||
return EntityCondition.makeCondition(
|
||||
EntityCondition.makeCondition(
|
||||
EntityCondition.makeCondition(thruDateName, EntityOperator.EQUALS, null),
|
||||
EntityOperator.OR,
|
||||
EntityCondition.makeCondition(thruDateName, EntityOperator.GREATER_THAN, moment)
|
||||
),
|
||||
EntityOperator.AND,
|
||||
EntityCondition.makeCondition(
|
||||
EntityCondition.makeCondition(fromDateName, EntityOperator.EQUALS, null),
|
||||
EntityOperator.OR,
|
||||
EntityCondition.makeCondition(fromDateName, EntityOperator.LESS_THAN_EQUAL_TO, moment)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an EntityCondition representing a date range filter query to be used against
|
||||
* entities that themselves represent a date range. When used the resulting entities
|
||||
* will meet at least one of the following criteria:
|
||||
* - fromDate is equal to or after rangeStart but before rangeEnd
|
||||
* - thruDate is equal to or after rangeStart but before rangeEnd
|
||||
* - fromDate is null and thruDate is equal to or after rangeStart
|
||||
* - thruDate is null and fromDate is before rangeEnd
|
||||
* - fromDate is null and thruDate is null
|
||||
*
|
||||
* @param rangeStart The start of the range to filter against
|
||||
* @param rangeEnd The end of the range to filter against
|
||||
* @param fromDateName The name of the field containing the entity's "fromDate"
|
||||
* @param thruDateName The name of the field containing the entity's "thruDate"
|
||||
* @return EntityCondition representing the date range filter
|
||||
*/
|
||||
public static EntityCondition makeRangeCondition(Timestamp rangeStart, Timestamp rangeEnd, String fromDateName, String thruDateName) {
|
||||
List<EntityCondition> criteria = new LinkedList<EntityCondition>();
|
||||
// fromDate is equal to or after rangeStart but before rangeEnd
|
||||
criteria.add(
|
||||
EntityCondition.makeCondition(
|
||||
EntityCondition.makeCondition(fromDateName, EntityOperator.GREATER_THAN_EQUAL_TO, rangeStart),
|
||||
EntityOperator.AND,
|
||||
EntityCondition.makeCondition(fromDateName, EntityOperator.LESS_THAN, rangeEnd)
|
||||
)
|
||||
);
|
||||
// thruDate is equal to or after rangeStart but before rangeEnd
|
||||
criteria.add(
|
||||
EntityCondition.makeCondition(
|
||||
EntityCondition.makeCondition(thruDateName, EntityOperator.GREATER_THAN_EQUAL_TO, rangeStart),
|
||||
EntityOperator.AND,
|
||||
EntityCondition.makeCondition(thruDateName, EntityOperator.LESS_THAN, rangeEnd)
|
||||
)
|
||||
);
|
||||
// fromDate is null and thruDate is equal to or after rangeStart
|
||||
criteria.add(
|
||||
EntityCondition.makeCondition(
|
||||
EntityCondition.makeCondition(fromDateName, EntityOperator.EQUALS, null),
|
||||
EntityOperator.AND,
|
||||
EntityCondition.makeCondition(thruDateName, EntityOperator.GREATER_THAN_EQUAL_TO, rangeStart)
|
||||
)
|
||||
);
|
||||
// thruDate is null and fromDate is before rangeEnd
|
||||
criteria.add(
|
||||
EntityCondition.makeCondition(
|
||||
EntityCondition.makeCondition(thruDateName, EntityOperator.EQUALS, null),
|
||||
EntityOperator.AND,
|
||||
EntityCondition.makeCondition(fromDateName, EntityOperator.LESS_THAN, rangeEnd)
|
||||
)
|
||||
);
|
||||
// fromDate is null and thruDate is null
|
||||
criteria.add(
|
||||
EntityCondition.makeCondition(
|
||||
EntityCondition.makeCondition(thruDateName, EntityOperator.EQUALS, null),
|
||||
EntityOperator.AND,
|
||||
EntityCondition.makeCondition(fromDateName, EntityOperator.EQUALS, null)
|
||||
)
|
||||
);
|
||||
// require at least one of the above to be true
|
||||
return EntityCondition.makeCondition(criteria, EntityOperator.OR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.ObjectType;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.DelegatorFactory;
|
||||
import org.ofbiz.entity.GenericEntity;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelField;
|
||||
import org.ofbiz.entity.model.ModelFieldType;
|
||||
|
||||
/**
|
||||
* Encapsulates simple expressions used for specifying queries
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public final class EntityExpr extends EntityCondition {
|
||||
public static final String module = EntityExpr.class.getName();
|
||||
|
||||
private final Object lhs;
|
||||
private final EntityOperator<Object, Object, ?> operator;
|
||||
private final Object rhs;
|
||||
|
||||
public <L,R,LL,RR> EntityExpr(L lhs, EntityComparisonOperator<LL,RR> operator, R rhs) {
|
||||
if (lhs == null) {
|
||||
throw new IllegalArgumentException("The field name/value cannot be null");
|
||||
}
|
||||
if (operator == null) {
|
||||
throw new IllegalArgumentException("The operator argument cannot be null");
|
||||
}
|
||||
|
||||
if (rhs == null || rhs == GenericEntity.NULL_FIELD) {
|
||||
if (!EntityOperator.NOT_EQUAL.equals(operator) && !EntityOperator.EQUALS.equals(operator)) {
|
||||
throw new IllegalArgumentException("Operator must be EQUALS or NOT_EQUAL when right/rhs argument is NULL ");
|
||||
}
|
||||
}
|
||||
|
||||
if (EntityOperator.BETWEEN.equals(operator)) {
|
||||
if (!(rhs instanceof Collection<?>) || (((Collection<?>) rhs).size() != 2)) {
|
||||
throw new IllegalArgumentException("BETWEEN Operator requires a Collection with 2 elements for the right/rhs argument");
|
||||
}
|
||||
}
|
||||
|
||||
if (lhs instanceof String) {
|
||||
this.lhs = EntityFieldValue.makeFieldValue((String) lhs);
|
||||
} else {
|
||||
this.lhs = lhs;
|
||||
}
|
||||
this.operator = UtilGenerics.cast(operator);
|
||||
this.rhs = rhs;
|
||||
|
||||
//Debug.logInfo("new EntityExpr internal field=" + lhs + ", value=" + rhs + ", value type=" + (rhs == null ? "null object" : rhs.getClass().getName()), module);
|
||||
}
|
||||
|
||||
public EntityExpr(EntityCondition lhs, EntityJoinOperator operator, EntityCondition rhs) {
|
||||
if (lhs == null) {
|
||||
throw new IllegalArgumentException("The left EntityCondition argument cannot be null");
|
||||
}
|
||||
if (rhs == null) {
|
||||
throw new IllegalArgumentException("The right EntityCondition argument cannot be null");
|
||||
}
|
||||
if (operator == null) {
|
||||
throw new IllegalArgumentException("The operator argument cannot be null");
|
||||
}
|
||||
|
||||
this.lhs = lhs;
|
||||
this.operator = UtilGenerics.cast(operator);
|
||||
this.rhs = rhs;
|
||||
}
|
||||
|
||||
public Object getLhs() {
|
||||
return lhs;
|
||||
}
|
||||
|
||||
public <L,R,T> EntityOperator<L,R,T> getOperator() {
|
||||
return UtilGenerics.cast(operator);
|
||||
}
|
||||
|
||||
public Object getRhs() {
|
||||
return rhs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return operator.isEmpty(lhs, rhs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String makeWhereString(ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, Datasource datasourceInfo) {
|
||||
// if (Debug.verboseOn()) Debug.logVerbose("makeWhereString for entity " + modelEntity.getEntityName(), module);
|
||||
|
||||
this.checkRhsType(modelEntity, null);
|
||||
|
||||
StringBuilder sql = new StringBuilder();
|
||||
operator.addSqlValue(sql, modelEntity, entityConditionParams, true, lhs, rhs, datasourceInfo);
|
||||
return sql.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mapMatches(Delegator delegator, Map<String, ? extends Object> map) {
|
||||
return operator.mapMatches(delegator, map, lhs, rhs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkCondition(ModelEntity modelEntity) throws GenericModelException {
|
||||
// if (Debug.verboseOn()) Debug.logVerbose("checkCondition for entity " + modelEntity.getEntityName(), module);
|
||||
if (lhs instanceof EntityCondition) {
|
||||
((EntityCondition) lhs).checkCondition(modelEntity);
|
||||
((EntityCondition) rhs).checkCondition(modelEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void addValue(StringBuilder buffer, ModelField field, Object value, List<EntityConditionParam> params) {
|
||||
if (rhs instanceof EntityFunction.UPPER) {
|
||||
if (value instanceof String) {
|
||||
value = ((String) value).toUpperCase();
|
||||
}
|
||||
}
|
||||
super.addValue(buffer, field, value, params);
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityCondition freeze() {
|
||||
return operator.freeze(lhs, rhs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(EntityConditionVisitor visitor) {
|
||||
visitor.acceptEntityOperator(operator, lhs, rhs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(EntityConditionVisitor visitor) {
|
||||
visitor.acceptEntityExpr(this);
|
||||
}
|
||||
|
||||
public void checkRhsType(ModelEntity modelEntity, Delegator delegator) {
|
||||
if (this.rhs == null || this.rhs == GenericEntity.NULL_FIELD || modelEntity == null) return;
|
||||
|
||||
Object value = this.rhs;
|
||||
if (this.rhs instanceof EntityFunction<?>) {
|
||||
value = UtilGenerics.<EntityFunction<?>>cast(this.rhs).getOriginalValue();
|
||||
}
|
||||
|
||||
if (value instanceof Collection<?>) {
|
||||
Collection<?> valueCol = UtilGenerics.cast(value);
|
||||
if (valueCol.size() > 0) {
|
||||
value = valueCol.iterator().next();
|
||||
} else {
|
||||
value = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (delegator == null) {
|
||||
// this will be the common case for now as the delegator isn't available where we want to do this
|
||||
// we'll cheat a little here and assume the default delegator
|
||||
delegator = DelegatorFactory.getDelegator("default");
|
||||
}
|
||||
|
||||
String fieldName = null;
|
||||
ModelField curField;
|
||||
if (this.lhs instanceof EntityFieldValue) {
|
||||
EntityFieldValue efv = (EntityFieldValue) this.lhs;
|
||||
fieldName = efv.getFieldName();
|
||||
curField = efv.getModelField(modelEntity);
|
||||
} else {
|
||||
// nothing to check
|
||||
return;
|
||||
}
|
||||
|
||||
if (curField == null) {
|
||||
throw new IllegalArgumentException("FieldName " + fieldName + " not found for entity: " + modelEntity.getEntityName());
|
||||
}
|
||||
ModelFieldType type = null;
|
||||
try {
|
||||
type = delegator.getEntityFieldType(modelEntity, curField.getType());
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logWarning(e, module);
|
||||
}
|
||||
if (type == null) {
|
||||
throw new IllegalArgumentException("Type " + curField.getType() + " not found for entity [" + modelEntity.getEntityName() + "]; probably because there is no datasource (helper) setup for the entity group that this entity is in: [" + delegator.getEntityGroupName(modelEntity.getEntityName()) + "]");
|
||||
}
|
||||
if (value instanceof EntityConditionSubSelect){
|
||||
ModelFieldType valueType = null;
|
||||
try {
|
||||
ModelEntity valueModelEntity= ((EntityConditionSubSelect) value).getModelEntity();
|
||||
valueType = delegator.getEntityFieldType(valueModelEntity, valueModelEntity.getField(((EntityConditionSubSelect) value).getKeyFieldName()).getType());
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logWarning(e, module);
|
||||
}
|
||||
// make sure the type of keyFieldName of EntityConditionSubSelect matches the field Java type
|
||||
try {
|
||||
if (!ObjectType.instanceOf(ObjectType.loadClass(valueType.getJavaType()), type.getJavaType())) {
|
||||
String errMsg = "Warning using ["+ value.getClass().getName() + "] and entity field [" + modelEntity.getEntityName() + "." + curField.getName() + "]. The Java type of keyFieldName : [" + valueType.getJavaType()+ "] is not compatible with the Java type of the field [" + type.getJavaType() + "]";
|
||||
// eventually we should do this, but for now we'll do a "soft" failure: throw new IllegalArgumentException(errMsg);
|
||||
Debug.logWarning(new Exception("Location of database type warning"), "=-=-=-=-=-=-=-=-= Database type warning in EntityExpr =-=-=-=-=-=-=-=-= " + errMsg, module);
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
String errMsg = "Warning using ["+ value.getClass().getName() + "] and entity field [" + modelEntity.getEntityName() + "." + curField.getName() + "]. The Java type of keyFieldName : [" + valueType.getJavaType()+ "] could not be found]";
|
||||
// eventually we should do this, but for now we'll do a "soft" failure: throw new IllegalArgumentException(errMsg);
|
||||
Debug.logWarning(e, "=-=-=-=-=-=-=-=-= Database type warning in EntityExpr =-=-=-=-=-=-=-=-= " + errMsg, module);
|
||||
}
|
||||
} else if (value instanceof EntityFieldValue) {
|
||||
EntityFieldValue efv = (EntityFieldValue) this.lhs;
|
||||
String rhsFieldName = efv.getFieldName();
|
||||
ModelField rhsField = efv.getModelField(modelEntity);
|
||||
if (rhsField == null) {
|
||||
throw new IllegalArgumentException("FieldName " + rhsFieldName + " not found for entity: " + modelEntity.getEntityName());
|
||||
}
|
||||
ModelFieldType rhsType = null;
|
||||
try {
|
||||
rhsType = delegator.getEntityFieldType(modelEntity, rhsField.getType());
|
||||
} catch (GenericEntityException e) {
|
||||
Debug.logWarning(e, module);
|
||||
}
|
||||
try {
|
||||
if (!ObjectType.instanceOf(ObjectType.loadClass(rhsType.getJavaType()), type.getJavaType())) {
|
||||
String errMsg = "Warning using ["+ value.getClass().getName() + "] and entity field [" + modelEntity.getEntityName() + "." + curField.getName() + "]. The Java type [" + rhsType.getJavaType() + "] of rhsFieldName : [" + rhsFieldName + "] is not compatible with the Java type of the field [" + type.getJavaType() + "]";
|
||||
// eventually we should do this, but for now we'll do a "soft" failure: throw new IllegalArgumentException(errMsg);
|
||||
Debug.logWarning(new Exception("Location of database type warning"), "=-=-=-=-=-=-=-=-= Database type warning in EntityExpr =-=-=-=-=-=-=-=- " + errMsg, module);
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
String errMsg = "Warning using ["+ value.getClass().getName() + "] and entity field [" + modelEntity.getEntityName() + "." + curField.getName() + "]. The Java type [" + rhsType.getJavaType() + "] of rhsFieldName : [" + rhsFieldName + "] could not be found]";
|
||||
// eventually we should do this, but for now we'll do a "soft" failure: throw new IllegalArgumentException(errMsg);
|
||||
Debug.logWarning(e, "=-=-=-=-=-=-=-=-= Database type warning in EntityExpr =-=-=-=-=-=-=-=-= " + errMsg, module);
|
||||
}
|
||||
} else {
|
||||
// make sure the type matches the field Java type
|
||||
if (!ObjectType.instanceOf(value, type.getJavaType())) {
|
||||
String errMsg = "In entity field [" + modelEntity.getEntityName() + "." + curField.getName() + "] set the value passed in [" + value.getClass().getName() + "] is not compatible with the Java type of the field [" + type.getJavaType() + "]";
|
||||
// eventually we should do this, but for now we'll do a "soft" failure: throw new IllegalArgumentException(errMsg);
|
||||
Debug.logWarning(new Exception("Location of database type warning"), "=-=-=-=-=-=-=-=-= Database type warning in EntityExpr =-=-=-=-=-=-=-=-= " + errMsg, module);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof EntityExpr)) return false;
|
||||
EntityExpr other = (EntityExpr) obj;
|
||||
boolean isEqual = equals(lhs, other.lhs) &&
|
||||
equals(operator, other.operator) &&
|
||||
equals(rhs, other.rhs);
|
||||
//if (!isEqual) {
|
||||
// Debug.logWarning("EntityExpr.equals is false for: \n-this.lhs=" + this.lhs + "; other.lhs=" + other.lhs +
|
||||
// "\nthis.operator=" + this.operator + "; other.operator=" + other.operator +
|
||||
// "\nthis.rhs=" + this.rhs + "other.rhs=" + other.rhs, module);
|
||||
//}
|
||||
return isEqual;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return hashCode(lhs) +
|
||||
hashCode(operator) +
|
||||
hashCode(rhs);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.entity.util.EntityUtil;
|
||||
|
||||
/**
|
||||
* Encapsulates simple expressions used for specifying queries
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public final class EntityFieldMap extends EntityConditionListBase<EntityExpr> {
|
||||
|
||||
protected final Map<String, ? extends Object> fieldMap;
|
||||
|
||||
public static <V> List<EntityExpr> makeConditionList(Map<String, V> fieldMap, EntityComparisonOperator<?,V> op) {
|
||||
if (fieldMap == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<EntityExpr> list = new ArrayList<EntityExpr>(fieldMap.size());
|
||||
for (Map.Entry<String, ? extends Object> entry: fieldMap.entrySet()) {
|
||||
list.add(EntityCondition.makeCondition(entry.getKey(), op, entry.getValue()));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public <V> EntityFieldMap(EntityComparisonOperator<?,?> compOp, EntityJoinOperator joinOp, V... keysValues) {
|
||||
this(EntityUtil.makeFields(keysValues), UtilGenerics.<EntityComparisonOperator<String,V>>cast(compOp), joinOp);
|
||||
}
|
||||
|
||||
public <V> EntityFieldMap(Map<String, V> fieldMap, EntityComparisonOperator<?,?> compOp, EntityJoinOperator joinOp) {
|
||||
super(makeConditionList(fieldMap, UtilGenerics.<EntityComparisonOperator<String,V>>cast(compOp)), joinOp);
|
||||
this.fieldMap = fieldMap == null ? Collections.<String, Object>emptyMap() : fieldMap;
|
||||
}
|
||||
|
||||
public Object getField(String name) {
|
||||
return this.fieldMap.get(name);
|
||||
}
|
||||
|
||||
public boolean containsField(String name) {
|
||||
return this.fieldMap.containsKey(name);
|
||||
}
|
||||
|
||||
public Iterator<String> getFieldKeyIterator() {
|
||||
return Collections.unmodifiableSet(this.fieldMap.keySet()).iterator();
|
||||
}
|
||||
|
||||
public Iterator<Map.Entry<String, ? extends Object>> getFieldEntryIterator() {
|
||||
return Collections.<Map.Entry<String, ? extends Object>>unmodifiableSet(this.fieldMap.entrySet()).iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(EntityConditionVisitor visitor) {
|
||||
visitor.acceptEntityFieldMap(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntity;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelField;
|
||||
import org.ofbiz.entity.model.ModelViewEntity;
|
||||
import org.ofbiz.entity.model.ModelViewEntity.ModelAlias;
|
||||
|
||||
/**
|
||||
* Field value expression.
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class EntityFieldValue extends EntityConditionValue {
|
||||
|
||||
public static final String module = EntityFieldValue.class.getName();
|
||||
|
||||
protected String fieldName = null;
|
||||
protected String entityAlias = null;
|
||||
protected List<String> entityAliasStack = null;
|
||||
protected ModelViewEntity modelViewEntity = null;
|
||||
|
||||
public static EntityFieldValue makeFieldValue(String fieldName) {
|
||||
EntityFieldValue efv = new EntityFieldValue();
|
||||
efv.init(fieldName, null, null, null);
|
||||
return efv;
|
||||
}
|
||||
|
||||
public static EntityFieldValue makeFieldValue(String fieldName, String entityAlias, List<String> entityAliasStack, ModelViewEntity modelViewEntity) {
|
||||
EntityFieldValue efv = new EntityFieldValue();
|
||||
efv.init(fieldName, entityAlias, entityAliasStack, modelViewEntity);
|
||||
return efv;
|
||||
}
|
||||
|
||||
public void init(String fieldName, String entityAlias, List<String> entityAliasStack, ModelViewEntity modelViewEntity) {
|
||||
this.fieldName = fieldName;
|
||||
this.entityAlias = entityAlias;
|
||||
if (UtilValidate.isNotEmpty(entityAliasStack)) {
|
||||
this.entityAliasStack = new LinkedList<String>();
|
||||
this.entityAliasStack.addAll(entityAliasStack);
|
||||
}
|
||||
this.modelViewEntity = modelViewEntity;
|
||||
if (UtilValidate.isNotEmpty(this.entityAliasStack) && UtilValidate.isEmpty(this.entityAlias)) {
|
||||
// look it up on the view entity so it can be part of the big list, this only happens for aliased fields, so find the entity-alias and field-name for the alias
|
||||
ModelAlias modelAlias = this.modelViewEntity.getAlias(this.fieldName);
|
||||
if (modelAlias != null) {
|
||||
this.entityAlias = modelAlias.getEntityAlias();
|
||||
this.fieldName = modelAlias.getField();
|
||||
}
|
||||
// TODO/NOTE: this will ignore function, group-by, etc... should maybe support those in conditions too at some point
|
||||
}
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
this.fieldName = null;
|
||||
this.entityAlias = null;
|
||||
this.entityAliasStack = null;
|
||||
this.modelViewEntity = null;
|
||||
}
|
||||
|
||||
public String getFieldName() {
|
||||
return fieldName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hash = fieldName.hashCode();
|
||||
if (this.entityAlias != null) hash |= this.entityAlias.hashCode();
|
||||
if (this.entityAliasStack != null) hash |= this.entityAliasStack.hashCode();
|
||||
if (this.modelViewEntity != null) hash |= this.modelViewEntity.hashCode();
|
||||
return hash;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof EntityFieldValue)) return false;
|
||||
EntityFieldValue otherValue = (EntityFieldValue) obj;
|
||||
if (!fieldName.equals(otherValue.fieldName)) return false;
|
||||
if (UtilMisc.compare(this.entityAlias, otherValue.entityAlias) != 0) return false;
|
||||
if (UtilMisc.compare(this.entityAliasStack, otherValue.entityAliasStack) != 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModelField getModelField(ModelEntity modelEntity) {
|
||||
if (this.modelViewEntity != null) {
|
||||
if (this.entityAlias != null) {
|
||||
ModelEntity memberModelEntity = modelViewEntity.getMemberModelEntity(entityAlias);
|
||||
return getField(memberModelEntity, fieldName);
|
||||
} else {
|
||||
return getField(modelViewEntity, fieldName);
|
||||
}
|
||||
}
|
||||
return getField(modelEntity, fieldName);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void setModelField(ModelField field) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addSqlValue(StringBuilder sql, Map<String, String> tableAliases, ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, boolean includeTableNamePrefix, Datasource datasourceInfo) {
|
||||
if (this.modelViewEntity != null) {
|
||||
// NOTE: this section is a bit of a hack; the other code is terribly complex and really needs to be refactored to incorporate support for this
|
||||
|
||||
if (UtilValidate.isNotEmpty(entityAlias)) {
|
||||
ModelEntity memberModelEntity = modelViewEntity.getMemberModelEntity(entityAlias);
|
||||
ModelField modelField = memberModelEntity.getField(fieldName);
|
||||
|
||||
// using entityAliasStack (ordered top to bottom) build a big long alias; not that dots will be replaced after it is combined with the column name in the SQL gen
|
||||
if (UtilValidate.isNotEmpty(this.entityAliasStack)) {
|
||||
boolean dotUsed = false;
|
||||
for (String curEntityAlias: entityAliasStack) {
|
||||
sql.append(curEntityAlias);
|
||||
if (dotUsed) {
|
||||
sql.append("_");
|
||||
} else {
|
||||
sql.append(".");
|
||||
dotUsed = true;
|
||||
}
|
||||
|
||||
}
|
||||
sql.append(entityAlias);
|
||||
sql.append("_");
|
||||
sql.append(modelField.getColName());
|
||||
} else {
|
||||
sql.append(entityAlias);
|
||||
sql.append(".");
|
||||
sql.append(modelField.getColName());
|
||||
}
|
||||
} else {
|
||||
sql.append(getColName(tableAliases, modelViewEntity, fieldName, includeTableNamePrefix, datasourceInfo));
|
||||
}
|
||||
} else {
|
||||
sql.append(getColName(tableAliases, modelEntity, fieldName, includeTableNamePrefix, datasourceInfo));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validateSql(ModelEntity modelEntity) throws GenericModelException {
|
||||
ModelField field = getModelField(modelEntity);
|
||||
if (field == null) {
|
||||
throw new GenericModelException("Field with name " + fieldName + " not found in the " + modelEntity.getEntityName() + " Entity");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getValue(Delegator delegator, Map<String, ? extends Object> map) {
|
||||
if (map == null) {
|
||||
return null;
|
||||
}
|
||||
if (map instanceof GenericEntity.NULL) {
|
||||
return null;
|
||||
} else {
|
||||
return map.get(fieldName);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(EntityConditionVisitor visitor) {
|
||||
visitor.acceptEntityFieldValue(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(EntityConditionVisitor visitor) {
|
||||
visitor.acceptEntityFieldValue(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityConditionValue freeze() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelField;
|
||||
|
||||
/**
|
||||
* Base class for entity functions.
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public abstract class EntityFunction<T extends Comparable<?>> extends EntityConditionValue {
|
||||
|
||||
public static interface Fetcher<T> {
|
||||
T getValue(Object value);
|
||||
}
|
||||
|
||||
public static enum SQLFunction {
|
||||
LENGTH, TRIM, UPPER, LOWER;
|
||||
}
|
||||
|
||||
public static final int ID_LENGTH = SQLFunction.LENGTH.ordinal();
|
||||
public static final int ID_TRIM = SQLFunction.TRIM.ordinal();
|
||||
public static final int ID_UPPER = SQLFunction.UPPER.ordinal();
|
||||
public static final int ID_LOWER = SQLFunction.LOWER.ordinal();
|
||||
|
||||
public static EntityFunction<Integer> LENGTH(EntityConditionValue nested) { return new LENGTH(nested); }
|
||||
public static EntityFunction<Integer> LENGTH(Object value) { return new LENGTH(value); }
|
||||
public static EntityFunction<String> TRIM(EntityConditionValue nested) { return new TRIM(nested); }
|
||||
public static EntityFunction<String> TRIM(Object value) { return new TRIM(value); }
|
||||
public static EntityFunction<String> UPPER(EntityConditionValue nested) { return new UPPER(nested); }
|
||||
public static EntityFunction<String> UPPER(Object value) { return new UPPER(value); }
|
||||
public static EntityFunction<String> UPPER_FIELD(String fieldName) { return new UPPER(EntityFieldValue.makeFieldValue(fieldName)); }
|
||||
public static EntityFunction<String> LOWER(EntityConditionValue nested) { return new LOWER(nested); }
|
||||
public static EntityFunction<String> LOWER(Object value) { return new LOWER(value); }
|
||||
|
||||
/**
|
||||
* Length() entity function.
|
||||
*
|
||||
*/
|
||||
public static class LENGTH extends EntityFunctionSingle<Integer> {
|
||||
public static Fetcher<Integer> FETCHER = new Fetcher<Integer>() {
|
||||
public Integer getValue(Object value) { return value.toString().length(); }
|
||||
};
|
||||
|
||||
private LENGTH(Object value) {
|
||||
super(FETCHER, SQLFunction.LENGTH, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Trim() entity function.
|
||||
*
|
||||
*/
|
||||
public static class TRIM extends EntityFunctionSingle<String> {
|
||||
public static Fetcher<String> FETCHER = new Fetcher<String>() {
|
||||
public String getValue(Object value) { return value.toString().trim(); }
|
||||
};
|
||||
|
||||
private TRIM(Object value) {
|
||||
super(FETCHER, SQLFunction.TRIM, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upper() entity function.
|
||||
*
|
||||
*/
|
||||
public static class UPPER extends EntityFunctionSingle<String> {
|
||||
public static Fetcher<String> FETCHER = new Fetcher<String>() {
|
||||
public String getValue(Object value) { return value.toString().toUpperCase(); }
|
||||
};
|
||||
|
||||
private UPPER(Object value) {
|
||||
super(FETCHER, SQLFunction.UPPER, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lower() entity function.
|
||||
*
|
||||
*/
|
||||
public static class LOWER extends EntityFunctionSingle<String> {
|
||||
public static Fetcher<String> FETCHER = new Fetcher<String>() {
|
||||
public String getValue(Object value) { return value.toString().toLowerCase(); }
|
||||
};
|
||||
|
||||
private LOWER(Object value) {
|
||||
super(FETCHER, SQLFunction.LOWER, value);
|
||||
}
|
||||
}
|
||||
|
||||
public static abstract class EntityFunctionSingle<T extends Comparable<?>> extends EntityFunction<T> {
|
||||
protected EntityFunctionSingle(Fetcher<T> fetcher, SQLFunction function, Object value) {
|
||||
super(fetcher, function, value);
|
||||
}
|
||||
}
|
||||
|
||||
public static abstract class EntityFunctionNested<T extends Comparable<?>> extends EntityFunction<T> {
|
||||
protected EntityFunctionNested(Fetcher<T> fetcher, SQLFunction function, EntityConditionValue nested) {
|
||||
super(fetcher, function, nested);
|
||||
}
|
||||
}
|
||||
|
||||
protected final SQLFunction function;
|
||||
protected final EntityConditionValue nested;
|
||||
protected final Object value;
|
||||
protected final Fetcher<T> fetcher;
|
||||
protected ModelField field;
|
||||
|
||||
protected EntityFunction(Fetcher<T> fetcher, SQLFunction function, EntityConditionValue nested) {
|
||||
this.fetcher = fetcher;
|
||||
this.function = function;
|
||||
this.nested = nested;
|
||||
this.value = null;
|
||||
}
|
||||
|
||||
protected EntityFunction(Fetcher<T> fetcher, SQLFunction function, Object value) {
|
||||
this.fetcher = fetcher;
|
||||
this.function = function;
|
||||
if (value instanceof EntityConditionValue) {
|
||||
this.nested = (EntityConditionValue) value;
|
||||
this.value = null;
|
||||
} else {
|
||||
this.nested = null;
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityConditionValue freeze() {
|
||||
if (nested != null) {
|
||||
return new EntityFunctionNested<T>(fetcher, function, nested.freeze()) {};
|
||||
} else {
|
||||
return new EntityFunctionSingle<T>(fetcher, function, value) {};
|
||||
}
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return function.name();
|
||||
}
|
||||
|
||||
public Object getOriginalValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return function.ordinal();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return function.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof EntityFunction<?>)) return false;
|
||||
EntityFunction<?> otherFunc = UtilGenerics.cast(obj);
|
||||
return (this.function == otherFunc.function &&
|
||||
(this.nested != null ? nested.equals(otherFunc.nested) : otherFunc.nested == null) &&
|
||||
(this.value != null ? value.equals(otherFunc.value) : otherFunc.value == null));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addSqlValue(StringBuilder sql, Map<String, String> tableAliases, ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, boolean includeTableNamePrefix, Datasource datasourceinfo) {
|
||||
sql.append(function.name()).append('(');
|
||||
if (nested != null) {
|
||||
nested.addSqlValue(sql, tableAliases, modelEntity, entityConditionParams, includeTableNamePrefix, datasourceinfo);
|
||||
} else {
|
||||
addValue(sql, null, value, entityConditionParams);
|
||||
}
|
||||
sql.append(')');
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(EntityConditionVisitor visitor) {
|
||||
if (nested != null) {
|
||||
visitor.acceptEntityConditionValue(nested);
|
||||
} else {
|
||||
visitor.acceptObject(value);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(EntityConditionVisitor visitor) {
|
||||
visitor.acceptEntityFunction(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModelField getModelField(ModelEntity modelEntity) {
|
||||
if (nested != null) {
|
||||
return nested.getModelField(modelEntity);
|
||||
}
|
||||
return field;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setModelField(ModelField field) {
|
||||
this.field = field;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validateSql(ModelEntity modelEntity) throws GenericModelException {
|
||||
if (nested != null) {
|
||||
nested.validateSql(modelEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getValue(Delegator delegator, Map<String, ? extends Object> map) {
|
||||
Object value = nested != null ? nested.getValue(delegator, map) : this.value;
|
||||
return value != null ? fetcher.getValue(value) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntity;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
|
||||
/**
|
||||
* Join operator (AND/OR).
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class EntityJoinOperator extends EntityOperator<EntityCondition, EntityCondition, Boolean> {
|
||||
|
||||
protected boolean shortCircuitValue;
|
||||
|
||||
protected EntityJoinOperator(int id, String code, boolean shortCircuitValue) {
|
||||
super(id, code);
|
||||
this.shortCircuitValue = shortCircuitValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addSqlValue(StringBuilder sql, ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, boolean compat, EntityCondition lhs, EntityCondition rhs, Datasource datasourceInfo) {
|
||||
List<EntityCondition> conditions = new LinkedList<EntityCondition>();
|
||||
conditions.add(lhs);
|
||||
conditions.add(rhs);
|
||||
addSqlValue(sql, modelEntity, entityConditionParams, conditions, datasourceInfo);
|
||||
}
|
||||
|
||||
public void addSqlValue(StringBuilder sql, ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, List<? extends EntityCondition> conditionList, Datasource datasourceInfo) {
|
||||
if (UtilValidate.isNotEmpty(conditionList)) {
|
||||
boolean hadSomething = false;
|
||||
Iterator<? extends EntityCondition> conditionIter = conditionList.iterator();
|
||||
while (conditionIter.hasNext()) {
|
||||
EntityCondition condition = conditionIter.next();
|
||||
if (condition.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (hadSomething) {
|
||||
sql.append(' ');
|
||||
sql.append(getCode());
|
||||
sql.append(' ');
|
||||
} else {
|
||||
hadSomething = true;
|
||||
sql.append('(');
|
||||
}
|
||||
sql.append(condition.makeWhereString(modelEntity, entityConditionParams, datasourceInfo));
|
||||
}
|
||||
if (hadSomething) {
|
||||
sql.append(')');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected EntityCondition freeze(Object item) {
|
||||
return ((EntityCondition) item).freeze();
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityCondition freeze(EntityCondition lhs, EntityCondition rhs) {
|
||||
return EntityCondition.makeCondition(freeze(lhs), this, freeze(rhs));
|
||||
}
|
||||
|
||||
public EntityCondition freeze(List<? extends EntityCondition> conditionList) {
|
||||
List<EntityCondition> newList = new ArrayList<EntityCondition>(conditionList.size());
|
||||
for (EntityCondition condition: conditionList) {
|
||||
newList.add(condition.freeze());
|
||||
}
|
||||
return EntityCondition.makeCondition(newList, this);
|
||||
}
|
||||
|
||||
public void visit(EntityConditionVisitor visitor, List<? extends EntityCondition> conditionList) {
|
||||
if (UtilValidate.isNotEmpty(conditionList)) {
|
||||
for (EntityCondition condition: conditionList) {
|
||||
visitor.visit(condition);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(EntityConditionVisitor visitor, EntityCondition lhs, EntityCondition rhs) {
|
||||
lhs.visit(visitor);
|
||||
visitor.visit(rhs);
|
||||
}
|
||||
|
||||
public Boolean eval(GenericEntity entity, EntityCondition lhs, EntityCondition rhs) {
|
||||
return entityMatches(entity, lhs, rhs) ? Boolean.TRUE : Boolean.FALSE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty(EntityCondition lhs, EntityCondition rhs) {
|
||||
return lhs.isEmpty() && rhs.isEmpty();
|
||||
}
|
||||
|
||||
public boolean isEmpty(List<? extends EntityCondition> conditionList) {
|
||||
for (EntityCondition condition: conditionList) {
|
||||
if (!condition.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean entityMatches(GenericEntity entity, EntityCondition lhs, EntityCondition rhs) {
|
||||
if (lhs.entityMatches(entity) == shortCircuitValue) return shortCircuitValue;
|
||||
if (rhs.entityMatches(entity) == shortCircuitValue) return shortCircuitValue;
|
||||
return !shortCircuitValue;
|
||||
}
|
||||
|
||||
public boolean entityMatches(GenericEntity entity, List<? extends EntityCondition> conditionList) {
|
||||
return mapMatches(entity.getDelegator(), entity, conditionList);
|
||||
}
|
||||
|
||||
public Boolean eval(Delegator delegator, Map<String, ? extends Object> map, EntityCondition lhs, EntityCondition rhs) {
|
||||
return castBoolean(mapMatches(delegator, map, lhs, rhs));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mapMatches(Delegator delegator, Map<String, ? extends Object> map, EntityCondition lhs, EntityCondition rhs) {
|
||||
if (lhs.mapMatches(delegator, map) == shortCircuitValue) return shortCircuitValue;
|
||||
if (rhs.mapMatches(delegator, map) == shortCircuitValue) return shortCircuitValue;
|
||||
return !shortCircuitValue;
|
||||
}
|
||||
|
||||
public Boolean eval(Delegator delegator, Map<String, ? extends Object> map, List<? extends EntityCondition> conditionList) {
|
||||
return castBoolean(mapMatches(delegator, map, conditionList));
|
||||
}
|
||||
|
||||
public boolean mapMatches(Delegator delegator, Map<String, ? extends Object> map, List<? extends EntityCondition> conditionList) {
|
||||
if (UtilValidate.isNotEmpty(conditionList)) {
|
||||
for (EntityCondition condition: conditionList) {
|
||||
if (condition.mapMatches(delegator, map) == shortCircuitValue) return shortCircuitValue;
|
||||
}
|
||||
}
|
||||
return !shortCircuitValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validateSql(ModelEntity modelEntity, EntityCondition lhs, EntityCondition rhs) throws GenericModelException {
|
||||
lhs.checkCondition(modelEntity);
|
||||
rhs.checkCondition(modelEntity);
|
||||
}
|
||||
|
||||
public void validateSql(ModelEntity modelEntity, List<? extends EntityCondition> conditionList) throws GenericModelException {
|
||||
if (conditionList == null) {
|
||||
throw new GenericModelException("Condition list is null");
|
||||
}
|
||||
for (EntityCondition condition: conditionList) {
|
||||
condition.checkCondition(modelEntity);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntity;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelField;
|
||||
|
||||
/**
|
||||
* Base class for operators (less than, greater than, equals, etc).
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public abstract class EntityOperator<L, R, T> extends EntityConditionBase {
|
||||
|
||||
public static final int ID_EQUALS = 1;
|
||||
public static final int ID_NOT_EQUAL = 2;
|
||||
public static final int ID_LESS_THAN = 3;
|
||||
public static final int ID_GREATER_THAN = 4;
|
||||
public static final int ID_LESS_THAN_EQUAL_TO = 5;
|
||||
public static final int ID_GREATER_THAN_EQUAL_TO = 6;
|
||||
public static final int ID_IN = 7;
|
||||
public static final int ID_BETWEEN = 8;
|
||||
public static final int ID_NOT = 9;
|
||||
public static final int ID_AND = 10;
|
||||
public static final int ID_OR = 11;
|
||||
public static final int ID_LIKE = 12;
|
||||
public static final int ID_NOT_IN = 13;
|
||||
public static final int ID_NOT_LIKE = 14;
|
||||
|
||||
private static final AtomicInteger dynamicId = new AtomicInteger();
|
||||
private static HashMap<String, EntityOperator<?,?,?>> registry = new HashMap<String, EntityOperator<?,?,?>>();
|
||||
|
||||
private static <L,R,T> void registerCase(String name, EntityOperator<L,R,T> operator) {
|
||||
registry.put(name.toLowerCase(), operator);
|
||||
registry.put(name.toUpperCase(), operator);
|
||||
}
|
||||
|
||||
public static <L,R,T> void register(String name, EntityOperator<L,R,T> operator) {
|
||||
registerCase(name, operator);
|
||||
registerCase(name.replaceAll("-", "_"), operator);
|
||||
registerCase(name.replaceAll("_", "-"), operator);
|
||||
}
|
||||
|
||||
public static <L,R,T> EntityOperator<L,R,T> lookup(String name) {
|
||||
return UtilGenerics.cast(registry.get(name));
|
||||
}
|
||||
|
||||
public static <L,R> EntityComparisonOperator<L,R> lookupComparison(String name) {
|
||||
EntityOperator<?,?,Boolean> operator = lookup(name);
|
||||
if (!(operator instanceof EntityComparisonOperator<?,?>))
|
||||
throw new IllegalArgumentException(name + " is not a comparison operator");
|
||||
return UtilGenerics.cast(operator);
|
||||
}
|
||||
|
||||
public static EntityJoinOperator lookupJoin(String name) {
|
||||
EntityOperator<?,?,Boolean> operator = lookup(name);
|
||||
if (!(operator instanceof EntityJoinOperator))
|
||||
throw new IllegalArgumentException(name + " is not a join operator");
|
||||
return UtilGenerics.cast(operator);
|
||||
}
|
||||
|
||||
public static int requestId() {
|
||||
return dynamicId.get();
|
||||
}
|
||||
|
||||
public static final EntityComparisonOperator<?,?> EQUALS = new ComparableEntityComparisonOperator<Object>(ID_EQUALS, "=") {
|
||||
@Override
|
||||
public boolean compare(Comparable<Object> lhs, Object rhs) { return EntityComparisonOperator.compareEqual(lhs, rhs); }
|
||||
@Override
|
||||
protected void makeRHSWhereString(ModelEntity entity, List<EntityConditionParam> entityConditionParams, StringBuilder sb, ModelField field, Object rhs, Datasource datasourceInfo) {
|
||||
if (rhs == null || rhs == GenericEntity.NULL_FIELD) {
|
||||
//Debug.logInfo("makeRHSWhereString: field IS NULL: " + field.getName(), module);
|
||||
sb.append(" IS NULL");
|
||||
} else {
|
||||
//Debug.logInfo("makeRHSWhereString: field not null, doing super: " + field.getName() + ", type: " + rhs.getClass().getName() + ", value: " + rhs, module);
|
||||
super.makeRHSWhereString(entity, entityConditionParams, sb, field, rhs, datasourceInfo);
|
||||
}
|
||||
}
|
||||
};
|
||||
static { register("equals", EQUALS); }
|
||||
static { register("=", EQUALS); }
|
||||
public static final EntityComparisonOperator<?,?> NOT_EQUAL = new ComparableEntityComparisonOperator<Object>(ID_NOT_EQUAL, "<>") {
|
||||
@Override
|
||||
public boolean compare(Comparable<Object> lhs, Object rhs) { return EntityComparisonOperator.compareNotEqual(lhs, rhs); }
|
||||
@Override
|
||||
protected void makeRHSWhereString(ModelEntity entity, List<EntityConditionParam> entityConditionParams, StringBuilder sb, ModelField field, Object rhs, Datasource datasourceInfo) {
|
||||
if (rhs == null || rhs == GenericEntity.NULL_FIELD) {
|
||||
sb.append(" IS NOT NULL");
|
||||
} else {
|
||||
super.makeRHSWhereString(entity, entityConditionParams, sb, field, rhs, datasourceInfo);
|
||||
}
|
||||
}
|
||||
};
|
||||
static { register("not-equal", NOT_EQUAL); }
|
||||
static { register("not-equals", NOT_EQUAL); }
|
||||
static { register("notEqual", NOT_EQUAL); }
|
||||
static { register("!=", NOT_EQUAL); }
|
||||
static { register("<>", NOT_EQUAL); }
|
||||
public static final EntityComparisonOperator<?,?> LESS_THAN = new ComparableEntityComparisonOperator<Object>(ID_LESS_THAN, "<") {
|
||||
@Override
|
||||
public boolean compare(Comparable<Object> lhs, Object rhs) { return EntityComparisonOperator.compareLessThan(lhs, rhs); }
|
||||
};
|
||||
static { register("less", LESS_THAN); }
|
||||
static { register("less-than", LESS_THAN); }
|
||||
static { register("lessThan", LESS_THAN); }
|
||||
static { register("<", LESS_THAN); }
|
||||
public static final EntityComparisonOperator<?,?> GREATER_THAN = new ComparableEntityComparisonOperator<Object>(ID_GREATER_THAN, ">") {
|
||||
@Override
|
||||
public boolean compare(Comparable<Object> lhs, Object rhs) { return EntityComparisonOperator.compareGreaterThan(lhs, rhs); }
|
||||
};
|
||||
static { register("greater", GREATER_THAN); }
|
||||
static { register("greater-than", GREATER_THAN); }
|
||||
static { register("greaterThan", GREATER_THAN); }
|
||||
static { register(">", GREATER_THAN); }
|
||||
public static final EntityComparisonOperator<?,?> LESS_THAN_EQUAL_TO = new ComparableEntityComparisonOperator<Object>(ID_LESS_THAN_EQUAL_TO, "<=") {
|
||||
@Override
|
||||
public boolean compare(Comparable<Object> lhs, Object rhs) { return EntityComparisonOperator.compareLessThanEqualTo(lhs, rhs); }
|
||||
};
|
||||
static { register("less-equals", LESS_THAN_EQUAL_TO); }
|
||||
static { register("less-than-equal-to", LESS_THAN_EQUAL_TO); }
|
||||
static { register("lessThanEqualTo", LESS_THAN_EQUAL_TO); }
|
||||
static { register("<=", LESS_THAN_EQUAL_TO); }
|
||||
public static final EntityComparisonOperator<?,?> GREATER_THAN_EQUAL_TO = new ComparableEntityComparisonOperator<Object>(ID_GREATER_THAN_EQUAL_TO, ">=") {
|
||||
@Override
|
||||
public boolean compare(Comparable<Object> lhs, Object rhs) { return EntityComparisonOperator.compareGreaterThanEqualTo(lhs, rhs); }
|
||||
};
|
||||
static { register("greater-equals", GREATER_THAN_EQUAL_TO); }
|
||||
static { register("greater-than-equal-to", GREATER_THAN_EQUAL_TO); }
|
||||
static { register("greaterThanEqualTo", GREATER_THAN_EQUAL_TO); }
|
||||
static { register(">=", GREATER_THAN_EQUAL_TO); }
|
||||
public static final EntityComparisonOperator<?,?> IN = new CollectionEntityComparisonOperator<Object>(ID_IN, "IN") {
|
||||
@Override
|
||||
public boolean compare(Comparable<Object> lhs, Collection<Comparable<Object>> rhs) { return EntityComparisonOperator.compareIn(lhs, rhs); }
|
||||
@Override
|
||||
protected void makeRHSWhereStringValue(ModelEntity entity, List<EntityConditionParam> entityConditionParams, StringBuilder sb, ModelField field, Collection<Comparable<Object>> rhs, Datasource datasourceInfo) { appendRHSList(entityConditionParams, sb, field, rhs); }
|
||||
};
|
||||
static { register("in", IN); }
|
||||
public static final EntityComparisonOperator<?,?> BETWEEN = new CollectionEntityComparisonOperator<Object>(ID_BETWEEN, "BETWEEN") {
|
||||
@Override
|
||||
public boolean compare(Comparable<Object> lhs, Collection<Comparable<Object>> rhs) { return EntityComparisonOperator.compareIn(lhs, rhs); }
|
||||
@Override
|
||||
protected void makeRHSWhereStringValue(ModelEntity entity, List<EntityConditionParam> entityConditionParams, StringBuilder sb, ModelField field, Collection<Comparable<Object>> rhs, Datasource datasourceInfo) { appendRHSBetweenList(entityConditionParams, sb, field, rhs); }
|
||||
};
|
||||
static { register("between", BETWEEN); }
|
||||
public static final EntityComparisonOperator<?,?> NOT = new EntityComparisonOperator<Object, EntityCondition>(ID_NOT, "NOT") {
|
||||
@Override
|
||||
public boolean compare(Object lhs, EntityCondition rhs) { throw new UnsupportedOperationException(); }
|
||||
};
|
||||
static { register("not", NOT); }
|
||||
public static final EntityJoinOperator AND = new EntityJoinOperator(ID_AND, "AND", false);
|
||||
static { register("and", AND); }
|
||||
public static final EntityJoinOperator OR = new EntityJoinOperator(ID_OR, "OR", true);
|
||||
static { register("or", OR); }
|
||||
public static final EntityComparisonOperator<?,?> LIKE = new ComparableEntityComparisonOperator<Object>(ID_LIKE, "LIKE") {
|
||||
@Override
|
||||
public boolean compare(Comparable<Object> lhs, Object rhs) { return EntityComparisonOperator.compareLike(lhs, rhs); }
|
||||
};
|
||||
static { register("like", LIKE); }
|
||||
public static final EntityComparisonOperator<?,?> NOT_LIKE = new ComparableEntityComparisonOperator<Object>(ID_NOT_LIKE, "NOT LIKE") {
|
||||
@Override
|
||||
public boolean compare(Comparable<Object> lhs, Object rhs) { return !EntityComparisonOperator.compareLike(lhs, rhs); }
|
||||
};
|
||||
static { register("not-like", NOT_LIKE); }
|
||||
public static final EntityComparisonOperator<?,?> NOT_IN = new CollectionEntityComparisonOperator<Object>(ID_NOT_IN, "NOT IN") {
|
||||
@Override
|
||||
public boolean compare(Comparable<Object> lhs, Collection<Comparable<Object>> rhs) { return !EntityComparisonOperator.compareIn(lhs, rhs); }
|
||||
@Override
|
||||
protected void makeRHSWhereStringValue(ModelEntity entity, List<EntityConditionParam> entityConditionParams, StringBuilder sb, ModelField field, Collection<Comparable<Object>> rhs, Datasource datasourceInfo) { appendRHSList(entityConditionParams, sb, field, rhs); }
|
||||
};
|
||||
static { register("not-in", NOT_IN); }
|
||||
|
||||
protected int idInt;
|
||||
protected String codeString;
|
||||
|
||||
public EntityOperator(int id, String code) {
|
||||
idInt = id;
|
||||
codeString = code;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
if (codeString == null) {
|
||||
return "null";
|
||||
} else {
|
||||
return codeString;
|
||||
}
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return idInt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return codeString;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return this.codeString.hashCode();
|
||||
}
|
||||
|
||||
// FIXME: CCE
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj instanceof EntityOperator<?,?,?>) {
|
||||
EntityOperator<?,?,?> otherOper = UtilGenerics.cast(obj);
|
||||
return this.idInt == otherOper.idInt;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean entityMatches(GenericEntity entity, L lhs, R rhs) {
|
||||
return mapMatches(entity.getDelegator(), entity, lhs, rhs);
|
||||
}
|
||||
|
||||
protected void appendRHSList(List<EntityConditionParam> entityConditionParams, StringBuilder whereStringBuilder, ModelField field, R rhs) {
|
||||
whereStringBuilder.append('(');
|
||||
|
||||
if (rhs instanceof Collection<?>) {
|
||||
Iterator<R> rhsIter = UtilGenerics.<Collection<R>>cast(rhs).iterator();
|
||||
|
||||
while (rhsIter.hasNext()) {
|
||||
Object inObj = rhsIter.next();
|
||||
|
||||
addValue(whereStringBuilder, field, inObj, entityConditionParams);
|
||||
if (rhsIter.hasNext()) {
|
||||
whereStringBuilder.append(", ");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
addValue(whereStringBuilder, field, rhs, entityConditionParams);
|
||||
}
|
||||
whereStringBuilder.append(')');
|
||||
}
|
||||
|
||||
protected <X> void appendRHSBetweenList(List<EntityConditionParam> entityConditionParams, StringBuilder whereStringBuilder, ModelField field, X rhs) {
|
||||
if (rhs instanceof Collection<?>) {
|
||||
Iterator<R> rhsIter = UtilGenerics.<Collection<R>>cast(rhs).iterator();
|
||||
|
||||
while (rhsIter.hasNext()) {
|
||||
Object inObj = rhsIter.next();
|
||||
|
||||
addValue(whereStringBuilder, field, inObj, entityConditionParams);
|
||||
if (rhsIter.hasNext()) {
|
||||
whereStringBuilder.append(" AND ");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
public T eval(Delegator delegator, Map<String, ? extends Object> map, Object lhs, Object rhs) {
|
||||
return castBoolean(mapMatches(delegator, map, lhs, rhs));
|
||||
}
|
||||
*/
|
||||
|
||||
public abstract boolean isEmpty(L lhs, R rhs);
|
||||
public abstract boolean mapMatches(Delegator delegator, Map<String, ? extends Object> map, L lhs, R rhs);
|
||||
public abstract void validateSql(ModelEntity entity, L lhs, R rhs) throws GenericModelException;
|
||||
public void addSqlValue(StringBuilder sql, ModelEntity entity, List<EntityConditionParam> entityConditionParams, L lhs, R rhs, Datasource datasourceInfo) {
|
||||
addSqlValue(sql, entity, entityConditionParams, true, lhs, rhs, datasourceInfo);
|
||||
}
|
||||
|
||||
public abstract void addSqlValue(StringBuilder sql, ModelEntity entity, List<EntityConditionParam> entityConditionParams, boolean compat, L lhs, R rhs, Datasource datasourceInfo);
|
||||
public abstract EntityCondition freeze(L lhs, R rhs);
|
||||
public abstract void visit(EntityConditionVisitor visitor, L lhs, R rhs);
|
||||
|
||||
public static final Comparable<?> WILDCARD = new Comparable<Object>() {
|
||||
public int compareTo(Object obj) {
|
||||
if (obj != WILDCARD) throw new ClassCastException();
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "(WILDCARD)";
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Comparison operator for <code>Collection</code> types.
|
||||
*
|
||||
* @param <E>
|
||||
*/
|
||||
public static abstract class CollectionEntityComparisonOperator<E> extends EntityComparisonOperator<Comparable<E>, Collection<Comparable<E>>> {
|
||||
public CollectionEntityComparisonOperator(int id, String code) {
|
||||
super(id, code);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Comparison operator for <code>Comparable</code> types.
|
||||
*
|
||||
* @param <E>
|
||||
*/
|
||||
public static abstract class ComparableEntityComparisonOperator<E> extends EntityComparisonOperator<Comparable<E>, E> {
|
||||
public ComparableEntityComparisonOperator(int id, String code) {
|
||||
super(id, code);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntity;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
|
||||
/**
|
||||
* <p>Encapsulates SQL expressions used for where clause snippets.
|
||||
* NOTE: This is UNSAFE and BREAKS the idea behind the Entity Engine where
|
||||
* you avoid directly specifying SQL. So, KEEP IT MINIMAL and preferably replace
|
||||
* it when the feature you are getting at is implemented in a more automatic way for you.</p>
|
||||
*
|
||||
* <p>By minimal I mean use this in conjunction with other EntityConditions like the
|
||||
* EntityExpr, EntityConditionList and EntityFieldMap objects which more cleanly
|
||||
* encapsulate where conditions and don't require you to directly write SQL.</p>
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public final class EntityWhereString extends EntityCondition {
|
||||
|
||||
protected final String sqlString;
|
||||
|
||||
public EntityWhereString(String sqlString) {
|
||||
this.sqlString = sqlString;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return UtilValidate.isEmpty(sqlString);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String makeWhereString(ModelEntity modelEntity, List<EntityConditionParam> entityConditionParams, Datasource datasourceInfo) {
|
||||
return sqlString;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkCondition(ModelEntity modelEntity) throws GenericModelException {// no nothing, this is always assumed to be fine... could do funky SQL syntax checking, but hey this is a HACK anyway
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean entityMatches(GenericEntity entity) {
|
||||
throw new UnsupportedOperationException("Cannot do entityMatches on a WhereString, ie no SQL evaluation in EE; Where String is: " + sqlString);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mapMatches(Delegator delegator, Map<String, ? extends Object> map) {
|
||||
throw new UnsupportedOperationException("Cannot do mapMatches on a WhereString, ie no SQL evaluation in EE; Where String is: " + sqlString);
|
||||
}
|
||||
|
||||
public String getWhereString() {
|
||||
return sqlString;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityCondition freeze() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(EntityConditionVisitor visitor) {
|
||||
visitor.acceptEntityWhereString(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof EntityWhereString)) return false;
|
||||
EntityWhereString other = (EntityWhereString) obj;
|
||||
return equals(sqlString, other.sqlString);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return hashCode(sqlString);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.entity.GenericEntity;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
|
||||
public class OrderByItem implements Comparator<GenericEntity> {
|
||||
public static final int DEFAULT = 0;
|
||||
public static final int UPPER = 1;
|
||||
public static final int LOWER = 2;
|
||||
|
||||
public static final String NULLS_FIRST = "NULLS FIRST";
|
||||
public static final String NULLS_LAST = "NULLS LAST";
|
||||
|
||||
protected boolean descending;
|
||||
protected Boolean nullsFirst;
|
||||
protected EntityConditionValue value;
|
||||
|
||||
public OrderByItem(EntityConditionValue value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public OrderByItem(EntityConditionValue value, boolean descending) {
|
||||
this(value);
|
||||
this.descending = descending;
|
||||
}
|
||||
|
||||
public OrderByItem(EntityConditionValue value, boolean descending, Boolean nullsFirst) {
|
||||
this(value, descending);
|
||||
this.nullsFirst = nullsFirst;
|
||||
}
|
||||
|
||||
public EntityConditionValue getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public boolean getDescending() {
|
||||
return descending;
|
||||
}
|
||||
|
||||
public static final OrderByItem parse(Object obj) {
|
||||
if (obj instanceof String) {
|
||||
return parse((String) obj);
|
||||
} else if (obj instanceof EntityConditionValue) {
|
||||
return new OrderByItem((EntityConditionValue) obj, false);
|
||||
} else if (obj instanceof OrderByItem) {
|
||||
return (OrderByItem) obj;
|
||||
} else {
|
||||
throw new IllegalArgumentException("unknown orderBy item: " + obj);
|
||||
}
|
||||
}
|
||||
|
||||
public static final OrderByItem parse(String text) {
|
||||
text = text.trim();
|
||||
|
||||
// handle nulls first/last
|
||||
Boolean nullsFirst = null;
|
||||
if (text.toUpperCase().endsWith(NULLS_FIRST)) {
|
||||
nullsFirst = true;
|
||||
text = text.substring(0, text.length() - NULLS_FIRST.length()).trim();
|
||||
}
|
||||
|
||||
if (text.toUpperCase().endsWith(NULLS_LAST)) {
|
||||
nullsFirst = false;
|
||||
text = text.substring(0, text.length() - NULLS_LAST.length()).trim();
|
||||
}
|
||||
|
||||
int startIndex = 0, endIndex = text.length();
|
||||
boolean descending;
|
||||
int caseSensitivity;
|
||||
if (text.endsWith(" DESC")) {
|
||||
descending = true;
|
||||
endIndex -= 5;
|
||||
} else if (text.endsWith(" ASC")) {
|
||||
descending = false;
|
||||
endIndex -= 4;
|
||||
} else if (text.startsWith("-")) {
|
||||
descending = true;
|
||||
startIndex++;
|
||||
} else if (text.startsWith("+")) {
|
||||
descending = false;
|
||||
startIndex++;
|
||||
} else {
|
||||
descending = false;
|
||||
}
|
||||
|
||||
if (startIndex != 0 || endIndex != text.length()) {
|
||||
text = text.substring(startIndex, endIndex);
|
||||
startIndex = 0;
|
||||
endIndex = text.length();
|
||||
}
|
||||
|
||||
if (text.endsWith(")")) {
|
||||
String upperText = text.toUpperCase();
|
||||
endIndex--;
|
||||
if (upperText.startsWith("UPPER(")) {
|
||||
caseSensitivity = UPPER;
|
||||
startIndex = 6;
|
||||
} else if (upperText.startsWith("LOWER(")) {
|
||||
caseSensitivity = LOWER;
|
||||
startIndex = 6;
|
||||
} else {
|
||||
caseSensitivity = DEFAULT;
|
||||
}
|
||||
} else {
|
||||
caseSensitivity = DEFAULT;
|
||||
}
|
||||
|
||||
if (startIndex != 0 || endIndex != text.length()) {
|
||||
text = text.substring(startIndex, endIndex);
|
||||
startIndex = 0;
|
||||
endIndex = text.length();
|
||||
}
|
||||
EntityConditionValue value = EntityFieldValue.makeFieldValue(text);
|
||||
switch (caseSensitivity) {
|
||||
case UPPER:
|
||||
value = EntityFunction.UPPER(value);
|
||||
break;
|
||||
case LOWER:
|
||||
value = EntityFunction.LOWER(value);
|
||||
break;
|
||||
}
|
||||
return new OrderByItem(value, descending, nullsFirst);
|
||||
}
|
||||
|
||||
public void checkOrderBy(ModelEntity modelEntity) throws GenericModelException {
|
||||
value.validateSql(modelEntity);
|
||||
}
|
||||
|
||||
public int compare(GenericEntity obj1, GenericEntity obj2) {
|
||||
Comparable<Object> value1 = UtilGenerics.cast(value.getValue(obj1));
|
||||
Object value2 = value.getValue(obj2);
|
||||
|
||||
int result;
|
||||
// null is defined as the largest possible value
|
||||
if (value1 == null) {
|
||||
result = value2 == null ? 0 : 1;
|
||||
} else if (value2 == null) {
|
||||
result = value1 == null ? 0 : -1;
|
||||
} else {
|
||||
result = value1.compareTo(value2);
|
||||
}
|
||||
// if (Debug.infoOn()) Debug.logInfo("[OrderByComparator.compareAsc] Result is " + result + " for [" + value + "] and [" + value2 + "]", module);
|
||||
return descending ? -result : result;
|
||||
}
|
||||
|
||||
public String makeOrderByString(ModelEntity modelEntity, boolean includeTablenamePrefix, Datasource datasourceInfo) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
makeOrderByString(sb, modelEntity, includeTablenamePrefix, datasourceInfo);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void makeOrderByString(StringBuilder sb, ModelEntity modelEntity, boolean includeTablenamePrefix, Datasource datasourceInfo) {
|
||||
if ((nullsFirst != null) && (!datasourceInfo.getUseOrderByNulls())) {
|
||||
sb.append("CASE WHEN ");
|
||||
getValue().addSqlValue(sb, modelEntity, null, includeTablenamePrefix, datasourceInfo);
|
||||
sb.append(" IS NULL THEN ");
|
||||
sb.append(nullsFirst ? "0" : "1");
|
||||
sb.append(" ELSE ");
|
||||
sb.append(nullsFirst ? "1" : "0");
|
||||
sb.append(" END, ");
|
||||
}
|
||||
|
||||
getValue().addSqlValue(sb, modelEntity, null, includeTablenamePrefix, datasourceInfo);
|
||||
sb.append(descending ? " DESC" : " ASC");
|
||||
|
||||
if ((nullsFirst != null) && (datasourceInfo.getUseOrderByNulls())) {
|
||||
sb.append(nullsFirst ? " NULLS FIRST" : " NULLS LAST");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(java.lang.Object obj) {
|
||||
if (!(obj instanceof OrderByItem)) return false;
|
||||
OrderByItem that = (OrderByItem) obj;
|
||||
|
||||
return getValue().equals(that.getValue()) && getDescending() == that.getDescending();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(getValue());
|
||||
sb.append(descending ? " DESC" : " ASC");
|
||||
if (nullsFirst != null) {
|
||||
sb.append(nullsFirst ? " NULLS FIRST" : " NULLS LAST");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.condition;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
import org.ofbiz.entity.GenericEntity;
|
||||
import org.ofbiz.entity.GenericModelException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
|
||||
public class OrderByList implements Comparator<GenericEntity> {
|
||||
protected List<OrderByItem> orderByList = new ArrayList<OrderByItem>();
|
||||
|
||||
public OrderByList() {
|
||||
}
|
||||
|
||||
public OrderByList(String... orderByList) {
|
||||
addOrderBy(orderByList);
|
||||
}
|
||||
|
||||
public OrderByList(Collection<String> orderByList) {
|
||||
addOrderBy(orderByList);
|
||||
}
|
||||
|
||||
public void addOrderBy(String... orderByList) {
|
||||
for (String orderByItem: orderByList) {
|
||||
addOrderBy(orderByItem);
|
||||
}
|
||||
}
|
||||
|
||||
public void addOrderBy(Collection<String> orderByList) {
|
||||
for (String orderByItem: orderByList) {
|
||||
addOrderBy(orderByItem);
|
||||
}
|
||||
}
|
||||
|
||||
public void addOrderBy(String text) {
|
||||
addOrderBy(OrderByItem.parse(text));
|
||||
}
|
||||
|
||||
public void addOrderBy(EntityConditionValue value) {
|
||||
addOrderBy(value, false);
|
||||
}
|
||||
|
||||
public void addOrderBy(EntityConditionValue value, boolean descending) {
|
||||
addOrderBy(new OrderByItem(value, descending));
|
||||
}
|
||||
|
||||
public void addOrderBy(OrderByItem orderByItem) {
|
||||
orderByList.add(orderByItem);
|
||||
}
|
||||
|
||||
public void checkOrderBy(ModelEntity modelEntity) throws GenericModelException {
|
||||
for (OrderByItem orderByItem: orderByList) {
|
||||
orderByItem.checkOrderBy(modelEntity);
|
||||
}
|
||||
}
|
||||
|
||||
public String makeOrderByString(ModelEntity modelEntity, boolean includeTablenamePrefix, Datasource datasourceInfo) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
makeOrderByString(sb, modelEntity, includeTablenamePrefix, datasourceInfo);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void makeOrderByString(StringBuilder sb, ModelEntity modelEntity, boolean includeTablenamePrefix, Datasource datasourceInfo) {
|
||||
if (!orderByList.isEmpty()) {
|
||||
sb.append(" ORDER BY ");
|
||||
}
|
||||
for (int i = 0; i < orderByList.size(); i++) {
|
||||
if (i != 0) sb.append(", ");
|
||||
OrderByItem orderByItem = orderByList.get(i);
|
||||
orderByItem.makeOrderByString(sb, modelEntity, includeTablenamePrefix, datasourceInfo);
|
||||
}
|
||||
}
|
||||
|
||||
public int compare(GenericEntity entity1, GenericEntity entity2) {
|
||||
int result = 0;
|
||||
for (OrderByItem orderByItem: orderByList) {
|
||||
result = orderByItem.compare(entity1, entity2);
|
||||
if (result != 0) break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(java.lang.Object obj) {
|
||||
if (!(obj instanceof OrderByList)) return false;
|
||||
OrderByList that = (OrderByList) obj;
|
||||
return orderByList.equals(that.orderByList);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return makeOrderByString(null, false, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><connection-factory></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class ConnectionFactory {
|
||||
|
||||
private final String className; // type = xs:string
|
||||
|
||||
ConnectionFactory(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String className = element.getAttribute("class").intern();
|
||||
if (className.isEmpty()) {
|
||||
throw new GenericEntityConfException("<connection-factory> element class attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.className = className;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>class</code> attribute. */
|
||||
public String getClassName() {
|
||||
return this.className;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><datasource></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class Datasource {
|
||||
|
||||
/*
|
||||
public static final int TYPE_JNDI_JDBC = 1;
|
||||
public static final int TYPE_INLINE_JDBC = 2;
|
||||
public static final int TYPE_TYREX_DATA_SOURCE = 3;
|
||||
public static final int TYPE_OTHER = 4;
|
||||
*/
|
||||
|
||||
private final String name; // type = xs:string
|
||||
private final String helperClass; // type = xs:string
|
||||
private final String fieldTypeName; // type = xs:string
|
||||
private final boolean useSchemas;
|
||||
private final String schemaName; // type = xs:string
|
||||
private final boolean checkOnStart;
|
||||
private final boolean addMissingOnStart;
|
||||
private final boolean usePkConstraintNames;
|
||||
private final boolean checkPksOnStart;
|
||||
private final int constraintNameClipLength; // type = xs:nonNegativeInteger
|
||||
private final boolean useProxyCursor;
|
||||
private final String proxyCursorName; // type = xs:string
|
||||
private final int resultFetchSize; // type = xs:integer
|
||||
private final boolean useForeignKeys;
|
||||
private final boolean useForeignKeyIndices;
|
||||
private final boolean checkFksOnStart;
|
||||
private final boolean checkFkIndicesOnStart;
|
||||
private final String fkStyle;
|
||||
private final boolean useFkInitiallyDeferred;
|
||||
private final boolean useIndices;
|
||||
private final boolean useIndicesUnique;
|
||||
private final boolean checkIndicesOnStart;
|
||||
private final String joinStyle;
|
||||
private final boolean aliasViewColumns;
|
||||
private final boolean alwaysUseConstraintKeyword;
|
||||
private final boolean dropFkUseForeignKeyKeyword;
|
||||
private final boolean useBinaryTypeForBlob;
|
||||
private final boolean useOrderByNulls;
|
||||
private final String offsetStyle;
|
||||
private final String tableType; // type = xs:string
|
||||
private final String characterSet; // type = xs:string
|
||||
private final String collate; // type = xs:string
|
||||
private final int maxWorkerPoolSize; // type = xs:integer
|
||||
private final List<SqlLoadPath> sqlLoadPathList; // <sql-load-path>
|
||||
private final List<ReadData> readDataList; // <read-data>
|
||||
private final InlineJdbc inlineJdbc; // <inline-jdbc>
|
||||
private final JndiJdbc jndiJdbc; // <jndi-jdbc>
|
||||
private final TyrexDataSource tyrexDataSource; // <tyrex-dataSource>
|
||||
|
||||
Datasource(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String name = element.getAttribute("name").intern();
|
||||
if (name.isEmpty()) {
|
||||
throw new GenericEntityConfException("<datasource> element name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.name = name;
|
||||
String helperClass = element.getAttribute("helper-class").intern();
|
||||
if (helperClass.isEmpty()) {
|
||||
throw new GenericEntityConfException("<datasource> element helper-class attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.helperClass = helperClass;
|
||||
String fieldTypeName = element.getAttribute("field-type-name").intern();
|
||||
if (fieldTypeName.isEmpty()) {
|
||||
throw new GenericEntityConfException("<datasource> element field-type-name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.fieldTypeName = fieldTypeName;
|
||||
this.useSchemas = !"false".equals(element.getAttribute("use-schemas"));
|
||||
this.schemaName = element.getAttribute("schema-name").intern();
|
||||
this.checkOnStart = !"false".equals(element.getAttribute("check-on-start"));
|
||||
this.addMissingOnStart = "true".equals(element.getAttribute("add-missing-on-start"));
|
||||
this.usePkConstraintNames = !"false".equals(element.getAttribute("use-pk-constraint-names"));
|
||||
this.checkPksOnStart = !"false".equals(element.getAttribute("check-pks-on-start"));
|
||||
String constraintNameClipLength = element.getAttribute("constraint-name-clip-length");
|
||||
if (constraintNameClipLength.isEmpty()) {
|
||||
this.constraintNameClipLength = 30;
|
||||
} else {
|
||||
try {
|
||||
this.constraintNameClipLength = Integer.parseInt(constraintNameClipLength);
|
||||
} catch (Exception e) {
|
||||
throw new GenericEntityConfException("<datasource> element constraint-name-clip-length attribute is invalid" + lineNumberText);
|
||||
}
|
||||
}
|
||||
this.useProxyCursor = "true".equalsIgnoreCase(element.getAttribute("use-proxy-cursor"));
|
||||
String proxyCursorName = element.getAttribute("proxy-cursor-name").intern();
|
||||
if (proxyCursorName.isEmpty()) {
|
||||
proxyCursorName = "p_cursor";
|
||||
}
|
||||
this.proxyCursorName = proxyCursorName;
|
||||
String resultFetchSize = element.getAttribute("result-fetch-size");
|
||||
if (resultFetchSize.isEmpty()) {
|
||||
this.resultFetchSize = -1;
|
||||
} else {
|
||||
try {
|
||||
this.resultFetchSize = Integer.parseInt(resultFetchSize);
|
||||
} catch (Exception e) {
|
||||
throw new GenericEntityConfException("<datasource> element result-fetch-size attribute is invalid" + lineNumberText);
|
||||
}
|
||||
}
|
||||
this.useForeignKeys = !"false".equals(element.getAttribute("use-foreign-keys"));
|
||||
this.useForeignKeyIndices = !"false".equals(element.getAttribute("use-foreign-key-indices"));
|
||||
this.checkFksOnStart = "true".equals(element.getAttribute("check-fks-on-start"));
|
||||
this.checkFkIndicesOnStart = "true".equals(element.getAttribute("check-fk-indices-on-start"));
|
||||
String fkStyle = element.getAttribute("fk-style").intern();
|
||||
if (fkStyle.isEmpty()) {
|
||||
fkStyle = "name_constraint";
|
||||
}
|
||||
this.fkStyle = fkStyle;
|
||||
this.useFkInitiallyDeferred = "true".equals(element.getAttribute("use-fk-initially-deferred"));
|
||||
this.useIndices = !"false".equals(element.getAttribute("use-indices"));
|
||||
this.useIndicesUnique = !"false".equals(element.getAttribute("use-indices-unique"));
|
||||
this.checkIndicesOnStart = "true".equals(element.getAttribute("check-indices-on-start"));
|
||||
String joinStyle = element.getAttribute("join-style").intern();
|
||||
if (joinStyle.isEmpty()) {
|
||||
joinStyle = "ansi";
|
||||
}
|
||||
this.joinStyle = joinStyle;
|
||||
this.aliasViewColumns = "true".equals(element.getAttribute("alias-view-columns"));
|
||||
this.alwaysUseConstraintKeyword = "true".equals(element.getAttribute("always-use-constraint-keyword"));
|
||||
this.dropFkUseForeignKeyKeyword = "true".equals(element.getAttribute("drop-fk-use-foreign-key-keyword"));
|
||||
this.useBinaryTypeForBlob = "true".equals(element.getAttribute("use-binary-type-for-blob"));
|
||||
this.useOrderByNulls = "true".equals(element.getAttribute("use-order-by-nulls"));
|
||||
String offsetStyle = element.getAttribute("offset-style").intern();
|
||||
if (offsetStyle.isEmpty()) {
|
||||
offsetStyle = "none";
|
||||
}
|
||||
this.offsetStyle = offsetStyle;
|
||||
this.tableType = element.getAttribute("table-type").intern();
|
||||
this.characterSet = element.getAttribute("character-set").intern();
|
||||
this.collate = element.getAttribute("collate").intern();
|
||||
String maxWorkerPoolSize = element.getAttribute("max-worker-pool-size").intern();
|
||||
if (maxWorkerPoolSize.isEmpty()) {
|
||||
this.maxWorkerPoolSize = 1;
|
||||
} else {
|
||||
try {
|
||||
int maxWorkerPoolSizeInt = Integer.parseInt(maxWorkerPoolSize);
|
||||
if (maxWorkerPoolSizeInt == 0) {
|
||||
maxWorkerPoolSizeInt = 1;
|
||||
} else if (maxWorkerPoolSizeInt < 0) {
|
||||
maxWorkerPoolSizeInt = Math.abs(maxWorkerPoolSizeInt) * Runtime.getRuntime().availableProcessors();
|
||||
}
|
||||
this.maxWorkerPoolSize = maxWorkerPoolSizeInt;
|
||||
} catch (Exception e) {
|
||||
throw new GenericEntityConfException("<datasource> element max-worker-pool-size attribute is invalid" + lineNumberText);
|
||||
}
|
||||
}
|
||||
List<? extends Element> sqlLoadPathElementList = UtilXml.childElementList(element, "sql-load-path");
|
||||
if (sqlLoadPathElementList.isEmpty()) {
|
||||
this.sqlLoadPathList = Collections.emptyList();
|
||||
} else {
|
||||
List<SqlLoadPath> sqlLoadPathList = new ArrayList<SqlLoadPath>(sqlLoadPathElementList.size());
|
||||
for (Element sqlLoadPathElement : sqlLoadPathElementList) {
|
||||
sqlLoadPathList.add(new SqlLoadPath(sqlLoadPathElement));
|
||||
}
|
||||
this.sqlLoadPathList = Collections.unmodifiableList(sqlLoadPathList);
|
||||
}
|
||||
List<? extends Element> readDataElementList = UtilXml.childElementList(element, "read-data");
|
||||
if (readDataElementList.isEmpty()) {
|
||||
this.readDataList = Collections.emptyList();
|
||||
} else {
|
||||
List<ReadData> readDataList = new ArrayList<ReadData>(readDataElementList.size());
|
||||
for (Element readDataElement : readDataElementList) {
|
||||
readDataList.add(new ReadData(readDataElement));
|
||||
}
|
||||
this.readDataList = Collections.unmodifiableList(readDataList);
|
||||
}
|
||||
int jdbcElementCount = 0;
|
||||
Element inlineJdbcElement = UtilXml.firstChildElement(element, "inline-jdbc");
|
||||
if (inlineJdbcElement == null) {
|
||||
this.inlineJdbc = null;
|
||||
} else {
|
||||
this.inlineJdbc = new InlineJdbc(inlineJdbcElement);
|
||||
jdbcElementCount++;
|
||||
}
|
||||
Element jndiJdbcElement = UtilXml.firstChildElement(element, "jndi-jdbc");
|
||||
if (jndiJdbcElement == null) {
|
||||
this.jndiJdbc = null;
|
||||
} else {
|
||||
this.jndiJdbc = new JndiJdbc(jndiJdbcElement);
|
||||
jdbcElementCount++;
|
||||
}
|
||||
Element tyrexElement = UtilXml.firstChildElement(element, "tyrex-dataSource");
|
||||
if (tyrexElement == null) {
|
||||
this.tyrexDataSource = null;
|
||||
} else {
|
||||
this.tyrexDataSource = new TyrexDataSource(tyrexElement);
|
||||
jdbcElementCount++;
|
||||
}
|
||||
if (jdbcElementCount > 1) {
|
||||
throw new GenericEntityConfException("<datasource> element is invalid: Only one of <inline-jdbc>, <jndi-jdbc>, <tyrex-dataSource> is allowed" + lineNumberText);
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>name</code> attribute. */
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>helper-class</code> attribute. */
|
||||
public String getHelperClass() {
|
||||
return this.helperClass;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>field-type-name</code> attribute. */
|
||||
public String getFieldTypeName() {
|
||||
return this.fieldTypeName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>use-schemas</code> attribute. */
|
||||
public boolean getUseSchemas() {
|
||||
return this.useSchemas;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>schema-name</code> attribute. */
|
||||
public String getSchemaName() {
|
||||
return this.schemaName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>check-on-start</code> attribute. */
|
||||
public boolean getCheckOnStart() {
|
||||
return this.checkOnStart;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>add-missing-on-start</code> attribute. */
|
||||
public boolean getAddMissingOnStart() {
|
||||
return this.addMissingOnStart;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>use-pk-constraint-names</code> attribute. */
|
||||
public boolean getUsePkConstraintNames() {
|
||||
return this.usePkConstraintNames;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>check-pks-on-start</code> attribute. */
|
||||
public boolean getCheckPksOnStart() {
|
||||
return this.checkPksOnStart;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>constraint-name-clip-length</code> attribute. */
|
||||
public int getConstraintNameClipLength() {
|
||||
return this.constraintNameClipLength;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>use-proxy-cursor</code> attribute. */
|
||||
public boolean getUseProxyCursor() {
|
||||
return this.useProxyCursor;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>proxy-cursor-name</code> attribute. */
|
||||
public String getProxyCursorName() {
|
||||
return this.proxyCursorName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>result-fetch-size</code> attribute. */
|
||||
public int getResultFetchSize() {
|
||||
return this.resultFetchSize;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>use-foreign-keys</code> attribute. */
|
||||
public boolean getUseForeignKeys() {
|
||||
return this.useForeignKeys;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>use-foreign-key-indices</code> attribute. */
|
||||
public boolean getUseForeignKeyIndices() {
|
||||
return this.useForeignKeyIndices;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>check-fks-on-start</code> attribute. */
|
||||
public boolean getCheckFksOnStart() {
|
||||
return this.checkFksOnStart;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>check-fk-indices-on-start</code> attribute. */
|
||||
public boolean getCheckFkIndicesOnStart() {
|
||||
return this.checkFkIndicesOnStart;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>fk-style</code> attribute. */
|
||||
public String getFkStyle() {
|
||||
return this.fkStyle;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>use-fk-initially-deferred</code> attribute. */
|
||||
public boolean getUseFkInitiallyDeferred() {
|
||||
return this.useFkInitiallyDeferred;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>use-indices</code> attribute. */
|
||||
public boolean getUseIndices() {
|
||||
return this.useIndices;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>use-indices-unique</code> attribute. */
|
||||
public boolean getUseIndicesUnique() {
|
||||
return this.useIndicesUnique;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>check-indices-on-start</code> attribute. */
|
||||
public boolean getCheckIndicesOnStart() {
|
||||
return this.checkIndicesOnStart;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>join-style</code> attribute. */
|
||||
public String getJoinStyle() {
|
||||
return this.joinStyle;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>alias-view-columns</code> attribute. */
|
||||
public boolean getAliasViewColumns() {
|
||||
return this.aliasViewColumns;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>always-use-constraint-keyword</code> attribute. */
|
||||
public boolean getAlwaysUseConstraintKeyword() {
|
||||
return this.alwaysUseConstraintKeyword;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>drop-fk-use-foreign-key-keyword</code> attribute. */
|
||||
public boolean getDropFkUseForeignKeyKeyword() {
|
||||
return this.dropFkUseForeignKeyKeyword;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>use-binary-type-for-blob</code> attribute. */
|
||||
public boolean getUseBinaryTypeForBlob() {
|
||||
return this.useBinaryTypeForBlob;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>use-order-by-nulls</code> attribute. */
|
||||
public boolean getUseOrderByNulls() {
|
||||
return this.useOrderByNulls;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>offset-style</code> attribute. */
|
||||
public String getOffsetStyle() {
|
||||
return this.offsetStyle;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>table-type</code> attribute. */
|
||||
public String getTableType() {
|
||||
return this.tableType;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>character-set</code> attribute. */
|
||||
public String getCharacterSet() {
|
||||
return this.characterSet;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>collate</code> attribute. */
|
||||
public String getCollate() {
|
||||
return this.collate;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>max-worker-pool-size</code> attribute. */
|
||||
public int getMaxWorkerPoolSize() {
|
||||
return this.maxWorkerPoolSize;
|
||||
}
|
||||
|
||||
/** Returns the <code><sql-load-path></code> child elements. */
|
||||
public List<SqlLoadPath> getSqlLoadPathList() {
|
||||
return this.sqlLoadPathList;
|
||||
}
|
||||
|
||||
/** Returns the <code><read-data></code> child elements. */
|
||||
public List<ReadData> getReadDataList() {
|
||||
return this.readDataList;
|
||||
}
|
||||
|
||||
/** Returns the <code><inline-jdbc></code> child element. */
|
||||
public InlineJdbc getInlineJdbc() {
|
||||
return this.inlineJdbc;
|
||||
}
|
||||
|
||||
/** Returns the <code><jndi-jdbc></code> child element. */
|
||||
public JndiJdbc getJndiJdbc() {
|
||||
return this.jndiJdbc;
|
||||
}
|
||||
|
||||
/** Returns the <code><tyrex-dataSource></code> child element. */
|
||||
public TyrexDataSource getTyrexDataSource() {
|
||||
return this.tyrexDataSource;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><debug-xa-resources></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class DebugXaResources {
|
||||
|
||||
private final boolean value; // type = xs:string
|
||||
|
||||
DebugXaResources(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String value = element.getAttribute("value").intern();
|
||||
if (value.isEmpty()) {
|
||||
throw new GenericEntityConfException("<debug-xa-resources> element value attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.value = "true".equals(value);
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>value</code> attribute. */
|
||||
public boolean getValue() {
|
||||
return this.value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><delegator></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class DelegatorElement {
|
||||
|
||||
private final String name; // type = xs:string
|
||||
private final String entityModelReader; // type = xs:string
|
||||
private final String entityGroupReader; // type = xs:string
|
||||
private final String entityEcaReader; // type = xs:string
|
||||
private final boolean entityEcaEnabled;
|
||||
private final String entityEcaHandlerClassName; // type = xs:string
|
||||
private final boolean distributedCacheClearEnabled;
|
||||
private final String distributedCacheClearClassName; // type = xs:string
|
||||
private final String distributedCacheClearUserLoginId; // type = xs:string
|
||||
private final String sequencedIdPrefix; // type = xs:string
|
||||
private final String defaultGroupName; // type = xs:string
|
||||
private final String keyEncryptingKey; // type = xs:string
|
||||
private final List<GroupMap> groupMapList; // <group-map>
|
||||
private final Map<String, String> groupMapMap; // <group-map>
|
||||
|
||||
DelegatorElement(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String name = element.getAttribute("name").intern();
|
||||
if (name.isEmpty()) {
|
||||
throw new GenericEntityConfException("<delegator> element name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.name = name;
|
||||
String entityModelReader = element.getAttribute("entity-model-reader").intern();
|
||||
if (entityModelReader.isEmpty()) {
|
||||
throw new GenericEntityConfException("<delegator> element entity-model-reader attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.entityModelReader = entityModelReader;
|
||||
String entityGroupReader = element.getAttribute("entity-group-reader").intern();
|
||||
if (entityGroupReader.isEmpty()) {
|
||||
throw new GenericEntityConfException("<delegator> element entity-group-reader attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.entityGroupReader = entityGroupReader;
|
||||
this.entityEcaReader = element.getAttribute("entity-eca-reader").intern();
|
||||
this.entityEcaEnabled = !"false".equalsIgnoreCase(element.getAttribute("entity-eca-enabled"));
|
||||
String entityEcaHandlerClassName = element.getAttribute("entity-eca-handler-class-name").intern();
|
||||
if (entityEcaHandlerClassName.isEmpty()) {
|
||||
entityEcaHandlerClassName = "org.ofbiz.entityext.eca.DelegatorEcaHandler";
|
||||
}
|
||||
this.entityEcaHandlerClassName = entityEcaHandlerClassName;
|
||||
this.distributedCacheClearEnabled = "true".equalsIgnoreCase(element.getAttribute("distributed-cache-clear-enabled"));
|
||||
String distributedCacheClearClassName = element.getAttribute("distributed-cache-clear-class-name").intern();
|
||||
if (distributedCacheClearClassName.isEmpty()) {
|
||||
distributedCacheClearClassName = "org.ofbiz.entityext.cache.EntityCacheServices";
|
||||
}
|
||||
this.distributedCacheClearClassName = distributedCacheClearClassName;
|
||||
String distributedCacheClearUserLoginId = element.getAttribute("distributed-cache-clear-user-login-id").intern();
|
||||
if (distributedCacheClearUserLoginId.isEmpty()) {
|
||||
distributedCacheClearUserLoginId = "system";
|
||||
}
|
||||
this.distributedCacheClearUserLoginId = distributedCacheClearUserLoginId;
|
||||
this.sequencedIdPrefix = element.getAttribute("sequenced-id-prefix").intern();
|
||||
String defaultGroupName = element.getAttribute("default-group-name").intern();
|
||||
if (defaultGroupName.isEmpty()) {
|
||||
defaultGroupName = "org.ofbiz";
|
||||
}
|
||||
this.defaultGroupName = defaultGroupName;
|
||||
this.keyEncryptingKey = element.getAttribute("key-encrypting-key").intern();
|
||||
List<? extends Element> groupMapElementList = UtilXml.childElementList(element, "group-map");
|
||||
if (groupMapElementList.isEmpty()) {
|
||||
throw new GenericEntityConfException("<delegator> element child elements <group-map> are missing" + lineNumberText);
|
||||
} else {
|
||||
List<GroupMap> groupMapList = new ArrayList<GroupMap>(groupMapElementList.size());
|
||||
Map<String, String> groupMapMap = new HashMap<String, String>();
|
||||
for (Element groupMapElement : groupMapElementList) {
|
||||
GroupMap groupMap = new GroupMap(groupMapElement);
|
||||
groupMapList.add(groupMap);
|
||||
groupMapMap.put(groupMap.getGroupName(), groupMap.getDatasourceName());
|
||||
}
|
||||
this.groupMapList = Collections.unmodifiableList(groupMapList);
|
||||
this.groupMapMap = Collections.unmodifiableMap(groupMapMap);
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>name</code> attribute. */
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>entity-model-reader</code> attribute. */
|
||||
public String getEntityModelReader() {
|
||||
return this.entityModelReader;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>entity-group-reader</code> attribute. */
|
||||
public String getEntityGroupReader() {
|
||||
return this.entityGroupReader;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>entity-eca-reader</code> attribute. */
|
||||
public String getEntityEcaReader() {
|
||||
return this.entityEcaReader;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>entity-eca-enabled</code> attribute. */
|
||||
public boolean getEntityEcaEnabled() {
|
||||
return this.entityEcaEnabled;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>entity-eca-handler-class-name</code> attribute. */
|
||||
public String getEntityEcaHandlerClassName() {
|
||||
return this.entityEcaHandlerClassName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>distributed-cache-clear-enabled</code> attribute. */
|
||||
public boolean getDistributedCacheClearEnabled() {
|
||||
return this.distributedCacheClearEnabled;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>distributed-cache-clear-class-name</code> attribute. */
|
||||
public String getDistributedCacheClearClassName() {
|
||||
return this.distributedCacheClearClassName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>distributed-cache-clear-user-login-id</code> attribute. */
|
||||
public String getDistributedCacheClearUserLoginId() {
|
||||
return this.distributedCacheClearUserLoginId;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>sequenced-id-prefix</code> attribute. */
|
||||
public String getSequencedIdPrefix() {
|
||||
return this.sequencedIdPrefix;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>default-group-name</code> attribute. */
|
||||
public String getDefaultGroupName() {
|
||||
return this.defaultGroupName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>key-encrypting-key</code> attribute. */
|
||||
public String getKeyEncryptingKey() {
|
||||
return this.keyEncryptingKey;
|
||||
}
|
||||
|
||||
/** Returns the <code><group-map></code> child elements. */
|
||||
public List<GroupMap> getGroupMapList() {
|
||||
return this.groupMapList;
|
||||
}
|
||||
|
||||
/** Returns the specified <code><group-map> datasource-name</code> attribute value,
|
||||
* or <code>null</code> if the <code><group-map></code> element does not exist . */
|
||||
public String getGroupDataSource(String groupName) {
|
||||
return this.groupMapMap.get(groupName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilProperties;
|
||||
import org.ofbiz.base.util.UtilURL;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* A singleton class that models the <code><entity-config></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class EntityConfig {
|
||||
public static final String ENTITY_ENGINE_XML_FILENAME = "entityengine.xml";
|
||||
|
||||
private static final String module = EntityConfig.class.getName();
|
||||
|
||||
private static final EntityConfig instance = createNewInstance();
|
||||
private final List<ResourceLoader> resourceLoaderList; // <resource-loader>
|
||||
private final Map<String, ResourceLoader> resourceLoaderMap; // <resource-loader>
|
||||
private final TransactionFactory transactionFactory; // <transaction-factory>
|
||||
private final ConnectionFactory connectionFactory; // <connection-factory>
|
||||
private final DebugXaResources debugXaResources; // <debug-xa-resources>
|
||||
private final List<DelegatorElement> delegatorList; // <delegator>
|
||||
private final Map<String, DelegatorElement> delegatorMap; // <delegator>
|
||||
private final List<EntityModelReader> entityModelReaderList; // <entity-model-reader>
|
||||
private final Map<String, EntityModelReader> entityModelReaderMap; // <entity-model-reader>
|
||||
private final List<EntityGroupReader> entityGroupReaderList; // <entity-group-reader>
|
||||
private final Map<String, EntityGroupReader> entityGroupReaderMap; // <entity-group-reader>
|
||||
private final List<EntityEcaReader> entityEcaReaderList; // <entity-eca-reader>
|
||||
private final Map<String, EntityEcaReader> entityEcaReaderMap; // <entity-eca-reader>
|
||||
private final List<EntityDataReader> entityDataReaderList; // <entity-data-reader>
|
||||
private final Map<String, EntityDataReader> entityDataReaderMap; // <entity-data-reader>
|
||||
private final List<FieldType> fieldTypeList; // <field-type>
|
||||
private final Map<String, FieldType> fieldTypeMap; // <field-type>
|
||||
private final List<Datasource> datasourceList; // <datasource>
|
||||
private final Map<String, Datasource> datasourceMap;
|
||||
|
||||
private EntityConfig() throws GenericEntityConfException {
|
||||
Element element;
|
||||
URL confUrl = UtilURL.fromResource(ENTITY_ENGINE_XML_FILENAME);
|
||||
if (confUrl == null) {
|
||||
throw new GenericEntityConfException("Could not find the " + ENTITY_ENGINE_XML_FILENAME + " file");
|
||||
}
|
||||
try {
|
||||
element = UtilXml.readXmlDocument(confUrl, true, true).getDocumentElement();
|
||||
} catch (Exception e) {
|
||||
throw new GenericEntityConfException("Exception thrown while reading " + ENTITY_ENGINE_XML_FILENAME + ": ", e);
|
||||
}
|
||||
|
||||
List<? extends Element> resourceLoaderElementList = UtilXml.childElementList(element, "resource-loader");
|
||||
if (resourceLoaderElementList.isEmpty()) {
|
||||
throw new GenericEntityConfException("<entity-config> element child elements <resource-loader> are missing");
|
||||
} else {
|
||||
List<ResourceLoader> resourceLoaderList = new ArrayList<ResourceLoader>(resourceLoaderElementList.size());
|
||||
Map<String, ResourceLoader> resourceLoaderMap = new HashMap<String, ResourceLoader>();
|
||||
for (Element resourceLoaderElement : resourceLoaderElementList) {
|
||||
ResourceLoader resourceLoader = new ResourceLoader(resourceLoaderElement);
|
||||
resourceLoaderList.add(resourceLoader);
|
||||
resourceLoaderMap.put(resourceLoader.getName(), resourceLoader);
|
||||
}
|
||||
this.resourceLoaderList = Collections.unmodifiableList(resourceLoaderList);
|
||||
this.resourceLoaderMap = Collections.unmodifiableMap(resourceLoaderMap);
|
||||
}
|
||||
Element transactionFactoryElement = UtilXml.firstChildElement(element, "transaction-factory");
|
||||
if (transactionFactoryElement == null) {
|
||||
throw new GenericEntityConfException("<entity-config> element child element <transaction-factory> is missing");
|
||||
} else {
|
||||
this.transactionFactory = new TransactionFactory(transactionFactoryElement);
|
||||
}
|
||||
Element connectionFactoryElement = UtilXml.firstChildElement(element, "connection-factory");
|
||||
if (connectionFactoryElement != null) {
|
||||
this.connectionFactory = new ConnectionFactory(connectionFactoryElement);
|
||||
} else {
|
||||
this.connectionFactory = null;
|
||||
}
|
||||
Element debugXaResourcesElement = UtilXml.firstChildElement(element, "debug-xa-resources");
|
||||
if (debugXaResourcesElement == null) {
|
||||
throw new GenericEntityConfException("<entity-config> element child element <debug-xa-resources> is missing");
|
||||
} else {
|
||||
this.debugXaResources = new DebugXaResources(debugXaResourcesElement);
|
||||
}
|
||||
List<? extends Element> delegatorElementList = UtilXml.childElementList(element, "delegator");
|
||||
if (delegatorElementList.isEmpty()) {
|
||||
throw new GenericEntityConfException("<entity-config> element child elements <delegator> are missing");
|
||||
} else {
|
||||
List<DelegatorElement> delegatorList = new ArrayList<DelegatorElement>(delegatorElementList.size());
|
||||
Map<String, DelegatorElement> delegatorMap = new HashMap<String, DelegatorElement>();
|
||||
for (Element delegatorElement : delegatorElementList) {
|
||||
DelegatorElement delegator = new DelegatorElement(delegatorElement);
|
||||
delegatorList.add(delegator);
|
||||
delegatorMap.put(delegator.getName(), delegator);
|
||||
}
|
||||
this.delegatorList = Collections.unmodifiableList(delegatorList);
|
||||
this.delegatorMap = Collections.unmodifiableMap(delegatorMap);
|
||||
}
|
||||
List<? extends Element> entityModelReaderElementList = UtilXml.childElementList(element, "entity-model-reader");
|
||||
if (entityModelReaderElementList.isEmpty()) {
|
||||
throw new GenericEntityConfException("<entity-config> element child elements <entity-model-reader> are missing");
|
||||
} else {
|
||||
List<EntityModelReader> entityModelReaderList = new ArrayList<EntityModelReader>(entityModelReaderElementList.size());
|
||||
Map<String, EntityModelReader> entityModelReaderMap = new HashMap<String, EntityModelReader>();
|
||||
for (Element entityModelReaderElement : entityModelReaderElementList) {
|
||||
EntityModelReader entityModelReader = new EntityModelReader(entityModelReaderElement);
|
||||
entityModelReaderList.add(entityModelReader);
|
||||
entityModelReaderMap.put(entityModelReader.getName(), entityModelReader);
|
||||
}
|
||||
this.entityModelReaderList = Collections.unmodifiableList(entityModelReaderList);
|
||||
this.entityModelReaderMap = Collections.unmodifiableMap(entityModelReaderMap);
|
||||
}
|
||||
List<? extends Element> entityGroupReaderElementList = UtilXml.childElementList(element, "entity-group-reader");
|
||||
if (entityGroupReaderElementList.isEmpty()) {
|
||||
throw new GenericEntityConfException("<entity-config> element child elements <entity-group-reader> are missing");
|
||||
} else {
|
||||
List<EntityGroupReader> entityGroupReaderList = new ArrayList<EntityGroupReader>(entityGroupReaderElementList.size());
|
||||
Map<String, EntityGroupReader> entityGroupReaderMap = new HashMap<String, EntityGroupReader>();
|
||||
for (Element entityGroupReaderElement : entityGroupReaderElementList) {
|
||||
EntityGroupReader entityGroupReader = new EntityGroupReader(entityGroupReaderElement);
|
||||
entityGroupReaderList.add(entityGroupReader);
|
||||
entityGroupReaderMap.put(entityGroupReader.getName(), entityGroupReader);
|
||||
}
|
||||
this.entityGroupReaderList = Collections.unmodifiableList(entityGroupReaderList);
|
||||
this.entityGroupReaderMap = Collections.unmodifiableMap(entityGroupReaderMap);
|
||||
}
|
||||
List<? extends Element> entityEcaReaderElementList = UtilXml.childElementList(element, "entity-eca-reader");
|
||||
if (entityEcaReaderElementList.isEmpty()) {
|
||||
this.entityEcaReaderList = Collections.emptyList();
|
||||
this.entityEcaReaderMap = Collections.emptyMap();
|
||||
} else {
|
||||
List<EntityEcaReader> entityEcaReaderList = new ArrayList<EntityEcaReader>(entityEcaReaderElementList.size());
|
||||
Map<String, EntityEcaReader> entityEcaReaderMap = new HashMap<String, EntityEcaReader>();
|
||||
for (Element entityEcaReaderElement : entityEcaReaderElementList) {
|
||||
EntityEcaReader entityEcaReader = new EntityEcaReader(entityEcaReaderElement);
|
||||
entityEcaReaderList.add(new EntityEcaReader(entityEcaReaderElement));
|
||||
entityEcaReaderMap.put(entityEcaReader.getName(), entityEcaReader);
|
||||
}
|
||||
this.entityEcaReaderList = Collections.unmodifiableList(entityEcaReaderList);
|
||||
this.entityEcaReaderMap = Collections.unmodifiableMap(entityEcaReaderMap);
|
||||
}
|
||||
List<? extends Element> entityDataReaderElementList = UtilXml.childElementList(element, "entity-data-reader");
|
||||
if (entityDataReaderElementList.isEmpty()) {
|
||||
this.entityDataReaderList = Collections.emptyList();
|
||||
this.entityDataReaderMap = Collections.emptyMap();
|
||||
} else {
|
||||
List<EntityDataReader> entityDataReaderList = new ArrayList<EntityDataReader>(entityDataReaderElementList.size());
|
||||
Map<String, EntityDataReader> entityDataReaderMap = new HashMap<String, EntityDataReader>();
|
||||
for (Element entityDataReaderElement : entityDataReaderElementList) {
|
||||
EntityDataReader entityDataReader = new EntityDataReader(entityDataReaderElement);
|
||||
entityDataReaderList.add(entityDataReader);
|
||||
entityDataReaderMap.put(entityDataReader.getName(), entityDataReader);
|
||||
}
|
||||
this.entityDataReaderList = Collections.unmodifiableList(entityDataReaderList);
|
||||
this.entityDataReaderMap = Collections.unmodifiableMap(entityDataReaderMap);
|
||||
}
|
||||
List<? extends Element> fieldTypeElementList = UtilXml.childElementList(element, "field-type");
|
||||
if (fieldTypeElementList.isEmpty()) {
|
||||
throw new GenericEntityConfException("<entity-config> element child elements <field-type> are missing");
|
||||
} else {
|
||||
List<FieldType> fieldTypeList = new ArrayList<FieldType>(fieldTypeElementList.size());
|
||||
Map<String, FieldType> fieldTypeMap = new HashMap<String, FieldType>();
|
||||
for (Element fieldTypeElement : fieldTypeElementList) {
|
||||
FieldType fieldType = new FieldType(fieldTypeElement);
|
||||
fieldTypeList.add(fieldType);
|
||||
fieldTypeMap.put(fieldType.getName(), fieldType);
|
||||
}
|
||||
this.fieldTypeList = Collections.unmodifiableList(fieldTypeList);
|
||||
this.fieldTypeMap = Collections.unmodifiableMap(fieldTypeMap);
|
||||
}
|
||||
List<? extends Element> datasourceElementList = UtilXml.childElementList(element, "datasource");
|
||||
if (datasourceElementList.isEmpty()) {
|
||||
throw new GenericEntityConfException("<entity-config> element child elements <datasource> are missing");
|
||||
} else {
|
||||
List<Datasource> datasourceList = new ArrayList<Datasource>(datasourceElementList.size());
|
||||
Map<String, Datasource> datasourceMap = new HashMap<String, Datasource>();
|
||||
for (Element datasourceElement : datasourceElementList) {
|
||||
Datasource datasource = new Datasource(datasourceElement);
|
||||
datasourceList.add(datasource);
|
||||
datasourceMap.put(datasource.getName(), datasource);
|
||||
}
|
||||
this.datasourceList = Collections.unmodifiableList(datasourceList);
|
||||
this.datasourceMap = Collections.unmodifiableMap(datasourceMap);
|
||||
}
|
||||
}
|
||||
|
||||
private static EntityConfig createNewInstance() {
|
||||
EntityConfig entityConfig = null;
|
||||
try {
|
||||
entityConfig = new EntityConfig();
|
||||
} catch (GenericEntityConfException gece) {
|
||||
Debug.logError(gece, module);
|
||||
}
|
||||
return entityConfig;
|
||||
}
|
||||
|
||||
public static EntityConfig getInstance() throws GenericEntityConfException {
|
||||
if (instance == null) {
|
||||
throw new GenericEntityConfException("EntityConfig is not initialized.");
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static String createConfigFileLineNumberText(Element element) {
|
||||
if (element.getUserData("startLine") != null) {
|
||||
return " [" + ENTITY_ENGINE_XML_FILENAME + " line " + element.getUserData("startLine") + "]";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/** Returns the specified <code><resource-loader></code> child element, or <code>null</code> if no child element was found. */
|
||||
public ResourceLoader getResourceLoader(String name) {
|
||||
return this.resourceLoaderMap.get(name);
|
||||
}
|
||||
|
||||
/** Returns the <code><resource-loader></code> child elements. */
|
||||
public List<ResourceLoader> getResourceLoaderList() {
|
||||
return this.resourceLoaderList;
|
||||
}
|
||||
|
||||
/** Returns the <code><transaction-factory></code> child element, or <code>null</code> if no child element was found. */
|
||||
public TransactionFactory getTransactionFactory() {
|
||||
return this.transactionFactory;
|
||||
}
|
||||
|
||||
/** Returns the <code><connection-factory></code> child element, or <code>null</code> if no child element was found. */
|
||||
public ConnectionFactory getConnectionFactory() {
|
||||
return this.connectionFactory;
|
||||
}
|
||||
|
||||
/** Returns the <code><debug-xa-resources></code> child element, or <code>null</code> if no child element was found. */
|
||||
public DebugXaResources getDebugXaResources() {
|
||||
return this.debugXaResources;
|
||||
}
|
||||
|
||||
/** Returns the specified <code><delegator></code> child element, or <code>null</code> if no child element was found. */
|
||||
public DelegatorElement getDelegator(String name) {
|
||||
return this.delegatorMap.get(name);
|
||||
}
|
||||
|
||||
/** Returns the <code><delegator></code> child elements. */
|
||||
public List<DelegatorElement> getDelegatorList() {
|
||||
return this.delegatorList;
|
||||
}
|
||||
|
||||
/** Returns the specified <code><entity-model-reader></code> child element, or <code>null</code> if no child element was found. */
|
||||
public EntityModelReader getEntityModelReader(String name) {
|
||||
return this.entityModelReaderMap.get(name);
|
||||
}
|
||||
|
||||
/** Returns the <code><entity-model-reader></code> child elements. */
|
||||
public List<EntityModelReader> getEntityModelReaderList() {
|
||||
return this.entityModelReaderList;
|
||||
}
|
||||
|
||||
/** Returns the specified <code><entity-group-reader></code> child element, or <code>null</code> if no child element was found. */
|
||||
public EntityGroupReader getEntityGroupReader(String name) {
|
||||
return this.entityGroupReaderMap.get(name);
|
||||
}
|
||||
|
||||
/** Returns the <code><entity-group-reader></code> child elements. */
|
||||
public List<EntityGroupReader> getEntityGroupReaderList() {
|
||||
return this.entityGroupReaderList;
|
||||
}
|
||||
|
||||
/** Returns the specified <code><entity-eca-reader></code> child element, or <code>null</code> if no child element was found. */
|
||||
public EntityEcaReader getEntityEcaReader(String name) {
|
||||
return this.entityEcaReaderMap.get(name);
|
||||
}
|
||||
|
||||
/** Returns the <code><entity-eca-reader></code> child elements. */
|
||||
public List<EntityEcaReader> getEntityEcaReaderList() {
|
||||
return this.entityEcaReaderList;
|
||||
}
|
||||
|
||||
/** Returns the specified <code><entity-data-reader></code> child element, or <code>null</code> if no child element was found. */
|
||||
public EntityDataReader getEntityDataReader(String name) {
|
||||
return this.entityDataReaderMap.get(name);
|
||||
}
|
||||
|
||||
/** Returns the <code><entity-data-reader></code> child elements. */
|
||||
public List<EntityDataReader> getEntityDataReaderList() {
|
||||
return this.entityDataReaderList;
|
||||
}
|
||||
|
||||
/** Returns the specified <code><field-type></code> child element, or <code>null</code> if no child element was found. */
|
||||
public FieldType getFieldType(String name) {
|
||||
return this.fieldTypeMap.get(name);
|
||||
}
|
||||
|
||||
/** Returns the <code><field-type></code> child elements. */
|
||||
public List<FieldType> getFieldTypeList() {
|
||||
return this.fieldTypeList;
|
||||
}
|
||||
|
||||
/** Returns the <code><datasource></code> child elements. */
|
||||
public List<Datasource> getDatasourceList() {
|
||||
return this.datasourceList;
|
||||
}
|
||||
|
||||
/** Returns the specified <code><datasource></code> child element or <code>null</code> if it does not exist. */
|
||||
/*
|
||||
public Datasource getDatasource(String name) {
|
||||
return this.datasourceMap.get(name);
|
||||
}
|
||||
*/
|
||||
public static Datasource getDatasource(String name) {
|
||||
try {
|
||||
return getInstance().datasourceMap.get(name);
|
||||
} catch (GenericEntityConfException e) {
|
||||
// FIXME: Doing this so we don't have to rewrite the entire API.
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the configured JDBC password.
|
||||
*
|
||||
* @param inlineJdbcElement
|
||||
* @return The configured JDBC password.
|
||||
* @throws GenericEntityConfException If the password was not found.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
public static String getJdbcPassword(InlineJdbc inlineJdbcElement) throws GenericEntityConfException {
|
||||
String jdbcPassword = inlineJdbcElement.getJdbcPassword();
|
||||
if (!jdbcPassword.isEmpty()) {
|
||||
return jdbcPassword;
|
||||
}
|
||||
String jdbcPasswordLookup = inlineJdbcElement.getJdbcPasswordLookup();
|
||||
if (jdbcPasswordLookup.isEmpty()) {
|
||||
throw new GenericEntityConfException("No jdbc-password or jdbc-password-lookup specified for inline-jdbc element, line: " + inlineJdbcElement.getLineNumber());
|
||||
}
|
||||
String key = "jdbc-password.".concat(jdbcPasswordLookup);
|
||||
jdbcPassword = UtilProperties.getPropertyValue("passwords", key);
|
||||
if (jdbcPassword.isEmpty()) {
|
||||
throw new GenericEntityConfException("'" + key + "' property not found in passwords.properties file for inline-jdbc element, line: " + inlineJdbcElement.getLineNumber());
|
||||
}
|
||||
return jdbcPassword;
|
||||
}
|
||||
|
||||
/** Returns the <code><datasource></code> child elements as a <code>Map</code>. */
|
||||
public Map<String, Datasource> getDatasourceMap() {
|
||||
return this.datasourceMap;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><entity-data-reader></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class EntityDataReader {
|
||||
|
||||
private final String name; // type = xs:string
|
||||
private final List<Resource> resourceList; // <resource>
|
||||
|
||||
public EntityDataReader(String name) throws GenericEntityConfException {
|
||||
if (name == null || name.isEmpty()) {
|
||||
throw new GenericEntityConfException("EntityDataReader name cannot be empty");
|
||||
}
|
||||
this.name = name;
|
||||
this.resourceList = Collections.emptyList();
|
||||
}
|
||||
|
||||
EntityDataReader(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String name = element.getAttribute("name").intern();
|
||||
if (name.isEmpty()) {
|
||||
throw new GenericEntityConfException("<entity-data-reader> element name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.name = name;
|
||||
List<? extends Element> resourceElementList = UtilXml.childElementList(element, "resource");
|
||||
if (resourceElementList.isEmpty()) {
|
||||
this.resourceList = Collections.emptyList();
|
||||
} else {
|
||||
List<Resource> resourceList = new ArrayList<Resource>(resourceElementList.size());
|
||||
for (Element resourceElement : resourceElementList) {
|
||||
resourceList.add(new Resource(resourceElement));
|
||||
}
|
||||
this.resourceList = Collections.unmodifiableList(resourceList);
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>name</code> attribute. */
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
/** Returns the <code><resource></code> child elements. */
|
||||
public List<Resource> getResourceList() {
|
||||
return this.resourceList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><entity-eca-reader></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class EntityEcaReader {
|
||||
|
||||
private final String name; // type = xs:string
|
||||
private final List<Resource> resourceList; // <resource>
|
||||
|
||||
EntityEcaReader(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String name = element.getAttribute("name").intern();
|
||||
if (name.isEmpty()) {
|
||||
throw new GenericEntityConfException("<entity-eca-reader> element name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.name = name;
|
||||
List<? extends Element> resourceElementList = UtilXml.childElementList(element, "resource");
|
||||
if (resourceElementList.isEmpty()) {
|
||||
this.resourceList = Collections.emptyList();
|
||||
} else {
|
||||
List<Resource> resourceList = new ArrayList<Resource>(resourceElementList.size());
|
||||
for (Element resourceElement : resourceElementList) {
|
||||
resourceList.add(new Resource(resourceElement));
|
||||
}
|
||||
this.resourceList = Collections.unmodifiableList(resourceList);
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>name</code> attribute. */
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
/** Returns the <code><resource></code> child elements. */
|
||||
public List<Resource> getResourceList() {
|
||||
return this.resourceList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><entity-group-reader></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class EntityGroupReader {
|
||||
|
||||
private final String name; // type = xs:string
|
||||
private final String loader; // type = xs:string
|
||||
private final String location; // type = xs:string
|
||||
private final List<Resource> resourceList; // <resource>
|
||||
|
||||
EntityGroupReader(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String name = element.getAttribute("name").intern();
|
||||
if (name.isEmpty()) {
|
||||
throw new GenericEntityConfException("<entity-group-reader> element name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.name = name;
|
||||
this.loader = element.getAttribute("loader").intern();
|
||||
this.location = element.getAttribute("location").intern();
|
||||
List<? extends Element> resourceElementList = UtilXml.childElementList(element, "resource");
|
||||
if (resourceElementList.isEmpty()) {
|
||||
this.resourceList = Collections.emptyList();
|
||||
} else {
|
||||
List<Resource> resourceList = new ArrayList<Resource>(resourceElementList.size());
|
||||
for (Element resourceElement : resourceElementList) {
|
||||
resourceList.add(new Resource(resourceElement));
|
||||
}
|
||||
this.resourceList = Collections.unmodifiableList(resourceList);
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>name</code> attribute. */
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>loader</code> attribute. */
|
||||
public String getLoader() {
|
||||
return this.loader;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>location</code> attribute. */
|
||||
public String getLocation() {
|
||||
return this.location;
|
||||
}
|
||||
|
||||
/** Returns the <code><resource></code> child elements. */
|
||||
public List<Resource> getResourceList() {
|
||||
return this.resourceList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><entity-model-reader></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class EntityModelReader {
|
||||
|
||||
private final String name; // type = xs:string
|
||||
private final List<Resource> resourceList; // <resource>
|
||||
|
||||
EntityModelReader(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String name = element.getAttribute("name").intern();
|
||||
if (name.isEmpty()) {
|
||||
throw new GenericEntityConfException("<entity-model-reader> element name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.name = name;
|
||||
List<? extends Element> resourceElementList = UtilXml.childElementList(element, "resource");
|
||||
if (resourceElementList.isEmpty()) {
|
||||
this.resourceList = Collections.emptyList();
|
||||
} else {
|
||||
List<Resource> resourceList = new ArrayList<Resource>(resourceElementList.size());
|
||||
for (Element resourceElement : resourceElementList) {
|
||||
resourceList.add(new Resource(resourceElement));
|
||||
}
|
||||
this.resourceList = Collections.unmodifiableList(resourceList);
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>name</code> attribute. */
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
/** Returns the <code><resource></code> child elements. */
|
||||
public List<Resource> getResourceList() {
|
||||
return this.resourceList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><field-type></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class FieldType {
|
||||
|
||||
private final String name; // type = xs:string
|
||||
private final String loader; // type = xs:string
|
||||
private final String location; // type = xs:string
|
||||
|
||||
FieldType(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String name = element.getAttribute("name").intern();
|
||||
if (name.isEmpty()) {
|
||||
throw new GenericEntityConfException("<field-type> element name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.name = name;
|
||||
String loader = element.getAttribute("loader").intern();
|
||||
if (loader.isEmpty()) {
|
||||
throw new GenericEntityConfException("<field-type> element loader attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.loader = loader;
|
||||
String location = element.getAttribute("location").intern();
|
||||
if (location.isEmpty()) {
|
||||
throw new GenericEntityConfException("<field-type> element location attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.location = location;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>name</code> attribute. */
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>loader</code> attribute. */
|
||||
public String getLoader() {
|
||||
return this.loader;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>location</code> attribute. */
|
||||
public String getLocation() {
|
||||
return this.location;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><group-map></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class GroupMap {
|
||||
|
||||
private final String groupName; // type = xs:string
|
||||
private final String datasourceName; // type = xs:string
|
||||
|
||||
GroupMap(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String groupName = element.getAttribute("group-name").intern();
|
||||
if (groupName.isEmpty()) {
|
||||
throw new GenericEntityConfException("<group-map> element group-name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.groupName = groupName;
|
||||
String datasourceName = element.getAttribute("datasource-name").intern();
|
||||
if (datasourceName.isEmpty()) {
|
||||
throw new GenericEntityConfException("<group-map> element datasource-name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.datasourceName = datasourceName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>group-name</code> attribute. */
|
||||
public String getGroupName() {
|
||||
return this.groupName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>datasource-name</code> attribute. */
|
||||
public String getDatasourceName() {
|
||||
return this.datasourceName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><inline-jdbc></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class InlineJdbc extends JdbcElement {
|
||||
|
||||
private final String jdbcDriver; // type = xs:string
|
||||
private final String jdbcUri; // type = xs:string
|
||||
private final String jdbcUsername; // type = xs:string
|
||||
private final String jdbcPassword; // type = xs:string
|
||||
private final String jdbcPasswordLookup; // type = xs:string
|
||||
private final int poolMaxsize; // type = xs:nonNegativeInteger
|
||||
private final int poolMinsize; // type = xs:nonNegativeInteger
|
||||
private final int idleMaxsize; // type = xs:nonNegativeInteger
|
||||
private final int timeBetweenEvictionRunsMillis; // type = xs:nonNegativeInteger
|
||||
private final int softMinEvictableIdleTimeMillis; // type = xs:nonNegativeInteger
|
||||
private final int poolSleeptime; // type = xs:nonNegativeInteger
|
||||
private final int poolLifetime; // type = xs:nonNegativeInteger
|
||||
private final int poolDeadlockMaxwait; // type = xs:nonNegativeInteger
|
||||
private final int poolDeadlockRetrywait; // type = xs:nonNegativeInteger
|
||||
private final String poolJdbcTestStmt; // type = xs:string
|
||||
private final boolean testOnCreate; // type = xs:boolean
|
||||
private final boolean testOnBorrow; // type = xs:boolean
|
||||
private final boolean testOnReturn; // type = xs:boolean
|
||||
private final boolean testWhileIdle; // type = xs:boolean
|
||||
private final String poolXaWrapperClass; // type = xs:string
|
||||
|
||||
InlineJdbc(Element element) throws GenericEntityConfException {
|
||||
super(element);
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String jdbcDriver = element.getAttribute("jdbc-driver").intern();
|
||||
if (jdbcDriver.isEmpty()) {
|
||||
throw new GenericEntityConfException("<inline-jdbc> element jdbc-driver attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.jdbcDriver = jdbcDriver;
|
||||
String jdbcUri = element.getAttribute("jdbc-uri").intern();
|
||||
if (jdbcUri.isEmpty()) {
|
||||
throw new GenericEntityConfException("<inline-jdbc> element jdbc-uri attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.jdbcUri = jdbcUri;
|
||||
String jdbcUsername = element.getAttribute("jdbc-username").intern();
|
||||
if (jdbcUsername.isEmpty()) {
|
||||
throw new GenericEntityConfException("<inline-jdbc> element jdbc-username attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.jdbcUsername = jdbcUsername;
|
||||
this.jdbcPassword = element.getAttribute("jdbc-password").intern();
|
||||
this.jdbcPasswordLookup = element.getAttribute("jdbc-password-lookup").intern();
|
||||
String poolMaxsize = element.getAttribute("pool-maxsize");
|
||||
if (poolMaxsize.isEmpty()) {
|
||||
this.poolMaxsize = 50;
|
||||
} else {
|
||||
try {
|
||||
this.poolMaxsize = Integer.parseInt(poolMaxsize);
|
||||
} catch (Exception e) {
|
||||
throw new GenericEntityConfException("<inline-jdbc> element pool-maxsize attribute is invalid" + lineNumberText);
|
||||
}
|
||||
}
|
||||
String poolMinsize = element.getAttribute("pool-minsize");
|
||||
if (poolMinsize.isEmpty()) {
|
||||
this.poolMinsize = 2;
|
||||
} else {
|
||||
try {
|
||||
this.poolMinsize = Integer.parseInt(poolMinsize);
|
||||
} catch (Exception e) {
|
||||
throw new GenericEntityConfException("<inline-jdbc> element pool-minsize attribute is invalid" + lineNumberText);
|
||||
}
|
||||
}
|
||||
String idleMaxsize = element.getAttribute("idle-maxsize");
|
||||
if (idleMaxsize.isEmpty()) {
|
||||
this.idleMaxsize = this.poolMaxsize / 2;
|
||||
} else {
|
||||
try {
|
||||
this.idleMaxsize = Integer.parseInt(idleMaxsize);
|
||||
} catch (Exception e) {
|
||||
throw new GenericEntityConfException("<inline-jdbc> element idle-maxsize attribute is invalid" + lineNumberText);
|
||||
}
|
||||
}
|
||||
String timeBetweenEvictionRunsMillis = element.getAttribute("time-between-eviction-runs-millis");
|
||||
if (timeBetweenEvictionRunsMillis.isEmpty()) {
|
||||
this.timeBetweenEvictionRunsMillis = 600000;
|
||||
} else {
|
||||
try {
|
||||
this.timeBetweenEvictionRunsMillis = Integer.parseInt(timeBetweenEvictionRunsMillis);
|
||||
} catch (Exception e) {
|
||||
throw new GenericEntityConfException("<inline-jdbc> element time-between-eviction-runs-millis attribute is invalid" + lineNumberText);
|
||||
}
|
||||
}
|
||||
String softMinEvictableIdleTimeMillis = element.getAttribute("soft-min-evictable-idle-time-millis");
|
||||
if (softMinEvictableIdleTimeMillis.isEmpty()) {
|
||||
this.softMinEvictableIdleTimeMillis = 600000;
|
||||
} else {
|
||||
try {
|
||||
this.softMinEvictableIdleTimeMillis = Integer.parseInt(softMinEvictableIdleTimeMillis);
|
||||
} catch (Exception e) {
|
||||
throw new GenericEntityConfException("<inline-jdbc> element soft-min-evictable-idle-time-millis attribute is invalid" + lineNumberText);
|
||||
}
|
||||
}
|
||||
String poolSleeptime = element.getAttribute("pool-sleeptime");
|
||||
if (poolSleeptime.isEmpty()) {
|
||||
this.poolSleeptime = 300000;
|
||||
} else {
|
||||
try {
|
||||
this.poolSleeptime = Integer.parseInt(poolSleeptime);
|
||||
} catch (Exception e) {
|
||||
throw new GenericEntityConfException("<inline-jdbc> element pool-sleeptime attribute is invalid" + lineNumberText);
|
||||
}
|
||||
}
|
||||
String poolLifetime = element.getAttribute("pool-lifetime");
|
||||
if (poolLifetime.isEmpty()) {
|
||||
this.poolLifetime = 600000;
|
||||
} else {
|
||||
try {
|
||||
this.poolLifetime = Integer.parseInt(poolLifetime);
|
||||
} catch (Exception e) {
|
||||
throw new GenericEntityConfException("<inline-jdbc> element pool-lifetime attribute is invalid" + lineNumberText);
|
||||
}
|
||||
}
|
||||
String poolDeadlockMaxwait = element.getAttribute("pool-deadlock-maxwait");
|
||||
if (poolDeadlockMaxwait.isEmpty()) {
|
||||
this.poolDeadlockMaxwait = 300000;
|
||||
} else {
|
||||
try {
|
||||
this.poolDeadlockMaxwait = Integer.parseInt(poolDeadlockMaxwait);
|
||||
} catch (Exception e) {
|
||||
throw new GenericEntityConfException("<inline-jdbc> element pool-deadlock-maxwait attribute is invalid" + lineNumberText);
|
||||
}
|
||||
}
|
||||
String poolDeadlockRetrywait = element.getAttribute("pool-deadlock-retrywait");
|
||||
if (poolDeadlockRetrywait.isEmpty()) {
|
||||
this.poolDeadlockRetrywait = 10000;
|
||||
} else {
|
||||
try {
|
||||
this.poolDeadlockRetrywait = Integer.parseInt(poolDeadlockRetrywait);
|
||||
} catch (Exception e) {
|
||||
throw new GenericEntityConfException("<inline-jdbc> element pool-deadlock-retrywait attribute is invalid" + lineNumberText);
|
||||
}
|
||||
}
|
||||
this.poolJdbcTestStmt = element.getAttribute("pool-jdbc-test-stmt").intern();
|
||||
this.testOnCreate = "true".equals(element.getAttribute("test-on-create"));
|
||||
this.testOnBorrow = "true".equals(element.getAttribute("test-on-borrow"));
|
||||
this.testOnReturn = "true".equals(element.getAttribute("test-on-return"));
|
||||
this.testWhileIdle = "true".equals(element.getAttribute("test-while-idle"));
|
||||
this.poolXaWrapperClass = element.getAttribute("pool-xa-wrapper-class").intern();
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>jdbc-driver</code> attribute. */
|
||||
public String getJdbcDriver() {
|
||||
return this.jdbcDriver;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>jdbc-uri</code> attribute. */
|
||||
public String getJdbcUri() {
|
||||
return this.jdbcUri;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>jdbc-username</code> attribute. */
|
||||
public String getJdbcUsername() {
|
||||
return this.jdbcUsername;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>jdbc-password</code> attribute. */
|
||||
public String getJdbcPassword() {
|
||||
return this.jdbcPassword;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>jdbc-password-lookup</code> attribute. */
|
||||
public String getJdbcPasswordLookup() {
|
||||
return this.jdbcPasswordLookup;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>pool-maxsize</code> attribute. */
|
||||
public int getPoolMaxsize() {
|
||||
return this.poolMaxsize;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>pool-minsize</code> attribute. */
|
||||
public int getPoolMinsize() {
|
||||
return this.poolMinsize;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>idle-maxsize</code> attribute. */
|
||||
public int getIdleMaxsize() {
|
||||
return this.idleMaxsize;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>time-between-eviction-runs-millis</code> attribute. */
|
||||
public int getTimeBetweenEvictionRunsMillis() {
|
||||
return this.timeBetweenEvictionRunsMillis;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>time-between-eviction-runs-millis</code> attribute. */
|
||||
public int getSoftMinEvictableIdleTimeMillis() {
|
||||
return this.softMinEvictableIdleTimeMillis;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>pool-sleeptime</code> attribute. */
|
||||
public int getPoolSleeptime() {
|
||||
return this.poolSleeptime;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>pool-lifetime</code> attribute. */
|
||||
public int getPoolLifetime() {
|
||||
return this.poolLifetime;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>pool-deadlock-maxwait</code> attribute. */
|
||||
public int getPoolDeadlockMaxwait() {
|
||||
return this.poolDeadlockMaxwait;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>pool-deadlock-retrywait</code> attribute. */
|
||||
public int getPoolDeadlockRetrywait() {
|
||||
return this.poolDeadlockRetrywait;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>pool-jdbc-test-stmt</code> attribute. */
|
||||
public String getPoolJdbcTestStmt() {
|
||||
return this.poolJdbcTestStmt;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>test-on-create</code> attribute. */
|
||||
public boolean getTestOnCreate() {
|
||||
return this.testOnCreate;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>test-on-create</code> attribute. */
|
||||
public boolean getTestOnBorrow() {
|
||||
return this.testOnBorrow;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>test-on-create</code> attribute. */
|
||||
public boolean getTestOnReturn() {
|
||||
return this.testOnReturn;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>test-on-create</code> attribute. */
|
||||
public boolean getTestWhileIdle() {
|
||||
return this.testWhileIdle;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>pool-xa-wrapper-class</code> attribute. */
|
||||
public String getPoolXaWrapperClass() {
|
||||
return this.poolXaWrapperClass;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An abstract class for <code><datasource></code> JDBC child elements.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
public abstract class JdbcElement {
|
||||
|
||||
private final String isolationLevel;
|
||||
private final String lineNumber;
|
||||
|
||||
protected JdbcElement(Element element) throws GenericEntityConfException {
|
||||
this.isolationLevel = element.getAttribute("isolation-level").intern();
|
||||
Object lineNumber = element.getUserData("startLine");
|
||||
this.lineNumber = lineNumber == null ? "unknown" : lineNumber.toString();
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>isolation-level</code> attribute. */
|
||||
public String getIsolationLevel() {
|
||||
return this.isolationLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the configuration file line number for this element.
|
||||
* @return The configuration file line number for this element
|
||||
*/
|
||||
public String getLineNumber() {
|
||||
return this.lineNumber;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><jndi-jdbc></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class JndiJdbc extends JdbcElement {
|
||||
|
||||
private final String jndiServerName; // type = xs:string
|
||||
private final String jndiName; // type = xs:string
|
||||
|
||||
JndiJdbc(Element element) throws GenericEntityConfException {
|
||||
super(element);
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String jndiServerName = element.getAttribute("jndi-server-name").intern();
|
||||
if (jndiServerName.isEmpty()) {
|
||||
throw new GenericEntityConfException("<jndi-jdbc> element jndi-server-name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.jndiServerName = jndiServerName;
|
||||
String jndiName = element.getAttribute("jndi-name").intern();
|
||||
if (jndiName.isEmpty()) {
|
||||
throw new GenericEntityConfException("<jndi-jdbc> element jndi-name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.jndiName = jndiName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>jndi-server-name</code> attribute. */
|
||||
public String getJndiServerName() {
|
||||
return this.jndiServerName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>jndi-name</code> attribute. */
|
||||
public String getJndiName() {
|
||||
return this.jndiName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><read-data></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class ReadData {
|
||||
|
||||
private final String readerName; // type = xs:string
|
||||
|
||||
ReadData(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String readerName = element.getAttribute("reader-name").intern();
|
||||
if (readerName.isEmpty()) {
|
||||
throw new GenericEntityConfException("<read-data> element reader-name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.readerName = readerName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>reader-name</code> attribute. */
|
||||
public String getReaderName() {
|
||||
return this.readerName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><resource></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class Resource {
|
||||
|
||||
private final String loader; // type = xs:string
|
||||
private final String location; // type = xs:string
|
||||
|
||||
Resource(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String loader = element.getAttribute("loader").intern();
|
||||
if (loader.isEmpty()) {
|
||||
throw new GenericEntityConfException("<resource> element loader attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.loader = loader;
|
||||
String location = element.getAttribute("location").intern();
|
||||
if (location.isEmpty()) {
|
||||
throw new GenericEntityConfException("<resource> element location attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.location = location;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>loader</code> attribute. */
|
||||
public String getLoader() {
|
||||
return this.loader;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>location</code> attribute. */
|
||||
public String getLocation() {
|
||||
return this.location;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><resource-loader></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class ResourceLoader {
|
||||
|
||||
private final String name; // type = xs:string
|
||||
private final String className; // type = xs:string
|
||||
private final String prependEnv; // type = xs:string
|
||||
private final String prefix; // type = xs:string
|
||||
|
||||
ResourceLoader(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String name = element.getAttribute("name").intern();
|
||||
if (name.isEmpty()) {
|
||||
throw new GenericEntityConfException("<resource-loader> element name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.name = name;
|
||||
String className = element.getAttribute("class").intern();
|
||||
if (className.isEmpty()) {
|
||||
throw new GenericEntityConfException("<resource-loader> element class attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.className = className;
|
||||
this.prependEnv = element.getAttribute("prepend-env").intern();
|
||||
this.prefix = element.getAttribute("prefix").intern();
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>name</code> attribute. */
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>class</code> attribute. */
|
||||
public String getClassName() {
|
||||
return this.className;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>prepend-env</code> attribute. */
|
||||
public String getPrependEnv() {
|
||||
return this.prependEnv;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>prefix</code> attribute. */
|
||||
public String getPrefix() {
|
||||
return this.prefix;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><sql-load-path></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class SqlLoadPath {
|
||||
|
||||
private final String path; // type = xs:string
|
||||
private final String prependEnv; // type = xs:string
|
||||
|
||||
SqlLoadPath(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String path = element.getAttribute("path").intern();
|
||||
if (path.isEmpty()) {
|
||||
throw new GenericEntityConfException("<sql-load-path> element path attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.path = path;
|
||||
this.prependEnv = element.getAttribute("prepend-env").intern();
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>path</code> attribute. */
|
||||
public String getPath() {
|
||||
return this.path;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>prepend-env</code> attribute. */
|
||||
public String getPrependEnv() {
|
||||
return this.prependEnv;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><transaction-factory></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class TransactionFactory {
|
||||
|
||||
private final String className; // type = xs:string
|
||||
private final UserTransactionJndi userTransactionJndi; // <user-transaction-jndi>
|
||||
private final TransactionManagerJndi transactionManagerJndi; // <transaction-manager-jndi>
|
||||
|
||||
TransactionFactory(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String className = element.getAttribute("class").intern();
|
||||
if (className.isEmpty()) {
|
||||
throw new GenericEntityConfException("<transaction-factory> element class attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.className = className;
|
||||
Element userTransactionJndiElement = UtilXml.firstChildElement(element, "user-transaction-jndi");
|
||||
if (userTransactionJndiElement == null) {
|
||||
this.userTransactionJndi = null;
|
||||
} else {
|
||||
this.userTransactionJndi = new UserTransactionJndi(userTransactionJndiElement);
|
||||
}
|
||||
Element transactionManagerJndiElement = UtilXml.firstChildElement(element, "transaction-manager-jndi");
|
||||
if (transactionManagerJndiElement == null) {
|
||||
this.transactionManagerJndi = null;
|
||||
} else {
|
||||
this.transactionManagerJndi = new TransactionManagerJndi(transactionManagerJndiElement);
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>class</code> attribute. */
|
||||
public String getClassName() {
|
||||
return this.className;
|
||||
}
|
||||
|
||||
/** Returns the <code><user-transaction-jndi></code> child element, or <code>null</code> if no child element was found. */
|
||||
public UserTransactionJndi getUserTransactionJndi() {
|
||||
return this.userTransactionJndi;
|
||||
}
|
||||
|
||||
/** Returns the <code><transaction-manager-jndi></code> child element, or <code>null</code> if no child element was found. */
|
||||
public TransactionManagerJndi getTransactionManagerJndi() {
|
||||
return this.transactionManagerJndi;
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><transaction-manager-jndi></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class TransactionManagerJndi {
|
||||
|
||||
private final String jndiServerName; // type = xs:string
|
||||
private final String jndiName; // type = xs:string
|
||||
|
||||
TransactionManagerJndi(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String jndiServerName = element.getAttribute("jndi-server-name").intern();
|
||||
if (jndiServerName.isEmpty()) {
|
||||
throw new GenericEntityConfException("<transaction-manager-jndi> element jndi-server-name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.jndiServerName = jndiServerName;
|
||||
String jndiName = element.getAttribute("jndi-name").intern();
|
||||
if (jndiName.isEmpty()) {
|
||||
throw new GenericEntityConfException("<transaction-manager-jndi> element jndi-name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.jndiName = jndiName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>jndi-server-name</code> attribute. */
|
||||
public String getJndiServerName() {
|
||||
return this.jndiServerName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>jndi-name</code> attribute. */
|
||||
public String getJndiName() {
|
||||
return this.jndiName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><tyrex-dataSource></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class TyrexDataSource extends JdbcElement {
|
||||
|
||||
private final String dataSourceName; // type = xs:string
|
||||
|
||||
TyrexDataSource(Element element) throws GenericEntityConfException {
|
||||
super(element);
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String dataSourceName = element.getAttribute("dataSource-name").intern();
|
||||
if (dataSourceName.isEmpty()) {
|
||||
throw new GenericEntityConfException("<tyrex-dataSource> element dataSource-name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.dataSourceName = dataSourceName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>dataSource-name</code> attribute. */
|
||||
public String getDataSourceName() {
|
||||
return this.dataSourceName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.config.model;
|
||||
|
||||
import org.ofbiz.base.lang.ThreadSafe;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* An object that models the <code><user-transaction-jndi></code> element.
|
||||
*
|
||||
* @see <code>entity-config.xsd</code>
|
||||
*/
|
||||
@ThreadSafe
|
||||
public final class UserTransactionJndi {
|
||||
|
||||
private final String jndiServerName; // type = xs:string
|
||||
private final String jndiName; // type = xs:string
|
||||
|
||||
UserTransactionJndi(Element element) throws GenericEntityConfException {
|
||||
String lineNumberText = EntityConfig.createConfigFileLineNumberText(element);
|
||||
String jndiServerName = element.getAttribute("jndi-server-name").intern();
|
||||
if (jndiServerName.isEmpty()) {
|
||||
throw new GenericEntityConfException("<user-transaction-jndi> element jndi-server-name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.jndiServerName = jndiServerName;
|
||||
String jndiName = element.getAttribute("jndi-name").intern();
|
||||
if (jndiName.isEmpty()) {
|
||||
throw new GenericEntityConfException("<user-transaction-jndi> element jndi-name attribute is empty" + lineNumberText);
|
||||
}
|
||||
this.jndiName = jndiName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>jndi-server-name</code> attribute. */
|
||||
public String getJndiServerName() {
|
||||
return this.jndiServerName;
|
||||
}
|
||||
|
||||
/** Returns the value of the <code>jndi-name</code> attribute. */
|
||||
public String getJndiName() {
|
||||
return this.jndiName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.connection;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.config.model.JdbcElement;
|
||||
import org.ofbiz.entity.datasource.GenericHelperInfo;
|
||||
|
||||
/**
|
||||
* ConnectionFactory
|
||||
*/
|
||||
public interface ConnectionFactory {
|
||||
|
||||
public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement jdbcElement) throws SQLException, GenericEntityException;
|
||||
public void closeAll();
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.connection;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.Driver;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import javax.transaction.TransactionManager;
|
||||
|
||||
import org.apache.commons.dbcp2.DriverConnectionFactory;
|
||||
import org.apache.commons.dbcp2.PoolableConnection;
|
||||
import org.apache.commons.dbcp2.PoolableConnectionFactory;
|
||||
import org.apache.commons.dbcp2.managed.LocalXAConnectionFactory;
|
||||
import org.apache.commons.dbcp2.managed.PoolableManagedConnectionFactory;
|
||||
import org.apache.commons.dbcp2.managed.XAConnectionFactory;
|
||||
import org.apache.commons.pool2.impl.GenericObjectPool;
|
||||
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.entity.GenericEntityConfException;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.config.model.EntityConfig;
|
||||
import org.ofbiz.entity.config.model.InlineJdbc;
|
||||
import org.ofbiz.entity.config.model.JdbcElement;
|
||||
import org.ofbiz.entity.datasource.GenericHelperInfo;
|
||||
import org.ofbiz.entity.transaction.TransactionFactoryLoader;
|
||||
import org.ofbiz.entity.transaction.TransactionUtil;
|
||||
|
||||
/**
|
||||
* Apache Commons DBCP connection factory.
|
||||
*
|
||||
* @see <a href="http://commons.apache.org/proper/commons-dbcp/">Apache Commons DBCP</a>
|
||||
*/
|
||||
public class DBCPConnectionFactory implements ConnectionFactory {
|
||||
|
||||
public static final String module = DBCPConnectionFactory.class.getName();
|
||||
// ManagedDataSource is useful to debug the usage of connections in the pool (must be verbose)
|
||||
// In case you don't want to be disturbed in the log (focusing on something else), it's still easy to comment out the line from DebugManagedDataSource
|
||||
protected static final ConcurrentHashMap<String, DebugManagedDataSource> dsCache = new ConcurrentHashMap<String, DebugManagedDataSource>();
|
||||
|
||||
public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc) throws SQLException, GenericEntityException {
|
||||
String cacheKey = helperInfo.getHelperFullName();
|
||||
DebugManagedDataSource mds = dsCache.get(cacheKey);
|
||||
if (mds != null) {
|
||||
return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
|
||||
}
|
||||
if (!(abstractJdbc instanceof InlineJdbc)) {
|
||||
throw new GenericEntityConfException("DBCP requires an <inline-jdbc> child element in the <datasource> element");
|
||||
}
|
||||
InlineJdbc jdbcElement = (InlineJdbc) abstractJdbc;
|
||||
// connection properties
|
||||
TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager();
|
||||
String driverName = jdbcElement.getJdbcDriver();
|
||||
|
||||
String jdbcUri = helperInfo.getOverrideJdbcUri(jdbcElement.getJdbcUri());
|
||||
String jdbcUsername = helperInfo.getOverrideUsername(jdbcElement.getJdbcUsername());
|
||||
String jdbcPassword = helperInfo.getOverridePassword(EntityConfig.getJdbcPassword(jdbcElement));
|
||||
|
||||
// pool settings
|
||||
int maxSize = jdbcElement.getPoolMaxsize();
|
||||
int minSize = jdbcElement.getPoolMinsize();
|
||||
int maxIdle = jdbcElement.getIdleMaxsize();
|
||||
// maxIdle must be greater than pool-minsize
|
||||
maxIdle = maxIdle > minSize ? maxIdle : minSize;
|
||||
// load the driver
|
||||
Driver jdbcDriver;
|
||||
synchronized (DBCPConnectionFactory.class) {
|
||||
// Sync needed for MS SQL JDBC driver. See OFBIZ-5216.
|
||||
try {
|
||||
jdbcDriver = (Driver) Class.forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance();
|
||||
} catch (Exception e) {
|
||||
Debug.logError(e, module);
|
||||
throw new GenericEntityException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
// connection factory properties
|
||||
Properties cfProps = new Properties();
|
||||
cfProps.put("user", jdbcUsername);
|
||||
cfProps.put("password", jdbcPassword);
|
||||
|
||||
// create the connection factory
|
||||
org.apache.commons.dbcp2.ConnectionFactory cf = new DriverConnectionFactory(jdbcDriver, jdbcUri, cfProps);
|
||||
|
||||
// wrap it with a LocalXAConnectionFactory
|
||||
XAConnectionFactory xacf = new LocalXAConnectionFactory(txMgr, cf);
|
||||
|
||||
// create the pool object factory
|
||||
PoolableConnectionFactory factory = new PoolableManagedConnectionFactory(xacf, null);
|
||||
factory.setValidationQuery(jdbcElement.getPoolJdbcTestStmt());
|
||||
factory.setDefaultReadOnly(false);
|
||||
factory.setRollbackOnReturn(false);
|
||||
factory.setEnableAutoCommitOnReturn(false);
|
||||
String transIso = jdbcElement.getIsolationLevel();
|
||||
if (!transIso.isEmpty()) {
|
||||
if ("Serializable".equals(transIso)) {
|
||||
factory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
|
||||
} else if ("RepeatableRead".equals(transIso)) {
|
||||
factory.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
|
||||
} else if ("ReadUncommitted".equals(transIso)) {
|
||||
factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
|
||||
} else if ("ReadCommitted".equals(transIso)) {
|
||||
factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
|
||||
} else if ("None".equals(transIso)) {
|
||||
factory.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
|
||||
}
|
||||
}
|
||||
|
||||
// configure the pool settings
|
||||
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
|
||||
poolConfig.setMaxTotal(maxSize);
|
||||
// settings for idle connections
|
||||
poolConfig.setMaxIdle(maxIdle);
|
||||
poolConfig.setMinIdle(minSize);
|
||||
poolConfig.setTimeBetweenEvictionRunsMillis(jdbcElement.getTimeBetweenEvictionRunsMillis());
|
||||
poolConfig.setMinEvictableIdleTimeMillis(-1); // disabled in favour of setSoftMinEvictableIdleTimeMillis(...)
|
||||
poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis());
|
||||
poolConfig.setNumTestsPerEvictionRun(maxSize); // test all the idle connections
|
||||
// settings for when the pool is exhausted
|
||||
poolConfig.setBlockWhenExhausted(true); // the thread requesting the connection waits if no connection is available
|
||||
poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread
|
||||
// settings for the execution of the validation query
|
||||
poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate());
|
||||
poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow());
|
||||
poolConfig.setTestOnReturn(jdbcElement.getTestOnReturn());
|
||||
poolConfig.setTestWhileIdle(jdbcElement.getTestWhileIdle());
|
||||
|
||||
GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(factory, poolConfig);
|
||||
factory.setPool(pool);
|
||||
|
||||
mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry());
|
||||
mds.setAccessToUnderlyingConnectionAllowed(true);
|
||||
|
||||
// cache the pool
|
||||
dsCache.putIfAbsent(cacheKey, mds);
|
||||
mds = dsCache.get(cacheKey);
|
||||
|
||||
return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
|
||||
}
|
||||
|
||||
public void closeAll() {
|
||||
// no methods on the pool to shutdown; so just clearing for GC
|
||||
dsCache.clear();
|
||||
}
|
||||
|
||||
public static Map<String, Object> getDataSourceInfo(String helperName) {
|
||||
Map<String, Object> dataSourceInfo = new HashMap<String, Object>();
|
||||
DebugManagedDataSource mds = dsCache.get(helperName);
|
||||
if (mds instanceof DebugManagedDataSource) {
|
||||
dataSourceInfo = mds.getInfo();
|
||||
}
|
||||
return dataSourceInfo;
|
||||
}
|
||||
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.connection;
|
||||
|
||||
import org.apache.commons.dbcp2.managed.ManagedDataSource;
|
||||
import org.apache.commons.dbcp2.managed.TransactionRegistry;
|
||||
import org.apache.commons.pool2.ObjectPool;
|
||||
|
||||
import org.apache.commons.pool2.impl.GenericObjectPool;
|
||||
import org.ofbiz.base.util.Debug;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class DebugManagedDataSource extends ManagedDataSource {
|
||||
|
||||
public static final String module = DebugManagedDataSource.class.getName();
|
||||
|
||||
public DebugManagedDataSource(ObjectPool pool, TransactionRegistry transactionRegistry) {
|
||||
super(pool, transactionRegistry);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Connection getConnection() throws SQLException {
|
||||
if (Debug.verboseOn()) {
|
||||
if (super.getPool() instanceof GenericObjectPool) {
|
||||
GenericObjectPool objectPool = (GenericObjectPool)super.getPool();
|
||||
Debug.logVerbose("Borrowing a connection from the pool; used/idle/total: " + objectPool.getNumActive() + "/" + objectPool.getNumIdle() + "/" + (objectPool.getNumActive() + objectPool.getNumIdle()) + "; min idle/max idle/max total: " + objectPool.getMinIdle() + "/" + objectPool.getMaxIdle() + "/" + objectPool.getMaxTotal(), module);
|
||||
} else {
|
||||
Debug.logVerbose("Borrowing a connection from the pool; used/idle/total: " + super.getPool().getNumActive() + "/" + super.getPool().getNumIdle() + "/" + (super.getPool().getNumActive() + super.getPool().getNumIdle()), module);
|
||||
}
|
||||
}
|
||||
return super.getConnection();
|
||||
}
|
||||
|
||||
public Map<String, Object> getInfo() {
|
||||
Map<String, Object> dataSourceInfo = new HashMap<String, Object>();
|
||||
dataSourceInfo.put("poolNumActive", super.getPool().getNumActive());
|
||||
dataSourceInfo.put("poolNumIdle", super.getPool().getNumIdle());
|
||||
dataSourceInfo.put("poolNumTotal", (super.getPool().getNumIdle() + super.getPool().getNumActive()));
|
||||
if (super.getPool() instanceof GenericObjectPool) {
|
||||
GenericObjectPool objectPool = (GenericObjectPool)super.getPool();
|
||||
dataSourceInfo.put("poolMaxActive", objectPool.getMaxTotal());
|
||||
dataSourceInfo.put("poolMaxIdle", objectPool.getMaxIdle());
|
||||
dataSourceInfo.put("poolMaxWait", objectPool.getMaxWaitMillis());
|
||||
dataSourceInfo.put("poolMinEvictableIdleTimeMillis", objectPool.getMinEvictableIdleTimeMillis());
|
||||
dataSourceInfo.put("poolMinIdle", objectPool.getMinIdle());
|
||||
}
|
||||
return dataSourceInfo;
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,128 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.datasource;
|
||||
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericPK;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelRelation;
|
||||
import org.ofbiz.entity.util.EntityFindOptions;
|
||||
import org.ofbiz.entity.util.EntityListIterator;
|
||||
|
||||
|
||||
/**
|
||||
* Generic Entity Helper Class
|
||||
*
|
||||
*/
|
||||
public interface GenericHelper {
|
||||
|
||||
/** Gets the name of the server configuration that corresponds to this helper
|
||||
*@return server configuration name
|
||||
*/
|
||||
public String getHelperName();
|
||||
|
||||
/** Creates a Entity in the form of a GenericValue and write it to the database
|
||||
*@return GenericValue instance containing the new instance
|
||||
*/
|
||||
public GenericValue create(GenericValue value) throws GenericEntityException;
|
||||
|
||||
/** Find a Generic Entity by its Primary Key
|
||||
*@param primaryKey The primary key to find by.
|
||||
*@return The GenericValue corresponding to the primaryKey
|
||||
*/
|
||||
public GenericValue findByPrimaryKey(GenericPK primaryKey) throws GenericEntityException;
|
||||
|
||||
/** Find a Generic Entity by its Primary Key and only returns the values requested by the passed keys (names)
|
||||
*@param primaryKey The primary key to find by.
|
||||
*@param keys The keys, or names, of the values to retrieve; only these values will be retrieved
|
||||
*@return The GenericValue corresponding to the primaryKey
|
||||
*/
|
||||
public GenericValue findByPrimaryKeyPartial(GenericPK primaryKey, Set<String> keys) throws GenericEntityException;
|
||||
|
||||
/** Find a number of Generic Value objects by their Primary Keys, all at once
|
||||
*@param primaryKeys A List of primary keys to find by.
|
||||
*@return List of GenericValue objects corresponding to the passed primaryKey objects
|
||||
*/
|
||||
public List<GenericValue> findAllByPrimaryKeys(List<GenericPK> primaryKeys) throws GenericEntityException;
|
||||
|
||||
/** Remove a Generic Entity corresponding to the primaryKey
|
||||
*@param primaryKey The primary key of the entity to remove.
|
||||
*@return int representing number of rows effected by this operation
|
||||
*/
|
||||
public int removeByPrimaryKey(GenericPK primaryKey) throws GenericEntityException;
|
||||
|
||||
public List<GenericValue> findByMultiRelation(GenericValue value, ModelRelation modelRelationOne, ModelEntity modelEntityOne,
|
||||
ModelRelation modelRelationTwo, ModelEntity modelEntityTwo, List<String> orderBy) throws GenericEntityException;
|
||||
|
||||
/** Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details.
|
||||
*@param modelEntity The ModelEntity of the Entity as defined in the entity XML file
|
||||
*@param whereEntityCondition The EntityCondition object that specifies how to constrain this query before any groupings are done (if this is a view entity with group-by aliases)
|
||||
*@param havingEntityCondition The EntityCondition object that specifies how to constrain this query after any groupings are done (if this is a view entity with group-by aliases)
|
||||
*@param fieldsToSelect The fields of the named entity to get from the database; if empty or null all fields will be retreived
|
||||
*@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending
|
||||
*@param findOptions An instance of EntityFindOptions that specifies advanced query options. See the EntityFindOptions JavaDoc for more details.
|
||||
*@return EntityListIterator representing the result of the query: NOTE THAT THIS MUST BE CLOSED WHEN YOU ARE
|
||||
* DONE WITH IT, AND DON'T LEAVE IT OPEN TOO LONG BEACUSE IT WILL MAINTAIN A DATABASE CONNECTION.
|
||||
*/
|
||||
public EntityListIterator findListIteratorByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition,
|
||||
EntityCondition havingEntityCondition, Collection<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions)
|
||||
throws GenericEntityException;
|
||||
|
||||
public long findCountByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition,
|
||||
EntityCondition havingEntityCondition, EntityFindOptions findOptions) throws GenericEntityException;
|
||||
|
||||
/** Removes/deletes Generic Entity records found by all the specified condition
|
||||
*@param modelEntity The ModelEntity of the Entity as defined in the entity XML file
|
||||
*@param condition The condition that restricts the list of removed values
|
||||
*@return int representing number of rows effected by this operation
|
||||
*/
|
||||
public int removeByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition condition) throws GenericEntityException;
|
||||
|
||||
/** Stores a group of values in a single query
|
||||
*@param modelEntity The ModelEntity of the Entity as defined in the entity XML file
|
||||
*@param fieldsToSet The fields of the named entity to set in the database
|
||||
*@param condition The condition that restricts the list of updated values
|
||||
*@return int representing number of rows effected by this operation
|
||||
*@throws GenericEntityException
|
||||
*/
|
||||
public int storeByCondition(Delegator delegator, ModelEntity modelEntity, Map<String, ? extends Object> fieldsToSet, EntityCondition condition) throws GenericEntityException;
|
||||
|
||||
/** Store the Entity from the GenericValue to the persistent store
|
||||
*@param value GenericValue instance containing the entity
|
||||
*@return int representing number of rows effected by this operation
|
||||
*/
|
||||
public int store(GenericValue value) throws GenericEntityException;
|
||||
|
||||
/** Check the datasource to make sure the entity definitions are correct, optionally adding missing entities or fields on the server
|
||||
*@param modelEntities Map of entityName names and ModelEntity values
|
||||
*@param messages List to put any result messages in
|
||||
*@param addMissing Flag indicating whether or not to add missing entities and fields on the server
|
||||
*/
|
||||
public void checkDataSource(Map<String, ModelEntity> modelEntities, List<String> messages, boolean addMissing) throws GenericEntityException;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.datasource;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericPK;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelRelation;
|
||||
import org.ofbiz.entity.util.EntityFindOptions;
|
||||
import org.ofbiz.entity.util.EntityListIterator;
|
||||
|
||||
/**
|
||||
* Generic Entity Helper Class
|
||||
*
|
||||
*/
|
||||
public class GenericHelperDAO implements GenericHelper {
|
||||
|
||||
public static final String module = GenericHelperDAO.class.getName();
|
||||
|
||||
protected GenericDAO genericDAO;
|
||||
protected GenericHelperInfo helperInfo;
|
||||
|
||||
public GenericHelperDAO(GenericHelperInfo helperInfo) {
|
||||
this.helperInfo = helperInfo;
|
||||
genericDAO = GenericDAO.getGenericDAO(helperInfo);
|
||||
}
|
||||
|
||||
public String getHelperName() {
|
||||
return this.helperInfo.getHelperFullName();
|
||||
}
|
||||
|
||||
/** Creates a Entity in the form of a GenericValue and write it to the database
|
||||
*@return GenericValue instance containing the new instance
|
||||
*/
|
||||
public GenericValue create(GenericValue value) throws GenericEntityException {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
int retVal = genericDAO.insert(value);
|
||||
if (Debug.verboseOn()) Debug.logVerbose("Insert Return Value : " + retVal, module);
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Find a Generic Entity by its Primary Key
|
||||
*@param primaryKey The primary key to find by.
|
||||
*@return The GenericValue corresponding to the primaryKey
|
||||
*/
|
||||
public GenericValue findByPrimaryKey(GenericPK primaryKey) throws GenericEntityException {
|
||||
if (primaryKey == null) {
|
||||
return null;
|
||||
}
|
||||
GenericValue genericValue = GenericValue.create(primaryKey);
|
||||
|
||||
genericDAO.select(genericValue);
|
||||
return genericValue;
|
||||
}
|
||||
|
||||
/** Find a Generic Entity by its Primary Key and only returns the values requested by the passed keys (names)
|
||||
*@param primaryKey The primary key to find by.
|
||||
*@param keys The keys, or names, of the values to retrieve; only these values will be retrieved
|
||||
*@return The GenericValue corresponding to the primaryKey
|
||||
*/
|
||||
public GenericValue findByPrimaryKeyPartial(GenericPK primaryKey, Set<String> keys) throws GenericEntityException {
|
||||
if (primaryKey == null) {
|
||||
return null;
|
||||
}
|
||||
GenericValue genericValue = GenericValue.create(primaryKey);
|
||||
|
||||
genericDAO.partialSelect(genericValue, keys);
|
||||
return genericValue;
|
||||
}
|
||||
|
||||
/** Find a number of Generic Value objects by their Primary Keys, all at once
|
||||
* This is done here for the DAO GenericHelper; for a client-server helper it
|
||||
* would be done on the server side to reduce network round trips.
|
||||
*@param primaryKeys A List of primary keys to find by.
|
||||
*@return List of GenericValue objects corresponding to the passed primaryKey objects
|
||||
*/
|
||||
public List<GenericValue> findAllByPrimaryKeys(List<GenericPK> primaryKeys) throws GenericEntityException {
|
||||
if (primaryKeys == null) return null;
|
||||
List<GenericValue> results = new LinkedList<GenericValue>();
|
||||
|
||||
for (GenericPK primaryKey: primaryKeys) {
|
||||
GenericValue result = this.findByPrimaryKey(primaryKey);
|
||||
|
||||
if (result != null) results.add(result);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/** Remove a Generic Entity corresponding to the primaryKey
|
||||
*@param primaryKey The primary key of the entity to remove.
|
||||
*@return int representing number of rows effected by this operation
|
||||
*/
|
||||
public int removeByPrimaryKey(GenericPK primaryKey) throws GenericEntityException {
|
||||
if (primaryKey == null) return 0;
|
||||
if (Debug.verboseOn()) Debug.logVerbose("Removing GenericPK: " + primaryKey.toString(), module);
|
||||
return genericDAO.delete(primaryKey);
|
||||
}
|
||||
|
||||
/** Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details.
|
||||
*@param modelEntity The ModelEntity of the Entity as defined in the entity XML file
|
||||
*@param whereEntityCondition The EntityCondition object that specifies how to constrain this query before any groupings are done (if this is a view entity with group-by aliases)
|
||||
*@param havingEntityCondition The EntityCondition object that specifies how to constrain this query after any groupings are done (if this is a view entity with group-by aliases)
|
||||
*@param fieldsToSelect The fields of the named entity to get from the database; if empty or null all fields will be retreived
|
||||
*@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending
|
||||
*@param findOptions An instance of EntityFindOptions that specifies advanced query options. See the EntityFindOptions JavaDoc for more details.
|
||||
*@return EntityListIterator representing the result of the query: NOTE THAT THIS MUST BE CLOSED WHEN YOU ARE
|
||||
* DONE WITH IT, AND DON'T LEAVE IT OPEN TOO LONG BEACUSE IT WILL MAINTAIN A DATABASE CONNECTION.
|
||||
*/
|
||||
public EntityListIterator findListIteratorByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition,
|
||||
EntityCondition havingEntityCondition, Collection<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions)
|
||||
throws GenericEntityException {
|
||||
return genericDAO.selectListIteratorByCondition(delegator, modelEntity, whereEntityCondition, havingEntityCondition, fieldsToSelect, orderBy, findOptions);
|
||||
}
|
||||
|
||||
public List<GenericValue> findByMultiRelation(GenericValue value, ModelRelation modelRelationOne, ModelEntity modelEntityOne,
|
||||
ModelRelation modelRelationTwo, ModelEntity modelEntityTwo, List<String> orderBy) throws GenericEntityException {
|
||||
return genericDAO.selectByMultiRelation(value, modelRelationOne, modelEntityOne, modelRelationTwo, modelEntityTwo, orderBy);
|
||||
}
|
||||
|
||||
public long findCountByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, EntityFindOptions findOptions) throws GenericEntityException {
|
||||
return genericDAO.selectCountByCondition(delegator, modelEntity, whereEntityCondition, havingEntityCondition, findOptions);
|
||||
}
|
||||
|
||||
/** Removes/deletes Generic Entity records found by all the specified condition
|
||||
*@param modelEntity The ModelEntity of the Entity as defined in the entity XML file
|
||||
*@param condition The condition that restricts the list of removed values
|
||||
*@return int representing number of rows effected by this operation
|
||||
*/
|
||||
public int removeByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition condition) throws GenericEntityException {
|
||||
if (modelEntity == null || condition == null) {
|
||||
return 0;
|
||||
}
|
||||
return genericDAO.deleteByCondition(delegator, modelEntity, condition);
|
||||
}
|
||||
|
||||
/** Store the Entity from the GenericValue to the persistent store
|
||||
*@param value GenericValue instance containing the entity
|
||||
*@return int representing number of rows effected by this operation
|
||||
*/
|
||||
public int store(GenericValue value) throws GenericEntityException {
|
||||
if (value == null) {
|
||||
return 0;
|
||||
}
|
||||
return genericDAO.update(value);
|
||||
}
|
||||
|
||||
/** Updates a group of values in a single pass.
|
||||
*@param modelEntity The ModelEntity of the Entity as defined in the entity XML file
|
||||
*@param fieldsToSet The fields of the named entity to set in the database
|
||||
*@param condition The condition that restricts the list of removed values
|
||||
*@return int representing number of rows effected by this operation
|
||||
*@throws GenericEntityException
|
||||
*/
|
||||
public int storeByCondition(Delegator delegator, ModelEntity modelEntity, Map<String, ? extends Object> fieldsToSet, EntityCondition condition) throws GenericEntityException {
|
||||
if (modelEntity == null || condition == null) {
|
||||
return 0;
|
||||
}
|
||||
return genericDAO.updateByCondition(delegator, modelEntity, fieldsToSet, condition);
|
||||
}
|
||||
|
||||
/** Check the datasource to make sure the entity definitions are correct, optionally adding missing entities or fields on the server
|
||||
*@param modelEntities Map of entityName names and ModelEntity values
|
||||
*@param messages List to put any result messages in
|
||||
*@param addMissing Flag indicating whether or not to add missing entities and fields on the server
|
||||
*/
|
||||
public void checkDataSource(Map<String, ModelEntity> modelEntities, List<String> messages, boolean addMissing) throws GenericEntityException {
|
||||
genericDAO.checkDb(modelEntities, messages, addMissing);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.datasource;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.config.model.EntityConfig;
|
||||
|
||||
/**
|
||||
* Generic Entity Helper Factory Class
|
||||
*
|
||||
*/
|
||||
public class GenericHelperFactory {
|
||||
|
||||
public static final String module = GenericHelperFactory.class.getName();
|
||||
|
||||
// protected static UtilCache helperCache = new UtilCache("entity.GenericHelpers", 0, 0);
|
||||
protected static Map<String, GenericHelper> helperCache = new HashMap<String, GenericHelper>();
|
||||
|
||||
public static GenericHelper getHelper(GenericHelperInfo helperInfo) {
|
||||
GenericHelper helper = helperCache.get(helperInfo.getHelperFullName());
|
||||
|
||||
if (helper == null) { // don't want to block here
|
||||
synchronized (GenericHelperFactory.class) {
|
||||
// must check if null again as one of the blocked threads can still enter
|
||||
helper = helperCache.get(helperInfo.getHelperFullName());
|
||||
if (helper == null) {
|
||||
try {
|
||||
Datasource datasourceInfo = EntityConfig.getDatasource(helperInfo.getHelperBaseName());
|
||||
|
||||
if (datasourceInfo == null) {
|
||||
throw new IllegalStateException("Could not find datasource definition with name " + helperInfo.getHelperBaseName());
|
||||
}
|
||||
String helperClassName = datasourceInfo.getHelperClass();
|
||||
Class<?> helperClass = null;
|
||||
|
||||
if (UtilValidate.isNotEmpty(helperClassName)) {
|
||||
try {
|
||||
ClassLoader loader = Thread.currentThread().getContextClassLoader();
|
||||
helperClass = loader.loadClass(helperClassName);
|
||||
} catch (ClassNotFoundException e) {
|
||||
Debug.logWarning(e, module);
|
||||
throw new IllegalStateException("Error loading GenericHelper class \"" + helperClassName + "\": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
Class<?>[] paramTypes = new Class<?>[] {GenericHelperInfo.class};
|
||||
Object[] params = new Object[] {helperInfo};
|
||||
|
||||
java.lang.reflect.Constructor<?> helperConstructor = null;
|
||||
|
||||
if (helperClass != null) {
|
||||
try {
|
||||
helperConstructor = helperClass.getConstructor(paramTypes);
|
||||
} catch (NoSuchMethodException e) {
|
||||
Debug.logWarning(e, module);
|
||||
throw new IllegalStateException("Error loading GenericHelper class \"" + helperClassName + "\": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
try {
|
||||
helper = (GenericHelper) helperConstructor.newInstance(params);
|
||||
} catch (IllegalAccessException e) {
|
||||
Debug.logWarning(e, module);
|
||||
throw new IllegalStateException("Error loading GenericHelper class \"" + helperClassName + "\": " + e.getMessage());
|
||||
} catch (InstantiationException e) {
|
||||
Debug.logWarning(e, module);
|
||||
throw new IllegalStateException("Error loading GenericHelper class \"" + helperClassName + "\": " + e.getMessage());
|
||||
} catch (java.lang.reflect.InvocationTargetException e) {
|
||||
Debug.logWarning(e, module);
|
||||
throw new IllegalStateException("Error loading GenericHelper class \"" + helperClassName + "\": " + e.getMessage());
|
||||
}
|
||||
|
||||
if (helper != null)
|
||||
helperCache.put(helperInfo.getHelperFullName(), helper);
|
||||
} catch (SecurityException e) {
|
||||
Debug.logError(e, module);
|
||||
throw new IllegalStateException("Error loading GenericHelper class: " + e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return helper;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.ofbiz.entity.datasource;
|
||||
|
||||
/**
|
||||
* A container for datasource connection information.
|
||||
* <p><b>Note that this class is not synchronized.</b>
|
||||
* If multiple threads access a <code>GenericHelperInfo</code> concurrently it must be synchronized externally.
|
||||
* </p>
|
||||
*
|
||||
*/
|
||||
public final class GenericHelperInfo {
|
||||
private final String entityGroupName;
|
||||
private final String helperBaseName;
|
||||
private String tenantId = "";
|
||||
private String overrideJdbcUri = "";
|
||||
private String overrideUsername = "";
|
||||
private String overridePassword = "";
|
||||
private String helperFullName = "";
|
||||
|
||||
public GenericHelperInfo(String entityGroupName, String helperBaseName) {
|
||||
this.entityGroupName = entityGroupName == null ? "" : entityGroupName;
|
||||
this.helperBaseName = helperBaseName == null ? "" : helperBaseName;
|
||||
this.helperFullName = this.helperBaseName;
|
||||
}
|
||||
|
||||
public String getHelperFullName() {
|
||||
return helperFullName;
|
||||
}
|
||||
|
||||
public String getEntityGroupName() {
|
||||
return entityGroupName;
|
||||
}
|
||||
|
||||
public String getHelperBaseName() {
|
||||
return helperBaseName;
|
||||
}
|
||||
|
||||
public String getTenantId() {
|
||||
return tenantId;
|
||||
}
|
||||
|
||||
public void setTenantId(String tenantId) {
|
||||
if (tenantId != null) {
|
||||
this.tenantId = tenantId;
|
||||
helperFullName = helperBaseName.concat("#").concat(tenantId);
|
||||
}
|
||||
}
|
||||
|
||||
public String getOverrideJdbcUri() {
|
||||
return overrideJdbcUri;
|
||||
}
|
||||
|
||||
public String getOverrideJdbcUri(String defaultValue) {
|
||||
return overrideJdbcUri.isEmpty() ? defaultValue : overrideJdbcUri;
|
||||
}
|
||||
|
||||
public void setOverrideJdbcUri(String overrideJdbcUri) {
|
||||
if (overrideJdbcUri != null) {
|
||||
this.overrideJdbcUri = overrideJdbcUri;
|
||||
}
|
||||
}
|
||||
|
||||
public String getOverrideUsername() {
|
||||
return overrideUsername;
|
||||
}
|
||||
|
||||
public String getOverrideUsername(String defaultValue) {
|
||||
return overrideUsername.isEmpty() ? defaultValue : overrideUsername;
|
||||
}
|
||||
|
||||
public void setOverrideUsername(String overrideUsername) {
|
||||
if (overrideUsername != null) {
|
||||
this.overrideUsername = overrideUsername;
|
||||
}
|
||||
}
|
||||
|
||||
public String getOverridePassword() {
|
||||
return overridePassword;
|
||||
}
|
||||
|
||||
public String getOverridePassword(String defaultValue) {
|
||||
return overridePassword.isEmpty() ? defaultValue : overridePassword;
|
||||
}
|
||||
|
||||
public void setOverridePassword(String overridePassword) {
|
||||
if (overridePassword != null) {
|
||||
this.overridePassword = overridePassword;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.eca;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntity;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
|
||||
/**
|
||||
* EntityEcaHandler interface
|
||||
*
|
||||
*/
|
||||
public interface EntityEcaHandler<T> {
|
||||
|
||||
public static final String EV_VALIDATE = "validate";
|
||||
public static final String EV_RUN = "run";
|
||||
public static final String EV_RETURN = "return";
|
||||
/**
|
||||
* Invoked after the entity operation, but before the cache is cleared.
|
||||
*/
|
||||
public static final String EV_CACHE_CLEAR = "cache-clear";
|
||||
public static final String EV_CACHE_CHECK = "cache-check";
|
||||
public static final String EV_CACHE_PUT = "cache-put";
|
||||
|
||||
public static final String OP_CREATE = "create";
|
||||
public static final String OP_STORE = "store";
|
||||
public static final String OP_REMOVE = "remove";
|
||||
public static final String OP_FIND = "find";
|
||||
|
||||
|
||||
public void setDelegator(Delegator delegator);
|
||||
|
||||
public Map<String, List<T>> getEntityEventMap(String entityName);
|
||||
|
||||
public void evalRules(String currentOperation, Map<String, List<T>> eventMap, String event, GenericEntity value, boolean isError) throws GenericEntityException;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.finder;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.collections.FlexibleMapAccessor;
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelFieldTypeReader;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* Uses the delegator to find entity values by a and
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class ByAndFinder extends ListFinder {
|
||||
|
||||
public static final String module = ByAndFinder.class.getName();
|
||||
|
||||
protected Map<FlexibleMapAccessor<Object>, Object> fieldMap;
|
||||
|
||||
public ByAndFinder(Element element) {
|
||||
super(element, "and");
|
||||
|
||||
// process field-map
|
||||
this.fieldMap = EntityFinderUtil.makeFieldMap(element);
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityCondition getWhereEntityCondition(Map<String, Object> context, ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader) {
|
||||
// create the by and map
|
||||
Map<String, Object> entityContext = new HashMap<String, Object>();
|
||||
EntityFinderUtil.expandFieldMapToContext(this.fieldMap, context, entityContext);
|
||||
// then convert the types...
|
||||
modelEntity.convertFieldMapInPlace(entityContext, modelFieldTypeReader);
|
||||
return EntityCondition.makeCondition(entityContext);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.finder;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
import org.ofbiz.entity.finder.EntityFinderUtil.Condition;
|
||||
import org.ofbiz.entity.finder.EntityFinderUtil.ConditionExpr;
|
||||
import org.ofbiz.entity.finder.EntityFinderUtil.ConditionList;
|
||||
import org.ofbiz.entity.finder.EntityFinderUtil.ConditionObject;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelFieldTypeReader;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* Uses the delegator to find entity values by a condition
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class ByConditionFinder extends ListFinder {
|
||||
public static final String module = ByConditionFinder.class.getName();
|
||||
|
||||
protected Condition whereCondition;
|
||||
protected Condition havingCondition;
|
||||
|
||||
public ByConditionFinder(Element element) {
|
||||
super(element, "condition");
|
||||
|
||||
// NOTE: the whereCondition can be null, ie (condition-expr | condition-list) is optional; if left out, means find all, or with no condition in essense
|
||||
// process condition-expr | condition-list
|
||||
Element conditionExprElement = UtilXml.firstChildElement(element, "condition-expr");
|
||||
Element conditionListElement = UtilXml.firstChildElement(element, "condition-list");
|
||||
Element conditionObjectElement = UtilXml.firstChildElement(element, "condition-object");
|
||||
if (conditionExprElement != null) {
|
||||
this.whereCondition = new ConditionExpr(conditionExprElement);
|
||||
} else if (conditionListElement != null) {
|
||||
this.whereCondition = new ConditionList(conditionListElement);
|
||||
} else if (conditionObjectElement != null) {
|
||||
this.whereCondition = new ConditionObject(conditionObjectElement);
|
||||
}
|
||||
|
||||
Element havingConditionListElement = UtilXml.firstChildElement(element, "having-condition-list");
|
||||
if (havingConditionListElement != null) {
|
||||
this.havingCondition = new ConditionList(havingConditionListElement);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityCondition getWhereEntityCondition(Map<String, Object> context, ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader) {
|
||||
// create whereEntityCondition from whereCondition
|
||||
if (this.whereCondition != null) {
|
||||
return this.whereCondition.createCondition(context, modelEntity, modelFieldTypeReader);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityCondition getHavingEntityCondition(Map<String, Object> context, ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader) {
|
||||
// create havingEntityCondition from havingCondition
|
||||
if (this.havingCondition != null) {
|
||||
return this.havingCondition.createCondition(context, modelEntity, modelFieldTypeReader);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.finder;
|
||||
|
||||
import static org.ofbiz.base.util.UtilGenerics.cast;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.ObjectType;
|
||||
import org.ofbiz.base.util.StringUtil;
|
||||
import org.ofbiz.base.util.UtilGenerics;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.base.util.collections.FlexibleMapAccessor;
|
||||
import org.ofbiz.base.util.string.FlexibleStringExpander;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.condition.EntityComparisonOperator;
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
import org.ofbiz.entity.condition.EntityFunction;
|
||||
import org.ofbiz.entity.condition.EntityJoinOperator;
|
||||
import org.ofbiz.entity.condition.EntityOperator;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelFieldTypeReader;
|
||||
import org.ofbiz.entity.util.EntityListIterator;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* Uses the delegator to find entity values by a condition
|
||||
*
|
||||
*/
|
||||
public final class EntityFinderUtil {
|
||||
|
||||
public static final String module = EntityFinderUtil.class.getName();
|
||||
|
||||
private EntityFinderUtil () {}
|
||||
|
||||
public static Map<FlexibleMapAccessor<Object>, Object> makeFieldMap(Element element) {
|
||||
Map<FlexibleMapAccessor<Object>, Object> fieldMap = null;
|
||||
List<? extends Element> fieldMapElementList = UtilXml.childElementList(element, "field-map");
|
||||
if (fieldMapElementList.size() > 0) {
|
||||
fieldMap = new HashMap<FlexibleMapAccessor<Object>, Object>(fieldMapElementList.size());
|
||||
for (Element fieldMapElement: fieldMapElementList) {
|
||||
// set the env-name for each field-name, noting that if no field-name is specified it defaults to the env-name
|
||||
String fieldName = fieldMapElement.getAttribute("field-name");
|
||||
String envName = fieldMapElement.getAttribute("from-field");
|
||||
if (envName.isEmpty()) {
|
||||
envName = fieldMapElement.getAttribute("env-name");
|
||||
}
|
||||
String value = fieldMapElement.getAttribute("value");
|
||||
if (fieldName.isEmpty()) {
|
||||
// no fieldName, use envName for both
|
||||
fieldMap.put(FlexibleMapAccessor.getInstance(envName), FlexibleMapAccessor.getInstance(envName));
|
||||
} else {
|
||||
if (!value.isEmpty()) {
|
||||
fieldMap.put(FlexibleMapAccessor.getInstance(fieldName), FlexibleStringExpander.getInstance(value));
|
||||
} else {
|
||||
// at this point we have a fieldName and no value, do we have a envName?
|
||||
if (!envName.isEmpty()) {
|
||||
fieldMap.put(FlexibleMapAccessor.getInstance(fieldName), FlexibleMapAccessor.getInstance(envName));
|
||||
} else {
|
||||
// no envName, use fieldName for both
|
||||
fieldMap.put(FlexibleMapAccessor.getInstance(fieldName), FlexibleMapAccessor.getInstance(fieldName));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return fieldMap;
|
||||
}
|
||||
|
||||
public static void expandFieldMapToContext(Map<FlexibleMapAccessor<Object>, Object> fieldMap, Map<String, Object> context, Map<String, Object> outContext) {
|
||||
//Debug.logInfo("fieldMap: " + fieldMap, module);
|
||||
if (fieldMap != null) {
|
||||
for (Map.Entry<FlexibleMapAccessor<Object>, Object> entry: fieldMap.entrySet()) {
|
||||
FlexibleMapAccessor<Object> serviceContextFieldAcsr = entry.getKey();
|
||||
Object valueSrc = entry.getValue();
|
||||
if (valueSrc instanceof FlexibleMapAccessor<?>) {
|
||||
FlexibleMapAccessor<Object> contextEnvAcsr = cast(valueSrc);
|
||||
serviceContextFieldAcsr.put(outContext, contextEnvAcsr.get(context));
|
||||
} else if (valueSrc instanceof FlexibleStringExpander) {
|
||||
FlexibleStringExpander valueExdr = (FlexibleStringExpander) valueSrc;
|
||||
serviceContextFieldAcsr.put(outContext, valueExdr.expandString(context));
|
||||
} else {
|
||||
// hmmmm...
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static List<FlexibleStringExpander> makeSelectFieldExpanderList(Element element) {
|
||||
List<FlexibleStringExpander> selectFieldExpanderList = null;
|
||||
List<? extends Element> selectFieldElementList = UtilXml.childElementList(element, "select-field");
|
||||
if (selectFieldElementList.size() > 0) {
|
||||
selectFieldExpanderList = new ArrayList<FlexibleStringExpander>(selectFieldElementList.size());
|
||||
for (Element selectFieldElement: selectFieldElementList) {
|
||||
selectFieldExpanderList.add(FlexibleStringExpander.getInstance(selectFieldElement.getAttribute("field-name")));
|
||||
}
|
||||
}
|
||||
return selectFieldExpanderList;
|
||||
}
|
||||
|
||||
public static Set<String> makeFieldsToSelect(List<FlexibleStringExpander> selectFieldExpanderList, Map<String, Object> context) {
|
||||
Set<String> fieldsToSelect = null;
|
||||
if (UtilValidate.isNotEmpty(selectFieldExpanderList)) {
|
||||
fieldsToSelect = new HashSet<String>();
|
||||
for (FlexibleStringExpander selectFieldExpander: selectFieldExpanderList) {
|
||||
fieldsToSelect.add(selectFieldExpander.expandString(context));
|
||||
}
|
||||
}
|
||||
return fieldsToSelect;
|
||||
}
|
||||
|
||||
public static List<String> makeOrderByFieldList(List<FlexibleStringExpander> orderByExpanderList, Map<String, Object> context) {
|
||||
List<String> orderByFields = null;
|
||||
if (UtilValidate.isNotEmpty(orderByExpanderList)) {
|
||||
orderByFields = new ArrayList<String>(orderByExpanderList.size());
|
||||
for (FlexibleStringExpander orderByExpander: orderByExpanderList) {
|
||||
orderByFields.add(orderByExpander.expandString(context));
|
||||
}
|
||||
}
|
||||
return orderByFields;
|
||||
}
|
||||
|
||||
public static interface Condition extends Serializable {
|
||||
public EntityCondition createCondition(Map<String, ? extends Object> context, ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader);
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public static final class ConditionExpr implements Condition {
|
||||
private final String fieldName;
|
||||
private final EntityOperator<?,?,?> operator;
|
||||
private final FlexibleMapAccessor<Object> envNameAcsr;
|
||||
private final FlexibleStringExpander valueExdr;
|
||||
private final FlexibleStringExpander ignoreExdr;
|
||||
private final boolean ignoreIfNull;
|
||||
private final boolean ignoreIfEmpty;
|
||||
private final boolean ignoreCase;
|
||||
|
||||
public ConditionExpr(Element conditionExprElement) {
|
||||
String fieldNameAttribute = conditionExprElement.getAttribute("field-name");
|
||||
if (fieldNameAttribute.isEmpty()) {
|
||||
fieldNameAttribute = conditionExprElement.getAttribute("name");
|
||||
}
|
||||
this.fieldName = fieldNameAttribute;
|
||||
String operatorAttribute = conditionExprElement.getAttribute("operator");
|
||||
if (operatorAttribute.isEmpty()) {
|
||||
operatorAttribute = "equals";
|
||||
}
|
||||
this.operator = EntityOperator.lookup(operatorAttribute);
|
||||
if (this.operator == null) {
|
||||
throw new IllegalArgumentException("Could not find an entity operator for the name: " + operatorAttribute);
|
||||
}
|
||||
String fromFieldAttribute = conditionExprElement.getAttribute("from-field");
|
||||
if (fromFieldAttribute.isEmpty()) {
|
||||
fromFieldAttribute = conditionExprElement.getAttribute("env-name");
|
||||
}
|
||||
this.envNameAcsr = FlexibleMapAccessor.getInstance(fromFieldAttribute);
|
||||
this.valueExdr = FlexibleStringExpander.getInstance(conditionExprElement.getAttribute("value"));
|
||||
this.ignoreIfNull = "true".equals(conditionExprElement.getAttribute("ignore-if-null"));
|
||||
this.ignoreIfEmpty = "true".equals(conditionExprElement.getAttribute("ignore-if-empty"));
|
||||
this.ignoreCase = "true".equals(conditionExprElement.getAttribute("ignore-case"));
|
||||
this.ignoreExdr = FlexibleStringExpander.getInstance(conditionExprElement.getAttribute("ignore"));
|
||||
}
|
||||
|
||||
public EntityCondition createCondition(Map<String, ? extends Object> context, ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader) {
|
||||
if ("true".equals(this.ignoreExdr.expandString(context))) {
|
||||
return null;
|
||||
}
|
||||
if (modelEntity.getField(fieldName) == null) {
|
||||
throw new IllegalArgumentException("Error in Entity Find: could not find field [" + fieldName + "] in entity with name [" + modelEntity.getEntityName() + "]");
|
||||
}
|
||||
|
||||
Object value = envNameAcsr.get(context);
|
||||
if (value == null && !valueExdr.isEmpty()) {
|
||||
value = valueExdr.expandString(context);
|
||||
}
|
||||
if (this.ignoreIfNull && value == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// If IN or BETWEEN operator, see if value is a literal list and split it
|
||||
if ((operator.equals(EntityOperator.IN) || operator.equals(EntityOperator.BETWEEN) || operator.equals(EntityOperator.NOT_IN))
|
||||
&& value instanceof String) {
|
||||
String delim = null;
|
||||
if (((String)value).indexOf("|") >= 0) {
|
||||
delim = "|";
|
||||
} else if (((String)value).indexOf(",") >= 0) {
|
||||
delim = ",";
|
||||
}
|
||||
if (delim != null) {
|
||||
value = StringUtil.split((String)value, delim);
|
||||
}
|
||||
}
|
||||
|
||||
// don't convert the field to the desired type if this is an IN or BETWEEN operator and we have a Collection
|
||||
if (!((operator.equals(EntityOperator.IN) || operator.equals(EntityOperator.BETWEEN) || operator.equals(EntityOperator.NOT_IN))
|
||||
&& value instanceof Collection<?>)) {
|
||||
// now to a type conversion for the target fieldName
|
||||
value = modelEntity.convertFieldValue(modelEntity.getField(fieldName), value, modelFieldTypeReader, context);
|
||||
}
|
||||
|
||||
if (Debug.verboseOn()) Debug.logVerbose("Got value for fieldName [" + fieldName + "]: " + value, module);
|
||||
|
||||
if (this.ignoreIfEmpty && ObjectType.isEmpty(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (operator == EntityOperator.NOT_EQUAL && value != null) {
|
||||
// since some databases don't consider nulls in != comparisons, explicitly include them
|
||||
// this makes more sense logically, but if anyone ever needs it to not behave this way we should add an "or-null" attribute that is true by default
|
||||
if (ignoreCase) {
|
||||
return EntityCondition.makeCondition(
|
||||
EntityCondition.makeCondition(EntityFunction.UPPER_FIELD(fieldName), UtilGenerics.<EntityComparisonOperator<?,?>>cast(operator), EntityFunction.UPPER(value)),
|
||||
EntityOperator.OR,
|
||||
EntityCondition.makeCondition(fieldName, EntityOperator.EQUALS, null));
|
||||
} else {
|
||||
return EntityCondition.makeCondition(
|
||||
EntityCondition.makeCondition(fieldName, UtilGenerics.<EntityComparisonOperator<?,?>>cast(operator), value),
|
||||
EntityOperator.OR,
|
||||
EntityCondition.makeCondition(fieldName, EntityOperator.EQUALS, null));
|
||||
}
|
||||
} else {
|
||||
if (ignoreCase) {
|
||||
// use the stuff to upper case both sides
|
||||
return EntityCondition.makeCondition(EntityFunction.UPPER_FIELD(fieldName), UtilGenerics.<EntityComparisonOperator<?,?>>cast(operator), EntityFunction.UPPER(value));
|
||||
} else {
|
||||
return EntityCondition.makeCondition(fieldName, UtilGenerics.<EntityComparisonOperator<?,?>>cast(operator), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public static final class ConditionList implements Condition {
|
||||
private final List<Condition> conditionList;
|
||||
private final EntityOperator<?,?,?> operator;
|
||||
|
||||
public ConditionList(Element conditionListElement) {
|
||||
String operatorAttribute = conditionListElement.getAttribute("combine");
|
||||
if (operatorAttribute.isEmpty()) {
|
||||
operatorAttribute = "and";
|
||||
}
|
||||
this.operator = EntityOperator.lookup(operatorAttribute);
|
||||
if (this.operator == null) {
|
||||
throw new IllegalArgumentException("Could not find an entity operator for the name: " + operatorAttribute);
|
||||
}
|
||||
List<? extends Element> subElements = UtilXml.childElementList(conditionListElement);
|
||||
if (subElements.isEmpty()) {
|
||||
this.conditionList = null;
|
||||
} else {
|
||||
List<Condition> conditionList = new ArrayList<Condition>(subElements.size());
|
||||
for (Element subElement : subElements) {
|
||||
if ("condition-expr".equals(subElement.getNodeName())) {
|
||||
conditionList.add(new ConditionExpr(subElement));
|
||||
} else if ("condition-list".equals(subElement.getNodeName())) {
|
||||
conditionList.add(new ConditionList(subElement));
|
||||
} else if ("condition-object".equals(subElement.getNodeName())) {
|
||||
conditionList.add(new ConditionObject(subElement));
|
||||
} else {
|
||||
throw new IllegalArgumentException("Invalid element with name [" + subElement.getNodeName() + "] found under a condition-list element.");
|
||||
}
|
||||
}
|
||||
this.conditionList = Collections.unmodifiableList(conditionList);
|
||||
}
|
||||
}
|
||||
|
||||
public EntityCondition createCondition(Map<String, ? extends Object> context, ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader) {
|
||||
if (this.conditionList == null) {
|
||||
return null;
|
||||
}
|
||||
if (this.conditionList.size() == 1) {
|
||||
Condition condition = this.conditionList.get(0);
|
||||
return condition.createCondition(context, modelEntity, modelFieldTypeReader);
|
||||
}
|
||||
List<EntityCondition> entityConditionList = new ArrayList<EntityCondition>(this.conditionList.size());
|
||||
for (Condition curCondition: this.conditionList) {
|
||||
EntityCondition econd = curCondition.createCondition(context, modelEntity, modelFieldTypeReader);
|
||||
if (econd != null) {
|
||||
entityConditionList.add(econd);
|
||||
}
|
||||
}
|
||||
return EntityCondition.makeCondition(entityConditionList, UtilGenerics.<EntityJoinOperator>cast(operator));
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public static final class ConditionObject implements Condition {
|
||||
private final FlexibleMapAccessor<Object> fieldNameAcsr;
|
||||
|
||||
public ConditionObject(Element conditionExprElement) {
|
||||
String fieldNameAttribute = conditionExprElement.getAttribute("field");
|
||||
if (fieldNameAttribute.isEmpty()) {
|
||||
fieldNameAttribute = conditionExprElement.getAttribute("field-name");
|
||||
}
|
||||
this.fieldNameAcsr = FlexibleMapAccessor.getInstance(fieldNameAttribute);
|
||||
}
|
||||
|
||||
public EntityCondition createCondition(Map<String, ? extends Object> context, ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader) {
|
||||
return (EntityCondition) fieldNameAcsr.get(context);
|
||||
}
|
||||
}
|
||||
|
||||
public static interface OutputHandler extends Serializable {
|
||||
public void handleOutput(EntityListIterator eli, Map<String, Object> context, FlexibleMapAccessor<Object> listAcsr);
|
||||
public void handleOutput(List<GenericValue> results, Map<String, Object> context, FlexibleMapAccessor<Object> listAcsr);
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public static class LimitRange implements OutputHandler {
|
||||
FlexibleStringExpander startExdr;
|
||||
FlexibleStringExpander sizeExdr;
|
||||
|
||||
public LimitRange(Element limitRangeElement) {
|
||||
this.startExdr = FlexibleStringExpander.getInstance(limitRangeElement.getAttribute("start"));
|
||||
this.sizeExdr = FlexibleStringExpander.getInstance(limitRangeElement.getAttribute("size"));
|
||||
}
|
||||
|
||||
int getStart(Map<String, Object> context) {
|
||||
String startStr = this.startExdr.expandString(context);
|
||||
try {
|
||||
return Integer.parseInt(startStr);
|
||||
} catch (NumberFormatException e) {
|
||||
String errMsg = "The limit-range start number \"" + startStr + "\" was not valid: " + e.toString();
|
||||
Debug.logError(e, errMsg, module);
|
||||
throw new IllegalArgumentException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
int getSize(Map<String, Object> context) {
|
||||
String sizeStr = this.sizeExdr.expandString(context);
|
||||
try {
|
||||
return Integer.parseInt(sizeStr);
|
||||
} catch (NumberFormatException e) {
|
||||
String errMsg = "The limit-range size number \"" + sizeStr + "\" was not valid: " + e.toString();
|
||||
Debug.logError(e, errMsg, module);
|
||||
throw new IllegalArgumentException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
public void handleOutput(EntityListIterator eli, Map<String, Object> context, FlexibleMapAccessor<Object> listAcsr) {
|
||||
int start = getStart(context) + 1; // ELI index is one-based.
|
||||
int size = getSize(context);
|
||||
try {
|
||||
listAcsr.put(context, eli.getPartialList(start, size));
|
||||
eli.close();
|
||||
} catch (GenericEntityException e) {
|
||||
String errMsg = "Error getting partial list in limit-range with start=" + start + " and size=" + size + ": " + e.toString();
|
||||
Debug.logError(e, errMsg, module);
|
||||
throw new IllegalArgumentException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
public void handleOutput(List<GenericValue> results, Map<String, Object> context, FlexibleMapAccessor<Object> listAcsr) {
|
||||
List<GenericValue> result = null;
|
||||
int start = getStart(context);
|
||||
if (start < results.size()) {
|
||||
int size = getSize(context);
|
||||
int end = start + size;
|
||||
if (end > results.size()) {
|
||||
end = results.size();
|
||||
}
|
||||
result = results.subList(start, end);
|
||||
} else {
|
||||
result = new LinkedList<GenericValue>();
|
||||
}
|
||||
listAcsr.put(context, result);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public static class LimitView implements OutputHandler {
|
||||
FlexibleStringExpander viewIndexExdr;
|
||||
FlexibleStringExpander viewSizeExdr;
|
||||
|
||||
public LimitView(Element limitViewElement) {
|
||||
this.viewIndexExdr = FlexibleStringExpander.getInstance(limitViewElement.getAttribute("view-index"));
|
||||
this.viewSizeExdr = FlexibleStringExpander.getInstance(limitViewElement.getAttribute("view-size"));
|
||||
}
|
||||
|
||||
int getIndex(Map<String, Object> context) {
|
||||
String viewIndexStr = this.viewIndexExdr.expandString(context);
|
||||
try {
|
||||
return Integer.parseInt(viewIndexStr);
|
||||
} catch (NumberFormatException e) {
|
||||
String errMsg = "The limit-view view-index number \"" + viewIndexStr + "\" was not valid: " + e.toString();
|
||||
Debug.logError(e, errMsg, module);
|
||||
throw new IllegalArgumentException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
int getSize(Map<String, Object> context) {
|
||||
String viewSizeStr = this.viewSizeExdr.expandString(context);
|
||||
try {
|
||||
return Integer.parseInt(viewSizeStr);
|
||||
} catch (NumberFormatException e) {
|
||||
String errMsg = "The limit-view view-size number \"" + viewSizeStr + "\" was not valid: " + e.toString();
|
||||
Debug.logError(e, errMsg, module);
|
||||
throw new IllegalArgumentException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
public void handleOutput(EntityListIterator eli, Map<String, Object> context, FlexibleMapAccessor<Object> listAcsr) {
|
||||
int index = this.getIndex(context);
|
||||
int size = this.getSize(context);
|
||||
try {
|
||||
listAcsr.put(context, eli.getPartialList(((index - 1) * size) + 1, size)); // ELI index is one-based.
|
||||
eli.close();
|
||||
} catch (GenericEntityException e) {
|
||||
String errMsg = "Error getting partial list in limit-view with index=" + index + " and size=" + size + ": " + e.toString();
|
||||
Debug.logError(e, errMsg, module);
|
||||
throw new IllegalArgumentException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
public void handleOutput(List<GenericValue> results, Map<String, Object> context, FlexibleMapAccessor<Object> listAcsr) {
|
||||
List<GenericValue> result = null;
|
||||
int index = this.getIndex(context);
|
||||
int size = this.getSize(context);
|
||||
int begin = (index - 1) * size;
|
||||
if (begin < results.size()) {
|
||||
int end = begin + size;
|
||||
if (end > results.size()) {
|
||||
end = results.size();
|
||||
}
|
||||
result = results.subList(begin, end);
|
||||
} else {
|
||||
result = new LinkedList<GenericValue>();
|
||||
}
|
||||
listAcsr.put(context, result);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public static class UseIterator implements OutputHandler {
|
||||
public UseIterator(Element useIteratorElement) {
|
||||
// no parameters, nothing to do
|
||||
}
|
||||
|
||||
public void handleOutput(EntityListIterator eli, Map<String, Object> context, FlexibleMapAccessor<Object> listAcsr) {
|
||||
listAcsr.put(context, eli);
|
||||
}
|
||||
|
||||
public void handleOutput(List<GenericValue> results, Map<String, Object> context, FlexibleMapAccessor<Object> listAcsr) {
|
||||
throw new IllegalArgumentException("Cannot handle output with use-iterator when the query is cached, or the result in general is not an EntityListIterator");
|
||||
}
|
||||
}
|
||||
@SuppressWarnings("serial")
|
||||
public static class GetAll implements OutputHandler {
|
||||
public GetAll() {
|
||||
// no parameters, nothing to do
|
||||
}
|
||||
|
||||
public void handleOutput(EntityListIterator eli, Map<String, Object> context, FlexibleMapAccessor<Object> listAcsr) {
|
||||
try {
|
||||
listAcsr.put(context, eli.getCompleteList());
|
||||
eli.close();
|
||||
} catch (GenericEntityException e) {
|
||||
String errorMsg = "Error getting list from EntityListIterator: " + e.toString();
|
||||
Debug.logError(e, errorMsg, module);
|
||||
throw new IllegalArgumentException(errorMsg);
|
||||
}
|
||||
}
|
||||
|
||||
public void handleOutput(List<GenericValue> results, Map<String, Object> context, FlexibleMapAccessor<Object> listAcsr) {
|
||||
listAcsr.put(context, results);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.finder;
|
||||
|
||||
import java.util.Map;
|
||||
import java.io.Serializable;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import org.ofbiz.base.util.GeneralException;
|
||||
import org.ofbiz.base.util.string.FlexibleStringExpander;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public abstract class Finder implements Serializable {
|
||||
protected FlexibleStringExpander entityNameExdr;
|
||||
protected FlexibleStringExpander useCacheStrExdr;
|
||||
|
||||
protected Finder(Element element) {
|
||||
this.entityNameExdr = FlexibleStringExpander.getInstance(element.getAttribute("entity-name"));
|
||||
this.useCacheStrExdr = FlexibleStringExpander.getInstance(element.getAttribute("use-cache"));
|
||||
}
|
||||
|
||||
public String getEntityName() {
|
||||
String entName = this.entityNameExdr.getOriginal();
|
||||
// if there is expansion syntax
|
||||
if (entName.indexOf("${") >= 0) return null;
|
||||
return entName;
|
||||
}
|
||||
|
||||
public void setEntityName(String entityName) {
|
||||
this.entityNameExdr = FlexibleStringExpander.getInstance(entityName);
|
||||
}
|
||||
|
||||
public abstract void runFind(Map<String, Object> context, Delegator delegator) throws GeneralException;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.finder;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.GeneralException;
|
||||
import org.ofbiz.base.util.UtilMisc;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.base.util.UtilXml;
|
||||
import org.ofbiz.base.util.collections.FlexibleMapAccessor;
|
||||
import org.ofbiz.base.util.string.FlexibleStringExpander;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.DelegatorFactory;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.condition.EntityCondition;
|
||||
import org.ofbiz.entity.finder.EntityFinderUtil.GetAll;
|
||||
import org.ofbiz.entity.finder.EntityFinderUtil.LimitRange;
|
||||
import org.ofbiz.entity.finder.EntityFinderUtil.LimitView;
|
||||
import org.ofbiz.entity.finder.EntityFinderUtil.OutputHandler;
|
||||
import org.ofbiz.entity.finder.EntityFinderUtil.UseIterator;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelFieldTypeReader;
|
||||
import org.ofbiz.entity.transaction.TransactionUtil;
|
||||
import org.ofbiz.entity.util.EntityFindOptions;
|
||||
import org.ofbiz.entity.util.EntityListIterator;
|
||||
import org.ofbiz.entity.util.EntityUtil;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* Uses the delegator to find entity values by a and
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public abstract class ListFinder extends Finder {
|
||||
public static final String module = ListFinder.class.getName();
|
||||
|
||||
protected String label;
|
||||
|
||||
protected FlexibleStringExpander filterByDateStrExdr;
|
||||
protected FlexibleStringExpander distinctStrExdr;
|
||||
protected FlexibleStringExpander delegatorNameExdr;
|
||||
protected FlexibleMapAccessor<Object> listAcsr;
|
||||
protected FlexibleStringExpander resultSetTypeExdr;
|
||||
|
||||
protected List<FlexibleStringExpander> selectFieldExpanderList;
|
||||
protected List<FlexibleStringExpander> orderByExpanderList;
|
||||
protected OutputHandler outputHandler;
|
||||
|
||||
protected ListFinder(Element element, String label) {
|
||||
super(element);
|
||||
this.label = label;
|
||||
|
||||
this.filterByDateStrExdr = FlexibleStringExpander.getInstance(element.getAttribute("filter-by-date"));
|
||||
this.distinctStrExdr = FlexibleStringExpander.getInstance(element.getAttribute("distinct"));
|
||||
this.delegatorNameExdr = FlexibleStringExpander.getInstance(element.getAttribute("delegator-name"));
|
||||
if (UtilValidate.isNotEmpty(element.getAttribute("list"))) {
|
||||
this.listAcsr = FlexibleMapAccessor.getInstance(element.getAttribute("list"));
|
||||
} else {
|
||||
this.listAcsr = FlexibleMapAccessor.getInstance(element.getAttribute("list-name"));
|
||||
}
|
||||
this.resultSetTypeExdr = FlexibleStringExpander.getInstance(element.getAttribute("result-set-type"));
|
||||
|
||||
// process select-field
|
||||
selectFieldExpanderList = EntityFinderUtil.makeSelectFieldExpanderList(element);
|
||||
|
||||
// process order-by
|
||||
List<? extends Element> orderByElementList = UtilXml.childElementList(element, "order-by");
|
||||
if (orderByElementList.size() > 0) {
|
||||
orderByExpanderList = new ArrayList<FlexibleStringExpander>(orderByElementList.size());
|
||||
for (Element orderByElement: orderByElementList) {
|
||||
orderByExpanderList.add(FlexibleStringExpander.getInstance(orderByElement.getAttribute("field-name")));
|
||||
}
|
||||
}
|
||||
|
||||
// process limit-range | limit-view | use-iterator
|
||||
Element limitRangeElement = UtilXml.firstChildElement(element, "limit-range");
|
||||
Element limitViewElement = UtilXml.firstChildElement(element, "limit-view");
|
||||
Element useIteratorElement = UtilXml.firstChildElement(element, "use-iterator");
|
||||
if ((limitRangeElement != null && limitViewElement != null) || (limitRangeElement != null && useIteratorElement != null) || (limitViewElement != null && useIteratorElement != null)) {
|
||||
throw new IllegalArgumentException("In entity find by " + label + " element, cannot have more than one of the following: limit-range, limit-view, " + label + " use-iterator");
|
||||
}
|
||||
if (limitRangeElement != null) {
|
||||
outputHandler = new LimitRange(limitRangeElement);
|
||||
} else if (limitViewElement != null) {
|
||||
outputHandler = new LimitView(limitViewElement);
|
||||
} else if (useIteratorElement != null) {
|
||||
outputHandler = new UseIterator(useIteratorElement);
|
||||
} else {
|
||||
// default to get all
|
||||
outputHandler = new GetAll();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runFind(Map<String, Object> context, Delegator delegator) throws GeneralException {
|
||||
String entityName = this.entityNameExdr.expandString(context);
|
||||
String useCacheStr = this.useCacheStrExdr.expandString(context);
|
||||
String filterByDateStr = this.filterByDateStrExdr.expandString(context);
|
||||
String distinctStr = this.distinctStrExdr.expandString(context);
|
||||
String delegatorName = this.delegatorNameExdr.expandString(context);
|
||||
ModelEntity modelEntity = delegator.getModelEntity(entityName);
|
||||
String resultSetTypeString = this.resultSetTypeExdr.expandString(context);
|
||||
|
||||
if (modelEntity == null) {
|
||||
throw new IllegalArgumentException("In find entity by " + label + " could not find definition for entity with name [" + entityName + "].");
|
||||
}
|
||||
|
||||
boolean useCache = "true".equals(useCacheStr);
|
||||
boolean filterByDate = "true".equals(filterByDateStr);
|
||||
boolean distinct = "true".equals(distinctStr);
|
||||
int resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
|
||||
if ("forward".equals(resultSetTypeString))
|
||||
resultSetType = ResultSet.TYPE_FORWARD_ONLY;
|
||||
|
||||
if (UtilValidate.isNotEmpty(delegatorName)) {
|
||||
delegator = DelegatorFactory.getDelegator(delegatorName);
|
||||
}
|
||||
|
||||
EntityCondition whereEntityCondition = getWhereEntityCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity));
|
||||
EntityCondition havingEntityCondition = getHavingEntityCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity));
|
||||
if (useCache) {
|
||||
// if useCache == true && outputHandler instanceof UseIterator, throw exception; not a valid combination
|
||||
if (outputHandler instanceof UseIterator) {
|
||||
Debug.logWarning("In find entity by " + label + " cannot have use-cache set to true " + label + " select use-iterator for the output type. Using cache and ignoring use-iterator setting.", module);
|
||||
outputHandler = new GetAll();
|
||||
}
|
||||
if (distinct) {
|
||||
throw new IllegalArgumentException("In find entity by " + label + " cannot have use-cache set to true " + label + " set distinct to true.");
|
||||
}
|
||||
if (havingEntityCondition != null) {
|
||||
throw new IllegalArgumentException("In find entity by " + label + " cannot have use-cache set to true and specify a having-condition-list (can only use a where condition with condition-expr or condition-list).");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// get the list of fieldsToSelect from selectFieldExpanderList
|
||||
Set<String> fieldsToSelect = EntityFinderUtil.makeFieldsToSelect(selectFieldExpanderList, context);
|
||||
|
||||
//if fieldsToSelect != null and useCacheBool is true, throw an error
|
||||
if (fieldsToSelect != null && useCache) {
|
||||
throw new IllegalArgumentException("Error in entity query by " + label + " definition, cannot specify select-field elements when use-cache is set to true");
|
||||
}
|
||||
|
||||
// get the list of orderByFields from orderByExpanderList
|
||||
List<String> orderByFields = EntityFinderUtil.makeOrderByFieldList(this.orderByExpanderList, context);
|
||||
|
||||
try {
|
||||
// if filterByDate, do a date filter on the results based on the now-timestamp
|
||||
if (filterByDate && !useCache) {
|
||||
EntityCondition filterByDateCondition = EntityUtil.getFilterByDateExpr();
|
||||
if (whereEntityCondition != null) {
|
||||
whereEntityCondition = EntityCondition.makeCondition(UtilMisc.toList(whereEntityCondition, filterByDateCondition));
|
||||
} else {
|
||||
whereEntityCondition = filterByDateCondition;
|
||||
}
|
||||
}
|
||||
|
||||
if (useCache) {
|
||||
List<GenericValue> results = delegator.findList(entityName, whereEntityCondition, fieldsToSelect, orderByFields, null, true);
|
||||
if (filterByDate) {
|
||||
results = EntityUtil.filterByDate(results);
|
||||
}
|
||||
this.outputHandler.handleOutput(results, context, listAcsr);
|
||||
} else {
|
||||
boolean useTransaction = true;
|
||||
if (this.outputHandler instanceof UseIterator && !TransactionUtil.isTransactionInPlace()) {
|
||||
Exception newE = new Exception("Stack Trace");
|
||||
Debug.logError(newE, "ERROR: Cannot do a by " + label + " find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", module);
|
||||
useTransaction = false;
|
||||
}
|
||||
|
||||
EntityFindOptions options = new EntityFindOptions();
|
||||
options.setDistinct(distinct);
|
||||
options.setResultSetType(resultSetType);
|
||||
if (outputHandler instanceof LimitRange) {
|
||||
LimitRange limitRange = (LimitRange) outputHandler;
|
||||
int start = limitRange.getStart(context);
|
||||
int size = limitRange.getSize(context);
|
||||
options.setMaxRows(start + size);
|
||||
} else if (outputHandler instanceof LimitView) {
|
||||
LimitView limitView = (LimitView) outputHandler;
|
||||
int index = limitView.getIndex(context);
|
||||
int size = limitView.getSize(context);
|
||||
options.setMaxRows(size * (index + 1));
|
||||
}
|
||||
boolean beganTransaction = false;
|
||||
try {
|
||||
if (useTransaction) {
|
||||
beganTransaction = TransactionUtil.begin();
|
||||
}
|
||||
|
||||
EntityListIterator eli = delegator.find(entityName, whereEntityCondition, havingEntityCondition, fieldsToSelect, orderByFields, options);
|
||||
this.outputHandler.handleOutput(eli, context, listAcsr);
|
||||
} catch (GenericEntityException e) {
|
||||
String errMsg = "Failure in by " + label + " find operation, rolling back transaction";
|
||||
Debug.logError(e, errMsg, module);
|
||||
try {
|
||||
// only rollback the transaction if we started one...
|
||||
TransactionUtil.rollback(beganTransaction, errMsg, e);
|
||||
} catch (GenericEntityException e2) {
|
||||
Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
|
||||
}
|
||||
// after rolling back, rethrow the exception
|
||||
throw e;
|
||||
} finally {
|
||||
// only commit the transaction if we started one... this will throw an exception if it fails
|
||||
TransactionUtil.commit(beganTransaction);
|
||||
}
|
||||
}
|
||||
} catch (GenericEntityException e) {
|
||||
String errMsg = "Error doing find by " + label + ": " + e.toString();
|
||||
Debug.logError(e, module);
|
||||
throw new GeneralException(errMsg, e);
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> getOrderByFieldList(Map<String, Object> context) {
|
||||
List<String> orderByFields = EntityFinderUtil.makeOrderByFieldList(this.orderByExpanderList, context);
|
||||
return orderByFields;
|
||||
}
|
||||
|
||||
public EntityCondition getWhereEntityCondition(Map<String, Object> context, ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public EntityCondition getHavingEntityCondition(Map<String, Object> context, ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.ofbiz.entity.finder;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.base.util.GeneralException;
|
||||
import org.ofbiz.base.util.UtilValidate;
|
||||
import org.ofbiz.base.util.collections.FlexibleMapAccessor;
|
||||
import org.ofbiz.base.util.string.FlexibleStringExpander;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.GenericPK;
|
||||
import org.ofbiz.entity.GenericValue;
|
||||
import org.ofbiz.entity.model.ModelEntity;
|
||||
import org.ofbiz.entity.model.ModelField;
|
||||
import org.ofbiz.entity.util.EntityQuery;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* Uses the delegator to find entity values by a condition
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class PrimaryKeyFinder extends Finder {
|
||||
public static final String module = PrimaryKeyFinder.class.getName();
|
||||
|
||||
protected FlexibleMapAccessor<Object> valueNameAcsr;
|
||||
protected FlexibleStringExpander autoFieldMapExdr;
|
||||
protected Map<FlexibleMapAccessor<Object>, Object> fieldMap;
|
||||
protected List<FlexibleStringExpander> selectFieldExpanderList;
|
||||
|
||||
public PrimaryKeyFinder(Element entityOneElement) {
|
||||
super(entityOneElement);
|
||||
if (UtilValidate.isNotEmpty(entityOneElement.getAttribute("value-field"))) {
|
||||
this.valueNameAcsr = FlexibleMapAccessor.getInstance(entityOneElement.getAttribute("value-field"));
|
||||
} else {
|
||||
this.valueNameAcsr = FlexibleMapAccessor.getInstance(entityOneElement.getAttribute("value-name"));
|
||||
}
|
||||
this.autoFieldMapExdr = FlexibleStringExpander.getInstance(entityOneElement.getAttribute("auto-field-map"));
|
||||
|
||||
// process field-map
|
||||
this.fieldMap = EntityFinderUtil.makeFieldMap(entityOneElement);
|
||||
|
||||
// process select-field
|
||||
selectFieldExpanderList = EntityFinderUtil.makeSelectFieldExpanderList(entityOneElement);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runFind(Map<String, Object> context, Delegator delegator) throws GeneralException {
|
||||
String entityName = this.entityNameExdr.expandString(context);
|
||||
|
||||
String useCacheString = this.useCacheStrExdr.expandString(context);
|
||||
// default to false
|
||||
boolean useCacheBool = "true".equals(useCacheString);
|
||||
|
||||
String autoFieldMapString = this.autoFieldMapExdr.expandString(context);
|
||||
// default to true
|
||||
boolean autoFieldMapBool = !"false".equals(autoFieldMapString);
|
||||
|
||||
ModelEntity modelEntity = delegator.getModelEntity(entityName);
|
||||
if (modelEntity == null) {
|
||||
throw new IllegalArgumentException("No entity definition found for entity name [" + entityName + "]");
|
||||
}
|
||||
|
||||
GenericValue valueOut = runFind(modelEntity, context, delegator, useCacheBool, autoFieldMapBool, this.fieldMap, this.selectFieldExpanderList);
|
||||
|
||||
//Debug.logInfo("PrimaryKeyFinder: valueOut=" + valueOut, module);
|
||||
//Debug.logInfo("PrimaryKeyFinder: going into=" + this.valueNameAcsr.getOriginalName(), module);
|
||||
if (!valueNameAcsr.isEmpty()) {
|
||||
this.valueNameAcsr.put(context, valueOut);
|
||||
} else {
|
||||
if (valueOut != null) {
|
||||
context.putAll(valueOut);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static GenericValue runFind(ModelEntity modelEntity, Map<String, Object> context, Delegator delegator, boolean useCache, boolean autoFieldMap,
|
||||
Map<FlexibleMapAccessor<Object>, Object> fieldMap, List<FlexibleStringExpander> selectFieldExpanderList) throws GeneralException {
|
||||
|
||||
// assemble the field map
|
||||
Map<String, Object> entityContext = new HashMap<String, Object>();
|
||||
if (autoFieldMap) {
|
||||
// try a map called "parameters", try it first so values from here are overridden by values in the main context
|
||||
Object parametersObj = context.get("parameters");
|
||||
Boolean parametersObjExists = parametersObj != null && parametersObj instanceof Map<?, ?>;
|
||||
// only need PK fields
|
||||
Iterator<ModelField> iter = modelEntity.getPksIterator();
|
||||
while (iter.hasNext()) {
|
||||
ModelField curField = iter.next();
|
||||
String fieldName = curField.getName();
|
||||
Object fieldValue = null;
|
||||
if (parametersObjExists) {
|
||||
fieldValue = ((Map<?, ?>) parametersObj).get(fieldName);
|
||||
}
|
||||
if (context.containsKey(fieldName)) {
|
||||
fieldValue = context.get(fieldName);
|
||||
}
|
||||
entityContext.put(fieldName, fieldValue);
|
||||
}
|
||||
}
|
||||
EntityFinderUtil.expandFieldMapToContext(fieldMap, context, entityContext);
|
||||
//Debug.logInfo("PrimaryKeyFinder: entityContext=" + entityContext, module);
|
||||
// then convert the types...
|
||||
|
||||
// need the timeZone and locale for conversion, so add here and remove after
|
||||
entityContext.put("locale", context.get("locale"));
|
||||
entityContext.put("timeZone", context.get("timeZone"));
|
||||
modelEntity.convertFieldMapInPlace(entityContext, delegator);
|
||||
entityContext.remove("locale");
|
||||
entityContext.remove("timeZone");
|
||||
|
||||
// get the list of fieldsToSelect from selectFieldExpanderList
|
||||
Set<String> fieldsToSelect = EntityFinderUtil.makeFieldsToSelect(selectFieldExpanderList, context);
|
||||
|
||||
//if fieldsToSelect != null and useCacheBool is true, throw an error
|
||||
if (fieldsToSelect != null && useCache) {
|
||||
throw new IllegalArgumentException("Error in entity-one definition, cannot specify select-field elements when use-cache is set to true");
|
||||
}
|
||||
|
||||
try {
|
||||
GenericValue valueOut = null;
|
||||
GenericPK entityPK = delegator.makePK(modelEntity.getEntityName(), entityContext);
|
||||
|
||||
// make sure we have a full primary key, if any field is null then just log a warning and return null instead of blowing up
|
||||
if (entityPK.containsPrimaryKey(true)) {
|
||||
if (useCache) {
|
||||
valueOut = EntityQuery.use(delegator).from(entityPK.getEntityName()).where(entityPK).cache(true).queryOne();
|
||||
} else {
|
||||
if (fieldsToSelect != null) {
|
||||
valueOut = delegator.findByPrimaryKeyPartial(entityPK, fieldsToSelect);
|
||||
} else {
|
||||
valueOut = EntityQuery.use(delegator).from(entityPK.getEntityName()).where(entityPK).cache(false).queryOne();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (Debug.infoOn()) Debug.logInfo("Returning null because found incomplete primary key in find: " + entityPK, module);
|
||||
}
|
||||
|
||||
return valueOut;
|
||||
} catch (GenericEntityException e) {
|
||||
String errMsg = "Error finding entity value by primary key with entity-one: " + e.toString();
|
||||
Debug.logError(e, errMsg, module);
|
||||
throw new GeneralException(errMsg, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.jdbc;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
public abstract class AbstractCursorHandler implements InvocationHandler {
|
||||
|
||||
protected String cursorName;
|
||||
protected int fetchSize;
|
||||
|
||||
protected AbstractCursorHandler(String cursorName, int fetchSize) {
|
||||
this.cursorName = cursorName;
|
||||
this.fetchSize = fetchSize;
|
||||
}
|
||||
|
||||
public void setCursorName(String cursorName) {
|
||||
this.cursorName = cursorName;
|
||||
}
|
||||
|
||||
public String getCursorName() {
|
||||
return cursorName;
|
||||
}
|
||||
|
||||
public void setFetchSize(int fetchSize) {
|
||||
this.fetchSize = fetchSize;
|
||||
}
|
||||
|
||||
public int getFetchSize() {
|
||||
return fetchSize;
|
||||
}
|
||||
|
||||
protected Object invoke(Object obj, Object proxy, Method method, Object... args) throws Throwable {
|
||||
if ("toString".equals(method.getName())) {
|
||||
String str = obj.toString();
|
||||
return getClass().getName() + "{" + str + "}";
|
||||
}
|
||||
return method.invoke(obj, args);
|
||||
}
|
||||
|
||||
protected static <T> T newHandler(InvocationHandler handler, Class<T> implClass) throws IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException {
|
||||
ClassLoader loader = implClass.getClassLoader();
|
||||
if (loader == null) loader = ClassLoader.getSystemClassLoader();
|
||||
Class<?> proxyClass = Proxy.getProxyClass(loader, implClass);
|
||||
Constructor<?> constructor = proxyClass.getConstructor(InvocationHandler.class);
|
||||
return implClass.cast(constructor.newInstance(handler));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.jdbc;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.entity.config.model.EntityConfig;
|
||||
import org.ofbiz.entity.connection.ConnectionFactory;
|
||||
|
||||
/**
|
||||
* ConnectionFactoryLoader - utility class that loads the connection manager and provides to client code a reference to it (ConnectionFactory)
|
||||
*
|
||||
*/
|
||||
public class ConnectionFactoryLoader {
|
||||
// Debug module name
|
||||
public static final String module = ConnectionFactoryLoader.class.getName();
|
||||
private static final ConnectionFactory connFactory = createConnectionFactory();
|
||||
|
||||
private static ConnectionFactory createConnectionFactory() {
|
||||
ConnectionFactory instance = null;
|
||||
try {
|
||||
if (EntityConfig.getInstance().getConnectionFactory() == null) {
|
||||
return null;
|
||||
}
|
||||
String className = EntityConfig.getInstance().getConnectionFactory().getClassName();
|
||||
if (className == null) {
|
||||
throw new IllegalStateException("Could not find connection factory class name definition");
|
||||
}
|
||||
ClassLoader loader = Thread.currentThread().getContextClassLoader();
|
||||
Class<?> tfClass = loader.loadClass(className);
|
||||
instance = (ConnectionFactory) tfClass.newInstance();
|
||||
} catch (ClassNotFoundException cnfe) {
|
||||
Debug.logError(cnfe, "Could not find connection factory class", module);
|
||||
} catch (Exception e) {
|
||||
Debug.logError(e, "Unable to instantiate the connection factory", module);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static ConnectionFactory getInstance() {
|
||||
if (connFactory == null) {
|
||||
throw new IllegalStateException("The Connection Factory is not initialized.");
|
||||
}
|
||||
return connFactory;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.jdbc;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.Statement;
|
||||
|
||||
|
||||
public class CursorConnection extends AbstractCursorHandler {
|
||||
|
||||
public static Connection newCursorConnection(Connection con, String cursorName, int pageSize) throws Exception {
|
||||
return newHandler(new CursorConnection(con, cursorName, pageSize), Connection.class);
|
||||
}
|
||||
|
||||
protected Connection con;
|
||||
|
||||
protected CursorConnection(Connection con, String cursorName, int fetchSize) {
|
||||
super(cursorName, fetchSize);
|
||||
this.con = con;
|
||||
}
|
||||
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
if (method.getName().equals("prepareStatement")) {
|
||||
System.err.println("prepareStatement");
|
||||
args[0] = "DECLARE " + cursorName + " CURSOR FOR " + args[0];
|
||||
PreparedStatement pstmt = (PreparedStatement) method.invoke(con, args);
|
||||
return CursorStatement.newCursorPreparedStatement(pstmt, cursorName, fetchSize);
|
||||
} else if (method.getName().equals("createStatement")) {
|
||||
System.err.println("createStatement");
|
||||
Statement stmt = (Statement) method.invoke(con, args);
|
||||
return CursorStatement.newCursorStatement(stmt, cursorName, fetchSize);
|
||||
}
|
||||
return super.invoke(con, proxy, method, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.jdbc;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
|
||||
public class CursorResultSet extends AbstractCursorHandler {
|
||||
|
||||
protected ResultSet rs;
|
||||
protected Statement stmt;
|
||||
protected String query;
|
||||
|
||||
protected CursorResultSet(Statement stmt, String cursorName, int fetchSize) throws SQLException {
|
||||
super(cursorName, fetchSize);
|
||||
this.stmt = stmt;
|
||||
query = "FETCH FORWARD " + fetchSize + " IN " + cursorName;
|
||||
System.err.println("executing page fetch(1)");
|
||||
rs = stmt.executeQuery(query);
|
||||
}
|
||||
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
if ("close".equals(method.getName())) {
|
||||
close();
|
||||
return null;
|
||||
} else if ("next".equals(method.getName())) {
|
||||
return next() ? Boolean.TRUE : Boolean.FALSE;
|
||||
}
|
||||
return super.invoke(rs, proxy, method, args);
|
||||
}
|
||||
|
||||
protected boolean next() throws SQLException {
|
||||
if (rs.next()) return true;
|
||||
System.err.println("executing page fetch(2)");
|
||||
rs = stmt.executeQuery(query);
|
||||
return rs.next();
|
||||
}
|
||||
|
||||
protected void close() throws SQLException {
|
||||
stmt.executeUpdate("CLOSE " + cursorName);
|
||||
rs.close();
|
||||
}
|
||||
|
||||
public static ResultSet newCursorResultSet(Statement stmt, String cursorName, int fetchSize) throws SQLException, Exception {
|
||||
return newHandler(new CursorResultSet(stmt, cursorName, fetchSize), ResultSet.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.jdbc;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import org.ofbiz.entity.transaction.GenericTransactionException;
|
||||
import org.ofbiz.entity.transaction.TransactionUtil;
|
||||
|
||||
|
||||
public class CursorStatement extends AbstractCursorHandler {
|
||||
|
||||
protected ResultSet currentResultSet;
|
||||
protected Statement stmt;
|
||||
protected boolean beganTransaction;
|
||||
protected boolean autoCommit;
|
||||
|
||||
protected CursorStatement(Statement stmt, String cursorName, int fetchSize) throws GenericTransactionException, SQLException {
|
||||
super(cursorName, fetchSize);
|
||||
this.stmt = stmt;
|
||||
beganTransaction = TransactionUtil.begin();
|
||||
autoCommit = stmt.getConnection().getAutoCommit();
|
||||
stmt.getConnection().setAutoCommit(false);
|
||||
System.err.println("beganTransaction=" + beganTransaction + ", autoCommit=" + autoCommit);
|
||||
}
|
||||
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
if ("close".equals(method.getName())) {
|
||||
stmt.getConnection().setAutoCommit(autoCommit);
|
||||
TransactionUtil.commit(beganTransaction);
|
||||
stmt.close();
|
||||
return null;
|
||||
} else if ("execute".equals(method.getName())) {
|
||||
} else if ("executeQuery".equals(method.getName()) && args == null) {
|
||||
PreparedStatement pstmt = (PreparedStatement) stmt;
|
||||
pstmt.executeUpdate();
|
||||
currentResultSet = CursorResultSet.newCursorResultSet(stmt, cursorName, fetchSize);
|
||||
return currentResultSet;
|
||||
} else if ("executeQuery".equals(method.getName()) && args != null) {
|
||||
args[0] = "DECLARE " + cursorName + " CURSOR FOR " + args[0];
|
||||
System.err.println("query=" + args[0]);
|
||||
if (stmt.execute((String) args[0])) {
|
||||
throw new SQLException("DECLARE returned a ResultSet");
|
||||
}
|
||||
currentResultSet = CursorResultSet.newCursorResultSet(stmt, cursorName, fetchSize);
|
||||
return currentResultSet;
|
||||
} else if ("getMoreResults".equals(method.getName())) {
|
||||
boolean hasMoreResults = stmt.getMoreResults();
|
||||
if (hasMoreResults) {
|
||||
currentResultSet = stmt.getResultSet();
|
||||
} else {
|
||||
currentResultSet = null;
|
||||
}
|
||||
return hasMoreResults ? Boolean.TRUE : Boolean.FALSE;
|
||||
} else if ("getResultSet".equals(method.getName())) {
|
||||
return currentResultSet;
|
||||
} else if ("getCursorName".equals(method.getName())) {
|
||||
return getCursorName();
|
||||
} else if ("setCursorName".equals(method.getName())) {
|
||||
setCursorName((String) args[0]);
|
||||
} else if ("getFetchSize".equals(method.getName())) {
|
||||
return Integer.valueOf(getFetchSize());
|
||||
} else if ("setFetchSize".equals(method.getName())) {
|
||||
setFetchSize(((Integer) args[0]).intValue());
|
||||
}
|
||||
return super.invoke(stmt, proxy, method, args);
|
||||
}
|
||||
|
||||
public static Statement newCursorStatement(Statement stmt, String cursorName, int fetchSize) throws Exception {
|
||||
return newHandler(new CursorStatement(stmt, cursorName, fetchSize), Statement.class);
|
||||
}
|
||||
|
||||
public static PreparedStatement newCursorPreparedStatement(PreparedStatement pstmt, String cursorName, int fetchSize) throws Exception {
|
||||
return newHandler(new CursorStatement(pstmt, cursorName, fetchSize), PreparedStatement.class);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,26 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.jdbc;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public interface ExecQueryCallbackFunctionIF {
|
||||
public boolean processNextRow(ResultSet rs) throws SQLException;
|
||||
}
|
||||
@@ -0,0 +1,803 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.jdbc;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Reader;
|
||||
import java.sql.Blob;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Timestamp;
|
||||
import java.sql.Types;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.sql.rowset.serial.SerialBlob;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
|
||||
/**
|
||||
* An object that handles getting/setting column values in JDBC
|
||||
* <code>PreparedStatement</code> and <code>ResultSet</code> objects.
|
||||
*
|
||||
*/
|
||||
public abstract class JdbcValueHandler<T> {
|
||||
public static final String module = JdbcValueHandler.class.getName();
|
||||
private static final Map<String, JdbcValueHandler<?>> JdbcValueHandlerMap = createJdbcValueHandlerMap();
|
||||
private static final Map<String, Integer> SqlTypeMap = createSqlTypeMap();
|
||||
|
||||
private static Map<String, JdbcValueHandler<?>> createJdbcValueHandlerMap() {
|
||||
/*
|
||||
This Map is used to select the correct JdbcValueHandler
|
||||
for the specified Java type. The JdbcValueHandler instances are
|
||||
initialized with the SQL type recommended by Sun/Oracle.
|
||||
*/
|
||||
Map<String, JdbcValueHandler<?>> result = new HashMap<String, JdbcValueHandler<?>>();
|
||||
// JDBC 1
|
||||
result.put("Array", new ArrayJdbcValueHandler(Types.ARRAY));
|
||||
result.put("java.sql.Array", new ArrayJdbcValueHandler(Types.ARRAY));
|
||||
result.put("byte[]", new ByteArrayJdbcValueHandler(Types.LONGVARBINARY));
|
||||
result.put("java.lang.Boolean", new BooleanJdbcValueHandler(Types.BOOLEAN));
|
||||
result.put("Boolean", new BooleanJdbcValueHandler(Types.BOOLEAN));
|
||||
result.put("java.lang.Double", new DoubleJdbcValueHandler(Types.DOUBLE));
|
||||
result.put("Double", new DoubleJdbcValueHandler(Types.DOUBLE));
|
||||
result.put("java.lang.Float", new FloatJdbcValueHandler(Types.FLOAT));
|
||||
result.put("Float", new FloatJdbcValueHandler(Types.FLOAT));
|
||||
result.put("java.lang.Integer", new IntegerJdbcValueHandler(Types.INTEGER));
|
||||
result.put("Integer", new IntegerJdbcValueHandler(Types.INTEGER));
|
||||
result.put("java.lang.Long", new LongJdbcValueHandler(Types.BIGINT));
|
||||
result.put("Long", new LongJdbcValueHandler(Types.BIGINT));
|
||||
result.put("java.lang.Short", new ShortJdbcValueHandler(Types.SMALLINT));
|
||||
result.put("Short", new ShortJdbcValueHandler(Types.SMALLINT));
|
||||
result.put("java.lang.String", new StringJdbcValueHandler(Types.CHAR));
|
||||
result.put("String", new StringJdbcValueHandler(Types.CHAR));
|
||||
result.put("java.sql.Date", new DateJdbcValueHandler(Types.DATE));
|
||||
result.put("Date", new DateJdbcValueHandler(Types.DATE));
|
||||
result.put("java.sql.Time", new TimeJdbcValueHandler(Types.TIME));
|
||||
result.put("Time", new TimeJdbcValueHandler(Types.TIME));
|
||||
result.put("java.sql.Timestamp", new TimestampJdbcValueHandler(Types.TIMESTAMP));
|
||||
result.put("Timestamp", new TimestampJdbcValueHandler(Types.TIMESTAMP));
|
||||
// JDBC 2
|
||||
result.put("java.math.BigDecimal", new BigDecimalJdbcValueHandler(Types.DECIMAL));
|
||||
result.put("BigDecimal", new BigDecimalJdbcValueHandler(Types.DECIMAL));
|
||||
result.put("java.sql.Blob", new BlobJdbcValueHandler(Types.BLOB));
|
||||
result.put("Blob", new BlobJdbcValueHandler(Types.BLOB));
|
||||
result.put("java.sql.Clob", new ClobJdbcValueHandler(Types.CLOB));
|
||||
result.put("Clob", new ClobJdbcValueHandler(Types.CLOB));
|
||||
// JDBC 4
|
||||
result.put("RowId", new RowIdJdbcValueHandler(Types.ROWID));
|
||||
result.put("java.sql.RowId", new RowIdJdbcValueHandler(Types.ROWID));
|
||||
// Non-JDBC Types
|
||||
result.put("java.lang.Object", new ObjectJdbcValueHandler(Types.BLOB));
|
||||
result.put("Object", new ObjectJdbcValueHandler(Types.BLOB));
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Map<String, Integer> createSqlTypeMap() {
|
||||
/*
|
||||
This Map is used to select the correct SQL data type
|
||||
for the PreparedStatement.setNull method. The setNull
|
||||
method must be called with the correct type, or an
|
||||
exception will be thrown.
|
||||
*/
|
||||
Map<String, Integer> result = new HashMap<String, Integer>();
|
||||
// SQL 2003 Data Types
|
||||
result.put("ARRAY", Types.ARRAY);
|
||||
result.put("BIGINT", Types.BIGINT);
|
||||
result.put("BIT", Types.BIT);
|
||||
result.put("BINARY LARGE OBJECT", Types.BLOB);
|
||||
result.put("BLOB", Types.BLOB);
|
||||
result.put("BOOLEAN", Types.BOOLEAN);
|
||||
result.put("CHAR", Types.CHAR);
|
||||
result.put("CHARACTER", Types.CHAR);
|
||||
result.put("CHAR VARYING", Types.VARCHAR);
|
||||
result.put("CHARACTER VARYING", Types.VARCHAR);
|
||||
result.put("CHAR LARGE OBJECT", Types.CLOB);
|
||||
result.put("CHARACTER LARGE OBJECT", Types.CLOB);
|
||||
result.put("CLOB", Types.CLOB);
|
||||
result.put("DATE", Types.DATE);
|
||||
result.put("DEC", Types.DECIMAL);
|
||||
result.put("DECIMAL", Types.DECIMAL);
|
||||
result.put("DOUBLE", Types.DOUBLE);
|
||||
result.put("DOUBLE PRECISION", Types.DOUBLE);
|
||||
result.put("FLOAT", Types.FLOAT);
|
||||
result.put("INT", Types.INTEGER);
|
||||
result.put("INTEGER", Types.INTEGER);
|
||||
//result.put("INTERVAL", Types.?);
|
||||
//result.put("MULTISET", Types.?);
|
||||
result.put("NATIONAL CHAR", Types.NCHAR);
|
||||
result.put("NATIONAL CHARACTER", Types.NCHAR);
|
||||
result.put("NCHAR", Types.NCHAR);
|
||||
result.put("NATIONAL CHAR VARYING", Types.NVARCHAR);
|
||||
result.put("NATIONAL CHARACTER VARYING", Types.NVARCHAR);
|
||||
result.put("NCHAR VARYING", Types.NVARCHAR);
|
||||
result.put("NATIONAL CHARACTER LARGE OBJECT", Types.NCLOB);
|
||||
result.put("NCHAR LARGE OBJECT", Types.NCLOB);
|
||||
result.put("NCLOB", Types.NCLOB);
|
||||
result.put("NUMERIC", Types.NUMERIC);
|
||||
result.put("REAL", Types.REAL);
|
||||
result.put("REF", Types.REF);
|
||||
result.put("ROW", Types.ROWID);
|
||||
result.put("ROWID", Types.ROWID);
|
||||
result.put("SMALLINT", Types.SMALLINT);
|
||||
result.put("TIME", Types.TIME);
|
||||
result.put("TIMESTAMP", Types.TIMESTAMP);
|
||||
result.put("VARCHAR", Types.VARCHAR);
|
||||
// DB2, MS SQL Data Types
|
||||
// Note: Do NOT map the DATETIME SQL data type, the
|
||||
// java-type will be used to select the correct data type
|
||||
result.put("LONGVARCHAR", Types.LONGVARCHAR);
|
||||
result.put("LONG VARCHAR", Types.LONGVARCHAR);
|
||||
result.put("BIGINT", Types.BIGINT);
|
||||
result.put("TEXT", Types.LONGVARCHAR);
|
||||
result.put("IMAGE", Types.BLOB);
|
||||
result.put("BINARY", Types.BINARY);
|
||||
result.put("VARBINARY", Types.VARBINARY);
|
||||
result.put("LONGVARBINARY", Types.LONGVARBINARY);
|
||||
result.put("LONG VARBINARY", Types.LONGVARBINARY);
|
||||
// PostgreSQL SQL Data Types
|
||||
result.put("BYTEA", Types.BINARY);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Returns the <code>JdbcValueHandler</code> that corresponds to a field
|
||||
* type.
|
||||
*
|
||||
* @param javaType The Java type specified in fieldtype*.xml
|
||||
* @param sqlType The SQL type specified in fieldtype*.xml
|
||||
* @return A <code>JdbcValueHandler</code> instance
|
||||
*/
|
||||
public static JdbcValueHandler<?> getInstance(String javaType, String sqlType) {
|
||||
JdbcValueHandler<?> handler = JdbcValueHandlerMap.get(javaType);
|
||||
if (handler != null) {
|
||||
String key = parseSqlType(sqlType);
|
||||
Integer sqlTypeInt = SqlTypeMap.get(key);
|
||||
if (sqlTypeInt != null) {
|
||||
handler = handler.create(sqlTypeInt);
|
||||
}
|
||||
}
|
||||
return handler;
|
||||
}
|
||||
|
||||
protected static String parseSqlType(String sqlType) {
|
||||
String result = sqlType.toUpperCase();
|
||||
int pos = result.indexOf("(");
|
||||
if (pos != -1) {
|
||||
result = result.substring(0, pos);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
protected static byte[] serializeObject(Object obj) throws SQLException {
|
||||
ByteArrayOutputStream os = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = null;
|
||||
try {
|
||||
oos = new ObjectOutputStream(os);
|
||||
oos.writeObject(obj);
|
||||
os.close();
|
||||
} catch (IOException e) {
|
||||
throw new SQLException(e);
|
||||
} finally {
|
||||
if (oos != null) {
|
||||
try {
|
||||
oos.close();
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
}
|
||||
return os.toByteArray();
|
||||
}
|
||||
|
||||
// The target database SQL type to be used for the
|
||||
// PreparedStatement.setNull method.
|
||||
private final int sqlType;
|
||||
|
||||
protected JdbcValueHandler(int sqlType) {
|
||||
this.sqlType = sqlType;
|
||||
}
|
||||
|
||||
/** Sets a value in a <code>PreparedStatement</code>. The
|
||||
* <code>obj</code> argument is converted to the correct data
|
||||
* type. Subclasses override this method to cast <code>obj</code>
|
||||
* to the correct data type and call the appropriate
|
||||
* <code>PreparedStatement.setXxx</code> method.
|
||||
*
|
||||
* @param ps
|
||||
* @param parameterIndex
|
||||
* @param obj
|
||||
* @throws SQLException
|
||||
*/
|
||||
protected abstract void castAndSetValue(PreparedStatement ps, int parameterIndex, T obj) throws SQLException;
|
||||
|
||||
protected JdbcValueHandler<T> create(int sqlType) {
|
||||
if (sqlType == this.getSqlType()) {
|
||||
return this;
|
||||
}
|
||||
return newInstance(sqlType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the SQL type for this handler.
|
||||
* @return return the SQL type
|
||||
* @see <code>java.sql.Types</code>
|
||||
*/
|
||||
public int getSqlType() {
|
||||
return this.sqlType;
|
||||
}
|
||||
|
||||
/** Returns a value from a <code>ResultSet</code>. The returned
|
||||
* object is converted to the Java data type specified in the fieldtype
|
||||
* file.
|
||||
*
|
||||
* @param rs the ResultSet object
|
||||
* @param columnIndex the column index
|
||||
* @return get value from result set
|
||||
* @throws SQLException
|
||||
*/
|
||||
public abstract T getValue(ResultSet rs, int columnIndex) throws SQLException;
|
||||
|
||||
/**
|
||||
* Returns a new instance of the object - initialized with
|
||||
* the specified SQL type.
|
||||
* @param sqlType the sql type
|
||||
* @return returns a new instance
|
||||
*/
|
||||
protected abstract JdbcValueHandler<T> newInstance(int sqlType);
|
||||
|
||||
public abstract Class<T> getJavaClass();
|
||||
|
||||
/** Sets a value in a <code>PreparedStatement</code>. The
|
||||
* <code>obj</code> argument is converted to the correct data
|
||||
* type.
|
||||
*
|
||||
* @param ps
|
||||
* @param parameterIndex
|
||||
* @param obj
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setValue(PreparedStatement ps, int parameterIndex, T obj) throws SQLException {
|
||||
if (obj == null) {
|
||||
ps.setNull(parameterIndex, this.getSqlType());
|
||||
return;
|
||||
}
|
||||
this.castAndSetValue(ps, parameterIndex, obj);
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.sql.Array</code> JDBC value handler.
|
||||
*/
|
||||
protected static class ArrayJdbcValueHandler extends JdbcValueHandler<java.sql.Array> {
|
||||
protected ArrayJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<java.sql.Array> getJavaClass() {
|
||||
return java.sql.Array.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, java.sql.Array obj) throws SQLException {
|
||||
ps.setArray(parameterIndex, obj);
|
||||
}
|
||||
@Override
|
||||
public java.sql.Array getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
return rs.getArray(columnIndex);
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<java.sql.Array> newInstance(int sqlType) {
|
||||
return new ArrayJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.math.BigDecimal</code> JDBC value handler.
|
||||
*/
|
||||
protected static class BigDecimalJdbcValueHandler extends JdbcValueHandler<java.math.BigDecimal> {
|
||||
protected BigDecimalJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<java.math.BigDecimal> getJavaClass() {
|
||||
return java.math.BigDecimal.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, java.math.BigDecimal obj) throws SQLException {
|
||||
ps.setBigDecimal(parameterIndex, obj);
|
||||
}
|
||||
@Override
|
||||
public java.math.BigDecimal getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
return rs.getBigDecimal(columnIndex);
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<java.math.BigDecimal> newInstance(int sqlType) {
|
||||
return new BigDecimalJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.sql.Blob</code> JDBC value handler.
|
||||
*/
|
||||
protected static class BlobJdbcValueHandler extends JdbcValueHandler<Object> {
|
||||
protected BlobJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<Object> getJavaClass() {
|
||||
return Object.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, Object obj) throws SQLException {
|
||||
ps.setBlob(parameterIndex, (Blob) obj);
|
||||
}
|
||||
@Override
|
||||
public Object getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
Blob fieldBlob = rs.getBlob(columnIndex);
|
||||
if (fieldBlob != null) {
|
||||
return new SerialBlob(fieldBlob);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<Object> newInstance(int sqlType) {
|
||||
return new BlobJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.lang.Boolean</code> JDBC value handler.
|
||||
*/
|
||||
protected static class BooleanJdbcValueHandler extends JdbcValueHandler<Boolean> {
|
||||
protected BooleanJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<Boolean> getJavaClass() {
|
||||
return Boolean.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, Boolean obj) throws SQLException {
|
||||
ps.setBoolean(parameterIndex, obj);
|
||||
}
|
||||
@Override
|
||||
public Boolean getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
boolean value = rs.getBoolean(columnIndex);
|
||||
return rs.wasNull() ? null : Boolean.valueOf(value);
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<Boolean> newInstance(int sqlType) {
|
||||
return new BooleanJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>byte[]</code> JDBC value handler.
|
||||
*/
|
||||
protected static class ByteArrayJdbcValueHandler extends JdbcValueHandler<byte[]> {
|
||||
protected ByteArrayJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<byte[]> getJavaClass() {
|
||||
return byte[].class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, byte[] obj) throws SQLException {
|
||||
ps.setBytes(parameterIndex, obj);
|
||||
}
|
||||
@Override
|
||||
public byte[] getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
byte[] value = rs.getBytes(columnIndex);
|
||||
return rs.wasNull() ? null : value;
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<byte[]> newInstance(int sqlType) {
|
||||
return new ByteArrayJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.sql.Clob</code> JDBC value handler.
|
||||
*/
|
||||
protected static class ClobJdbcValueHandler extends JdbcValueHandler<Object> {
|
||||
protected ClobJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<Object> getJavaClass() {
|
||||
return Object.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, Object obj) throws SQLException {
|
||||
try {
|
||||
// FIXME: This is here for backwards compatibility. Client code
|
||||
// that uses a Clob java-type for a java.lang.String should use a
|
||||
// java.lang.String java-type instead.
|
||||
String str = (String) obj;
|
||||
Debug.logWarning("Clob java-type used for java.lang.String. Use java.lang.String java-type instead.", module);
|
||||
ps.setString(parameterIndex, str);
|
||||
return;
|
||||
} catch (ClassCastException e) {}
|
||||
ps.setClob(parameterIndex, (java.sql.Clob) obj);
|
||||
return;
|
||||
}
|
||||
@Override
|
||||
public Object getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
java.sql.Clob clob = rs.getClob(columnIndex);
|
||||
if (clob == null || clob.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
Reader clobReader = null;
|
||||
try {
|
||||
clobReader = clob.getCharacterStream();
|
||||
int clobLength = (int) clob.length();
|
||||
char[] charBuffer = new char[clobLength];
|
||||
int offset = 0;
|
||||
int charsRead = clobReader.read(charBuffer, offset, clobLength);
|
||||
while (charsRead > 0) {
|
||||
offset += charsRead;
|
||||
charsRead = clobReader.read(charBuffer, offset, clobLength);
|
||||
}
|
||||
// FIXME: This is here for backwards compatibility. Client code
|
||||
// that uses a Clob java-type for a java.lang.String should use a
|
||||
// java.lang.String java-type instead.
|
||||
return new String(charBuffer);
|
||||
} catch (IOException e) {
|
||||
throw new SQLException(e);
|
||||
}
|
||||
finally {
|
||||
if (clobReader != null) {
|
||||
try {
|
||||
clobReader.close();
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<Object> newInstance(int sqlType) {
|
||||
return new ClobJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.sql.Date</code> JDBC value handler.
|
||||
*/
|
||||
protected static class DateJdbcValueHandler extends JdbcValueHandler<java.sql.Date> {
|
||||
protected DateJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<java.sql.Date> getJavaClass() {
|
||||
return java.sql.Date.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, java.sql.Date obj) throws SQLException {
|
||||
ps.setDate(parameterIndex, obj);
|
||||
}
|
||||
@Override
|
||||
public java.sql.Date getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
return rs.getDate(columnIndex);
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<java.sql.Date> newInstance(int sqlType) {
|
||||
return new DateJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.lang.Double</code> JDBC value handler.
|
||||
*/
|
||||
protected static class DoubleJdbcValueHandler extends JdbcValueHandler<Double> {
|
||||
protected DoubleJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<Double> getJavaClass() {
|
||||
return Double.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, Double obj) throws SQLException {
|
||||
ps.setDouble(parameterIndex, obj);
|
||||
}
|
||||
@Override
|
||||
public Double getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
double value = rs.getDouble(columnIndex);
|
||||
return rs.wasNull() ? null : Double.valueOf(value);
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<Double> newInstance(int sqlType) {
|
||||
return new DoubleJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.lang.Float</code> JDBC value handler.
|
||||
*/
|
||||
protected static class FloatJdbcValueHandler extends JdbcValueHandler<Float> {
|
||||
protected FloatJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<Float> getJavaClass() {
|
||||
return Float.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, Float obj) throws SQLException {
|
||||
ps.setFloat(parameterIndex, obj);
|
||||
}
|
||||
@Override
|
||||
public Float getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
float value = rs.getFloat(columnIndex);
|
||||
return rs.wasNull() ? null : Float.valueOf(value);
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<Float> newInstance(int sqlType) {
|
||||
return new FloatJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.lang.Integer</code> JDBC value handler.
|
||||
*/
|
||||
protected static class IntegerJdbcValueHandler extends JdbcValueHandler<Integer> {
|
||||
protected IntegerJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<Integer> getJavaClass() {
|
||||
return Integer.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, Integer obj) throws SQLException {
|
||||
ps.setInt(parameterIndex, obj);
|
||||
}
|
||||
@Override
|
||||
public Integer getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
int value = rs.getInt(columnIndex);
|
||||
return rs.wasNull() ? null : Integer.valueOf(value);
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<Integer> newInstance(int sqlType) {
|
||||
return new IntegerJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.lang.Long</code> JDBC value handler.
|
||||
*/
|
||||
protected static class LongJdbcValueHandler extends JdbcValueHandler<Long> {
|
||||
protected LongJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<Long> getJavaClass() {
|
||||
return Long.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, Long obj) throws SQLException {
|
||||
ps.setLong(parameterIndex, obj);
|
||||
}
|
||||
@Override
|
||||
public Long getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
long value = rs.getLong(columnIndex);
|
||||
return rs.wasNull() ? null : Long.valueOf(value);
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<Long> newInstance(int sqlType) {
|
||||
return new LongJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.lang.Object</code> JDBC value handler.
|
||||
*/
|
||||
protected static class ObjectJdbcValueHandler extends JdbcValueHandler<Object> {
|
||||
protected ObjectJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<Object> getJavaClass() {
|
||||
return Object.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, Object obj) throws SQLException {
|
||||
ps.setBytes(parameterIndex, serializeObject(obj));
|
||||
}
|
||||
@Override
|
||||
public Object getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
ObjectInputStream in = null;
|
||||
InputStream bis = null;
|
||||
try {
|
||||
bis = rs.getBinaryStream(columnIndex);
|
||||
if (bis == null) {
|
||||
return null;
|
||||
}
|
||||
in = new ObjectInputStream(bis);
|
||||
return in.readObject();
|
||||
} catch (Exception e) {
|
||||
throw new SQLException(e);
|
||||
} finally {
|
||||
if (in != null) {
|
||||
try {
|
||||
in.close();
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
if (bis != null) {
|
||||
try {
|
||||
bis.close();
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<Object> newInstance(int sqlType) {
|
||||
return new ObjectJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.sql.RowId</code> JDBC value handler.
|
||||
*/
|
||||
protected static class RowIdJdbcValueHandler extends JdbcValueHandler<java.sql.RowId> {
|
||||
protected RowIdJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<java.sql.RowId> getJavaClass() {
|
||||
return java.sql.RowId.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, java.sql.RowId obj) throws SQLException {
|
||||
ps.setRowId(parameterIndex, obj);
|
||||
}
|
||||
@Override
|
||||
public java.sql.RowId getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
return rs.getRowId(columnIndex);
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<java.sql.RowId> newInstance(int sqlType) {
|
||||
return new RowIdJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.lang.Short</code> JDBC value handler.
|
||||
*/
|
||||
protected static class ShortJdbcValueHandler extends JdbcValueHandler<Short> {
|
||||
protected ShortJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<Short> getJavaClass() {
|
||||
return Short.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, Short obj) throws SQLException {
|
||||
ps.setShort(parameterIndex, obj);
|
||||
}
|
||||
@Override
|
||||
public Short getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
short value = rs.getShort(columnIndex);
|
||||
return rs.wasNull() ? null : Short.valueOf(value);
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<Short> newInstance(int sqlType) {
|
||||
return new ShortJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.lang.String</code> JDBC value handler.
|
||||
*/
|
||||
protected static class StringJdbcValueHandler extends JdbcValueHandler<String> {
|
||||
protected StringJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<String> getJavaClass() {
|
||||
return String.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, String obj) throws SQLException {
|
||||
ps.setString(parameterIndex, obj);
|
||||
}
|
||||
@Override
|
||||
public String getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
return rs.getString(columnIndex);
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<String> newInstance(int sqlType) {
|
||||
return new StringJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.sql.Time</code> JDBC value handler.
|
||||
*/
|
||||
protected static class TimeJdbcValueHandler extends JdbcValueHandler<java.sql.Time> {
|
||||
protected TimeJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<java.sql.Time> getJavaClass() {
|
||||
return java.sql.Time.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, java.sql.Time obj) throws SQLException {
|
||||
ps.setTime(parameterIndex, obj);
|
||||
}
|
||||
@Override
|
||||
public java.sql.Time getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
return rs.getTime(columnIndex);
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<java.sql.Time> newInstance(int sqlType) {
|
||||
return new TimeJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A <code>java.sql.Timestamp</code> JDBC value handler.
|
||||
* <p>This <code>JdbcValueHandler</code> accommodates databases that
|
||||
* don't support sub-second precision. If the date-time field type
|
||||
* is a <code>CHAR(30)</code> SQL type, <code>java.sql.Timestamp</code>s
|
||||
* will be stored as JDBC timestamp escape format strings
|
||||
* (<code>yyyy-mm-dd hh:mm:ss.fffffffff</code>), referenced to UTC.</p>
|
||||
*/
|
||||
protected static class TimestampJdbcValueHandler extends JdbcValueHandler<java.sql.Timestamp> {
|
||||
protected TimestampJdbcValueHandler(int jdbcType) {
|
||||
super(jdbcType);
|
||||
}
|
||||
@Override
|
||||
public Class<java.sql.Timestamp> getJavaClass() {
|
||||
return java.sql.Timestamp.class;
|
||||
}
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, java.sql.Timestamp obj) throws SQLException {
|
||||
ps.setTimestamp(parameterIndex, obj);
|
||||
}
|
||||
@Override
|
||||
public java.sql.Timestamp getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
return rs.getTimestamp(columnIndex);
|
||||
}
|
||||
@Override
|
||||
protected JdbcValueHandler<java.sql.Timestamp> newInstance(int sqlType) {
|
||||
if (sqlType == Types.CHAR) {
|
||||
return new TimestampJdbcValueHandler(sqlType) {
|
||||
@Override
|
||||
protected void castAndSetValue(PreparedStatement ps, int parameterIndex, java.sql.Timestamp obj) throws SQLException {
|
||||
ps.setString(parameterIndex, obj.toString());
|
||||
}
|
||||
@Override
|
||||
public java.sql.Timestamp getValue(ResultSet rs, int columnIndex) throws SQLException {
|
||||
String str = rs.getString(columnIndex);
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
return Timestamp.valueOf(str);
|
||||
}
|
||||
};
|
||||
} else {
|
||||
return new TimestampJdbcValueHandler(sqlType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,895 @@
|
||||
/*******************************************************************************
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*******************************************************************************/
|
||||
package org.ofbiz.entity.jdbc;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Blob;
|
||||
import java.sql.Clob;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Types;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.ofbiz.base.util.Debug;
|
||||
import org.ofbiz.entity.Delegator;
|
||||
import org.ofbiz.entity.GenericDataSourceException;
|
||||
import org.ofbiz.entity.GenericEntityException;
|
||||
import org.ofbiz.entity.config.model.Datasource;
|
||||
import org.ofbiz.entity.config.model.EntityConfig;
|
||||
import org.ofbiz.entity.datasource.GenericHelperInfo;
|
||||
import org.ofbiz.entity.transaction.GenericTransactionException;
|
||||
import org.ofbiz.entity.transaction.TransactionFactoryLoader;
|
||||
import org.ofbiz.entity.transaction.TransactionUtil;
|
||||
|
||||
/**
|
||||
* SQLProcessor - provides utility functions to ease database access
|
||||
*
|
||||
*/
|
||||
public class SQLProcessor {
|
||||
|
||||
/** Module Name Used for debugging */
|
||||
public static final String module = SQLProcessor.class.getName();
|
||||
|
||||
/** Used for testing connections when test is enabled */
|
||||
public static List<String> CONNECTION_TEST_LIST = new ArrayList<String>();
|
||||
public static int MAX_CONNECTIONS = 1000;
|
||||
public static boolean ENABLE_TEST = false;
|
||||
|
||||
private final Delegator delegator;
|
||||
|
||||
/** The datasource helper (see entityengine.xml <datasource name="..">) */
|
||||
private GenericHelperInfo helperInfo;
|
||||
|
||||
// / The database resources to be used
|
||||
private Connection _connection = null;
|
||||
|
||||
// / The database resources to be used
|
||||
private PreparedStatement _ps = null;
|
||||
|
||||
// / The database resources to be used
|
||||
private ResultSet _rs = null;
|
||||
|
||||
private ResultSetMetaData _rsmd = null;
|
||||
|
||||
// / The SQL String used. Use for debugging only
|
||||
private String _sql;
|
||||
|
||||
// / Index to be used with preparedStatement.setValue(_ind, ...)
|
||||
private int _ind;
|
||||
|
||||
// / true in case of manual transactions
|
||||
private boolean _manualTX;
|
||||
|
||||
// / true in case the connection shall be closed.
|
||||
private boolean _bDeleteConnection = false;
|
||||
|
||||
/**
|
||||
* Construct an object based on the helper/datasource
|
||||
*
|
||||
* @param helperInfo The datasource helper (see entityengine.xml <datasource name="..">)
|
||||
*/
|
||||
public SQLProcessor(Delegator delegator, GenericHelperInfo helperInfo) {
|
||||
this.delegator = delegator;
|
||||
this.helperInfo = helperInfo;
|
||||
this._manualTX = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct an object with an connection given. The connection will not
|
||||
* be closed by this SQLProcessor, but may be by some other.
|
||||
*
|
||||
* @param helperInfo The datasource helper (see entityengine.xml <datasource name="..">)
|
||||
* @param connection The connection to be used
|
||||
*/
|
||||
public SQLProcessor(Delegator delegator, GenericHelperInfo helperInfo, Connection connection) {
|
||||
this.delegator = delegator;
|
||||
this.helperInfo = helperInfo;
|
||||
this._connection = connection;
|
||||
|
||||
// Do not commit while closing
|
||||
if (_connection != null) {
|
||||
_manualTX = false;
|
||||
}
|
||||
}
|
||||
|
||||
public Delegator getDelegator() {
|
||||
return delegator;
|
||||
}
|
||||
|
||||
ResultSetMetaData getResultSetMetaData() {
|
||||
if (_rsmd == null) {
|
||||
// try the ResultSet, if not null, or try the PreparedStatement, also if not null
|
||||
try {
|
||||
if (_rs != null) {
|
||||
_rsmd = _rs.getMetaData();
|
||||
} else if (_ps != null) {
|
||||
_rsmd = _ps.getMetaData();
|
||||
}
|
||||
} catch (SQLException sqle2) {
|
||||
Debug.logWarning("[SQLProcessor.rollback]: SQL Exception while rolling back insert. Error was:" + sqle2, module);
|
||||
Debug.logWarning(sqle2, module);
|
||||
}
|
||||
}
|
||||
return _rsmd;
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit all modifications
|
||||
*
|
||||
* @throws GenericDataSourceException
|
||||
*/
|
||||
public void commit() throws GenericDataSourceException {
|
||||
if (_connection == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Debug.verboseOn()) Debug.logVerbose("SQLProcessor:commit() _manualTX=" + _manualTX, module);
|
||||
|
||||
if (_manualTX) {
|
||||
try {
|
||||
_connection.commit();
|
||||
if (Debug.verboseOn()) Debug.logVerbose("SQLProcessor:commit() : called commit on connection", module);
|
||||
} catch (SQLException sqle) {
|
||||
Debug.logError(sqle, "Error committing transaction: " + sqle.toString());
|
||||
try {
|
||||
rollback();
|
||||
} catch (GenericDataSourceException rbsqle) {
|
||||
Debug.logError(rbsqle, "Got another error when trying to rollback after error committing transaction: " + sqle.toString());
|
||||
}
|
||||
throw new GenericDataSourceException("SQL Exception occurred on commit", sqle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rollback all modifications
|
||||
*/
|
||||
public void rollback() throws GenericDataSourceException {
|
||||
if (_connection == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Debug.verboseOn()) Debug.logVerbose("SQLProcessor:rollback() _manualTX=" + _manualTX, module);
|
||||
|
||||
try {
|
||||
if (_manualTX) {
|
||||
_connection.rollback();
|
||||
if (Debug.verboseOn()) Debug.logVerbose("SQLProcessor:rollback() : _manualTX=" + _manualTX, module);
|
||||
} else {
|
||||
try {
|
||||
TransactionUtil.setRollbackOnly("rollback called in Entity Engine SQLProcessor", new Exception("Current Location Stack"));
|
||||
if (Debug.verboseOn()) Debug.logVerbose("SQLProcessor:rollback() : _manualTX=" + _manualTX, module);
|
||||
} catch (GenericTransactionException e) {
|
||||
Debug.logError(e, "Error setting rollback only", module);
|
||||
throw new GenericDataSourceException("Error setting rollback only", e);
|
||||
}
|
||||
}
|
||||
} catch (SQLException sqle2) {
|
||||
Debug.logWarning("[SQLProcessor.rollback]: SQL Exception while rolling back insert. Error was:" + sqle2, module);
|
||||
Debug.logWarning(sqle2, module);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit if required and remove all allocated resources
|
||||
*
|
||||
* @throws GenericDataSourceException
|
||||
*/
|
||||
public void close() throws GenericDataSourceException {
|
||||
if (_manualTX) {
|
||||
if (Debug.verboseOn()) Debug.logVerbose("SQLProcessor:close() calling commit : _manualTX=" + _manualTX, module);
|
||||
commit();
|
||||
}
|
||||
|
||||
_sql = null;
|
||||
|
||||
if (_rs != null) {
|
||||
try {
|
||||
_rs.close();
|
||||
if (Debug.verboseOn()) Debug.logVerbose("SQLProcessor:close() result close : _manualTX=" + _manualTX, module);
|
||||
} catch (SQLException sqle) {
|
||||
Debug.logWarning(sqle.getMessage(), module);
|
||||
}
|
||||
|
||||
_rs = null;
|
||||
}
|
||||
|
||||
if (_ps != null) {
|
||||
try {
|
||||
_ps.close();
|
||||
if (Debug.verboseOn()) Debug.logVerbose("SQLProcessor:close() preparedStatement close : _manualTX=" + _manualTX, module);
|
||||
} catch (SQLException sqle) {
|
||||
Debug.logWarning(sqle.getMessage(), module);
|
||||
}
|
||||
|
||||
_ps = null;
|
||||
}
|
||||
|
||||
if ((_connection != null) && _bDeleteConnection) {
|
||||
try {
|
||||
_connection.close();
|
||||
if (Debug.verboseOn()) Debug.logVerbose("SQLProcessor:close() connection close : _manualTX=" + _manualTX, module);
|
||||
} catch (SQLException sqle) {
|
||||
Debug.logWarning(sqle.getMessage(), module);
|
||||
}
|
||||
|
||||
_connection = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a connection from the TransactionFactoryLoader
|
||||
*
|
||||
* @return The connection created
|
||||
*
|
||||
* @throws GenericDataSourceException
|
||||
* @throws GenericEntityException
|
||||
*/
|
||||
public Connection getConnection() throws GenericDataSourceException, GenericEntityException {
|
||||
if (_connection != null)
|
||||
return _connection;
|
||||
|
||||
_manualTX = true;
|
||||
|
||||
try {
|
||||
_connection = TransactionFactoryLoader.getInstance().getConnection(helperInfo);
|
||||
if (Debug.verboseOn()) Debug.logVerbose("SQLProcessor:connection() : manualTx=" + _manualTX, module);
|
||||
} catch (SQLException sqle) {
|
||||
throw new GenericDataSourceException("Unable to esablish a connection with the database.", sqle);
|
||||
}
|
||||
|
||||
// make sure we actually did get a connection
|
||||
if (_connection == null) {
|
||||
throw new GenericDataSourceException("Unable to esablish a connection with the database. Connection was null!");
|
||||
}
|
||||
|
||||
// test the connection
|
||||
testConnection(_connection);
|
||||
|
||||
/* causes problems w/ postgres ??
|
||||
if (Debug.verboseOn()) {
|
||||
int isoLevel = -999;
|
||||
try {
|
||||
isoLevel = _connection.getTransactionIsolation();
|
||||
} catch (SQLException e) {
|
||||
Debug.logError(e, "Problems getting the connection's isolation level", module);
|
||||
}
|
||||
if (isoLevel == Connection.TRANSACTION_NONE) {
|
||||
Debug.logVerbose("Transaction isolation level set to 'None'.", module);
|
||||
} else if (isoLevel == Connection.TRANSACTION_READ_COMMITTED) {
|
||||
Debug.logVerbose("Transaction isolation level set to 'ReadCommited'.", module);
|
||||
} else if (isoLevel == Connection.TRANSACTION_READ_UNCOMMITTED) {
|
||||
Debug.logVerbose("Transaction isolation level set to 'ReadUncommitted'.", module);
|
||||
} else if (isoLevel == Connection.TRANSACTION_REPEATABLE_READ) {
|
||||
Debug.logVerbose("Transaction isolation level set to 'RepeatableRead'.", module);
|
||||
} else if (isoLevel == Connection.TRANSACTION_SERIALIZABLE) {
|
||||
Debug.logVerbose("Transaction isolation level set to 'Serializable'.", module);
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
// always try to set auto commit to false, but if we can't then later on we won't commit
|
||||
try {
|
||||
if (_connection.getAutoCommit()) {
|
||||
try {
|
||||
_connection.setAutoCommit(false);
|
||||
if (Debug.verboseOn()) Debug.logVerbose("SQLProcessor:setAutoCommit(false) : manualTx=" + _manualTX, module);
|
||||
} catch (SQLException sqle) {
|
||||
_manualTX = false;
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new GenericDataSourceException("Cannot get autoCommit status from connection", e);
|
||||
}
|
||||
|
||||
try {
|
||||
if (TransactionUtil.getStatus() == TransactionUtil.STATUS_ACTIVE) {
|
||||
if (Debug.verboseOn()) Debug.logVerbose("[SQLProcessor.getConnection] : active transaction", module);
|
||||
_manualTX = false;
|
||||
}
|
||||
} catch (GenericTransactionException e) {
|
||||
// nevermind, don't worry about it, but print the exc anyway
|
||||
Debug.logWarning("[SQLProcessor.getConnection]: Exception was thrown trying to check " +
|
||||
"transaction status: " + e.toString(), module);
|
||||
}
|
||||
|
||||
if (Debug.verboseOn()) Debug.logVerbose("[SQLProcessor.getConnection] : con=" + _connection, module);
|
||||
|
||||
_bDeleteConnection = true;
|
||||
return _connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare a statement. In case no connection has been given, allocate a
|
||||
* new one.
|
||||
*
|
||||
* @param sql The SQL statement to be executed
|
||||
*
|
||||
* @throws GenericDataSourceException
|
||||
* @throws GenericEntityException
|
||||
*/
|
||||
public void prepareStatement(String sql) throws GenericDataSourceException, GenericEntityException {
|
||||
this.prepareStatement(sql, false, 0, 0, -1, -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare a statement. In case no connection has been given, allocate a
|
||||
* new one.
|
||||
*
|
||||
* @param sql The SQL statement to be executed
|
||||
*
|
||||
* @throws GenericDataSourceException
|
||||
* @throws GenericEntityException
|
||||
*/
|
||||
public void prepareStatement(String sql, boolean specifyTypeAndConcur, int resultSetType, int resultSetConcurrency) throws GenericDataSourceException, GenericEntityException {
|
||||
this.prepareStatement(sql, specifyTypeAndConcur, resultSetType, resultSetConcurrency, -1, -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare a statement. In case no connection has been given, allocate a
|
||||
* new one.
|
||||
*
|
||||
* @param sql The SQL statement to be executed
|
||||
*
|
||||
* @throws GenericDataSourceException
|
||||
* @throws GenericEntityException
|
||||
*/
|
||||
public void prepareStatement(String sql, boolean specifyTypeAndConcur, int resultSetType, int resultSetConcurrency, int fetchSize, int maxRows) throws GenericDataSourceException, GenericEntityException {
|
||||
if (Debug.verboseOn()) Debug.logVerbose("[SQLProcessor.prepareStatement] sql=" + sql, module);
|
||||
|
||||
if (_connection == null) {
|
||||
getConnection();
|
||||
}
|
||||
|
||||
try {
|
||||
_sql = sql;
|
||||
_ind = 1;
|
||||
if (specifyTypeAndConcur) {
|
||||
_ps = _connection.prepareStatement(sql, resultSetType, resultSetConcurrency);
|
||||
if (Debug.verboseOn()) Debug.logVerbose("[SQLProcessor.prepareStatement] _ps=" + _ps, module);
|
||||
} else {
|
||||
_ps = _connection.prepareStatement(sql);
|
||||
if (Debug.verboseOn()) Debug.logVerbose("[SQLProcessor.prepareStatement] (def) _ps=" + _ps, module);
|
||||
}
|
||||
if (maxRows > 0) {
|
||||
_ps.setMaxRows(maxRows);
|
||||
if (Debug.verboseOn()) Debug.logVerbose("[SQLProcessor.prepareStatement] max rows set : " + maxRows, module);
|
||||
}
|
||||
this.setFetchSize(_ps, fetchSize);
|
||||
} catch (SQLException sqle) {
|
||||
throw new GenericDataSourceException("SQL Exception while executing the following:" + sql, sqle);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a query based on the prepared statement
|
||||
*
|
||||
* @return The result set of the query
|
||||
* @throws GenericDataSourceException
|
||||
*/
|
||||
public ResultSet executeQuery() throws GenericDataSourceException {
|
||||
try {
|
||||
// if (Debug.verboseOn()) Debug.logVerbose("[SQLProcessor.executeQuery] ps=" + _ps.toString(), module);
|
||||
_rs = _ps.executeQuery();
|
||||
} catch (SQLException sqle) {
|
||||
this.checkLockWaitInfo(sqle);
|
||||
throw new GenericDataSourceException("SQL Exception while executing the following:" + _sql, sqle);
|
||||
}
|
||||
|
||||
return _rs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a query based on the SQL string given
|
||||
*
|
||||
* @param sql The SQL string to be executed
|
||||
* @return The result set of the query
|
||||
* @throws GenericEntityException
|
||||
* @throws GenericDataSourceException
|
||||
*/
|
||||
public ResultSet executeQuery(String sql) throws GenericDataSourceException, GenericEntityException {
|
||||
prepareStatement(sql);
|
||||
return executeQuery();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute updates
|
||||
*
|
||||
* @return The number of rows updated
|
||||
* @throws GenericDataSourceException
|
||||
*/
|
||||
public int executeUpdate() throws GenericDataSourceException {
|
||||
try {
|
||||
// if (Debug.verboseOn()) Debug.logVerbose("[SQLProcessor.executeUpdate] ps=" + _ps.toString(), module);
|
||||
//TransactionUtil.printAllThreadsTransactionBeginStacks();
|
||||
return _ps.executeUpdate();
|
||||
} catch (SQLException sqle) {
|
||||
this.checkLockWaitInfo(sqle);
|
||||
// don't display this here, may not be critical, allow handling further up... Debug.logError(sqle, "SQLProcessor.executeUpdate() : ERROR : ", module);
|
||||
throw new GenericDataSourceException("SQL Exception while executing the following:" + _sql, sqle);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute update based on the SQL statement given
|
||||
*
|
||||
* @param sql SQL statement to be executed
|
||||
* @throws GenericDataSourceException
|
||||
*/
|
||||
public int executeUpdate(String sql) throws GenericDataSourceException {
|
||||
Statement stmt = null;
|
||||
|
||||
try {
|
||||
stmt = _connection.createStatement();
|
||||
return stmt.executeUpdate(sql);
|
||||
} catch (SQLException sqle) {
|
||||
// passing on this exception as nested, no need to log it here: Debug.logError(sqle, "SQLProcessor.executeUpdate(sql) : ERROR : ", module);
|
||||
throw new GenericDataSourceException("SQL Exception while executing the following:" + _sql, sqle);
|
||||
} finally {
|
||||
if (stmt != null) {
|
||||
try {
|
||||
stmt.close();
|
||||
} catch (SQLException sqle) {
|
||||
Debug.logWarning("Unable to close 'statement': " + sqle.getMessage(), module);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if there more records available
|
||||
*
|
||||
* @return true, if there more records available
|
||||
*
|
||||
* @throws GenericDataSourceException
|
||||
*/
|
||||
public boolean next() throws GenericDataSourceException {
|
||||
try {
|
||||
return _rs.next();
|
||||
} catch (SQLException sqle) {
|
||||
throw new GenericDataSourceException("SQL Exception while executing the following:" + _sql, sqle);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter: get the currently active ResultSet
|
||||
*
|
||||
* @return ResultSet
|
||||
*/
|
||||
public ResultSet getResultSet() {
|
||||
return _rs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter: get the prepared statement
|
||||
*
|
||||
* @return PreparedStatement
|
||||
*/
|
||||
public PreparedStatement getPreparedStatement() {
|
||||
return _ps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a query based on the SQL string given. For each record
|
||||
* of the ResultSet return, execute a callback function
|
||||
*
|
||||
* @param sql The SQL string to be executed
|
||||
* @param aListener The callback function object
|
||||
*
|
||||
* @throws GenericEntityException
|
||||
*/
|
||||
public void execQuery(String sql, ExecQueryCallbackFunctionIF aListener) throws GenericEntityException {
|
||||
if (_connection == null) {
|
||||
getConnection();
|
||||
}
|
||||
|
||||
try {
|
||||
if (Debug.verboseOn()) Debug.logVerbose("[SQLProcessor.execQuery]: " + sql, module);
|
||||
executeQuery(sql);
|
||||
|
||||
// process the results by calling the listener for
|
||||
// each row...
|
||||
boolean keepGoing = true;
|
||||
|
||||
while (keepGoing && _rs.next()) {
|
||||
keepGoing = aListener.processNextRow(_rs);
|
||||
}
|
||||
|
||||
if (_manualTX) {
|
||||
_connection.commit();
|
||||
}
|
||||
|
||||
} catch (SQLException sqle) {
|
||||
Debug.logWarning("[SQLProcessor.execQuery]: SQL Exception while executing the following:\n" +
|
||||
sql + "\nError was:", module);
|
||||
Debug.logWarning(sqle.getMessage(), module);
|
||||
throw new GenericEntityException("SQL Exception while executing the following:" + _sql, sqle);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement.
|
||||
*
|
||||
* @param handler
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public <T> void setValue(JdbcValueHandler<T> handler, T field) throws SQLException {
|
||||
handler.setValue(_ps, _ind, field);
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement.
|
||||
*
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setValue(String field) throws SQLException {
|
||||
//ResultSetMetaData rsmd = this.getResultSetMetaData();
|
||||
//this doesn't seem to work, query not yet parsed: int colType = rsmd.getColumnType(_ind);
|
||||
if (field != null) {
|
||||
//if (field.length() > 4000) {
|
||||
//Clob clb = new Cl
|
||||
// doesn't work with Oracle drivers, need the funky work-around: _ps.setCharacterStream(_ind, new StringReader(field), field.length());
|
||||
//_needClobWorkAroundWrite.put(Integer.valueOf(_ind), field);
|
||||
//_ps.setString(_ind, " ");
|
||||
//} else {
|
||||
_ps.setString(_ind, field);
|
||||
//}
|
||||
} else {
|
||||
// silly workaround for Derby (Cloudscape 10 beta Bug #5928)
|
||||
// this should be removed after the know bug is fixed
|
||||
try {
|
||||
_ps.setNull(_ind, Types.VARCHAR);
|
||||
} catch (SQLException e) {
|
||||
try {
|
||||
_ps.setString(_ind, null);
|
||||
} catch (SQLException e2) {
|
||||
Debug.logError(e2, module);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement.
|
||||
*
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setValue(java.sql.Timestamp field) throws SQLException {
|
||||
if (field != null) {
|
||||
_ps.setTimestamp(_ind, field);
|
||||
} else {
|
||||
_ps.setNull(_ind, Types.TIMESTAMP);
|
||||
}
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement.
|
||||
*
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setValue(java.sql.Time field) throws SQLException {
|
||||
if (field != null) {
|
||||
_ps.setTime(_ind, field);
|
||||
} else {
|
||||
_ps.setNull(_ind, Types.TIME);
|
||||
}
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement.
|
||||
*
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setValue(java.sql.Date field) throws SQLException {
|
||||
if (field != null) {
|
||||
_ps.setDate(_ind, field);
|
||||
} else {
|
||||
_ps.setNull(_ind, Types.DATE);
|
||||
}
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement.
|
||||
*
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setValue(Integer field) throws SQLException {
|
||||
if (field != null) {
|
||||
_ps.setInt(_ind, field.intValue());
|
||||
} else {
|
||||
_ps.setNull(_ind, Types.NUMERIC);
|
||||
}
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement.
|
||||
*
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setValue(Long field) throws SQLException {
|
||||
if (field != null) {
|
||||
_ps.setLong(_ind, field.longValue());
|
||||
} else {
|
||||
_ps.setNull(_ind, Types.NUMERIC);
|
||||
}
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement.
|
||||
*
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setValue(Float field) throws SQLException {
|
||||
if (field != null) {
|
||||
_ps.setFloat(_ind, field.floatValue());
|
||||
} else {
|
||||
_ps.setNull(_ind, Types.NUMERIC);
|
||||
}
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement.
|
||||
*
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setValue(Double field) throws SQLException {
|
||||
if (field != null) {
|
||||
_ps.setDouble(_ind, field.doubleValue());
|
||||
} else {
|
||||
_ps.setNull(_ind, Types.NUMERIC);
|
||||
}
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement.
|
||||
*
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setValue(BigDecimal field) throws SQLException {
|
||||
if (field != null) {
|
||||
_ps.setBigDecimal(_ind, field);
|
||||
} else {
|
||||
_ps.setNull(_ind, Types.NUMERIC);
|
||||
}
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement.
|
||||
*
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setValue(Boolean field) throws SQLException {
|
||||
if (field != null) {
|
||||
_ps.setBoolean(_ind, field.booleanValue());
|
||||
} else {
|
||||
_ps.setNull(_ind, Types.BOOLEAN);
|
||||
}
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement.
|
||||
*
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setValue(Object field) throws SQLException {
|
||||
if (field != null) {
|
||||
_ps.setObject(_ind, field, Types.JAVA_OBJECT);
|
||||
} else {
|
||||
_ps.setNull(_ind, Types.JAVA_OBJECT);
|
||||
}
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement
|
||||
*
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setValue(Blob field) throws SQLException {
|
||||
if (field != null) {
|
||||
_ps.setBlob(_ind, field);
|
||||
} else {
|
||||
Datasource datasourceInfo = EntityConfig.getDatasource(this.helperInfo.getHelperBaseName());
|
||||
if (datasourceInfo.getUseBinaryTypeForBlob()) {
|
||||
_ps.setNull(_ind, Types.BINARY);
|
||||
} else {
|
||||
_ps.setNull(_ind, Types.BLOB);
|
||||
}
|
||||
}
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement
|
||||
*
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setValue(Clob field) throws SQLException {
|
||||
if (field != null) {
|
||||
_ps.setClob(_ind, field);
|
||||
} else {
|
||||
_ps.setNull(_ind, Types.CLOB);
|
||||
}
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement
|
||||
* to write the serialized data of 'field' to a BLOB.
|
||||
*
|
||||
* @param field
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setBinaryStream(Object field) throws SQLException {
|
||||
if (field != null) {
|
||||
try {
|
||||
ByteArrayOutputStream os = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(os);
|
||||
oos.writeObject(field);
|
||||
oos.close();
|
||||
|
||||
byte[] buf = os.toByteArray();
|
||||
os.close();
|
||||
ByteArrayInputStream is = new ByteArrayInputStream(buf);
|
||||
_ps.setBinaryStream(_ind, is, buf.length);
|
||||
is.close();
|
||||
} catch (IOException ex) {
|
||||
throw new SQLException(ex.getMessage());
|
||||
}
|
||||
} else {
|
||||
Datasource datasourceInfo = EntityConfig.getDatasource(this.helperInfo.getHelperBaseName());
|
||||
if (datasourceInfo.getUseBinaryTypeForBlob()) {
|
||||
_ps.setNull(_ind, Types.BINARY);
|
||||
} else {
|
||||
_ps.setNull(_ind, Types.BLOB);
|
||||
}
|
||||
}
|
||||
|
||||
_ind++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the next binding variable of the currently active prepared statement
|
||||
* to write the serialized data of 'field' to a Blob with the given bytes.
|
||||
*
|
||||
* @param bytes
|
||||
*
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void setBytes(byte[] bytes) throws SQLException {
|
||||
if (bytes != null) {
|
||||
_ps.setBytes(_ind, bytes);
|
||||
} else {
|
||||
Datasource datasourceInfo = EntityConfig.getDatasource(this.helperInfo.getHelperBaseName());
|
||||
if (datasourceInfo.getUseBinaryTypeForBlob()) {
|
||||
_ps.setNull(_ind, Types.BINARY);
|
||||
} else {
|
||||
_ps.setNull(_ind, Types.BLOB);
|
||||
}
|
||||
}
|
||||
_ind++;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void finalize() throws Throwable {
|
||||
try {
|
||||
this.close();
|
||||
} catch (Exception e) {
|
||||
Debug.logError(e, "Error closing the result, connection, etc in finalize SQLProcessor", module);
|
||||
}
|
||||
super.finalize();
|
||||
}
|
||||
|
||||
protected void testConnection(Connection con) throws GenericEntityException {
|
||||
if (SQLProcessor.ENABLE_TEST) {
|
||||
if (SQLProcessor.CONNECTION_TEST_LIST.contains(con.toString())) {
|
||||
throw new GenericEntityException("Connection the exact same as index " + SQLProcessor.CONNECTION_TEST_LIST.indexOf(con.toString()));
|
||||
}
|
||||
SQLProcessor.CONNECTION_TEST_LIST.add(con.toString());
|
||||
if (SQLProcessor.CONNECTION_TEST_LIST.size() > SQLProcessor.MAX_CONNECTIONS) {
|
||||
SQLProcessor.CONNECTION_TEST_LIST.remove(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void setFetchSize(Statement stmt, int fetchSize) throws SQLException {
|
||||
// do not set fetch size when using the cursor connection
|
||||
if (_connection instanceof CursorConnection) return;
|
||||
|
||||
// check if the statement was called with a specific fetch size, if not grab the default from the datasource
|
||||
if (fetchSize < 0) {
|
||||
Datasource ds = EntityConfig.getDatasource(this.helperInfo.getHelperBaseName());
|
||||
if (ds != null) {
|
||||
fetchSize = ds.getResultFetchSize();
|
||||
} else {
|
||||
Debug.logWarning("Datasource is null, not setting fetch size!", module);
|
||||
}
|
||||
}
|
||||
|
||||
// otherwise only set if the size is > -1 (0 is sometimes used to note ALL rows)
|
||||
if (fetchSize > -1) {
|
||||
stmt.setFetchSize(fetchSize);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkLockWaitInfo(Exception sqle) {
|
||||
String eMsg = sqle.getMessage();
|
||||
|
||||
// see if there is a lock wait timeout error, if so try to get and print more info about it
|
||||
// the string for Derby is "A lock could not be obtained within the time requested"
|
||||
// the string for MySQL is "Lock wait timeout exceeded; try restarting transaction"
|
||||
if (eMsg.indexOf("A lock could not be obtained within the time requested") >= 0 ||
|
||||
eMsg.indexOf("Lock wait timeout exceeded") >= 0) {
|
||||
Debug.logWarning(sqle, "Lock wait timeout error found in thread [" + Thread.currentThread().getId() + "]: (" + eMsg + ") when executing the SQL [" + _sql + "]", module);
|
||||
TransactionUtil.printAllThreadsTransactionBeginStacks();
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user