abstractcachableoperator.java

来自「Rapla是一个灵活的多用户资源管理系统。它提供的一些功能有:日历GUI」· Java 代码 · 共 914 行 · 第 1/3 页

JAVA
914
字号

    }


    /** check if we find an object with the same name.
     * If a different object (different id) with the same unique
     * attributes is found a UniqueKeyException will be thrown.
     */
    final protected void checkUnique(Collection entities) throws RaplaException {
        Iterator it = entities.iterator();
        while (it.hasNext()) {
            RefEntity entity = (RefEntity) it.next();
            String name = "";
            RefEntity entity2 = null;
            if ( DynamicType.TYPE.equals( entity.getRaplaType() )) {
                DynamicType type =(DynamicType) entity;
                name = type.getElementKey();

                entity2  = (RefEntity) cache.getDynamicType(name);
                if (entity2 != null && !entity2.equals(entity))
                    throwNotUnique(entity,name);
            }

            if ( Category.TYPE.equals( entity.getRaplaType()) ) {
            	Category category = (Category) entity;
            	Category[] categories = category.getCategories();
            	for ( int i= 0; i<categories.length;i++){
            		String key = categories[i].getKey();
            		for ( int j= i+1; j<categories.length; j++) {
            			String key2 =  categories[j].getKey();
            			if ( key == key2 || (key != null && key.equals( key2 ) ) ) {
            				throwNotUnique( (RefEntity) categories[i], key );
            			}
            		}
            	}
            }

            if ( User.TYPE.equals( entity.getRaplaType() ) ) {
                name = ((User) entity).getUsername();
                entity2 = (RefEntity) cache.getUser(name);
                if (entity2 != null && !entity2.equals(entity))
                    throwNotUnique(entity,name);
            }
        }
    }

    /** Check if the objects are consistent, so that they can be safely stored.*/
    protected void checkConsistency(Collection entities) throws RaplaException {
    	Iterator it = entities.iterator();
        while (it.hasNext()) {
            RefEntity entity = (RefEntity) it.next();
            // Check if the user group is missing
            if ( Category.TYPE.equals( entity.getRaplaType())  ) {
                if (entity.equals( cache.getSuperCategory() )) {
                    Category userGroups = ((Category) entity).getCategory( Permission.GROUP_CATEGORY_KEY );
                    if ( userGroups == null) {
                        throw new RaplaException("The category with the key '" + Permission.GROUP_CATEGORY_KEY + "' is missing.");
                    }
                } else {
                   Category category = (Category) entity;
                   if (category.getParent() == null) {
                       throw new RaplaException("The category " + category + " needs a parent.");
                   }
                }
            }
        }
    }

    /** Check if the references of each entity refers to an object in cache or in the passed collection.*/
    final protected void checkReferences(Collection entities) throws RaplaException {
        Iterator it = entities.iterator();
        while (it.hasNext()) {
            SimpleEntity entity = (SimpleEntity) it.next();
            Iterator it2 = entity.getReferences();
            while (it2.hasNext()) {
                RefEntity reference = (RefEntity) it2.next();
                if ( reference instanceof Preferences) {
                    throw new RaplaException("The current version of Rapla doesnt allow references to preferences.");
                }
                if ( reference instanceof Reservation) {
                    if (!( entity instanceof Appointment)) {
                        throw new RaplaException("The current version of Rapla doesnt allow references to events");
                    }
                }
                if ( reference instanceof Appointment) {
                    if (!( entity instanceof Reservation)) {
                        throw new RaplaException("The current version of Rapla doesnt allow references to appointment");
                    }
                }

                // Reference in cache ?
                if ( findPersistantVersion( reference ) != null)
                    continue;
                // References in collection.
                if (entities.contains(reference))
                    continue;
                throw new ReferenceNotFoundException(i18n.format("error.reference_not_stored", getName(reference)));
            }
        }
    }

    private String getName(Object object) {
        if (object == null)
            return (String) null;
        if (object instanceof Named)
            return (((Named)object).getName(i18n.getLocale()));
        return object.toString();
    }


    /** returns all entities that depend one the passed entities. In most cases
     one object depends on an other object if it has a reference to it.*/
    final protected Collection getDependencies(RefEntity entity) throws RaplaException {
        HashSet dependencyList = new HashSet();
        RaplaType type = entity.getRaplaType();
        if ( Category.TYPE.equals( type ) ||  DynamicType.TYPE.equals( type ) || Allocatable.TYPE.equals( type ) || User.TYPE.equals( type )) {
            dependencyList.addAll(getReferencingEntities(entity));
        } else {
            dependencyList.addAll(cache.getReferers(Preferences.TYPE, entity));
        }
        return dependencyList;
    }

    protected List getReferencingReservations( RefEntity entity )  throws RaplaException {
        ArrayList result = new ArrayList();
        Iterator it = this.getReservations(null,null,null).iterator();
        while (it.hasNext())
        {
            RefEntity referer = (RefEntity)it.next();
            if (referer != null && referer.isRefering(entity)) {
                result.add(referer);
            }
        }
        return result;
    }

    protected List getReferencingEntities(RefEntity entity) throws RaplaException{
        ArrayList list = new ArrayList();
        // Important to use getReferncingReservations here, because the method getReservations could be overidden in the subclass,
        // to avoid loading unneccessary Reservations in client/server mode.

        list.addAll(getReferencingReservations( entity ));
        list.addAll(cache.getReferers(Allocatable.TYPE, entity));
        list.addAll(cache.getReferers(Preferences.TYPE, entity));
        list.addAll(cache.getReferers(User.TYPE, entity));
        list.addAll(cache.getReferers(DynamicType.TYPE, entity));
        return list;
    }

    private int countDynamicTypes( Collection entities, String classificationType) {
        Iterator it = entities.iterator();
        int count = 0;
        while (it.hasNext()) {
            RaplaObject entity = (RaplaObject) it.next();
            if ( !DynamicType.TYPE.equals( entity.getRaplaType()) )
                continue;
            DynamicType type = (DynamicType) entity;
            if ( type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE).equals( classificationType ) ) {
                count ++;
            }
        }
        return count;
    }


    // Count dynamic-types to ensure that there is least one dynamic type left
    private void checkDynamicType( Collection entities, String classificationType) throws RaplaException {
        Collection allTypes = cache.getCollection( DynamicType.TYPE );
        int count = countDynamicTypes( entities, classificationType );
        if (  count >= 0 && count >= countDynamicTypes( allTypes, classificationType ) ) {
            throw new RaplaException(i18n.getString("error.one_type_requiered"));
        }
    }

    final protected void checkNoDependencies(Collection entities) throws RaplaException {
        HashSet dep = new HashSet();

        Iterator it = entities.iterator();
        while (it.hasNext()) {
            // Add dependencies for the entity
            dep.addAll(getDependencies( (RefEntity) it.next() ));
        }
        if (dep.size()>0) {
            Collection names = new ArrayList();
            Iterator entityIt = dep.iterator();
            while (entityIt.hasNext()) {
                RaplaObject type = (RaplaObject)entityIt.next();
                if ( type instanceof Named) {
                    names.add( ((Named)type).getName( i18n.getLocale() ));
                } else {
                    names.add( type.toString());
                }
            }
            throw new DependencyException( names );
        }
        // Count dynamic-types to ensure that there is least one dynamic type
        // for resources, for persons and for reservations
        checkDynamicType( entities, DynamicTypeAnnotations.VALUE_RESERVATION_CLASSIFICATION);
        checkDynamicType( entities, DynamicTypeAnnotations.VALUE_RESOURCE_CLASSIFICATION);
        checkDynamicType( entities, DynamicTypeAnnotations.VALUE_PERSON_CLASSIFICATION);
    }

    /** Entities will be resolved against resolveableEntities.
        If not found the ParentResolver will be used.
     */
    public EntityResolver createEntityResolver(Collection resolveableEntities,LocalCache parent) {
        EntityStore resolver = new EntityStore( parent, cache.getSuperCategory() );
        resolver.addAll( resolveableEntities);
        return resolver;
    }


    public RefEntity resolveId(Object id) throws EntityNotFoundException {
        return cache.resolve(id);
    }




    /** compares the version of the cached entities with the versions of the new entities.
     * Throws an Exception if the newVersion != cachedVersion
     */
    protected void checkVersions( Collection entities ) throws RaplaException {
        Iterator it = entities.iterator();
        while (it.hasNext()) {
            // Check Versions
            RefEntity entity = (RefEntity) it.next();
            RefEntity persistandVersion = findPersistantVersion( entity );
            // If the entities are newer, everything is o.k.
            if (persistandVersion != null && persistandVersion != entity && entity.getVersion () < persistandVersion.getVersion()) {
                getLogger().warn("There is a newer  version for: "
                                 + entity.getId()
                                 + " stored version :" + persistandVersion.getVersion()
                                 + " version to store :" + entity.getVersion());
                throw new RaplaException(getI18n().format("error.new_version", entity.toString()));
            }
        }
    }

    private RefEntity findPersistantVersion(RefEntity entity) {
        return (RefEntity) cache.get( entity.getId() );
    }


    public void authenticate(String username,String password)
        throws RaplaException {
        if (getLogger().isInfoEnabled())
            getLogger().info ("Check password for User " + username );
        User user= cache.getUser(username);
        if (user != null && checkPassword(((RefEntity)user).getId(), password ) ) {
        	return;
        }
        throw new RaplaSecurityException(i18n.getString("error.login"));
    }

    public boolean canChangePassword() {
        return true;
    }

    public void changePassword(User user,char[] oldPassword,char[] newPassword) throws RaplaException {
        if (getLogger().isInfoEnabled())
            getLogger().info ("Change password for User " + user.getUsername() );

        Object userId = ((RefEntity)user).getId();
        String password = new String(newPassword);
            if ( encryption != null )
                password = encrypt( password );
        cache.putPassword( userId, password );
        storeAndRemove( new Entity[] { editObject(user, null) }, Entity.ENTITY_ARRAY, user);
    }

    public Object getLock() {
        return lock;
    }

    protected String encrypt(String password) {
        synchronized ( md ) {
            md.reset();
            md.update( password.getBytes());
            return encryption + ":" + Tools.convert( md.digest() );
        }
    }

    private boolean checkPassword(Object userId, String password) {
        if (userId == null)
            return false;

        String correct_pw = (String)cache.getPassword(userId);
        if ( correct_pw == null) {
            return false;
        }
        if ( encryption != null && correct_pw.indexOf( encryption + ":" ) >= 0) {
            password = encrypt( password );
        }

        if ( correct_pw.equals(password)) {
            return true;
        }
        return false;
    }

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?