code
stringlengths
3
1.18M
language
stringclasses
1 value
/** * */ package org.rapla.servletpages; import java.io.IOException; import java.util.Collection; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RaplaAppletPageGenerator implements RaplaPageGenerator{ private String getLibsApplet(ServletContext context) throws java.io.IOException { StringBuffer buf = new StringBuffer(); Collection<String> files = RaplaJNLPPageGenerator.getClientLibs(context); boolean first= true; for (String file:files) { if ( !first) { buf.append(", "); } else { first = false; } buf.append(file); } return buf.toString(); } public void generatePage( ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws IOException { String linkPrefix = request.getPathTranslated() != null ? "../": ""; response.setContentType("text/html; charset=ISO-8859-1"); java.io.PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println(" <title>Rapla Applet</title>"); out.println(" <link REL=\"stylesheet\" href=\""+linkPrefix+"default.css\" type=\"text/css\">"); out.println("</head>"); out.println("<body>"); out.println(" <applet code=\"org.rapla.client.MainApplet\" codebase=\".\" align=\"baseline\""); out.println(" width=\"300\" height=\"300\" archive=\""+getLibsApplet(context)+"\" codebase_lookup=\"false\""); out.println(" >"); out.println(" <param name=\"archive\" value=\""+getLibsApplet(context) +"\"/>"); out.println(" <param name=\"java_code\" value=\"org.rapla.client.MainApplet\"/>"); out.println(" <param name=\"java_codebase\" value=\"./\">"); out.println(" <param name=\"java_type\" value=\"application/x-java-applet;jpi-version=1.4.1\"/>"); out.println(" <param name=\"codebase_lookup\" value=\"false\"/>"); out.println(" <param name=\"scriptable\" value=\"true\"/>"); out.println(" No Java support for APPLET tags please install java plugin for your browser!!"); out.println(" </applet>"); out.println("</body>"); out.println("</html>"); out.close(); } }
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 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; /* @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; 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.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
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) 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) 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
/*--------------------------------------------------------------------------* | 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) 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) 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
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
/*--------------------------------------------------------------------------* | 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; 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.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) 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
/*--------------------------------------------------------------------------* | 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
/*--------------------------------------------------------------------------* | 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) 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; 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) 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; 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.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; /**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) 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
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.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
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) 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, 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.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; /** 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
/*--------------------------------------------------------------------------* | 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
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) 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; /**This interface is a marker to distinct the different rapla classes * like Reservation, Allocatable and Category. * It is something like the java instanceof keyword. But it must be unique for each * class. This type-information is for examle used for mapping the correct storage-, * editing- mechanism to the class. */ public interface RaplaObject<T> extends Cloneable { public static final String[] EMPTY_STRING_ARRAY = new String[0]; RaplaType<T> getRaplaType(); T 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; 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 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 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.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) 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.text.Collator; import java.util.Comparator; import java.util.Locale; import org.rapla.components.util.Assert; public class NamedComparator<T extends Named> implements Comparator<T> { Locale locale; Collator collator; public NamedComparator(Locale locale) { this.locale = locale; Assert.notNull( locale ); collator = Collator.getInstance(locale); } public int compare(Named o1,Named o2) { if ( o1.equals(o2)) return 0; Named r1 = o1; Named r2 = o2; int result = collator.compare( r1.getName(locale) ,r2.getName(locale) ); if ( result !=0 ) return result; else return (o1.hashCode() < o2.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.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) 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) 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 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) 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.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; /** 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
/*--------------------------------------------------------------------------* | 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 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) 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
/*--------------------------------------------------------------------------* | 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
/** * */ 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) 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
package org.rapla.entities.dynamictype; public interface RaplaAnnotation { }
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.configuration; import java.util.Collection; import java.util.Date; import java.util.Map; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.framework.TypedComponentRole; /** * * @author ckohlhaas * @version 1.00.00 * @since 2.03.00 */ public interface CalendarModelConfiguration extends RaplaObject<CalendarModelConfiguration> { public static final RaplaType<CalendarModelConfiguration> TYPE = new RaplaType<CalendarModelConfiguration>(CalendarModelConfiguration.class, "calendar"); public static final TypedComponentRole<CalendarModelConfiguration> CONFIG_ENTRY = new TypedComponentRole<CalendarModelConfiguration>("org.rapla.DefaultSelection"); public static final TypedComponentRole<RaplaMap<CalendarModelConfiguration>> EXPORT_ENTRY = new TypedComponentRole<RaplaMap<CalendarModelConfiguration>>("org.rapla.plugin.autoexport"); public Date getStartDate(); public Date getEndDate(); public Date getSelectedDate(); public String getTitle(); public String getView(); public Collection<Entity> getSelected(); public Map<String,String> getOptionMap(); //public Configuration get public ClassificationFilter[] getFilter(); public boolean isDefaultEventTypes(); public boolean isDefaultResourceTypes(); public boolean isResourceRootSelected(); public CalendarModelConfiguration cloneWithNewOptions(Map<String, String> newMap); }
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.configuration; import java.util.Map; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; /** * This Map can hold only Objects of type RaplaObject and String * (It cannot hold references to appointments or attributes) * @see RaplaObject */ public interface RaplaMap<T> extends RaplaObject, Map<String,T> { public static final RaplaType<RaplaMap> TYPE = new RaplaType<RaplaMap>(RaplaMap.class, "map"); }
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.configuration; import org.rapla.entities.Entity; 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.framework.TypedComponentRole; /** Preferences store user-specific Information. You can store arbitrary configuration objects under unique role names. Each role can contain 1-n configuration entries. @see org.rapla.entities.User */ public interface Preferences extends Entity<Preferences>,Ownable,Timestamp, Named { final RaplaType<Preferences> TYPE = new RaplaType<Preferences>(Preferences.class, "preferences"); final String ID_PREFIX = TYPE.getLocalName() + "_"; final String SYSTEM_PREFERENCES_ID = ID_PREFIX + "0"; /** returns if there are any preference-entries */ boolean isEmpty(); boolean hasEntry(TypedComponentRole<?> role); <T extends RaplaObject> T getEntry(TypedComponentRole<T> role); <T extends RaplaObject> T getEntry(TypedComponentRole<T> role, T defaultEntry); String getEntryAsString(TypedComponentRole<String> role, String defaultValue); Boolean getEntryAsBoolean(TypedComponentRole<Boolean> role, boolean defaultValue); Integer getEntryAsInteger(TypedComponentRole<Integer> role, int defaultValue); /** puts a new configuration entry to the role.*/ void putEntry(TypedComponentRole<Boolean> role,Boolean entry); void putEntry(TypedComponentRole<Integer> role,Integer entry); void putEntry(TypedComponentRole<String> role,String entry); void putEntry(TypedComponentRole<CalendarModelConfiguration> role,CalendarModelConfiguration entry); <T> void putEntry(TypedComponentRole<RaplaMap<T>> role,RaplaMap<T> entry); void putEntry(TypedComponentRole<RaplaConfiguration> role,RaplaConfiguration entry); void removeEntry(String role); }
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.configuration; import java.io.Serializable; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; /** * This class adds just the get Type method to the DefaultConfiguration so that the config can be stored in a preference object * @author ckohlhaas * @version 1.00.00 * @since 2.03.00 */ public class RaplaConfiguration extends DefaultConfiguration implements RaplaObject, Serializable{ // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; public static final RaplaType<RaplaConfiguration> TYPE = new RaplaType<RaplaConfiguration>(RaplaConfiguration.class, "config"); public RaplaConfiguration() { super(); } /** Creates a RaplaConfinguration with one element of the specified name * @param name the element name * @param content The content of the element. Can be null. */ public RaplaConfiguration( String name, String content) { super(name, content); } public RaplaConfiguration(String localName) { super(localName); } public RaplaConfiguration(Configuration configuration) { super( configuration); } public RaplaType getRaplaType() { return TYPE; } public RaplaConfiguration replace( Configuration oldChild, Configuration newChild) { return (RaplaConfiguration) super.replace( oldChild, newChild); } @Override protected RaplaConfiguration newConfiguration(String localName) { return new RaplaConfiguration( localName); } public RaplaConfiguration clone() { return new RaplaConfiguration( this); } }
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.configuration.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.internal.ClassificationFilterImpl; import org.rapla.entities.storage.EntityResolver; import org.rapla.framework.RaplaException; public class CalendarModelConfigurationImpl extends AbstractClassifiableFilter implements CalendarModelConfiguration { // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; List<String> selected; List<String> typeList; String title; Date startDate; Date endDate; Date selectedDate; String view; Map<String,String> optionMap; boolean defaultEventTypes; boolean defaultResourceTypes; boolean resourceRootSelected; public CalendarModelConfigurationImpl( Collection<String> selected,Collection<RaplaType> idTypeList,boolean resourceRootSelected, ClassificationFilter[] filter, boolean defaultResourceTypes, boolean defaultEventTypes,String title, Date startDate, Date endDate, Date selectedDate,String view,Map<String,String> extensionMap) { if (selected != null) { this.selected = Collections.unmodifiableList(new ArrayList<String>(selected)); typeList = new ArrayList<String>(); for ( RaplaType type:idTypeList) { typeList.add(type.getLocalName()); } } else { this.selected = Collections.emptyList(); typeList = Collections.emptyList(); } this.view = view; this.resourceRootSelected = resourceRootSelected; this.defaultEventTypes = defaultEventTypes; this.defaultResourceTypes = defaultResourceTypes; this.title = title; this.startDate = startDate; this.endDate = endDate; this.selectedDate = selectedDate; List<ClassificationFilterImpl> filterList = new ArrayList<ClassificationFilterImpl>(); if ( filter != null) { for ( ClassificationFilter f:filter) { filterList.add((ClassificationFilterImpl)f); } } super.setClassificationFilter( filterList ); Map<String,String> map= new LinkedHashMap<String,String>(); if ( extensionMap != null) { map.putAll(extensionMap); } this.optionMap = Collections.unmodifiableMap( map); } CalendarModelConfigurationImpl() { } @Override public boolean isResourceRootSelected() { return resourceRootSelected; } public void setResolver( EntityResolver resolver) { super.setResolver( resolver ); } public RaplaType<CalendarModelConfiguration> getRaplaType() { return TYPE; } public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } public Date getSelectedDate() { return selectedDate; } public String getTitle() { return title; } public String getView() { return view; } public Collection<Entity> getSelected() { ArrayList<Entity> result = new ArrayList<Entity>(); for ( String id: selected) { Entity entity = resolver.tryResolve(id); if ( entity != null) { result.add( entity); } } return result; } @Override public Iterable<ReferenceInfo> getReferenceInfo() { Iterable<ReferenceInfo> references = super.getReferenceInfo(); List<ReferenceInfo> selectedInfo = new ArrayList<ReferenceInfo>(); int size = selected.size(); for ( int i = 0;i<size;i++) { String id = selected.get(0); String localname = typeList.get(0); Class<? extends Entity> type = null; RaplaType raplaType; try { raplaType = RaplaType.find(localname); Class typeClass = raplaType.getTypeClass(); if ( Entity.class.isAssignableFrom(typeClass )) { @SuppressWarnings("unchecked") Class<? extends Entity> casted = (Class<? extends Entity>)typeClass; type = casted; } } catch (RaplaException e) { } ReferenceInfo referenceInfo = new ReferenceInfo(id, type); selectedInfo.add( referenceInfo); } return new IteratorChain<ReferenceInfo>(references, selectedInfo); } public Map<String,String> getOptionMap() { return optionMap; } public boolean isDefaultEventTypes() { return defaultEventTypes; } public boolean isDefaultResourceTypes() { return defaultResourceTypes; } @SuppressWarnings("unchecked") static private void copy(CalendarModelConfigurationImpl source,CalendarModelConfigurationImpl dest) { dest.view = source.view; dest.defaultEventTypes = source.defaultEventTypes; dest.defaultResourceTypes = source.defaultResourceTypes; dest.title = source.title; dest.startDate = source.startDate; dest.endDate = source.endDate; dest.selectedDate = source.selectedDate; dest.resourceRootSelected = source.resourceRootSelected; dest.setResolver( source.resolver); List<ClassificationFilterImpl> newFilter = new ArrayList<ClassificationFilterImpl>(); for ( ClassificationFilterImpl f: source.classificationFilters) { ClassificationFilterImpl clone = f.clone(); newFilter.add( clone); } dest.setClassificationFilter(newFilter ); dest.selected = (List<String>)((ArrayList<String>)source.selected).clone(); LinkedHashMap<String, String> optionMap = new LinkedHashMap<String,String>(); optionMap.putAll(source.optionMap); dest.optionMap = Collections.unmodifiableMap(optionMap); } public void copy(CalendarModelConfiguration obj) { copy((CalendarModelConfigurationImpl)obj, this); } public CalendarModelConfiguration deepClone() { CalendarModelConfigurationImpl clone = new CalendarModelConfigurationImpl(); copy(this,clone); return clone; } public CalendarModelConfiguration clone() { return deepClone(); } public List<String> getSelectedIds() { return selected; } public String toString() { return super.toString() + ",selected=" + selected; } @Override public CalendarModelConfiguration cloneWithNewOptions(Map<String, String> newMap) { CalendarModelConfigurationImpl clone = (CalendarModelConfigurationImpl) deepClone(); clone.optionMap = Collections.unmodifiableMap( newMap); return clone; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas, Frithjof Kurtz | | | | 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.configuration.internal; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.rapla.components.util.iterator.NestedIterator; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.ClassificationFilterImpl; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityResolver; public abstract class AbstractClassifiableFilter implements EntityReferencer, DynamicTypeDependant, Serializable { private static final long serialVersionUID = 1L; List<ClassificationFilterImpl> classificationFilters; protected transient EntityResolver resolver; AbstractClassifiableFilter() { classificationFilters = new ArrayList<ClassificationFilterImpl>(); } public void setResolver( EntityResolver resolver) { this.resolver = resolver; for (ClassificationFilterImpl filter:classificationFilters) { filter.setResolver( resolver ); } } @Override public Iterable<ReferenceInfo> getReferenceInfo() { Iterable<ClassificationFilterImpl> classificatonFilterIterator = classificationFilters; return new NestedIterator<ReferenceInfo,ClassificationFilterImpl>(classificatonFilterIterator) { public Iterable<ReferenceInfo> getNestedIterator(ClassificationFilterImpl obj) { return obj.getReferenceInfo(); } }; } public void setClassificationFilter(List<ClassificationFilterImpl> classificationFilters) { if ( classificationFilters != null) this.classificationFilters = classificationFilters; else this.classificationFilters = Collections.emptyList(); } public boolean needsChange(DynamicType type) { for (ClassificationFilterImpl filter:classificationFilters) { if (filter.needsChange(type)) return true; } return false; } public void commitChange(DynamicType type) { for (ClassificationFilterImpl filter:classificationFilters) { if (filter.getType().equals(type)) filter.commitChange(type); } } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { boolean removed = false; List<ClassificationFilterImpl> newFilter = new ArrayList<ClassificationFilterImpl>( classificationFilters); for (Iterator<ClassificationFilterImpl> f=newFilter.iterator();f.hasNext();) { ClassificationFilterImpl filter = f.next(); if (filter.getType().equals(type)) { removed = true; f.remove(); } } if ( removed) { classificationFilters = newFilter; } } public ClassificationFilter[] getFilter() { return classificationFilters.toArray( ClassificationFilter.CLASSIFICATIONFILTER_ARRAY); } public String toString() { return classificationFilters.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.configuration.internal; import java.util.Date; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Set; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.entities.configuration.RaplaMap; import org.rapla.entities.dynamictype.DynamicType; 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; import org.rapla.facade.RaplaComponent; import org.rapla.framework.Configuration; import org.rapla.framework.TypedComponentRole; import org.rapla.storage.PreferencePatch; public class PreferencesImpl extends SimpleEntity implements Preferences ,ModifiableTimestamp , DynamicTypeDependant { private Date lastChanged; private Date createDate; RaplaMapImpl map = new RaplaMapImpl(); Set<String> removedKeys = new LinkedHashSet<String>(); final public RaplaType<Preferences> getRaplaType() {return TYPE;} private transient PreferencePatch patch = new PreferencePatch(); PreferencesImpl() { this(null,null); } public PreferencesImpl(Date createDate,Date lastChanged ) { super(); this.createDate = createDate; this.lastChanged = lastChanged; } public Date getLastChanged() { return lastChanged; } @Deprecated public Date getLastChangeTime() { return lastChanged; } public Date getCreateTime() { return createDate; } public void setLastChanged(Date date) { checkWritable(); lastChanged = date; } @Override public void putEntry(TypedComponentRole<CalendarModelConfiguration> role, CalendarModelConfiguration entry) { putEntryPrivate(role.getId(), entry); } @Override public void putEntry(TypedComponentRole<RaplaConfiguration> role, RaplaConfiguration entry) { putEntryPrivate(role.getId(), entry); } @Override public <T> void putEntry(TypedComponentRole<RaplaMap<T>> role, RaplaMap<T> entry) { putEntryPrivate(role.getId(), entry); } public void putEntryPrivate(String role,RaplaObject entry) { updateMap(role, entry); } private void updateMap(String role, Object entry) { checkWritable(); map.putPrivate(role, entry); patch.putPrivate( role, entry); if ( entry == null) { patch.addRemove( role); } } public void putEntryPrivate(String role,String entry) { updateMap(role, entry); } public void setResolver( EntityResolver resolver) { super.setResolver(resolver); map.setResolver(resolver); patch.setResolver(resolver); } public <T> T getEntry(String role) { return getEntry(role, null); } public <T> T getEntry(String role, T defaultValue) { try { @SuppressWarnings("unchecked") T result = (T) map.get( role ); if ( result == null) { return defaultValue; } return result; } catch ( ClassCastException ex) { throw new ClassCastException( "Stored entry is not of requested Type: " + ex.getMessage()); } } private String getEntryAsString(String role) { return (String) map.get( role ); } public String getEntryAsString(TypedComponentRole<String> role, String defaultValue) { String value = getEntryAsString( role.getId()); if ( value != null) return value; return defaultValue; } public Iterable<String> getPreferenceEntries() { return map.keySet(); } public void removeEntry(String role) { updateMap(role, null); } @Override public Iterable<ReferenceInfo> getReferenceInfo() { Iterable<ReferenceInfo> parentReferences = super.getReferenceInfo(); Iterable<ReferenceInfo> mapReferences = map.getReferenceInfo(); IteratorChain<ReferenceInfo> iteratorChain = new IteratorChain<ReferenceInfo>(parentReferences,mapReferences); return iteratorChain; } public boolean isEmpty() { return map.isEmpty(); } public PreferencesImpl clone() { PreferencesImpl clone = new PreferencesImpl(); super.deepClone(clone); clone.map = map.deepClone(); clone.createDate = createDate; clone.lastChanged = lastChanged; // we clear the patch on a clone clone.patch = new PreferencePatch(); clone.patch.setUserId( getOwnerId()); return clone; } @Override public void setOwner(User owner) { super.setOwner(owner); patch.setUserId( getOwnerId()); } public PreferencePatch getPatch() { return patch; } /** * @see org.rapla.entities.Named#getName(java.util.Locale) */ public String getName(Locale locale) { StringBuffer buf = new StringBuffer(); if ( getOwner() != null) { buf.append( "Preferences of "); buf.append( getOwner().getName( locale)); } else { buf.append( "Rapla Preferences!"); } return buf.toString(); } /* (non-Javadoc) * @see org.rapla.entities.configuration.Preferences#getEntryAsBoolean(java.lang.String, boolean) */ public Boolean getEntryAsBoolean(TypedComponentRole<Boolean> role, boolean defaultValue) { String entry = getEntryAsString( role.getId()); if ( entry == null) return defaultValue; return Boolean.valueOf(entry).booleanValue(); } /* (non-Javadoc) * @see org.rapla.entities.configuration.Preferences#getEntryAsInteger(java.lang.String, int) */ public Integer getEntryAsInteger(TypedComponentRole<Integer> role, int defaultValue) { String entry = getEntryAsString( role.getId()); if ( entry == null) return defaultValue; return Integer.parseInt(entry); } public boolean needsChange(DynamicType type) { return map.needsChange(type); } public void commitChange(DynamicType type) { map.commitChange(type); patch.commitChange(type); } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { map.commitRemove(type); patch.commitRemove(type); } public String toString() { return super.toString() + " " + map.toString(); } public <T extends RaplaObject> void putEntry(TypedComponentRole<T> role,T entry) { putEntryPrivate( role.getId(), entry); } public void applyPatch(PreferencePatch patch) { checkWritable(); Set<String> removedEntries = patch.getRemovedEntries(); for (String key:patch.keySet()) { Object value = patch.get( key); updateMap(key, value); } for ( String remove:removedEntries) { updateMap(remove, null); } } public <T extends RaplaObject> T getEntry(TypedComponentRole<T> role) { return getEntry( role, null); } public <T extends RaplaObject> T getEntry(TypedComponentRole<T> role, T defaultValue) { return getEntry( role.getId(), defaultValue); } public boolean hasEntry(TypedComponentRole<?> role) { return map.get( role.getId() ) != null; } public void putEntry(TypedComponentRole<Boolean> role, Boolean entry) { putEntry_(role, entry != null ? entry.toString(): null); } public void putEntry(TypedComponentRole<Integer> role, Integer entry) { putEntry_(role, entry != null ? entry.toString() : null); } public void putEntry(TypedComponentRole<String> role, String entry) { putEntry_(role, entry); } protected void putEntry_(TypedComponentRole<?> role, Object entry) { checkWritable(); String key = role.getId(); updateMap(key, entry); // if ( entry == null) // { // map.remove( id); // } // else // { // map.put( id ,entry.toString()); // } } public static String getPreferenceIdFromUser(String userId) { String preferenceId = (userId != null ) ? Preferences.ID_PREFIX + userId : SYSTEM_PREFERENCES_ID; return preferenceId.intern(); } @Deprecated public Configuration getOldPluginConfig(String pluginClassName) { RaplaConfiguration raplaConfig = getEntry(RaplaComponent.PLUGIN_CONFIG); Configuration pluginConfig = null; if ( raplaConfig != null) { pluginConfig = raplaConfig.find("class", pluginClassName); } if ( pluginConfig == null) { pluginConfig = new RaplaConfiguration("plugin"); } return pluginConfig; } // public static boolean isServerEntry(String configRole) { // if ( configRole == null) // { // return false; // } // if ( configRole.startsWith("server.") || configRole.contains(".server.")) // { // return true; // } // return false; // } }
Java
/*--------------------------------------------------------------------------* | C o//pyright (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.configuration.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.rapla.components.util.iterator.FilterIterator; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.components.util.iterator.NestedIterator; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.ReadOnlyException; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.entities.configuration.RaplaMap; import org.rapla.entities.domain.Allocatable; 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.internal.ReferenceHandler; /** Maps can only support one type value at a time. Especially a mixture out of references and other values is not supported*/ public class RaplaMapImpl implements EntityReferencer, DynamicTypeDependant, RaplaObject, RaplaMap { //this map stores all objects in the map private Map<String,String> constants; private Map<String,RaplaConfiguration> configurations; private Map<String,RaplaMapImpl> maps; private Map<String,CalendarModelConfigurationImpl> calendars; protected LinkReferenceHandler links; transient protected Map<String,Object> map; transient EntityResolver resolver; static private RaplaType[] SUPPORTED_TYPES = new RaplaType[] { Allocatable.TYPE, Category.TYPE, DynamicType.TYPE}; // this map only stores the references // this map only stores the child objects (not the references) public RaplaMapImpl() { } public <T> RaplaMapImpl( Collection<T> list) { this( makeMap(list) ); } public RaplaType getRaplaType() { return RaplaMap.TYPE; } private static <T> Map<String,T> makeMap(Collection<T> list) { Map<String,T> map = new TreeMap<String,T>(); int key = 0; for ( Iterator<T> it = list.iterator();it.hasNext();) { T next = it.next(); if ( next == null) { System.err.println("Adding null value in list" ); } map.put( new String( String.valueOf(key++)), next); } return map; } public RaplaMapImpl( Map<String,?> map) { for ( Iterator<String> it = map.keySet().iterator();it.hasNext();) { String key = it.next(); Object o = map.get(key ); putPrivate(key, o); } } /** This method is only used in storage operations, please dont use it from outside, as it skips type protection and resolving*/ public void putPrivate(String key, Object value) { cachedEntries = null; if ( value == null) { if (links != null) { links.removeWithKey(key); } if ( maps != null) { maps.remove( key); } if ( map != null) { map.remove( key); } if ( configurations != null) { configurations.remove(key); } if ( maps != null) { maps.remove(key); } if ( calendars != null) { calendars.remove(key); } if ( constants != null) { constants.remove(key); } return; } // if ( ! (value instanceof RaplaObject ) && !(value instanceof String) ) // { // } if ( value instanceof Entity) { Entity entity = (Entity) value; String id = entity.getId(); RaplaType raplaType = entity.getRaplaType(); if ( !isTypeSupportedAsLink( raplaType)) { throw new IllegalArgumentException("RaplaType " + raplaType + " cannot be stored as link in map"); } putIdPrivate(key, id, raplaType); } else if ( value instanceof RaplaConfiguration) { if ( configurations == null) { configurations = new LinkedHashMap<String,RaplaConfiguration>(); } configurations.put( key, (RaplaConfiguration) value); getMap().put(key, value); } else if ( value instanceof RaplaMap) { if ( maps == null) { maps = new LinkedHashMap<String,RaplaMapImpl>(); } maps.put( key, (RaplaMapImpl) value); getMap().put(key, value); } else if ( value instanceof CalendarModelConfiguration) { if ( calendars == null) { calendars = new LinkedHashMap<String,CalendarModelConfigurationImpl>(); } calendars.put( key, (CalendarModelConfigurationImpl) value); getMap().put(key, value); } else if ( value instanceof String) { if ( constants == null) { constants = new LinkedHashMap<String,String>(); } constants.put( key , (String) value); getMap().put(key, value); } else { throw new IllegalArgumentException("Map type not supported only category, dynamictype, allocatable, raplamap, raplaconfiguration or String."); } } private Map<String, Object> getMap() { if (links != null) { Map<String, ?> linkMap = links.getLinkMap(); @SuppressWarnings("unchecked") Map<String,Object> casted = (Map<String,Object>)linkMap; return casted; } if ( maps == null && configurations == null && constants == null && calendars == null) { return Collections.emptyMap(); } if ( map == null) { map = new LinkedHashMap<String,Object>(); fillMap(maps); fillMap(configurations); fillMap(constants); fillMap(calendars); } return map; } private void fillMap(Map<String, ?> map) { if ( map == null) { return; } this.map.putAll( map); } public void putIdPrivate(String key, String id, RaplaType raplaType) { cachedEntries = null; if ( links == null) { links = new LinkReferenceHandler(); links.setLinkType( raplaType.getLocalName()); if ( resolver != null) { links.setResolver( resolver); } } links.putId( key,id); map = null; } @Override public Iterable<ReferenceInfo> getReferenceInfo() { NestedIterator<ReferenceInfo,EntityReferencer> refIt = new NestedIterator<ReferenceInfo,EntityReferencer>( getEntityReferencers()) { public Iterable<ReferenceInfo> getNestedIterator(EntityReferencer obj) { Iterable<ReferenceInfo> referencedIds = obj.getReferenceInfo(); return referencedIds; } }; if ( links == null) { return refIt; } Iterable<ReferenceInfo> referencedLinks = links.getReferenceInfo(); return new IteratorChain<ReferenceInfo>( refIt, referencedLinks); } private Iterable<EntityReferencer> getEntityReferencers() { return new FilterIterator<EntityReferencer>( getMap().values()) { protected boolean isInIterator(Object obj) { return obj instanceof EntityReferencer; } }; } /* public Iterator getReferences() { return getReferenceHandler().getReferences(); } public boolean isRefering(Entity entity) { return getReferenceHandler().isRefering( entity); }*/ public void setResolver( EntityResolver resolver) { this.resolver = resolver; if ( links != null) { links.setResolver( resolver ); } setResolver( calendars); setResolver( maps ); map = null; } private void setResolver(Map<String,? extends EntityReferencer> map) { if ( map == null) { return; } for (EntityReferencer ref:map.values()) { ref.setResolver( resolver); } } public Object get(Object key) { if (links != null) { return links.getEntity((String)key); } return getMap().get(key); } /** * @see java.util.Map#clear() */ public void clear() { throw createReadOnlyException(); } protected ReadOnlyException createReadOnlyException() { return new ReadOnlyException("RaplaMap is readonly you must create a new Object"); } /** * @see java.util.Map#size() */ public int size() { return getMap().size(); } /** * @see java.util.Map#isEmpty() */ public boolean isEmpty() { return getMap().isEmpty(); } /** * @see java.util.Map#containsKey(java.lang.Object) */ public boolean containsKey(Object key) { return getMap().containsKey( key); } /** * @see java.util.Map#containsValue(java.lang.Object) */ public boolean containsValue(Object key) { return getMap().containsValue( key); } /** * @see java.util.Map#keySet() */ public Set<String> keySet() { return getMap().keySet(); } public boolean needsChange(DynamicType type) { for (Iterator it = getMap().values().iterator();it.hasNext();) { Object obj = it.next(); if ( obj instanceof DynamicTypeDependant) { if (((DynamicTypeDependant) obj).needsChange( type )) return true; } } return false; } public void commitChange(DynamicType type) { for (Object obj:getMap().values()) { if ( obj instanceof DynamicTypeDependant) { ((DynamicTypeDependant) obj).commitChange( type ); } } } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { for (Object obj:getMap().values()) { if ( obj instanceof DynamicTypeDependant) { ((DynamicTypeDependant) obj).commitRemove( type ); } } } /** Clones the entity and all subentities*/ public RaplaMapImpl deepClone() { RaplaMapImpl clone = new RaplaMapImpl(getMap()); clone.setResolver( resolver ); return clone; } // public Collection<RaplaObject> getLinkValues() // { // ArrayList<RaplaObject> result = new ArrayList<RaplaObject>(); // EntityResolver resolver = getReferenceHandler().getResolver(); // for (String id: getReferencedIds()) // { // result.add( resolver.tryResolve( id)); // } // return result; // // } /** Clones the entity while preserving the references to the subentities*/ public Object clone() { return deepClone(); } /** * @see java.util.Map#put(java.lang.Object, java.lang.Object) */ public Object put(Object key, Object value) { throw createReadOnlyException(); } public Object remove(Object arg0) { throw createReadOnlyException(); } /** * @see java.util.Map#putAll(java.util.Map) */ public void putAll(Map m) { throw createReadOnlyException(); } /** * @see java.util.Map#values() */ public Collection values() { if ( links == null) { return getMap().values(); } else { List<Entity> result = new ArrayList<Entity>(); Iterable<String> values = links.getReferencedIds(); for (String id: values) { Entity resolved = links.getResolver().tryResolve( id); result.add( resolved); } return result; } } public static final class LinkReferenceHandler extends ReferenceHandler { protected String linkType; transient private Class<? extends Entity> linkClass; protected Class<? extends Entity> getInfoClass(String key) { return getLinkClass(); } public Iterable<String> getReferencedIds() { Set<String> result = new HashSet<String>(); if (links != null) { for (List<String> entries:links.values()) { for ( String id: entries) { result.add(id); } } } return result; } public Entity getEntity(String key) { Class<? extends Entity> linkClass = getLinkClass(); return getEntity(key, linkClass); } private Class<? extends Entity> getLinkClass() { if ( linkClass != null) { return linkClass; } if ( linkType != null ) { for ( RaplaType type: SUPPORTED_TYPES ) { if (linkType.equals( type.getLocalName())) { @SuppressWarnings("unchecked") Class<? extends Entity> casted = type.getTypeClass(); this.linkClass = casted; return linkClass; } } } return null; } public void setLinkType(String type) { this.linkType = type; linkClass = null; } } class Entry implements Map.Entry<String, Object> { String key; String id; Entry(String key,String id) { this.key = key; this.id = id; if ( id == null) { throw new IllegalArgumentException("Empty id added"); } } public String getKey() { return key; } public Object getValue() { if ( id == null) { return null; } Entity resolve = links.getResolver().tryResolve( id ); return resolve; } public Object setValue(Object value) { throw new UnsupportedOperationException(); } public int hashCode() { return key.hashCode(); } @Override public boolean equals(Object obj) { return key.equals( ((Entry) obj).key); } public String toString() { Entity value = links.getResolver().tryResolve( id ); return key + "=" + ((value != null) ? value : "unresolvable_" + id); } } transient Set<Map.Entry<String, Object>> cachedEntries; public Set<Map.Entry<String, Object>> entrySet() { if ( links != null) { if ( cachedEntries == null) { cachedEntries = new HashSet<Map.Entry<String, Object>>(); for (String key:links.getReferenceKeys()) { String id = links.getId( key); if ( id == null) { System.err.println("Empty id " + id); } cachedEntries.add(new Entry( key, id)); } } return cachedEntries; } else { if ( cachedEntries == null) { cachedEntries = new HashSet<Map.Entry<String, Object>>(); for (Map.Entry<String,Object> entry:getMap().entrySet()) { if ( entry.getValue() == null) { System.err.println("Empty value for " + entry.getKey()); } cachedEntries.add((Map.Entry<String, Object>) entry); } } return cachedEntries; } } public String toString() { return entrySet().toString(); } public boolean isTypeSupportedAsLink(RaplaType raplaType) { for ( RaplaType type: SUPPORTED_TYPES ) { if ( type == raplaType) { 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; /**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; 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; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; /** Some entities (especially dynamic-types and attributes) can have multiple names to allow easier reuse of created schemas or support for multi-language-environments. @see MultiLanguageNamed */ public class MultiLanguageName implements java.io.Serializable { // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; Map<String,String> mapLocales = new TreeMap<String,String>(); transient private boolean readOnly; public MultiLanguageName(String language,String translation) { setName(language,translation); } public MultiLanguageName(String[][] data) { for (int i=0;i<data.length;i++) setName(data[i][0],data[i][1]); } public MultiLanguageName() { } public void setReadOnly() { this.readOnly = true; } public boolean isReadOnly() { return this.readOnly; } public String getName(String language) { if ( language == null) { language = "en"; } String result = mapLocales.get(language); if (result == null) { result = mapLocales.get("en"); } if (result == null) { Iterator<String> it = mapLocales.values().iterator(); if (it.hasNext()) result = it.next(); } if (result == null) { result = ""; } return result; } public void setName(String language,String translation) { checkWritable(); setNameWithoutReadCheck(language, translation); } private void checkWritable() { if ( isReadOnly() ) throw new ReadOnlyException("Can't modify this multilanguage name."); } public void setTo(MultiLanguageName newName) { checkWritable(); mapLocales = new TreeMap<String,String>(newName.mapLocales); } public Collection<String> getAvailableLanguages() { return mapLocales.keySet(); } public Object clone() { MultiLanguageName newName= new MultiLanguageName(); newName.mapLocales.putAll(mapLocales); return newName; } public String toString() { return getName("en"); } @Deprecated public void setNameWithoutReadCheck(String language, String translation) { if (translation != null && !translation.trim().equals("")) { mapLocales.put(language,translation.trim()); } else { mapLocales.remove(language); } } }
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; 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.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) 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.internal; import java.util.Collection; import java.util.Date; import java.util.Locale; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.framework.RaplaException; public class UserImpl extends SimpleEntity implements User, ModifiableTimestamp { private String username = ""; private String email = ""; private String name = ""; private boolean admin = false; private Date lastChanged; private Date createDate; // The resolved references transient private Category[] groups; final public RaplaType<User> getRaplaType() {return TYPE;} UserImpl() { this(null,null); } public UserImpl(Date createDate,Date lastChanged) { this.createDate = createDate; this.lastChanged = lastChanged; } 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 boolean isAdmin() {return admin;} public String getName() { final Allocatable person = getPerson(); if ( person != null) { return person.getName( null ); } return name; } public String getEmail() { final Allocatable person = getPerson(); if ( person != null) { final Classification classification = person.getClassification(); final Attribute attribute = classification.getAttribute("email"); return attribute != null ? (String)classification.getValue(attribute) : null; } return email; } public String getUsername() { return username; } public String toString() { return getUsername(); } public void setName(String name) { checkWritable(); this.name = name; } public void setEmail(String email) { checkWritable(); this.email = email; } public void setUsername(String username) { checkWritable(); this.username = username; } public void setAdmin(boolean bAdmin) { checkWritable(); this.admin=bAdmin; } public String getName(Locale locale) { final Allocatable person = getPerson(); if ( person != null) { return person.getName(locale); } final String name = getName(); if ( name == null || name.length() == 0) { return getUsername(); } else { return name; } } public void addGroup(Category group) { checkWritable(); if ( isRefering("groups", group.getId())) { return; } groups = null; add("groups",group); } public boolean removeGroup(Category group) { checkWritable(); return removeId(group.getId()); } public Category[] getGroups() { updateGroupArray(); return groups; } public boolean belongsTo( Category group ) { for (Category uGroup:getGroups()) { if (group.equals( uGroup) || group.isAncestorOf( uGroup)) { return true; } } return false; } private void updateGroupArray() { if (groups != null) return; synchronized ( this ) { Collection<Category> groupList = getList("groups", Category.class); groups = groupList.toArray(Category.CATEGORY_ARRAY); } } public User clone() { UserImpl clone = new UserImpl(); super.deepClone(clone); clone.groups = null; clone.username = username; clone.name = name; clone.email = email; clone.admin = admin; clone.lastChanged = lastChanged; clone.createDate = createDate; return clone; } public int compareTo(User o) { int result = toString().compareTo( o.toString()); if (result != 0) { return result; } else { return super.compareTo( o); } } public void setPerson(Allocatable person) throws RaplaException { checkWritable(); if ( person == null) { putEntity("person", null); return; } final Classification classification = person.getClassification(); final Attribute attribute = classification.getAttribute("email"); final String email = attribute != null ? (String)classification.getValue(attribute) : null; if ( email == null || email.length() == 0) { throw new RaplaException("Email of " + person + " not set. Linking to user needs an email "); } else { this.email = email; putEntity("person", (Entity) person); setName(person.getClassification().getName(null)); } } public Allocatable getPerson() { final Allocatable person = getEntity("person", Allocatable.class); return person; } }
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.internal; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; 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.IllegalAnnotationException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.ParentEntity; import org.rapla.entities.storage.internal.SimpleEntity; final public class CategoryImpl extends SimpleEntity implements Category, ParentEntity, ModifiableTimestamp { private MultiLanguageName name = new MultiLanguageName(); private String key; Set<CategoryImpl> childs = new LinkedHashSet<CategoryImpl>(); private Date lastChanged; private Date createDate; private Map<String,String> annotations = new LinkedHashMap<String,String>(); private transient Category parent; CategoryImpl() { } public CategoryImpl(Date createDate, Date lastChanged) { this.createDate = createDate; this.lastChanged = lastChanged; } @Override public void setResolver(EntityResolver resolver) { super.setResolver(resolver); for (CategoryImpl child:childs) { child.setParent( this); } } @Override public void addEntity(Entity entity) { childs.add( (CategoryImpl) entity); } public Date getLastChanged() { return lastChanged; } @Deprecated public Date getLastChangeTime() { return lastChanged; } public Date getCreateTime() { return createDate; } public void setLastChanged(Date date) { checkWritable(); lastChanged = date; for ( CategoryImpl child:childs) { child.setLastChanged( date); } } public RaplaType<Category> getRaplaType() {return TYPE;} void setParent(CategoryImpl parent) { putEntity("parent", parent); this.parent = parent; } public void removeParent() { removeWithKey("parent"); this.parent = null; } public Category getParent() { if ( parent == null) { parent = getEntity("parent", Category.class); } return parent; } public Category[] getCategories() { return childs.toArray(Category.CATEGORY_ARRAY); } @SuppressWarnings("unchecked") public Collection<CategoryImpl> getSubEntities() { return childs; } public boolean isAncestorOf(Category category) { if (category == null) return false; if (category.getParent() == null) return false; if (category.getParent().equals(this)) return true; else return isAncestorOf(category.getParent()); } public Category getCategory(String key) { for (Entity ref: getSubEntities()) { Category cat = (Category) ref; if (cat.getKey().equals(key)) return cat; } return null; } public boolean hasCategory(Category category) { return childs.contains(category); } public void addCategory(Category category) { checkWritable(); Assert.isTrue(category.getParent() == null || category.getParent().equals(this) ,"Category is already attached to a parent"); CategoryImpl categoryImpl = (CategoryImpl)category; if ( resolver != null) { Assert.isTrue( !categoryImpl.isAncestorOf( this), "Can't add a parent category to one of its ancestors."); } addEntity( (Entity) category); categoryImpl.setParent(this); } public int getRootPathLength() { Category parent = getParent(); if ( parent == null) { return 0; } else { int parentDepth = parent.getRootPathLength(); return parentDepth + 1; } } public int getDepth() { int max = 0; Category[] categories = getCategories(); for (int i=0;i<categories.length;i++) { int depth = categories[i].getDepth(); if (depth > max) max = depth; } return max + 1; } public void removeCategory(Category category) { checkWritable(); if ( findCategory( category ) == null) return; childs.remove(category); //if (category.getParent().equals(this)) ((CategoryImpl)category).setParent(null); } public Category findCategory(Category copy) { return (Category) super.findEntity((Entity)copy); } public MultiLanguageName getName() { return name; } public void setReadOnly() { super.setReadOnly( ); name.setReadOnly( ); } public String getName(Locale locale) { if ( locale == null) { locale = Locale.getDefault(); } return name.getName(locale.getLanguage()); } public String getKey() { return key; } public void setKey(String key) { checkWritable(); this.key = key; } public String getPath(Category rootCategory,Locale locale) { StringBuffer buf = new StringBuffer(); if (rootCategory != null && this.equals(rootCategory)) return ""; if (this.getParent() != null) { String path = this.getParent().getPath(rootCategory,locale); buf.append(path); if (path.length()>0) buf.append('/'); } buf.append(this.getName(locale)); return buf.toString(); } public List<String> getKeyPath(Category rootCategory) { LinkedList<String> result = new LinkedList<String>(); if (rootCategory != null && this.equals(rootCategory)) return result; Category cat = this; while (cat.getParent() != null) { Category parent = cat.getParent(); result.addFirst( parent.getKey()); cat = parent; if ( parent == this) { throw new IllegalStateException("Parent added as own child"); } } result.add( getKey()); return result; } public String toString() { MultiLanguageName name = getName(); if (name != null) { return name.toString() + " ID='" + getId() + "'"; } else { return getKey() + " " + getId(); } } public String getPathForCategory(Category searchCategory) throws EntityNotFoundException { List<String> keyPath = getPathForCategory(searchCategory, true); return getKeyPathString(keyPath); } public static String getKeyPathString(List<String> keyPath) { StringBuffer buf = new StringBuffer(); for (String category:keyPath) { buf.append('/'); buf.append(category); } if ( buf.length() > 0) { buf.deleteCharAt(0); } String pathForCategory = buf.toString(); return pathForCategory ; } public List<String> getPathForCategory(Category searchCategory, boolean fail) throws EntityNotFoundException { LinkedList<String> result = new LinkedList<String>(); Category category = searchCategory; Category parent = category.getParent(); if (category == this) return result; if (parent == null) throw new EntityNotFoundException("Category has no parents!"); while (true) { String entry ="category[key='" + category.getKey() + "']"; result.addFirst(entry); parent = category.getParent(); category = parent; if (parent == null) { if ( fail) { throw new EntityNotFoundException("Category not found!" + searchCategory); } return null; } if (parent.equals(this)) break; } return result; } public Category getCategoryFromPath(String path) throws EntityNotFoundException { int start = 0; int end = 0; int pos = 0; Category category = this; while (category != null) { start = path.indexOf("'",pos) + 1; if (start==0) break; end = path.indexOf("'",start); if (end < 0) throw new EntityNotFoundException("Invalid xpath expression: " + path); String key = path.substring(start,end); category = category.getCategory(key); pos = end + 1; } if (category == null) throw new EntityNotFoundException("could not resolve category xpath expression: " + path); return category; } public Category findCategory(Object copy) { return (Category) super.findEntity((Entity)copy); } 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; } annotations.put(key,annotation); } public String[] getAnnotationKeys() { return annotations.keySet().toArray(RaplaObject.EMPTY_STRING_ARRAY); } @SuppressWarnings("unchecked") public Category clone() { CategoryImpl clone = new CategoryImpl(); super.deepClone(clone); clone.name = (MultiLanguageName) name.clone(); clone.parent = parent; clone.annotations = (HashMap<String,String>) ((HashMap<String,String>)annotations).clone(); clone.key = key; clone.lastChanged = lastChanged; clone.createDate = createDate; for (Entity ref:clone.getSubEntities()) { ((CategoryImpl)ref).setParent(clone); } return clone; } public int compareTo(Object o) { if ( o == this ) { return 0; } if ( equals( o )) { return 0; } Category c1= this; Category c2= (Category) o; if ( c1.isAncestorOf( c2)) { return -1; } if ( c2.isAncestorOf( c1)) { return 1; } while ( c1.getRootPathLength() > c2.getRootPathLength()) { c1 = c1.getParent(); } while ( c2.getRootPathLength() > c2.getRootPathLength()) { c2 = c2.getParent(); } while ( c1.getParent() != null && c2.getParent() != null && (!c1.getParent().equals( c2.getParent()))) { c1 = c1.getParent(); c2 = c2.getParent(); } //now the two categories have the same parent if ( c1.getParent() == null || c2.getParent() == null) { return super.compareTo( o); } Category parent = c1.getParent(); // We look who is first in the list Category[] categories = parent.getCategories(); for ( Category category: categories) { if ( category.equals( c1)) { return -1; } if ( category.equals( c2)) { return 1; } } return super.compareTo( o); } public void replace(Category category) { String id = category.getId(); CategoryImpl existingEntity = (CategoryImpl) findEntityForId(id); if ( existingEntity != null) { LinkedHashSet<CategoryImpl> newChilds = new LinkedHashSet<CategoryImpl>(); for ( CategoryImpl child: childs) { newChilds.add( ( child != existingEntity) ? child: (CategoryImpl)category); } childs = newChilds; } } }
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.internal; import java.util.Date; import org.rapla.entities.Timestamp; import org.rapla.entities.User; public interface ModifiableTimestamp extends Timestamp { /** updates the last-changed timestamp */ void setLastChanged(Date date); void setLastChangedBy( User user); }
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
package org.rapla.framework; import java.util.HashMap; public class RaplaDefaultContext implements RaplaContext { private final HashMap<String,Object> contextObjects = new HashMap<String,Object>(); protected final RaplaContext parent; public RaplaDefaultContext() { this( null ); } public RaplaDefaultContext( final RaplaContext parent ) { this.parent = parent; } /** * @throws RaplaContextException */ protected Object lookup( final String key ) throws RaplaContextException { return contextObjects.get( key ); } protected boolean has( final String key ) { return contextObjects.get( key ) != null; } public <T> void put(Class<T> componentRole, T instance) { contextObjects.put(componentRole.getName(), instance ); } public <T> void put(TypedComponentRole<T> componentRole, T instance) { contextObjects.put(componentRole.getId(), instance ); } public boolean has(Class<?> componentRole) { if (has(componentRole.getName())) { return true; } return parent != null && parent.has( componentRole); } public boolean has(TypedComponentRole<?> componentRole) { if (has( componentRole.getId())) { return true; } return parent != null && parent.has( componentRole); } @SuppressWarnings("unchecked") public <T> T lookup(Class<T> componentRole) throws RaplaContextException { final String key = componentRole.getName(); T lookup = (T) lookup(key); if ( lookup == null) { if ( parent != null) { return parent.lookup( componentRole); } else { throw new RaplaContextException( key ); } } return lookup; } @SuppressWarnings("unchecked") public <T> T lookup(TypedComponentRole<T> componentRole) throws RaplaContextException { final String key = componentRole.getId(); T lookup = (T) lookup(key); if ( lookup == null) { if ( parent != null) { return parent.lookup( componentRole); } else { throw new RaplaContextException( key ); } } return lookup; } // @SuppressWarnings("unchecked") // public <T> T lookup(TypedComponentRole<T> componentRole, String hint) throws RaplaContextException { // String key = componentRole.getId()+ "/" + hint; // T lookup = (T) lookup(key); // if ( lookup == null) // { // if ( parent != null) // { // return parent.lookup( componentRole, hint); // } // else // { // throw new RaplaContextException( key ); // } // } // return lookup; // } }
Java
package org.rapla.framework; public class ConfigurationException extends Exception { private static final long serialVersionUID = 1L; public ConfigurationException(String string, Throwable exception) { super( string, exception); } public ConfigurationException(String string) { super( string ); } }
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.framework; /** the base-class for all Rapla specific Exceptions */ public class RaplaException extends Exception { private static final long serialVersionUID = 1L; public RaplaException(String text) { super(text); } public RaplaException(Throwable throwable) { super(throwable.getMessage(),throwable); } public RaplaException(String text,Throwable ex) { super(text,ex); } }
Java
package org.rapla.framework; public class RaplaSynchronizationException extends RaplaException { private static final long serialVersionUID = 1L; public RaplaSynchronizationException(String text) { super(text); } public RaplaSynchronizationException(Throwable ex) { super( ex.getMessage(), ex); } }
Java
package org.rapla.framework; public interface Configuration { String getName(); Configuration getChild(String name); Configuration[] getChildren(String name); Configuration[] getChildren(); String getValue() throws ConfigurationException; String getValue(String defaultValue); boolean getValueAsBoolean(boolean defaultValue); long getValueAsLong(int defaultValue); int getValueAsInteger(int defaultValue); String getAttribute(String name) throws ConfigurationException; String getAttribute(String name, String defaultValue); boolean getAttributeAsBoolean(String string, boolean defaultValue); String[] getAttributeNames(); public Configuration find( String localName); public Configuration find( String attributeName, String attributeValue); }
Java
package org.rapla.framework; public class SimpleProvider<T> implements Provider<T> { T value; public T get() { return value; } public void setValue(T value) { this.value = value; } }
Java
package org.rapla.framework; public interface Disposable { public void dispose(); }
Java
package org.rapla.framework.logger; public class NullLogger extends AbstractLogger { public NullLogger() { super(LEVEL_FATAL); } public Logger getChildLogger(String childLoggerName) { return this; } protected void write(int logLevel, String message, Throwable cause) { } }
Java
package org.rapla.framework.logger; public class ConsoleLogger extends AbstractLogger { String prefix; public ConsoleLogger(int logLevel) { super(logLevel); } public ConsoleLogger(String prefix,int logLevel) { super(logLevel); this.prefix = prefix; } public ConsoleLogger() { this(LEVEL_INFO); } public Logger getChildLogger(String prefix) { String newPrefix = prefix; if ( this.prefix != null) { newPrefix = this.prefix + "." + prefix; } return new ConsoleLogger( newPrefix, logLevel); } String getLogLevelString(int logLevel) { switch (logLevel) { case LEVEL_DEBUG: return "DEBUG"; case LEVEL_INFO: return "INFO"; case LEVEL_WARN: return "WARN"; case LEVEL_ERROR: return "ERROR"; case LEVEL_FATAL: return "FATAL"; } return ""; } protected void write(int logLevel, String message, Throwable cause) { String logLevelString = getLogLevelString( logLevel ); StringBuffer buf = new StringBuffer(); buf.append( logLevelString ); buf.append( " " ); if ( prefix != null) { buf.append( prefix); buf.append( ": " ); } if ( message != null) { buf.append( message); if ( cause != null) { buf.append( ": " ); } } while( cause!= null) { StackTraceElement[] stackTrace = cause.getStackTrace(); buf.append( cause.getMessage()); buf.append( "\n" ); for ( StackTraceElement element:stackTrace) { buf.append(" "); buf.append( element.toString()); buf.append( "\n"); } cause = cause.getCause(); if ( cause != null) { buf.append(" caused by "); buf.append( cause.getMessage()); buf.append( " " ); } } System.out.println(buf.toString()); } }
Java
package org.rapla.framework.logger; public interface Logger { boolean isDebugEnabled(); void debug(String message); void info(String message); void warn(String message); void warn(String message, Throwable cause); void error(String message); void error(String message, Throwable cause); Logger getChildLogger(String childLoggerName); }
Java
package org.rapla.framework.logger; public abstract class AbstractLogger implements Logger{ protected int logLevel; public static final int LEVEL_FATAL = 4; public static final int LEVEL_ERROR = 3; public static final int LEVEL_WARN = 2; public static final int LEVEL_INFO = 1; public static final int LEVEL_DEBUG = 0; public AbstractLogger(int logLevel) { this.logLevel = logLevel; } public void error(String message, Throwable cause) { log( LEVEL_ERROR,message, cause); } private void log(int logLevel, String message) { log( logLevel, message, null); } private void log(int logLevel, String message, Throwable cause) { if ( logLevel < this.logLevel) { return; } write( logLevel, message, cause); } protected abstract void write(int logLevel, String message, Throwable cause); public void debug(String message) { log( LEVEL_DEBUG,message); } public void info(String message) { log( LEVEL_INFO,message); } public void warn(String message) { log( LEVEL_WARN,message); } public void warn(String message, Throwable cause) { log( LEVEL_WARN,message, cause); } public void error(String message) { log( LEVEL_ERROR,message); } public void fatalError(String message) { log( LEVEL_FATAL,message); } public void fatalError(String message, Throwable cause) { log( LEVEL_FATAL,message, cause); } public boolean isDebugEnabled() { return logLevel<= LEVEL_DEBUG; } }
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.framework; import java.util.Collection; public interface Container extends Disposable { StartupEnvironment getStartupEnvironment(); RaplaContext getContext(); /** lookup an named component from the raplaserver.xconf */ <T> T lookup(Class<T> componentRole, String hint) throws RaplaContextException; <T,I extends T> void addContainerProvidedComponent(Class<T> roleInterface,Class<I> implementingClass); <T,I extends T> void addContainerProvidedComponent(Class<T> roleInterface,Class<I> implementingClass, Configuration config); <T,I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass); <T,I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass, Configuration config); /** lookup all services for this role*/ <T> Collection<T> lookupServicesFor(TypedComponentRole<T> extensionPoint) throws RaplaContextException; /** lookup all services for this role*/ <T> Collection<T> lookupServicesFor(Class<T> role) throws RaplaContextException; }
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.framework; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.Writer; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Stack; import org.rapla.framework.logger.Logger; /** Helper Class for automated creation of the rapla-plugin.list in the * META-INF directory. Can be used in the build environment. */ public class ServiceListCreator { public static void main (String[] args) { try { String sourceDir = args[0]; String destDir = (args.length>1) ? args[1] : sourceDir; processDir(sourceDir,destDir); } catch (IOException e) { throw new RuntimeException( e.getMessage()); } catch (ClassNotFoundException e) { throw new RuntimeException( e.getMessage()); } } public static void processDir(String srcDir,String destFile) throws ClassNotFoundException, IOException { File topDir = new File(srcDir); List<String> list = findPluginClasses(topDir, null); Writer writer = new BufferedWriter(new FileWriter( destFile )); try { for ( String className:list) { System.out.println("Found PluginDescriptor for " + className); writer.write( className ); writer.write( "\n" ); } } finally { writer.close(); } } public static List<String> findPluginClasses(File topDir,Logger logger) throws ClassNotFoundException { List<String> list = new ArrayList<String>(); Stack<File> stack = new Stack<File>(); stack.push(topDir); while (!stack.empty()) { File file = stack.pop(); if (file.isDirectory()) { File[] files = file.listFiles(); for (int i=0;i<files.length;i++) stack.push(files[i]); } else { String name = file.getName(); if (file.getAbsolutePath().contains("rapla") && (name.endsWith("Plugin.class") || name.endsWith("PluginServer.class"))) { String absolut = file.getAbsolutePath(); String relativePath = absolut.substring(topDir.getAbsolutePath().length()); String pathName = relativePath.substring(1,relativePath.length()-".class".length()); String className = pathName.replace(File.separatorChar,'.'); try { Class<?> pluginClass = ServiceListCreator.class.getClassLoader().loadClass(className ); if (!pluginClass.isInterface() ) { if ( PluginDescriptor.class.isAssignableFrom(pluginClass)) { list.add( className); } else { if ( logger != null) { logger.warn("No PluginDescriptor found for Class " + className ); } } } } catch (NoClassDefFoundError ex) { System.out.println(ex.getMessage()); } } } } return list; } /** lookup for plugin classes in classpath*/ public static Collection<String> findPluginClasses(Logger logger) throws ClassNotFoundException { Collection<String> result = new LinkedHashSet<String>(); URL mainDir = ServiceListCreator.class.getResource("/"); if ( mainDir != null) { String classpath = System.getProperty("java.class.path"); final String[] split; if (classpath != null) { split = classpath.split(""+File.pathSeparatorChar); } else { split = new String[] { mainDir.toExternalForm()}; } for ( String path: split) { File pluginPath = new File(path); List<String> foundInClasspathEntry = findPluginClasses(pluginPath, logger); result.addAll(foundInClasspathEntry); } } return result; } /** lookup for plugin classes in classpath*/ public static Collection<File> findPluginWebappfolders(Logger logger) throws ClassNotFoundException { Collection<File> result = new LinkedHashSet<File>(); URL mainDir = ServiceListCreator.class.getResource("/"); if ( mainDir != null) { String classpath = System.getProperty("java.class.path"); final String[] split; if (classpath != null) { split = classpath.split(""+File.pathSeparatorChar); } else { split = new String[] { mainDir.toExternalForm()}; } FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name != null && name.equals("war"); } }; for ( String path: split) { File pluginPath = new File(path); List<String> foundInClasspathEntry = findPluginClasses(pluginPath, logger); if ( foundInClasspathEntry.size() > 0) { File parent = pluginPath.getParentFile().getAbsoluteFile(); int depth= 0; while ( parent != null && parent.isDirectory()) { File[] listFiles = parent.listFiles( filter); if (listFiles != null && listFiles.length == 1) { result.add( listFiles[0]); } depth ++; if ( depth > 5) { break; } parent = parent.getParentFile(); } } } } 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.framework; public interface PluginDescriptor<T extends Container>{ public void provideServices(T container, Configuration configuration) throws RaplaContextException; }
Java
package org.rapla.framework; public interface RaplaContext { /** Returns a reference to the requested object (e.g. a component instance). * throws a RaplaContextException if the object can't be returned. This could have * different reasons: For example it is not found in the context, or there has been * a problem during the component creation. */ <T> T lookup(Class<T> componentRole) throws RaplaContextException; boolean has(Class<?> clazz); <T> T lookup(TypedComponentRole<T> componentRole) throws RaplaContextException; //<T> T lookup(TypedComponentRole<T> componentRole, String hint) throws RaplaContextException; boolean has(TypedComponentRole<?> componentRole); }
Java
package org.rapla.framework; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class DefaultConfiguration implements Configuration { Map<String,String> attributes = new LinkedHashMap<String, String>(); List<DefaultConfiguration> children = new ArrayList<DefaultConfiguration>(); String value; String name; public DefaultConfiguration() { } public DefaultConfiguration(String localName) { this.name = localName; } public DefaultConfiguration(String localName, String value) { this.name = localName; if ( value != null) { this.value = value; } } public DefaultConfiguration(Configuration config) { this.name = config.getName(); for (Configuration conf: config.getChildren()) { children.add( new DefaultConfiguration( conf)); } this.value = ((DefaultConfiguration)config).value; attributes.putAll(((DefaultConfiguration)config).attributes); } public void addChild(Configuration configuration) { children.add( (DefaultConfiguration) configuration); } public void setAttribute(String name, boolean value) { attributes.put( name, value ? "true" : "false"); } public void setAttribute(String name, String value) { attributes.put( name, value); } public void setValue(String value) { this.value = value; } public void setValue(int intValue) { this.value = Integer.toString( intValue); } public void setValue(boolean selected) { this.value = Boolean.toString( selected); } public DefaultConfiguration getMutableChild(String name, boolean create) { for (DefaultConfiguration child:children) { if ( child.getName().equals( name)) { return child; } } if ( create ) { DefaultConfiguration newConfig = new DefaultConfiguration( name); children.add( newConfig); return newConfig; } else { return null; } } public void removeChild(Configuration child) { children.remove( child); } public String getName() { return name; } public Configuration getChild(String name) { for (DefaultConfiguration child:children) { if ( child.getName().equals( name)) { return child; } } return new DefaultConfiguration( name); } public Configuration[] getChildren(String name) { List<Configuration> result = new ArrayList<Configuration>(); for (DefaultConfiguration child:children) { if ( child.getName().equals( name)) { result.add( child); } } return result.toArray( new Configuration[] {}); } public Configuration[] getChildren() { return children.toArray( new Configuration[] {}); } public String getValue() throws ConfigurationException { if ( value == null) { throw new ConfigurationException("Value not set in configuration " + name); } return value; } public String getValue(String defaultValue) { if ( value == null) { return defaultValue; } return value; } public boolean getValueAsBoolean(boolean defaultValue) { if ( value == null) { return defaultValue; } if ( value.equalsIgnoreCase("yes")) { return true; } if ( value.equalsIgnoreCase("no")) { return false; } return Boolean.parseBoolean( value); } public long getValueAsLong(int defaultValue) { if ( value == null) { return defaultValue; } return Long.parseLong( value); } public int getValueAsInteger(int defaultValue) { if ( value == null) { return defaultValue; } return Integer.parseInt( value); } public String getAttribute(String name) throws ConfigurationException { String value = attributes.get(name); if ( value == null) { throw new ConfigurationException("Attribute " + name + " not found "); } return value; } public String getAttribute(String name, String defaultValue) { String value = attributes.get(name); if ( value == null) { return defaultValue; } return value; } public boolean getAttributeAsBoolean(String string, boolean defaultValue) { String value = getAttribute(string, defaultValue ? "true": "false"); return Boolean.parseBoolean( value); } public String[] getAttributeNames() { String[] attributeNames = attributes.keySet().toArray( new String[] {}); return attributeNames; } public Configuration find( String localName) { Configuration[] childList= getChildren(); for ( int i=0;i<childList.length;i++) { if (childList[i].getName().equals( localName)) { return childList[i]; } } return null; } public Configuration find( String attributeName, String attributeValue) { Configuration[] childList= getChildren(); for ( int i=0;i<childList.length;i++) { String attribute = childList[i].getAttribute( attributeName,null); if (attributeValue.equals( attribute)) { return childList[i]; } } return null; } public DefaultConfiguration replace( Configuration newChild) throws ConfigurationException { Configuration find = find( newChild.getName()); if ( find == null) { throw new ConfigurationException(" could not find " + newChild.getName()); } return replace( find, newChild ); } public DefaultConfiguration replace( Configuration oldChild, Configuration newChild) { String localName = getName(); DefaultConfiguration newConfig = newConfiguration(localName); boolean present = false; Configuration[] childList= getChildren(); for ( int i=0;i<childList.length;i++) { if (childList[i] != oldChild) { newConfig.addChild( childList[i]); } else { present = true; newConfig.addChild( newChild ); } } if (!present) { newConfig.addChild( newChild ); } return newConfig; } protected DefaultConfiguration newConfiguration(String localName) { return new DefaultConfiguration( localName); } public DefaultConfiguration add( Configuration newChild) { String localName = getName(); DefaultConfiguration newConfig = newConfiguration(localName); boolean present = false; Configuration[] childList= getChildren(); for ( int i=0;i<childList.length;i++) { if (childList[i] == newChild) { present = true; } } if (!present) { newConfig.addChild( newChild ); } return newConfig; } /** * @param configuration * @throws ConfigurationException */ public DefaultConfiguration remove(Configuration configuration) { String localName = getName(); DefaultConfiguration newConfig = newConfiguration(localName); Configuration[] childList= getChildren(); for ( int i=0;i<childList.length;i++) { if (childList[i] != configuration) { newConfig.addChild( childList[i]); } } return newConfig; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((attributes == null) ? 0 : attributes.hashCode()); result = prime * result + ((children == null) ? 0 : children.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DefaultConfiguration other = (DefaultConfiguration) obj; if (attributes == null) { if (other.attributes != null) return false; } else if (!attributes.equals(other.attributes)) return false; if (children == null) { if (other.children != null) return false; } else if (!children.equals(other.children)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append( name); if (attributes.size() > 0) { buf.append( "["); boolean first= true; for ( Map.Entry<String, String> entry: attributes.entrySet()) { if (!first) { buf.append( ", "); } else { first = false; } buf.append(entry.getKey()); buf.append( "='"); buf.append(entry.getValue()); buf.append( "'"); } buf.append( "]"); } buf.append( "{"); boolean first= true; for ( Configuration child:children) { if (first) { buf.append("\n"); first =false; } buf.append( child.toString()); buf.append("\n"); } if ( value != null) { buf.append( value); } buf.append( "}"); return buf.toString(); } }
Java
package org.rapla.framework; @SuppressWarnings("unused") public class TypedComponentRole<T> { String id; public TypedComponentRole(String id) { this.id = id.intern(); } public String getId() { return id; } public String toString() { return id; } public boolean equals(Object obj) { if (obj == null) { return false; } if ( !(obj instanceof TypedComponentRole)) { return false; } return id.equals(obj.toString()); } @Override public int hashCode() { return id.hashCode(); } }
Java
package org.rapla.framework; import java.net.URL; import org.rapla.framework.logger.Logger; public interface StartupEnvironment { int CONSOLE = 1; int WEBSTART = 2; int APPLET = 3; Configuration getStartupConfiguration() throws RaplaException; URL getDownloadURL() throws RaplaException; URL getConfigURL() throws RaplaException; /** either EMBEDDED, CONSOLE, WEBSTART, APPLET,SERVLET or CLIENT */ int getStartupMode(); URL getContextRootURL() throws RaplaException; Logger getBootstrapLogger(); }
Java
package org.rapla.framework; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.rapla.components.util.SerializableDateTimeFormat; /** This class contains all locale specific information for Rapla. Like <ul> <li>Selected language.</li> <li>Selected country.</li> <li>Available languages (if the user has the possibility to choose a language)</li> <li>TimeZone for appointments (This is always GMT+0)</li> </ul> <p> Also it provides basic formating information for the dates. </p> <p> Configuration is done in the rapla.xconf: <pre> &lt;locale> &lt;languages default="de"> &lt;language>de&lt;/language> &lt;language>en&lt;/language> &lt;/languages> &lt;country>US&lt;/country> &lt;/locale> </pre> If languages default is not set, the system default wil be used.<br> If country code is not set, the system default will be used.<br> </p> <p> Rapla hasn't a support for different Timezones yet. if you look into RaplaLocale you find 3 timzones in Rapla: </p> <ul> <li>{@link RaplaLocale#getTimeZone}</li> <li>{@link RaplaLocale#getSystemTimeZone}</li> <li>{@link RaplaLocale#getImportExportTimeZone}</li> </ul> */ public interface RaplaLocale { TypedComponentRole<String> LANGUAGE_ENTRY = new TypedComponentRole<String>("org.rapla.language"); String[] getAvailableLanguages(); /** creates a calendar initialized with the Rapla timezone ( that is always GMT+0 for Rapla ) and the selected locale*/ Calendar createCalendar(); String formatTime( Date date ); Date fromUTCTimestamp(Date timestamp); /** sets time to 0:00:00 or 24:00:00 */ Date toDate( Date date, boolean fillDate ); /** sets time to 0:00:00 * Warning month is zero based so January is 0 * @deprecated use toRaplaDate*/ Date toDate( int year, int month, int date ); /** * month is 1-12 January is 1 */ Date toRaplaDate( int year, int month, int date ); /** sets date to 0:00:00 */ Date toTime( int hour, int minute, int second ); /** Uses the first date parameter for year, month, date information and the second for hour, minutes, second, millisecond information.*/ Date toDate( Date date, Date time ); /** format long with the local NumberFormat */ String formatNumber( long number ); /** format without year */ String formatDateShort( Date date ); /** format with locale DateFormat.SHORT */ String formatDate( Date date ); /** format with locale DateFormat.MEDIUM */ String formatDateLong( Date date ); String formatTimestamp(Date timestamp); @Deprecated String formatTimestamp(Date timestamp, TimeZone timezone); /** Abbreviation of locale weekday name of date. */ String getWeekday( Date date ); /** Monthname of date. */ String getMonth( Date date ); String getCharsetNonUtf(); /** This method always returns GMT+0. This is used for all internal calls. All dates and times are stored internaly with this Timezone. Rapla can't work with timezones but to use the Date api it needs a timezone, so GMT+0 is used, because it doesn't have DaylightSavingTimes which would confuse the conflict detection. This timezone (GMT+0) is only used internaly and never shown in Rapla. Rapla only displays the time e.g. 10:00am without the timezone. */ TimeZone getTimeZone(); /** returns the timezone of the system where Rapla is running (java default) this is used on the server for storing the dates in mysql. Prior to 1.7 Rapla always switched the system time to gmt for the mysql api. But now the dates are converted from GMT+0 to system time before storing. Converted meens: 10:00am GMT+0 Raplatime is converted to 10:00am Europe/Berlin, if thats the system timezone. When loading 10:00am Europe/Berlin is converted back to 10:00am GMT+0. This timezone is also used for the timestamps, so created-at and last-changed dates are always stored in system time. Also the logging api uses this timezone and now logs are in system time. @see RaplaLocale#toRaplaTime(TimeZone, long) @deprecated only used internally by the storage api */ @Deprecated TimeZone getSystemTimeZone(); /** returns the timezone configured via main options, this is per default the system timezon. This timezone is used for ical/exchange import/export If Rapla will support timezones in the future, than this will be the default timezone for all times. Now its only used on import and export. It works as with system time above. 10:00am GMT+0 is converted to 10:00am of the configured timezone on export and on import all times are converted to GMT+0. @see RaplaLocale#toRaplaTime(TimeZone, long) @deprecated moved to ImportExportLocale */ @Deprecated TimeZone getImportExportTimeZone(); /** @deprecated moved to TimeZoneConverter */ @Deprecated long fromRaplaTime(TimeZone timeZone,long raplaTime); /** @deprecated moved to TimeZoneConverter */ @Deprecated long toRaplaTime(TimeZone timeZone,long time); /** @deprecated moved to TimeZoneConverter */ @Deprecated Date fromRaplaTime(TimeZone timeZone,Date raplaTime); /** * converts a common Date object into a Date object that * assumes that the user (being in the given timezone) is in the * UTC-timezone by adding the offset between UTC and the given timezone. * * <pre> * Example: If you pass the Date "2013 Jan 15 11:00:00 UTC" * and the TimeZone "GMT+1", this method will return a Date * "2013 Jan 15 12:00:00 UTC" which is effectivly 11:00:00 GMT+1 * </pre> * * @param timeZone * the orgin timezone * @param time * the Date object in the passed timezone * @see RaplaLocale#fromRaplaTime @deprecated moved to TimeZoneConverter */ Date toRaplaTime(TimeZone timeZone,Date time); Locale getLocale(); SerializableDateTimeFormat getSerializableFormat(); }
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.framework.internal; import java.text.DateFormat; import java.text.FieldPosition; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.rapla.components.util.DateTools; import org.rapla.components.xmlbundle.LocaleSelector; import org.rapla.components.xmlbundle.impl.LocaleSelectorImpl; import org.rapla.framework.Configuration; import org.rapla.framework.logger.Logger; public class RaplaLocaleImpl extends AbstractRaplaLocale { TimeZone zone; TimeZone systemTimezone; TimeZone importExportTimeZone; LocaleSelector localeSelector = new LocaleSelectorImpl(); String[] availableLanguages; String COUNTRY = "country"; String LANGUAGES = "languages"; String LANGUAGE = "language"; String CHARSET = "charset"; String charsetForHtml; public RaplaLocaleImpl(Configuration config,Logger logger ) { String selectedCountry = config.getChild( COUNTRY).getValue(Locale.getDefault().getCountry() ); Configuration languageConfig = config.getChild( LANGUAGES ); Configuration[] languages = languageConfig.getChildren( LANGUAGE ); charsetForHtml = config.getChild(CHARSET).getValue("iso-8859-15"); availableLanguages = new String[languages.length]; for ( int i=0;i<languages.length;i++ ) { availableLanguages[i] = languages[i].getValue("en"); } String selectedLanguage = languageConfig.getAttribute( "default", Locale.getDefault().getLanguage() ); if (selectedLanguage.trim().length() == 0) selectedLanguage = Locale.getDefault().getLanguage(); localeSelector.setLocale( new Locale(selectedLanguage, selectedCountry) ); zone = DateTools.getTimeZone(); systemTimezone = TimeZone.getDefault(); importExportTimeZone = systemTimezone; logger.info("Configured Locale= " + getLocaleSelector().getLocale().toString()); } public TimeZone getSystemTimeZone() { return systemTimezone; } public LocaleSelector getLocaleSelector() { return localeSelector; } public Date fromUTCTimestamp(Date date) { Date raplaTime = toRaplaTime( importExportTimeZone,date ); return raplaTime; } /* (non-Javadoc) * @see org.rapla.common.IRaplaLocale#getAvailableLanguages() */ public String[] getAvailableLanguages() { return availableLanguages; } /* (non-Javadoc) * @see org.rapla.common.IRaplaLocale#createCalendar() */ public Calendar createCalendar() { return Calendar.getInstance( zone, getLocale() ); } /* (non-Javadoc) * @see org.rapla.common.IRaplaLocale#formatTime(java.util.Date) */ public String formatTime( Date date ) { Locale locale = getLocale(); TimeZone timezone = getTimeZone(); DateFormat format = DateFormat.getTimeInstance( DateFormat.SHORT, locale ); format.setTimeZone( timezone ); String formatTime = format.format( date ); return formatTime; } /* (non-Javadoc) * @see org.rapla.common.IRaplaLocale#formatNumber(long) */ public String formatNumber( long number ) { Locale locale = getLocale(); return NumberFormat.getInstance( locale).format(number ); } /* (non-Javadoc) * @see org.rapla.common.IRaplaLocale#formatDateShort(java.util.Date) */ public String formatDateShort( Date date ) { Locale locale = getLocale(); TimeZone timezone = zone; StringBuffer buf = new StringBuffer(); FieldPosition fieldPosition = new FieldPosition( DateFormat.YEAR_FIELD ); DateFormat format = DateFormat.getDateInstance( DateFormat.SHORT, locale ); format.setTimeZone( timezone ); buf = format.format(date, buf, fieldPosition ); if ( fieldPosition.getEndIndex()<buf.length() ) { buf.delete( fieldPosition.getBeginIndex(), fieldPosition.getEndIndex()+1 ); } else if ( (fieldPosition.getBeginIndex()>=0) ) { buf.delete( fieldPosition.getBeginIndex(), fieldPosition.getEndIndex() ); } String result = buf.toString(); return result; } /* (non-Javadoc) * @see org.rapla.common.IRaplaLocale#formatDate(java.util.Date) */ public String formatDate( Date date ) { TimeZone timezone = zone; Locale locale = getLocale(); DateFormat format = DateFormat.getDateInstance( DateFormat.SHORT, locale ); format.setTimeZone( timezone ); return format.format( date ); } /* (non-Javadoc) * @see org.rapla.common.IRaplaLocale#formatDateLong(java.util.Date) */ public String formatDateLong( Date date ) { TimeZone timezone = zone; Locale locale = getLocale(); DateFormat format = DateFormat.getDateInstance( DateFormat.MEDIUM, locale ); format.setTimeZone( timezone ); String dateFormat = format.format( date); return dateFormat + " (" + getWeekday(date) + ")"; } @Deprecated public String formatTimestamp( Date date, TimeZone timezone ) { Locale locale = getLocale(); StringBuffer buf = new StringBuffer(); { DateFormat format = DateFormat.getDateInstance( DateFormat.SHORT, locale ); format.setTimeZone( timezone ); String formatDate= format.format( date ); buf.append( formatDate); } buf.append(" "); { DateFormat format = DateFormat.getTimeInstance( DateFormat.SHORT, locale ); format.setTimeZone( timezone ); String formatTime = format.format( date ); buf.append( formatTime); } return buf.toString(); } /* (non-Javadoc) * @see org.rapla.common.IRaplaLocale#getWeekday(java.util.Date) */ public String getWeekday( Date date ) { TimeZone timeZone = getTimeZone(); Locale locale = getLocale(); SimpleDateFormat format = new SimpleDateFormat( "EE", locale ); format.setTimeZone( timeZone ); return format.format( date ); } /* (non-Javadoc) * @see org.rapla.common.IRaplaLocale#getMonth(java.util.Date) */ public String getMonth( Date date ) { TimeZone timeZone = getTimeZone(); Locale locale = getLocale(); SimpleDateFormat format = new SimpleDateFormat( "MMMMM", locale ); format.setTimeZone( timeZone ); return format.format( date ); } /* (non-Javadoc) * @see org.rapla.common.IRaplaLocale#getTimeZone() */ public TimeZone getTimeZone() { return zone; } public TimeZone getImportExportTimeZone() { return importExportTimeZone; } public void setImportExportTimeZone(TimeZone importExportTimeZone) { this.importExportTimeZone = importExportTimeZone; } /* (non-Javadoc) * @see org.rapla.common.IRaplaLocale#getLocale() */ public Locale getLocale() { return localeSelector.getLocale(); } public String getCharsetNonUtf() { return charsetForHtml; } }
Java