Class DIFUtilities


  • public final class DIFUtilities
    extends java.lang.Object
    This class contains most of DIF convenience methods. As the goal for basic DIF interfaces was to have really minimum required methods there, many useful utilities are implemented out of these interfaces as static external methods and located in this class.

    For example in DFItem there is no method like #getCapability(Class) finding the appropriate capability of the given type. You can use the utility method findCapability(DFItem,Class) method instead.

    Author:
    Petr Hamernik
    • Method Detail

      • findCapability

        public static <T extends DFCapability> T findCapability​(DFItem item,
                                                                java.lang.Class<T> capabilityClass)
        Find the capability which is instance of the given class.
        Type Parameters:
        T - type of the capability
        Parameters:
        item - The DFItem where we are asking for the capability; might be null
        capabilityClass - The required class of the capability
        Returns:
        The first capability which is instance of the required type or null if there is no such a capability or if the given item is null
      • findMimeType

        public static java.lang.String findMimeType​(DFField field)
      • findNewTypeWithOptions

        public static <T extends DFItemDFNewType<T> findNewTypeWithOptions​(java.util.List<DFNewType<T>> allNewTypes,
                                                                             boolean existingItem,
                                                                             java.lang.Class optionsClass)
        Find the appropriate DFNewType object in the list. Use this method if you are looking for a specific newtype among all newtypes provided by DFContainer.
        Parameters:
        allNewTypes - The original list of newtypes
        existingItem - The flag if newtype should be creating new objects or just promote the existing artefacts to a new DFItem
        optionsClass - The required type of options object provided by a DFNewType
        Returns:
        The first appropriate DFNewType or null.
      • findAllAppropriateNewTypes

        public static <T extends DFItem> java.util.List<DFNewType<T>> findAllAppropriateNewTypes​(java.util.List<DFNewType<T>> allNewTypes,
                                                                                                 boolean existingItem,
                                                                                                 java.lang.Class[] requiredCapabilities,
                                                                                                 java.lang.Class[] excludeCapabilities)
        Find all the appropriate DFNewType object in the list. Use this method if you are looking for a specific newtype among all newtypes provided by DFContainer.
        Parameters:
        allNewTypes - The original list of newtypes
        existingItem - The flag if newtype should be creating new objects or just promote the existing artefacts to a new DFItem
        requiredCapabilities - The required types (all must be included)
        excludeCapabilities - The required types (none of these can be included)
        Returns:
        All appropriate DFNewTypes or empty list (never returns null).
      • findFirstAppropriateNewType

        public static <T extends DFItemDFNewType<T> findFirstAppropriateNewType​(java.util.List<DFNewType<T>> allNewTypes,
                                                                                  boolean existingItem,
                                                                                  java.lang.Class[] requiredCapabilities,
                                                                                  java.lang.Class[] excludeCapabilities)
        Find the first the appropriate DFNewType object in the list. Use this method if you are looking for a specific newtype among all newtypes provided by DFContainer.
        Parameters:
        allNewTypes - The original list of newtypes
        existingItem - The flag if newtype should be creating new objects or just promote the existing artefacts to a new DFItem
        requiredCapabilities - The required types (all must be included)
        excludeCapabilities - The required types (none of these can be included)
        Returns:
        The first appropriate DFNewType or null.
      • findAppropriateNewType

        public static <T extends DFItemDFNewType<T> findAppropriateNewType​(java.util.List<DFNewType<T>> allNewTypes,
                                                                             boolean existingItem,
                                                                             java.lang.String type)
        Find the first the appropriate DFNewType object in the list. Use this method if you are looking for a specific implementation type. Use this method very carefully. It is usually better to find the newtype using required DFCapabilities instead of looking for specific implementation type.
        Parameters:
        allNewTypes - The original list of newtypes
        existingItem - The flag if newtype should be creating new objects or just promote the existing artefacts to a new DFItem
        type - The required DFItem implementation type
        Returns:
        The first appropriate DFNewType or null.
      • findConvertorFor

        public static DFDataConvertor findConvertorFor​(java.lang.Class<? extends DFFieldDataTypeCapability> type)
        Return appropriate data convertor for the specified type. Can return null if there is no such convertor registered.
        Parameters:
        type - The requested data type.
        Returns:
        The convertor or null
      • createSchemaField

        public static DFField createSchemaField​(DFEntity parent,
                                                java.lang.String fieldName,
                                                java.lang.String fieldType,
                                                boolean existing,
                                                com.im.commons.progress.DFEnvironmentRW env)
        A convenience method to create a field named `fieldName' of type `fieldType' in a parent Entity. The method uses DFNewType to look up appropriate code that creates the field. If the DFNewType cannot be found, the method throws UnsupportedOperationException. If the new type does not support the required options, it will throw IllegalArgumentException for the requested field type.
        Parameters:
        parent - The parent Entity
        fieldName - The n ame for the new field
        fieldType - The t ype for the new field (DBImplConstants.FIELD_xxx)
        existing - True, if a DFField for an existing storage object should be created, false, if storage artifacts should be created along
        env - The e xecution environment.
        Returns:
        The instance of new field
      • createSchemaEntity

        public static DFEntity createSchemaEntity​(DFSchema parent,
                                                  java.lang.String entityName,
                                                  java.lang.String entityType,
                                                  com.im.commons.progress.DFEnvironmentRW env)
        A convenience method to create a entity named `entityName' of type `entityType' in a parent Schema. If the name is already used by a different entity, the next available name will be used instead. The method uses DFNewType to look up appropriate code that creates the entity. If the DFNewType cannot be found, the method throws UnsupportedOperationException. If the new type does not support the required options, it will throw IllegalArgumentException for the requested entity type.
        Parameters:
        parent - The parent schema
        entityName - The n ame for the new entity
        entityType - The t ype for the new entity
        env - The e xecution environment.
        Returns:
        The instance of new entity
      • createDataTreeForEntity

        @Deprecated
        public static DFDataTree createDataTreeForEntity​(DFEntity entity,
                                                         com.im.commons.progress.DFEnvironmentRW env)
        Deprecated.
        Use @link {DFDataTrees.createDataTree(DFEntity rootEntity, String dataTreeName, DFEnvironmentRW env)}
        Creates a default datatree for the entity. This method is using standard DFNewType approach.
        Parameters:
        entity - for the data tree.
        env - environment for creating data tree.
        Returns:
        new dataTree.
      • findEntityDataProvider

        @Deprecated
        public static DFEntityDataProvider findEntityDataProvider​(DFEntity entity)
        Deprecated.
        Utility method just doing entity.getSchema().getDataProvider().getEntityDataProvider(entity).
        Parameters:
        entity - entity of interest
        Returns:
        the instance
      • findSchema

        @Deprecated
        public static DFSchema findSchema​(DFItem item)
        Deprecated.
        use DFSchemas.find(DFItem) instead. Will be removed two releases away from 5.12.
        Utility method finding parent schema for any DFItem type.
      • fieldsToSorts

        public static boolean[] fieldsToSorts​(DFField[] fields,
                                              boolean[] isAscendings)
      • canDestroy

        public static boolean canDestroy​(DFItem item)
        Returns:
        True, if the item can be destroyed and removed from the parent
      • safeEqualsIgnoreCase

        public static boolean safeEqualsIgnoreCase​(java.lang.String s1,
                                                   java.lang.String s2)
      • safeEqualsLists

        public static boolean safeEqualsLists​(java.util.List<java.lang.String> list1,
                                              java.util.List<java.lang.String> list2)
      • getOwnerUsername

        public static java.lang.String getOwnerUsername​(DFUserItem item)
        Try to find username of owner of given object. If the object has DFSharedObjectCapability it returns the name of user from this interface. Otherwise returns constant representing unknown user: USER_UNKNOWN (you can use == operator to test it).
        Parameters:
        item - Tested item
        Returns:
        The username of owner if it's possible to determine, otherwise magical constant USER_UNKNOWN. Never returns null.
      • amIOwner

        public static boolean amIOwner​(DFUserItem item)
        Test if currently logged user is owner of given object. If it's not possible to determine it, it expects user IS owner. The current user is obtained from item's schema from IJCUserLoginService. If this capability is not present, then it also expects the current user is only one in the system and so also owner of all objects.
        Parameters:
        item - Tested item
        Returns:
        False if currently logged user is NOT owner of item, otherwise true.
      • checkAmIOwner

        public static boolean checkAmIOwner​(DFSchema schema,
                                            java.lang.String owner)
      • getLockable

        public static com.im.commons.progress.DFLockable getLockable​(java.lang.Object item)
        Find the lockable for any object (DFItem or DFResultSet). If you are looking for views' lockable use getLockable(DFDataTree, boolean) instead.
      • getLockable

        public static com.im.commons.progress.DFLockable getLockable​(DFDataTree item,
                                                                     boolean forViewsOrQueries)
        Find lockable for datatree.
        Parameters:
        item - The datatree
        forViewsOrQueries - If true User lockable is returned, otherwise it returns standard schema DDL lockable
      • getLockable

        public static com.im.commons.progress.DFLockable getLockable​(DFView item)
      • getLockable

        public static com.im.commons.progress.DFLockable getLockable​(DFList item)
      • getLockable

        public static com.im.commons.progress.DFLockable getLockable​(DFQuery item)
      • getLockable

        public static com.im.commons.progress.DFLockable getLockable​(DFScript item)
      • getLockable

        public static com.im.commons.progress.DFLockable getLockable​(DFSchema item)
      • getLockable

        public static com.im.commons.progress.DFLockable getLockable​(DFEntity item)
      • getLockable

        public static com.im.commons.progress.DFLockable getLockable​(DFEntity item,
                                                                     boolean forLists)
      • getLockable

        public static com.im.commons.progress.DFLockable getLockable​(DFField item)
      • getLockable

        public static com.im.commons.progress.DFLockable getLockable​(DFResultSet item)
      • getLockable

        public static com.im.commons.progress.DFLockable getLockable​(DFEntityDataProvider item)
      • getLockable

        public static com.im.commons.progress.DFLockable getLockable​(DFRelationship rel)
      • weakEntityDataListener

        public static DFEntityDataListener weakEntityDataListener​(DFEntityDataListener l,
                                                                  DFEntityDataProvider source)
        Creates a weak implementation of DFEntityDataListener.
        Parameters:
        l - The listener to delegate to
        source - The source that the listener should detach from when listener l is freed, can be null
        Returns:
        A ChangeListener delegating to l.
      • findUsages

        public static java.util.List<DFRelationship> findUsages​(DFField field)
        Find all relationships where the given field participates. All these relationships must be also removed when deleting field.
      • findDependentLists

        public static java.util.List<DFList> findDependentLists​(java.util.List<DFField> fields)
        Find all DFLists depending on given fields. All these DFLists must be also deleted when deleting field
      • findDirectionFromOrigin

        public static DFRelationship.Direction findDirectionFromOrigin​(DFRelationship rel,
                                                                       DFEntity entity)
        Finds the relationship direction which originates at entity 'entity'. If the entity is neither source or destination of 'rel', an IllegalArgumentException is thrown.
        Parameters:
        rel - The r elationship of interest
        entity - The direction's originating entity
        Returns:
        The direction, that originates on 'entity'.
      • findOutgoingDirections

        public static java.util.List<DFRelationship.Direction> findOutgoingDirections​(DFEntity entity)
        Finds all relationship directions which originate in an entity.
        Parameters:
        entity - originating entity
        Returns:
        directions originating from an entity or an empty list if none found
      • findUsages

        public static java.util.List<DFDataTree.Edge> findUsages​(DFRelationship rel)
        Find all datatrees.edges which are built on top of given relationship. All these edges must be removed when deleting relationship.
      • findUsagesInDataTrees

        public static java.util.List<DFDataTree.Vertex> findUsagesInDataTrees​(DFEntity entity)
        Find all datatrees.vertexes which are built on top of given entity. All these edges must be removed when deleting relationship.
      • findEntityInDataTree

        public static DFDataTree.Vertex findEntityInDataTree​(DFDataTree.Vertex vertex,
                                                             DFEntity entity)
        Finds a vertex in the DataTree, which corresponds to the given entity. The search starts at the specified vertex (e.g. DFDataTree.getRootVertex()).
        Parameters:
        vertex - The root of the search
        entity - The entity to find
        Returns:
        The Vertex that corresponds to the given entity or null, if the entity does not have a Vertex in the subtree.
      • findAllTreeEntities

        public static java.util.Set<DFEntity> findAllTreeEntities​(DFDataTree.Vertex vertex)
        Collects all entities used in the specified vertex and its children. The set will always contain at least the vertex' own entity. The returned Set is a private copy and can be changed.
        Parameters:
        vertex - The root from where Entities should be collected
        Returns:
        The set of entities found.
      • findUsagesInRelationships

        public static java.util.List<DFRelationship> findUsagesInRelationships​(DFEntity entity)
        Find all relationships where the given entity participates. All these relationships must be also removed when deleting entity.
      • findFieldsUsedInRelationships

        public static java.util.Set<DFField> findFieldsUsedInRelationships​(DFEntity entity)
        Find all fields of specified entity which participate in any relationships.
        Parameters:
        entity - The entity which is searched.
        Returns:
        The list of entity's fields participating in any relationship.
      • findAllFieldsInExpression

        public static java.util.Set<DFField> findAllFieldsInExpression​(DFTermExpression term)
      • computePath

        public static DFRelationship.Direction[] computePath​(DFDataTree.Vertex vertex)
        Computes path of a vertex in a datatree.
        Parameters:
        vertex - for which path is computed
        Returns:
        path from dataTree's root vertex to provided vertex. If not found, null is returned
      • connectAutomatically

        @Deprecated
        public static DFSchema connectAutomatically​(DFSchemaProvider schemaProvider,
                                                    com.im.commons.progress.DFFeedback aFeedback)
        Automatically goes through schema connect process and returns fully-initialized schema. Never asks user (username, password, etc.). If any information is missing and schema can't be initialized without interaction with user then it just closes it and returns null. Make sure all information necessary for schema init are written in ijs schema properties.
        Parameters:
        schemaProvider - schema provider for connection
        aFeedback - feedBack for schema initialization
        Returns:
        The fully-initialized schema
      • registerWhenSchemaReady

        public static void registerWhenSchemaReady​(DFSchemaProvider schemaProvider,
                                                   DIFUtilities.SchemaReadyRunnable schemaReadyListener)
        Register to schema provider to be notified about schema providers status changes. The main reason of this method is to be notified when schema is ready, but it can be used to listen to all status changes. Important note: schemaReadyListener is registered to DFSchemaProvider weakly, so you must hold your reference to this schemaReadyListener. Otherwise it's unregistered and you will never be notified.

        This method immediately invokes (on the same thread) the status change for the current status of the schema provider and so schemaReady method is invoked too if schema is currently already prepared.

        The preferred usage is something like:

        
           mySchemaReadyListener = new DIFUtilities.SchemaReadyRunnable() {
               public void schemaReady(DFSchemaProvider schemaProvider, DFSchema schema) {
                   doSomething(schema);
                   // if you do not care about future changes of schema provider status (e.g. disconnect) then forgot
                   // reference to this object:
                   // mySchemaReadyListener = null;
               }
           };
           DIFUtilities.registerWhenSchemaReady(schemaProvider, mySchemaReadyListener);
         
      • registerListenerToDataTree

        public static java.lang.Object registerListenerToDataTree​(DFDataTree dt,
                                                                  java.beans.PropertyChangeListener pcl)
        Register listener to the datatree as well as to all its vertexes, entities and their fields. Property change events are fired with correct source, so you can recognize the origin of the event. The listener is automatically added to newly created fields or vertexes. The listener is registered using weak listeners and is automatically removed from all objects when it's not necessary. When register to datatree, you must keep the hard reference to the returned object. When the reference is released the listener is unregistered from all objects and you won't receive any future event; actually some more events can be fired, but it should stop firing them very shortly when next garbage collection is executed.
        Parameters:
        dt - The datatree you want to listen to changes
        pcl - The propery change listener to be invoked when any change is fired
        Returns:
        Keep this reference as long as you want to recieve property change events.
      • isMultiple

        public static boolean isMultiple​(DFRelationship.Direction dir)
        Determines, if the relationship end has 'multiple' cardinality. That is, multiple rows of 'src' entity may refer to a single 'dst' entity's row
        Parameters:
        dir - The direction to test
        Returns:
        True, if the 'src' endpoint has multiple cardinality.
      • connectRelationalData

        public static void connectRelationalData​(DFRelationship.Direction dir,
                                                 java.lang.Comparable<?> myID,
                                                 java.lang.Comparable<?> otherID,
                                                 com.im.commons.progress.DFEnvironmentRW env)
                                          throws DFRelationDataException
        Connects two rows of related data. This helper works around the ambivalence of DFRelationDataProvider's addRelation() and removeRelation() and swaps the IDs as appropriate.
        Parameters:
        myID - ID at 'this' end of the relation (value of source field of the 'dir' direction)
        otherID - ID at the 'other' end of the relation
        dir - The relationship direction
        Throws:
        DFRelationDataException
      • getForeignKeys

        public static java.util.Collection<com.im.commons.db.ddl.DBForeignKeyInfo> getForeignKeys​(DFSchema ijcSchema)
        Collects are FKs defined in the database schema, regardless of whether the FK is mapped to a Relationship or not. Returns empty collection, if the schema has no DB capability.
        Parameters:
        ijcSchema - The IJC schema
        Returns:
        The collection of DFForeignKeyInfo instances.
      • findForeignKey

        public static com.im.commons.db.ddl.DBForeignKeyInfo findForeignKey​(DFSchema ijcSchema,
                                                                            com.im.commons.db.util.SchemaQualifiedName fkName)
        Finds the named Foreign Key. Names are case-insensitive. Returns null, if the key is not found, or the schema has no DB capability.
        Parameters:
        ijcSchema - The IJC schema
        fkName - The name of the key
        Returns:
        DFForeignKey instance, or null if the name is not found.
      • findForeignKey

        public static com.im.commons.db.ddl.DBForeignKeyInfo findForeignKey​(DFSchema ijcSchema,
                                                                            com.im.commons.db.util.SchemaQualifiedName table,
                                                                            java.lang.String[] columnNames,
                                                                            DIFUtilities.FKSearchType pkfk)
        Finds a foreign key, which references the named columns as its PK or FK columns, depending on parameters
        Parameters:
        table - The t able name
        ijcSchema - The parent IJC schema
        columnNames - The c olumn names for the FK
        Returns:
        The foreign key if found, or null
      • fieldForColumn

        public static DFField fieldForColumn​(DFEntity entity,
                                             java.lang.String colName)
        Finds a DFField, that uses the named column. Returns first such DFField, or null, if the column is not used in any DFField.
        Parameters:
        entity - The parent of the DFField
        colName - The n ame of the underlying DB column
        Returns:
        The DFField or null.
      • convertValuesToCorrectType

        public static java.util.List convertValuesToCorrectType​(DFField field,
                                                                java.util.List values,
                                                                java.lang.String listName)
        Convert the list of values to correct type for the given field. For example when list containing just String instances is passed to this method with Integer field type, it returns the list where all objects will be Integer. Convertor's options are currently ignored. When conversion throws exception (it's not possible to convert the value), it's ignored, only info message is printed to log (listName parameter is used for this message).
        Parameters:
        field - This field is asked for convertor
        values - Values to be converted
        listName - List name is only used when reporting errors in conversion to log
        Returns:
        The list of values in correct type.
      • convertListValues

        public static java.util.List<? extends java.lang.Object> convertListValues​(DFField sourceField,
                                                                                   DFField targetField,
                                                                                   java.util.List<? extends java.lang.Object> sourceValues,
                                                                                   boolean forceValidation,
                                                                                   com.im.commons.progress.DFEnvironmentRO env)
        Converts a list of sourceField values to a list of targetField values. This method will search for entity data (rows) identified by the sourceField values and return the targetField value for each sourceField value. Both sourceField and targetField ought to be from the same entity. If there is no row in the entity for some sourceField value it is skipped. Hence the returned list may contain less values than the supplied sourceValues list. Also there is no guarantee that the returned list will contain values in the exact same order as the sourceValues list.
        Parameters:
        sourceField - Source field whose values are going to be converted.
        targetField - Field whose values are expected as result of this method.
        sourceValues - Values of sourceField.
        forceValidation - When true then this operation is going to SELECT database even when source and target field is the same. In other words it does validation and filters out non-existing values. When false this returns sourceValues if sourceValues == targetField.
        env - Environment for monitoring progress.
        Returns:
        The converted list values, never returns null.
        Since:
        6.2
      • findEntityByFieldID

        public static DFEntity findEntityByFieldID​(DFContainer<DFEntity> dfContainer,
                                                   java.lang.String fieldId)
        Return entity which contains the field with specified ID.
        Parameters:
        dfContainer - The entity DFContainer
        fieldId - The fieldId
        Returns:
        The entity or null (if not found)
      • getExtraProperty

        @Deprecated
        public static java.lang.String getExtraProperty​(DFItem item,
                                                        java.lang.Class<? extends ExtraDFItemProperty<?,​?>> extraProp)
        Deprecated.
        Since 5.10. Use ExtraDFItemProperties#getExtraProperty(DFItem item, Class<? extends ExtraDFItemProperty> extraProp).
        Utility method for getting value for extra property.
        Parameters:
        item - The entity or field
        extraProp - The property type
        Returns:
        Null if the property is not
      • getIJCUsername

        public static java.lang.String getIJCUsername​(DFSchema schema)
        Get the username of the IJC user or null if the user has not yet logged in.
        Returns:
        The name of the current user. e.g. "admin"
      • computeDiff

        public static <T> java.util.List<T>[] computeDiff​(java.util.List<? extends T> arr1,
                                                          java.util.List<? extends T> arr2)
      • getDefaultSchemaName

        public static java.lang.String getDefaultSchemaName​(DFSchema schema)
      • isExpressionStructural

        public static boolean isExpressionStructural​(DFTermExpression exp)
        Detects structural expressions
        Parameters:
        exp - tested expression
        Returns:
        true if expression is a structural expression
      • containsStructuralExpression

        public static boolean containsStructuralExpression​(DFTermExpression exp)
        Detects expressions containing structural sub-expressions
        Parameters:
        exp - tested expression
        Returns:
        true this expression or
      • splitOperands

        public static java.lang.String[] splitOperands​(java.lang.String operands)
        Utility method for separating comma separated strings, ie. when using code IN LIST operator.
        Parameters:
        operands - comma separated string
        Returns:
        split comma-separated operands, stripped of outer parenthesis. If the input is quoted, it won't get separated even when containing a comma