code
stringlengths
3
1.18M
language
stringclasses
1 value
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import org.rapla.framework.RaplaException; /** Thrown if the same key is used by another object. */ public class UniqueKeyException extends RaplaException { private static final long serialVersionUID = 1L; public UniqueKeyException(String text) { super(text); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import org.rapla.framework.RaplaException; public class EntityNotFoundException extends RaplaException { private static final long serialVersionUID = 1L; Comparable id; public EntityNotFoundException(String text) { this(text, null); } public EntityNotFoundException(String text, Comparable id) { super(text); this.id = id; } public Comparable getId() { return id; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; public interface CategoryAnnotations{ String KEY_NAME_COLOR="color"; String GROUP_ADMIN_KEY = "admin"; String GROUP_REGISTERER_KEY = "registerer"; String GROUP_MODIFY_PREFERENCES_KEY = "modify-preferences"; String GROUP_CAN_READ_EVENTS_FROM_OTHERS = "read-events-from-others"; String GROUP_CAN_CREATE_EVENTS = "create-events"; String GROUP_CAN_EDIT_TEMPLATES = "edit-templates"; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; /** This Exception is thrown when the application wants to write to a read-only entity. You should use the edit method to get a writable version of the entity. */ public class ReadOnlyException extends RuntimeException { private static final long serialVersionUID = 1L; public ReadOnlyException(Object object) { super("Can't modify entity [" + object + "]. Use the edit-method to get a writable version!"); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; /**Should be implemented by objects which can be uniquely associated with a User. */ public interface Ownable { void setOwner(User owner); User getOwner(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; public interface Annotatable { void setAnnotation(String key, String annotation) throws IllegalAnnotationException; //<T extends RaplaAnnotation> String getAnnotation(Class<T> annotation); //<T extends RaplaAnnotation> String getAnnotation(Class<T> annotation, T defaultValue); String getAnnotation(String key); String getAnnotation(String key, String defaultValue); String[] getAnnotationKeys(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; /* @see MultiLanguageName */ public interface MultiLanguageNamed extends Named { MultiLanguageName getName(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import java.util.Arrays; import java.util.Collection; import org.rapla.framework.RaplaException; public class DependencyException extends RaplaException { private static final long serialVersionUID = 1L; Collection<String> dependentObjects; public DependencyException(String message,String[] dependentObjectsNames) { this(message, Arrays.asList(dependentObjectsNames)); } public DependencyException(String message,Collection<String> dependentObjectsNames) { super(message); this.dependentObjects = dependentObjectsNames ; } public Collection<String> getDependencies() { return dependentObjects; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import java.util.Locale; /** Hierarchical categorization of information. * Categories can be used as attribute values. * @see org.rapla.entities.dynamictype.Attribute */ public interface Category extends MultiLanguageNamed,Entity<Category>,Timestamp, Annotatable, Comparable { final RaplaType<Category> TYPE = new RaplaType<Category>(Category.class, "category"); final String SUPER_CATEGORY_ID = TYPE.getLocalName() + "_0"; /** add a sub-category. * This category is set as parent of the passed category.*/ void addCategory(Category category); /** remove a sub-category */ void removeCategory(Category category); /** returns all subcategories */ Category[] getCategories(); /** returns the subcategory with the specified key. * null if subcategory was not found. */ Category getCategory(String key); /** find a sub-category in that equals the specified category. */ Category findCategory(Category copy); /** Returns the parent of this category or null if the category has no parent.*/ Category getParent(); /** returns true if the passed category is a direct child of this category */ boolean hasCategory(Category category); /** set the key of the category. The can be used in the getCategory() method for lookup. */ void setKey(String key); /** returns the key of the category */ String getKey(); /** returns true this category is an ancestor * (parent or parent of parent, ...) of the specified * category */ boolean isAncestorOf(Category category); /** returns the path form the rootCategory to this category. * Path elements are the category-names in the selected locale separated * with the / operator. If the rootCategory is null the path will be calculated * to the top-most parent. * Example: <strong>area51/aliencell</strong> */ String getPath(Category rootCategory,Locale locale); /** returns the max depth of the cildrens */ int getDepth(); /** returns the number of ancestors. * (How many Time you must call getParent() until you receive null) */ int getRootPathLength(); Category[] CATEGORY_ARRAY = new Category[0]; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import org.rapla.framework.RaplaException; public class IllegalAnnotationException extends RaplaException { private static final long serialVersionUID = 1L; public IllegalAnnotationException(String text) { super(text); } public IllegalAnnotationException(String text, Exception ex) { super(text, ex); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import java.util.Comparator; import org.rapla.entities.domain.Allocatable; import org.rapla.framework.RaplaException; /** The User-Class is mainly for authentication-purpose */ public interface User extends Entity<User>, Named, Comparable, Timestamp { final RaplaType<User> TYPE = new RaplaType<User>(User.class,"user"); /** returns the loginname */ String getUsername(); /** returns the complete name of user */ String getName(); /** returns the email of the user */ String getEmail(); /** returns if the user has admin-privilige */ boolean isAdmin(); void setPerson(Allocatable person) throws RaplaException; Allocatable getPerson(); void setUsername(String username); void setName(String name); void setEmail(String email); void setAdmin(boolean isAdmin); void addGroup(Category group); boolean removeGroup(Category group); Category[] getGroups(); boolean belongsTo( Category group ); public static User[] USER_ARRAY = new User[0]; Comparator<User> USER_COMPARATOR= new Comparator<User>() { @SuppressWarnings("unchecked") @Override public int compare(User u1, User u2) { if ( u2 == null) { return 1; } if ( u1==u2 || u1.equals(u2)) return 0; int result = String.CASE_INSENSITIVE_ORDER.compare( u1.getUsername() ,u2.getUsername() ); if ( result !=0 ) return result; result = u1.compareTo( u2 ); return result; } }; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import java.util.Date; public interface Timestamp { /** returns the creation date of the object. */ Date getCreateTime(); /** returns the date of last change of the object. */ Date getLastChanged(); /**@deprecated use getLastChanged instead */ Date getLastChangeTime(); User getLastChangedBy(); //String getId(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; public interface AttributeAnnotations { String KEY_EDIT_VIEW = "edit-view"; String VALUE_EDIT_VIEW_MAIN = "main-view"; String VALUE_EDIT_VIEW_ADDITIONAL = "additional-view"; String VALUE_EDIT_VIEW_NO_VIEW = "no-view"; String KEY_EXPECTED_ROWS = "expected-rows"; String KEY_EXPECTED_COLUMNS = "expected-columns"; String KEY_COLOR = "color"; String KEY_EMAIL = "email"; String KEY_CATEGORIZATION = "categorization"; String KEY_PERMISSION_MODIFY = "permission_modify"; String KEY_PERMISSION_READ = "permission_read"; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; import org.rapla.entities.Annotatable; import org.rapla.entities.Entity; import org.rapla.entities.MultiLanguageNamed; import org.rapla.entities.RaplaType; import org.rapla.entities.Timestamp; /** In rapla it is possible to dynamicly classify a reservation, resource or person with customized attributes. You can for example define a dynamicType called <em>room</em> with the attributes <em>name</em> and <em>seats</em> and classify all your room-resources as <em>room</em>. */ public interface DynamicType extends Entity<DynamicType>,MultiLanguageNamed,Annotatable, Timestamp { final RaplaType<DynamicType> TYPE = new RaplaType<DynamicType>(DynamicType.class, "dynamictype"); Attribute[] getAttributes(); /** returns null if the attribute is not found */ Attribute getAttribute(String key); void addAttribute(Attribute attribute); /** find an attribute in the dynamic type that equals the specified attribute This is usefull if you have the * persistant version of an attribute and want to discover the editable version in the working copy of a dynamic type */ String findAttribute(Attribute attribute); boolean hasAttribute(Attribute attribute); void removeAttribute(Attribute attribute); /** exchange the two attribute positions */ void exchangeAttributes(int index1, int index2); /** @deprecated use setKey instead*/ @Deprecated() void setElementKey(String elementKey); /** @deprecated use getKey instead*/ @Deprecated() String getElementKey(); void setKey(String key); String getKey(); /* creates a new classification and initializes it with the attribute defaults * @throws IllegalStateException when called from a non persistant instance of DynamicType */ Classification newClassification(); /* creates a new classification * @throws IllegalStateException when called from a non persistant instance of DynamicType */ Classification newClassification(boolean useDefaults); /* creates a new classification and tries to fill it with the values of the originalClassification. * @throws IllegalStateException when called from a non persistant instance of DynamicType */ Classification newClassification(Classification originalClassification); /* @throws IllegalStateException when called from a non persistant instance of DynamicType */ ClassificationFilter newClassificationFilter(); final DynamicType[] DYNAMICTYPE_ARRAY = new DynamicType[0]; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; import java.util.Collection; import java.util.Locale; import org.rapla.entities.Named; /** A Classification is an instance of a DynamicType. It holds the * attribute values for the attributesof the corresponding type. You * need one classification for each object you want to * classify. */ public interface Classification extends Named,Cloneable { DynamicType getType(); String getName(Locale locale); String getNamePlaning(Locale locale); Attribute[] getAttributes(); Attribute getAttribute(String key); void setValue(Attribute attribute,Object value); <T> void setValues(Attribute attribute,Collection<T> values); /** calls setValue(getAttribute(key),value)*/ void setValue(String key,Object value); /** calls getValue(getAttribte(key))*/ Object getValue(Attribute attribute); Object getValue(String key); Collection<Object> getValues(Attribute attribute); /** returns the value as a String in the selected locale.*/ String getValueAsString(Attribute attribute,Locale locale); Object clone(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; import java.util.Iterator; /** <p>A new ClassificationFilter for a classifications belonging to the same DynamicType can be created by the newClassificationFilter of the corresponding DynamicType object. </p> <p>You can set rules for the attributes of the DynamicType. A Classification (object implementing Classifiable) is matched by the filter when the conditions for each attribute-rule are matched (AND - function).</p> <p>A condition is an array of size 2, the first field contains the operator of the condition and the second the test value. When an attribute-rule has more than one condition, at least one of the conditions must be matched (OR - function ) . </p> <p> The following Example matches all classifications with a title-value that contains either "rapla" or "sourceforge" ,a size-value that is > 5 and a category-department-value that is either the departmentA or the departmentB. </p> <pre> DynamicType eventType = facade.getDynamicType("event"); ClassificationFilter f = eventType.newClassificationFilter(); f.addRule( "title" ,new Object { {"contains", "rapla"} ,{"contains", "sourceforge"} }); f.addRule( "size" ,new Object{ {">", new Integer(5)} }); Category departemntCategory = facade.getRootCategory().getCategory("departments"); Category departmentA = departmentCategory.getCategory("departmentA"); Category departmentB = departmentCategory.getCategory("departmentB"); f.addRule( "department" ,new Object{ {"=", departmentA} ,{ "=", departmentB} }); </pre> @see Classification */ public interface ClassificationFilter extends Cloneable { DynamicType getType(); /** Defines a rule for the passed attribute. */ void setRule(int index, String attributeName,Object[][] conditions); void setRule(int index, Attribute attribute,Object[][] conditions); /** appends a rule. * @see #setRule*/ void addRule(String attributeName,Object[][] conditions); /** shortcut to * <pre> * f.addRule( attributeName ,new Object{ {"=", object}} }); * </pre> * @param attributeName * @param object */ void addEqualsRule( String attributeName,Object object); /** shortcut to * <pre> * f.addRule( attributeName ,new Object{ {"is", object}} }); * </pre> * @param attributeName * @param object */ void addIsRule( String attributeName,Object object); int ruleSize(); Iterator<? extends ClassificationFilterRule> ruleIterator(); void removeAllRules(); void removeRule(int index); boolean matches(Classification classification); ClassificationFilter clone(); final ClassificationFilter[] CLASSIFICATIONFILTER_ARRAY = new ClassificationFilter[0]; ClassificationFilter[] toArray(); class Util { static public boolean matches(ClassificationFilter[] filters, Classifiable classifiable) { Classification classification = classifiable.getClassification(); for (int i = 0; i < filters.length; i++) { if (filters[i].matches(classification)) { return true; } } return false; } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype.internal; import java.util.Date; import org.rapla.components.util.ParseDateException; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.ClassificationFilterRule; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.storage.internal.ReferenceHandler; public final class ClassificationFilterRuleImpl extends ReferenceHandler implements ClassificationFilterRule ,java.io.Serializable { // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; String[] operators; String[] ruleValues; String attributeId; ClassificationFilterRuleImpl() { } ClassificationFilterRuleImpl(Attribute attribute, String[] operators,Object[] ruleValues) { attributeId = attribute.getId(); DynamicType type = attribute.getDynamicType(); if ( type== null) { throw new IllegalArgumentException("Attribute type cannot be null"); } putEntity("dynamictype",type); this.operators = operators; this.ruleValues = new String[ruleValues.length]; RaplaType refType = attribute.getRefType(); for (int i=0;i<ruleValues.length;i++) { Object ruleValue = ruleValues[i]; if (ruleValue instanceof Entity) { putEntity(String.valueOf(i),(Entity)ruleValue); //unresolvedRuleValues[i] = ((Entity)ruleValues[i]).getId(); } else if (refType != null && (ruleValue instanceof String) /*&& refType.isId(ruleValue)*/) { putId(String.valueOf(i),(String)ruleValue); } else { setValue(i, ruleValue); } } } public boolean needsChange(Attribute typeAttribute) { Object[] ruleValues = getValues(); for (int i=0;i<ruleValues.length;i++) if (typeAttribute.needsChange(ruleValues[i])) return true; return false; } public void commitChange(Attribute typeAttribute) { Object[] ruleValues = getValues(); for (int i=0;i<ruleValues.length;i++) { Object oldValue = ruleValues[i]; Object newValue = typeAttribute.convertValue(oldValue); setValue(i, newValue); } } /** find the attribute of the given type that matches the id */ private Attribute findAttribute(DynamicType type,Object id) { Attribute[] typeAttributes = type.getAttributes(); for (int i=0; i<typeAttributes.length; i++) { if (((Entity)typeAttributes[i]).getId().equals(id)) { return typeAttributes[i]; } } return null; } public Attribute getAttribute() { DynamicType dynamicType = getDynamicType(); return findAttribute(dynamicType, attributeId); } public DynamicType getDynamicType() { return getEntity("dynamictype", DynamicType.class); } @Override protected Class<? extends Entity> getInfoClass(String key) { if ( key.equals("dynamictype")) { return DynamicType.class; } Attribute attribute = getAttribute(); if ( key.length() > 0 && Character.isDigit(key.charAt(0))) { //int index = Integer.parseInt(key); AttributeType type = attribute.getType(); if (type == AttributeType.CATEGORY ) { return Category.class; } else if ( type == AttributeType.ALLOCATABLE) { return Allocatable.class; } } return null; } public String[] getOperators() { return this.operators; } public Object[] getValues() { Object[] result = new Object[operators.length]; Attribute attribute = getAttribute(); for (int i=0;i<operators.length;i++) { Object value = getValue(attribute,i); result[i] = value; } return result; } private Object getValue(Attribute attribute, int index) { AttributeType type = attribute.getType(); if (type == AttributeType.CATEGORY ) { return getEntity(String.valueOf(index), Category.class); } else if (type == AttributeType.ALLOCATABLE) { return getEntity(String.valueOf(index), Allocatable.class); } String stringValue = ruleValues[index]; if ( stringValue == null) { return null; } if (type == AttributeType.STRING) { return stringValue; } else if (type == AttributeType.BOOLEAN) { return Boolean.parseBoolean( stringValue); } else if (type == AttributeType.INT ) { return Long.parseLong(stringValue); } else if (type == AttributeType.DATE) { try { return SerializableDateTimeFormat.INSTANCE.parseTimestamp( stringValue); } catch (ParseDateException e) { return null; } } else { throw new IllegalStateException("Attributetype " + type + " not supported in filter"); } } private void setValue(int i, Object ruleValue) { String newValue; if (ruleValue instanceof Entity) { putEntity(String.valueOf(i), (Entity)ruleValue); newValue = null; } else if ( ruleValue instanceof Date) { Date date = (Date) ruleValue; newValue= SerializableDateTimeFormat.INSTANCE.formatTimestamp(date); } else { newValue = ruleValue != null ? ruleValue.toString() : null; removeId( String.valueOf( i)); } ruleValues[i] = newValue; } boolean matches(Object value) { //String[] ruleOperators = getOperators(); Attribute attribute = getAttribute(); for (int i=0;i<operators.length;i++) { String operator = operators[i]; if (matches(attribute,operator,i,value)) return true; } return false; } private boolean matches(Attribute attribute,String operator,int index,Object value) { AttributeType type = attribute.getType(); Object ruleValue = getValue(attribute, index); if (type == AttributeType.CATEGORY) { Category category = (Category) ruleValue; if (category == null) { return (value == null); } if ( operator.equals("=") ) { return value != null && category.isIdentical((Category)value); } else if ( operator.equals("is") ) { return value != null && (category.isIdentical((Category)value) || category.isAncestorOf((Category)value)); } } else if (type == AttributeType.ALLOCATABLE) { Allocatable allocatable = (Allocatable) ruleValue; if (allocatable == null) { return (value == null); } if ( operator.equals("=") ) { return value != null && allocatable.isIdentical((Allocatable)value); } else if ( operator.equals("is") ) { return value != null && (allocatable.isIdentical((Allocatable)value) ); // || category.isAncestorOf((Category)value)); } } else if (type == AttributeType.STRING) { if (ruleValue == null) { return (value == null); } if ( operator.equals("is") || operator.equals("=")) { return value != null && value.equals( ruleValue ); } else if ( operator.equals("contains") ) { String string = ((String)ruleValue).toLowerCase(); if (string == null) return true; string = string.trim(); if (value == null) return string.length() == 0; return (((String)value).toLowerCase().indexOf(string)>=0); } else if ( operator.equals("starts") ) { String string = ((String)ruleValue).toLowerCase(); if (string == null) return true; string = string.trim(); if (value == null) return string.length() == 0; return (((String)value).toLowerCase().startsWith(string)); } } else if (type == AttributeType.BOOLEAN) { Boolean boolean1 = (Boolean)ruleValue; Boolean boolean2 = (Boolean)value; if (boolean1 == null) { return (boolean2 == null || boolean2.booleanValue()); } if (boolean2 == null) { return !boolean1.booleanValue(); } return (boolean1.equals(boolean2)); } else if (type == AttributeType.INT || type ==AttributeType.DATE) { if(ruleValue == null) { if (operator.equals("<>")) if(value == null) return false; else return true; else if (operator.equals("=")) if(value == null) return true; else return false; else return false; } if(value == null) return false; long long1 = type == AttributeType.INT ? ((Long) value).longValue() : ((Date) value).getTime(); long long2 = type == AttributeType.INT ? ((Long) ruleValue).longValue() : ((Date) ruleValue).getTime(); if (operator.equals("<")) { return long1 < long2; } else if (operator.equals("=")) { return long1 == long2; } else if (operator.equals(">")) { return long1 > long2; } else if (operator.equals(">=")) { return long1 >= long2; } else if (operator.equals("<=")) { return long1 >= long2; } else if (operator.equals("<>")) { return long1 != long2; } } return false; } public String toString() { StringBuilder buf = new StringBuilder(); buf.append(getAttribute().getKey()); Object[] values = getValues(); String[] operators = getOperators(); for ( int i=0;i<values.length;i++) { String operator = i<operators.length ? operators[i] : "="; buf.append(" " + operator + " "); buf.append(values[i]); buf.append(", "); } return buf.toString(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.RaplaType; import org.rapla.entities.ReadOnlyException; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.entities.dynamictype.internal.ParsedText.EvalContext; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.UnresolvableReferenceExcpetion; /** Use the method <code>newClassification()</code> of class <code>DynamicType</code> to * create a classification. Once created it is not possible to change the * type of a classifiction. But you can replace the classification of an * object implementing <code>Classifiable</code> with a new one. * @see DynamicType * @see org.rapla.entities.dynamictype.Classifiable */ public class ClassificationImpl implements Classification,DynamicTypeDependant, EntityReferencer { private String typeId; private String type; private Map<String,List<String>> data = new LinkedHashMap<String,List<String>>(); private transient boolean readOnly = false; private transient TextCache name; private transient TextCache namePlaning; private transient EntityResolver resolver; /** stores the nonreference values like integers,boolean and string.*/ //HashMap<String,Object> attributeValueMap = new HashMap<String,Object>(1); /** stores the references to the dynamictype and the reference values */ //transient ReferenceHandler referenceHandler = new ReferenceHandler(data); class TextCache { String nameString; ParsedText lastParsedAnnotation; public String getName(Locale locale, String keyNameFormat) { DynamicTypeImpl type = (DynamicTypeImpl)getType(); ParsedText parsedAnnotation = type.getParsedAnnotation( keyNameFormat ); if ( parsedAnnotation == null) { return type.toString(); } if (nameString != null) { if (parsedAnnotation.equals(lastParsedAnnotation)) return nameString; } lastParsedAnnotation = parsedAnnotation; EvalContext evalContext = new EvalContext(locale) { public Classification getClassification() { return ClassificationImpl.this; } }; nameString = parsedAnnotation.formatName(evalContext).trim(); return nameString; } } public ClassificationImpl() { } ClassificationImpl(DynamicTypeImpl dynamicType) { typeId = dynamicType.getId(); type = dynamicType.getKey(); } public void setResolver( EntityResolver resolver) { this.resolver = resolver; } public void setReadOnly() { this.readOnly = true; } public boolean isReadOnly() { return readOnly; } public void checkWritable() { if ( readOnly ) throw new ReadOnlyException( this ); } @Override public Iterable<ReferenceInfo> getReferenceInfo() { List<ReferenceInfo> result = new ArrayList<ReferenceInfo>(); String parentId = getParentId(); result.add( new ReferenceInfo(parentId, DynamicType.class) ); DynamicTypeImpl type = getType(); for ( Map.Entry<String,List<String>> entry:data.entrySet()) { String key = entry.getKey(); Attribute attribute = type.getAttribute(key); RaplaType refType = attribute.getRefType(); if ( attribute == null || refType == null) { continue; } List<String> values = entry.getValue(); if (values != null ) { @SuppressWarnings("unchecked") Class<? extends Entity> class1 = refType.getTypeClass(); for ( String value:values) { result.add(new ReferenceInfo(value, class1) ); } } } return result; } private String getParentId() { if (typeId != null) return typeId; if (type == null) { throw new UnresolvableReferenceExcpetion( "type and parentId are both not set"); } DynamicType dynamicType = resolver.getDynamicType( type); if ( dynamicType == null) { throw new UnresolvableReferenceExcpetion( type); } typeId = dynamicType.getId(); return typeId; } public DynamicTypeImpl getType() { if ( resolver == null) { throw new IllegalStateException("Resolver not set on "+ toString()); } String parentId = getParentId(); DynamicTypeImpl type = (DynamicTypeImpl) resolver.tryResolve( parentId, DynamicType.class); if ( type == null) { throw new UnresolvableReferenceExcpetion(DynamicType.class +":" + parentId + " " +data); } return type; } public String getName(Locale locale) { // display name = Title of event if ( name == null) { name = new TextCache(); } return name.getName(locale, DynamicTypeAnnotations.KEY_NAME_FORMAT); } public String getNamePlaning(Locale locale) { if ( namePlaning == null) { namePlaning = new TextCache(); } return namePlaning.getName(locale, DynamicTypeAnnotations.KEY_NAME_FORMAT_PLANNING); } public String getValueAsString(Attribute attribute,Locale locale) { Collection values = getValues(attribute); StringBuilder buf = new StringBuilder(); boolean first = true; for ( Object value: values) { if (first) { first = false; } else { buf.append(", "); } buf.append( ((AttributeImpl)attribute).getValueAsString( locale, value)); } String result = buf.toString(); return result; } public Attribute getAttribute(String key) { return getType().getAttribute(key); } public Attribute[] getAttributes() { return getType().getAttributes(); } public boolean needsChange(DynamicType newType) { if ( !hasType (newType )) { return false; } DynamicTypeImpl type = getType(); if ( !newType.getKey().equals( type.getKey())) return true; for (String key:data.keySet()) { Attribute attribute = getType().getAttribute(key); if ( attribute == null) { return true; } String attributeId = attribute.getId(); if (type.hasAttributeChanged( (DynamicTypeImpl)newType , attributeId)) return true; } return false; } boolean hasType(DynamicType type) { return getType().equals( type); } public void commitChange(DynamicType type) { if ( !hasType (type )) { return; } Collection<String> removedKeys = new ArrayList<String>(); Map<Attribute,Attribute> attributeMapping = new HashMap<Attribute,Attribute>(); for (String key:data.keySet()) { Attribute attribute = getType().getAttribute(key); Attribute attribute2 = type.getAttribute(key); // key now longer availabe so remove it if ( attribute2 == null) { removedKeys.add( key ); } if ( attribute == null) { continue; } String attId = attribute.getId(); Attribute newAtt = findAttributeById(type, attId); if ( newAtt != null) { attributeMapping.put(attribute, newAtt); } } for (Attribute attribute: attributeMapping.keySet()) { Collection<Object> convertedValues = new ArrayList<Object>(); Collection<?> valueCollection = getValues( attribute); Attribute newAttribute = attributeMapping.get( attribute); for (Object oldValue: valueCollection) { Object newValue = newAttribute.convertValue(oldValue); if ( newValue != null) { convertedValues.add( newValue); } } setValues(newAttribute, convertedValues); } for (String key:removedKeys) { data.remove( key ); } this.type = type.getKey(); name = null; namePlaning = null; } /** find the attribute of the given type that matches the id */ private Attribute findAttributeById(DynamicType type,String id) { Attribute[] typeAttributes = type.getAttributes(); for (int i=0; i<typeAttributes.length; i++) { String key2 = typeAttributes[i].getId(); if (key2.equals(id)) { return typeAttributes[i]; } } return null; } public void setValue(String key,Object value) { Attribute attribute = getAttribute( key ); if ( attribute == null ) { throw new NoSuchElementException("No attribute found for key " + key); } setValue( attribute,value); } public Object getValue(String key) { Attribute attribute = getAttribute( key ); if ( attribute == null ) { throw new NoSuchElementException("No attribute found for key " + key); } return getValue(getAttribute(key)); } public void setValue(Attribute attribute,Object value) { checkWritable(); if ( value != null && !(value instanceof Collection<?>)) { value = Collections.singleton( value); } setValues(attribute, (Collection<?>) value); } public <T> void setValues(Attribute attribute,Collection<T> values) { checkWritable(); String attributeKey = attribute.getKey(); if ( values == null || values.isEmpty()) { data.remove(attributeKey); name = null; namePlaning = null; return; } ArrayList<String> newValues = new ArrayList<String>(); for (Object value:values) { String stringValue = ((AttributeImpl)attribute).toStringValue(value); if ( stringValue != null) { newValues.add(stringValue); } } data.put(attributeKey,newValues); //isNameUpToDate = false; name = null; namePlaning = null; } public <T> void addValue(Attribute attribute,T value) { checkWritable(); String attributeKey = attribute.getKey(); String stringValue = ((AttributeImpl)attribute).toStringValue( value); if ( stringValue == null) { return; } List<String> l = data.get(attributeKey); if ( l == null) { l = new ArrayList<String>(); data.put(attributeKey, l); } l.add(stringValue); } public Collection<Object> getValues(Attribute attribute) { if ( attribute == null ) { throw new NullPointerException("Attribute can't be null"); } String attributeKey = attribute.getKey(); // first lookup in attribute map List<String> list = data.get(attributeKey); if ( list == null || list.size() == 0) { return Collections.emptyList(); } List<Object> result = new ArrayList<Object>(); for (String value:list) { Object obj; try { obj = ((AttributeImpl)attribute).fromString(resolver,value); result.add( obj); } catch (EntityNotFoundException e) { } } return result; } public Object getValue(Attribute attribute) { if ( attribute == null ) { throw new NullPointerException("Attribute can't be null"); } String attributeKey = attribute.getKey(); // first lookup in attribute map List<String> o = data.get(attributeKey); if ( o == null || o.size() == 0) { return null; } String stringRep = o.get(0); Object fromString; try { fromString = ((AttributeImpl)attribute).fromString(resolver, stringRep); return fromString; } catch (EntityNotFoundException e) { throw new IllegalStateException(e.getMessage()); } } public ClassificationImpl clone() { ClassificationImpl clone = new ClassificationImpl((DynamicTypeImpl)getType()); //clone.referenceHandler = (ReferenceHandler) referenceHandler.clone((Map<String, List<String>>) ((HashMap<String, List<String>>)data).clone()); //clone.attributeValueMap = (HashMap<String,Object>) attributeValueMap.clone(); for ( Map.Entry<String,List<String>> entry: data.entrySet()) { String key = entry.getKey(); List<String> value = new ArrayList<String>(entry.getValue()); clone.data.put(key, value); } clone.resolver = resolver; clone.typeId = getParentId(); clone.type = type; clone.name = null; clone.namePlaning = null; clone.readOnly = false;// clones are always writable return clone; } public String toString() { try { StringBuilder builder = new StringBuilder(); boolean first = true; builder.append("{"); for ( Attribute attribute:getAttributes()) { if ( !first) { builder.append(", "); } else { first = false; } String key = attribute.getKey(); String valueAsString = getValueAsString(attribute, null); builder.append(key); builder.append(':'); builder.append(valueAsString); } builder.append("}"); return builder.toString(); } catch (Exception ex) { return data.toString(); } } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { throw new CannotExistWithoutTypeException(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.components.util.iterator.NestedIterator; import org.rapla.entities.Entity; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.entities.dynamictype.internal.ParsedText.EvalContext; import org.rapla.entities.dynamictype.internal.ParsedText.Function; import org.rapla.entities.dynamictype.internal.ParsedText.ParseContext; import org.rapla.entities.internal.ModifiableTimestamp; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.ParentEntity; import org.rapla.entities.storage.internal.SimpleEntity; final public class DynamicTypeImpl extends SimpleEntity implements DynamicType, ParentEntity, ModifiableTimestamp { private Date lastChanged; private Date createDate; // added an attribute array for performance reasons List<AttributeImpl> attributes = new ArrayList<AttributeImpl>(); MultiLanguageName name = new MultiLanguageName(); String key = ""; //Map<String,String> unparsedAnnotations = new HashMap<String,String>(); Map<String,ParsedText> annotations = new HashMap<String,ParsedText>(); transient DynamicTypeParseContext parseContext = new DynamicTypeParseContext(this); transient Map<String,AttributeImpl> attributeIndex; public DynamicTypeImpl() { this( new Date(),new Date()); } public DynamicTypeImpl(Date createDate, Date lastChanged) { this.createDate = createDate; this.lastChanged = lastChanged; } public void setResolver( EntityResolver resolver) { super.setResolver( resolver); for (AttributeImpl child:attributes) { child.setParent( this); } for ( ParsedText annotation: annotations.values()) { try { annotation.init(parseContext); } catch (IllegalAnnotationException e) { } } } public RaplaType<DynamicType> getRaplaType() {return TYPE;} public boolean isInternal() { boolean result =key.startsWith("rapla:"); return result; } public Classification newClassification() { return newClassification( true ); } public Classification newClassification(boolean useDefaults) { if ( !isReadOnly()) { throw new IllegalStateException("You can only create Classifications from a persistant Version of DynamicType"); } final ClassificationImpl classification = new ClassificationImpl(this); if ( resolver != null) { classification.setResolver( resolver); } // Array could not be up todate final Attribute[] attributes2 = getAttributes(); if ( useDefaults) { for ( Attribute att: attributes2) { final Object defaultValue = att.defaultValue(); if ( defaultValue != null) { classification.setValue(att, defaultValue); } } } return classification; } public Classification newClassification(Classification original) { if ( !isReadOnly()) { throw new IllegalStateException("You can only create Classifications from a persistant Version of DynamicType"); } final ClassificationImpl newClassification = (ClassificationImpl) newClassification(true); { Attribute[] attributes = original.getAttributes(); for (int i=0;i<attributes.length;i++) { Attribute originalAttribute = attributes[i]; String attributeKey = originalAttribute.getKey(); Attribute newAttribute = newClassification.getAttribute( attributeKey ); Object defaultValue = originalAttribute.defaultValue(); Object originalValue = original.getValue( attributeKey ); if ( newAttribute != null && newAttribute.getType().equals( originalAttribute.getType())) { Object newDefaultValue = newAttribute.defaultValue(); // If the default value of the new type differs from the old one and the value is the same as the old default then use the new default if ( newDefaultValue != null && ((defaultValue == null && originalValue == null )|| (defaultValue != null && originalValue != null && !newDefaultValue.equals(defaultValue) && (originalValue.equals( defaultValue))))) { newClassification.setValue( newAttribute, newDefaultValue); } else { newClassification.setValue( newAttribute, newAttribute.convertValue( originalValue )); } } } return newClassification; } } public ClassificationFilter newClassificationFilter() { if ( !isReadOnly()) { throw new IllegalStateException("You can only create ClassificationFilters from a persistant Version of DynamicType"); } ClassificationFilterImpl classificationFilterImpl = new ClassificationFilterImpl(this); if ( resolver != null) { classificationFilterImpl.setResolver( resolver); } return classificationFilterImpl; } public MultiLanguageName getName() { return name; } public void setReadOnly() { super.setReadOnly(); name.setReadOnly( ); } public String getName(Locale locale) { if ( locale == null) { return name.getName( null); } String language = locale.getLanguage(); return name.getName(language); } public String getAnnotation(String key) { ParsedText parsedAnnotation = annotations.get(key); if ( parsedAnnotation != null) { return parsedAnnotation.getExternalRepresentation(parseContext); } else { return null; } } @Deprecated public Date getLastChangeTime() { return lastChanged; } @Override public Date getLastChanged() { return lastChanged; } public Date getCreateTime() { return createDate; } public void setLastChanged(Date date) { checkWritable(); lastChanged = date; } @Override public Iterable<ReferenceInfo> getReferenceInfo() { return new IteratorChain<ReferenceInfo>(super.getReferenceInfo(), new NestedIterator<ReferenceInfo,AttributeImpl>( attributes ) { public Iterable<ReferenceInfo> getNestedIterator(AttributeImpl obj) { return obj.getReferenceInfo(); } } ); } @Override public void addEntity(Entity entity) { Attribute attribute = (Attribute) entity; attributes.add((AttributeImpl) attribute); if (attribute.getDynamicType() != null && !this.isIdentical(attribute.getDynamicType())) throw new IllegalStateException("Attribute '" + attribute + "' belongs to another dynamicType :" + attribute.getDynamicType()); ((AttributeImpl) attribute).setParent(this); } public String getAnnotation(String key, String defaultValue) { String annotation = getAnnotation( key ); return annotation != null ? annotation : defaultValue; } public void setAnnotation(String key,String annotation) throws IllegalAnnotationException { checkWritable(); if (annotation == null) { annotations.remove(key); return; } ParsedText parsedText = new ParsedText(annotation); parsedText.init(parseContext); annotations.put(key,parsedText); } public String[] getAnnotationKeys() { return annotations.keySet().toArray(RaplaObject.EMPTY_STRING_ARRAY); } @Deprecated public void setElementKey(String elementKey) { setKey(elementKey); } public void setKey(String key) { checkWritable(); this.key = key; for ( ParsedText text:annotations.values()) { text.updateFormatString(parseContext); } } public String getElementKey() { return getKey(); } public String getKey() { return key; } /** exchange the two attribute positions */ public void exchangeAttributes(int index1, int index2) { checkWritable(); Attribute[] attribute = getAttributes(); Attribute attribute1 = attribute[index1]; Attribute attribute2 = attribute[index2]; List<AttributeImpl> newMap = new ArrayList<AttributeImpl>(); for (int i=0;i<attribute.length;i++) { Attribute att; if (i == index1) att = attribute2; else if (i == index2) att = attribute1; else att = attribute[i]; newMap.add((AttributeImpl) att); } attributes = newMap; } /** find an attribute in the dynamic-type that equals the specified attribute. */ public Attribute findAttributeForId(Object id) { Attribute[] typeAttributes = getAttributes(); for (int i=0; i<typeAttributes.length; i++) { if (((Entity)typeAttributes[i]).getId().equals(id)) { return typeAttributes[i]; } } return null; } /** * @param attributeImpl * @param key */ public void keyChanged(AttributeImpl attributeImpl, String key) { attributeIndex = null; for ( ParsedText text:annotations.values()) { text.updateFormatString(parseContext); } } public void removeAttribute(Attribute attribute) { checkWritable(); String matchingAttributeKey = findAttribute( attribute ); if ( matchingAttributeKey == null) { return; } attributes.remove( attribute); if (this.equals(attribute.getDynamicType())) { if (((AttributeImpl) attribute).isReadOnly()) { throw new IllegalArgumentException("Attribute is not writable. It does not belong to the same dynamictype instance"); } ((AttributeImpl) attribute).setParent(null); } } public String findAttribute(Attribute attribute) { for ( AttributeImpl att: attributes ) { if (att.equals( attribute)) { return att.getKey(); } } return null; } public void addAttribute(Attribute attribute) { checkWritable(); if ( hasAttribute(attribute)) { return; } addEntity(attribute); attributeIndex = null; } public boolean hasAttribute(Attribute attribute) { return attributes.contains( attribute ); } public Attribute[] getAttributes() { return attributes.toArray(Attribute.ATTRIBUTE_ARRAY); } public AttributeImpl getAttribute(String key) { if ( attributeIndex == null) { attributeIndex = new HashMap<String, AttributeImpl>(); for ( AttributeImpl att:attributes) { attributeIndex.put( att.getKey(), att); } } AttributeImpl attributeImpl = attributeIndex.get( key); return attributeImpl; } public ParsedText getParsedAnnotation(String key) { return annotations.get( key ); } @SuppressWarnings("unchecked") public Collection<AttributeImpl> getSubEntities() { return attributes; } public DynamicTypeImpl clone() { DynamicTypeImpl clone = new DynamicTypeImpl(); super.deepClone(clone); clone.lastChanged = lastChanged; clone.createDate = createDate; clone.name = (MultiLanguageName) name.clone(); clone.key = key; for (AttributeImpl att:clone.getSubEntities()) { ((AttributeImpl)att).setParent(clone); } clone.annotations = new LinkedHashMap<String, ParsedText>(); DynamicTypeParseContext parseContext = new DynamicTypeParseContext(clone); for (Map.Entry<String,ParsedText> entry: annotations.entrySet()) { String annotation = entry.getKey(); ParsedText parsedAnnotation =entry.getValue(); String parsedValue = parsedAnnotation.getExternalRepresentation(parseContext); try { clone.setAnnotation(annotation, parsedValue); } catch (IllegalAnnotationException e) { throw new IllegalStateException("Can't parse annotation back", e); } } return clone; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(" ["); buf.append ( super.toString()) ; buf.append("] key="); buf.append( getKey() ); buf.append(": "); if ( attributes != null ) { Attribute[] att = getAttributes(); for ( int i=0;i<att.length; i++){ if ( i> 0) buf.append(", "); buf.append( att[i].getKey()); } } return buf.toString(); } /** * @param newType * @param attributeId */ public boolean hasAttributeChanged(DynamicTypeImpl newType, String attributeId) { Attribute oldAttribute = findAttributeForId(attributeId ); Attribute newAttribute = newType.findAttributeForId(attributeId ); if ( oldAttribute == null && newAttribute == null) { return false; } if ((newAttribute == null ) || ( oldAttribute == null)) { return true; } String newKey = newAttribute.getKey(); String oldKey = oldAttribute.getKey(); if ( !newKey.equals( oldKey )) { return true; } if ( !newAttribute.getType().equals( oldAttribute.getType())) { return true; } { String[] keys = newAttribute.getConstraintKeys(); String[] oldKeys = oldAttribute.getConstraintKeys(); if ( keys.length != oldKeys.length) { return true; } for ( int i=0;i< keys.length;i++) { if ( !keys[i].equals( oldKeys[i]) ) return true; Object oldConstr = oldAttribute.getConstraint( keys[i]); Object newConstr = newAttribute.getConstraint( keys[i]); if ( oldConstr == null && newConstr == null) continue; if ( oldConstr == null || newConstr == null) return true; if ( !oldConstr.equals( newConstr)) return true; } } return false; } public static boolean isInternalType(Classifiable classifiable) { boolean isRaplaType =false; Classification classification = classifiable.getClassification(); if ( classification != null ) { String classificationType = classification.getType().getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); if ( classificationType != null && classificationType.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE)) { isRaplaType = true; } } return isRaplaType; } static class DynamicTypeParseContext implements ParseContext { private DynamicTypeImpl type; DynamicTypeParseContext( DynamicType type) { this.type = (DynamicTypeImpl)type; } public Function resolveVariableFunction(String variableName) throws IllegalAnnotationException { Attribute attribute = type.getAttribute(variableName); if (attribute != null) { return new AttributeFunction(attribute); } else if (variableName.equals(type.getKey())) { return new TypeFunction(type); } return null; } class AttributeFunction extends ParsedText.Function { Object id; AttributeFunction(Attribute attribute ) { super("attribute:"+attribute.getKey()); id =attribute.getId() ; } protected String getName() { Attribute attribute = findAttribute( type); if ( attribute != null) { return attribute.getKey(); } return name; } public Attribute eval(EvalContext context) { Classification classification = context.getClassification(); DynamicTypeImpl type = (DynamicTypeImpl) classification.getType(); return findAttribute(type); } public Attribute findAttribute(DynamicTypeImpl type) { Attribute attribute = type.findAttributeForId( id ); if ( attribute!= null) { return attribute; } return null; } @Override public String getRepresentation( ParseContext context) { Attribute attribute = type.findAttributeForId( id ); if ( attribute!= null) { return attribute.getKey(); } return ""; } } class TypeFunction extends ParsedText.Function { Object id; TypeFunction(DynamicType type) { super("type:"+type.getKey()); id = type.getId() ; } public String eval(EvalContext context) { DynamicTypeImpl type = (DynamicTypeImpl) context.getClassification().getType(); return type.getName( context.getLocale()); } @Override public String getRepresentation( ParseContext context) { if ( type.getId().equals( id ) ) { return type.getKey(); } return ""; } } } public static boolean isTransferedToClient(Classifiable classifiable) { if ( classifiable == null) { return false; } DynamicType type = classifiable.getClassification().getType(); boolean result = isTransferedToClient(type); return result; } public static boolean isTransferedToClient(DynamicType type) { String annotation = type.getAnnotation( DynamicTypeAnnotations.KEY_TRANSFERED_TO_CLIENT); if ( annotation == null) { return true; } return !annotation.equals( DynamicTypeAnnotations.VALUE_TRANSFERED_TO_CLIENT_NEVER); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 21006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype.internal; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.rapla.components.util.DateTools; import org.rapla.components.util.ParseDateException; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.ConstraintIds; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.framework.RaplaException; final public class AttributeImpl extends SimpleEntity implements Attribute { public static final MultiLanguageName TRUE_TRANSLATION = new MultiLanguageName(); public static final MultiLanguageName FALSE_TRANSLATION = new MultiLanguageName(); static { TRUE_TRANSLATION.setName("en", "yes"); FALSE_TRANSLATION.setName("en", "no"); } private MultiLanguageName name = new MultiLanguageName(); private AttributeType type; private String key; private boolean multiSelect; private boolean bOptional = false; private Map<String,String> annotations = new LinkedHashMap<String,String>(); private String defaultValue =null; private transient DynamicTypeImpl parent; public final static AttributeType DEFAULT_TYPE = AttributeType.STRING; public AttributeImpl() { this.type = DEFAULT_TYPE; } public AttributeImpl(AttributeType type) { setType(type); } void setParent(DynamicTypeImpl parent) { this.parent = parent; } public DynamicType getDynamicType() { return parent; } final public RaplaType<Attribute> getRaplaType() {return TYPE;} public RaplaType getRefType() { if (type == null) { return null; } if ( type.equals(AttributeType.CATEGORY)) { return Category.TYPE; } else if ( type.equals( AttributeType.ALLOCATABLE)) { return Allocatable.TYPE; } return null; } public AttributeType getType() { return type; } public void setType(AttributeType type) { checkWritable(); Object oldValue = defaultValue; if ( type.equals( AttributeType.CATEGORY)) { oldValue = getEntity("default.category", Category.class); } this.type = type; setDefaultValue(convertValue( oldValue)); } public MultiLanguageName getName() { return name; } public void setReadOnly() { super.setReadOnly( ); name.setReadOnly( ); } public String getName(Locale locale) { return name.getName(locale.getLanguage()); } public String getKey() { return key; } public void setConstraint(String key,Object constraint) { checkWritable(); setContraintWithoutWritableCheck(key, constraint); } public void setContraintWithoutWritableCheck(String key,Object constraint) { if ( getConstraintClass( key ) == Category.class || getConstraintClass( key ) == DynamicType.class) { String refID = "constraint." + key; if ( constraint == null) { removeWithKey( refID); } else if ( constraint instanceof Entity) { putEntity(refID,(Entity)constraint); } else if ( constraint instanceof String) { putId(refID,(String)constraint); } } if ( key.equals( ConstraintIds.KEY_MULTI_SELECT)) { multiSelect = true; } } @Override protected Class<? extends Entity> getInfoClass(String key) { Class<? extends Entity> infoClass = super.getInfoClass(key); if ( infoClass == null) { if ( key.equals( "default.category")) { return Category.class; } if ( key.startsWith( "constraint.")) { String constraintKey = key.substring( "constraint.".length()); Class<?> constraintClass = getConstraintClass( constraintKey); if ( !constraintClass.equals(String.class)) { @SuppressWarnings("unchecked") Class<? extends Entity> casted = (Class<? extends Entity>) constraintClass; return casted; } } } return infoClass; } public void setDefaultValue(Object object) { checkWritable(); if ( type.equals( AttributeType.CATEGORY)) { putEntity("default.category",(Entity)object); defaultValue = null; } else { defaultValue = (String) convertValue(object, AttributeType.STRING); } } public Object getConstraint(String key) { if ( key.equals(ConstraintIds.KEY_MULTI_SELECT)) { return multiSelect; } Class<?> constraintClass = getConstraintClass( key ); if ( constraintClass == Category.class || constraintClass == DynamicType.class) { @SuppressWarnings("unchecked") Class<? extends Entity> class1 = (Class<? extends Entity>) constraintClass; return getEntity("constraint." + key, class1); } return null; } public Class<?> getConstraintClass(String key) { if (key.equals(ConstraintIds.KEY_ROOT_CATEGORY)) { return Category.class; } if (key.equals(ConstraintIds.KEY_DYNAMIC_TYPE)) { return DynamicType.class; } if (key.equals(ConstraintIds.KEY_MULTI_SELECT)) { return Boolean.class; } return String.class; } public String[] getConstraintKeys() { if (type.equals( AttributeType.CATEGORY)) { return new String[] {ConstraintIds.KEY_ROOT_CATEGORY, ConstraintIds.KEY_MULTI_SELECT}; } if (type.equals( AttributeType.ALLOCATABLE)) { return new String[] {ConstraintIds.KEY_DYNAMIC_TYPE, ConstraintIds.KEY_MULTI_SELECT}; } else { return new String[0]; } } public void setKey(String key) { checkWritable(); this.key = key; if ( parent != null) { parent.keyChanged( this, key); } } public boolean isValid(Object obj) { return true; } public boolean isOptional() { return bOptional; } public void setOptional(boolean bOptional) { checkWritable(); this.bOptional = bOptional; } public Object defaultValue() { Object value; if ( type.equals( AttributeType.CATEGORY)) { value = getEntity("default.category", Category.class); } else { value = convertValue(defaultValue); } return value; } public boolean needsChange(Object value) { if (value == null) return false; if (type.equals( AttributeType.STRING )) { return !(value instanceof String); } if (type.equals( AttributeType.INT )) { return !(value instanceof Long); } if (type.equals( AttributeType.DATE )) { return !(value instanceof Date); } if (type.equals( AttributeType.BOOLEAN )) { return !(value instanceof Boolean); } if (type.equals( AttributeType.ALLOCATABLE )) { return !(value instanceof Allocatable); } if (type.equals( AttributeType.CATEGORY )) { if (!(value instanceof Category)) return true; Category temp = (Category) value; // look if the attribute category is a ancestor of the value category Category rootCategory = (Category) getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); if ( rootCategory != null) { boolean change = !rootCategory.isAncestorOf( temp ); return change; } return false; } return false; } public Object convertValue(Object value) { return convertValue(value, type); } private Object convertValue(Object value, AttributeType type) { if (type.equals( AttributeType.STRING )) { if (value == null) return null; if (value instanceof Date) { return new SerializableDateTimeFormat().formatDate( (Date) value); } // if (value instanceof Category) // { // return ((Category) value).get // } return value.toString(); } if (type.equals( AttributeType.DATE )) { if (value == null) return null; else if (value instanceof Date) return value; try { return new SerializableDateTimeFormat().parseDate( value.toString(), false); } catch (ParseDateException e) { return null; } } if (type.equals( AttributeType.INT )) { if (value == null) return null; if (value instanceof Boolean) return ((Boolean) value).booleanValue() ? new Long(1) : new Long(0); String str = value.toString().trim().toLowerCase(); try { return new Long(str); } catch (NumberFormatException ex) { return null; } } if (type.equals( AttributeType.BOOLEAN )) { if (value == null) return Boolean.FALSE; String str = value.toString().trim().toLowerCase(); if (str.equals("")) { return Boolean.FALSE; } if (str.equals("0") || str.equals("false")) return Boolean.FALSE; else return Boolean.TRUE; } if (type.equals( AttributeType.ALLOCATABLE)) { // we try to convert ids if ( value instanceof String) { Entity result = resolver.tryResolve( (String) value); if ( result != null && result instanceof Allocatable) { return (Allocatable) result; } } return null; } if (type.equals( AttributeType.CATEGORY )) { if (value == null) return null; Category rootCategory = (Category) getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); if (value instanceof Category) { Category temp = (Category) value; if ( rootCategory != null ) { if (rootCategory.isAncestorOf( temp )) { return value; } // if the category can't be found under the root then we check if we find a category path with the same keys List<String> keyPathRootCategory = ((CategoryImpl)rootCategory).getKeyPath( null); List<String> keyPath = ((CategoryImpl)temp).getKeyPath( null); List<String> nonCommonPath = new ArrayList<String>(); boolean differInKeys = false; // for ( int i=0;i<keyPath.size();i++) { String key = keyPath.get(i); String rootCatKey = keyPathRootCategory.size() > i ? keyPathRootCategory.get( i ) : null; if ( rootCatKey == null || !key.equals(rootCatKey)) { differInKeys = true; } if ( differInKeys) { nonCommonPath.add( key); } } Category parentCategory = rootCategory; Category newCategory = null; //we first check for the whole keypath this covers root changes from b to c, when c contains the b substructure including b // a // / \ // |b| |c| // / / // d b // / // d for ( String key: nonCommonPath) { newCategory = parentCategory.getCategory( key); if ( newCategory == null) { break; } else { parentCategory = newCategory; } } //if we don't find a category we also check if a keypath that contains on less entry // covers root changes from b to c when c contains directly the b substructure but not b itself // a // / \ // |b| |c| // / / // d d // if ( newCategory == null && nonCommonPath.size() > 1) { List<String> subList = nonCommonPath.subList(1, nonCommonPath.size()); for ( String key: subList) { newCategory = parentCategory.getCategory( key); if ( newCategory == null) { break; } else { parentCategory = newCategory; } } } return newCategory; } } else if ( value instanceof String) { Entity result = resolver.tryResolve( (String) value); if ( result != null && result instanceof Category) { return (Category) result; } } if ( rootCategory != null) { Category category = rootCategory.getCategory(value.toString()); if ( category == null) { return null; } return category; } } return null; } public String getAnnotation(String key) { return annotations.get(key); } public String getAnnotation(String key, String defaultValue) { String annotation = getAnnotation( key ); return annotation != null ? annotation : defaultValue; } public void setAnnotation(String key,String annotation) throws IllegalAnnotationException { checkWritable(); if (annotation == null) { annotations.remove(key); return; } // multiselect is now a constraint so we keep this for backward compatibility with old data format if ( key.equals( ConstraintIds.KEY_MULTI_SELECT)) { multiSelect = annotation != null && annotation.equalsIgnoreCase("true"); } else { annotations.put(key,annotation); } } public String[] getAnnotationKeys() { return annotations.keySet().toArray(RaplaObject.EMPTY_STRING_ARRAY); } public Attribute clone() { AttributeImpl clone = new AttributeImpl(); super.deepClone(clone); clone.name = (MultiLanguageName) name.clone(); @SuppressWarnings("unchecked") HashMap<String,String> annotationClone = (HashMap<String,String>) ((HashMap<String,String>) annotations).clone(); clone.annotations = annotationClone; clone.type = getType(); clone.multiSelect = multiSelect; clone.setKey(getKey()); clone.setOptional(isOptional()); String[] constraintKeys = getConstraintKeys(); for ( int i = 0;i < constraintKeys.length; i++) { String key = constraintKeys[ i ]; clone.setConstraint( key, getConstraint(key)); } clone.setDefaultValue( defaultValue()); return clone; } public String toString() { MultiLanguageName name = getName(); if (name != null) { return name.toString()+ " ID='" + getId() + "'"; } else { return getKey() + " " + getId(); } } @SuppressWarnings("deprecation") static public Object parseAttributeValue(Attribute attribute,String text) throws RaplaException { AttributeType type = attribute.getType(); final String trim = text.trim(); EntityResolver resolver = ((AttributeImpl)attribute).getResolver(); if (type.equals( AttributeType.STRING )) { return text; } else if (type.equals( AttributeType.ALLOCATABLE)) { String path = trim; if (path.length() == 0) { return null; } if ( resolver != null) { if ( resolver.tryResolve( path, Allocatable.class) != null) { return path; } } if (org.rapla.storage.OldIdMapping.isTextId(Allocatable.TYPE,path)) { return path ; } return null; } else if (type.equals( AttributeType.CATEGORY )) { String path = trim; if (path.length() == 0) { return null; } if ( resolver != null) { if ( resolver.tryResolve( path) != null) { return path; } } if (org.rapla.storage.OldIdMapping.isTextId(Category.TYPE,path) ) { String id = org.rapla.storage.OldIdMapping.getId( Category.TYPE, path); return id ; } else { CategoryImpl rootCategory = (CategoryImpl)attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); if (rootCategory == null) { //System.out.println( attribute.getConstraintKeys()); throw new RaplaException("Can't find " + ConstraintIds.KEY_ROOT_CATEGORY + " for attribute " + attribute); } Category categoryFromPath = rootCategory.getCategoryFromPath(path); if ( categoryFromPath == null) { // TODO call convert that tries to convert from a string path } return categoryFromPath; } } else if (trim.length() == 0) { return null; } else if (type.equals(AttributeType.BOOLEAN)) { return trim.equalsIgnoreCase("true") || trim.equals("1") ? Boolean.TRUE : Boolean.FALSE; } else if (type.equals( AttributeType.DATE )) { try { return new SerializableDateTimeFormat().parseDate( trim, false); } catch (ParseDateException e) { throw new RaplaException( e.getMessage(), e); } } else if (type.equals( AttributeType.INT)) { try { return new Long( trim ); } catch (NumberFormatException ex) { throw new RaplaException( ex.getMessage()); } } throw new RaplaException("Unknown attribute type: " + type ); } public static String attributeValueToString( Attribute attribute, Object value, boolean idOnly) throws EntityNotFoundException { AttributeType type = attribute.getType(); if (type.equals( AttributeType.ALLOCATABLE )) { return ((Entity)value).getId().toString(); } if (type.equals( AttributeType.CATEGORY )) { CategoryImpl rootCategory = (CategoryImpl) attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); if ( idOnly) { return ((Entity)value).getId().toString(); } else { return rootCategory.getPathForCategory((Category)value) ; } } else if (type.equals( AttributeType.DATE )) { return new SerializableDateTimeFormat().formatDate( (Date)value ) ; } else { return value.toString() ; } } static public class IntStrategy { String[] constraintKeys = new String[] {"min","max"}; public String[] getConstraintKeys() { return constraintKeys; } public boolean needsChange(Object value) { return !(value instanceof Long); } public Object convertValue(Object value) { if (value == null) return null; if (value instanceof Boolean) return ((Boolean) value).booleanValue() ? new Long(1) : new Long(0); String str = value.toString().trim().toLowerCase(); try { return new Long(str); } catch (NumberFormatException ex) { return null; } } } public String getValueAsString(Locale locale,Object value) { if (value == null) return ""; if (value instanceof Category) { Category rootCategory = (Category) getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); return ((Category) value).getPath(rootCategory, locale); } if (value instanceof Allocatable) { return ((Allocatable) value).getName( locale); } if (value instanceof Date) { return DateTools.formatDate((Date) value, locale); } if (value instanceof Boolean) { return getBooleanTranslation(locale, (Boolean) value); } else { return value.toString(); } } public static String getBooleanTranslation(Locale locale, Boolean value) { if (locale == null) { locale = Locale.getDefault(); } String language = locale.getLanguage(); if ( (Boolean) value) { return TRUE_TRANSLATION.getName( language); } else { return FALSE_TRANSLATION.getName( language); } } public String toStringValue( Object value) { String stringValue = null; RaplaType refType = getRefType(); if (refType != null) { if ( value instanceof Entity) { stringValue = ((Entity) value).getId(); } else { stringValue = value.toString(); } } else if (type.equals( AttributeType.DATE )) { return new SerializableDateTimeFormat().formatDate((Date)value); } else if ( value != null) { stringValue = value.toString(); } return stringValue; } public Object fromString(EntityResolver resolver, String value) throws EntityNotFoundException { RaplaType refType = getRefType(); if (refType != null) { Entity resolved = resolver.resolve( value ); return resolved; } Object result; try { result = parseAttributeValue(this, value); } catch (RaplaException e) { throw new IllegalStateException("Value not parsable"); } return result; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype.internal; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.rapla.components.util.Assert; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.components.util.iterator.NestedIterator; import org.rapla.entities.ReadOnlyException; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.ClassificationFilterRule; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.UnresolvableReferenceExcpetion; public final class ClassificationFilterImpl implements ClassificationFilter ,DynamicTypeDependant ,EntityReferencer ,java.io.Serializable { // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; private String typeId; transient boolean readOnly; List<ClassificationFilterRuleImpl> list = new LinkedList<ClassificationFilterRuleImpl>(); transient boolean arrayUpToDate = false; transient ClassificationFilterRuleImpl[] rulesArray; transient EntityResolver resolver; ClassificationFilterImpl() { } ClassificationFilterImpl(DynamicTypeImpl dynamicType) { typeId = dynamicType.getId(); } public void setResolver( EntityResolver resolver) { this.resolver = resolver; for (Iterator<ClassificationFilterRuleImpl> it=list.iterator();it.hasNext();) { it.next().setResolver( resolver ); } } public DynamicType getType() { DynamicType type = resolver.tryResolve(typeId, DynamicType.class); if ( type == null) { throw new UnresolvableReferenceExcpetion(typeId); } //DynamicType dynamicType = (DynamicType) referenceHandler.getEntity("parent"); return type; } @Override public Iterable<ReferenceInfo> getReferenceInfo() { return new IteratorChain<ReferenceInfo> ( Collections.singleton( new ReferenceInfo(typeId, DynamicType.class)) ,new NestedIterator<ReferenceInfo,ClassificationFilterRuleImpl>( list ) { public Iterable<ReferenceInfo> getNestedIterator(ClassificationFilterRuleImpl obj) { return obj.getReferenceInfo(); } } ); } public void setReadOnly(boolean enable) { this.readOnly = enable; } public boolean isReadOnly() { return readOnly; } public void checkWritable() { if ( readOnly ) throw new ReadOnlyException( this ); } public void addRule(String attributeName, Object[][] conditions) { setRule(ruleSize(), attributeName, conditions); } public void setRule(int index, String attributeName,Object[][] conditions) { setRule( index, getType().getAttribute( attributeName), conditions); } public void setRule(int index, Attribute attribute,Object[][] conditions) { checkWritable(); Assert.notNull( attribute ); String[] operators = new String[conditions.length]; Object[] ruleValues = new Object[conditions.length]; for (int i=0;i<conditions.length;i++) { operators[i] = conditions[i][0].toString().trim(); checkOperator(operators[i]); ruleValues[i] = conditions[i][1]; } ClassificationFilterRuleImpl rule = new ClassificationFilterRuleImpl( attribute, operators, ruleValues); if ( resolver != null) { rule.setResolver( resolver); } // System.out.println("Rule " + index + " for '" + dynamicType + "' added. " + " Attribute " + rule.attribute + " Params: " + rule.params[0]); if (index < list.size() ) list.set(index, rule); else list.add(index, rule); arrayUpToDate = false; } private void checkOperator(String operator) { if (operator.equals("<")) return; if (operator.equals(">")) return; if (operator.equals("=")) return; if (operator.equals("contains")) return; if (operator.equals("starts")) return; if (operator.equals("is")) return; if (operator.equals("<=")) return; if (operator.equals(">=")) return; if (operator.equals("<>")) return; throw new IllegalArgumentException("operator '" + operator + "' not supported!"); } public void addEqualsRule( String attributeName, Object object ) { addRule( attributeName, new Object[][] {{"=",object}}); } public void addIsRule( String attributeName, Object object ) { addRule( attributeName, new Object[][] {{"is",object}}); } public int ruleSize() { return list.size(); } public Iterator<? extends ClassificationFilterRule> ruleIterator() { return list.iterator(); } public void removeAllRules() { checkWritable(); list.clear(); arrayUpToDate = false; } public void removeRule(int index) { checkWritable(); list.remove(index); arrayUpToDate = false; //System.out.println("Rule " + index + " for '" + dynamicType + "' removed."); } private ClassificationFilterRuleImpl[] getRules() { if (!arrayUpToDate) rulesArray = list.toArray(new ClassificationFilterRuleImpl[0]); arrayUpToDate = true; return rulesArray; } public boolean matches(Classification classification) { if (!getType().equals(classification.getType())) return false; ClassificationFilterRuleImpl[] rules = getRules(); for (int i=0;i<rules.length;i++) { ClassificationFilterRuleImpl rule = rules[i]; Attribute attribute = rule.getAttribute(); if ( attribute != null) { Collection<Object> values = classification.getValues(attribute); if ( values.size() == 0) { if (!rule.matches( null)) { return false; } } else { boolean matchesOne= false; for (Object value: values) { if (rule.matches( value)) matchesOne = true; } if ( !matchesOne ) { return false; } } } } return true; } boolean hasType(DynamicType type) { return getType().equals( type); } public boolean needsChange(DynamicType newType) { if (!hasType( newType )) return false; if ( !newType.getKey().equals( getType().getKey())) return true; ClassificationFilterRuleImpl[] rules = getRules(); for (int i=0;i<rules.length;i++) { ClassificationFilterRuleImpl rule = rules[i]; Attribute attribute = rule.getAttribute(); if ( attribute == null ) { return true; } String id = attribute.getId(); if (((DynamicTypeImpl)getType()).hasAttributeChanged( (DynamicTypeImpl)newType , id)) return true; Attribute newAttribute = newType.getAttribute(attribute.getKey()); if ( newAttribute == null) { return true; } if (rule.needsChange(newAttribute)) { return true; } } return false; } public void commitChange(DynamicType type) { if (!hasType(type)) return; Iterator<ClassificationFilterRuleImpl> it = list.iterator(); while (it.hasNext()) { ClassificationFilterRuleImpl rule = it.next(); Attribute attribute = rule.getAttribute(); if ( attribute == null ) { it.remove(); continue; } Object id = attribute.getId(); Attribute typeAttribute = ((DynamicTypeImpl)type).findAttributeForId(id ); if (typeAttribute == null) { it.remove(); } else { rule.commitChange(typeAttribute); } } arrayUpToDate = false; } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { throw new CannotExistWithoutTypeException(); } public ClassificationFilterImpl clone() { ClassificationFilterImpl clone = new ClassificationFilterImpl((DynamicTypeImpl)getType()); clone.resolver = resolver; clone.list = new LinkedList<ClassificationFilterRuleImpl>(); Iterator<ClassificationFilterRuleImpl> it = list.iterator(); while (it.hasNext()) { ClassificationFilterRuleImpl rule = it.next(); Attribute attribute = rule.getAttribute(); if ( attribute != null) { ClassificationFilterRuleImpl clone2 =new ClassificationFilterRuleImpl(attribute,rule.getOperators(),rule.getValues()); clone.list.add(clone2); } } clone.readOnly = false;// clones are always writable clone.arrayUpToDate = false; return clone; } public ClassificationFilter[] toArray() { return new ClassificationFilter[] {this}; } public String toString() { StringBuilder buf = new StringBuilder(); buf.append(getType().getKey() +": "); for ( ClassificationFilterRule rule: getRules()) { buf.append(rule.toString()); buf.append(", "); } return buf.toString(); } }
Java
/** * */ package org.rapla.entities.dynamictype.internal; import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import org.rapla.components.util.DateTools; import org.rapla.components.util.TimeInterval; import org.rapla.entities.Category; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.Named; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classification; import org.rapla.rest.GwtIncompatible; /** * Enables text replacement of variables like {name} {email} with corresponding attribute values * Also some functions like {substring(name,1,2)} are available for simple text processing * */ public class ParsedText implements Serializable { private static final long serialVersionUID = 1; /** the terminal format elements*/ transient List<String> nonVariablesList; /** the variable format elements*/ transient List<Function> variablesList ; // used for fast storage of text without variables transient private String first; String formatString; ParsedText() { } public ParsedText(String formatString) { this.formatString = formatString; } public void init( ParseContext context) throws IllegalAnnotationException { variablesList = new ArrayList<Function>(); nonVariablesList = new ArrayList<String>(); int pos = 0; int length = formatString.length(); List<String> variableContent = new ArrayList<String>(); while (pos < length) { int start = formatString.indexOf('{',pos) + 1; if (start < 1) { nonVariablesList.add(formatString.substring(pos, length )); break; } int end = formatString.indexOf('}',start); if (end < 1 ) throw new IllegalAnnotationException("Closing bracket } missing! in " + formatString); nonVariablesList.add(formatString.substring(pos, start -1)); String key = formatString.substring(start,end).trim(); variableContent.add( key ); pos = end + 1; } for ( String content: variableContent) { Function func =parseFunctions(context,content); variablesList.add( func); } if ( variablesList.isEmpty() ) { if (nonVariablesList.size()>0) { first = nonVariablesList.iterator().next(); } variablesList = null; nonVariablesList = null; } } public void updateFormatString(ParseContext context) { formatString = getExternalRepresentation(context); } public String getExternalRepresentation(ParseContext context) { if ( nonVariablesList == null) { return first; } StringBuffer buf = new StringBuffer(); for (int i=0; i<nonVariablesList.size(); i++) { buf.append(nonVariablesList.get(i)); if ( i < variablesList.size() ) { Function variable = variablesList.get(i); String representation = variable.getRepresentation(context); buf.append("{"); buf.append( representation); buf.append("}"); } } return buf.toString(); } public String formatName(EvalContext context) { if ( nonVariablesList == null) { return first; } StringBuffer buf = new StringBuffer(); for (int i=0; i<nonVariablesList.size(); i++) { buf.append(nonVariablesList.get(i)); if ( i < variablesList.size()) { Function function = variablesList.get(i); Object result = function.eval(context); String stringResult = toString(result, context); buf.append( stringResult); } } return buf.toString(); } Function parseFunctions(ParseContext context,String content) throws IllegalAnnotationException { StringBuffer functionName = new StringBuffer(); for ( int i=0;i<content.length();i++) { char c = content.charAt(i); if ( c == '(' ) { int depth = 0; for ( int j=i+1;j<content.length();j++) { if ( functionName.length() == 0) { throw new IllegalAnnotationException("Function name missing"); } char c2 = content.charAt(j); if ( c2== ')') { if ( depth == 0) { String recursiveContent = content.substring(i+1,j); String function = functionName.toString(); return parseArguments( context,function,recursiveContent); } else { depth--; } } if ( c2 == '(' ) { depth++; } } } else if ( c== ')') { throw new IllegalAnnotationException("Opening parenthis missing."); } else { functionName.append( c); } } String variableName = functionName.toString().trim(); if ( variableName.startsWith("'") && (variableName.endsWith("'")) || (variableName.startsWith("\"") && variableName.endsWith("\"") ) && variableName.length() > 1) { String constant = variableName.substring(1, variableName.length() - 1); return new StringVariable(constant); } Function varFunction = context.resolveVariableFunction( variableName); if (varFunction != null) { return varFunction; } else { try { Long l = Long.parseLong( variableName.trim() ); return new IntVariable( l); } catch (NumberFormatException ex) { } // try // { // Double d = Double.parseDouble( variableName); // } catch (NumberFormatException ex) // { // } throw new IllegalAnnotationException("Attribute for key '" + variableName + "' not found. You have probably deleted or renamed the attribute. " ); } } private Function parseArguments(ParseContext context,String functionName, String content) throws IllegalAnnotationException { int depth = 0; List<Function> args = new ArrayList<Function>(); StringBuffer currentArg = new StringBuffer(); for ( int i=0;i<content.length();i++) { char c = content.charAt(i); if ( c == '(' ) { depth++; } else if ( c == ')' ) { depth --; } if ( c != ',' || depth > 0) { currentArg.append( c); } if ( depth == 0) { if ( c == ',' || i == content.length()-1) { String arg = currentArg.toString(); Function function = parseFunctions(context,arg); args.add(function); currentArg = new StringBuffer(); } } } if ( functionName.equals("key")) { return new KeyFunction(args); } if ( functionName.equals("parent")) { return new ParentFunction(args); } if ( functionName.equals("substring")) { return new SubstringFunction(args); } if ( functionName.equals("if")) { return new IfFunction(args); } if ( functionName.equals("equals")) { return new EqualsFunction(args); } else { throw new IllegalAnnotationException("Unknown function '"+ functionName + "'" ); } //return new SubstringFunction(functionName, args); } static public abstract class Function { String name; List<Function> args; public Function( String name,List<Function> args ) { this.name = name; this.args = args; } public Function(String name) { this.name = name; this.args = Collections.emptyList(); } protected String getName() { return name; } public abstract Object eval(EvalContext context); public String getRepresentation( ParseContext context) { StringBuffer buf = new StringBuffer(); buf.append(getName()); for ( int i=0;i<args.size();i++) { if ( i == 0) { buf.append("("); } else { buf.append(","); } buf.append( args.get(i).getRepresentation(context)); if ( i == args.size() - 1) { buf.append(")"); } } return buf.toString(); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(getName()); for ( int i=0;i<args.size();i++) { if ( i == 0) { buf.append("("); } else { buf.append(", "); } buf.append( args.get(i).toString()); if ( i == args.size() - 1) { buf.append(")"); } } return buf.toString(); } } class KeyFunction extends Function { Function arg; public KeyFunction( List<Function> args) throws IllegalAnnotationException { super( "key", args); if ( args.size() != 1) { throw new IllegalAnnotationException("Key Function expects one argument!"); } arg = args.get(0); //testMethod(); } @GwtIncompatible private void testMethod() throws IllegalAnnotationException { Method method; try { Class<? extends Function> class1 = arg.getClass(); method = class1.getMethod("eval", new Class[] {EvalContext.class}); } catch (Exception e) { String message = e.getMessage(); throw new IllegalAnnotationException( "Could not parse method for internal error : " + message); } if ( !method.getReturnType().isAssignableFrom(Attribute.class)) { if ( !method.getReturnType().isAssignableFrom(Category.class)) { throw new IllegalAnnotationException("Key Function expects an attribute variable or a function which returns a category"); } } } @Override public String eval(EvalContext context) { Object obj = arg.eval( context); if ( obj == null || !(obj instanceof RaplaObject)) { return ""; } RaplaObject raplaObject = (RaplaObject) obj; RaplaType raplaType = raplaObject.getRaplaType(); if ( raplaType == Category.TYPE) { Category category = (Category) raplaObject; String key = category.getKey(); return key; } else if ( raplaType == Attribute.TYPE) { Classification classification = context.getClassification(); Object result = classification.getValue((Attribute) raplaObject); if ( result instanceof Category) { String key = ((Category) result).getKey(); return key; } } return ""; } } class IntVariable extends Function { Long l; public IntVariable( Long l) { super( "long"); this.l = l; } @Override public Long eval(EvalContext context) { return l; } public String getRepresentation( ParseContext context) { return l.toString(); } public String toString() { return l.toString(); } } class StringVariable extends Function { String s; public StringVariable( String s) { super( "string"); this.s = s; } @Override public String eval(EvalContext context) { return s; } public String getRepresentation( ParseContext context) { return "\"" + s.toString() + "\""; } public String toString() { return s.toString(); } } class ParentFunction extends Function { Function arg; public ParentFunction( List<Function> args) throws IllegalAnnotationException { super( "parent", args); if ( args.size() != 1) { throw new IllegalAnnotationException("Parent Function expects one argument!"); } arg = args.get(0); //testMethod(); } @GwtIncompatible private void testMethod() throws IllegalAnnotationException { Method method; try { Class<? extends Function> class1 = arg.getClass(); method = class1.getMethod("eval", new Class[] {EvalContext.class}); } catch (Exception e) { throw new IllegalAnnotationException( "Could not parse method for internal error : " + e.getMessage()); } if ( !method.getReturnType().isAssignableFrom(Attribute.class)) { if ( !method.getReturnType().isAssignableFrom(Category.class)) { throw new IllegalAnnotationException("Parent Function expects an attribute variable or a function which returns a category"); } } } @Override public Category eval(EvalContext context) { Object obj = arg.eval( context); if ( obj == null || !(obj instanceof RaplaObject)) { return null; } RaplaObject raplaObject = (RaplaObject)obj; RaplaType raplaType = raplaObject.getRaplaType(); if ( raplaType == Category.TYPE) { Category category = (Category) raplaObject; return category.getParent(); } else if ( raplaType == Attribute.TYPE) { Classification classification = context.getClassification(); Object result = classification.getValue((Attribute) raplaObject); if ( result instanceof Category) { return ((Category) result).getParent(); } } return null; } } class SubstringFunction extends Function { Function content; Function start; Function end; public SubstringFunction( List<Function> args) throws IllegalAnnotationException { super( "substring", args); if ( args.size() != 3) { throw new IllegalAnnotationException("Substring Function expects 3 argument!"); } content = args.get(0); start = args.get(1); end = args.get(2); //testMethod(); } @GwtIncompatible private void testMethod() throws IllegalAnnotationException { { Method method; try { Class<? extends Function> class1 = start.getClass(); method = class1.getMethod("eval", new Class[] {EvalContext.class}); } catch (Exception e) { throw new IllegalAnnotationException( "Could not parse method for internal error : " + e.getMessage()); } if ( !method.getReturnType().isAssignableFrom(Long.class)) { throw new IllegalAnnotationException( "Substring method expects a Long parameter as second argument"); } } { Method method; try { Class<? extends Function> class1 = end.getClass(); method = class1.getMethod("eval", new Class[] {EvalContext.class}); } catch (Exception e) { throw new IllegalAnnotationException( "Could not parse method for internal error : " + e.getMessage()); } if ( !method.getReturnType().isAssignableFrom(Long.class)) { throw new IllegalAnnotationException( "Substring method expects a Long parameter as third argument"); } } } @Override public String eval(EvalContext context) { Object result =content.eval( context); String stringResult = ParsedText.this.toString( result, context); if ( stringResult == null) { return stringResult; } Long firstIndex = (Long)start.eval( context); Long lastIndex = (Long) end.eval( context); if ( firstIndex == null) { return null; } else if ( lastIndex == null) { return stringResult.substring( Math.min(firstIndex.intValue(), stringResult.length()) ); } else { return stringResult.substring( Math.min(firstIndex.intValue(), stringResult.length()) , Math.min(lastIndex.intValue(), stringResult.length()) ); } } } class IfFunction extends Function { Function condition; Function conditionTrue; Function conditionFalse; public IfFunction( List<Function> args) throws IllegalAnnotationException { super( "if", args); if ( args.size() != 3) { throw new IllegalAnnotationException("if function expects 3 argument!"); } condition = args.get(0); conditionTrue = args.get(1); conditionFalse = args.get(2); testMethod(); } /** * @throws IllegalAnnotationException */ private void testMethod() throws IllegalAnnotationException { } @Override public Object eval(EvalContext context) { Object condResult =condition.eval( context); Object resultCond = ParsedText.this.getValueForIf( condResult, context); boolean isTrue; if ( resultCond != null) { isTrue = Boolean.parseBoolean(resultCond.toString()); } else { isTrue = false; } Function resultFunction = isTrue ? conditionTrue : conditionFalse; Object result = resultFunction.eval(context); return result; } } class EqualsFunction extends Function { Function arg1; Function arg2; public EqualsFunction( List<Function> args) throws IllegalAnnotationException { super( "equals", args); if ( args.size() != 2) { throw new IllegalAnnotationException("equals function expects 2 argument!"); } arg1 = args.get(0); arg2 = args.get(1); testMethod(); } @SuppressWarnings("unused") private void testMethod() throws IllegalAnnotationException { } @Override public Boolean eval(EvalContext context) { Object evalResult1 = arg1.eval( context); Object evalResult2 =arg2.eval( context); if ( evalResult1 == null || evalResult2 == null) { return evalResult1 == evalResult2; } return evalResult1.equals( evalResult2); } } private Object getValueForIf(Object result, EvalContext context) { if ( result instanceof Attribute) { Attribute attribute = (Attribute) result; Classification classification = context.getClassification(); return classification.getValue(attribute); } return result; } private String toString(Object result, EvalContext context) { if ( result == null) { return ""; } Locale locale = context.getLocale(); if ( result instanceof Collection) { StringBuffer buf = new StringBuffer(); Collection<?> collection = (Collection<?>) result; int i=0; for ( Object obj: collection) { if ( i>0) { buf.append(", "); } buf.append(toString(obj, context)); i++; } return buf.toString(); } else if ( result instanceof TimeInterval) { Date start = ((TimeInterval) result).getStart(); Date end = ((TimeInterval) result).getEnd(); if ( DateTools.cutDate( end ).equals( end)) { end = DateTools.subDay(end); } StringBuffer buf = new StringBuffer(); buf.append( DateTools.formatDate( start, locale)); if ( end != null && end.after(start)) { buf.append( "-"); buf.append( DateTools.formatDate( end, locale)); } return buf.toString(); } else if ( result instanceof Date) { Date date = (Date) result; StringBuffer buf = new StringBuffer(); buf.append( DateTools.formatDate( date, locale)); return buf.toString(); } else if ( result instanceof Attribute) { Attribute attribute = (Attribute) result; Classification classification = context.getClassification(); return classification.getValueAsString(attribute, locale); } else if ( result instanceof Named) { return ((Named) result).getName( locale); } return result.toString(); } public interface ParseContext { Function resolveVariableFunction(String variableName) throws IllegalAnnotationException; } static public class EvalContext { private Locale locale; public EvalContext( Locale locale) { this.locale = locale; } /** override this method if you can return a classification object in the context. Than the use of attributes is possible*/ public Classification getClassification() { return null; } public Locale getLocale() { return locale; } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; public interface ConstraintIds{ String KEY_ROOT_CATEGORY="root-category"; String KEY_DYNAMIC_TYPE="dynamic-type"; String KEY_MULTI_SELECT = "multi-select"; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; public interface DynamicTypeAnnotations { String KEY_NAME_FORMAT="nameformat"; String KEY_NAME_FORMAT_PLANNING="nameformat_planing"; String KEY_CLASSIFICATION_TYPE="classification-type"; String VALUE_CLASSIFICATION_TYPE_RESOURCE="resource"; String VALUE_CLASSIFICATION_TYPE_RESERVATION="reservation"; String VALUE_CLASSIFICATION_TYPE_PERSON="person"; String VALUE_CLASSIFICATION_TYPE_RAPLATYPE="rapla"; String KEY_COLORS="colors"; String VALUE_COLORS_AUTOMATED = "rapla:automated"; String VALUE_COLORS_COLOR_ATTRIBUTE = "color"; String VALUE_COLORS_DISABLED = "rapla:disabled"; String KEY_CONFLICTS="conflicts"; String VALUE_CONFLICTS_NONE="never"; String VALUE_CONFLICTS_ALWAYS="always"; String VALUE_CONFLICTS_WITH_OTHER_TYPES="withOtherTypes"; String KEY_TRANSFERED_TO_CLIENT = "transferedToClient"; String VALUE_TRANSFERED_TO_CLIENT_NEVER = "never"; String KEY_LOCATION="location"; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; import org.rapla.entities.Annotatable; import org.rapla.entities.Entity; import org.rapla.entities.MultiLanguageNamed; import org.rapla.entities.RaplaType; /** Attributes are to DynamicTypes, what properties are to Beans. Currently Rapla supports the following types: <li>string</li> <li>int</li> <li>date</li> <li>boolean</li> <li>rapla:category</li> @see DynamicType */ public interface Attribute extends Entity<Attribute>,MultiLanguageNamed,Annotatable { final RaplaType<Attribute> TYPE = new RaplaType<Attribute>(Attribute.class, "attribute"); AttributeType getType(); RaplaType getRefType(); /** Set the type of the Attribute. <strong>Warning:</strong> Changing the type after initialization can lead to data loss, if there are already classifications that use this attribute and the classification value can't be converted to the new type. Example a non numerical string can't be converted to an int.*/ void setType(AttributeType type); void setKey(String key); /** The Key is identifier in string-form. Keys could be helpfull for interaction with other modules. An Invoice-Plugin could work on attributes with a "price" key. Keys also allow for a better readability of the XML-File. Changing of a key is possible, but should be used with care. */ String getKey(); Object defaultValue(); /** converts the passed value to fit the attributes type. Example Conversions are: <ul> <li>to string: The result of the method toString() will be the new value.</li> <li>boolean to int: The new value will be 1 when the oldValue is true. Otherwise it is 0.</li> <li>other types to int: First the value will be converted to string-type. And then the trimmed string will be parsed for Integer-values. If that is not possible the new value will be null</li> <li>to boolean: First the value will be converted to string-type. If the trimmed string equals "0" or "false" the new value is false. Otherwise it is true</li> </ul> */ Object convertValue(Object oldValue); /** Checks if the passed value matches the attribute type or needs conversion. @see #convertValue */ boolean needsChange(Object value); boolean isValid(Object object); boolean isOptional(); void setOptional(boolean bOptional); Object getConstraint(String key); Class<?> getConstraintClass(String key); void setConstraint(String key,Object constraint); String[] getConstraintKeys(); DynamicType getDynamicType(); public static final Attribute[] ATTRIBUTE_ARRAY = new Attribute[0]; void setDefaultValue(Object value); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; /** Attributes are to DynamicTypes, what properties are to Beans. Currently Rapla supports the following types: <li>string</li> <li>int</li> <li>date</li> <li>boolean</li> <li>rapla:category</li> <li>rapla:allocatable</li> @see DynamicType */ public enum AttributeType { STRING("string"), INT("int"), DATE("date"), BOOLEAN("boolean"), CATEGORY("rapla:category"), ALLOCATABLE("rapla:allocatable"); private String type; private AttributeType(String type) { this.type = type; } public boolean is(AttributeType other) { if ( other == null) return false; return type.equals( other.type); } public static AttributeType findForString(String string ) { for (AttributeType type:values()) { if ( type.type.equals( string)) { return type; } } return null; } public String toString() { return type; } }
Java
package org.rapla.entities.dynamictype; public interface RaplaAnnotation { }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; /** This Interfaces is implemented by all Rapla-Objects that can * have classification information: Reservation, Resource, Person. * @see Classification */ public interface Classifiable { Classification getClassification(); void setClassification(Classification classification); final Classifiable[] CLASSIFIABLE_ARRAY = new Classifiable[0]; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; public interface ClassificationFilterRule { public Attribute getAttribute(); public String[] getOperators(); public Object[] getValues(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.rapla.framework.RaplaException; /** * Enumeration Pattern for all Rapla objects. You should not instanciate Objects of this type, * there is only one instance of RaplaType for each class of objects. You can get it via * the object interface. E.g. Reservation.TYPE or Allocatable.TYPE */ public class RaplaType<T> { private Class<T> type; private String localname; private static Map<Class<? extends RaplaObject>,RaplaType> registeredTypes = new HashMap<Class<? extends RaplaObject>,RaplaType>(); private static Map<String,RaplaType> registeredTypeNames = new HashMap<String,RaplaType>(); public RaplaType(Class<T> clazz, String localname) { // @SuppressWarnings("unchecked") // Class<? extends RaplaObject> clazz2 = clazz; this.type = clazz; this.localname = localname; if ( registeredTypes == null) { registeredTypes = new HashMap<Class<? extends RaplaObject>,RaplaType>(); registeredTypeNames = new HashMap<String,RaplaType>(); } if ( registeredTypes.get( clazz ) != null) { throw new IllegalStateException( "Type already registered"); } @SuppressWarnings("unchecked") Class<? extends RaplaObject> casted = (Class<? extends RaplaObject>) type; registeredTypes.put( casted, this); registeredTypeNames.put( localname, this); } static public RaplaType find( String typeName) throws RaplaException { RaplaType raplaType = registeredTypeNames.get( typeName); if (raplaType != null) { return raplaType; } throw new RaplaException("Cant find Raplatype for name" + typeName); } static public <T extends RaplaObject> RaplaType<T> get(Class<T> clazz) { @SuppressWarnings("unchecked") RaplaType<T> result = registeredTypes.get( clazz); return result; } public boolean is(RaplaType other) { if ( other == null) return false; return type.equals( other.type); } public String getLocalName() { return localname; } public String toString() { return type.getName(); } public boolean equals( Object other) { if ( !(other instanceof RaplaType)) return false; return is( (RaplaType)other); } public int hashCode() { return type.hashCode(); } public Class<T> getTypeClass() { return type; } @SuppressWarnings("unchecked") public static <T extends RaplaObject> Set<T> retainObjects(Collection<? extends RaplaObject> set,Collection<T> col) { HashSet<RaplaObject> tempSet = new HashSet<RaplaObject>(set.size()); tempSet.addAll(set); tempSet.retainAll(col); if (tempSet.size() >0) { HashSet<T> result = new HashSet<T>(); for ( RaplaObject t : tempSet) { result.add( (T)t); } return result; } else { return Collections.emptySet(); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import java.util.Locale; public interface Named { String getName(Locale locale); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain; import java.util.Comparator; public class AppointmentStartComparator implements Comparator<Appointment> { public int compare(Appointment a1,Appointment a2) { if ( a1.equals(a2)) return 0; if (a1.getStart().before(a2.getStart())) return -1; if (a1.getStart().after(a2.getStart())) return 1; @SuppressWarnings("unchecked") int compareTo = ((Comparable)a1).compareTo( (Comparable)a2 ); return compareTo; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain; import java.util.Comparator; import java.util.Date; import java.util.Locale; import org.rapla.entities.NamedComparator; public class ReservationStartComparator implements Comparator<Reservation> { NamedComparator<Reservation> namedComp; public ReservationStartComparator(Locale locale) { namedComp = new NamedComparator<Reservation>( locale); } public int compare(Reservation o1,Reservation o2) { if ( o1.equals(o2)) return 0; Reservation r1 = o1; Reservation r2 = o2; if (getStart(r1).before(getStart(r2))) return -1; if (getStart(r1).after(getStart(r2))) return 1; return namedComp.compare(o1,o2); } public static Date getStart(Reservation r) { Date maxDate = null; Appointment[] apps =r.getAppointments(); for ( int i=0;i< apps.length;i++) { Appointment app = apps[i]; if (maxDate == null || app.getStart().before( maxDate)) { maxDate = app.getStart() ; } } if ( maxDate == null) { maxDate = new Date(); } return maxDate; } public int compare(Date d1,Object o2) { if (o2 instanceof Date) return d1.compareTo((Date) o2); Reservation r2 = (Reservation) o2; if (d1.before(getStart(r2))) { //System.out.println(a2 + ">" + d1); return -1; } if (d1.after(getStart(r2))) { // System.out.println(a2 + "<" + d1); return 1; } // If appointment.getStart().equals(date) // set the appointment before the date return 1; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain; import java.util.List; /** Formats the different appointment outputs. */ public interface AppointmentFormater { String getShortSummary(Appointment appointment); String getVeryShortSummary(Appointment appointment); String getSummary( Appointment a ); String getSummary( Repeating r , List<Period> periods); String getSummary( Repeating r ); String getExceptionSummary( Repeating r ); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.rapla.components.util.Assert; import org.rapla.components.util.DateTools; import org.rapla.components.util.TimeInterval; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.AppointmentStartComparator; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.RepeatingType; import org.rapla.entities.domain.Reservation; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.facade.RaplaComponent; public final class AppointmentImpl extends SimpleEntity implements Appointment { private Date start; private Date end; private RepeatingImpl repeating; private boolean isWholeDaysSet = false; /** set DE (DebugDisabled) to false for debuging output. You must change in code because this flag is final for efficience reasons.*/ public final static boolean DE = true; public final static String BUG = null; public static String DD = null; final public RaplaType<Appointment> getRaplaType() {return TYPE;} transient ReservationImpl parent; public AppointmentImpl() { } public AppointmentImpl(Date start,Date end) { this.start = start; this.end = end; if ( start != null && end!= null && DateTools.cutDate( start ).equals( start) && DateTools.cutDate( end).equals(end)) { isWholeDaysSet = true; } } public AppointmentImpl(Date start,Date end, RepeatingType type, int repeatingDuration) { this(start,end); this.repeating = new RepeatingImpl(type,this); repeating.setAppointment( this ); repeating.setNumber(repeatingDuration); } public void setParent(ReservationImpl parent) { this.parent = parent; if (repeating != null) { repeating.setAppointment( this ); } } public void removeParent() { this.parent = null; } public Date getStart() { return start;} public Date getEnd() { return end;} public void setReadOnly() { super.setReadOnly( ); if ( repeating != null ) repeating.setReadOnly( ); } public void move(Date newStart) { long diff = this.end.getTime() - this.start.getTime(); move(newStart, new Date(newStart.getTime() + diff)); } public void move(Date start,Date end) { checkWritable(); this.start = start; this.end = end; if ( isWholeDaysSet) { if (start.getTime() != DateTools.cutDate(start.getTime()) || end.getTime() != DateTools.cutDate(end.getTime())) { isWholeDaysSet = false; } } } public String toString() { if (start != null && end != null) return f(start.getTime(),end.getTime()) + ((repeating != null) ? (" [" + repeating.toString()) + "]": ""); else return start + "-" + end; } public Reservation getReservation() { return parent; } public boolean isWholeDaysSet() { return isWholeDaysSet; } @Override public Iterable<ReferenceInfo> getReferenceInfo() { return Collections.emptyList(); } public void setWholeDays(boolean enable) { checkWritable(); if (enable) { long cutStartTime = DateTools.cutDate(start.getTime()); if (start.getTime() != cutStartTime) { this.start = new Date(cutStartTime); } long cutEndTime = DateTools.cutDate(end.getTime()); if (end.getTime() != cutEndTime) { this.end = DateTools.fillDate(this.end); } if ( end.getTime() <= start.getTime()) { this.end = DateTools.fillDate(this.start); } if ( repeating != null && repeating.getType() == RepeatingType.DAILY) { this.end = DateTools.fillDate( this.start); } } isWholeDaysSet = enable; } public int compareTo(Appointment a2) { Date start2 = a2.getStart(); Date end2 = a2.getEnd(); if (start.before( start2)) return -1; if (start.after( start2)) return 1; if (getEnd().before( end2)) return -1; if (getEnd().after( end2)) return 1; if ( a2 == this) { return 0; } Comparable id1 = getId(); Comparable id2 = a2.getId(); if ( id1 == null || id2 == null) { return hashCode() < a2.hashCode() ? -1 : 1; } @SuppressWarnings("unchecked") int compareTo = id1.compareTo( id2); return compareTo; } transient Date maxDate; /** returns the largest date that covers the appointment and null if the appointments repeats forever. */ public Date getMaxEnd() { long end = (this.end!= null) ? this.end.getTime():0; if (repeating != null) if (repeating.getEnd() != null) end = Math.max(end ,repeating.getEnd().getTime()); else end = 0; if (end == 0) return null; // cache max date object if (maxDate == null || maxDate.getTime() != end) maxDate = new Date(end); return maxDate; } public Repeating getRepeating() { if ( repeating != null && repeating.getAppointment() == null) { repeating.setAppointment( this); } return repeating; } public void setRepeatingEnabled(boolean enableRepeating) { checkWritable(); if (this.repeating == null) { if (enableRepeating) { this.repeating = new RepeatingImpl(Repeating.WEEKLY,this); this.repeating.setAppointment( this); } } else { if (!enableRepeating) { this.repeating = null; } } } public boolean isRepeatingEnabled() { return repeating != null; } public Date getFirstDifference( Appointment a2, Date maxDate ) { List<AppointmentBlock> blocks1 = new ArrayList<AppointmentBlock>(); createBlocks( start, maxDate, blocks1); List<AppointmentBlock> blocks2 = new ArrayList<AppointmentBlock>(); a2.createBlocks(a2.getStart(), maxDate, blocks2); // System.out.println("block sizes " + blocks1.size() + ", " + blocks2.size() ); int i=0; for ( AppointmentBlock block:blocks1) { long a1Start = block.getStart(); long a1End = block.getEnd(); if ( i >= blocks2.size() ) { return new Date( a1Start ); } long a2Start = blocks2.get( i ).getStart(); long a2End = blocks2.get( i ).getEnd(); //System.out.println("a1Start " + a1Start + " a1End " + a1End); //System.out.println("a2Start " + a2Start + " a2End " + a2End); if ( a1Start != a2Start ) return new Date( Math.min ( a1Start, a2Start ) ); if ( a1End != a2End ) return new Date( Math.min ( a1End, a2End ) ); i++; } if ( blocks2.size() > blocks1.size() ) { return new Date( blocks2.get( blocks1.size() ).getStart() ); } return null; } public Date getLastDifference( Appointment a2, Date maxDate ) { List<AppointmentBlock> blocks1 = new ArrayList<AppointmentBlock>(); createBlocks( start, maxDate, blocks1); List<AppointmentBlock> blocks2 = new ArrayList<AppointmentBlock>(); a2.createBlocks(a2.getStart(), maxDate, blocks2); if ( blocks2.size() > blocks1.size() ) { return new Date( blocks2.get( blocks1.size() ).getEnd() ); } if ( blocks1.size() > blocks2.size() ) { return new Date( blocks1.get( blocks2.size() ).getEnd() ); } for ( int i = blocks1.size() - 1 ; i >= 0; i-- ) { long a1Start = blocks1.get( i ).getStart(); long a1End = blocks1.get( i ).getEnd(); long a2Start = blocks2.get( i ).getStart(); long a2End = blocks2.get( i ).getEnd(); if ( a1End != a2End ) return new Date( Math.max ( a1End, a2End ) ); if ( a1Start != a2Start ) return new Date( Math.max ( a1Start, a2Start ) ); } return null; } public boolean matches(Appointment a2) { if (!equalsOrBothNull(this.start, a2.getStart())) return false; if (!equalsOrBothNull(this.end, a2.getEnd())) return false; Repeating r1 = this.repeating; Repeating r2 = a2.getRepeating(); // No repeatings. The two appointments match if (r1 == null && r2 == null) { return true; } else if (r1 == null || r2 == null) { // one repeating is null the other not so the appointments don't match return false; } if (!r1.getType().equals(r2.getType())) return false; if (r1.getInterval() != r2.getInterval()) return false; if (!equalsOrBothNull(r1.getEnd(), r2.getEnd())) return false; // The repeatings match regulary, so we must test the exceptions Date[] e1 = r1.getExceptions(); Date[] e2 = r2.getExceptions(); if (e1.length != e2.length) { //System.out.println("Exception-length don't match"); return false; } for (int i=0;i<e1.length;i++) if (!e1[i].equals(e2[i])) { //System.out.println("Exception " + e1[i] + " doesn't match " + e2[i]); return false; } // Even the repeatings match, so we can return true return true; } public void createBlocks(Date start,Date end,Collection<AppointmentBlock> blocks) { boolean excludeExceptions = true; createBlocks(start,end, blocks, excludeExceptions); } public void createBlocks(Date start,Date end,Collection<AppointmentBlock> blocks, boolean excludeExceptions) { Assert.notNull(blocks); Assert.notNull(start,"You must set a startDate"); Assert.notNull(end, "You must set an endDate"); processBlocks(start.getTime(), end.getTime(), blocks, excludeExceptions, null); } public void createBlocks(Date start,Date end,Collection<AppointmentBlock> blocks, SortedSet<AppointmentBlock> additionalSet) { Assert.notNull(blocks); Assert.notNull(start,"You must set a startDate"); Assert.notNull(end, "You must set an endDate"); processBlocks(start.getTime(), end.getTime(), blocks, true, additionalSet); } /* returns true if there is at least one block in an array. If the passed blocks array is not null it will contain all blocks * that overlap the start,end period after a call.*/ private boolean processBlocks(long start,long end,Collection<AppointmentBlock> blocks, boolean excludeExceptions, SortedSet<AppointmentBlock> additionalSet) { long c1 = start; long c2 = end; long s = this.start.getTime(); long e = this.end.getTime(); // if there is no repeating if (repeating==null) { if (s <c2 && e>c1) { // check only if ( blocks == null ) { return true; } else { AppointmentBlock block = new AppointmentBlock(s,e,this, false); blocks.add(block); if ( additionalSet != null) { additionalSet.add( block ); } } } return false; } DD=DE?BUG: print("s = appointmentstart, e = appointmentend, c1 = intervalstart c2 = intervalend"); DD=DE?BUG: print("s:" + n(s) + " e:" + n(e) + " c2:" + n(c2) + " c1:" + n(c1)); if (s <c2 && e>c1 && (!repeating.isException(s) || !excludeExceptions)) { // check only if ( blocks == null) { return true; } else { AppointmentBlock block = new AppointmentBlock(s,e,this, repeating.isException(s)); blocks.add(block); if ( additionalSet != null) { additionalSet.add( block ); } } } long l = repeating.getIntervalLength( s ); //System.out.println( "l in days " + l / DateTools.MILLISECONDS_PER_DAY ); Assert.isTrue(l>0); long timeFromStart = l ; if ( repeating.isFixedIntervalLength()) { timeFromStart = Math.max(l,((c1-e) / l)* l); } int maxNumber = repeating.getNumber(); long maxEnding = Long.MAX_VALUE; if ( maxNumber >= 0) { maxEnding = repeating.getEnd().getTime(); } DD=DE?BUG: print("l = repeatingInterval (in minutes), x = stepcount"); DD=DE?BUG: print("Maxend " + f( maxEnding)); long currentPos = s + timeFromStart; DD=DE?BUG: print( " currentPos:" + n(currentPos) + " c2-s:" + n(c2-s) + " c1-e:" + n(c1-e)); long blockLength = Math.max(0, e - s); while (currentPos <= c2 && (maxNumber<0 || (currentPos<=maxEnding ))) { DD=DE?BUG: print(" current pos:" + f(currentPos)); if (( currentPos + blockLength > c1 ) && ( currentPos < c2 ) && (( end!=DateTools.cutDate(end) || !repeating.isDaily() || currentPos < maxEnding))) { boolean isException =repeating.isException( currentPos ); if ((!isException || !excludeExceptions)) { // check only if ( blocks == null ) { return true; } else { AppointmentBlock block = new AppointmentBlock(currentPos,currentPos + blockLength,this, isException); blocks.add( block); if ( additionalSet != null) { additionalSet.add( block ); } } } } currentPos += repeating.getIntervalLength( currentPos) ; } return false; } public boolean overlaps(Date start,Date end) { return overlaps( start, end , true ); } public boolean overlaps(AppointmentBlock block) { long end = block.getEnd(); long start = block.getStart(); return overlaps(start, end, true); } public boolean overlaps(TimeInterval interval) { if ( interval == null) { return false; } return overlaps( interval.getStart(), interval.getEnd()); } public boolean overlaps(Date start2,Date end2, boolean excludeExceptions) { if (start2 == null && end2 == null) return true; if (start2 == null) start2 = this.start; if (end2 == null) { // there must be an overlapp because there can't be infinity exceptions if (getMaxEnd() == null) return true; end2 = getMaxEnd(); } if (getMaxEnd() != null && !start2.before(getMaxEnd())) return false; if (!this.start.before(end2)) return false; boolean overlaps = processBlocks( start2.getTime(), end2.getTime(), null, excludeExceptions, null ); return overlaps; } public boolean overlaps(long start,long end, boolean excludeExceptions) { if (getMaxEnd() != null && getMaxEnd().getTime()<start) return false; if (this.start.getTime() > end) return false; boolean overlaps = processBlocks( start, end, null, excludeExceptions, null ); return overlaps; } private static Date getOverlappingEnd(Repeating r1,Repeating r2) { Date maxEnd = null; if (r1.getEnd() != null) maxEnd = r1.getEnd(); if (r2.getEnd() != null) if (maxEnd != null && r2.getEnd().before(maxEnd)) maxEnd = r2.getEnd(); return maxEnd; } public boolean overlaps(Appointment a2) { if ( a2 == this) return true; Date start2 =a2.getStart(); Date end2 =a2.getEnd(); long s1 = this.start.getTime(); long s2 = start2.getTime(); long e1 = this.end.getTime(); long e2 = a2.getEnd().getTime(); RepeatingImpl r1 = this.repeating; RepeatingImpl r2 = (RepeatingImpl)a2.getRepeating(); DD=DE?BUG: print("Testing overlap of"); DD=DE?BUG: print(" A1: " + toString()); DD=DE?BUG: print(" A2: " + a2.toString()); if (r1 == null && r2 == null) { if (e2<=s1 || e1<=s2) return false; return true; } if (r1 == null) { return a2.overlaps(this.start,this.end); } if (r2 == null) { return overlaps(start2,end2); } // So both appointments have a repeating // If r2 has no exceptions we can check if a1 overlaps the first appointment of a2 if (overlaps(start2,end2) && !r2.isException(start2.getTime())) { DD=DE?BUG: print("Primitive overlap for " + getReservation() + " with " + a2.getReservation()); return true; } // Check if appointments could overlap because of the end-dates of an repeating Date end = getOverlappingEnd(r1,r2); if (end != null && (end.getTime()<=s1 || end.getTime()<=s2)) return false; end = getOverlappingEnd(r2,r1); if (end != null && (end.getTime()<=s1 || end.getTime()<=s2)) // We cant compare the fixed interval length here so we have to compare the blocks if ( !r1.isFixedIntervalLength()) { return overlapsHard( (AppointmentImpl)a2); } if ( !r2.isFixedIntervalLength()) { return ((AppointmentImpl)a2).overlapsHard( this); } // O.K. we found 2 Candidates for the hard way long l1 = r1.getFixedIntervalLength(); long l2 = r2.getFixedIntervalLength(); // The greatest common divider of the two intervals long gcd = gcd(l1,l2); long startx1 = Math.max(0,(s2-e1))/l1; long startx2 = Math.max(0,(s1-e2))/l2; DD=DE?BUG: print("l? = intervalsize for A?, x? = stepcount for A? "); long max_x1 = l2/gcd + startx1; if (end!= null && (end.getTime()-s1)/l1 + startx1 < max_x1) max_x1 = (end.getTime()-s1)/l1 + startx1; long max_x2 = l1/gcd + startx2; if (end!= null && (end.getTime()-s2)/l2 + startx2 < max_x2) max_x2 = (end.getTime()-s2)/l2 + startx2; long x1 =startx1; long x2 =startx2; DD=DE?BUG: print( "l1: " + n(l1) + " l2: " + n(l2) + " gcd: " + n(gcd) + " start_x1: " + startx1 + " start_x2: " + startx2 + " max_x1: " + max_x1 + " max_x2: " + max_x2 ); boolean overlaps = false; long current1 = x1 *l1; long current2 = x2 *l2; long maxEnd1 = max_x1*l1; long maxEnd2 = max_x2*l2; while (current1<=maxEnd1 && current2<=maxEnd2) { // DD=DE?BUG: print("x1: " + x1 + " x2:" + x2); DD=DE?BUG: print(" A1: " + f(s1 + current1, e1 + current1)); DD=DE?BUG: print(" A2: " + f(s2 + current2, e2 + current2)); if ((s1 + current1) < (e2 + current2) && (e1 + current1) > (s2 + current2)) { if (!hasExceptionForEveryPossibleCollisionInInterval(s1 + current1,s2 + current2,r2)) { overlaps = true; break; } } if ((s1 + current1) < (s2 + current2)) current1+=l1; else current2+=l2; } if (overlaps) DD=DE?BUG: print("Appointments overlap"); else DD=DE?BUG: print("Appointments don't overlap"); return overlaps; } private boolean overlapsHard( AppointmentImpl a2 ) { Repeating r2 = a2.getRepeating(); Collection<AppointmentBlock> array = new ArrayList<AppointmentBlock>(); Date maxEnd =r2.getEnd(); // overlaps will be checked two 250 weeks (5 years) from now on long maxCheck = System.currentTimeMillis() + DateTools.MILLISECONDS_PER_WEEK * 250; if ( maxEnd == null || maxEnd.getTime() > maxCheck) { maxEnd = new Date(maxCheck); } createBlocks( getStart(), maxEnd, array); for ( AppointmentBlock block:array) { long start = block.getStart(); long end = block.getEnd(); if (a2.overlaps( start, end, true)) { return true; } } return false; } /** the greatest common divider of a and b (Euklids Algorithm) */ public static long gcd(long a,long b){ return (b == 0) ? a : gcd(b, a%b); } /* Prueft im Abstand von "gap" millisekunden das Intervall von start bis ende auf Ausnahmen. Gibt es fuer einen Punkt keine Ausnahme wird false zurueckgeliefert. */ private boolean hasExceptionForEveryPossibleCollisionInInterval(long s1,long s2,RepeatingImpl r2) { RepeatingImpl r1 = repeating; Date end= getOverlappingEnd(r1,r2); if (end == null) return false; if ((!r1.hasExceptions() && !r2.hasExceptions())) return false; long l1 = r1.getFixedIntervalLength(); long l2 = r2.getFixedIntervalLength(); long gap = (l1 * l2) / gcd(l1,l2); Date[] exceptions1 = r1.getExceptions(); Date[] exceptions2 = r2.getExceptions(); DD=DE?BUG: print(" Testing Exceptions for overlapp " + f(s1) + " with " + f(s2) + " gap " + n(gap)); int i1 = 0; int i2 = 0; long x = 0; if (exceptions1.length>i1) DD=DE?BUG: print("Exception a1: " + fe(exceptions1[i1].getTime())); if (exceptions2.length>i2) DD=DE?BUG: print("Exception a2: " + fe(exceptions2[i2].getTime())); long exceptionTime1 = 0; long exceptionTime2 = 0; while (s1 + x * gap < end.getTime()) { DD=DE?BUG: print("Looking for exception for gap " + x + " s1: " + fe(s1+x*gap) + " s2: " + fe(s2+x*gap)); long pos1 = s1 + x*gap; long pos2 = s2 + x*gap; // Find first exception from app1 that matches gap while (i1<exceptions1.length) { exceptionTime1=exceptions1[i1].getTime(); if ( exceptionTime1 >= pos1) { DD=DE?BUG: print("Exception a1: " + fe(exceptionTime1)); break; } i1 ++; } // Find first exception from app2 that matches gap while (i2<exceptions2.length) { exceptionTime2 = exceptions2[i2].getTime(); if ( exceptionTime2 >= pos1) { DD=DE?BUG: print("Exception a2: " + fe(exceptionTime2)); break; } i2 ++; } boolean matches1 = false; if (pos1 >= exceptionTime1 && pos1<= exceptionTime1 + DateTools.MILLISECONDS_PER_DAY) { DD=DE?BUG: print("Exception from a1 matches!"); matches1=true; } boolean matches2 = false; if ((pos2 >= exceptionTime2 && pos2 <= exceptionTime2 + DateTools.MILLISECONDS_PER_DAY)) { DD=DE?BUG: print("Exception from a2 matches!"); matches2=true; } if (!matches1 && !matches2) { DD=DE?BUG: print("No matching exception found at date " + fe(pos1) + " or " + fe(pos2) ); return false; } DD=DE?BUG: print("Exception found for gap " + x); x ++; } DD=DE?BUG: print("Exceptions found for every gap. No overlapping. "); return true; } private static String print(String string) { if (string != null) System.out.println(string); return string; } /* cuts the milliseconds and seconds. Usefull for debugging output.*/ private long n(long n) { return n / (1000 * 60); } /* Formats milliseconds as date. Usefull for debugging output.*/ static String f(long n) { return DateTools.formatDateTime(new Date(n)); } /* Formats milliseconds as date without time. Usefull for debugging output.*/ static String fe(long n) { return DateTools.formatDate(new Date(n)); } /* Formats 2 dates in milliseconds as appointment. Usefull for debugging output.*/ static String f(long s,long e) { Date start = new Date(s); Date end = new Date(e); if (DateTools.isSameDay(s,e)) { return DateTools.formatDateTime(start) + "-" + DateTools.formatTime(end); } else { return DateTools.formatDateTime(start) + "-" + DateTools.formatDateTime(end); } } static private void copy(AppointmentImpl source,AppointmentImpl dest) { dest.isWholeDaysSet = source.isWholeDaysSet; dest.start = source.start; dest.end = source.end; dest.repeating = (RepeatingImpl) ((source.repeating != null) ? source.repeating.clone() : null); if (dest.repeating != null) dest.repeating.setAppointment(dest); dest.parent = source.parent; } public void copy(Object obj) { synchronized ( this) { AppointmentImpl casted = (AppointmentImpl) obj; copy(casted,this); } } public AppointmentImpl clone() { AppointmentImpl clone = new AppointmentImpl(); super.deepClone(clone); copy(this,clone); return clone; } static public SortedSet<Appointment> getAppointments(SortedSet<Appointment> sortedAppointmentList,User user,Date start,Date end, boolean excludeExceptions) { SortedSet<Appointment> appointmentSet = new TreeSet<Appointment>(new AppointmentStartComparator()); Iterator<Appointment> it; if (end != null) { // all appointments that start before the enddate AppointmentImpl compareElement = new AppointmentImpl(end, end); compareElement.setId("DUMMYID"); SortedSet<Appointment> headSet = sortedAppointmentList.headSet(compareElement); it = headSet.iterator(); //it = appointments.values().iterator(); } else { it = sortedAppointmentList.iterator(); } while (it.hasNext()) { Appointment appointment = it.next(); // test if appointment end before the start-date if (end != null && appointment.getStart().after(end)) break; // Ignore appointments without a reservation if ( appointment.getReservation() == null) continue; if ( !appointment.overlaps(start,end, excludeExceptions)) continue; if (user == null || user.equals(appointment.getOwner()) ) { appointmentSet.add(appointment); } } return appointmentSet; } public static Set<Appointment> getConflictingAppointments(SortedSet<Appointment> appointmentSet, Appointment appointment, Collection<Reservation> ignoreList, boolean onlyFirstConflictingAppointment) { Set<Appointment> conflictingAppointments = new HashSet<Appointment>(); Date start =appointment.getStart(); Date end = appointment.getMaxEnd(); // Templates don't cause conflicts if ( RaplaComponent.isTemplate( appointment)) { return conflictingAppointments; } boolean excludeExceptions = true; SortedSet<Appointment> appointmentsToTest = AppointmentImpl.getAppointments(appointmentSet, null, start, end, excludeExceptions); for ( Appointment overlappingAppointment: appointmentsToTest) { Reservation r1 = appointment.getReservation(); Reservation r2 = overlappingAppointment.getReservation(); if ( RaplaComponent.isTemplate( r1) || RaplaComponent.isTemplate( r2)) { continue; } if ( r2 != null && ignoreList.contains( r2)) { continue; } // Don't test overlapping for the same reservations if ( r1 != null && r2 != null && r1.equals( r2) ) { continue; } // or the same appointment if ( overlappingAppointment.equals(appointment )) { continue; } if ( overlappingAppointment.overlaps( appointment) ) { if ( !RaplaComponent.isTemplate( overlappingAppointment)) { conflictingAppointments.add( overlappingAppointment); if ( onlyFirstConflictingAppointment) { return conflictingAppointments; } } } } return conflictingAppointments; } private static boolean equalsOrBothNull(Object o1, Object o2) { if (o1 == null) { if (o2 != null) { return false; } } else if ( o2 == null) { return false; } else if (!o1.equals( o2 ) ) { return false; } return true; } public User getOwner() { Reservation reservation = getReservation(); if ( reservation != null) { User owner = reservation.getOwner(); return owner; } return null; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, of which license fullfill the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import org.rapla.components.util.DateTools; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.ReadOnlyException; import org.rapla.entities.User; import org.rapla.entities.domain.Permission; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.internal.ReferenceHandler; public final class PermissionImpl extends ReferenceHandler implements Permission,EntityReferencer { transient boolean readOnly = false; Date pEnd = null; Date pStart = null; Integer maxAdvance = null; Integer minAdvance = null; int accessLevel = ALLOCATE_CONFLICTS; public void setUser(User user) { checkWritable(); if (user != null) putEntity("group",null); putEntity("user",(Entity)user); } public void setEnd(Date end) { checkWritable(); this.pEnd = end; if ( end != null ) this.maxAdvance = null; } public Date getEnd() { return pEnd; } @Override protected Class<? extends Entity> getInfoClass(String key) { if ( key.equals("group")) { return Category.class; } if ( key.equals("user")) { return User.class; } return null; } public void setStart(Date start) { checkWritable(); this.pStart = start; if ( start != null ) this.minAdvance = null; } public Date getStart() { return pStart; } public void setMinAdvance(Integer minAdvance) { checkWritable(); this.minAdvance = minAdvance; if ( minAdvance != null ) this.pStart = null; } public Integer getMinAdvance() { return minAdvance; } public void setMaxAdvance(Integer maxAdvance) { checkWritable(); this.maxAdvance = maxAdvance; if ( maxAdvance != null ) this.pEnd = null; } public Integer getMaxAdvance() { return maxAdvance; } public void setReadOnly() { this.readOnly = true; } public boolean isReadOnly() { return readOnly; } public void checkWritable() { if ( readOnly ) throw new ReadOnlyException( this ); } public boolean affectsUser(User user) { int userEffect = getUserEffect( user ); return userEffect> NO_PERMISSION; } public int getUserEffect(User user) { return getUserEffect(user, null); } public int getUserEffect(User user, Collection<Category> groups) { User pUser = getUser(); Category pGroup = getGroup(); if ( pUser == null && pGroup == null ) { return ALL_USER_PERMISSION; } if ( pUser != null && user.equals( pUser ) ) { return USER_PERMISSION; } else if ( pGroup != null ) { if ( groups == null) { if ( user.belongsTo( pGroup)) { return GROUP_PERMISSION; } } else { if ( groups.contains(pGroup)) { return GROUP_PERMISSION; } } } return NO_PERMISSION; } public void setAccessLevel(int accessLevel) { if (accessLevel <5) { accessLevel*= 100; } this.accessLevel = accessLevel; } public int getAccessLevel() { return accessLevel; } public User getUser() { return getEntity("user", User.class); } public void setGroup(Category group) { if (group != null) putEntity("user",null); putEntity("group",(Entity)group); } public ReferenceHandler getReferenceHandler() { return this; } public Category getGroup() { return getEntity("group", Category.class); } public Date getMinAllowed(Date today) { if ( pStart != null ) return pStart; if ( minAdvance != null) return new Date( today.getTime() + DateTools.MILLISECONDS_PER_DAY * minAdvance.longValue() ); return null; } public Date getMaxAllowed(Date today) { if ( pEnd != null ) return pEnd; if ( maxAdvance != null) return new Date( today.getTime() + DateTools.MILLISECONDS_PER_DAY * (maxAdvance.longValue() + 1) ); return null; } public boolean hasTimeLimits() { return pStart != null || pEnd != null || minAdvance != null || maxAdvance != null; } /** only checks if the user is allowed to make a reservation in the future */ public boolean valid( Date today ) { if ( pEnd != null && ( today == null || pEnd.getTime() + DateTools.MILLISECONDS_PER_DAY<=( today.getTime() ) ) ) { return false; } if ( maxAdvance != null && today != null) { long pEndTime = today.getTime() + DateTools.MILLISECONDS_PER_DAY * (maxAdvance.longValue() + 1); if ( pEndTime < today.getTime() ) { //System.out.println( " end after permission " + end + " > " + pEndTime ); return false; } } return true; } public boolean covers( Date start, Date end, Date today ) { if ( pStart != null && (start == null || start.before ( pStart ) ) ) { //System.out.println( " start before permission "); return false; } if ( pEnd != null && ( end == null || pEnd.getTime() + DateTools.MILLISECONDS_PER_DAY<=end.getTime() ) ) { //System.out.println( " end before permission "); return false; } if ( minAdvance != null ) { long pStartTime = today.getTime() + DateTools.MILLISECONDS_PER_DAY * minAdvance.longValue(); if ( start == null || start.getTime() < pStartTime ) { //System.out.println( " start before permission " + start + " < " + pStartTime ); return false; } } if ( maxAdvance != null ) { long pEndTime = today.getTime() + DateTools.MILLISECONDS_PER_DAY * (maxAdvance.longValue() + 1); if ( end == null || pEndTime < end.getTime() ) { //System.out.println( " end after permission " + end + " > " + pEndTime ); return false; } } return true; } public PermissionImpl clone() { PermissionImpl clone = new PermissionImpl(); clone.links = new LinkedHashMap<String,List<String>>(); for ( String key:links.keySet()) { List<String> idList = links.get( key); clone.links.put( key, new ArrayList<String>(idList)); } clone.resolver = this.resolver; // This must be done first clone.accessLevel = accessLevel; clone.pEnd = pEnd; clone.pStart = pStart; clone.minAdvance = minAdvance; clone.maxAdvance = maxAdvance; return clone; } // compares two Permissions on basis of their attributes: user, group, // start, end, access // therefore, method uses the method equalValues() for comparing two // attributes public boolean equals(Object o) { if (o == null) return false; PermissionImpl perm = (PermissionImpl) o; if (equalValues(this.getReferenceHandler().getId("user"), perm.getReferenceHandler().getId("user")) && equalValues(this.getReferenceHandler().getId("group"), perm.getReferenceHandler().getId("group")) && equalValues(this.getStart(), perm.getStart()) && equalValues(this.getEnd(), perm.getEnd()) && equalValues(this.getAccessLevel(), perm.getAccessLevel())) return true; else return false; } public int hashCode() { StringBuilder buf = new StringBuilder(); append( buf,getReferenceHandler().getId("user")); append( buf,getReferenceHandler().getId("group")); append( buf,getStart()); append( buf,getEnd()); append( buf,getAccessLevel()); return buf.toString().hashCode(); } private void append(StringBuilder buf, Object obj) { if ( obj != null) { buf.append( obj.hashCode()); } } // compares two values/attributes // equity is given when both are null or equal private boolean equalValues(Object obj1, Object obj2) { return (obj1 == null && obj2 == null) || (obj1 != null && obj1.equals(obj2)); } public String toString() { StringBuffer buf = new StringBuffer(); if ( getUser() != null) { buf.append("User=" + getUser().getUsername()); } if ( getGroup() != null) { buf.append("Group=" + getGroup().getName(Locale.ENGLISH)); } buf.append ( " AccessLevel=" + getAccessLevel()); if ( getStart() != null) { buf.append ( " Beginning=" + getStart()); } if ( getEnd() != null) { buf.append ( " Ending=" + getEnd()); } if (getMinAdvance() != null) { buf.append ( " MinAdvance=" + getMinAdvance()); } if (getMaxAdvance() != null) { buf.append ( " MaxAdvance=" + getMaxAdvance()); } return buf.toString(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain.internal; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import org.rapla.components.util.TimeInterval; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.components.util.iterator.NestedIterator; import org.rapla.entities.Category; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Permission; import org.rapla.entities.domain.ResourceAnnotations; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.entities.dynamictype.internal.ClassificationImpl; import org.rapla.entities.internal.ModifiableTimestamp; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.internal.SimpleEntity; public final class AllocatableImpl extends SimpleEntity implements Allocatable,DynamicTypeDependant, ModifiableTimestamp { private ClassificationImpl classification; private Set<PermissionImpl> permissions = new LinkedHashSet<PermissionImpl>(); private Date lastChanged; private Date createDate; private Map<String,String> annotations; transient private boolean permissionArrayUpToDate = false; transient private PermissionImpl[] permissionArray; AllocatableImpl() { this (null, null); } public AllocatableImpl(Date createDate, Date lastChanged ) { // No create date should be possible and time should always be set through storage operators as they now the timezone settings // if (createDate == null) { // Calendar calendar = Calendar.getInstance(); // this.createDate = calendar.getTime(); // } // else this.createDate = createDate; this.lastChanged = lastChanged; if (lastChanged == null) this.lastChanged = this.createDate; } public void setResolver( EntityResolver resolver) { super.setResolver( resolver); if ( classification != null) { classification.setResolver( resolver); } for (Iterator<PermissionImpl> it = permissions.iterator();it.hasNext();) { it.next().setResolver( resolver); } } public void setReadOnly() { super.setReadOnly( ); classification.setReadOnly( ); Iterator<PermissionImpl> it = permissions.iterator(); while (it.hasNext()) { it.next().setReadOnly(); } } public Date getLastChanged() { return lastChanged; } @Deprecated public Date getLastChangeTime() { return lastChanged; } public Date getCreateTime() { return createDate; } public void setLastChanged(Date date) { checkWritable(); lastChanged = date; } public void setCreateDate(Date createDate) { checkWritable(); this.createDate = createDate; } public RaplaType<Allocatable> getRaplaType() { return TYPE; } // Implementation of interface classifiable public Classification getClassification() { return classification; } public void setClassification(Classification classification) { this.classification = (ClassificationImpl) classification; } public String getName(Locale locale) { Classification c = getClassification(); if (c == null) return ""; return c.getName(locale); } public boolean isPerson() { final Classification classification2 = getClassification(); if ( classification2 == null) { return false; } final String annotation = classification2.getType().getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); return annotation != null && annotation.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON); } private boolean hasAccess( User user, int accessLevel, Date start, Date end, Date today, boolean checkOnlyToday ) { Permission[] permissions = getPermissions(); if ( user == null || user.isAdmin() ) return true; int maxAccessLevel = 0; int maxEffectLevel = Permission.NO_PERMISSION; Category[] originalGroups = user.getGroups(); Collection<Category> groups = new HashSet<Category>( Arrays.asList( originalGroups)); for ( Category group: originalGroups) { Category parent = group.getParent(); while ( parent != null) { if ( ! groups.contains( parent)) { groups.add( parent); } if ( parent == group) { throw new IllegalStateException("Parent added to own child"); } parent = parent.getParent(); } } for ( int i = 0; i < permissions.length; i++ ) { Permission p = permissions[i]; int effectLevel = ((PermissionImpl)p).getUserEffect(user, groups); if ( effectLevel >= maxEffectLevel && effectLevel > Permission.NO_PERMISSION) { if ( p.hasTimeLimits() && accessLevel >= Permission.ALLOCATE && today!= null) { if (p.getAccessLevel() != Permission.ADMIN ) { if ( checkOnlyToday ) { if (!((PermissionImpl)p).valid(today)) { continue; } } else { if (!p.covers( start, end, today )) { continue; } } } } if ( maxAccessLevel < p.getAccessLevel() || effectLevel > maxEffectLevel) { maxAccessLevel = p.getAccessLevel(); } maxEffectLevel = effectLevel; } } boolean granted = maxAccessLevel >= accessLevel ; return granted; } public TimeInterval getAllocateInterval( User user, Date today) { Permission[] permissions = getPermissions(); if ( user == null || user.isAdmin() ) return new TimeInterval( null, null); TimeInterval interval = null; int maxEffectLevel = Permission.NO_PERMISSION; for ( int i = 0; i < permissions.length; i++ ) { Permission p = permissions[i]; int effectLevel = p.getUserEffect(user); int accessLevel = p.getAccessLevel(); if ( effectLevel >= maxEffectLevel && effectLevel > Permission.NO_PERMISSION && accessLevel>= Permission.ALLOCATE) { Date start; Date end; if (accessLevel != Permission.ADMIN ) { start = p.getMinAllowed( today); end = p.getMaxAllowed(today); if ( end != null && end.before( today)) { continue; } } else { start = null; end = null; } if ( interval == null || effectLevel > maxEffectLevel) { interval = new TimeInterval(start, end); } else { interval = interval.union(new TimeInterval(start, end)); } maxEffectLevel = effectLevel; } } return interval; } private boolean hasAccess( User user, int accessLevel ) { return hasAccess(user, accessLevel, null, null, null, false); } public boolean canCreateConflicts( User user ) { return hasAccess( user, Permission.ALLOCATE_CONFLICTS); } public boolean canModify(User user) { return hasAccess( user, Permission.ADMIN); } public boolean canRead(User user) { return hasAccess( user, Permission.READ ); } @Deprecated public boolean isHoldBackConflicts() { String annotation = getAnnotation(ResourceAnnotations.KEY_CONFLICT_CREATION); if ( annotation != null && annotation.equals(ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE)) { return true; } return false; } public boolean canReadOnlyInformation(User user) { return hasAccess( user, Permission.READ_ONLY_INFORMATION ); } public boolean canAllocate( User user,Date today ) { boolean hasAccess = hasAccess(user, Permission.ALLOCATE, null, null, today, true); if ( !hasAccess ) { return false; } return true; } public boolean canAllocate( User user, Date start, Date end, Date today ) { return hasAccess(user, Permission.ALLOCATE,start, end, today, false); } public void addPermission(Permission permission) { checkWritable(); permissionArrayUpToDate = false; permissions.add((PermissionImpl)permission); } public boolean removePermission(Permission permission) { checkWritable(); permissionArrayUpToDate = false; return permissions.remove(permission); } public Permission newPermission() { PermissionImpl permissionImpl = new PermissionImpl(); if ( resolver != null) { permissionImpl.setResolver( resolver); } return permissionImpl; } public Permission[] getPermissions() { updatePermissionArray(); return permissionArray; } private void updatePermissionArray() { if ( permissionArrayUpToDate ) return; synchronized ( this) { permissionArray = permissions.toArray(new PermissionImpl[] {}); permissionArrayUpToDate = true; } } @Override public Iterable<ReferenceInfo> getReferenceInfo() { return new IteratorChain<ReferenceInfo> ( super.getReferenceInfo() ,classification.getReferenceInfo() ,new NestedIterator<ReferenceInfo,PermissionImpl>( permissions ) { public Iterable<ReferenceInfo> getNestedIterator(PermissionImpl obj) { return obj.getReferenceInfo(); } } ); } public boolean needsChange(DynamicType type) { return classification.needsChange( type ); } public void commitChange(DynamicType type) { classification.commitChange( type ); } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { classification.commitRemove(type); } public String getAnnotation(String key) { if ( annotations == null) { return null; } return annotations.get(key); } public String getAnnotation(String key, String defaultValue) { String annotation = getAnnotation( key ); return annotation != null ? annotation : defaultValue; } public void setAnnotation(String key,String annotation) throws IllegalAnnotationException { checkWritable(); if ( annotations == null) { annotations = new LinkedHashMap<String, String>(1); } if (annotation == null) { annotations.remove(key); return; } annotations.put(key,annotation); } public String[] getAnnotationKeys() { if ( annotations == null) { return RaplaObject.EMPTY_STRING_ARRAY; } return annotations.keySet().toArray(RaplaObject.EMPTY_STRING_ARRAY); } public Allocatable clone() { AllocatableImpl clone = new AllocatableImpl(); super.deepClone(clone); clone.permissionArrayUpToDate = false; clone.classification = classification.clone(); clone.permissions.clear(); Iterator<PermissionImpl> it = permissions.iterator(); while ( it.hasNext() ) { clone.permissions.add(it.next().clone()); } clone.createDate = createDate; clone.lastChanged = lastChanged; @SuppressWarnings("unchecked") Map<String,String> annotationClone = (Map<String, String>) (annotations != null ? ((HashMap<String,String>)(annotations)).clone() : null); clone.annotations = annotationClone; return clone; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(getRaplaType().getLocalName()); buf.append(" ["); buf.append(super.toString()); buf.append("] "); try { if ( getClassification() != null) { buf.append (getClassification().toString()) ; } } catch ( NullPointerException ex) { } return buf.toString(); } public int compareTo(Allocatable o) { return super.compareTo(o); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain.internal; import java.util.Date; import java.util.Locale; import org.rapla.components.util.DateTools; import org.rapla.entities.RaplaType; import org.rapla.entities.domain.Period; public class PeriodImpl implements Period { private final static long WEEK_MILLIS= DateTools.MILLISECONDS_PER_WEEK; String name; Date start; Date end; public PeriodImpl() { } public PeriodImpl(String name,Date start, Date end) { this.name = name; this.start = start; this.end = end; } final public RaplaType<Period> getRaplaType() {return TYPE;} public Date getStart() { return start; } public Date getEnd() { return end; } public int getWeeks() { if ( end == null || start == null) { return -1; } long diff= end.getTime()-start.getTime(); return (int)(((diff-1)/WEEK_MILLIS )+ 1); } public String getName(Locale locale) { return name; } public String getName() { return name; } public boolean contains(Date date) { return ((end == null || date.before(end))&& (start == null || !date.before(start))); } public String toString() { return getName() + " " + getStart() + " - " + getEnd(); } public int compareTo_(Date date) { int result = getEnd().compareTo(date); if (result == 0) return 1; else return result; } public int compareTo(Period period) { int result = getStart().compareTo(period.getStart()); if (result != 0) return result; if (equals(period)) return 0; return (hashCode() < period.hashCode()) ? -1 : 1; } public PeriodImpl clone() { return new PeriodImpl(name, start, end); } public void setStart(Date start) { this.start = start; } public void setEnd(Date end) { this.end = end; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain.internal; import java.util.Arrays; import java.util.Date; import java.util.Set; import java.util.TreeSet; import org.rapla.components.util.Assert; import org.rapla.components.util.DateTools; import org.rapla.components.util.DateTools.DateWithoutTimezone; import org.rapla.entities.ReadOnlyException; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.RepeatingType; final class RepeatingImpl implements Repeating,java.io.Serializable { // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; private boolean readOnly = false; private int interval = 1; private boolean isFixedNumber; private int number = -1; private Date end; private RepeatingType repeatingType; private Set<Date> exceptions; transient private Date[] exceptionArray; transient private boolean arrayUpToDate = false; transient private Appointment appointment; private int frequency; boolean monthly; boolean yearly; RepeatingImpl() { if ( repeatingType != null) { setType( repeatingType); } } RepeatingImpl(RepeatingType type,Appointment appointment) { setType(type); setAppointment(appointment); setNumber( 1) ; } public void setType(RepeatingType repeatingType) { if ( repeatingType == null ) { throw new IllegalStateException("Repeating type cannot be null"); } checkWritable(); this.repeatingType = repeatingType; monthly = false; yearly = false; if (repeatingType.equals( RepeatingType.WEEKLY )) { frequency = 7 ; } else if (repeatingType.equals( RepeatingType.MONTHLY)) { frequency = 7; monthly = true; } else if (repeatingType.equals( RepeatingType.DAILY)) { frequency = 1; } else if (repeatingType.equals( RepeatingType.YEARLY)) { frequency = 1; yearly = true; } else { throw new UnsupportedOperationException(" repeatingType " + repeatingType + " not supported"); } } public RepeatingType getType() { return repeatingType; } void setAppointment(Appointment appointment) { this.appointment = appointment; } public void setReadOnly() { this.readOnly = true; } public boolean isReadOnly() { return readOnly; } public void checkWritable() { if ( readOnly ) throw new ReadOnlyException( this ); } public Appointment getAppointment() { return appointment; } public void setInterval(int interval) { checkWritable(); if (interval<1) interval = 1; this.interval = interval; } public int getInterval() { return interval; } public boolean isFixedNumber() { return isFixedNumber; } public boolean isWeekly() { return RepeatingType.WEEKLY.equals( getType()); } public boolean isDaily() { return RepeatingType.DAILY.equals( getType()); } public boolean isMonthly() { return monthly; } public boolean isYearly() { return yearly; } public void setEnd(Date end) { checkWritable(); isFixedNumber = false; number = -1; this.end = end; } transient Date endTime; public Date getEnd() { if (!isFixedNumber) return end; if ( this.appointment == null) return null; if (endTime == null) endTime = new Date(); if ( number < 0 ) { return null; } if ( number == 0 ) { return getAppointment().getStart(); } if ( !isFixedIntervalLength()) { int counts = ((number -1) * interval) ; Date appointmentStart = appointment.getStart(); Date newDate = appointmentStart; for ( int i=0;i< counts;i++) { long newTime; if ( monthly) { newTime = gotoNextMonth( appointmentStart,newDate); } else { newTime = gotoNextYear( appointmentStart,newDate); } newDate = new Date( newTime); } return newDate; } else { long intervalLength = getFixedIntervalLength(); endTime.setTime(DateTools.fillDate( this.appointment.getStart().getTime() + (this.number -1)* intervalLength )); } return endTime; } /** returns interval-length in milliseconds. @see #getInterval */ public long getFixedIntervalLength() { long intervalDays = frequency * interval; return intervalDays * DateTools.MILLISECONDS_PER_DAY; } public void setNumber(int number) { checkWritable(); if (number>-1) { isFixedNumber = true; this.number = Math.max(number,1); } else { isFixedNumber = false; this.number = -1; setEnd(null); } } public boolean isException(long time) { if (!hasExceptions()) return false; Date[] exceptions = getExceptions(); if (exceptions.length == 0) { // System.out.println("no exceptions"); return false; } for (int i=0;i<exceptions.length;i++) { //System.out.println("Comparing exception " + exceptions[i] + " with " + new Date(time)); if (exceptions[i].getTime()<=time && time<exceptions[i].getTime() + DateTools.MILLISECONDS_PER_DAY) { //System.out.println("Exception matched " + exceptions[i]); return true; } } return false; } public int getNumber() { if (number>-1) return number; if (end==null) return -1; // System.out.println("End " + end.getTime() + " Start " + appointment.getStart().getTime() + " Duration " + duration); if ( isFixedIntervalLength() ) { long duration = end.getTime() - DateTools.fillDate(appointment.getStart().getTime()); if (duration<0) return 0; long intervalLength = getFixedIntervalLength(); return (int) ((duration/ intervalLength) + 1); } else { Date appointmentStart = appointment.getStart(); int number = 0; Date newDate = appointmentStart; do { number ++; long newTime; if ( monthly) { newTime = gotoNextMonth( appointmentStart,newDate); } else { newTime = gotoNextYear( appointmentStart, newDate); } newDate = new Date( newTime); } while ( newDate.before( end)); return number; } } public void addException(Date date) { checkWritable(); if ( date == null) { return; } if (exceptions == null) exceptions = new TreeSet<Date>(); exceptions.add(DateTools.cutDate(date)); arrayUpToDate = false; } public void removeException(Date date) { checkWritable(); if (exceptions == null) return; if ( date == null) { return; } exceptions.remove(DateTools.cutDate(date)); if (exceptions.size()==0) exceptions = null; arrayUpToDate = false; } public void clearExceptions() { if (exceptions == null) return; exceptions.clear(); exceptions = null; arrayUpToDate = false; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("Repeating type="); buf.append(repeatingType); buf.append(" interval="); buf.append(interval); if (isFixedNumber()) { buf.append(" number="); buf.append(number); } else { if (end != null) { buf.append(" end-date="); buf.append(AppointmentImpl.fe(end.getTime())); } } if ( exceptions != null && exceptions.size()>0) { buf.append(" exceptions="); boolean first = true; for (Date exception:exceptions) { if (!first) { buf.append(", "); } else { first = false; } buf.append(exception); } } return buf.toString(); } public Object clone() { RepeatingImpl dest = new RepeatingImpl(repeatingType,appointment); RepeatingImpl source = this; copy(source, dest); dest.appointment = appointment; dest.readOnly = false;// clones are always writable return dest; } private void copy(RepeatingImpl source, RepeatingImpl dest) { dest.monthly = source.monthly; dest.yearly = source.yearly; dest.interval = source.interval; dest.isFixedNumber = source.isFixedNumber; dest.number = source.number; dest.end = source.end; dest.interval = source.interval; if (source.exceptions != null) { dest.exceptions = new TreeSet<Date>(); dest.exceptions.addAll(source.exceptions); } else { dest.exceptions = null; } } public void setFrom(Repeating repeating) { checkWritable(); RepeatingImpl dest = this; dest.setType(repeating.getType()); RepeatingImpl source = (RepeatingImpl)repeating; copy( source, dest); } private static Date[] DATE_ARRAY = new Date[0]; public Date[] getExceptions() { if (!arrayUpToDate) { if (exceptions != null) { exceptionArray = exceptions.toArray(DATE_ARRAY); Arrays.sort(exceptionArray); } else exceptionArray = DATE_ARRAY; arrayUpToDate = true; } return exceptionArray; } public boolean hasExceptions() { return exceptions != null && exceptions.size()>0; } final public long getIntervalLength( long s ) { if ( isFixedIntervalLength()) { return getFixedIntervalLength(); } Date appointmentStart = appointment.getStart(); Date startDate = new Date(s); long newTime; if ( monthly) { newTime = gotoNextMonth( appointmentStart,startDate); } else { newTime = gotoNextYear( appointmentStart,startDate); } // Date newDate = cal.getTime(); // long newTime = newDate.getTime(); Assert.isTrue( newTime > s ); return newTime- s; // yearly } private long gotoNextMonth( Date start,Date beginDate ) { int dayofweekinmonth = DateTools.getDayOfWeekInMonth( start); Date newDate = DateTools.addWeeks( beginDate, 4); while ( DateTools.getDayOfWeekInMonth( newDate) != dayofweekinmonth ) { newDate = DateTools.addWeeks( newDate, 1); } return newDate.getTime(); } private long gotoNextYear( Date start,Date beginDate ) { DateWithoutTimezone dateObj = DateTools.toDate( start.getTime()); int dayOfMonth = dateObj.day; int month = dateObj.month; int yearAdd = 1; if ( month == 2 && dayOfMonth ==29) { int startYear = DateTools.toDate( beginDate.getTime()).year; while (!DateTools.isLeapYear( startYear + yearAdd )) { yearAdd++; } } Date newDate = DateTools.addYears( beginDate, yearAdd); return newDate.getTime(); // cal.setTime( start); // int dayOfMonth = cal.get( Calendar.DAY_OF_MONTH); // int month = cal.get( Calendar.MONTH); // cal.setTime( beginDate); // cal.add( Calendar.YEAR,1); // while ( cal.get( Calendar.DAY_OF_MONTH) != dayOfMonth) // { // cal.add( Calendar.YEAR,1); // cal.set( Calendar.MONTH, month); // cal.set( Calendar.DAY_OF_MONTH, dayOfMonth); // } } final public boolean isFixedIntervalLength() { return !monthly &&!yearly; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, of which license fullfill the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain.internal; /** The default Implementation of the <code>Reservation</code> * @see ModificationEvent * @see org.rapla.facade.ClientFacade */ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.rapla.components.util.Assert; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.entities.Entity; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.entities.dynamictype.internal.ClassificationImpl; import org.rapla.entities.internal.ModifiableTimestamp; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.ParentEntity; import org.rapla.entities.storage.UnresolvableReferenceExcpetion; import org.rapla.entities.storage.internal.SimpleEntity; public final class ReservationImpl extends SimpleEntity implements Reservation, ModifiableTimestamp, DynamicTypeDependant, ParentEntity { private ClassificationImpl classification; private List<AppointmentImpl> appointments = new ArrayList<AppointmentImpl>(1); private Map<String,List<String>> restrictions; private Map<String,String> annotations; private Date lastChanged; private Date createDate; transient HashMap<String,AppointmentImpl> appointmentIndex; public static final String PERMISSION_READ = "permission_read"; public static final String PERMISSION_MODIFY = "permission_modify"; // this is only used when you add a resource that is not yet stored, so the resolver won't find it transient Map<String,AllocatableImpl> nonpersistantAllocatables; ReservationImpl() { this (null, null); } public ReservationImpl( Date createDate, Date lastChanged ) { this.createDate = createDate; if (createDate == null) this.createDate = new Date(); this.lastChanged = lastChanged; if (lastChanged == null) this.lastChanged = this.createDate; } public void setResolver( EntityResolver resolver) { super.setResolver( resolver); for (AppointmentImpl child:appointments) { child.setParent( this); } if ( classification != null) { classification.setResolver( resolver); } } public void addEntity(Entity entity) { checkWritable(); AppointmentImpl app = (AppointmentImpl) entity; app.setParent(this); appointments.add( app); appointmentIndex = null; } public void setReadOnly() { super.setReadOnly( ); classification.setReadOnly( ); } final public RaplaType<Reservation> getRaplaType() {return TYPE;} // Implementation of interface classifiable public Classification getClassification() { return classification; } public void setClassification(Classification classification) { checkWritable(); this.classification = (ClassificationImpl) classification; } public String getName(Locale locale) { Classification c = getClassification(); if (c == null) return ""; return c.getName(locale); } public Date getLastChanged() { return lastChanged; } public Date getLastChangeTime() { return lastChanged; } public Date getCreateTime() { return createDate; } public void setLastChanged(Date date) { checkWritable(); lastChanged = date; } public void setCreateDate(Date createDate) { checkWritable(); this.createDate = createDate; } public Appointment[] getAppointments() { return appointments.toArray(Appointment.EMPTY_ARRAY); } public Collection<AppointmentImpl> getAppointmentList() { return appointments; } @SuppressWarnings("unchecked") public Collection<AppointmentImpl> getSubEntities() { return appointments; } @Override public Iterable<ReferenceInfo> getReferenceInfo() { return new IteratorChain<ReferenceInfo> ( super.getReferenceInfo() ,classification.getReferenceInfo() ); } @Override protected Class<? extends Entity> getInfoClass(String key) { Class<? extends Entity> result = super.getInfoClass(key); if ( result == null) { if ( key.equals("resources")) { return Allocatable.class; } } return result; } public void removeAllSubentities() { appointments.clear(); } public void addAppointment(Appointment appointment) { if (appointment.getReservation() != null && !this.isIdentical(appointment.getReservation())) throw new IllegalStateException("Appointment '" + appointment + "' belongs to another reservation :" + appointment.getReservation()); this.addEntity(appointment); } public void removeAppointment(Appointment appointment) { checkWritable(); appointments.remove( appointment ); // Remove allocatable if its restricted to the appointment String appointmentId = appointment.getId(); // we clone the list so we can safely remove a refererence it while traversing Collection<String> ids = new ArrayList<String>(getIds("resources")); for (String allocatableId:ids) { List<String> restriction = getRestrictionPrivate(allocatableId); if (restriction.size() == 1 && restriction.get(0).equals(appointmentId)) { removeId(allocatableId); } } clearRestrictions(appointment); if (this.equals(appointment.getReservation())) ((AppointmentImpl) appointment).setParent(null); appointmentIndex = null; } private void clearRestrictions(Appointment appointment) { if (restrictions == null) return; ArrayList<String> list = null; for (String key:restrictions.keySet()) { List<String> appointments = restrictions.get(key); if ( appointments.size()>0) { if (list == null) list = new ArrayList<String>(); list.add(key); } } if (list == null) return; for (String key: list) { ArrayList<String> newApps = new ArrayList<String>(); for ( String appId:restrictions.get(key)) { if ( !appId.equals( appointment.getId() ) ) { newApps.add( appId ); } } setRestrictionForId( key, newApps); } } public void addAllocatable(Allocatable allocatable) { checkWritable(); if ( hasAllocated( allocatable)) { return; } addAllocatablePrivate(allocatable.getId()); if ( !allocatable.isReadOnly()) { if ( nonpersistantAllocatables == null) { nonpersistantAllocatables = new LinkedHashMap<String,AllocatableImpl>(); } nonpersistantAllocatables.put( allocatable.getId(), (AllocatableImpl) allocatable); } } private void addAllocatablePrivate(String allocatableId) { synchronized (this) { addId("resources",allocatableId); } } public void removeAllocatable(Allocatable allocatable) { checkWritable(); removeId(allocatable.getId()); } public Allocatable[] getAllocatables() { Collection<Allocatable> allocatables = getAllocatables(null); return allocatables.toArray(new Allocatable[allocatables.size()]); } public Allocatable[] getResources() { Collection<Allocatable> allocatables = getAllocatables(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE); return allocatables.toArray(new Allocatable[allocatables.size()]); } public Allocatable[] getPersons() { Collection<Allocatable> allocatables = getAllocatables(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON); return allocatables.toArray(new Allocatable[allocatables.size()]); } @Override protected <T extends Entity> T tryResolve(String id,Class<T> entityClass) { T entity = super.tryResolve(id, entityClass); if ( entity == null && nonpersistantAllocatables != null) { AllocatableImpl allocatableImpl = nonpersistantAllocatables.get( id); @SuppressWarnings("unchecked") T casted = (T) allocatableImpl; entity = casted; } return entity; } public Collection<Allocatable> getAllocatables(String annotationType) { Collection<Allocatable> allocatableList = new ArrayList<Allocatable>(); Collection<Allocatable> list = getList("resources", Allocatable.class); for (Allocatable alloc: list) { if ( annotationType != null) { boolean person = alloc.isPerson(); if (annotationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON) ) { if (!person) { continue; } } else { if (person) { continue; } } } else { } allocatableList.add(alloc); } return allocatableList; } public boolean hasAllocated(Allocatable allocatable) { return isRefering("resources",allocatable.getId()); } public boolean hasAllocated(Allocatable allocatable,Appointment appointment) { if (!hasAllocated(allocatable)) return false; if (restrictions == null) { return true; } List<String> r = this.restrictions.get(allocatable.getId()); String appointmentId = appointment.getId(); if ( r == null || r.size() == 0 || r.contains( appointmentId)) { return true; } return false; } public void setRestriction(Allocatable allocatable,Appointment[] appointments) { checkWritable(); List<String> appointmentIds = new ArrayList<String>(); for ( Appointment app:appointments) { appointmentIds.add( app.getId()); } setRestrictionPrivate(allocatable, appointmentIds); } public Appointment[] getRestriction(Allocatable allocatable) { List<String> restrictionPrivate = getRestrictionPrivate(allocatable.getId()); Appointment[] list = new Appointment[restrictionPrivate.size()]; int i=0; updateIndex(); for (String id:restrictionPrivate) { list[i++] = appointmentIndex.get( id ); } return list; } private void updateIndex() { if (appointmentIndex == null) { appointmentIndex = new HashMap<String,AppointmentImpl>(); for (AppointmentImpl app: appointments) { appointmentIndex.put( app.getId(), app); } } } protected void setRestrictionPrivate(Allocatable allocatable,List<String> appointmentIds) { String id = allocatable.getId(); if ( !hasAllocated( allocatable)) { addAllocatable( allocatable); } Assert.notNull(id,"Allocatable object has no ID"); setRestrictionForId(id,appointmentIds); } public void setRestriction(Appointment appointment, Allocatable[] restrictedAllocatables) { for ( Allocatable alloc: restrictedAllocatables) { List<String> restrictions = new ArrayList<String>(); String allocatableId = alloc.getId(); if ( !hasAllocated( alloc)) { addAllocatable( alloc); } else { restrictions.addAll(getRestrictionPrivate(allocatableId) ); } String appointmentId = appointment.getId(); if ( !restrictions.contains(appointmentId)) { restrictions.add( appointmentId); } String id = allocatableId; setRestrictionForId( id, restrictions); } } public void setRestrictionForId(String id,List<String> appointmentIds) { if (restrictions == null) { restrictions = new HashMap<String,List<String>>(1); } if (appointmentIds == null || appointmentIds.size() == 0) { restrictions.remove(id); } else { restrictions.put(id, appointmentIds); } } public void addRestrictionForId(String id,String appointmentId) { if (restrictions == null) restrictions = new HashMap<String,List<String>>(1); List<String> appointments = restrictions.get( id ); if ( appointments == null) { appointments = new ArrayList<String>(); restrictions.put(id , appointments); } appointments.add(appointmentId); } public List<String> getRestrictionPrivate(String allocatableId) { Assert.notNull(allocatableId,"Allocatable object has no ID"); if (restrictions != null) { List<String> restriction = restrictions.get(allocatableId); if (restriction != null) { return restriction; } } return Collections.emptyList(); } public Appointment[] getAppointmentsFor(Allocatable allocatable) { Appointment[] restrictedAppointments = getRestriction( allocatable); if ( restrictedAppointments.length == 0) return getAppointments(); else return restrictedAppointments; } public Allocatable[] getRestrictedAllocatables(Appointment appointment) { HashSet<Allocatable> set = new HashSet<Allocatable>(); for (String allocatableId: getIds("resources")) { for (String restriction:getRestrictionPrivate( allocatableId )) { if ( restriction.equals( appointment.getId() ) ) { Allocatable alloc = getResolver().tryResolve( allocatableId, Allocatable.class); if ( alloc == null) { throw new UnresolvableReferenceExcpetion( allocatableId, toString()); } set.add( alloc ); } } } return set.toArray( Allocatable.ALLOCATABLE_ARRAY); } public Allocatable[] getAllocatablesFor(Appointment appointment) { HashSet<Allocatable> set = new HashSet<Allocatable>(); Collection<String> list = getIds("resources"); String id = appointment.getId(); for (String allocatableId:list) { boolean found = false; List<String> restriction = getRestrictionPrivate( allocatableId ); if ( restriction.size() == 0) { found = true; } else { for (String rest:restriction) { if ( rest.equals( id ) ) { found = true; } } } if (found ) { Allocatable alloc = getResolver().tryResolve( allocatableId, Allocatable.class); if ( alloc == null) { throw new UnresolvableReferenceExcpetion( Allocatable.class.getName() + ":" + allocatableId, toString()); } set.add( alloc); } } return set.toArray( Allocatable.ALLOCATABLE_ARRAY); } public Appointment findAppointment(Appointment copy) { updateIndex(); String id = copy.getId(); return (Appointment) appointmentIndex.get( id); } public boolean needsChange(DynamicType type) { return classification.needsChange( type ); } public void commitChange(DynamicType type) { classification.commitChange( type ); } public ReservationImpl clone() { ReservationImpl clone = new ReservationImpl(); super.deepClone(clone); // First we must invalidate the arrays. clone.classification = (ClassificationImpl) classification.clone(); for (String resourceId:getIds("resources")) { if ( restrictions != null) { if ( clone.restrictions == null) { clone.restrictions = new LinkedHashMap<String,List<String>>(); } List<String> list = restrictions.get( resourceId); if ( list != null) { clone.restrictions.put( resourceId, new ArrayList<String>(list)); } } } clone.createDate = createDate; clone.lastChanged = lastChanged; @SuppressWarnings("unchecked") Map<String,String> annotationClone = (Map<String, String>) (annotations != null ? ((HashMap<String,String>)(annotations)).clone() : null); clone.annotations = annotationClone; return clone; } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { classification.commitRemove(type); } public Date getFirstDate() { Appointment[] apps = getAppointments(); Date minimumDate = null; for (int i=0;i< apps.length;i++) { Appointment app = apps[i]; if ( minimumDate == null || app.getStart().before( minimumDate)) { minimumDate = app.getStart(); } } return minimumDate; } public Date getMaxEnd() { Appointment[] apps = getAppointments(); Date maximumDate = getFirstDate(); for (int i=0;i< apps.length;i++) { if ( maximumDate == null) { break; } Appointment app = apps[i]; Date maxEnd = app.getMaxEnd(); if ( maxEnd == null || maxEnd.after( maximumDate)) { maximumDate = maxEnd; } } return maximumDate; } public String getAnnotation(String key) { if ( annotations == null) { return null; } return annotations.get(key); } public String getAnnotation(String key, String defaultValue) { String annotation = getAnnotation( key ); return annotation != null ? annotation : defaultValue; } public void setAnnotation(String key,String annotation) throws IllegalAnnotationException { checkWritable(); if ( annotations == null) { annotations = new LinkedHashMap<String, String>(1); } if (annotation == null) { annotations.remove(key); return; } annotations.put(key,annotation); } public String[] getAnnotationKeys() { if ( annotations == null) { return RaplaObject.EMPTY_STRING_ARRAY; } return annotations.keySet().toArray(RaplaObject.EMPTY_STRING_ARRAY); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(getRaplaType().getLocalName()); buf.append(" ["); buf.append(super.toString()); buf.append("] "); try { if ( getClassification() != null) { buf.append (getClassification().toString()) ; } } catch ( NullPointerException ex) { } return buf.toString(); } }
Java
package org.rapla.entities.domain; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class Template implements Comparable<Template> { private String name; private List<Reservation> reservations = new ArrayList<Reservation>(); public Template(String name) { this.name = name; } public String getName() { return name; } public String toString() { return name; } public Collection<Reservation> getReservations() { return reservations; } public void add(Reservation r) { reservations.add( r); } public int compareTo(Template o) { return name.compareTo(o.name); } public boolean equals(Object obj) { if ( !(obj instanceof Template)) { return false; } return name.equals(((Template)obj).name); } public int hashCode() { return name.hashCode(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain; import java.util.Date; import org.rapla.entities.Named; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; /** Most universities and schools are planning for fixed periods/terms rather than arbitrary dates. Rapla provides support for this periods. */ public interface Period extends RaplaObject<Period>,Comparable<Period>,Named { final RaplaType<Period> TYPE = new RaplaType<Period>(Period.class, "period"); Date getStart(); Date getEnd(); int getWeeks(); String getName(); boolean contains(Date date); String toString(); public static Period[] PERIOD_ARRAY = new Period[0]; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain; import java.util.Date; import org.rapla.components.util.TimeInterval; import org.rapla.entities.Annotatable; import org.rapla.entities.Entity; import org.rapla.entities.Named; import org.rapla.entities.Ownable; import org.rapla.entities.RaplaType; import org.rapla.entities.Timestamp; import org.rapla.entities.User; import org.rapla.entities.dynamictype.Classifiable; /** Objects that implement allocatable can be allocated by reservations. @see Reservation */ public interface Allocatable extends Entity<Allocatable>,Named,Classifiable,Ownable,Timestamp, Annotatable { final RaplaType<Allocatable> TYPE = new RaplaType<Allocatable>(Allocatable.class, "resource"); /** Conflicts for this allocatable should be ignored, if this flag is enabled. * @deprecated use getAnnotation(IGNORE_CONFLICTS) instead*/ @Deprecated boolean isHoldBackConflicts(); /** Static empty dummy Array. Mainly for using the toArray() method of the collection interface */ Allocatable[] ALLOCATABLE_ARRAY = new Allocatable[0]; // adds a permission. Permissions are stored in a hashset so the same permission can't be added twice void addPermission( Permission permission ); boolean removePermission( Permission permission ); /** returns if the user has the permission to allocate the resource in the given time. It returns <code>true</code> if for at least one permission calling <code>permission.covers()</code> and <code>permission.affectsUser</code> yields <code>true</code>. */ boolean canAllocate( User user, Date start, Date end, Date today ); /** returns if the user has the permission to allocate the resource in at a time in the future without specifying the exact time */ boolean canAllocate(User user, Date today); /** returns the interval in which the user can allocate the resource. Returns null if the user can't allocate the resource */ TimeInterval getAllocateInterval( User user, Date today); /** returns if the user has the permission to create a conflict for the resource.*/ boolean canCreateConflicts( User user ); /** returns if the user has the permission to modify the allocatable (and also its permission-table).*/ boolean canModify( User user ); /** returns if the user has the permission to read the information and the allocations of this resource.*/ boolean canRead( User user ); /** returns if the user has the permission to read only the information but not the allocations of this resource.*/ boolean canReadOnlyInformation( User user ); Permission[] getPermissions(); Permission newPermission(); boolean isPerson(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain; import java.util.Date; /** Encapsulates the repeating rule for an appointment. @see Appointment*/ public interface Repeating { RepeatingType DAILY = RepeatingType.DAILY; RepeatingType WEEKLY = RepeatingType.WEEKLY; RepeatingType MONTHLY = RepeatingType.MONTHLY; RepeatingType YEARLY = RepeatingType.YEARLY; void setInterval(int interval); /** returns the number of intervals between two repeatings. * That are in the selected context: * <li>For weekly repeatings: Number of weeks.</li> * <li>For dayly repeatings: Number of days.</li> */ int getInterval(); /** The value returned depends which method was called last. * If <code>setNumber()</code> has been called with a parameter * &gt;=0 <code>fixedNumber()</code> will return true. If * <code>setEnd()</code> has been called * <code>fixedNumber()</code> will return false. * @see #setEnd * @see #setNumber */ boolean isFixedNumber(); /** Set the end of repeating. * If this value is set to null and the * number is set to -1 the appointment will repeat * forever. * @param end If not null isFixedNumber will return true. * @see #setNumber */ void setEnd(Date end); /* @return end of repeating or null if unlimited */ Date getEnd(); /** Set a fixed number of repeating. * If this value is set to -1 * and the repeating end is set to null the appointment will * repeat forever. * @param number If &gt;=0 isFixedNumber will return true. * @see #setEnd * @see #isFixedNumber */ void setNumber(int number); /* @return number of repeating or -1 if it repeats forever. */ int getNumber(); /* daily,weekly, monthly */ RepeatingType getType(); /* daily,weekly, monthly */ void setType(RepeatingType type); /* exceptions for this repeating. */ Date[] getExceptions(); boolean hasExceptions(); boolean isWeekly(); boolean isDaily(); boolean isMonthly(); boolean isYearly(); void addException(Date date); void removeException(Date date); void clearExceptions(); /** returns the appointment of this repeating. @see Appointment */ Appointment getAppointment(); /** copy the values from another repeating */ void setFrom(Repeating repeating); /** tests if an exception is added for the given date */ boolean isException(long date); Object clone(); }
Java
package org.rapla.entities.domain; import java.util.Comparator; public class AppointmentBlockStartComparator implements Comparator<AppointmentBlock> { /** * This method is used to compare two appointment blocks by their start dates */ public int compare(AppointmentBlock a1, AppointmentBlock a2) { // Otherwise the comparison between two appointment blocks is needed if ( a1 == a2) { return 0; } // a1 before a2 if (a1.getStart() <a2.getStart()) return -1; // a1 after a2< if (a1.getStart() > a2.getStart()) return 1; // a1 before a2 if (a1.getEnd() < a2.getEnd()) return -1; // a1 after a2 if (a1.getEnd() > a2.getEnd()) return 1; // If a1 and a2 have equal start and end dates, sort by hash code return (a1.hashCode() < a2.hashCode()) ? -1 : 1; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /**Currently Rapla supports the following types: <li>weekly</li> <li>daily</li> */ public class RepeatingEnding implements Serializable { // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; private String type; final static public RepeatingEnding END_DATE = new RepeatingEnding("repeating.end_date"); final static public RepeatingEnding N_TIMES = new RepeatingEnding("repeating.n_times"); final static public RepeatingEnding FOREVEVER = new RepeatingEnding("repeating.forever"); private static Map<String,RepeatingEnding> types; private RepeatingEnding(String type) { this.type = type; if (types == null) { types = new HashMap<String,RepeatingEnding>(); } types.put( type, this); } public boolean is(RepeatingEnding other) { if ( other == null) return false; return type.equals( other.type); } public static RepeatingEnding findForString(String string ) { RepeatingEnding type = types.get( string ); return type; } public String toString() { return type; } public boolean equals( Object other) { if ( !(other instanceof RepeatingEnding)) return false; return is( (RepeatingEnding)other); } public int hashCode() { return type.hashCode(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain; /**Currently Rapla supports the following types: <li>weekly</li> <li>daily</li> */ public enum RepeatingType { WEEKLY("weekly"), DAILY("daily"), MONTHLY("monthly"), YEARLY("yearly"); String type; RepeatingType(String type) { this.type = type; } // public RepeatingType WEEKLY = new RepeatingType("weekly"); // public RepeatingType DAILY = new RepeatingType("daily"); // public RepeatingType MONTHLY = new RepeatingType("monthly"); // public RepeatingType YEARLY = new RepeatingType("yearly"); // public boolean is(RepeatingType other) { if ( other == null) return false; return type.equals( other.type); } public static RepeatingType findForString(String string ) { for (RepeatingType type:values()) { if ( type.type.equals( string)) { return type; } } return null; } public String toString() { return type; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain; import java.util.Collection; import java.util.Date; import org.rapla.components.util.TimeInterval; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.User; /** The basic building blocks of reservations. @see Reservation @see Repeating*/ public interface Appointment extends Entity<Appointment>, Comparable { final RaplaType<Appointment> TYPE = new RaplaType<Appointment>(Appointment.class, "appointment" ); Date getStart(); Date getEnd(); /** <p> If no repeating is set this method will return the same as <code>getEnd()</code>. </p> <p> If the repeating has no end the method will return <strong>Null</strong>. Oterwise the maximum of getEnd() and repeating.getEnd() will be returned. </p> @see #getEnd @see Repeating */ Date getMaxEnd(); User getOwner(); /** returns the reservation that owns the appointment. @return the reservation that owns the appointment or null if the appointment does not belong to a reservation. */ Reservation getReservation(); /** @return null if the appointment has no repeating */ Repeating getRepeating(); /** Enables repeating for this appointment. Use getRepeating() to manipulate the repeating. */ void setRepeatingEnabled(boolean enableRepeating); /** returns if the appointment has a repeating */ boolean isRepeatingEnabled(); /** Changes the start- and end-time of the appointment. */ void move(Date start,Date end); /** Moves the start-time of the appointment. The end-time will be adjusted accordingly to the duration of the appointment. */ void move(Date newStart); /** Tests two appointments for overlap. Important: Times like 13:00-14:00 and 14:00-15:00 do not overlap The overlap-relation must be symmetric <code>a1.overlaps(a2) == a2.overlaps(a1)</code> @return true if the appointment overlaps the given appointment. */ boolean overlaps(Appointment appointment); boolean overlaps(AppointmentBlock block); /** Test for overlap with a period. * same as overlaps( start, end, true) * @return true if the overlaps with the given period. */ boolean overlaps(Date start,Date end); /** Test for overlap with a period. * same as overlaps( start, end, true) * @return true if the overlaps with the given period. */ boolean overlaps(TimeInterval interval); /** Test for overlap with a period. You can specify if exceptions should be considered in the overlapping algorithm. * if excludeExceptions is set an overlap will return false if all dates are excluded by exceptions in the specfied start-end intervall @return true if the overlaps with the given period. */ boolean overlaps(Date start,Date end, boolean excludeExceptions); /** Returns if the exceptions, repeatings, start and end dates of the Appoinemnts are the same.*/ boolean matches(Appointment appointment); /** @param maxDate must not be null, specifies the last date that should be searched returns the first date at which the two appointments differ (dates after maxDate will not be calculated) */ Date getFirstDifference( Appointment a2, Date maxDate ); /** @param maxDate must not be null, specifies the last date that should be searched returns the last date at which the two appointments differ. (dates after maxDate will not be calculated)*/ Date getLastDifference( Appointment a2, Date maxDate ); /** this method will be used for future enhancements */ boolean isWholeDaysSet(); /** this method will be used for future enhancements */ void setWholeDays(boolean enable); /** adds all Appointment-blocks in the given period to the appointmentBlockArray. A block is in the period if its starttime<end or its endtime>start. Exceptions are excluded, i.e. there is no block on an exception date. */ void createBlocks(Date start,Date end,Collection<AppointmentBlock> blocks); /** adds all Appointment-blocks in the given period to the appointmentBlockArray. A block is in the period if its starttime<end or its endtime>start. You can specify if exceptions should be excluded. If this is set no blocks are added on an exception date. */ void createBlocks(Date start,Date end,Collection<AppointmentBlock> blocks, boolean excludeExceptions); final Appointment[] EMPTY_ARRAY = new Appointment[0]; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2011 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain; import java.util.Date; import org.rapla.components.util.DateTools; /** * This class represents a time block of an appointment. * @since Rapla 1.4 */ public class AppointmentBlock implements Comparable<AppointmentBlock> { long start; long end; boolean isException; private Appointment appointment; /** * Basic constructor */ public AppointmentBlock(long start, long end, Appointment appointment, boolean isException) { this.start = start; this.end = end; this.appointment = appointment; this.isException = isException; } public AppointmentBlock(Appointment appointment) { this.start = appointment.getStart().getTime(); this.end = appointment.getEnd().getTime(); this.appointment = appointment; this.isException = false; } public boolean includes(AppointmentBlock a2) { return start <= a2.start && end>= a2.end; } /** * Returns the start date of this block * * @return Date */ public long getStart() { return start; } /** * Returns the end date of this block * * @return Date */ public long getEnd() { return end; } /** * Returns if the block is an exception from the appointment rule * */ public boolean isException() { return isException; } /** * Returns the appointment to which this block belongs * * @return Appointment */ public Appointment getAppointment() { return appointment; } /** * This method is used to compare two appointment blocks by their start dates */ public int compareTo(AppointmentBlock other) { if (other.start > start) return -1; if (other.start < start) return 1; if (other.end > end) return 1; if (other.end < end) return -1; if ( other == this) { return 0; } @SuppressWarnings("unchecked") int compareTo = appointment.compareTo(other.appointment); return compareTo; } public String toString() { return DateTools.formatDateTime(new Date(start)) + " - " + DateTools.formatDateTime(new Date(end)); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.rapla.entities.Category; import org.rapla.entities.User; /** New feature to restrict the access to allocatables on a per user/group basis. * Specify absolute and relative booking-timeframes for each resource * per user/group. You can, for example, prevent modifing appointments * in the past, by setting the relative start-time to 0. */ public interface Permission { String GROUP_CATEGORY_KEY = "user-groups"; String GROUP_REGISTERER_KEY = "registerer"; String GROUP_MODIFY_PREFERENCES_KEY = "modify-preferences"; String GROUP_CAN_READ_EVENTS_FROM_OTHERS = "read-events-from-others"; String GROUP_CAN_CREATE_EVENTS = "create-events"; String GROUP_CAN_EDIT_TEMPLATES = "edit-templates"; int DENIED = 0; int READ_ONLY_INFORMATION = 50; int READ = 100; int ALLOCATE =200; int ALLOCATE_CONFLICTS = 300; int ADMIN = 400; int NO_PERMISSION = -2; int ALL_USER_PERMISSION = -1; int GROUP_PERMISSION = 5000; int USER_PERMISSION = 10000; public static class AccessTable { final LinkedHashMap<Integer,String> map = new LinkedHashMap<Integer,String>(); { map.put( DENIED,"denied"); map.put( READ_ONLY_INFORMATION,"read_no_allocation"); map.put( READ,"read"); map.put( ALLOCATE, "allocate"); map.put( ALLOCATE_CONFLICTS, "allocate-conflicts"); map.put( ADMIN, "admin"); } public String get(int accessLevel) { return map.get(accessLevel); } public Integer findAccessLevel(String accessLevelName) { for (Map.Entry<Integer, String> entry: map.entrySet()) { if (entry.getValue().equals( accessLevelName)) { return entry.getKey(); } } return null; } public Set<Integer> keySet() { return map.keySet(); } } AccessTable ACCESS_LEVEL_NAMEMAP = new AccessTable(); /* * static { Arrays. for (int i=0;i<ACCESS_LEVEL_TYPES.length;i++) { ACCESS_LEVEL_NAMEMAP.put( ACCESS_LEVEL_TYPES[i], ACCESS_LEVEL_NAMES[i]); } }; */ /** sets a user for the permission. * If a user is not null, the group will be set to null. */ void setUser(User user); User getUser(); /** sets a group for the permission. * If the group ist not null, the user will be set to null. */ void setGroup(Category category); Category getGroup(); /** set the minumum number of days a resource must be booked in advance. If days is null, a reservation can be booked anytime. * Example: If you set days to 7, a resource must be allocated 7 days before its acutual use */ void setMinAdvance(Integer days); Integer getMinAdvance(); /** set the maximum number of days a reservation can be booked in advance. If days is null, a reservation can be booked anytime. * Example: If you set days to 7, a resource can only be for the next 7 days. */ void setMaxAdvance(Integer days); Integer getMaxAdvance(); /** sets the starttime of the period in which the resource can be booked*/ void setStart(Date end); Date getStart(); /** sets the endtime of the period in which the resource can be booked*/ void setEnd(Date end); Date getEnd(); /** Convenince Method: returns the last date for which the resource can be booked */ Date getMaxAllowed(Date today); /** Convenince Method: returns the first date for which the resource can be booked */ Date getMinAllowed(Date today); /** returns true if one of start, end or maxAllowed, MinAllowed is set*/ boolean hasTimeLimits(); /** returns if the user or a group of the user is affected by the permission. * Groups are hierarchical. If the user belongs * to a subgroup of the permission-group the user is also * affected by the permission. * returns true if the result of getUserEffect is greater than NO_PERMISSION */ boolean affectsUser( User user); /** * * @return NO_PERMISSION if permission does not effect user * @return ALL_USER_PERMISSION if permission affects all users * @return USER_PERMISSION if permission specifies the current user * @return if the permission affects a users group the depth of the permission group category specified */ int getUserEffect(User user); /** returns if the permission covers the interval specified by the start and end date. * The current date must be passed to calculate the permissable * interval from minAdvance and maxAdvance. */ boolean covers( Date start, Date end, Date currentDate); /** Possible values are * DENIED, READ_ONLY_INFORMATION, READ, ALLOCATE, ALLOCATE_CONFLICTS, ADMIN * @param access */ void setAccessLevel(int access); int getAccessLevel(); /** Static empty dummy Array. * Mainly for using the toArray() method of the collection interface */ Permission[] PERMISSION_ARRAY = new Permission[0]; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain; public interface ResourceAnnotations { final String KEY_CONFLICT_CREATION = "conflictCreation"; final String VALUE_CONFLICT_CREATION_IGNORE = "ignore"; }
Java
package org.rapla.entities.domain; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import org.rapla.facade.PeriodModel; public class ReservationHelper { static public void makeRepeatingForPeriod(PeriodModel model, Appointment appointment, RepeatingType repeatingType, int repeatings) { appointment.setRepeatingEnabled(true); Repeating repeating = appointment.getRepeating(); repeating.setType( repeatingType ); Period period = model.getNearestPeriodForStartDate( appointment.getStart()); if ( period != null && repeatings <=1) { repeating.setEnd(period.getEnd()); } else { repeating.setNumber( repeatings ); } } /** find the first visible reservation*/ static public Date findFirst( List<Reservation> reservationList) { Date firstStart = null; Iterator<Reservation> it = reservationList.iterator(); while (it.hasNext()) { Appointment[] appointments = ( it.next()).getAppointments(); for (int i=0;i<appointments.length;i++) { Date start = appointments[i].getStart(); Repeating r = appointments[i].getRepeating(); if (firstStart == null) { firstStart = start; continue; } if (!start.before(firstStart)) continue; if ( r== null || !r.isException(start.getTime())) { firstStart = start; } else { Collection<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>(); appointments[i].createBlocks( start, firstStart, blocks ); for (AppointmentBlock block: blocks) { if (block.getStart()<firstStart.getTime()) { firstStart = new Date(block.getStart()); continue; } } } } } return firstStart; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain; public interface RaplaObjectAnnotations { /** Template Annotation */ final String KEY_TEMPLATE = "template"; final String KEY_TEMPLATE_COPYOF = "copyof"; /** Template externalid annotation */ final String KEY_EXTERNALID = "externalid"; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.domain; import java.util.Date; import org.rapla.entities.Annotatable; import org.rapla.entities.Entity; import org.rapla.entities.Named; import org.rapla.entities.Ownable; import org.rapla.entities.RaplaType; import org.rapla.entities.Timestamp; import org.rapla.entities.dynamictype.Classifiable; /** The <code>Reservation</code> interface is the central interface of * Rapla. Objects implementing this interface are the courses or * events to be scheduled. A <code>Reservation</code> consist * of a group of appointments and a set of allocated * resources (rooms, notebooks, ..) and persons. * By default all resources and persons are allocated on every appointment. * If you want to associate allocatable objects to special appointments * use Restrictions. * * @see Classifiable * @see Appointment * @see Allocatable */ public interface Reservation extends Entity<Reservation>,Classifiable,Named,Ownable,Timestamp, Annotatable { final RaplaType<Reservation> TYPE = new RaplaType<Reservation>(Reservation.class,"reservation"); public final int MAX_RESERVATION_LENGTH = 100; void addAppointment(Appointment appointment); void removeAppointment(Appointment appointment); /** returns all appointments that are part off the reservation.*/ Appointment[] getAppointments(); /** Restrict an allocation to one ore more appointments. * By default all objects of a reservation are allocated * on every appointment. Restrictions allow to model * relations between allocatables and appointments. * A resource or person is restricted if its connected to * one or more appointments instead the whole reservation. */ void setRestriction(Allocatable alloc,Appointment[] appointments); void setRestriction(Appointment appointment, Allocatable[] restrictedAllocatables); Appointment[] getRestriction(Allocatable alloc); /** returns all appointments for an allocatable. This are either the restrictions, if there are any or all appointments * @see #getRestriction * @see #getAppointments*/ Appointment[] getAppointmentsFor(Allocatable alloc); /** find an appointment in the reservation that equals the specified appointment. This is usefull if you have the * persistant version of an appointment and want to discover the editable appointment in the working copy of a reservation. * This does only work with persistant appointments, that have an id.*/ Appointment findAppointment(Appointment appointment); void addAllocatable(Allocatable allocatable); void removeAllocatable(Allocatable allocatable); Allocatable[] getAllocatables(); Allocatable[] getRestrictedAllocatables(Appointment appointment); /** get all allocatables that are allocated on the appointment, restricted and non restricted ones*/ Allocatable[] getAllocatablesFor(Appointment appointment); /** returns if an the reservation has allocated the specified object. */ boolean hasAllocated(Allocatable alloc); /** returns if the allocatable is reserved on the specified appointment. */ boolean hasAllocated(Allocatable alloc,Appointment appointment); /** returns all persons that are associated with the reservation. Need not necessarily to be users of the System. */ Allocatable[] getPersons(); /** returns all resources that are associated with the reservation. */ Allocatable[] getResources(); public static final Reservation[] RESERVATION_ARRAY = new Reservation[0]; /** returns the first (in time) start of all appointments. Returns null when the reservation has no appointments*/ Date getFirstDate(); /** returns the last (in time) maxEnd of all appointments. Returns null when one appointment has no end*/ Date getMaxEnd(); }
Java
package org.rapla.entities.domain; import java.util.Comparator; public class AppointmentBlockEndComparator implements Comparator<AppointmentBlock> { /** * This method is used to compare two appointment blocks by their start dates */ public int compare(AppointmentBlock a1, AppointmentBlock a2) { // Otherwise the comparison between two appointment blocks is needed if ( a1 == a2) { return 0; } // a1 before a2 if (a1.getEnd() < a2.getEnd()) return -1; // a1 after a2 if (a1.getEnd() > a2.getEnd()) return 1; // a1 before a2 if (a1.getStart() <a2.getStart()) return -1; // a1 after a2< if (a1.getStart() > a2.getStart()) return 1; // If a1 and a2 have equal start and end dates, sort by hash code return (a1.hashCode() < a2.hashCode()) ? -1 : 1; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.storage.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.rapla.entities.Entity; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.UnresolvableReferenceExcpetion; /** The ReferenceHandler takes care of serializing and deserializing references to Entity objects. <p> The references will be serialized to the ids of the corresponding entity. Deserialization of the ids takes place in the contextualize method. You need to provide an EntityResolver on the Context. </p> <p> The ReferenceHandler support both named and unnamed References. Use the latter one, if you don't need to refer to the particular reference by name and if you want to keep the order of the references. <pre> // put a named reference referenceHandler.put("owner",user); // put unnamed reference Iterator it = resources.iterator(); while (it.hasNext()) referenceHandler.add(it.next()); // returns User referencedUser = referenceHandler.get("owner"); // returns both the owner and the resources Itertor references = referenceHandler.getReferences(); </pre> </p> @see EntityResolver */ abstract public class ReferenceHandler /*extends HashMap<String,List<String>>*/ implements EntityReferencer { protected Map<String,List<String>> links = new LinkedHashMap<String,List<String>>(); protected transient EntityResolver resolver; public EntityResolver getResolver() { return resolver; } public ReferenceHandler() { } public Map<String,?> getLinkMap() { return links; } /** * @see org.rapla.entities.storage.EntityReferencer#setResolver(org.rapla.entities.storage.EntityResolver) */ public void setResolver(EntityResolver resolver) { if (resolver == null){ throw new IllegalArgumentException("Null not allowed"); } this.resolver = resolver; // try { // for (String key :idmap.keySet()) { // List<String> ids = idmap.get( key); // for (String id: ids) // { // Entity entity = resolver.resolve(id); // } // } // } catch (EntityNotFoundException ex) { // clearReferences(); // throw ex; // } } @Override public Iterable<ReferenceInfo> getReferenceInfo() { Set<ReferenceInfo> result = new HashSet<ReferenceInfo>(); if (links != null) { for (String key:links.keySet()) { List<String> entries = links.get( key); for ( String id: entries) { ReferenceInfo referenceInfo = new ReferenceInfo(id, getInfoClass( key)); result.add( referenceInfo); } } } return result; } abstract protected Class<? extends Entity> getInfoClass(String key); /** Use this method if you want to implement deserialization of the object manualy. * You have to add the reference-ids to other entities immediatly after the constructor. * @throws IllegalStateException if contextualize has been called before. */ public void putId(String key,String id) { putIds( key, Collections.singleton(id)); } public void addId(String key,String id) { synchronized (this) { List<String> idEntries = links.get( key ); if ( idEntries == null ) { idEntries = new ArrayList<String>(); links.put(key, idEntries); } idEntries.add(id); } } public void add(String key, Entity entity) { synchronized (this) { addId( key, entity.getId()); } } public void putIds(String key,Collection<String> ids) { synchronized (this) { if (ids == null || ids.size() == 0) { links.remove(key); return; } List<String> entries = new ArrayList<String>(); for (String id:ids) { entries.add( id); } links.put(key, entries); } } public String getId(String key) { List<String> entries = links.get(key); if ( entries == null || entries.size() == 0) { return null; } String entry = entries.get(0); if (entry == null) return null; return entry; } public Collection<String> getIds(String key) { List<String> entries = links.get(key); if ( entries == null ) { return Collections.emptyList(); } return entries; } public void putEntity(String key,Entity entity) { synchronized (this) { if (entity == null) { links.remove(key); return; } links.put(key, Collections.singletonList(entity.getId()) ); } } public void putList(String key, Collection<Entity>entities) { synchronized (this) { if (entities == null || entities.size() == 0) { links.remove(key); return; } List<String> idEntries = new ArrayList<String>(); for (Entity ent: entities) { String id = ent.getId(); idEntries.add( id); } links.put(key, idEntries); } } public <T extends Entity> Collection<T> getList(String key, Class<T> entityClass) { List<String> ids = links.get(key); if ( ids == null ) { return Collections.emptyList(); } List<T> entries = new ArrayList<T>(ids.size()); for ( String id:ids) { T entity = tryResolve(id, entityClass); if ( entity != null) { entries.add( entity ); } else { throw new UnresolvableReferenceExcpetion( entityClass.getName() + ":" + id, toString() ); } } return entries; } protected <T extends Entity> T tryResolve(String id,Class<T> entityClass) { return resolver.tryResolve( id , entityClass); } // public Entity getEntity(String key) { // // } public <T extends Entity> T getEntity(String key,Class<T> entityClass) { List<String>entries = links.get(key); if ( entries == null || entries.size() == 0) { return null; } String id = entries.get(0); if (id == null) return null; if ( resolver == null) { throw new IllegalStateException("Resolver not set"); } T resolved = tryResolve(id, entityClass); if ( resolved == null) { throw new UnresolvableReferenceExcpetion(entityClass.getName() + ":" + id); } return resolved; } public boolean removeWithKey(String key) { synchronized (this) { if ( links.remove(key) != null ) { return true; } else { return false; } } } public boolean removeId(String id) { boolean removed = false; synchronized (this) { for (String key: links.keySet()) { List<String> entries = links.get(key); if ( entries.contains( id)) { entries.remove( id); removed = true; } } } return removed; } protected boolean isRefering(String key,String id) { List<String> ids = links.get(key); if ( ids == null) { return false; } return ids.contains( id); } public Iterable<String> getReferenceKeys() { return links.keySet(); } public void clearReferences() { links.clear(); } // @SuppressWarnings("unchecked") // public ReferenceHandler clone() { // ReferenceHandler clone; // } public String toString() { StringBuilder builder = new StringBuilder(); for (ReferenceInfo ref: getReferenceInfo()) { builder.append(ref); builder.append(","); } return builder.toString(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.storage.internal; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import org.rapla.components.util.Assert; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.ReadOnlyException; import org.rapla.entities.Timestamp; import org.rapla.entities.User; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.ParentEntity; import org.rapla.entities.storage.RefEntity; /** Base-class for all Rapla Entity-Implementations. Provides services * for deep cloning and serialization of references. {@link ReferenceHandler} */ public abstract class SimpleEntity extends ReferenceHandler implements RefEntity, Comparable { private String id; transient boolean readOnly = false; public SimpleEntity() { } public void checkWritable() { if ( readOnly ) throw new ReadOnlyException( this ); } @Deprecated public boolean isPersistant() { return isReadOnly(); } public void setResolver( EntityResolver resolver) { super.setResolver( resolver); Iterable<Entity>subEntities = getSubEntities(); for (Entity subEntity :subEntities) { ((EntityReferencer)subEntity).setResolver( resolver ); } } public boolean isIdentical(Entity object) { return equals( object); } private Iterable<Entity>getSubEntities() { if (!( this instanceof ParentEntity)) { return Collections.emptyList(); } else { //@SuppressWarnings("unchecked") Iterable<Entity>subEntities = ((ParentEntity)this).getSubEntities(); return subEntities; } } public void setReadOnly() { this.readOnly = true; for (Entity ref:getSubEntities()) { ((SimpleEntity)ref).setReadOnly(); } } public boolean isReadOnly() { return readOnly; } public User getOwner() { return getEntity("owner", User.class); } protected String getOwnerId() { return getId("owner"); } public void setOwner(User owner) { putEntity("owner",owner); } public User getLastChangedBy() { return getEntity("last_changed_by", User.class); } public void setLastChangedBy(User user) { putEntity("last_changed_by",user); } @Override protected Class<? extends Entity> getInfoClass(String key) { if ( key.equals( "owner") || key.equals("last_changed_by")) { return User.class; } return null; } /** sets the identifier for an object. The identifier should be * unique accross all entities (not only accross the entities of a * the same type). Once set, the identifier for an object should * not change. The identifier is necessary to store the relationsships * between enties. * @see SimpleIdentifier */ public void setId(String id) { if ( id != null) { id = id.intern(); } this.id= id; } /** @return the identifier of the object. * @see SimpleIdentifier */ final public String getId() { return id; } /** two Entities are equal if they are identical. * @see #isIdentical */ final public boolean equals(Object o) { if (!( o instanceof Entity)) { return false; } Entity e2 = (Entity) o; String id2 = e2.getId(); if ( id2== null || id == null) return e2 == this; if (id == id2) { return true; } return id.equals(id2); } /** The hashcode of the id-object will be returned. * @return the hashcode of the id. * @throws IllegalStateException if no id is set. */ public int hashCode() { if ( id != null) { return id.hashCode(); } else { throw new IllegalStateException("Id not set. You must set an Id before you can use the hashCode method." ); } } /** find the sub-entity that has the same id as the passed copy. Returns null, if the entity was not found. */ public Entity findEntity(Entity copy) { for (Entity entity:getSubEntities()) { if (entity.equals(copy)) { return entity; } } return null; } /** find the sub-entity that has the same id as the passed copy. Returns null, if the entity was not found. */ public Entity findEntityForId(String id) { for (Entity entity:getSubEntities()) { if (id.equals(entity.getId())) { return entity; } } return null; } protected void deepClone(SimpleEntity clone) { clone.id = id; clone.links = new LinkedHashMap<String,List<String>>(); for ( String key:links.keySet()) { List<String> idList = links.get( key); clone.links.put( key, new ArrayList<String>(idList)); } clone.resolver = this.resolver; Assert.isTrue(!clone.getSubEntities().iterator().hasNext()); ArrayList<Entity>newSubEntities = new ArrayList<Entity>(); Iterable<Entity> oldEntities = getSubEntities(); for (Entity entity: oldEntities) { Entity deepClone = (Entity) entity.clone(); newSubEntities.add( deepClone); } for (Entity entity: newSubEntities) { ((ParentEntity)clone).addEntity( entity ); } } public String toString() { if (id != null) return id.toString(); return "no id for " + super.toString(); } public int compareTo(Object o) { return compare_(this, (SimpleEntity)o); } static public <T extends Entity> void checkResolveResult(String id, Class<T> entityClass, T entity) throws EntityNotFoundException { if ( entity == null) { Serializable serializable = entityClass != null ? entityClass : "Object"; throw new EntityNotFoundException(serializable +" for id [" + id + "] not found for class ", id); } } static private int compare_(SimpleEntity o1,SimpleEntity o2) { if ( o1 == o2) { return 0; } if ( o1.equals( o2)) return 0; // first try to compare the entities with their create time if ( o1 instanceof Timestamp && o2 instanceof Timestamp) { Date c1 = ((Timestamp)o1).getCreateTime(); Date c2 = ((Timestamp)o2).getCreateTime(); if ( c1 != null && c2 != null) { int result = c1.compareTo( c2); if ( result != 0) { return result; } } } String id1 = o1.getId(); String id2 = o2.getId(); if ( id1 == null) { if ( id2 == null) { throw new IllegalStateException("Can't compare two entities without ids"); } else { return -1; } } else if ( id2 == null) { return 1; } return id1.compareTo( id2 ); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.storage; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.dynamictype.DynamicType; /** resolves the id to a proper reference to the object. @see org.rapla.entities.storage.internal.ReferenceHandler */ public interface EntityResolver { public Entity resolve(String id) throws EntityNotFoundException; /** same as resolve but returns null when an entity is not found instead of throwing an {@link EntityNotFoundException} */ public Entity tryResolve(String id); /** now the type safe version */ public <T extends Entity> T tryResolve(String id,Class<T> entityClass); /** now the type safe version */ public <T extends Entity> T resolve(String id,Class<T> entityClass) throws EntityNotFoundException; public DynamicType getDynamicType(String key); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.storage; import java.util.Collection; import org.rapla.entities.Entity; public interface ParentEntity { /** returns all entities that are aggregated under the entity. This information is usefull to transparently store the subentities along with their parent. * The difference between subEntities and other references is, * that the subEntities are aggregated instead of associated. That * means SubEntities should be * <li>stored, when the parent is stored</li> * <li>deleted, when the parent is deleted or when they are * removed from the parent</li> */ <T extends Entity> Collection<T> getSubEntities(); void addEntity(Entity entity); Entity findEntity(Entity copy); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.storage; import org.rapla.entities.dynamictype.DynamicType; /** DynamicTypeDependent needs to be implemented by all classes that would be affected by a change to a dynamic type. * E.g. If you remove or modify an attribute of a dynamic resource type. All resources of this types must take certain actions.*/ public interface DynamicTypeDependant { /** returns true if the object needs to be changed with new dynamic type change and false if no modification of the object is requiered. * Example: If you remove an attribute from a resource type, and one resource of the resourcetype doesnt use this attribute this resource doesnt need modifaction, so it can return false * @param type The new dynamic type * */ public boolean needsChange(DynamicType type); /** process the change in the object *Example: If you remove an attribute from a resource type, you should remove the corresponding attriabute value in all resources of the resourcetype * @param type The new dynamic type*/ public void commitChange(DynamicType type); /** throws a CannotExistWithoutTypeException when type cannot be removed*/ public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.storage; /** The id is the unique key to distinct the entity from all others. It is needed to safely update the entities and their associations (or aggregations) with other entities.<br> <b>Note:</b> Use this interface only in the storage-backend. */ public interface RefEntity extends EntityReferencer { void setId(String id); String getId(); void setReadOnly(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.storage; import org.rapla.entities.Entity; /** transforms ids into references to * the corresponding objects. * @see org.rapla.entities.storage.internal.ReferenceHandler; */ public interface EntityReferencer { void setResolver( EntityResolver resolver); /**Return all References of the object*/ Iterable<ReferenceInfo> getReferenceInfo(); /** returns if the entity is refering to the Object. */ public class ReferenceInfo { final private String id; final private Class<? extends Entity> type; public ReferenceInfo(String id, Class<? extends Entity> type) { super(); this.id = id; this.type = type; } public String getId() { return id; } public Class<? extends Entity> getType() { return type; } @Override public boolean equals(Object obj) { if ( ! (obj instanceof ReferenceInfo)) { return false; } return this.id.equals(((ReferenceInfo)obj).id); } @Override public int hashCode() { return id.hashCode(); } @Override public String toString() { return type + ":" + id; } public boolean isReferenceOf(Entity object) { return id.equals(object.getId() ); } } }
Java
package org.rapla.entities.storage; public class UnresolvableReferenceExcpetion extends RuntimeException { private static final long serialVersionUID = 1L; public UnresolvableReferenceExcpetion(String id) { super("Can't resolve reference for id " + id ); } public UnresolvableReferenceExcpetion(String id, String reference) { super("Can't resolve reference for id " + id + " from refererer " + reference); } }
Java
package org.rapla.entities.storage; import org.rapla.framework.RaplaException; public class CannotExistWithoutTypeException extends RaplaException { public CannotExistWithoutTypeException() { super("This object cannot exist without a dynamictype. Type cannot be removed."); } /** * */ private static final long serialVersionUID = 1L; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; public interface Entity<T> extends RaplaObject<T> { /** returns true, if the passed object is an instance of Entity * and has the same id as the object. If both Entities have * no ids, the == operator will be applied. */ String getId(); boolean isIdentical(Entity id2); /** @deprecated as of rapla 1.8 there can be multiple persistant versions of an object. You can still use isReadOnly to test if the object is editable * returns if the instance of the entity is persisant and the cache or just a local copy. * Persistant objects are usably not editable and are updated in a multiuser system. * Persistant instances with the same id should therefore have the same content and * <code>persistant1.isIdentical(persistant2)</code> implies <code>persistant1 == persistant2</code>. * A non persistant instance has never the same reference as the persistant entity with the same id. * <code>persistant1.isIdentical(nonPersitant1)</code> implies <code>persistant1 != nonPersistant2</code>. * As */ @Deprecated boolean isPersistant(); boolean isReadOnly(); public static Entity<?>[] ENTITY_ARRAY = new Entity[0]; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; import java.util.Date; import java.util.Iterator; import java.util.List; import org.rapla.components.util.DateTools; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentFormater; import org.rapla.entities.domain.Period; import org.rapla.entities.domain.Repeating; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; /** default implementation of appointment formater */ public class AppointmentFormaterImpl implements AppointmentFormater { I18nBundle i18n; RaplaLocale loc; public AppointmentFormaterImpl(RaplaContext context) throws RaplaException { i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES); loc = context.lookup(RaplaLocale.class); } protected RaplaLocale getRaplaLocale() { return loc; } protected I18nBundle getI18n() { return i18n; } protected String getString(String key) { return i18n.getString(key); } public String getShortSummary(Appointment appointment) { String time = loc.formatTime(appointment.getStart()); Repeating repeating = appointment.getRepeating(); final boolean wholeDaysSet = appointment.isWholeDaysSet(); final String timeString = wholeDaysSet ? "" :" " + time; String weekday = loc.getWeekday(appointment.getStart()); if (repeating != null) { if (repeating.isWeekly()) { return weekday + timeString; } if (repeating.isDaily()) return getString("daily") + " " + time; if (repeating.isMonthly()) return getWeekdayOfMonth( appointment.getStart() ) + weekday + timeString; if (repeating.isYearly()) return getDayOfMonth( appointment.getStart() ) + loc.getMonth(appointment.getStart()) +" " + timeString; } String date = loc.formatDate(appointment.getStart()); return weekday + " " +date + " " + timeString; } public String getVeryShortSummary(Appointment appointment) { Repeating repeating = appointment.getRepeating(); if (repeating != null) { if (repeating.isWeekly()) return getRaplaLocale().getWeekday(appointment.getStart()); if (repeating.isDaily()) { String time = getRaplaLocale().formatTime(appointment.getStart()); return time; } if (repeating.isMonthly()) { return getRaplaLocale().getWeekday(appointment.getStart()); } } String date = getRaplaLocale().formatDateShort(appointment.getStart()); return date; } public String getSummary( Appointment a ) { StringBuffer buf = new StringBuffer(); Repeating repeating = a.getRepeating(); final boolean wholeDaysSet = a.isWholeDaysSet(); Date start = a.getStart(); Date end = a.getEnd(); if ( repeating == null ) { buf.append( loc.getWeekday( start ) ); buf.append( ' ' ); buf.append( loc.formatDate( start ) ); if (!wholeDaysSet && !( end.equals( DateTools.cutDate(end)) && start.equals(DateTools.cutDate( start)))) { buf.append( ' ' ); buf.append( loc.formatTime( start ) ); if ( isSameDay( start, end ) || (end.equals( DateTools.cutDate(end)) && isSameDay( DateTools.fillDate( start), end)) ) { buf.append( '-' ); } else { buf.append( " - " ); buf.append( loc.getWeekday( end ) ); buf.append( ' ' ); buf.append( loc.formatDate( end ) ); buf.append( ' ' ); } buf.append( loc.formatTime( end ) ); } else if ( end.getTime() - start.getTime() > DateTools.MILLISECONDS_PER_DAY) { buf.append( " - " ); buf.append( loc.getWeekday( DateTools.addDays(end,-1 )) ); buf.append( ' ' ); buf.append( loc.formatDate( DateTools.addDays(end,-1 )) ); } } else if ( repeating.isWeekly() || repeating.isMonthly() || repeating.isYearly()) { if( repeating.isMonthly()) { buf.append( getWeekdayOfMonth( start )); } if (repeating.isYearly()) { buf.append( getDayOfMonth( start ) ); buf.append( loc.getMonth( start ) ); } else { buf.append( loc.getWeekday( start ) ); } if (wholeDaysSet) { if ( end.getTime() - start.getTime() > DateTools.MILLISECONDS_PER_DAY) { if ( end.getTime() - start.getTime() <= DateTools.MILLISECONDS_PER_DAY * 6 ) { buf.append( " - " ); buf.append( loc.getWeekday( end ) ); } else { buf.append( ' ' ); buf.append( loc.formatDate( start ) ); buf.append( " - " ); buf.append( loc.getWeekday( end ) ); buf.append( ' ' ); buf.append( loc.formatDate( end ) ); } } } else { buf.append( ' ' ); if ( isSameDay( start, end ) ) { buf.append( loc.formatTime( start ) ); buf.append( '-' ); buf.append( loc.formatTime( end ) ); } else if ( end.getTime() - start.getTime() <= DateTools.MILLISECONDS_PER_DAY * 6 ) { buf.append( loc.formatTime( start ) ); buf.append( " - " ); buf.append( loc.getWeekday( end ) ); buf.append( ' ' ); buf.append( loc.formatTime( end ) ); } else { buf.append( loc.formatDate( start ) ); buf.append( ' ' ); buf.append( loc.formatTime( start ) ); buf.append( " - " ); buf.append( loc.getWeekday( end ) ); buf.append( ' ' ); buf.append( loc.formatDate( end ) ); buf.append( ' ' ); buf.append( loc.formatTime( end ) ); } } if ( repeating.isWeekly()) { buf.append( ' ' ); buf.append( getInterval( repeating ) ); } if ( repeating.isMonthly()) { buf.append(" " + getString("monthly")); } if ( repeating.isYearly()) { buf.append(" " + getString("yearly")); } } else if ( repeating.isDaily() ) { long days =(end.getTime() - start.getTime()) / (DateTools.MILLISECONDS_PER_HOUR * 24 ); if ( !a.isWholeDaysSet()) { buf.append( loc.formatTime( start ) ); if ( days <1) { buf.append( '-' ); buf.append( loc.formatTime( end ) ); } buf.append( ' ' ); } buf.append( getInterval( repeating ) ); } return buf.toString(); } private String getWeekdayOfMonth( Date date ) { StringBuffer b = new StringBuffer(); int numb = DateTools.getDayOfWeekInMonth( date ); b.append( String.valueOf(numb)); b.append( '.'); b.append( ' '); return b.toString(); } private String getDayOfMonth( Date date ) { StringBuffer b = new StringBuffer(); int numb = DateTools.getDayOfMonth( date ); b.append( String.valueOf(numb)); b.append( '.'); b.append( ' '); return b.toString(); } private boolean isSameDay( Date d1, Date d2 ) { return DateTools.isSameDay(d1, d2); } public String getExceptionSummary( Repeating r ) { StringBuffer buf = new StringBuffer(); buf.append(getString("appointment.exceptions")); buf.append(": "); Date[] exc = r.getExceptions(); for ( int i=0;i<exc.length;i++) { if (i>0) buf.append(", "); buf.append( getRaplaLocale().formatDate( exc[i] ) ); } return buf.toString(); } private String getInterval( Repeating r ) { StringBuffer buf = new StringBuffer(); if ( r.getInterval() == 1 ) { buf.append( getString( r.getType().toString() ) ); } else { String fString ="weekly"; if ( r.isWeekly() ) { fString = getString( "weeks" ); } if ( r.isDaily() ) { fString = getString( "days" ); } buf.append( getI18n().format( "interval.format", "" + r.getInterval(), fString ) ); } return buf.toString(); } private boolean isPeriodicaly(Period period, Repeating r) { Appointment a = r.getAppointment(); if (r.getEnd().after( period.getEnd() ) ) return false; if ( r.isWeekly() ) { return ( DateTools.cutDate(a.getStart().getTime()) - period.getStart().getTime() ) <= DateTools.MILLISECONDS_PER_DAY * 6 && ( DateTools.cutDate(period.getEnd().getTime()) - r.getEnd().getTime() ) <= DateTools.MILLISECONDS_PER_DAY * 6 ; } else if ( r.isDaily() ) { return isSameDay( a.getStart(), period.getStart() ) && isSameDay( r.getEnd(), period.getEnd() ) ; } return false; } public String getSummary( Repeating r , List<Period> periods) { if ( r.getEnd() != null && !r.isFixedNumber() ) { Iterator<Period> it = periods.iterator(); while ( it.hasNext() ) { Period period = it.next(); if ( isPeriodicaly(period, r)) return getI18n().format("in_period.format" ,period.getName(loc.getLocale()) ); } } return getSummary(r); } public String getSummary( Repeating r ) { Appointment a = r.getAppointment(); StringBuffer buf = new StringBuffer(); String startDate = loc.formatDate( a.getStart() ); buf.append( getI18n().format("format.repeat_from", startDate) ); buf.append( ' ' ); // print end date, when end is given if ( r.getEnd() != null) { String endDate = loc.formatDate( DateTools.subDay(r.getEnd()) ); buf.append( getI18n().format("format.repeat_until", endDate) ); buf.append( ' ' ); } // print number of repeating if number is gt 0 and fixed times if ( r.getNumber()>=0 && r.isFixedNumber() ) { buf.append( getI18n().format("format.repeat_n_times", String.valueOf(r.getNumber())) ); buf.append( ' ' ); } // print never ending if end is null if (r.getEnd() == null ){ buf.append( getString("repeating.forever") ); buf.append( ' ' ); } return buf.toString(); } }
Java
package org.rapla.bootstrap; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; @SuppressWarnings({ "rawtypes", "unchecked" }) public class CustomJettyStarter { public static final String USAGE = new String ( "Usage : \n" + "[-?|-c PATH_TO_CONFIG_FILE] [ACTION]\n" + "Possible actions:\n" + " standalone : Starts the rapla-gui with embedded server (this is the default)\n" + " server : Starts the rapla-server \n" + " client : Starts the rapla-client \n" + " import : Import from file into the database\n" + " export : Export from database into file\n" + "the config file is jetty.xml generally located in etc/jetty.xml" ); public static void main(final String[] args) throws Exception { String property = System.getProperty("org.rapla.disableHostChecking"); if ( Boolean.parseBoolean( property)) { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); } new CustomJettyStarter().start( args); } Class ServerC ; Class ConfigurationC; Class ConnectorC; Class ResourceC; Class EnvEntryC; Class LifeCyleC; Class LifeCyleListenerC; // Class DeploymentManagerC; // Class ContextHandlerC; // Class WebAppContextC; // Class AppC; // Class AppProviderC; // Class ServletHandlerC; // Class ServletHolderC; ClassLoader loader; Method stopMethod; Logger logger = Logger.getLogger(getClass().getName()); String startupMode; String startupUser; /** parse startup parameters. The parse format: <pre> [-?|-c PATH_TO_CONFIG_FILE] [ACTION] </pre> Possible map entries: <ul> <li>config: the config-file</li> <li>action: the start action</li> </ul> @return a map with the parameter-entries or null if format is invalid or -? is used */ public static Map<String,String> parseParams( String[] args ) { boolean bInvalid = false; Map<String,String> map = new HashMap<String,String>(); String config = null; String action = null; // Investigate the passed arguments for ( int i = 0; i < args.length; i++ ) { String arg = args[i].toLowerCase(); if ( arg.equals( "-c" ) ) { if ( i + 1 == args.length ) { bInvalid = true; break; } config = args[++i]; continue; } if ( arg.equals( "-?" ) ) { bInvalid = true; break; } if ( arg.substring( 0, 1 ).equals( "-" ) ) { bInvalid = true; break; } if (action == null) { action = arg; } } if ( bInvalid ) { return null; } if ( config != null ) map.put( "config", config ); if ( action != null ) map.put( "action", action ); return map; } public void start(final String[] arguments) throws Exception { Map<String, String> parseParams = parseParams(arguments); String configFiles = parseParams.get("config"); if ( configFiles == null) { configFiles = "etc/jetty.xml"; String property = System.getProperty("jetty.home"); if (property != null) { if ( !property.endsWith("/")) { property += "/"; } configFiles = property + configFiles; } } startupMode =System.getProperty("org.rapla.startupMode"); if (startupMode == null) { startupMode = parseParams.get("action"); } if (startupMode == null) { startupMode = "standalone"; } startupUser =System.getProperty("org.rapla.startupUser"); boolean isServer = startupMode.equals("server"); final boolean removeConnectors = !isServer; if ( isServer) { System.setProperty( "java.awt.headless", "true" ); } loader = Thread.currentThread().getContextClassLoader(); Class<?> LoadingProgressC= null; final Object progressBar; if ( startupMode.equals("standalone" ) || startupMode.equals("client" )) { LoadingProgressC = loader.loadClass("org.rapla.bootstrap.LoadingProgress"); progressBar = LoadingProgressC.getMethod("getInstance").invoke(null); LoadingProgressC.getMethod("start", int.class, int.class).invoke( progressBar, 1,4); } else { progressBar = null; } final String contextPath = System.getProperty("org.rapla.context",null); final String downloadUrl = System.getProperty("org.rapla.serverUrl",null); final String[] jettyArgs = configFiles.split(","); final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); AccessController.doPrivileged(new PrivilegedAction<Object>() { boolean started; boolean shutdownShouldRun; public Object run() { try { Properties properties = new Properties(); // Add System Properties Enumeration<?> ensysprop = System.getProperties().propertyNames(); while (ensysprop.hasMoreElements()) { String name = (String)ensysprop.nextElement(); properties.put(name,System.getProperty(name)); } //loader.loadClass("org.rapla.bootstrap.JNDIInit").newInstance(); ServerC =loader.loadClass("org.eclipse.jetty.server.Server"); stopMethod = ServerC.getMethod("stop"); ConfigurationC =loader.loadClass("org.eclipse.jetty.xml.XmlConfiguration"); ConnectorC = loader.loadClass("org.eclipse.jetty.server.Connector"); ResourceC = loader.loadClass("org.eclipse.jetty.util.resource.Resource"); EnvEntryC = loader.loadClass("org.eclipse.jetty.plus.jndi.EnvEntry"); LifeCyleC = loader.loadClass( "org.eclipse.jetty.util.component.LifeCycle"); LifeCyleListenerC = loader.loadClass( "org.eclipse.jetty.util.component.LifeCycle$Listener"); // DeploymentManagerC = loader.loadClass("org.eclipse.jetty.deploy.DeploymentManager"); // ContextHandlerC = loader.loadClass("org.eclipse.jetty.server.handler.ContextHandler"); // WebAppContextC = loader.loadClass("org.eclipse.jetty.webapp.WebAppContext"); // AppC = loader.loadClass("org.eclipse.jetty.deploy.App"); // AppProviderC = loader.loadClass("org.eclipse.jetty.deploy.AppProvider"); // ServletHandlerC = loader.loadClass("org.eclipse.jetty.servlet.ServletHandler"); // ServletHolderC = loader.loadClass("org.eclipse.jetty.servlet.ServletHolder"); // For all arguments, load properties or parse XMLs Object last = null; Object[] obj = new Object[jettyArgs.length]; for (int i = 0; i < jettyArgs.length; i++) { String configFile = jettyArgs[i]; Object newResource = ResourceC.getMethod("newResource",String.class).invoke(null,configFile); if (configFile.toLowerCase(Locale.ENGLISH).endsWith(".properties")) { properties.load((InputStream)ResourceC.getMethod("getInputStream").invoke(newResource)); } else { URL url = (URL)ResourceC.getMethod("getURL").invoke(newResource); Object configuration = ConfigurationC.getConstructor(URL.class).newInstance(url); if (last != null) ((Map)ConfigurationC.getMethod("getIdMap").invoke(configuration)).putAll((Map)ConfigurationC.getMethod("getIdMap").invoke(last)); if (properties.size() > 0) { Map<String, String> props = new HashMap<String, String>(); for (Object key : properties.keySet()) { props.put(key.toString(),String.valueOf(properties.get(key))); } ((Map)ConfigurationC.getMethod("getProperties").invoke( configuration)).putAll( props); } Object configuredObject = ConfigurationC.getMethod("configure").invoke(configuration); Integer port = null; if ( ServerC.isInstance(configuredObject)) { final Object server = configuredObject; Object[] connectors = (Object[]) ServerC.getMethod("getConnectors").invoke(server); for (Object c: connectors) { port = (Integer) ConnectorC.getMethod("getPort").invoke(c); if ( removeConnectors) { ServerC.getMethod("removeConnector", ConnectorC).invoke(server, c); } } final Method shutdownMethod = ServerC.getMethod("stop"); InvocationHandler proxy = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); if ( name.toLowerCase(Locale.ENGLISH).indexOf("started")>=0) { if ( shutdownShouldRun) { shutdownMethod.invoke( server); } else { started = true; } } return null; } }; Class<?>[] interfaces = new Class[] {LifeCyleListenerC}; Object proxyInstance = Proxy.newProxyInstance(loader, interfaces, proxy); ServerC.getMethod("addLifeCycleListener", LifeCyleListenerC).invoke(server, proxyInstance); Constructor newJndi = EnvEntryC.getConstructor(String.class,Object.class); Method addBean = ServerC.getMethod("addBean", Object.class); if ( !startupMode.equals("server")) { addBean.invoke(server, newJndi.newInstance("rapla_startup_user", startupUser)); addBean.invoke(server, newJndi.newInstance("rapla_startup_mode", startupMode)); addBean.invoke(server, newJndi.newInstance("rapla_download_url", downloadUrl)); addBean.invoke(server, newJndi.newInstance("rapla_instance_counter", new ArrayList<String>())); if ( contextPath != null) { addBean.invoke(server, newJndi.newInstance("rapla_startup_context", contextPath)); } } addBean.invoke(server, newJndi.newInstance("rapla_startup_port", port)); { Runnable shutdownCommand = new Runnable() { public void run() { if ( started) { try { shutdownMethod.invoke(server); } catch (Exception ex) { logger.log(Level.SEVERE,ex.getMessage(),ex); } } else { shutdownShouldRun = true; } } }; addBean.invoke(server, newJndi.newInstance("rapla_shutdown_command", shutdownCommand)); } } obj[i] = configuredObject; last = configuration; } } // For all objects created by XmlConfigurations, start them if they are lifecycles. for (int i = 0; i < obj.length; i++) { if (LifeCyleC.isInstance(obj[i])) { Object o =obj[i]; if ( !(Boolean)LifeCyleC.getMethod("isStarted").invoke(o)) { LifeCyleC.getMethod("start").invoke(o); } } } } catch (Exception e) { exception.set(e); } return null; } }); if ( progressBar != null && LoadingProgressC != null) { LoadingProgressC.getMethod("close").invoke( progressBar); } Throwable th = exception.get(); if (th != null) { if (th instanceof RuntimeException) throw (RuntimeException)th; else if (th instanceof Exception) throw (Exception)th; else if (th instanceof Error) throw (Error)th; throw new Error(th); } } // void doStart(final Object server, String passedContext) // { // try // { // Object bean = ServerC.getMethod("getBean", Class.class).invoke(server, DeploymentManagerC); // Map<String, Object> raplaServletMap = new LinkedHashMap<String, Object>(); // Collection<?> apps = (Collection<?>) DeploymentManagerC.getMethod("getApps").invoke(bean); // for (Object handler:apps) // { // // Object context_ = AppC.getMethod("getContextHandler").invoke(handler); // String contextPath = (String) ContextHandlerC.getMethod("getContextPath").invoke(context_); // Object[] servlets = (Object[]) ContextHandlerC.getMethod("getChildHandlersByClass", Class.class).invoke(context_, ServletHandlerC); // for ( Object childHandler : servlets) // { // Object servlet = ServletHandlerC.getMethod("getServlet",String.class).invoke( childHandler,"RaplaServer"); // if ( servlet != null) // { // raplaServletMap.put(contextPath, servlet); // } // } // } // // Set<String> keySet = raplaServletMap.keySet(); // if ( keySet.size() == 0) // { // logger.log(Level.SEVERE,"No rapla context found in jetty container."); // stopMethod.invoke(server); // } // else if ( keySet.size() > 1 && passedContext == null) // { // logger.log(Level.SEVERE,"Multiple context found in jetty container " + keySet +" Please specify one via -Dorg.rapla.context=REPLACE_WITH_CONTEXT"); // stopMethod.invoke(server); // } // else // { // //Class MainServletC = loader.loadClass("org.rapla.MainServlet"); // Object servletHolder = passedContext == null ? raplaServletMap.values().iterator().next(): raplaServletMap.get( passedContext); // if ( servletHolder != null) // { // // Object servlet = ServletHolderC.getMethod("getServlet").invoke( servletHolder); // PropertyChangeListener castedHack = (PropertyChangeListener)servlet; // castedHack.propertyChange( new PropertyChangeEvent(server, startupMode, null, shutdownCommand)); // } // else // { // logger.log(Level.SEVERE,"Rapla context ' " + passedContext +"' not found."); // stopMethod.invoke(server); // } // } // } // catch (Exception ex) // { // logger.log(Level.SEVERE,ex.getMessage(),ex); // try { // stopMethod.invoke(server); // } catch (Exception e) { // logger.log(Level.SEVERE,e.getMessage(),e); // } // } // } }
Java
package org.rapla.bootstrap; import java.io.IOException; public class RaplaClientLoader { public static void main(String[] args) throws IOException { RaplaJettyLoader.main(new String[] {"client"}); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.bootstrap; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker; import java.awt.Toolkit; import java.awt.image.ImageObserver; import java.net.URL; import javax.swing.JProgressBar; final public class LoadingProgress { static LoadingProgress instance; JProgressBar progressBar; Frame frame; ImageObserver observer; Image image; Component canvas; int maxValue; static public LoadingProgress getInstance() { if ( instance == null) { instance = new LoadingProgress(); } return instance; } public boolean isStarted() { return frame != null; } /** this method creates the progress bar */ public void start(int startValue, int maxValue) { this.maxValue = maxValue; frame = new Frame() { private static final long serialVersionUID = 1L; public void paint(Graphics g) { super.paint(g); g.drawRect(0, 0, getWidth() - 1, getHeight() - 1); } }; observer = new ImageObserver() { public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h) { if ((flags & ALLBITS) != 0) { canvas.repaint(); } return (flags & (ALLBITS | ABORT | ERROR)) == 0; } }; frame.setBackground(new Color(255, 255, 204)); canvas = new Component() { private static final long serialVersionUID = 1L; public void paint(Graphics g) { g.drawImage(image, 0, 0, observer); } }; Toolkit toolkit = Toolkit.getDefaultToolkit(); URL url = LoadingProgress.class.getResource("/org/rapla/bootstrap/tafel.png"); // Variables (integer pixels) for... // ... the width of the border around the picture int borderwidth = 4; // ... the height of the border around the picture int borderheight = 4; // ... the width of the picture within the frame int picturewidth = 356; // ... the height of the picture within the frame int pictureheight = 182; // ... calculating the frame width int framewidth = borderwidth + borderheight + picturewidth; // ... calculating the frame height int frameheight = borderwidth + borderheight + pictureheight; // ... width of the loading progress bar int progresswidth = 150; // ... height of the loading progress bar int progressheight = 15; image = toolkit.createImage(url); frame.setResizable(false); frame.setLayout(null); progressBar = new JProgressBar(0, maxValue); progressBar.setValue(startValue); // set the bounds to position the progressbar and set width and height progressBar.setBounds(158, 130, progresswidth, progressheight); progressBar.repaint(); // we have to add the progressbar first to get it infront of the picture frame.add(progressBar); frame.add(canvas); // width and height of the canvas equal to those of the picture inside // but here we need the borderwidth as X and the borderheight as Y value canvas.setBounds(borderwidth, borderheight, picturewidth, pictureheight); try { // If run on jdk < 1.4 this will throw a MethodNotFoundException // frame.setUndecorated(true); Frame.class.getMethod("setUndecorated", new Class[] { boolean.class }).invoke(frame, new Object[] { new Boolean(true) }); } catch (Exception ex) { } // we grab the actual size of the screen Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // to make sure the starting dialog is positioned in the middle of // the screen and has the width and height we specified for the frame frame.setBounds((screenSize.width / 2) - (picturewidth / 2), (screenSize.height / 2) - (pictureheight / 2), framewidth, frameheight); frame.validate(); frame.setVisible(true); frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); MediaTracker mt = new MediaTracker(frame); mt.addImage(image, 0); try { mt.waitForID(0); } catch (InterruptedException e) { } } public void advance() { if ( frame == null) { return; } int oldValue = progressBar.getValue(); if (oldValue < maxValue) progressBar.setValue(oldValue + 1); progressBar.repaint(); } public void close() { if ( frame != null) { frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); frame.dispose(); frame = null; } } }
Java
package org.rapla.bootstrap; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.StringTokenizer; /** Puts all jar-files from the libdirs into the classpath and start the mainClass. Usage: <code> Syntax: baseDir libdir1,libdir2,... mainClass arg1 arg2 ... Will put all jar-files from the libdirs into the classpath and start the mainClass baseDir: replace with the path, from wich you want the lib-dirs to resolve. libdir[1-n]: Lib-Directories relativ to the base jars."); mainClass: The Java-Class you want to start after loading the jars. arg[1-n]: Example: ./lib common,client org.rapla.Main rapla loads the jars in lib/common and lib/client and starts org.rapla.Main with the argument rapla </code> */ public class RaplaLoader { /** returns all *.jar files in the directories passed in dirList relative to the baseDir */ public static File[] getJarFilesAndClassesFolder(String baseDir,String dirList) throws IOException { ArrayList<File> completeList = new ArrayList<File>(); StringTokenizer tokenizer = new StringTokenizer(dirList,","); while (tokenizer.hasMoreTokens()) { File jarDir = new File(baseDir,tokenizer.nextToken()); if (jarDir.exists() && jarDir.isDirectory()) { File[] jarFiles = jarDir.listFiles(); for (int i = 0; i < jarFiles.length; i++) { if ( jarFiles[i].getAbsolutePath().endsWith(".jar") ) { completeList.add(jarFiles[i].getCanonicalFile()); } } completeList.add( jarDir.getCanonicalFile() ); } } return completeList.toArray(new File[] {}); } private static void printUsage() { System.out.println("Syntax: baseDir libdir1,libdir2,... mainClass arg1 arg2 ..."); System.out.println(); System.out.println("Will put all jar-files from the libdirs into the classpath and start the mainClass"); System.out.println(); System.out.println(" baseDir: replace with the path, from wich you want the lib-dirs to resolve."); System.out.println(" libdir[1-n]: Lib-Directories relativ to the base jars."); System.out.println(" mainClass: The Java-Class you want to start after loading the jars."); System.out.println(" arg[1-n]: "); System.out.println(); System.out.println(" Example: ./lib common,client org.rapla.Main rapla "); System.out.println("loads the jars in lib/common and lib/client and "); System.out.println(" starts org.rapla.Main with the argument rapla"); } public static void main(String[] args) { String baseDir; String dirList; String classname; String[] applicationArgs; if (args.length <3) { printUsage(); System.exit(1); } baseDir=args[0]; dirList=args[1]; classname=args[2]; applicationArgs = new String[args.length-3]; for (int i=0;i<applicationArgs.length;i++) { applicationArgs[i] = args[i+3]; } start( baseDir, dirList, classname, "main",new Object[] {applicationArgs} ); } public static void start( String baseDir, String dirList, String classname, String methodName,Object[] applicationArgs ) { try{ ClassLoader classLoader = getJarClassloader(baseDir, dirList); Thread.currentThread().setContextClassLoader(classLoader); startMain(classLoader,classname,methodName,applicationArgs); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } } private static ClassLoader getJarClassloader(String baseDir, String dirList) throws IOException, MalformedURLException { File[] jarFiles = getJarFilesAndClassesFolder(baseDir,dirList); URL[] urls = new URL[jarFiles.length]; for (int i = 0; i < jarFiles.length; i++) { urls[i] = jarFiles[i].toURI().toURL(); //System.out.println(urls[i]); } ClassLoader classLoader = new URLClassLoader ( urls ,RaplaLoader.class.getClassLoader() ); return classLoader; } private static void startMain(ClassLoader classLoader,String classname, String methodName,Object[] args) throws Exception { Class<?> startClass = classLoader.loadClass(classname); Class<?>[] argTypes = new Class[args.length]; for ( int i=0;i<args.length;i++) { argTypes[i] = args[i].getClass(); } Method mainMethod = startClass.getMethod(methodName,argTypes); mainMethod.invoke(null, args); } // public static void startFromWar( String baseDir, String dirList,String warfile, String classname, String methodName,Object[] applicationArgs ) // { // try{ // ClassLoader loader = getJarClassloader(baseDir, dirList); // Thread.currentThread().setContextClassLoader(loader); // Class<?> forName = loader.loadClass("org.slf4j.bridge.SLF4JBridgeHandler"); // forName.getMethod("removeHandlersForRootLogger", new Class[] {}).invoke(null, new Object[] {}); // forName.getMethod("install", new Class[] {}).invoke(null, new Object[] {}); // loader.loadClass("org.rapla.bootstrap.JNDIInit").newInstance(); // // File file = new File(baseDir, warfile); // ClassLoader classLoader; // if (file.exists()) // { // Class<?> webappContextClass = loader.loadClass("org.eclipse.jetty.webapp.WebAppContext"); // //org.eclipse.jetty.webapp.WebAppContext context = new org.eclipse.jetty.webapp.WebAppContext("webapps/rapla.war","/"); // Constructor<?> const1 = webappContextClass.getConstructor(String.class, String.class); // Object context = const1.newInstance(new Object[] {file.getPath(),"/"}); // Class<?> webappClassLoaderClass = loader.loadClass("org.eclipse.jetty.webapp.WebAppClassLoader"); // Class<?> contextClass = loader.loadClass("org.eclipse.jetty.webapp.WebAppClassLoader$Context"); // //org.eclipse.jetty.webapp.WebAppClassLoader classLoader = new org.eclipse.jetty.webapp.WebAppClassLoader(parentClassLoader, context); // Constructor<?> const2 = webappClassLoaderClass.getConstructor(ClassLoader.class, contextClass); // classLoader = (ClassLoader) const2.newInstance(loader, context); // webappContextClass.getMethod("setClassLoader", ClassLoader.class).invoke( context,classLoader); // Class<?> configurationClass = loader.loadClass("org.eclipse.jetty.webapp.WebInfConfiguration"); // Object config = configurationClass.newInstance(); // configurationClass.getMethod("preConfigure", webappContextClass).invoke(config, context); // configurationClass.getMethod("configure", webappContextClass).invoke(config, context); // } // else // { // classLoader = loader; // System.err.println("War " + warfile + " not found. Using original classpath."); // } // startMain(classLoader,classname,methodName,applicationArgs); // } catch (Exception ex) { // ex.printStackTrace(); // System.exit(1); // } // } }
Java
package org.rapla.bootstrap; import java.io.File; import java.io.IOException; public class RaplaServerAsServiceLoader { public static void main(String[] args) throws IOException { System.setProperty( "java.awt.headless", "true" ); String baseDir = System.getProperty("jetty.home"); if ( baseDir == null) { baseDir = "../.."; System.setProperty( "jetty.home", new File(baseDir ).getCanonicalPath() ); } RaplaServerLoader.main( args); } }
Java
package org.rapla.bootstrap; import java.io.IOException; public class RaplaStandaloneLoader { public static void main(String[] args) throws IOException { // This is for backwards compatibility if ( args.length > 0 && args[0].equals( "client")) { RaplaJettyLoader.main(new String[] {"client"}); } else { RaplaJettyLoader.main(new String[] {"standalone"}); } } }
Java
package org.rapla.bootstrap; import java.io.IOException; public class RaplaServerLoader { public static void main(String[] args) throws IOException { System.setProperty( "java.awt.headless", "true" ); RaplaJettyLoader.main(new String[] {"server"}); } }
Java
package org.rapla.bootstrap; import java.io.File; import java.io.IOException; public class RaplaJettyLoader { public static void main(String[] args) throws IOException { String baseDir = System.getProperty("jetty.home"); if ( baseDir == null) { baseDir = "."; System.setProperty( "jetty.home", new File(baseDir ).getCanonicalPath() ); } for ( String arg:args) { if ( arg != null && arg.toLowerCase().equals("server")) { System.setProperty( "java.awt.headless", "true" ); } } String dirList = "lib,lib/logging,lib/ext,resources"; String classname = "org.rapla.bootstrap.CustomJettyStarter"; String methodName = "main"; //System.setProperty( "java.awt.headless", "true" ); String test = "Starting rapla from " + System.getProperty("jetty.home"); System.out.println(test ); RaplaLoader.start( baseDir,dirList, classname,methodName, new Object[] {args }); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ /** A Facade Interface for manipulating the stored data. * This abstraction allows Rapla to store the data * in many ways. <BR> * Currently implemented are the storage in an XML-File * ,the storage in an SQL-DBMS and storage over a * network connection. * @see org.rapla.storage.dbsql.DBOperator * @see org.rapla.storage.dbfile.XMLOperator * @see org.rapla.storage.dbrm.RemoteOperator * @author Christopher Kohlhaas */ package org.rapla.storage; import java.util.Collection; import java.util.Date; import java.util.Map; import org.rapla.ConnectInfo; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.storage.EntityResolver; import org.rapla.facade.Conflict; import org.rapla.framework.RaplaException; public interface StorageOperator extends EntityResolver { public static final int MAX_DEPENDENCY = 20; public final static String UNRESOLVED_RESOURCE_TYPE = "rapla:unresolvedResource"; public final static String ANONYMOUSEVENT_TYPE = "rapla:anonymousEvent"; public final static String SYNCHRONIZATIONTASK_TYPE = "rapla:synchronizationTask"; public final static String DEFAUTL_USER_TYPE = "rapla:defaultUser"; public final static String PERIOD_TYPE = "rapla:period"; User connect() throws RaplaException; User connect(ConnectInfo connectInfo) throws RaplaException; boolean isConnected(); /** Refreshes the data. This could be helpful if the storage * operator uses a cache and does not support "Active Monitoring" * of the original data */ void refresh() throws RaplaException; void disconnect() throws RaplaException; /** should return a clone of the object. <strong>Never</strong> edit the original, <strong>always</strong> edit the object returned by editObject.*/ Collection<Entity> editObjects(Collection<Entity> obj, User user) throws RaplaException; Map<String,Entity> getFromId(Collection<String> idSet, boolean throwEntityNotFound) throws RaplaException; Map<Entity,Entity> getPersistant(Collection<? extends Entity> entity) throws RaplaException; /** Stores and/or removes entities and specifies a user that is responsible for the changes. * Notifies all registered StorageUpdateListeners after a successful storage.*/ void storeAndRemove(Collection<Entity> storeObjects,Collection<Entity> removeObjects,User user) throws RaplaException; String[] createIdentifier(RaplaType raplaType, int count) throws RaplaException; Collection<User> getUsers() throws RaplaException; Collection<DynamicType> getDynamicTypes() throws RaplaException; /** returns the user or null if a user with the given username was not found. */ User getUser(String username) throws RaplaException; Preferences getPreferences(User user, boolean createIfNotNull) throws RaplaException; /** returns the reservations of the specified user, sorted by name. * @param allocatables * @param reservationFilters * @param annotationQuery */ Collection<Reservation> getReservations(User user,Collection<Allocatable> allocatables, Date start,Date end, ClassificationFilter[] reservationFilters, Map<String, String> annotationQuery) throws RaplaException; Collection<Allocatable> getAllocatables(ClassificationFilter[] filters) throws RaplaException; Category getSuperCategory(); /** changes the password for the user */ void changePassword(User user,char[] oldPassword,char[] newPassword) throws RaplaException; /** changes the name for the passed user. If a person is connected then all three fields are used. Otherwise only lastname is used*/ void changeName(User user,String title, String firstname, String surname) throws RaplaException; /** changes the name for the user */ void changeEmail(User user,String newEmail) throws RaplaException; void confirmEmail(User user, String newEmail) throws RaplaException; boolean canChangePassword() throws RaplaException; void addStorageUpdateListener(StorageUpdateListener updateListener); void removeStorageUpdateListener(StorageUpdateListener updateListener); /** returns the beginning of the current day. Uses getCurrentTimstamp. */ Date today(); /** returns the date and time in seconds for creation. Server time will be used if in client/server mode. Note that this is always the utc time */ Date getCurrentTimestamp(); boolean supportsActiveMonitoring(); Map<Allocatable,Collection<Appointment>> getFirstAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException; Map<Allocatable, Map<Appointment,Collection<Appointment>>> getAllAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException; Date getNextAllocatableDate(Collection<Allocatable> allocatables,Appointment appointment, Collection<Reservation> ignoreList, Integer worktimeStartMinutes,Integer worktimeEndMinutes, Integer[] excludedDays, Integer rowsPerHour) throws RaplaException; Collection<Conflict> getConflicts(User user) throws RaplaException; Collection<String> getTemplateNames() throws RaplaException; }
Java
package org.rapla.storage; import org.rapla.entities.Entity; public interface UpdateOperation { public Entity getCurrent(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.impl; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.rapla.components.util.Assert; import org.rapla.components.util.TimeInterval; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.Named; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.internal.ModifiableTimestamp; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityReferencer.ReferenceInfo; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.RefEntity; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.framework.logger.Logger; import org.rapla.storage.LocalCache; import org.rapla.storage.PreferencePatch; import org.rapla.storage.StorageOperator; import org.rapla.storage.StorageUpdateListener; import org.rapla.storage.UpdateEvent; import org.rapla.storage.UpdateResult; /** * An abstract implementation of the StorageOperator-Interface. It operates on a * LocalCache-Object and doesn't implement connect, isConnected, refresh, * createIdentifier and disconnect. <b>!!WARNING!!</b> This operator is not * thread-safe. {@link org.rapla.server.internal.ServerServiceImpl} for an * example of an thread-safe wrapper around this storageoperator. * * @see LocalCache */ public abstract class AbstractCachableOperator implements StorageOperator { protected RaplaLocale raplaLocale; final List<StorageUpdateListener> storageUpdateListeners = new Vector<StorageUpdateListener>(); Map<String,String> createdPreferenceIds = new HashMap<String,String>(); protected LocalCache cache; protected I18nBundle i18n; protected RaplaContext context; Logger logger; protected ReadWriteLock lock = new ReentrantReadWriteLock(); public AbstractCachableOperator(RaplaContext context, Logger logger) throws RaplaException { this.logger = logger; this.context = context; raplaLocale = context.lookup(RaplaLocale.class); i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES); Assert.notNull(raplaLocale.getLocale()); cache = new LocalCache(); } public Logger getLogger() { return logger; } public User connect() throws RaplaException { return connect(null); } // Implementation of StorageOperator public <T extends Entity> T editObject(T o, User user)throws RaplaException { Set<Entity>singleton = Collections.singleton( (Entity)o); Collection<Entity> list = editObjects( singleton, user); Entity first = list.iterator().next(); @SuppressWarnings("unchecked") T casted = (T) first; return casted; } public Collection<Entity> editObjects(Collection<Entity>list, User user)throws RaplaException { checkConnected(); Collection<Entity> toEdit = new LinkedHashSet<Entity>(); // read lock Map<Entity,Entity> persistantMap = getPersistant(list); // read unlock for (Entity o:list) { Entity persistant = persistantMap.get(o); Entity refEntity = editObject(o, persistant, user); toEdit.add( refEntity); } return toEdit; } protected Entity editObject(Entity newObj, Entity persistant, User user) { final SimpleEntity clone; if ( persistant != null) { clone = (SimpleEntity) persistant.clone(); } else { clone = (SimpleEntity) newObj.clone(); } SimpleEntity refEntity = clone; if (refEntity instanceof ModifiableTimestamp) { ((ModifiableTimestamp) refEntity).setLastChangedBy(user); } return (Entity) refEntity; } public void storeAndRemove(final Collection<Entity> storeObjects, final Collection<Entity>removeObjects, final User user) throws RaplaException { checkConnected(); UpdateEvent evt = new UpdateEvent(); if (user != null) { evt.setUserId(user.getId()); } for (Entity obj : storeObjects) { if ( obj instanceof Preferences) { PreferencePatch patch = ((PreferencesImpl)obj).getPatch(); evt.putPatch( patch); } else { evt.putStore(obj); } } for (Entity entity : removeObjects) { RaplaType type = entity.getRaplaType(); if (Appointment.TYPE ==type || Category.TYPE == type || Attribute.TYPE == type) { String name = getName( entity); throw new RaplaException(getI18n().format("error.remove_object",name)); } evt.putRemove(entity); } dispatch(evt); } /** * implement this method to implement the persistent mechanism. By default it * calls <li>check()</li> <li>update()</li> <li>fireStorageUpdate()</li> <li> * fireTriggerEvents()</li> You should not call dispatch directly from the * client. Use storeObjects and removeObjects instead. */ public abstract void dispatch(UpdateEvent evt) throws RaplaException; public Collection<User> getUsers() throws RaplaException { checkConnected(); Lock readLock = readLock(); try { Collection<User> collection = cache.getUsers(); // We return a clone to avoid synchronization Problems return new LinkedHashSet<User>(collection); } finally { unlock(readLock); } } public Collection<DynamicType> getDynamicTypes() throws RaplaException { checkConnected(); Lock readLock = readLock(); try { Collection<DynamicType> collection = cache.getDynamicTypes(); // We return a clone to avoid synchronization Problems return new ArrayList<DynamicType>( collection); } finally { unlock(readLock); } } public Collection<Allocatable> getAllocatables(ClassificationFilter[] filters) throws RaplaException { Collection<Allocatable> allocatables = new LinkedHashSet<Allocatable>(); checkConnected(); Lock readLock = readLock(); try { Collection<Allocatable> collection = cache.getAllocatables(); // We return a clone to avoid synchronization Problems allocatables.addAll(collection); } finally { unlock(readLock); } removeFilteredClassifications(allocatables, filters); return allocatables; } protected void removeFilteredClassifications( Collection<? extends Classifiable> list, ClassificationFilter[] filters) { if (filters == null) { // remove internal types if not specified in filters to remain backwards compatibility Iterator<? extends Classifiable> it = list.iterator(); while (it.hasNext()) { Classifiable classifiable = it.next(); if ( DynamicTypeImpl.isInternalType(classifiable) ) { it.remove(); } } return; } Iterator<? extends Classifiable> it = list.iterator(); while (it.hasNext()) { Classifiable classifiable = it.next(); if (!ClassificationFilter.Util.matches(filters, classifiable)) { it.remove(); } } } public User getUser(final String username) throws RaplaException { checkConnected(); Lock readLock = readLock(); try { return cache.getUser(username); } finally { unlock(readLock); } } Map<String,PreferencesImpl> emptyPreferencesProxy = new ConcurrentHashMap<String, PreferencesImpl>(); public Preferences getPreferences(final User user, boolean createIfNotNull) throws RaplaException { checkConnected(); // Test if user is already stored if (user != null) { resolve(user.getId(), User.class); } String userId = user != null ? user.getId() : null; String preferenceId = PreferencesImpl.getPreferenceIdFromUser(userId); PreferencesImpl pref = (PreferencesImpl) cache.tryResolve( preferenceId, Preferences.class); if (pref == null && createIfNotNull ) { PreferencesImpl preferencesImpl = emptyPreferencesProxy.get( preferenceId); if ( preferencesImpl != null) { return preferencesImpl; } } if (pref == null && createIfNotNull) { PreferencesImpl newPref = newPreferences(userId); newPref.setReadOnly( ); pref = newPref; emptyPreferencesProxy.put(preferenceId , pref); } return pref; } private PreferencesImpl newPreferences(final String userId) throws EntityNotFoundException { Date now = getCurrentTimestamp(); String id = PreferencesImpl.getPreferenceIdFromUser(userId); PreferencesImpl newPref = new PreferencesImpl(now,now); newPref.setResolver( this); if ( userId != null) { User user = resolve( userId, User.class); newPref.setOwner(user); } newPref.setId( id ); return newPref; } public Category getSuperCategory() { return cache.getSuperCategory(); } public synchronized void addStorageUpdateListener(StorageUpdateListener listener) { storageUpdateListeners.add(listener); } public synchronized void removeStorageUpdateListener(StorageUpdateListener listener) { storageUpdateListeners.remove(listener); } public synchronized StorageUpdateListener[] getStorageUpdateListeners() { return storageUpdateListeners.toArray(new StorageUpdateListener[] {}); } protected Lock writeLock() throws RaplaException { return RaplaComponent.lock( lock.writeLock(), 60); } protected Lock readLock() throws RaplaException { return RaplaComponent.lock( lock.readLock(), 10); } protected void unlock(Lock lock) { RaplaComponent.unlock( lock ); } protected I18nBundle getI18n() { return i18n; } protected void fireStorageUpdated(final UpdateResult evt) { StorageUpdateListener[] listeners = getStorageUpdateListeners(); for (int i = 0; i < listeners.length; i++) { listeners[i].objectsUpdated(evt); } } protected void fireUpdateError(final RaplaException ex) { if (storageUpdateListeners.size() == 0) return; StorageUpdateListener[] listeners = getStorageUpdateListeners(); for (int i = 0; i < listeners.length; i++) { listeners[i].updateError(ex); } } protected void fireStorageDisconnected(String message) { if (storageUpdateListeners.size() == 0) return; StorageUpdateListener[] listeners = getStorageUpdateListeners(); for (int i = 0; i < listeners.length; i++) { listeners[i].storageDisconnected(message); } } // End of StorageOperator interface protected void checkConnected() throws RaplaException { if (!isConnected()) { throw new RaplaException(getI18n().format("error.connection_closed", "")); } } @Override public Map<String,Entity> getFromId(Collection<String> idSet, boolean throwEntityNotFound) throws RaplaException { Lock readLock = readLock(); try { Map<String, Entity> result= new LinkedHashMap<String,Entity>(); for ( String id:idSet) { Entity persistant = (throwEntityNotFound ? cache.resolve(id) : cache.tryResolve(id)); if ( persistant != null) { result.put( id,persistant); } } return result; } finally { unlock(readLock); } } @Override public Map<Entity,Entity> getPersistant(Collection<? extends Entity> list) throws RaplaException { Map<String,Entity> idMap = new LinkedHashMap<String,Entity>(); for ( Entity key: list) { String id = key.getId().toString(); idMap.put( id, key); } Map<Entity,Entity> result = new LinkedHashMap<Entity,Entity>(); Set<String> keySet = idMap.keySet(); Map<String,Entity> resolvedList = getFromId( keySet, false); for (Entity entity:resolvedList.values()) { String id = entity.getId().toString(); Entity key = idMap.get( id); if ( key != null ) { result.put( key, entity); } } return result; } /** * @throws RaplaException */ protected void setResolver(Collection<? extends Entity> entities) throws RaplaException { for (Entity entity: entities) { if (entity instanceof EntityReferencer) { ((EntityReferencer)entity).setResolver(this); } } // It is important to do the read only later because some resolve might involve write to referenced objects for (Entity entity: entities) { if (entity instanceof RefEntity) { ((RefEntity)entity).setReadOnly(); } } } protected void testResolve(Collection<? extends Entity> entities) throws EntityNotFoundException { EntityStore store = new EntityStore( this, getSuperCategory()); store.addAll( entities); for (Entity entity: entities) { if (entity instanceof EntityReferencer) { ((EntityReferencer)entity).setResolver(store); } } for (Entity entity: entities) { if (entity instanceof EntityReferencer) { testResolve(store, (EntityReferencer)entity); } } } private void testResolve(EntityResolver resolver, EntityReferencer referencer) throws EntityNotFoundException { Iterable<ReferenceInfo> referencedIds =referencer.getReferenceInfo(); for ( ReferenceInfo id:referencedIds) { testResolve(resolver, referencer, id); } } private void testResolve(EntityResolver resolver, EntityReferencer obj, ReferenceInfo reference) throws EntityNotFoundException { Class<? extends Entity> class1 = reference.getType(); String id = reference.getId(); if (tryResolve(resolver,id, class1) == null) { String prefix = (class1!= null) ? class1.getName() : " unkown type"; throw new EntityNotFoundException(prefix + " with id " + id + " not found for " + obj); } } protected String getName(Object object) { if (object == null) return null; if (object instanceof Named) return (((Named) object).getName(i18n.getLocale())); return object.toString(); } protected String getString(String key) { return getI18n().getString(key); } public DynamicType getDynamicType(String key) { Lock readLock = null; try { readLock = readLock(); } catch (RaplaException e) { // this is not so dangerous getLogger().warn("Returning type " + key + " without read lock "); } try { return cache.getDynamicType( key); } finally { unlock(readLock); } } @Override public Entity tryResolve(String id) { return tryResolve( id, null); } @Override public Entity resolve(String id) throws EntityNotFoundException { return resolve( id, null); } @Override public <T extends Entity> T tryResolve(String id,Class<T> entityClass) { Lock readLock = null; try { readLock = readLock(); } catch (RaplaException e) { getLogger().warn("Returning object for id " + id + " without read lock "); } try { return tryResolve(cache,id, entityClass); } finally { unlock(readLock); } } @Override public <T extends Entity> T resolve(String id,Class<T> entityClass) throws EntityNotFoundException { Lock readLock; try { readLock = readLock(); } catch (RaplaException e) { throw new EntityNotFoundException( e.getMessage() + " " +e.getCause()); } try { return resolve(cache,id, entityClass); } finally { unlock(readLock); } } protected <T extends Entity> T resolve(EntityResolver resolver,String id,Class<T> entityClass) throws EntityNotFoundException { T entity = tryResolve(resolver,id, entityClass); SimpleEntity.checkResolveResult(id, entityClass, entity); return entity; } protected <T extends Entity> T tryResolve(EntityResolver resolver,String id,Class<T> entityClass) { return resolver.tryResolve(id, entityClass); } /** Writes the UpdateEvent in the cache */ protected UpdateResult update(final UpdateEvent evt) throws RaplaException { HashMap<Entity,Entity> oldEntities = new HashMap<Entity,Entity>(); // First make a copy of the old entities Collection<Entity>storeObjects = new LinkedHashSet<Entity>(evt.getStoreObjects()); for (Entity entity : storeObjects) { Entity persistantEntity = findPersistant(entity); if ( persistantEntity == null) { continue; } if (getLogger().isDebugEnabled()) { getLogger().debug("Storing old: " + entity); } if ( persistantEntity instanceof Appointment || ((persistantEntity instanceof Category) && storeObjects.contains( ((Category) persistantEntity).getParent()))) { throw new RaplaException( persistantEntity.getRaplaType() + " can only be stored via parent entity "); // we ingore subentities, because these are added as bellow via addSubentites. The originals will be contain false parent references (to the new parents) when copy is called } else { Entity oldEntity = persistantEntity; oldEntities.put(persistantEntity, oldEntity); } } Collection<PreferencePatch> preferencePatches = evt.getPreferencePatches(); for ( PreferencePatch patch:preferencePatches) { String userId = patch.getUserId(); PreferencesImpl oldEntity = cache.getPreferencesForUserId( userId); PreferencesImpl clone; if ( oldEntity == null) { clone = newPreferences( userId); } else { clone = oldEntity.clone(); } clone.applyPatch( patch); oldEntities.put(clone, oldEntity); storeObjects.add( clone); } List<Entity>updatedEntities = new ArrayList<Entity>(); // Then update the new entities for (Entity entity : storeObjects) { Entity persistant = findPersistant(entity); // do nothing, because the persitantVersion is always read only if (persistant == entity) { continue; } if ( entity instanceof Category) { Category category = (Category)entity; CategoryImpl parent = (CategoryImpl)category.getParent(); if ( parent != null) { parent.replace( category); } } cache.put(entity); updatedEntities.add(entity); } Collection<Entity> removeObjects = evt.getRemoveObjects(); Collection<Entity> toRemove = new HashSet<Entity>(); for (Entity entity : removeObjects) { Entity persistantVersion = findPersistant(entity); if (persistantVersion != null) { cache.remove(persistantVersion); ((RefEntity)persistantVersion).setReadOnly(); } toRemove.add( entity); } setResolver(updatedEntities); TimeInterval invalidateInterval = evt.getInvalidateInterval(); String userId = evt.getUserId(); return createUpdateResult(oldEntities, updatedEntities, toRemove, invalidateInterval, userId); } protected Entity findPersistant(Entity entity) { @SuppressWarnings("unchecked") Class<? extends Entity> typeClass = entity.getRaplaType().getTypeClass(); Entity persistantEntity = cache.tryResolve(entity.getId(), typeClass); return persistantEntity; } protected UpdateResult createUpdateResult( Map<Entity,Entity> oldEntities, Collection<Entity>updatedEntities, Collection<Entity>toRemove, TimeInterval invalidateInterval, String userId) throws EntityNotFoundException { User user = null; if (userId != null) { user = resolve(cache,userId, User.class); } UpdateResult result = new UpdateResult(user); if ( invalidateInterval != null) { result.setInvalidateInterval( invalidateInterval); } for (Entity toUpdate:updatedEntities) { Entity newEntity = toUpdate; Entity oldEntity = oldEntities.get(toUpdate); if (oldEntity != null) { result.addOperation(new UpdateResult.Change( newEntity, oldEntity)); } else { result.addOperation(new UpdateResult.Add( newEntity)); } } for (Entity entity:toRemove) { result.addOperation(new UpdateResult.Remove(entity)); } return result; } }
Java
package org.rapla.storage.impl.server; import java.util.Collection; import java.util.SortedSet; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; public interface AllocationMap { SortedSet<Appointment> getAppointments(Allocatable allocatable); Collection<Allocatable> getAllocatables(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.impl.server; import org.rapla.framework.Configuration; import org.rapla.framework.ConfigurationException; import org.rapla.framework.Container; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; import org.rapla.storage.CachableStorageOperator; import org.rapla.storage.CachableStorageOperatorCommand; import org.rapla.storage.ImportExportManager; import org.rapla.storage.LocalCache; /** Imports the content of on store into another. Export does an import with source and destination exchanged. <p>Configuration:</p> <pre> <importexport id="importexport" activation="request"> <source>raplafile</source> <dest>rapladb</dest> </importexport> </pre> */ public class ImportExportManagerImpl implements ImportExportManager { Container container; String sourceString; String destString; Logger logger; public ImportExportManagerImpl(RaplaContext context,Configuration configuration) throws RaplaException { this.logger = context.lookup( Logger.class); this.container = context.lookup( Container.class); try { sourceString = configuration.getChild("source").getValue(); destString = configuration.getChild("dest").getValue(); } catch (ConfigurationException e) { throw new RaplaException( e); } } protected Logger getLogger() { return logger.getChildLogger("importexport"); } /* Import the source into dest. */ public void doImport() throws RaplaException { Logger logger = getLogger(); logger.info("Import from " + sourceString + " into " + destString); CachableStorageOperator source = getSource(); source.connect(); CachableStorageOperator destination = getDestination(); doConvert(source,destination); logger.info("Import completed"); } /* Export the dest into source. */ public void doExport() throws RaplaException { Logger logger = getLogger(); logger.info("Export from " + destString + " into " + sourceString); CachableStorageOperator destination = getDestination(); destination.connect(); CachableStorageOperator source = getSource(); doConvert(destination,source); logger.info("Export completed"); } private void doConvert(final CachableStorageOperator cachableStorageOperator1,final CachableStorageOperator cachableStorageOperator2) throws RaplaException { cachableStorageOperator1.runWithReadLock( new CachableStorageOperatorCommand() { public void execute(LocalCache cache) throws RaplaException { cachableStorageOperator2.saveData(cache); } }); } @Override public CachableStorageOperator getSource() throws RaplaException { CachableStorageOperator lookup = container.lookup(CachableStorageOperator.class, sourceString); return lookup; } @Override public CachableStorageOperator getDestination() throws RaplaException { CachableStorageOperator lookup = container.lookup(CachableStorageOperator.class, destString); return lookup; } }
Java
package org.rapla.storage.impl.server; import java.util.HashSet; import java.util.Set; import org.rapla.entities.domain.Appointment; class AllocationChange { public Set<Appointment> toChange = new HashSet<Appointment>(); public Set<Appointment> toRemove= new HashSet<Appointment>(); public String toString() { return "toChange="+toChange.toString() + ";toRemove=" + toRemove.toString(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.impl.server; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TimeZone; import java.util.TreeSet; import java.util.UUID; import java.util.concurrent.locks.Lock; import org.rapla.components.util.Cancelable; import org.rapla.components.util.Command; import org.rapla.components.util.CommandScheduler; import org.rapla.components.util.DateTools; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.components.util.TimeInterval; import org.rapla.components.util.Tools; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.entities.Category; import org.rapla.entities.DependencyException; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.Named; import org.rapla.entities.Ownable; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.Timestamp; import org.rapla.entities.UniqueKeyException; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentStartComparator; import org.rapla.entities.domain.Permission; import org.rapla.entities.domain.RaplaObjectAnnotations; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.ResourceAnnotations; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.entities.dynamictype.internal.AttributeImpl; import org.rapla.entities.dynamictype.internal.ClassificationImpl; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.internal.ModifiableTimestamp; import org.rapla.entities.internal.UserImpl; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityReferencer.ReferenceInfo; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.RefEntity; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.facade.Conflict; import org.rapla.facade.RaplaComponent; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; import org.rapla.server.internal.TimeZoneConverterImpl; import org.rapla.storage.CachableStorageOperator; import org.rapla.storage.CachableStorageOperatorCommand; import org.rapla.storage.IdCreator; import org.rapla.storage.LocalCache; import org.rapla.storage.RaplaNewVersionException; import org.rapla.storage.RaplaSecurityException; import org.rapla.storage.UpdateEvent; import org.rapla.storage.UpdateOperation; import org.rapla.storage.UpdateResult; import org.rapla.storage.impl.AbstractCachableOperator; import org.rapla.storage.impl.EntityStore; public abstract class LocalAbstractCachableOperator extends AbstractCachableOperator implements Disposable, CachableStorageOperator, IdCreator { /** * set encryption if you want to enable password encryption. Possible values * are "sha" or "md5". */ private String encryption = "sha-1"; private ConflictFinder conflictFinder; private Map<String,SortedSet<Appointment>> appointmentMap; private SortedSet<Timestamp> timestampSet; private TimeZone systemTimeZone = TimeZone.getDefault(); private CommandScheduler scheduler; private Cancelable cleanConflictsTask; MessageDigest md; protected void addInternalTypes(LocalCache cache) throws RaplaException { { DynamicTypeImpl type = new DynamicTypeImpl(); String key = UNRESOLVED_RESOURCE_TYPE; type.setKey(key); type.setId( key); type.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{"+key + "}"); type.getName().setName("en", "anonymous"); type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON); type.setResolver( this); type.setReadOnly( ); cache.put( type); } { DynamicTypeImpl type = new DynamicTypeImpl(); String key = ANONYMOUSEVENT_TYPE; type.setKey(key); type.setId( key); type.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{"+key + "}"); type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION); type.getName().setName("en", "anonymous"); type.setResolver( this); cache.put( type); } { DynamicTypeImpl type = new DynamicTypeImpl(); String key = DEFAUTL_USER_TYPE; type.setKey(key); type.setId( key); type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE); //type.setAnnotation(DynamicTypeAnnotations.KEY_TRANSFERED_TO_CLIENT, DynamicTypeAnnotations.VALUE_TRANSFERED_TO_CLIENT_NEVER); addAttributeWithInternalId(type,"surname", AttributeType.STRING); addAttributeWithInternalId(type,"firstname", AttributeType.STRING); addAttributeWithInternalId(type,"email", AttributeType.STRING); type.setResolver( this); type.setReadOnly(); cache.put( type); } { DynamicTypeImpl type = new DynamicTypeImpl(); String key = PERIOD_TYPE; type.setKey(key); type.setId( key); type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE); type.setAnnotation(DynamicTypeAnnotations.KEY_TRANSFERED_TO_CLIENT, null); addAttributeWithInternalId(type,"name", AttributeType.STRING); addAttributeWithInternalId(type,"start", AttributeType.DATE); addAttributeWithInternalId(type,"end", AttributeType.DATE); type.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}"); type.setResolver( this); type.setReadOnly(); cache.put( type); } { DynamicTypeImpl type = new DynamicTypeImpl(); String key = SYNCHRONIZATIONTASK_TYPE; type.setKey(key); type.setId( key); type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE); type.setAnnotation(DynamicTypeAnnotations.KEY_TRANSFERED_TO_CLIENT, DynamicTypeAnnotations.VALUE_TRANSFERED_TO_CLIENT_NEVER); addAttributeWithInternalId(type,"objectId", AttributeType.STRING); addAttributeWithInternalId(type,"externalObjectId",AttributeType.STRING); addAttributeWithInternalId(type,"status",AttributeType.STRING); addAttributeWithInternalId(type,"retries", AttributeType.STRING); type.setResolver( this); type.setReadOnly(); cache.put( type); } } public LocalAbstractCachableOperator(RaplaContext context, Logger logger) throws RaplaException { super( context, logger); scheduler = context.lookup( CommandScheduler.class); try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RaplaException( e.getMessage() ,e); } } public void runWithReadLock(CachableStorageOperatorCommand cmd) throws RaplaException { Lock readLock = readLock(); try { cmd.execute( cache ); } finally { unlock( readLock); } } public List<Reservation> getReservations(User user, Collection<Allocatable> allocatables, Date start, Date end, ClassificationFilter[] filters,Map<String,String> annotationQuery) throws RaplaException { boolean excludeExceptions = false; HashSet<Reservation> reservationSet = new HashSet<Reservation>(); if (allocatables == null || allocatables.size() ==0) { allocatables = Collections.singleton( null); } for ( Allocatable allocatable: allocatables) { Lock readLock = readLock(); SortedSet<Appointment> appointments; try { appointments = getAppointments( allocatable); } finally { unlock( readLock); } SortedSet<Appointment> appointmentSet = AppointmentImpl.getAppointments(appointments,user,start,end, excludeExceptions); for (Appointment appointment:appointmentSet) { Reservation reservation = appointment.getReservation(); if ( !match(reservation, annotationQuery) ) { continue; } // Ignore Templates if not explicitly requested // FIXME this special case should be refactored, so one can get all reservations in one method else if ( RaplaComponent.isTemplate( reservation) && (annotationQuery == null || !annotationQuery.containsKey(RaplaObjectAnnotations.KEY_TEMPLATE) )) { continue; } if ( !reservationSet.contains( reservation)) { reservationSet.add( reservation ); } } } ArrayList<Reservation> result = new ArrayList<Reservation>(reservationSet); removeFilteredClassifications(result, filters); return result; } public boolean match(Reservation reservation, Map<String, String> annotationQuery) { if ( annotationQuery != null) { for (String key : annotationQuery.keySet()) { String annotationParam = annotationQuery.get( key); String annotation = reservation.getAnnotation( key); if ( annotation == null || annotationParam == null) { if (annotationParam!= null) { return false; } } else { if ( !annotation.equals(annotationParam)) { return false; } } } } return true; } public Collection<String> getTemplateNames() throws RaplaException { Lock readLock = readLock(); Collection<? extends Reservation> reservations; try { reservations = cache.getReservations(); } finally { unlock(readLock); } //Reservation[] reservations = cache.getReservations(user, start, end, filters.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY)); Set<String> templates = new LinkedHashSet<String>(); for ( Reservation r:reservations) { String templateName = r.getAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE); if ( templateName != null) { templates.add( templateName); } } return templates; } @Override public String createId(RaplaType raplaType) throws RaplaException { return UUID.randomUUID().toString(); } public String createId(RaplaType raplaType,String seed) throws RaplaException { byte[] data = new byte[16]; data = md.digest( seed.getBytes()); if ( data.length != 16 ) { throw new RaplaException("Wrong algorithm"); } data[6] &= 0x0f; /* clear version */ data[6] |= 0x40; /* set to version 4 */ data[8] &= 0x3f; /* clear variant */ data[8] |= 0x80; /* set to IETF variant */ long msb = 0; long lsb = 0; for (int i=0; i<8; i++) msb = (msb << 8) | (data[i] & 0xff); for (int i=8; i<16; i++) lsb = (lsb << 8) | (data[i] & 0xff); long mostSigBits = msb; long leastSigBits = lsb; UUID uuid = new UUID( mostSigBits, leastSigBits); return uuid.toString(); } public String[] createIdentifier(RaplaType raplaType, int count) throws RaplaException { String[] ids = new String[ count]; for ( int i=0;i<count;i++) { ids[i] = createId(raplaType); } return ids; } public Date today() { long time = getCurrentTimestamp().getTime(); long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time); Date raplaTime = new Date(time + offset); return DateTools.cutDate( raplaTime); } public Date getCurrentTimestamp() { long time = System.currentTimeMillis(); return new Date( time); } public void setTimeZone( TimeZone timeZone) { systemTimeZone = timeZone; } public TimeZone getTimeZone() { return systemTimeZone; } public String authenticate(String username, String password) throws RaplaException { Lock readLock = readLock(); try { getLogger().info("Check password for User " + username); User user = cache.getUser(username); if (user != null) { String userId = user.getId(); if (checkPassword(userId, password)) { return userId; } } getLogger().warn("Login failed for " + username); throw new RaplaSecurityException(i18n.getString("error.login")); } finally { unlock( readLock ); } } public boolean canChangePassword() throws RaplaException { return true; } public void changePassword(User user, char[] oldPassword,char[] newPassword) throws RaplaException { getLogger().info("Change password for User " + user.getUsername()); String userId = user.getId(); String password = new String(newPassword); if (encryption != null) password = encrypt(encryption, password); Lock writeLock = writeLock( ); try { cache.putPassword(userId, password); } finally { unlock( writeLock ); } User editObject = editObject(user, null); List<Entity> editList = new ArrayList<Entity>(1); editList.add(editObject); Collection<Entity>removeList = Collections.emptyList(); // synchronization will be done in the dispatch method storeAndRemove(editList, removeList, user); } public void changeName(User user, String title,String firstname, String surname) throws RaplaException { User editableUser = editObject(user, user); Allocatable personReference = editableUser.getPerson(); if (personReference == null) { editableUser.setName(surname); storeUser(editableUser); } else { Allocatable editablePerson = editObject(personReference, null); Classification classification = editablePerson.getClassification(); { Attribute attribute = classification.getAttribute("title"); if (attribute != null) { classification.setValue(attribute, title); } } { Attribute attribute = classification.getAttribute("firstname"); if (attribute != null) { classification.setValue(attribute, firstname); } } { Attribute attribute = classification.getAttribute("surname"); if (attribute != null) { classification.setValue(attribute, surname); } } ArrayList<Entity> arrayList = new ArrayList<Entity>(); arrayList.add(editableUser); arrayList.add(editablePerson); Collection<Entity> storeObjects = arrayList; Collection<Entity> removeObjects = Collections.emptySet(); // synchronization will be done in the dispatch method storeAndRemove(storeObjects, removeObjects, null); } } public void changeEmail(User user, String newEmail) throws RaplaException { User editableUser = user.isReadOnly() ? editObject(user, (User) user) : user; Allocatable personReference = editableUser.getPerson(); ArrayList<Entity>arrayList = new ArrayList<Entity>(); Collection<Entity>storeObjects = arrayList; Collection<Entity>removeObjects = Collections.emptySet(); storeObjects.add(editableUser); if (personReference == null) { editableUser.setEmail(newEmail); } else { Allocatable editablePerson = editObject(personReference, null); Classification classification = editablePerson.getClassification(); classification.setValue("email", newEmail); storeObjects.add(editablePerson); } storeAndRemove(storeObjects, removeObjects, null); } protected void resolveInitial(Collection<? extends Entity> entities,EntityResolver resolver) throws RaplaException { testResolve(entities); for (Entity entity: entities) { if ( entity instanceof EntityReferencer) { ((EntityReferencer)entity).setResolver(resolver); } } processUserPersonLink(entities); // It is important to do the read only later because some resolve might involve write to referenced objects for (Entity entity: entities) { ((RefEntity)entity).setReadOnly(); } } protected void processUserPersonLink(Collection<? extends Entity> entities) throws RaplaException { // resolve emails Map<String,Allocatable> resolvingMap = new HashMap<String,Allocatable>(); for (Entity entity: entities) { if ( entity instanceof Allocatable) { Allocatable allocatable = (Allocatable) entity; final Classification classification = allocatable.getClassification(); final Attribute attribute = classification.getAttribute("email"); if ( attribute != null) { final String email = (String)classification.getValue(attribute); if ( email != null ) { resolvingMap.put( email, allocatable); } } } } for ( Entity entity: entities) { if ( entity.getRaplaType().getTypeClass() == User.class) { User user = (User)entity; String email = user.getEmail(); if ( email != null && email.trim().length() > 0) { Allocatable person = resolvingMap.get(email); if ( person != null) { user.setPerson(person); } } } } } public void confirmEmail(User user, String newEmail) throws RaplaException { throw new RaplaException("Email confirmation must be done in the remotestorage class"); } public Collection<Conflict> getConflicts(User user) throws RaplaException { Lock readLock = readLock(); try { return conflictFinder.getConflicts( user); } finally { unlock( readLock ); } } boolean disposing; public void dispose() { // prevent reentrance in dispose synchronized ( this) { if ( disposing) { getLogger().warn("Disposing is called twice",new RaplaException("")); return; } disposing = true; } try { if ( cleanConflictsTask != null) { cleanConflictsTask.cancel(); } forceDisconnect(); } finally { disposing = false; } } protected void forceDisconnect() { try { disconnect(); } catch (Exception ex) { getLogger().error("Error during disconnect ", ex); } } /** performs Integrity constraints check */ protected void check(final UpdateEvent evt, final EntityStore store) throws RaplaException { Set<Entity> storeObjects = new HashSet<Entity>(evt.getStoreObjects()); //Set<Entity> removeObjects = new HashSet<Entity>(evt.getRemoveObjects()); checkConsistency(evt, store); checkUnique(evt,store); checkReferences(evt, store); checkNoDependencies(evt, store); checkVersions(storeObjects); } protected void updateLastChanged(UpdateEvent evt) throws RaplaException { Date currentTime = getCurrentTimestamp(); String userId = evt.getUserId(); User lastChangedBy = ( userId != null) ? resolve(userId,User.class) : null; for ( Entity e: evt.getStoreObjects()) { if ( e instanceof ModifiableTimestamp) { ModifiableTimestamp modifiableTimestamp = (ModifiableTimestamp)e; Date lastChangeTime = modifiableTimestamp.getLastChanged(); if ( lastChangeTime != null && lastChangeTime.equals( currentTime)) { // wait 1 ms to increase timestamp try { Thread.sleep(1); } catch (InterruptedException e1) { throw new RaplaException( e1.getMessage(), e1); } currentTime = getCurrentTimestamp(); } modifiableTimestamp.setLastChanged( currentTime); modifiableTimestamp.setLastChangedBy( lastChangedBy ); } } } class TimestampComparator implements Comparator<Timestamp> { public int compare(Timestamp o1, Timestamp o2) { if ( o1 == o2) { return 0; } Date d1 = o1.getLastChanged(); Date d2 = o2.getLastChanged(); // if d1 is null and d2 is not then d1 is before d2 if ( d1 == null && d2 != null ) { return -1; } // if d2 is null and d1 is not then d2 is before d1 if ( d1 != null && d2 == null) { return 1; } if ( d1 != null && d2 != null) { int result = d1.compareTo( d2); if ( result != 0) { return result; } } String id1 = (o1 instanceof Entity) ? ((Entity)o1).getId() : o1.toString(); String id2 = (o2 instanceof Entity) ? ((Entity)o2).getId() : o2.toString(); if ( id1 == null) { if ( id2 == null) { throw new IllegalStateException("Can't compare two entities without ids"); } else { return -1; } } else if ( id2 == null) { return 1; } return id1.compareTo( id2 ); } } protected void initIndizes() { timestampSet = new TreeSet<Timestamp>(new TimestampComparator()); timestampSet.addAll( cache.getDynamicTypes()); timestampSet.addAll( cache.getReservations()); timestampSet.addAll( cache.getAllocatables()); timestampSet.addAll( cache.getUsers()); // The appointment map appointmentMap = new HashMap<String, SortedSet<Appointment>>(); for ( Reservation r: cache.getReservations()) { for ( Appointment app:((ReservationImpl)r).getAppointmentList()) { Reservation reservation = app.getReservation(); Allocatable[] allocatables = reservation.getAllocatablesFor(app); { Collection<Appointment> list = getAndCreateList(appointmentMap,null); list.add( app); } for ( Allocatable alloc:allocatables) { Collection<Appointment> list = getAndCreateList(appointmentMap,alloc); list.add( app); } } } Date today2 = today(); AllocationMap allocationMap = new AllocationMap() { public SortedSet<Appointment> getAppointments(Allocatable allocatable) { return LocalAbstractCachableOperator.this.getAppointments(allocatable); } @SuppressWarnings("unchecked") public Collection<Allocatable> getAllocatables() { return (Collection)cache.getAllocatables(); } }; // The conflict map conflictFinder = new ConflictFinder(allocationMap, today2, getLogger(), this); long delay = DateTools.MILLISECONDS_PER_HOUR; long period = DateTools.MILLISECONDS_PER_HOUR; Command cleanUpConflicts = new Command() { @Override public void execute() throws Exception { removeOldConflicts(); } }; cleanConflictsTask = scheduler.schedule( cleanUpConflicts, delay, period); } /** updates the bindings of the resources and returns a map with all processed allocation changes*/ private void updateIndizes(UpdateResult result) { Map<Allocatable,AllocationChange> toUpdate = new HashMap<Allocatable,AllocationChange>(); List<Allocatable> removedAllocatables = new ArrayList<Allocatable>(); for (UpdateOperation operation: result.getOperations()) { Entity current = operation.getCurrent(); RaplaType raplaType = current.getRaplaType(); if ( raplaType == Reservation.TYPE ) { if ( operation instanceof UpdateResult.Remove) { Reservation old = (Reservation) current; for ( Appointment app: old.getAppointments() ) { updateBindings( toUpdate, old, app, true); } } if ( operation instanceof UpdateResult.Add) { Reservation newReservation = (Reservation) ((UpdateResult.Add) operation).getNew(); for ( Appointment app: newReservation.getAppointments() ) { updateBindings( toUpdate, newReservation,app, false); } } if ( operation instanceof UpdateResult.Change) { Reservation oldReservation = (Reservation) ((UpdateResult.Change) operation).getOld(); Reservation newReservation =(Reservation) ((UpdateResult.Change) operation).getNew(); Appointment[] oldAppointments = oldReservation.getAppointments(); for ( Appointment oldApp: oldAppointments) { updateBindings( toUpdate, oldReservation, oldApp, true); } Appointment[] newAppointments = newReservation.getAppointments(); for ( Appointment newApp: newAppointments) { updateBindings( toUpdate, newReservation, newApp, false); } } } if ( raplaType == Allocatable.TYPE ) { if ( operation instanceof UpdateResult.Remove) { Allocatable old = (Allocatable) current; removedAllocatables.add( old); } } if (raplaType == Allocatable.TYPE || raplaType == Reservation.TYPE || raplaType == DynamicType.TYPE || raplaType == User.TYPE || raplaType == Preferences.TYPE || raplaType == Category.TYPE ) { if ( operation instanceof UpdateResult.Remove) { Timestamp old = (Timestamp) current; timestampSet.remove( old); } if ( operation instanceof UpdateResult.Add) { Timestamp newEntity = (Timestamp) ((UpdateResult.Add) operation).getNew(); timestampSet.add( newEntity); } if ( operation instanceof UpdateResult.Change) { Timestamp newEntity = (Timestamp) ((UpdateResult.Change) operation).getNew(); Timestamp oldEntity = (Timestamp) ((UpdateResult.Change) operation).getOld(); timestampSet.remove( oldEntity); timestampSet.add( newEntity); } } } for ( Allocatable alloc: removedAllocatables) { SortedSet<Appointment> sortedSet = appointmentMap.get( alloc); if ( sortedSet != null && !sortedSet.isEmpty()) { getLogger().error("Removing non empty appointment map for resource " + alloc + " Appointments:" + sortedSet); } appointmentMap.remove( alloc); } Date today = today(); // processes the conflicts and adds the changes to the result conflictFinder.updateConflicts(toUpdate,result, today, removedAllocatables); checkAbandonedAppointments(); } @Override public Collection<Entity> getUpdatedEntities(final Date timestamp) throws RaplaException { Timestamp fromElement = new Timestamp() { @Override public User getLastChangedBy() { return null; } @Override public Date getLastChanged() { return timestamp; } @Override public Date getLastChangeTime() { return getLastChanged(); } @Override public Date getCreateTime() { return timestamp; } }; Lock lock = readLock(); Collection<Entity> result = new ArrayList<Entity>(); try { SortedSet<Timestamp> tailSet = timestampSet.tailSet(fromElement); for ( Timestamp entry : tailSet) { result.add( (Entity) entry ); } } finally { unlock(lock); } return result; } protected void updateBindings(Map<Allocatable, AllocationChange> toUpdate,Reservation reservation,Appointment app, boolean remove) { Set<Allocatable> allocatablesToProcess = new HashSet<Allocatable>(); allocatablesToProcess.add( null); if ( reservation != null) { Allocatable[] allocatablesFor = reservation.getAllocatablesFor( app); allocatablesToProcess.addAll( Arrays.asList(allocatablesFor)); // This double check is very imperformant and will be removed in the future, if it doesnt show in test runs // if ( remove) // { // Collection<Allocatable> allocatables = cache.getCollection(Allocatable.class); // for ( Allocatable allocatable:allocatables) // { // SortedSet<Appointment> appointmentSet = this.appointmentMap.get( allocatable.getId()); // if ( appointmentSet == null) // { // continue; // } // for (Appointment app1:appointmentSet) // { // if ( app1.equals( app)) // { // if ( !allocatablesToProcess.contains( allocatable)) // { // getLogger().error("Old reservation " + reservation.toString() + " has not the correct allocatable information. Using full search for appointment " + app + " and resource " + allocatable ) ; // allocatablesToProcess.add(allocatable); // } // } // } // } // } } else { getLogger().error("Appointment without reservation found " + app + " ignoring."); } for ( Allocatable allocatable: allocatablesToProcess) { AllocationChange updateSet; if ( allocatable != null) { updateSet = toUpdate.get( allocatable); if ( updateSet == null) { updateSet = new AllocationChange(); toUpdate.put(allocatable, updateSet); } } else { updateSet = null; } if ( remove) { Collection<Appointment> appointmentSet = getAndCreateList(appointmentMap,allocatable); // binary search could fail if the appointment has changed since the last add, which should not // happen as we only put and search immutable objects in the map. But the method is left here as a failsafe // with a log messaget if (!appointmentSet.remove( app)) { getLogger().error("Appointent has changed, so its not found in indexed binding map. Removing via full search"); // so we need to traverse all appointment Iterator<Appointment> it = appointmentSet.iterator(); while (it.hasNext()) { if (app.equals(it.next())) { it.remove(); break; } } } if ( updateSet != null) { updateSet.toRemove.add( app); } } else { SortedSet<Appointment> appointmentSet = getAndCreateList(appointmentMap, allocatable); appointmentSet.add(app); if ( updateSet != null) { updateSet.toChange.add( app); } } } } static final SortedSet<Appointment> EMPTY_SORTED_SET = Collections.unmodifiableSortedSet( new TreeSet<Appointment>()); protected SortedSet<Appointment> getAppointments(Allocatable allocatable) { String allocatableId = allocatable != null ? allocatable.getId() : null; SortedSet<Appointment> s = appointmentMap.get( allocatableId); if ( s == null) { return EMPTY_SORTED_SET; } return Collections.unmodifiableSortedSet(s); } private SortedSet<Appointment> getAndCreateList(Map<String,SortedSet<Appointment>> appointmentMap,Allocatable alloc) { String allocationId = alloc != null ? alloc.getId() : null; SortedSet<Appointment> set = appointmentMap.get( allocationId); if ( set == null) { set = new TreeSet<Appointment>(new AppointmentStartComparator()); appointmentMap.put(allocationId, set); } return set; } @Override protected UpdateResult update(UpdateEvent evt) throws RaplaException { UpdateResult update = super.update(evt); updateIndizes(update); return update; } public void removeOldConflicts() throws RaplaException { Map<Entity,Entity> oldEntities = new LinkedHashMap<Entity,Entity>(); Collection<Entity>updatedEntities = new LinkedHashSet<Entity>(); Collection<Entity>toRemove = new LinkedHashSet<Entity>(); TimeInterval invalidateInterval = null; String userId = null; UpdateResult result = createUpdateResult(oldEntities, updatedEntities, toRemove, invalidateInterval, userId); //Date today = getCurrentTimestamp(); Date today = today(); Lock readLock = readLock(); try { conflictFinder.removeOldConflicts(result, today); } finally { unlock( readLock); } fireStorageUpdated( result ); } protected void preprocessEventStorage(final UpdateEvent evt) throws RaplaException { EntityStore store = new EntityStore(this, this.getSuperCategory()); Collection<Entity>storeObjects = evt.getStoreObjects(); store.addAll(storeObjects); for (Entity entity:storeObjects) { if (getLogger().isDebugEnabled()) getLogger().debug("Contextualizing " + entity); ((EntityReferencer)entity).setResolver( store); // add all child categories to store if ( entity instanceof Category) { Set<Category> children = getAllCategories( (Category)entity); store.addAll(children); } } Collection<Entity>removeObjects = evt.getRemoveObjects(); store.addAll( removeObjects ); for ( Entity entity:removeObjects) { ((EntityReferencer)entity).setResolver( store); } // add transitve changes to event addClosure( evt, store ); // check event for inconsistencies check( evt, store); // update last changed date updateLastChanged( evt ); } /** * Create a closure for all objects that should be updated. The closure * contains all objects that are sub-entities of the entities and all * objects and all other objects that are affected by the update: e.g. * Classifiables when the DynamicType changes. The method will recursivly * proceed with all discovered objects. */ protected void addClosure(final UpdateEvent evt,EntityStore store) throws RaplaException { Collection<Entity> storeObjects = new ArrayList<Entity>(evt.getStoreObjects()); Collection<Entity> removeObjects = new ArrayList<Entity>(evt.getRemoveObjects()); for (Entity entity: storeObjects) { addStoreOperationsToClosure(evt, store,entity); } for (Entity entity: storeObjects) { // update old classifiables, that may not been update before via a change event // that could be the case if an old reservation is restored via undo but the dynamic type changed in between. // The undo cache does not notice the change in type if ( entity instanceof Classifiable && entity instanceof Timestamp) { Date lastChanged = ((Timestamp) entity).getLastChanged(); ClassificationImpl classification = (ClassificationImpl) ((Classifiable) entity).getClassification(); DynamicTypeImpl dynamicType = classification.getType(); Date typeLastChanged = dynamicType.getLastChanged(); if ( typeLastChanged != null && lastChanged != null && typeLastChanged.after( lastChanged)) { if (classification.needsChange(dynamicType)) { addChangedDependencies(evt, store, dynamicType, entity, false); } } } // TODO add conversion of classification filters or other dynamictypedependent that are stored in preferences // for (PreferencePatch patch:evt.getPreferencePatches()) // { // for (String key: patch.keySet()) // { // Object object = patch.get( key); // if ( object instanceof DynamicTypeDependant) // { // // } // } // } } for (Entity object: removeObjects) { addRemoveOperationsToClosure(evt, store, object); } Set<Entity> deletedCategories = getDeletedCategories(storeObjects); for (Entity entity: deletedCategories) { evt.putRemove(entity); } } protected void addStoreOperationsToClosure(UpdateEvent evt, EntityStore store,Entity entity) throws RaplaException { if (getLogger().isDebugEnabled() && !evt.getStoreObjects().contains(entity)) { getLogger().debug("Adding " + entity + " to store closure"); } evt.putStore(entity); if (DynamicType.TYPE == entity.getRaplaType()) { DynamicTypeImpl dynamicType = (DynamicTypeImpl) entity; addChangedDynamicTypeDependant(evt,store, dynamicType, false); } } private void addRemoveOperationsToClosure(UpdateEvent evt,EntityStore store,Entity entity) throws RaplaException { if (getLogger().isDebugEnabled() && !evt.getRemoveObjects().contains(entity)) { getLogger().debug("Adding " + entity + " to remove closure"); } evt.putRemove(entity); if (DynamicType.TYPE == entity.getRaplaType()) { DynamicTypeImpl dynamicType = (DynamicTypeImpl) entity; addChangedDynamicTypeDependant(evt, store,dynamicType, true); } // If entity is a user, remove the preference object if (User.TYPE == entity.getRaplaType()) { addRemovedUserDependant(evt, store,(User) entity); } } // protected void setCache(final LocalCache cache) { // super.setCache( cache); // if ( idTable == null) // { // idTable = new IdTable(); // } // idTable.setCache(cache); // } // protected void addChangedDynamicTypeDependant(UpdateEvent evt, EntityStore store,DynamicTypeImpl type, boolean toRemove) throws RaplaException { List<Entity> referencingEntities = getReferencingEntities( type, store); Iterator<Entity>it = referencingEntities.iterator(); while (it.hasNext()) { Entity entity = it.next(); if (!(entity instanceof DynamicTypeDependant)) { continue; } DynamicTypeDependant dependant = (DynamicTypeDependant) entity; // Classifiables need update? if (!dependant.needsChange(type) && !toRemove) continue; if (getLogger().isDebugEnabled()) getLogger().debug("Classifiable " + entity + " needs change!"); // Classifiables are allready on the store list addChangedDependencies(evt, store, type, entity, toRemove); } } private void addChangedDependencies(UpdateEvent evt,EntityStore store, DynamicTypeImpl type, Entity entity,boolean toRemove) throws EntityNotFoundException, RaplaException { DynamicTypeDependant dependant; if (evt.getStoreObjects().contains(entity)) { dependant = (DynamicTypeDependant) evt.findEntity(entity); } else { // no, then create a clone of the classfiable object and add to list User user = null; if (evt.getUserId() != null) { user = resolve(cache,evt.getUserId(), User.class); } @SuppressWarnings("unchecked") Class<Entity> entityType = entity.getRaplaType().getTypeClass(); Entity persistant = store.tryResolve(entity.getId(), entityType); dependant = (DynamicTypeDependant) editObject( entity, persistant, user); // replace or add the modified entity addStoreOperationsToClosure(evt, store,(Entity) dependant); } if (toRemove) { try { dependant.commitRemove(type); } catch (CannotExistWithoutTypeException ex) { // getLogger().warn(ex.getMessage(),ex); } } else { dependant.commitChange(type); } } protected void addRemovedUserDependant(UpdateEvent evt, EntityStore store,User user) throws RaplaException { PreferencesImpl preferences = cache.getPreferencesForUserId(user.getId()); if (preferences != null) { evt.putRemove(preferences); } List<Entity>referencingEntities = getReferencingEntities( user, store); Iterator<Entity>it = referencingEntities.iterator(); while (it.hasNext()) { Entity entity = it.next(); // Remove internal resources automatically if the owner is deleted if ( entity instanceof Classifiable && entity instanceof Ownable) { DynamicType type = ((Classifiable) entity).getClassification().getType(); if (((DynamicTypeImpl)type).isInternal()) { User owner = ((Ownable)entity).getOwner(); if ( owner != null && owner.equals( user)) { evt.putRemove( entity); continue; } } } if (entity instanceof Timestamp) { Timestamp timestamp = (Timestamp) entity; User lastChangedBy = timestamp.getLastChangedBy(); if ( lastChangedBy == null || !lastChangedBy.equals( user) ) { continue; } if ( entity instanceof Ownable ) { User owner = ((Ownable)entity).getOwner(); // we do nothing if the user is also owner, that dependencies need to be resolved manually if ( owner != null && owner.equals(user)) { continue; } } if (evt.getStoreObjects().contains(entity)) { ((SimpleEntity)evt.findEntity(entity)).setLastChangedBy(null); } else { @SuppressWarnings("unchecked") Class<? extends Entity> typeClass = entity.getRaplaType().getTypeClass(); Entity persistant= cache.tryResolve( entity.getId(), typeClass); Entity dependant = editObject( entity, persistant, user); ((SimpleEntity)dependant).setLastChangedBy( null ); addStoreOperationsToClosure(evt, store, dependant); } } } } /** * 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. * * @param entity */ final protected Set<Entity> getDependencies(Entity entity, EntityStore store) { RaplaType type = entity.getRaplaType(); final Collection<Entity>referencingEntities; if (Category.TYPE == type || DynamicType.TYPE == type || Allocatable.TYPE == type || User.TYPE == type) { HashSet<Entity> dependencyList = new HashSet<Entity>(); referencingEntities = getReferencingEntities(entity, store); dependencyList.addAll(referencingEntities); return dependencyList; } return Collections.emptySet(); } protected List<Entity> getReferencingEntities(Entity entity, EntityStore store) { List<Entity> result = new ArrayList<Entity>(); addReferers(cache.getReservations(), entity, result); addReferers(cache.getAllocatables(), entity, result); addReferers(cache.getUsers(), entity, result); addReferers(cache.getDynamicTypes(), entity, result); Iterable<Preferences> preferenceList = getPreferences(store); addReferers(preferenceList, entity, result); return result; } private Iterable<Preferences> getPreferences(EntityStore store) { List<Preferences> preferenceList = new ArrayList<Preferences>(); for ( User user:cache.getUsers()) { PreferencesImpl preferences = cache.getPreferencesForUserId( user.getId() ); if ( preferences != null) { preferenceList.add( preferences); } } PreferencesImpl systemPreferences = cache.getPreferencesForUserId( null); if ( systemPreferences != null) { preferenceList.add( systemPreferences ); } return preferenceList; } private void addReferers(Iterable<? extends Entity> refererList,Entity object, List<Entity> result) { for ( Entity referer: refererList) { if (referer != null && !referer.isIdentical(object) ) { for (ReferenceInfo info:((EntityReferencer)referer).getReferenceInfo()) { if (info.isReferenceOf(object) ) { result.add(referer); } } } } } private int countDynamicTypes(Collection<? extends RaplaObject> entities, String classificationType) throws RaplaException { Iterator<? extends RaplaObject> it = entities.iterator(); int count = 0; while (it.hasNext()) { RaplaObject entity = it.next(); if (DynamicType.TYPE != entity.getRaplaType()) continue; DynamicType type = (DynamicType) entity; String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); if ( annotation == null) { throw new RaplaException(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE + " not set for " + type); } if (annotation.equals( classificationType)) { count++; } } return count; } // Count dynamic-types to ensure that there is least one dynamic type left private void checkDynamicType(Collection<Entity>entities, String[] classificationTypes) throws RaplaException { int count = 0; for ( String classificationType: classificationTypes) { count += countDynamicTypes(entities, classificationType); } Collection<? extends DynamicType> allTypes = cache.getDynamicTypes(); int countAll = 0; for ( String classificationType: classificationTypes) { countAll = countDynamicTypes(allTypes, classificationType); } if (count >= 0 && count >= countAll) { throw new RaplaException(i18n.getString("error.one_type_requiered")); } } /** * Check if the references of each entity refers to an object in cache or in * the passed collection. */ final protected void checkReferences(UpdateEvent evt, EntityStore store) throws RaplaException { for (EntityReferencer entity: evt.getEntityReferences(false)) { for (ReferenceInfo info: entity.getReferenceInfo()) { String id = info.getId(); // Reference in cache or store? if (store.tryResolve(id, info.getType()) != null) continue; throw new EntityNotFoundException(i18n.format("error.reference_not_stored", info.getType() + ":" + id)); } } } /** * 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(final UpdateEvent evt, final EntityStore store) throws RaplaException { for (Entity entity : evt.getStoreObjects()) { String name = ""; Entity entity2 = null; if (DynamicType.TYPE == entity.getRaplaType()) { DynamicType type = (DynamicType) entity; name = type.getKey(); entity2 = (Entity) store.getDynamicType(name); if (entity2 != null && !entity2.equals(entity)) throwNotUnique(name); } if (Category.TYPE == 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(key); } } } } if (User.TYPE == entity.getRaplaType()) { name = ((User) entity).getUsername(); if (name == null || name.trim().length() == 0) { String message = i18n.format("error.no_entry_for", getString("username")); throw new RaplaException(message); } // FIXME Replace with store.getUser for the rare case that two users with the same username are stored in one operation entity2 = cache.getUser(name); if (entity2 != null && !entity2.equals(entity)) throwNotUnique(name); } } } private void throwNotUnique(String name) throws UniqueKeyException { throw new UniqueKeyException(i18n.format("error.not_unique", name)); } /** * 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<Entity>entities) throws RaplaException { for (Entity entity: entities) { // Check Versions Entity persistantVersion = findPersistant(entity); // If the entities are newer, everything is o.k. if (persistantVersion != null && persistantVersion != entity) { if (( persistantVersion instanceof Timestamp)) { Date lastChangeTimePersistant = ((Timestamp)persistantVersion).getLastChanged(); Date lastChangeTime = ((Timestamp)entity).getLastChanged(); if ( lastChangeTimePersistant != null && lastChangeTime != null && lastChangeTimePersistant.after( lastChangeTime) ) { getLogger().warn( "There is a newer version for: " + entity.getId() + " stored version :" + SerializableDateTimeFormat.INSTANCE.formatTimestamp(lastChangeTimePersistant) + " version to store :" + SerializableDateTimeFormat.INSTANCE.formatTimestamp(lastChangeTime)); throw new RaplaNewVersionException(getI18n().format( "error.new_version", entity.toString())); } } } } } /** Check if the objects are consistent, so that they can be safely stored. */ protected void checkConsistency(UpdateEvent evt, EntityStore store) throws RaplaException { for (EntityReferencer referencer : evt.getEntityReferences(false)) { for (ReferenceInfo referenceInfo:referencer.getReferenceInfo()) { Entity reference = store.resolve( referenceInfo.getId(), referenceInfo.getType()); if (reference instanceof Preferences || reference instanceof Conflict || reference instanceof Reservation || reference instanceof Appointment ) { throw new RaplaException("The current version of Rapla doesn't allow references to objects of type " + reference.getRaplaType()); } } } for (Entity entity : evt.getStoreObjects()) { CategoryImpl superCategory = store.getSuperCategory(); if (Category.TYPE == entity.getRaplaType()) { if (entity.equals(superCategory)) { // Check if the user group is missing 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 { // check if the category to be stored has a parent Category category = (Category) entity; Category parent = category.getParent(); if (parent == null) { throw new RaplaException("The category " + category + " needs a parent."); } else { int i = 0; while ( true) { if ( parent == null) { throw new RaplaException("Category needs to be a child of super category."); } else if ( parent.equals( superCategory)) { break; } parent = parent.getParent(); i++; if ( i>80) { throw new RaplaException("infinite recursion detection for category " + category); } } } } } } } protected void checkNoDependencies(final UpdateEvent evt, final EntityStore store) throws RaplaException { Collection<Entity> removeEntities = evt.getRemoveObjects(); Collection<Entity> storeObjects = new HashSet<Entity>(evt.getStoreObjects()); HashSet<Entity> dep = new HashSet<Entity>(); Set<Entity> deletedCategories = getDeletedCategories(storeObjects); IteratorChain<Entity> iteratorChain = new IteratorChain<Entity>( deletedCategories,removeEntities); for (Entity entity : iteratorChain) { // First we add the dependencies from the stored object list for (Entity obj : storeObjects) { if ( obj instanceof EntityReferencer) { if (isRefering((EntityReferencer)obj, entity )) { dep.add(obj); } } } // we check if the user deletes himself if ( entity instanceof User) { String eventUserId = evt.getUserId(); if (eventUserId != null && eventUserId.equals( entity.getId())) { List<String> emptyList = Collections.emptyList(); throw new DependencyException("User can't delete himself", emptyList); } } // Than we add the dependencies from the cache. It is important that // we don't add the dependencies from the stored object list here, // because a dependency could be removed in a stored object Set<Entity> dependencies = getDependencies(entity, store); for (Entity dependency : dependencies) { if (!storeObjects.contains(dependency) && !removeEntities.contains( dependency)) { // only add the first 21 dependencies; if (dep.size() > MAX_DEPENDENCY ) { break; } dep.add(dependency); } } } // CKO We skip this check as the admin should have the possibility to deny a user read to allocatables objects even if he has reserved it prior // for (Entity entity : storeObjects) { // if ( entity.getRaplaType() == Allocatable.TYPE) // { // Allocatable alloc = (Allocatable) entity; // for (Entity reference:getDependencies(entity)) // { // if ( reference instanceof Ownable) // { // User user = ((Ownable) reference).getOwner(); // if (user != null && !alloc.canReadOnlyInformation(user)) // { // throw new DependencyException( "User " + user.getUsername() + " refers to " + getName(alloc) + ". Read permission is required.", Collections.singleton( getDependentName(reference))); // } // } // } // } // } if (dep.size() > 0) { Collection<String> names = new ArrayList<String>(); for (Entity obj: dep) { String string = getDependentName(obj); names.add(string); } throw new DependencyException(getString("error.dependencies"),names.toArray( new String[]{})); } // Count dynamic-types to ensure that there is least one dynamic type // for reservations and one for resources or persons checkDynamicType(removeEntities, new String[] {DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION}); checkDynamicType(removeEntities, new String[] {DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE,DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON}); } private boolean isRefering(EntityReferencer referencer, Entity entity) { for (ReferenceInfo info : referencer.getReferenceInfo()) { if ( info.isReferenceOf(entity)) { return true; } } return false; } private Set<Entity> getDeletedCategories(Iterable<Entity> storeObjects) { Set<Entity> deletedCategories = new HashSet<Entity>(); for (Entity entity : storeObjects) { if ( entity.getRaplaType() == Category.TYPE) { Category newCat = (Category) entity; Category old = tryResolve(entity.getId(), Category.class); if ( old != null) { Set<Category> oldSet = getAllCategories( old); Set<Category> newSet = getAllCategories( newCat); oldSet.removeAll( newSet); deletedCategories.addAll( oldSet ); } } } return deletedCategories; } private Set<Category> getAllCategories(Category old) { HashSet<Category> result = new HashSet<Category>(); result.add( old); for (Category child : old.getCategories()) { result.addAll( getAllCategories(child)); } return result; } protected String getDependentName(Entity obj) { StringBuffer buf = new StringBuffer(); if (obj instanceof Reservation) { buf.append(getString("reservation")); } else if (obj instanceof Preferences) { buf.append(getString("preferences")); } else if (obj instanceof Category) { buf.append(getString("categorie")); } else if (obj instanceof Allocatable) { buf.append(getString("resources_persons")); } else if (obj instanceof User) { buf.append(getString("user")); } else if (obj instanceof DynamicType) { buf.append(getString("dynamictype")); } if (obj instanceof Named) { Locale locale = i18n.getLocale(); final String string = ((Named) obj).getName(locale); buf.append(": " + string); } else { buf.append(obj.toString()); } if (obj instanceof Reservation) { Reservation reservation = (Reservation)obj; Appointment[] appointments = reservation.getAppointments(); if ( appointments.length > 0) { buf.append(" "); Date start = appointments[0].getStart(); buf.append(raplaLocale.formatDate(start)); } String template = reservation.getAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE); if ( template != null) { buf.append(" in template " + template); } } final Object idFull = obj.getId(); if (idFull != null) { String idShort = idFull.toString(); int dot = idShort.lastIndexOf('.'); buf.append(" (" + idShort.substring(dot + 1) + ")"); } String string = buf.toString(); return string; } private void storeUser(User refUser) throws RaplaException { ArrayList<Entity> arrayList = new ArrayList<Entity>(); arrayList.add(refUser); Collection<Entity> storeObjects = arrayList; Collection<Entity> removeObjects = Collections.emptySet(); storeAndRemove(storeObjects, removeObjects, null); } protected String encrypt(String encryption, String password) throws RaplaException { MessageDigest md; try { md = MessageDigest.getInstance(encryption); } catch (NoSuchAlgorithmException ex) { throw new RaplaException(ex); } synchronized (md) { md.reset(); md.update(password.getBytes()); return encryption + ":" + Tools.convert(md.digest()); } } private boolean checkPassword(String userId, String password) throws RaplaException { if (userId == null) return false; String correct_pw = cache.getPassword(userId); if (correct_pw == null) { return false; } if (correct_pw.equals(password)) { return true; } int columIndex = correct_pw.indexOf(":"); if (columIndex > 0 && correct_pw.length() > 20) { String encryptionGuess = correct_pw.substring(0, columIndex); if (encryptionGuess.contains("sha") || encryptionGuess.contains("md5")) { password = encrypt(encryptionGuess, password); if (correct_pw.equals(password)) { return true; } } } return false; } @Override public Map<Allocatable,Collection<Appointment>> getFirstAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException { Lock readLock = readLock(); Map<Allocatable, Map<Appointment, Collection<Appointment>>> allocatableBindings; try { allocatableBindings = getAllocatableBindings(allocatables, appointments, ignoreList,true); } finally { unlock( readLock); } Map<Allocatable, Collection<Appointment>> map = new HashMap<Allocatable, Collection<Appointment>>(); for ( Map.Entry<Allocatable, Map<Appointment, Collection<Appointment>>> entry: allocatableBindings.entrySet()) { Allocatable alloc = entry.getKey(); Collection<Appointment> list = entry.getValue().keySet(); map.put( alloc, list); } return map; } @Override public Map<Allocatable, Map<Appointment,Collection<Appointment>>> getAllAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException { Lock readLock = readLock(); try { return getAllocatableBindings( allocatables, appointments, ignoreList, false); } finally { unlock( readLock ); } } public Map<Allocatable, Map<Appointment,Collection<Appointment>>> getAllocatableBindings(Collection<Allocatable> allocatables,Collection<Appointment> appointments, Collection<Reservation> ignoreList, boolean onlyFirstConflictingAppointment) { Map<Allocatable, Map<Appointment,Collection<Appointment>>> map = new HashMap<Allocatable, Map<Appointment,Collection<Appointment>>>(); for ( Allocatable allocatable:allocatables) { String annotation = allocatable.getAnnotation( ResourceAnnotations.KEY_CONFLICT_CREATION); boolean holdBackConflicts = annotation != null && annotation.equals( ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE); if ( holdBackConflicts) { continue; } SortedSet<Appointment> appointmentSet = getAppointments( allocatable); if ( appointmentSet == null) { continue; } map.put(allocatable, new HashMap<Appointment,Collection<Appointment>>() ); for (Appointment appointment:appointments) { Set<Appointment> conflictingAppointments = AppointmentImpl.getConflictingAppointments(appointmentSet, appointment, ignoreList, onlyFirstConflictingAppointment); if ( conflictingAppointments.size() > 0) { Map<Appointment,Collection<Appointment>> appMap = map.get( allocatable); if ( appMap == null) { appMap = new HashMap<Appointment, Collection<Appointment>>(); map.put( allocatable, appMap); } appMap.put( appointment, conflictingAppointments); } } } return map; } @Override public Date getNextAllocatableDate(Collection<Allocatable> allocatables,Appointment appointment,Collection<Reservation> ignoreList,Integer worktimeStartMinutes,Integer worktimeEndMinutes, Integer[] excludedDays, Integer rowsPerHour) throws RaplaException { Lock readLock = readLock(); try { Appointment newState = appointment; Date firstStart = appointment.getStart(); boolean startDateExcluded = isExcluded(excludedDays, firstStart); boolean wholeDay = appointment.isWholeDaysSet(); boolean inWorktime = inWorktime(appointment, worktimeStartMinutes,worktimeEndMinutes); if ( rowsPerHour == null || rowsPerHour <=1) { rowsPerHour = 1; } for ( int i=0;i<366*24 *rowsPerHour ;i++) { newState = ((AppointmentImpl) newState).clone(); Date start = newState.getStart(); long millisToAdd = wholeDay ? DateTools.MILLISECONDS_PER_DAY : (DateTools.MILLISECONDS_PER_HOUR / rowsPerHour ); Date newStart = new Date(start.getTime() + millisToAdd); if (!startDateExcluded && isExcluded(excludedDays, newStart)) { continue; } newState.move( newStart ); if ( !wholeDay && inWorktime && !inWorktime(newState, worktimeStartMinutes, worktimeEndMinutes)) { continue; } if (!isAllocated(allocatables, newState, ignoreList)) { return newStart; } } return null; } finally { unlock( readLock ); } } private boolean inWorktime(Appointment appointment, Integer worktimeStartMinutes, Integer worktimeEndMinutes) { long start = appointment.getStart().getTime(); int minuteOfDayStart = DateTools.getMinuteOfDay( start ); long end = appointment.getEnd().getTime(); int minuteOfDayEnd = DateTools.getMinuteOfDay( end ) + (int) DateTools.countDays(start, end) * 24 * 60; boolean inWorktime = (worktimeStartMinutes == null || worktimeStartMinutes<= minuteOfDayStart) && ( worktimeEndMinutes == null || worktimeEndMinutes >= minuteOfDayEnd); return inWorktime; } private boolean isExcluded(Integer[] excludedDays, Date date) { Integer weekday = DateTools.getWeekday( date); if (excludedDays != null) { for ( Integer day:excludedDays) { if ( day.equals( weekday)) { return true; } } } return false; } private boolean isAllocated(Collection<Allocatable> allocatables, Appointment appointment, Collection<Reservation> ignoreList) throws RaplaException { Map<Allocatable, Collection<Appointment>> firstAllocatableBindings = getFirstAllocatableBindings(allocatables, Collections.singleton( appointment) , ignoreList); for (Map.Entry<Allocatable, Collection<Appointment>> entry: firstAllocatableBindings.entrySet()) { if (entry.getValue().size() > 0) { return true; } } return false; } public Collection<Entity> getVisibleEntities(final User user)throws RaplaException { Lock readLock = readLock(); try { return cache.getVisibleEntities(user); } finally { unlock(readLock); } } // this check is only there to detect rapla bugs in the conflict api and can be removed if it causes performance issues private void checkAbandonedAppointments() { Collection<? extends Allocatable> allocatables = cache.getAllocatables(); Logger logger = getLogger().getChildLogger("appointmentcheck"); try { for ( Allocatable allocatable:allocatables) { SortedSet<Appointment> appointmentSet = this.appointmentMap.get( allocatable.getId()); if ( appointmentSet == null) { continue; } for (Appointment app:appointmentSet) { { SimpleEntity original = (SimpleEntity)app; String id = original.getId(); if ( id == null ) { logger.error( "Empty id for " + original); continue; } Appointment persistant = cache.tryResolve( id, Appointment.class ); if ( persistant == null ) { logger.error( "appointment not stored in cache " + original ); continue; } } Reservation reservation = app.getReservation(); if (reservation == null) { logger.error("Appointment without a reservation stored in cache " + app ); appointmentSet.remove( app); continue; } else if (!reservation.hasAllocated( allocatable, app)) { logger.error("Allocation is not stored correctly for " + reservation + " " + app + " " + allocatable + " removing binding for " + app); appointmentSet.remove( app); continue; } else { { Reservation original = reservation; String id = original.getId(); if ( id == null ) { logger.error( "Empty id for " + original); continue; } Reservation persistant = cache.tryResolve( id, Reservation.class ); if ( persistant != null ) { Date lastChanged = original.getLastChanged(); Date persistantLastChanged = persistant.getLastChanged(); if (persistantLastChanged != null && !persistantLastChanged.equals(lastChanged)) { logger.error( "Reservation stored in cache is not the same as in allocation store " + original ); continue; } } else { logger.error( "Reservation not stored in cache " + original + " removing binding for " + app); appointmentSet.remove( app); continue; } } } } } } catch (Exception ex) { logger.error(ex.getMessage(), ex); } } protected void createDefaultSystem(LocalCache cache) throws RaplaException { EntityStore store = new EntityStore( null, cache.getSuperCategory() ); DynamicTypeImpl resourceType = newDynamicType(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE,"resource"); setName(resourceType.getName(), "resource"); add(store, resourceType); DynamicTypeImpl personType = newDynamicType(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON,"person"); setName(personType.getName(), "person"); add(store, personType); DynamicTypeImpl eventType = newDynamicType(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION, "event"); setName(eventType.getName(), "event"); add(store, eventType); String[] userGroups = new String[] {Permission.GROUP_REGISTERER_KEY, Permission.GROUP_MODIFY_PREFERENCES_KEY,Permission.GROUP_CAN_READ_EVENTS_FROM_OTHERS, Permission.GROUP_CAN_CREATE_EVENTS, Permission.GROUP_CAN_EDIT_TEMPLATES}; Date now = getCurrentTimestamp(); CategoryImpl groupsCategory = new CategoryImpl(now,now); groupsCategory.setKey("user-groups"); setName( groupsCategory.getName(), groupsCategory.getKey()); setNew( groupsCategory); store.put( groupsCategory); for ( String catName: userGroups) { CategoryImpl group = new CategoryImpl(now,now); group.setKey( catName); setNew(group); setName( group.getName(), group.getKey()); groupsCategory.addCategory( group); store.put( group); } cache.getSuperCategory().addCategory( groupsCategory); UserImpl admin = new UserImpl(now,now); admin.setUsername("admin"); admin.setAdmin( true); setNew(admin); store.put( admin); Collection<Entity> list = store.getList(); cache.putAll( list ); testResolve( list); setResolver( list); UserImpl user = cache.getUser("admin"); String password =""; cache.putPassword( user.getId(), password ); cache.getSuperCategory().setReadOnly(); AllocatableImpl allocatable = new AllocatableImpl(now, now); allocatable.setResolver( this); allocatable.addPermission(allocatable.newPermission()); Classification classification = cache.getDynamicType("resource").newClassification(); allocatable.setClassification(classification); setNew(allocatable); classification.setValue("name", getString("test_resource")); allocatable.setOwner( user); cache.put( allocatable); } private void add(EntityStore list, DynamicTypeImpl type) { list.put( type); for (Attribute att:type.getAttributes()) { list.put((Entity) att); } } private Attribute createStringAttribute(String key, String name) throws RaplaException { Attribute attribute = newAttribute(AttributeType.STRING, null); attribute.setKey(key); setName(attribute.getName(), name); return attribute; } private void addAttributeWithInternalId(DynamicType dynamicType,String key, AttributeType type) throws RaplaException { String id = "rapla_"+ dynamicType.getKey() + "_" +key; Attribute attribute = newAttribute(type, id); attribute.setKey(key); setName(attribute.getName(), key); dynamicType.addAttribute( attribute); } private DynamicTypeImpl newDynamicType(String classificationType, String key) throws RaplaException { DynamicTypeImpl dynamicType = new DynamicTypeImpl(); dynamicType.setAnnotation("classification-type", classificationType); dynamicType.setKey(key); setNew(dynamicType); if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE)) { dynamicType.addAttribute(createStringAttribute("name", "name")); dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}"); dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS,"automatic"); } else if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)) { dynamicType.addAttribute(createStringAttribute("name","eventname")); dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}"); dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS, null); } else if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON)) { dynamicType.addAttribute(createStringAttribute("surname", "surname")); dynamicType.addAttribute(createStringAttribute("firstname", "firstname")); dynamicType.addAttribute(createStringAttribute("email", "email")); dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT, "{surname} {firstname}"); dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS, null); } dynamicType.setResolver( this); return dynamicType; } private Attribute newAttribute(AttributeType attributeType,String id) throws RaplaException { AttributeImpl attribute = new AttributeImpl(attributeType); if ( id == null) { setNew(attribute); } else { ((RefEntity)attribute).setId(id); } attribute.setResolver( this); return attribute; } private <T extends Entity> void setNew(T entity) throws RaplaException { RaplaType raplaType = entity.getRaplaType(); String id = createIdentifier(raplaType,1)[0]; ((RefEntity)entity).setId(id); } private void setName(MultiLanguageName name, String to) { String currentLang = i18n.getLang(); name.setName("en", to); try { String translation = i18n.getString( to); name.setName(currentLang, translation); } catch (Exception ex) { } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.impl.server; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.rapla.components.util.DateTools; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.AppointmentBlockEndComparator; import org.rapla.entities.domain.AppointmentBlockStartComparator; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.ResourceAnnotations; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.storage.EntityResolver; import org.rapla.facade.Conflict; import org.rapla.facade.RaplaComponent; import org.rapla.facade.internal.ConflictImpl; import org.rapla.framework.logger.Logger; import org.rapla.storage.UpdateResult; import org.rapla.storage.UpdateResult.Change; class ConflictFinder { AllocationMap allocationMap; Map<Allocatable,Set<Conflict>> conflictMap; Logger logger; EntityResolver resolver; public ConflictFinder( AllocationMap allocationMap, Date today, Logger logger, EntityResolver resolver) { this.logger = logger; this.allocationMap = allocationMap; conflictMap = new HashMap<Allocatable, Set<Conflict>>(); long startTime = System.currentTimeMillis(); int conflictSize = 0; for (Allocatable allocatable:allocationMap.getAllocatables()) { Set<Conflict> conflictList = Collections.emptySet(); Set<Conflict> newConflicts = updateConflicts(allocatable, null, today, conflictList); conflictMap.put( allocatable, newConflicts); conflictSize+= newConflicts.size(); } logger.info("Conflict initialization found " + conflictSize + " conflicts and took " + (System.currentTimeMillis()- startTime) + "ms. " ); this.resolver = resolver; } private Set<Conflict> updateConflicts(Allocatable allocatable,AllocationChange change, Date today, Set<Conflict> oldList ) { if ( isConflictIgnored(allocatable)) { return Collections.emptySet(); } Set<Appointment> allAppointments = allocationMap.getAppointments(allocatable); Set<Appointment> changedAppointments; Set<Appointment> removedAppointments; if ( change == null) { changedAppointments = allAppointments; removedAppointments = new TreeSet<Appointment>(); } else { changedAppointments = change.toChange; removedAppointments = change.toRemove; } Set<String> foundConflictIds = new HashSet<String>(); Set<Conflict> conflictList = new HashSet<Conflict>( );//conflictMap.get(allocatable); { Set<String> idList1 = getIds( removedAppointments); Set<String> idList2 = getIds( changedAppointments); for ( Conflict conflict:oldList) { if (endsBefore(conflict, today) || contains(conflict, idList1) || contains(conflict, idList2)) { continue; } conflictList.add( conflict ); } } { SortedSet<AppointmentBlock> allAppointmentBlocksSortedByStartDescending = null;//new TreeSet<AppointmentBlock>(new InverseComparator<AppointmentBlock>(new AppointmentBlockStartComparator())); SortedSet<AppointmentBlock> allAppointmentBlocks = createBlocks(today,allAppointments, new AppointmentBlockEndComparator(), allAppointmentBlocksSortedByStartDescending); SortedSet<AppointmentBlock> appointmentBlocks = createBlocks(today,changedAppointments, new AppointmentBlockStartComparator(), null); // Check the conflicts for each time block for (AppointmentBlock appBlock:appointmentBlocks) { final Appointment appointment1 = appBlock.getAppointment(); long start = appBlock.getStart(); long end = appBlock.getEnd(); /* * Shrink the set of all time blocks down to those with a start date which is * later than or equal to the start date of the block */ AppointmentBlock compareBlock = new AppointmentBlock(start, start, appointment1,false); final SortedSet<AppointmentBlock> tailSet = allAppointmentBlocks.tailSet(compareBlock); // Check all time blocks which start after or at the same time as the block which is being checked for (AppointmentBlock appBlock2:tailSet) { // If the start date of the compared block is after the end date of the block, skip the appointment if (appBlock2.getStart() > end) { break; } final Appointment appointment2 = appBlock2.getAppointment(); // we test that in the next step if ( appBlock == appBlock2 || appBlock2.includes( appBlock) || appointment1.equals( appointment2) ) { continue; } // Check if the corresponding appointments of both blocks overlap each other if (!appointment2.equals( appointment1) && appointment2.overlaps(appointment1)) { String id = ConflictImpl.createId(allocatable.getId(), appointment1.getId(), appointment2.getId()); if ( foundConflictIds.contains(id )) { continue; } // Add appointments to conflict list if (ConflictImpl.isConflictWithoutCheck(appointment1, appointment2, today)) { final ConflictImpl conflict = new ConflictImpl(allocatable,appointment1, appointment2, today, id); conflictList.add(conflict); foundConflictIds.add( id); } } } // we now need to check overlaps with appointments that start before and end after the appointment //AppointmentBlock compareBlock2 = new AppointmentBlock(end, end, appointment1,false); //SortedSet<AppointmentBlock> descending = allAppointmentBlocksSortedByStartDescending.tailSet(compareBlock); for (AppointmentBlock appBlock2:tailSet) { final Appointment appointment2 = appBlock2.getAppointment(); if ( appBlock == appBlock2 || !appBlock2.includes( appBlock) || appointment2.equals( appointment1) ) { continue; } String id = ConflictImpl.createId(allocatable.getId(), appointment1.getId(), appointment2.getId()); if ( foundConflictIds.contains(id )) { continue; } if (ConflictImpl.isConflictWithoutCheck(appointment1, appointment2, today)) { final ConflictImpl conflict = new ConflictImpl(allocatable,appointment1, appointment2, today, id); conflictList.add(conflict); foundConflictIds.add( id); } } } } if ( conflictList.isEmpty()) { return Collections.emptySet(); } return conflictList; } public Set<String> getIds(Collection<? extends Entity> list) { if ( list.isEmpty()) { return Collections.emptySet(); } Set<String> idList = new HashSet<String>(); for ( Entity entity:list) { idList.add( entity.getId()); } return idList; } private boolean isConflictIgnored(Allocatable allocatable) { String annotation = allocatable.getAnnotation(ResourceAnnotations.KEY_CONFLICT_CREATION); if ( annotation != null && annotation.equals(ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE)) { return true; } return false; } private boolean contains(Conflict conflict, Set<String> idList) { String appointment1 = conflict.getAppointment1(); String appointment2 = conflict.getAppointment2(); return( idList.contains( appointment1) || idList.contains( appointment2)); } private SortedSet<AppointmentBlock> createBlocks(Date today, Set<Appointment> appointmentSet,final Comparator<AppointmentBlock> comparator, SortedSet<AppointmentBlock> additionalSet) { // overlaps will be checked 260 weeks (5 years) from now on long maxCheck = System.currentTimeMillis() + DateTools.MILLISECONDS_PER_WEEK * 260; // Create a new set of time blocks, ordered by their start dates SortedSet<AppointmentBlock> allAppointmentBlocks = new TreeSet<AppointmentBlock>(comparator); if ( appointmentSet.isEmpty()) { return allAppointmentBlocks; } //Appointment last = appointmentSet.last(); // Get all time blocks of all appointments for (Appointment appointment:appointmentSet) { // Get the end date of the appointment (if repeating, end date of last occurence) Date maxEnd = appointment.getMaxEnd(); // Check if the appointment is repeating forever if ( maxEnd == null || maxEnd.getTime() > maxCheck) { // If the repeating has no end, set the end to the start of the last appointment in the set + 100 weeks (~2 years) maxEnd = new Date(maxCheck); } if ( maxEnd.before( today)) { continue; } if ( RaplaComponent.isTemplate(appointment.getReservation())) { continue; } Reservation r1 = appointment.getReservation(); DynamicType type1 = r1 != null ? r1.getClassification().getType() : null; String annotation1 = ConflictImpl.getConflictAnnotation( type1); if ( ConflictImpl.isNoConflicts( annotation1 ) ) { continue; } /* * If the appointment has a repeating, get all single time blocks of it. If it is no * repeating, this will just create one block, which is equal to the appointment * itself. */ Date start = appointment.getStart(); if ( start.before( today)) { start = today; } ((AppointmentImpl)appointment).createBlocks(start, DateTools.fillDate(maxEnd), allAppointmentBlocks,additionalSet); } return allAppointmentBlocks; } /** * Determines all conflicts which occur after a given start date. * if user is passed then only returns conflicts the user can modify * * @param allocatables */ public Collection<Conflict> getConflicts( User user) { Collection<Conflict> conflictList = new HashSet<Conflict>(); for ( Allocatable allocatable: conflictMap.keySet()) { Set<Conflict> set = conflictMap.get( allocatable); if ( set != null) { for ( Conflict conflict: set) { if (ConflictImpl.canModify(conflict,user,resolver)) { conflictList.add(conflict); } } } } return conflictList; } private boolean endsBefore(Conflict conflict,Date date ) { Appointment appointment1 = getAppointment( conflict.getAppointment1()); Appointment appointment2 = getAppointment( conflict.getAppointment2()); if ( appointment1 == null || appointment2 == null) { return false; } boolean result = ConflictImpl.endsBefore( appointment1, appointment2, date); return result; } private Appointment getAppointment(String id) { return resolver.tryResolve(id, Appointment.class); } public void updateConflicts(Map<Allocatable, AllocationChange> toUpdate,UpdateResult evt, Date today,Collection<Allocatable> removedAllocatables) { Iterator<Change> it = evt.getOperations(UpdateResult.Change.class); while (it.hasNext()) { Change next = it.next(); RaplaObject current = next.getNew(); if ( current.getRaplaType() == Allocatable.TYPE) { Allocatable old = (Allocatable) next.getOld(); Allocatable newAlloc = (Allocatable) next.getNew(); if ( old != null && newAlloc != null ) { if (isConflictIgnored(old) != isConflictIgnored(newAlloc)) { // add an recalculate all if holdbackconflicts changed toUpdate.put( newAlloc, null); } } } } for ( Allocatable alloc: removedAllocatables) { Set<Conflict> sortedSet = conflictMap.get( alloc); if ( sortedSet != null && !sortedSet.isEmpty()) { logger.error("Removing non empty conflict map for resource " + alloc + " Appointments:" + sortedSet); } conflictMap.remove( alloc); } Set<Conflict> added = new HashSet<Conflict>(); // this will recalculate the conflicts for that resource and the changed appointments for ( Map.Entry<Allocatable, AllocationChange> entry:toUpdate.entrySet()) { Allocatable allocatable = entry.getKey(); AllocationChange changedAppointments = entry.getValue(); if ( changedAppointments == null) { conflictMap.remove( allocatable); } Set<Conflict> conflictListBefore = conflictMap.get(allocatable); if ( conflictListBefore == null) { conflictListBefore = new LinkedHashSet<Conflict>(); } Set<Conflict> conflictListAfter = updateConflicts( allocatable, changedAppointments, today, conflictListBefore); conflictMap.put( allocatable, conflictListAfter); //User user = evt.getUser(); for ( Conflict conflict: conflictListBefore) { boolean isRemoved = !conflictListAfter.contains(conflict); if ( isRemoved ) { evt.addOperation( new UpdateResult.Remove(conflict)); } } for ( Conflict conflict: conflictListAfter) { boolean isNew = !conflictListBefore.contains(conflict); if ( isNew ) { evt.addOperation( new UpdateResult.Add(conflict)); added.add( conflict); } } } // so now we have the new conflicts, but what if a reservation or appointment changed without affecting the allocation but still // the conflict is still the same but the name could change, so we must somehow indicate the clients displaying that conflict, that they need to refresh the name, // because the involving reservations are not automatically pushed to the client // first we create a list with all changed appointments. Notice if a reservation is changed all the appointments will change to Map<Allocatable, Set<String>> appointmentUpdateMap = new LinkedHashMap<Allocatable, Set<String>>(); for (@SuppressWarnings("rawtypes") RaplaObject obj:evt.getChanged()) { if ( obj.getRaplaType().equals( Reservation.TYPE)) { Reservation reservation = (Reservation) obj; for (Appointment app: reservation.getAppointments()) { for ( Allocatable alloc:reservation.getAllocatablesFor( app)) { Set<String> set = appointmentUpdateMap.get( alloc); if ( set == null) { set = new HashSet<String>(); appointmentUpdateMap.put(alloc, set); } set.add( app.getId()); } } } } // then we create a map and look for any conflict that has changed appointment. This could still contain old appointment references Map<Conflict,Conflict> toUpdateConflicts = new LinkedHashMap<Conflict, Conflict>(); for ( Allocatable alloc: appointmentUpdateMap.keySet()) { Set<String> changedAppointments = appointmentUpdateMap.get( alloc); Set<Conflict> conflicts = conflictMap.get( alloc); if ( conflicts != null) { for ( Conflict conflict:conflicts) { String appointment1Id = conflict.getAppointment1(); String appointment2Id = conflict.getAppointment2(); boolean contains1 = changedAppointments.contains( appointment1Id); boolean contains2 = changedAppointments.contains( appointment2Id); if ( contains1 || contains2) { Conflict oldConflict = conflict; Appointment appointment1 = getAppointment( appointment1Id); Appointment appointment2 = getAppointment( appointment2Id); Conflict newConflict = new ConflictImpl( alloc, appointment1, appointment2, today); toUpdateConflicts.put( oldConflict, newConflict); } } } } // we update the conflict with the new appointment references ArrayList<Conflict> updateList = new ArrayList<Conflict>( toUpdateConflicts.keySet()); for ( Conflict oldConflict:updateList) { Conflict newConflict = toUpdateConflicts.get( oldConflict); Set<Conflict> conflicts = conflictMap.get( oldConflict.getAllocatable()); conflicts.remove( oldConflict); conflicts.add( newConflict); // we add a change operation // TODO Note that this list also contains the NEW conflicts, but the UpdateResult.NEW could still contain the old conflicts //if ( added.contains( oldConflict)) { evt.addOperation( new UpdateResult.Change( newConflict, oldConflict)); } } } // private SortedSet<Appointment> getAndCreateListId(Map<Allocatable,SortedSet<Appointment>> appointmentMap,Allocatable alloc) { // SortedSet<Appointment> set = appointmentMap.get( alloc); // if ( set == null) // { // set = new TreeSet<Appointment>(); // appointmentMap.put(alloc, set); // } // return set; // } // private Appointment getAppointment( // SortedSet<Appointment> changedAppointments, Appointment appointment) { // Appointment foundAppointment = changedAppointments.tailSet( appointment).iterator().next(); // return foundAppointment; // } public void removeOldConflicts(UpdateResult result, Date today) { for (Set<Conflict> sortedSet: conflictMap.values()) { Iterator<Conflict> it = sortedSet.iterator(); while (it.hasNext()) { Conflict conflict = it.next(); if ( endsBefore( conflict,today)) { it.remove(); result.addOperation( new UpdateResult.Remove(conflict)); } } } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.impl; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import org.rapla.components.util.Assert; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.internal.SimpleEntity; public class EntityStore implements EntityResolver { HashMap<String,Entity> entities = new LinkedHashMap<String,Entity>(); HashMap<String,DynamicType> dynamicTypes = new HashMap<String,DynamicType>(); HashMap<String,String> passwordList = new HashMap<String,String>(); CategoryImpl superCategory; EntityResolver parent; public EntityStore(EntityResolver parent,Category superCategory) { this.parent = parent; this.superCategory = (CategoryImpl) superCategory; } public void addAll(Collection<? extends Entity>collection) { Iterator<? extends Entity>it = collection.iterator(); while (it.hasNext()) { put(it.next()); } } public void put(Entity entity) { String id = entity.getId(); Assert.notNull(id); if ( entity.getRaplaType() == DynamicType.TYPE) { DynamicType dynamicType = (DynamicType) entity; dynamicTypes.put ( dynamicType.getKey(), dynamicType); } if ( entity.getRaplaType() == Category.TYPE) { for (Category child:((Category)entity).getCategories()) { put( child); } } entities.put(id,entity); } public DynamicType getDynamicType(String key) { DynamicType type = dynamicTypes.get( key); if ( type == null && parent != null) { type = parent.getDynamicType( key); } return type; } public Collection<Entity>getList() { return entities.values(); } public CategoryImpl getSuperCategory() { return superCategory; } public void putPassword( String userid, String password ) { passwordList.put(userid, password); } public String getPassword( String userid) { return passwordList.get(userid); } public Entity resolve(String id) throws EntityNotFoundException { return resolve(id, null); } public <T extends Entity> T resolve(String id,Class<T> entityClass) throws EntityNotFoundException { T entity = tryResolve(id, entityClass); SimpleEntity.checkResolveResult(id, entityClass, entity); return entity; } @Override public Entity tryResolve(String id) { return tryResolve(id, null); } @Override public <T extends Entity> T tryResolve(String id,Class<T> entityClass) { Assert.notNull( id); Entity entity = entities.get(id); if (entity != null) { @SuppressWarnings("unchecked") T casted = (T) entity; return casted; } if ( id.equals( superCategory.getId()) && (entityClass == null || Category.class.isAssignableFrom( entityClass))) { @SuppressWarnings("unchecked") T casted = (T) superCategory; return casted; } if (parent != null) { return parent.tryResolve(id, entityClass); } return null; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.rapla.components.util.TimeInterval; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.facade.ModificationEvent; public class UpdateResult implements ModificationEvent { private User user; private List<UpdateOperation> operations = new ArrayList<UpdateOperation>(); Set<RaplaType> modified = new HashSet<RaplaType>(); boolean switchTemplateMode = false; public UpdateResult(User user) { this.user = user; } public void addOperation(final UpdateOperation operation) { if ( operation == null) throw new IllegalStateException( "Operation can't be null" ); operations.add(operation); Entity current = operation.getCurrent(); if ( current != null) { RaplaType raplaType = current.getRaplaType(); modified.add( raplaType); } } public User getUser() { return user; } public Set<Entity> getRemoved() { return getObject( Remove.class); } public Set<Entity> getChangeObjects() { return getObject( Change.class); } public Set<Entity> getAddObjects() { return getObject( Add.class); } @SuppressWarnings("unchecked") public <T extends UpdateOperation> Iterator<T> getOperations( final Class<T> operationClass) { Iterator<UpdateOperation> operationsIt = operations.iterator(); if ( operationClass == null) throw new IllegalStateException( "OperationClass can't be null" ); List<T> list = new ArrayList<T>(); while ( operationsIt.hasNext() ) { UpdateOperation obj = operationsIt.next(); if ( operationClass.equals( obj.getClass())) { list.add( (T)obj ); } } return list.iterator(); } public Iterable<UpdateOperation> getOperations() { return Collections.unmodifiableCollection(operations); } protected <T extends UpdateOperation> Set<Entity> getObject( final Class<T> operationClass ) { Set<Entity> set = new HashSet<Entity>(); if ( operationClass == null) throw new IllegalStateException( "OperationClass can't be null" ); Iterator<? extends UpdateOperation> it= getOperations( operationClass); while (it.hasNext() ) { UpdateOperation next = it.next(); Entity current = next.getCurrent(); set.add( current); } return set; } static public class Add implements UpdateOperation { Entity newObj; // the object in the state when it was added public Add( Entity newObj) { this.newObj = newObj; } public Entity getCurrent() { return newObj; } public Entity getNew() { return newObj; } public String toString() { return "Add " + newObj; } } static public class Remove implements UpdateOperation { Entity currentObj; // the actual represantation of the object public Remove(Entity currentObj) { this.currentObj = currentObj; } public Entity getCurrent() { return currentObj; } public String toString() { return "Remove " + currentObj; } } static public class Change implements UpdateOperation{ Entity newObj; // the object in the state when it was changed Entity oldObj; // the object in the state before it was changed public Change( Entity newObj, Entity oldObj) { this.newObj = newObj; this.oldObj = oldObj; } public Entity getCurrent() { return newObj; } public Entity getNew() { return newObj; } public Entity getOld() { return oldObj; } public String toString() { return "Change " + oldObj + " to " + newObj; } } TimeInterval timeInterval; public void setInvalidateInterval(TimeInterval timeInterval) { this.timeInterval = timeInterval; } public TimeInterval getInvalidateInterval() { return timeInterval; } public TimeInterval calulateInvalidateInterval() { TimeInterval currentInterval = null; { Iterator<Change> operations = getOperations( Change.class); while (operations.hasNext()) { Change change = operations.next(); currentInterval = expandInterval( change.getNew(), currentInterval); currentInterval = expandInterval( change.getOld(), currentInterval); } } { Iterator<Add> operations = getOperations( Add.class); while (operations.hasNext()) { Add change = operations.next(); currentInterval = expandInterval( change.getNew(), currentInterval); } } { Iterator<Remove> operations = getOperations( Remove.class); while (operations.hasNext()) { Remove change = operations.next(); currentInterval = expandInterval( change.getCurrent(), currentInterval); } } return currentInterval; } private TimeInterval expandInterval(RaplaObject obj, TimeInterval currentInterval) { RaplaType type = obj.getRaplaType(); if ( type == Reservation.TYPE) { for ( Appointment app:((ReservationImpl)obj).getAppointmentList()) { currentInterval = invalidateInterval( currentInterval, app); } } return currentInterval; } private TimeInterval invalidateInterval(TimeInterval oldInterval,Appointment appointment) { Date start = appointment.getStart(); Date end = appointment.getMaxEnd(); TimeInterval interval = new TimeInterval(start, end).union( oldInterval); return interval; } public boolean hasChanged(Entity object) { return getChanged().contains(object); } public boolean isRemoved(Entity object) { return getRemoved().contains( object); } public boolean isModified(Entity object) { return hasChanged(object) || isRemoved( object); } /** returns the modified objects from a given set. * @deprecated use the retainObjects instead in combination with getChanged*/ public <T extends RaplaObject> Set<T> getChanged(Collection<T> col) { return RaplaType.retainObjects(getChanged(),col); } /** returns the modified objects from a given set. * @deprecated use the retainObjects instead in combination with getChanged*/ public <T extends RaplaObject> Set<T> getRemoved(Collection<T> col) { return RaplaType.retainObjects(getRemoved(),col); } public Set<Entity> getChanged() { Set<Entity> result = new HashSet<Entity>(getAddObjects()); result.addAll(getChangeObjects()); return result; } public boolean isModified(RaplaType raplaType) { return modified.contains( raplaType) ; } public boolean isModified() { return !operations.isEmpty() || switchTemplateMode; } public boolean isEmpty() { return !isModified() && timeInterval == null; } public void setSwitchTemplateMode(boolean b) { switchTemplateMode = b; } public boolean isSwitchTemplateMode() { return switchTemplateMode; } }
Java
package org.rapla.storage; import org.rapla.framework.RaplaException; public class RaplaNewVersionException extends RaplaException { private static final long serialVersionUID = 1L; public RaplaNewVersionException(String text) { super(text); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.rapla.components.util.ParseDateException; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.components.util.TimeInterval; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.internal.UserImpl; import org.rapla.entities.storage.EntityReferencer; import org.rapla.facade.Conflict; import org.rapla.facade.internal.ConflictImpl; public class UpdateEvent { transient Map listMap;// = new HashMap<Class, List<Entity>>(); List<CategoryImpl> categories = createList(Category.class); List<DynamicTypeImpl> types = createList(DynamicType.class); List<UserImpl> users = createList(User.class); List<PreferencePatch> preferencesPatches = new ArrayList<PreferencePatch>(); List<PreferencesImpl> preferences = createList(Preferences.class); List<AllocatableImpl> resources = createList(Allocatable.class); List<ReservationImpl> reservations = createList(Reservation.class); List<ConflictImpl> conflicts = createList(Conflict.class); private Set<String> removeSet = new LinkedHashSet<String>(); private Set<String> storeSet = new LinkedHashSet<String>(); private String userId; private boolean needResourcesRefresh = false; private TimeInterval invalidateInterval; private String lastValidated; private int timezoneOffset; public UpdateEvent() { } private <T> List<T> createList(@SuppressWarnings("unused") Class<? super T> clazz) { ArrayList<T> list = new ArrayList<T>(); return list; } public void setUserId( String userId) { this.userId = userId; } public String getUserId() { return userId; } private void addRemove(Entity entity) { removeSet.add( entity.getId()); add( entity); } private void addStore(Entity entity) { storeSet.add( entity.getId()); add( entity); } @SuppressWarnings("unchecked") public Map<Class, Collection<Entity>> getListMap() { if ( listMap == null) { listMap = new HashMap<Class,Collection<Entity>>(); listMap.put( Preferences.class,preferences); listMap.put( Allocatable.class,resources); listMap.put(Category.class, categories); listMap.put(User.class, users); listMap.put(DynamicType.class, types); listMap.put(Reservation.class, reservations); listMap.put(Conflict.class, conflicts); } return listMap; } private void add(Entity entity) { @SuppressWarnings("unchecked") Class<? extends RaplaType> class1 = entity.getRaplaType().getTypeClass(); Collection<Entity> list = getListMap().get( class1); if ( list == null) { //listMap.put( class1, list); throw new IllegalArgumentException(entity.getRaplaType() + " can't be stored "); } list.add( entity); } public void putPatch(PreferencePatch patch) { preferencesPatches.add( patch); } public Collection<Entity> getRemoveObjects() { HashSet<Entity> objects = new LinkedHashSet<Entity>(); for ( Collection<Entity> list:getListMap().values()) { for ( Entity entity:list) { if ( removeSet.contains( entity.getId())) { objects.add(entity); } } } return objects; } public Collection<Entity> getStoreObjects() { // Needs to be a linked hashset to keep the order of the entities HashSet<Entity> objects = new LinkedHashSet<Entity>(); for ( Collection<Entity> list:getListMap().values()) { for ( Entity entity:list) { if ( storeSet.contains( entity.getId())) { objects.add(entity); } } } return objects; } public Collection<EntityReferencer> getEntityReferences(boolean includeRemove) { HashSet<EntityReferencer> objects = new HashSet<EntityReferencer>(); for ( Collection<Entity> list:getListMap().values()) { for ( Entity entity:list) { String id = entity.getId(); boolean contains = storeSet.contains( id) || (includeRemove && removeSet.contains( id)); if ( contains && entity instanceof EntityReferencer) { EntityReferencer references = (EntityReferencer)entity; objects.add(references); } } } for ( PreferencePatch patch:preferencesPatches) { objects.add(patch); } return objects; } public List<PreferencePatch> getPreferencePatches() { return preferencesPatches; } /** use this method if you want to avoid adding the same Entity twice.*/ public void putStore(Entity entity) { if (!storeSet.contains(entity.getId())) addStore(entity); } /** use this method if you want to avoid adding the same Entity twice.*/ public void putRemove(Entity entity) { if (!removeSet.contains(entity.getId())) addRemove(entity); } /** find an entity in the update-event that matches the passed original. Returns null * if no such entity is found. */ public Entity findEntity(Entity original) { String originalId = original.getId(); if (!storeSet.contains( originalId)) { if (!removeSet.contains( originalId)) { return null; } } for ( Collection<Entity> list:getListMap().values()) { for ( Entity entity:list) { if ( entity.getId().equals( originalId)) { return entity; } } } throw new IllegalStateException("Entity in store/remove set but not found in list"); } public void setLastValidated( Date serverTime ) { if ( serverTime == null) { this.lastValidated = null; } this.lastValidated = SerializableDateTimeFormat.INSTANCE.formatTimestamp(serverTime); } public void setInvalidateInterval(TimeInterval invalidateInterval) { this.invalidateInterval = invalidateInterval; } public TimeInterval getInvalidateInterval() { return invalidateInterval; } public boolean isNeedResourcesRefresh() { return needResourcesRefresh; } public void setNeedResourcesRefresh(boolean needResourcesRefresh) { this.needResourcesRefresh = needResourcesRefresh; } public Collection<Entity> getAllObjects() { HashSet<Entity> objects = new HashSet<Entity>(); for ( Collection<Entity> list:getListMap().values()) { for ( Entity entity:list) { objects.add(entity); } } return objects; } public boolean isEmpty() { boolean isEmpty = removeSet.isEmpty() && storeSet.isEmpty() && invalidateInterval == null; return isEmpty; } public Date getLastValidated() { if ( lastValidated == null) { return null; } try { return SerializableDateTimeFormat.INSTANCE.parseTimestamp(lastValidated); } catch (ParseDateException e) { throw new IllegalStateException(e.getMessage()); } } public int getTimezoneOffset() { return timezoneOffset; } public void setTimezoneOffset(int timezoneOffset) { this.timezoneOffset = timezoneOffset; } }
Java
package org.rapla.storage; import java.util.LinkedHashSet; import java.util.Set; import org.rapla.entities.configuration.internal.RaplaMapImpl; public class PreferencePatch extends RaplaMapImpl { String userId; Set<String> removedEntries = new LinkedHashSet<String>(); public void addRemove(String role) { removedEntries.add( role); } public void setUserId(String userId) { this.userId = userId; } public String getUserId() { return userId; } public Set<String> getRemovedEntries() { return removedEntries; } @Override public String toString() { return "Patch for " + userId + " " + super.toString() + " Removed " + removedEntries.toString(); } }
Java
package org.rapla.storage; import org.rapla.entities.RaplaType; import org.rapla.framework.RaplaException; @Deprecated public class OldIdMapping { static public String getId(RaplaType type,String str) throws RaplaException { if (str == null) throw new RaplaException("Id string for " + type + " can't be null"); int index = str.lastIndexOf("_") + 1; if (index>str.length()) throw new RaplaException("invalid rapla-id '" + str + "'"); try { return getId(type,Integer.parseInt(str.substring(index))); } catch (NumberFormatException ex) { throw new RaplaException("invalid rapla-id '" + str + "'"); } } static public boolean isTextId( RaplaType type,String content ) { if ( content == null) { return false; } content = content.trim(); if ( isNumeric( content)) { return true; } String KEY_START = type.getLocalName() + "_"; boolean idContent = (content.indexOf( KEY_START ) >= 0 && content.length() > 0); return idContent; } static private boolean isNumeric(String text) { int length = text.length(); if ( length == 0) { return false; } for ( int i=0;i<length;i++) { char ch = text.charAt(i); if (!Character.isDigit(ch)) { return false; } } return true; } public static int parseId(String id) { int indexOf = id.indexOf("_"); String keyPart = id.substring( indexOf + 1); return Integer.parseInt(keyPart); } static public String getId(RaplaType type,int id) { return type.getLocalName() + "_" + id; } static public boolean isId( RaplaType type,Object object) { if (object instanceof String) { return ((String)object).startsWith(type.getLocalName()); } return false; } static public Integer getKey(RaplaType type,String id) { String keyPart = id.substring(type.getLocalName().length()+1); Integer key = Integer.parseInt( keyPart ); return key; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ /** A StorageOperator that operates on a LocalCache-Object. */ package org.rapla.storage; import java.util.Collection; import java.util.Date; import java.util.TimeZone; import org.rapla.entities.Entity; import org.rapla.entities.User; import org.rapla.framework.RaplaException; public interface CachableStorageOperator extends StorageOperator { void runWithReadLock(CachableStorageOperatorCommand cmd) throws RaplaException; void dispatch(UpdateEvent evt) throws RaplaException; String authenticate(String username,String password) throws RaplaException; void saveData(LocalCache cache) throws RaplaException; public Collection<Entity> getVisibleEntities(final User user) throws RaplaException; public Collection<Entity> getUpdatedEntities(Date timestamp) throws RaplaException; TimeZone getTimeZone(); //DynamicType getUnresolvedAllocatableType(); //DynamicType getAnonymousReservationType(); }
Java
package org.rapla.storage; import org.rapla.framework.RaplaException; public interface CachableStorageOperatorCommand { public void execute( LocalCache cache) throws RaplaException; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage; import org.rapla.framework.RaplaException; /** * This exception is thrown on an invalid login, * or when a client tries to access data without * the proper permissions. */ public class RaplaSecurityException extends RaplaException { private static final long serialVersionUID = 1L; public RaplaSecurityException(String text) { super(text); } public RaplaSecurityException(Throwable throwable) { super(throwable); } public RaplaSecurityException(String text,Throwable ex) { super(text,ex); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage; import org.rapla.framework.RaplaException; public interface StorageUpdateListener { public void objectsUpdated(UpdateResult evt); public void updateError(RaplaException ex); public void storageDisconnected(String disconnectionMessage); }
Java
package org.rapla.storage.dbrm; import org.rapla.framework.RaplaException; public class RaplaConnectException extends RaplaException { private static final long serialVersionUID = 1L; public RaplaConnectException(String text) { super(text, null); } public RaplaConnectException( Throwable cause) { super(cause.getMessage(), cause); } }
Java
package org.rapla.storage.dbrm; public class RaplaRestartingException extends RaplaConnectException { private static final long serialVersionUID = 1L; public RaplaRestartingException() { super("Connection to server aborted. Restarting client."); } }
Java
package org.rapla.storage.dbrm; import java.util.Date; public class LoginTokens { String accessToken; Date validUntil; @SuppressWarnings("unused") private LoginTokens() { } public LoginTokens(String accessToken, Date validUntil) { this.accessToken = accessToken; this.validUntil = validUntil; } public String getAccessToken() { return accessToken; } public Date getValidUntil() { return validUntil; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Praktikum Gruppe2?, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbrm; import org.rapla.framework.RaplaException; public interface RestartServer { public void restartServer() throws RaplaException; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 ?, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbrm; import java.util.Date; import java.util.List; import java.util.Map; import javax.jws.WebParam; import javax.jws.WebService; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.facade.internal.ConflictImpl; import org.rapla.framework.RaplaException; import org.rapla.rest.gwtjsonrpc.common.FutureResult; import org.rapla.rest.gwtjsonrpc.common.RemoteJsonService; import org.rapla.rest.gwtjsonrpc.common.ResultType; import org.rapla.rest.gwtjsonrpc.common.VoidResult; import org.rapla.storage.UpdateEvent; @WebService public interface RemoteStorage extends RemoteJsonService { final String USER_WAS_NOT_AUTHENTIFIED = "User was not authentified"; @ResultType(String.class) FutureResult<String> canChangePassword(); @ResultType(VoidResult.class) FutureResult<VoidResult> changePassword(String username,String oldPassword,String newPassword); @ResultType(VoidResult.class) FutureResult<VoidResult> changeName(String username, String newTitle,String newSurename,String newLastname); @ResultType(VoidResult.class) FutureResult<VoidResult> changeEmail(String username,String newEmail); @ResultType(VoidResult.class) FutureResult<VoidResult> confirmEmail(String username,String newEmail); @ResultType(UpdateEvent.class) FutureResult<UpdateEvent> getResources() throws RaplaException; /** delegates the corresponding method in the StorageOperator. * @param annotationQuery */ @ResultType(value=ReservationImpl.class,container=List.class) FutureResult<List<ReservationImpl>> getReservations(@WebParam(name="resources")String[] allocatableIds,@WebParam(name="start")Date start,@WebParam(name="end")Date end, @WebParam(name="annotations")Map<String, String> annotationQuery); @ResultType(UpdateEvent.class) FutureResult<UpdateEvent> getEntityRecursive(String... id); @ResultType(UpdateEvent.class) FutureResult<UpdateEvent> refresh(String clientRepoVersion); @ResultType(VoidResult.class) FutureResult<VoidResult> restartServer(); @ResultType(UpdateEvent.class) FutureResult<UpdateEvent> dispatch(UpdateEvent event); @ResultType(value=String.class,container=List.class) FutureResult<List<String>> getTemplateNames(); @ResultType(value=String.class,container=List.class) FutureResult<List<String>> createIdentifier(String raplaType, int count); @ResultType(value=ConflictImpl.class,container=List.class) FutureResult<List<ConflictImpl>> getConflicts(); @ResultType(BindingMap.class) FutureResult<BindingMap> getFirstAllocatableBindings(String[] allocatableIds, List<AppointmentImpl> appointments, String[] reservationIds); @ResultType(value=ReservationImpl.class,container=List.class) FutureResult<List<ReservationImpl>> getAllAllocatableBindings(String[] allocatables, List<AppointmentImpl> appointments, String[] reservationIds); @ResultType(Date.class) FutureResult<Date> getNextAllocatableDate(String[] allocatableIds, AppointmentImpl appointment,String[] reservationIds, Integer worktimeStartMinutes, Integer worktimeEndMinutes, Integer[] excludedDays, Integer rowsPerHour); //void logEntityNotFound(String logMessage,String... referencedIds) throws RaplaException; public static class BindingMap { Map<String,List<String>> bindings; BindingMap() { } public BindingMap(Map<String,List<String>> bindings) { this.bindings = bindings; } public Map<String,List<String>> get() { return bindings; } } void setConnectInfo(RemoteConnectionInfo info); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbrm; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.locks.Lock; import org.rapla.ConnectInfo; import org.rapla.components.util.Assert; import org.rapla.components.util.Cancelable; import org.rapla.components.util.Command; import org.rapla.components.util.CommandScheduler; import org.rapla.components.util.DateTools; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.components.util.TimeInterval; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentStartComparator; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.storage.EntityResolver; import org.rapla.facade.Conflict; import org.rapla.facade.UpdateModule; import org.rapla.facade.internal.ConflictImpl; import org.rapla.framework.Configuration; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.internal.ContextTools; import org.rapla.framework.logger.Logger; import org.rapla.rest.gwtjsonrpc.common.AsyncCallback; import org.rapla.rest.gwtjsonrpc.common.FutureResult; import org.rapla.storage.RaplaSecurityException; import org.rapla.storage.UpdateEvent; import org.rapla.storage.UpdateResult; import org.rapla.storage.impl.AbstractCachableOperator; /** This operator can be used to modify and access data over the * network. It needs an server-process providing the StorageService * (usually this is the default rapla-server). * <p>Sample configuration: <pre> &lt;remote-storage id="web"> &lt;/remote-storate> </pre> */ public class RemoteOperator extends AbstractCachableOperator implements RestartServer,Disposable { private boolean bSessionActive = false; String userId; RemoteServer remoteServer; RemoteStorage remoteStorage; protected CommandScheduler commandQueue; Date lastSyncedTimeLocal; Date lastSyncedTime; int timezoneOffset; ConnectInfo connectInfo; Configuration config; RemoteConnectionInfo connectionInfo; public RemoteOperator(RaplaContext context, Logger logger, Configuration config, RemoteServer remoteServer, RemoteStorage remoteStorage) throws RaplaException { super( context, logger ); this.config = config; this.remoteServer = remoteServer; this.remoteStorage = remoteStorage; commandQueue = context.lookup( CommandScheduler.class); this.connectionInfo = new RemoteConnectionInfo(); remoteStorage.setConnectInfo( connectionInfo ); remoteServer.setConnectInfo( connectionInfo ); if ( config != null) { String serverConfig = config.getChild("server").getValue("${downloadServer}"); final String serverURL= ContextTools.resolveContext(serverConfig, context ); connectionInfo.setServerURL(serverURL); } } public RemoteConnectionInfo getRemoteConnectionInfo() { return connectionInfo; } synchronized public User connect(ConnectInfo connectInfo) throws RaplaException { if ( connectInfo == null) { throw new RaplaException("RemoteOperator doesn't support anonymous connect"); } if (isConnected()) return null; getLogger().info("Connecting to server and starting login.."); Lock writeLock = writeLock(); try { User user = loginAndLoadData(connectInfo); connectionInfo.setReAuthenticateCommand(new FutureResult<String>() { @Override public String get() throws Exception { getLogger().info("Refreshing access token."); return loginWithoutDisconnect(); } @Override public String get(long wait) throws Exception { return get(); } @Override public void get(AsyncCallback<String> callback) { try { String string = get(); callback.onSuccess(string); } catch (Exception e) { callback.onFailure(e); } } }); initRefresh(); return user; } finally { unlock(writeLock); } } private User loginAndLoadData(ConnectInfo connectInfo) throws RaplaException { this.connectInfo = connectInfo; String username = this.connectInfo.getUsername(); login(); getLogger().info("login successfull"); User user = loadData(username); bSessionActive = true; return user; } protected String login() throws RaplaException { try { return loginWithoutDisconnect(); } catch (RaplaException ex){ disconnect(); throw ex; } catch (Exception ex){ disconnect(); throw new RaplaException(ex); } } private String loginWithoutDisconnect() throws Exception, RaplaSecurityException { String connectAs = this.connectInfo.getConnectAs(); String password = new String( this.connectInfo.getPassword()); String username = this.connectInfo.getUsername(); RemoteServer serv1 = getRemoteServer(); LoginTokens loginToken = serv1.login(username,password, connectAs).get(); String accessToken = loginToken.getAccessToken(); if ( accessToken != null) { connectionInfo.setAccessToken( accessToken); return accessToken; } else { throw new RaplaSecurityException("Invalid Access token"); } } public Date getCurrentTimestamp() { if (lastSyncedTime == null) { return new Date(System.currentTimeMillis()); } // no matter what the client clock says we always sync to the server clock long passedMillis = System.currentTimeMillis()- lastSyncedTimeLocal.getTime(); if ( passedMillis < 0) { passedMillis = 0; } long correctTime = this.lastSyncedTime.getTime() + passedMillis; Date date = new Date(correctTime); return date; } public Date today() { long time = getCurrentTimestamp().getTime(); Date raplaTime = new Date(time + timezoneOffset); return DateTools.cutDate( raplaTime); } Cancelable timerTask; int intervalLength; private final void initRefresh() { Command refreshTask = new Command() { public void execute() { try { // test if the remote operator is writable // if not we skip until the next update cycle Lock writeLock = lock.writeLock(); boolean tryLock = writeLock.tryLock(); if ( tryLock) { writeLock.unlock(); } if (isConnected() && tryLock) { refresh(); } } catch (RaplaConnectException e) { getLogger().error("Error connecting " + e.getMessage()); } catch (RaplaException e) { getLogger().error("Error refreshing.", e); } } }; intervalLength = UpdateModule.REFRESH_INTERVAL_DEFAULT; if (isConnected()) { try { intervalLength = getPreferences(null, true).getEntryAsInteger(UpdateModule.REFRESH_INTERVAL_ENTRY, UpdateModule.REFRESH_INTERVAL_DEFAULT); } catch (RaplaException e) { getLogger().error("Error refreshing.", e); } } if ( timerTask != null) { timerTask.cancel(); } timerTask = commandQueue.schedule(refreshTask, 0, intervalLength); } public void dispose() { if ( timerTask != null) { timerTask.cancel(); } } // public String getConnectionName() { // if ( connector != null) // { // return connector.getInfo(); // } // else // { // return "standalone"; // } // } // // private void doConnect() throws RaplaException { // boolean bFailed = true; // try { // bFailed = false; // } catch (Exception e) { // throw new RaplaException(i18n.format("error.connect",getConnectionName()),e); // } finally { // if (bFailed) // disconnect(); // } // } public boolean isConnected() { return bSessionActive; } public boolean supportsActiveMonitoring() { return true; } synchronized public void refresh() throws RaplaException { String clientRepoVersion = getClientRepoVersion(); RemoteStorage serv = getRemoteStorage(); try { UpdateEvent evt = serv.refresh( clientRepoVersion).get(); refresh( evt); } catch (EntityNotFoundException ex) { getLogger().error("Refreshing all resources due to " + ex.getMessage(), ex); refreshAll(); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } private String getClientRepoVersion() { return SerializableDateTimeFormat.INSTANCE.formatTimestamp(lastSyncedTime); } synchronized public void restartServer() throws RaplaException { getLogger().info("Restart in progress ..."); String message = i18n.getString("restart_server"); // isRestarting = true; try { RemoteStorage serv = getRemoteStorage(); serv.restartServer().get(); fireStorageDisconnected(message); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } synchronized public void disconnect() throws RaplaException { connectionInfo.setAccessToken( null); this.connectInfo = null; connectionInfo.setReAuthenticateCommand(null); disconnect("Disconnection from Server initiated"); } /** disconnect from the server */ synchronized public void disconnect(String message) throws RaplaException { boolean wasConnected = bSessionActive; getLogger().info("Disconnecting from server"); try { bSessionActive = false; cache.clearAll(); } catch (Exception e) { throw new RaplaException("Could not disconnect", e); } if ( wasConnected) { RemoteServer serv1 = getRemoteServer(); try { serv1.logout().get(); } catch (RaplaConnectException ex) { getLogger().warn( ex.getMessage()); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } fireStorageDisconnected(message); } } @Override protected void setResolver(Collection<? extends Entity> entities) throws RaplaException { // don't resolve entities in standalone mode if (context.has(RemoteMethodStub.class)) { return; } super.setResolver(entities); } @Override protected void testResolve(Collection<? extends Entity> entities) throws EntityNotFoundException { // don't resolve entities in standalone mode if (context.has(RemoteMethodStub.class)) { return; } super.testResolve(entities); } private User loadData(String username) throws RaplaException { getLogger().debug("Getting Data.."); RemoteStorage serv = getRemoteStorage(); try { UpdateEvent evt = serv.getResources().get(); this.userId = evt.getUserId(); if ( userId != null) { cache.setClientUserId( userId); } updateTimestamps(evt); Collection<Entity> storeObjects = evt.getStoreObjects(); cache.clearAll(); testResolve( storeObjects); setResolver( storeObjects ); for( Entity entity:storeObjects) { cache.put(entity); } getLogger().debug("Data flushed"); if ( username != null) { if ( userId == null) { throw new EntityNotFoundException("User with username "+ username + " not found in result"); } User user = cache.resolve( userId, User.class); return user; } else { return null; } } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } public void updateTimestamps(UpdateEvent evt) throws RaplaException { if ( evt.getLastValidated() == null) { throw new RaplaException("Server sync time is missing"); } lastSyncedTimeLocal = new Date(System.currentTimeMillis()); lastSyncedTime = evt.getLastValidated(); timezoneOffset = evt.getTimezoneOffset(); //long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time); } protected void checkConnected() throws RaplaException { if ( !bSessionActive ) { throw new RaplaException("Not logged in or connection closed!"); } } public void dispatch(UpdateEvent evt) throws RaplaException { checkConnected(); // Store on server if (getLogger().isDebugEnabled()) { Iterator<Entity>it =evt.getStoreObjects().iterator(); while (it.hasNext()) { Entity entity = it.next(); getLogger().debug("dispatching store for: " + entity); } it =evt.getRemoveObjects().iterator(); while (it.hasNext()) { Entity entity = it.next(); getLogger().debug("dispatching remove for: " + entity); } } RemoteStorage serv = getRemoteStorage(); evt.setLastValidated(lastSyncedTime); try { UpdateEvent serverClosure =serv.dispatch( evt ).get(); refresh(serverClosure); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } public String[] createIdentifier(RaplaType raplaType, int count) throws RaplaException { RemoteStorage serv = getRemoteStorage(); try { List<String> id = serv.createIdentifier(raplaType.getLocalName(), count).get(); return id.toArray(new String[] {}); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } private RemoteStorage getRemoteStorage() { return remoteStorage; } private RemoteServer getRemoteServer() { return remoteServer; } public boolean canChangePassword() throws RaplaException { RemoteStorage remoteMethod = getRemoteStorage(); try { String canChangePassword = remoteMethod.canChangePassword().get(); boolean result = canChangePassword != null && canChangePassword.equalsIgnoreCase("true"); return result; } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } @Override public void changePassword(User user,char[] oldPassword,char[] newPassword) throws RaplaException { try { RemoteStorage remoteMethod = getRemoteStorage(); String username = user.getUsername(); remoteMethod.changePassword(username, new String(oldPassword),new String(newPassword)).get(); refresh(); } catch (RaplaSecurityException ex) { throw new RaplaSecurityException(i18n.getString("error.wrong_password")); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } @Override public void changeEmail(User user, String newEmail) throws RaplaException { try { RemoteStorage remoteMethod = getRemoteStorage(); String username = user.getUsername(); remoteMethod.changeEmail(username,newEmail).get(); refresh(); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } @Override public void confirmEmail(User user, String newEmail) throws RaplaException { try { RemoteStorage remoteMethod = getRemoteStorage(); String username = user.getUsername(); remoteMethod.confirmEmail(username,newEmail).get(); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } @Override public void changeName(User user, String newTitle, String newFirstname, String newSurname) throws RaplaException { try { RemoteStorage remoteMethod = getRemoteStorage(); String username = user.getUsername(); remoteMethod.changeName(username,newTitle, newFirstname, newSurname).get(); refresh(); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } public Map<String,Entity> getFromId(Collection<String> idSet, boolean throwEntityNotFound) throws RaplaException { RemoteStorage serv = getRemoteStorage(); String[] array = idSet.toArray(new String[] {}); Map<String,Entity> result = new HashMap<String,Entity>(); try { UpdateEvent entityList = serv.getEntityRecursive( array).get(); Collection<Entity> list = entityList.getStoreObjects(); Lock lock = readLock(); try { testResolve( list); setResolver( list ); } finally { unlock(lock); } for (Entity entity:list) { String id = entity.getId(); if ( idSet.contains( id )) { result.put( id, entity); } } } catch (EntityNotFoundException ex) { if ( throwEntityNotFound) { throw ex; } } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } return result; } @Override protected <T extends Entity> T tryResolve(EntityResolver resolver,String id,Class<T> entityClass) { Assert.notNull( id); T entity = super.tryResolve(resolver,id, entityClass); if ( entity != null) { return entity; } if ( entityClass != null && Allocatable.class.isAssignableFrom(entityClass)) { AllocatableImpl unresolved = new AllocatableImpl(null, null); unresolved.setId( id); unresolved.setClassification( getDynamicType(UNRESOLVED_RESOURCE_TYPE).newClassification()); @SuppressWarnings("unchecked") T casted = (T) unresolved; return casted; } return null; } public List<Reservation> getReservations(User user,Collection<Allocatable> allocatables,Date start,Date end,ClassificationFilter[] filters, Map<String,String> annotationQuery) throws RaplaException { RemoteStorage serv = getRemoteStorage(); // if a refresh is due, we assume the system went to sleep so we refresh before we continue if ( intervalLength > 0 && lastSyncedTime != null && (lastSyncedTime.getTime() + intervalLength * 2) < getCurrentTimestamp().getTime()) { getLogger().info("cache not uptodate. Refreshing first."); refresh(); } String[] allocatableId = getIdList(allocatables); try { List<ReservationImpl> list =serv.getReservations(allocatableId,start, end, annotationQuery).get(); Lock lock = readLock(); try { testResolve( list); setResolver( list ); } finally { unlock(lock); } List<Reservation> result = new ArrayList<Reservation>(); Iterator it = list.iterator(); while ( it.hasNext()) { Object object = it.next(); Reservation next = (Reservation)object; result.add( next); } removeFilteredClassifications(result, filters); return result; } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } public List<String> getTemplateNames() throws RaplaException { checkConnected(); RemoteStorage serv = getRemoteStorage(); try { List<String> result = serv.getTemplateNames().get(); return result; } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } protected String[] getIdList(Collection<? extends Entity> entities) { List<String> idList = new ArrayList<String>(); if ( entities != null ) { for ( Entity entity:entities) { if (entity != null) idList.add( ((Entity)entity).getId().toString()); } } String[] ids = idList.toArray(new String[] {}); return ids; } synchronized private void refresh(UpdateEvent evt) throws RaplaException { updateTimestamps(evt); if ( evt.isNeedResourcesRefresh()) { refreshAll(); return; } UpdateResult result = null; testResolve(evt.getStoreObjects()); setResolver(evt.getStoreObjects()); // we don't test the references of the removed objects setResolver(evt.getRemoveObjects()); if ( bSessionActive && !evt.isEmpty() ) { getLogger().debug("Objects updated!"); Lock writeLock = writeLock(); try { result = update(evt); } finally { unlock(writeLock); } } if ( result != null && !result.isEmpty()) { fireStorageUpdated(result); } } protected void refreshAll() throws RaplaException,EntityNotFoundException { UpdateResult result; Collection<Entity> oldEntities; Lock readLock = readLock(); try { User user = cache.resolve( userId, User.class); oldEntities = cache.getVisibleEntities(user); } finally { unlock(readLock); } Lock writeLock = writeLock(); try { loadData(null); } finally { unlock(writeLock); } Collection<Entity> newEntities; readLock = readLock(); try { User user = cache.resolve( userId, User.class); newEntities = cache.getVisibleEntities(user); } finally { unlock(readLock); } HashSet<Entity> updated = new HashSet<Entity>(newEntities); Set<Entity> toRemove = new HashSet<Entity>(oldEntities); Set<Entity> toUpdate = new HashSet<Entity>(oldEntities); toRemove.removeAll(newEntities); updated.removeAll( toRemove); toUpdate.retainAll(newEntities); HashMap<Entity,Entity> oldEntityMap = new HashMap<Entity,Entity>(); for ( Entity update: toUpdate) { @SuppressWarnings("unchecked") Class<? extends Entity> typeClass = update.getRaplaType().getTypeClass(); Entity newEntity = cache.tryResolve( update.getId(), typeClass); if ( newEntity != null) { oldEntityMap.put( newEntity, update); } } TimeInterval invalidateInterval = new TimeInterval( null,null); result = createUpdateResult(oldEntityMap, updated, toRemove, invalidateInterval, userId); fireStorageUpdated(result); } @Override public Map<Allocatable, Collection<Appointment>> getFirstAllocatableBindings( Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException { checkConnected(); RemoteStorage serv = getRemoteStorage(); String[] allocatableIds = getIdList(allocatables); //AppointmentImpl[] appointmentArray = appointments.toArray( new AppointmentImpl[appointments.size()]); String[] reservationIds = getIdList(ignoreList); List<AppointmentImpl> appointmentList = new ArrayList<AppointmentImpl>(); Map<String,Appointment> appointmentMap= new HashMap<String,Appointment>(); for ( Appointment app: appointments) { appointmentList.add( (AppointmentImpl) app); appointmentMap.put( app.getId(), app); } try { Map<String, List<String>> resultMap = serv.getFirstAllocatableBindings(allocatableIds, appointmentList, reservationIds).get().get(); HashMap<Allocatable, Collection<Appointment>> result = new HashMap<Allocatable, Collection<Appointment>>(); for ( Allocatable alloc:allocatables) { List<String> list = resultMap.get( alloc.getId()); if ( list != null) { Collection<Appointment> appointmentBinding = new ArrayList<Appointment>(); for ( String id:list) { Appointment e = appointmentMap.get( id); if ( e != null) { appointmentBinding.add( e); } } result.put( alloc, appointmentBinding); } } return result; } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } @Override public Map<Allocatable, Map<Appointment, Collection<Appointment>>> getAllAllocatableBindings( Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException { checkConnected(); RemoteStorage serv = getRemoteStorage(); String[] allocatableIds = getIdList(allocatables); List<AppointmentImpl> appointmentArray = Arrays.asList(appointments.toArray( new AppointmentImpl[]{})); String[] reservationIds = getIdList(ignoreList); List<ReservationImpl> serverResult; try { serverResult = serv.getAllAllocatableBindings(allocatableIds, appointmentArray, reservationIds).get(); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } testResolve( serverResult); setResolver( serverResult ); SortedSet<Appointment> allAppointments = new TreeSet<Appointment>(new AppointmentStartComparator()); for ( ReservationImpl reservation: serverResult) { allAppointments.addAll(reservation.getAppointmentList()); } Map<Allocatable, Map<Appointment,Collection<Appointment>>> result = new HashMap<Allocatable, Map<Appointment,Collection<Appointment>>>(); for ( Allocatable alloc:allocatables) { Map<Appointment,Collection<Appointment>> appointmentBinding = new HashMap<Appointment, Collection<Appointment>>(); for (Appointment appointment: appointments) { SortedSet<Appointment> appointmentSet = getAppointments(alloc, allAppointments ); boolean onlyFirstConflictingAppointment = false; Set<Appointment> conflictingAppointments = AppointmentImpl.getConflictingAppointments(appointmentSet, appointment, ignoreList, onlyFirstConflictingAppointment); appointmentBinding.put( appointment, conflictingAppointments); } result.put( alloc, appointmentBinding); } return result; } @Override public Date getNextAllocatableDate(Collection<Allocatable> allocatables,Appointment appointment, Collection<Reservation> ignoreList, Integer worktimeStartMinutes,Integer worktimeEndMinutes, Integer[] excludedDays, Integer rowsPerHour) throws RaplaException { checkConnected(); RemoteStorage serv = getRemoteStorage(); String[] allocatableIds = getIdList(allocatables); String[] reservationIds = getIdList(ignoreList); try { Date result = serv.getNextAllocatableDate(allocatableIds, (AppointmentImpl)appointment, reservationIds, worktimeStartMinutes, worktimeEndMinutes, excludedDays, rowsPerHour).get(); return result; } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } static private SortedSet<Appointment> getAppointments(Allocatable alloc, SortedSet<Appointment> allAppointments) { SortedSet<Appointment> result = new TreeSet<Appointment>(new AppointmentStartComparator()); for ( Appointment appointment:allAppointments) { Reservation reservation = appointment.getReservation(); if ( reservation.hasAllocated( alloc, appointment)) { result.add( appointment); } } return result; } @Override public Collection<Conflict> getConflicts(User user) throws RaplaException { checkConnected(); RemoteStorage serv = getRemoteStorage(); try { List<ConflictImpl> list = serv.getConflicts().get(); testResolve( list); setResolver( list); List<Conflict> result = new ArrayList<Conflict>(); Iterator it = list.iterator(); while ( it.hasNext()) { Object object = it.next(); if ( object instanceof Conflict) { Conflict next = (Conflict)object; result.add( next); } } return result; } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } // @Override // protected void logEntityNotFound(Entity obj, EntityNotFoundException ex) { // RemoteStorage serv = getRemoteStorage(); // Comparable id = ex.getId(); // try { // if ( obj instanceof ConflictImpl) // { // Iterable<String> referencedIds = ((ConflictImpl)obj).getReferencedIds(); // List<String> ids = new ArrayList<String>(); // for (String refId:referencedIds) // { // ids.add( refId); // } // serv.logEntityNotFound( id + " not found in conflict :",ids.toArray(new String[0])); // } // else if ( id != null ) // { // serv.logEntityNotFound("Not found", id.toString() ); // } // } catch (Exception e) { // getLogger().error("Can't call server logging for " + ex.getMessage() + " due to " + e.getMessage(), e); // } // } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 ?, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbrm; import javax.jws.WebParam; import javax.jws.WebService; import org.rapla.rest.gwtjsonrpc.common.FutureResult; import org.rapla.rest.gwtjsonrpc.common.RemoteJsonService; import org.rapla.rest.gwtjsonrpc.common.ResultType; import org.rapla.rest.gwtjsonrpc.common.VoidResult; @WebService public interface RemoteServer extends RemoteJsonService { @ResultType(LoginTokens.class) FutureResult<LoginTokens> login(@WebParam(name="username") String username,@WebParam(name="password") String password,@WebParam(name="connectAs") String connectAs); @ResultType(LoginTokens.class) FutureResult<LoginTokens> auth(@WebParam(name="credentials") LoginCredentials credentials); @ResultType(VoidResult.class) FutureResult<VoidResult> logout(); @ResultType(String.class) FutureResult<String> getRefreshToken(); @ResultType(String.class) FutureResult<String> regenerateRefreshToken(); @ResultType(String.class) FutureResult<LoginTokens> refresh(@WebParam(name="refreshToken") String refreshToken); void setConnectInfo(RemoteConnectionInfo info); }
Java
package org.rapla.storage.dbrm; public class LoginCredentials { private String username; private String password; private String connectAs; public LoginCredentials(String username, String password, String connectAs) { super(); this.username = username; this.password = password; this.connectAs = connectAs; } public String getUsername() { return username; } public String getPassword() { return password; } public String getConnectAs() { return connectAs; } }
Java