📄 localcache.java
字号:
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.rapla.components.util.Assert;
import org.rapla.components.util.iterator.NestedIterator;
import org.rapla.entities.Category;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentStartComparator;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.entities.storage.EntityResolver;
import org.rapla.entities.storage.RefEntity;
import org.rapla.entities.storage.internal.SimpleIdentifier;
import org.rapla.framework.RaplaException;
public class LocalCache implements EntityResolver
{
Map passwords = new HashMap();
Map entities;
Set dynamicTypes;
Set users;
Set resources;
Set reservations;
Set periods;
Set categories;
Set appointments;
Set attributes;
Set preferences;
Map entityMap;
Map enities;
Locale locale;
// Index for start and end dates
TreeSet appointmentsStart;
class IdComparator implements Comparator {
public int compare(Object o1,Object o2) {
SimpleIdentifier id1 = (SimpleIdentifier)((RefEntity)o1).getId();
SimpleIdentifier id2 = (SimpleIdentifier)((RefEntity)o2).getId();
if ( id1.getKey() == id2.getKey())
return 0;
return (id1.getKey() < id2.getKey()) ? -1 : 1;
}
}
private CategoryImpl superCategory = new CategoryImpl();
public LocalCache(Locale locale) {
this.locale = locale;
superCategory.setId(LocalCache.SUPER_CATEGORY_ID);
superCategory.setKey("supercategory");
entityMap = new HashMap();
entities = new HashMap();
// top-level-entities
reservations = new TreeSet( new IdComparator());
periods = new TreeSet(new IdComparator());
users = new TreeSet( new IdComparator());
resources = new TreeSet( new IdComparator());
dynamicTypes = new TreeSet(new IdComparator());
// non-top-level-entities with exception of one super-category
categories = new HashSet();
appointments = new HashSet();
preferences = new HashSet();
attributes = new HashSet();
entityMap.put(DynamicType.TYPE,dynamicTypes);
entityMap.put(Attribute.TYPE, attributes);
entityMap.put(Category.TYPE, categories);
entityMap.put(Allocatable.TYPE,resources);
entityMap.put(User.TYPE,users);
entityMap.put(Period.TYPE,periods);
entityMap.put(Reservation.TYPE,reservations);
entityMap.put(Appointment.TYPE,appointments);
entityMap.put(Preferences.TYPE, preferences);
appointmentsStart = new TreeSet(new AppointmentStartComparator());
initSuperCategory();
}
/** @return true if the entity has been removed and false if the entity was not found*/
public boolean remove(RefEntity entity) {
RaplaType raplaType = entity.getRaplaType();
Set entitySet = (Set)entityMap.get(raplaType);
boolean bResult = true;
if (entitySet != null) {
if (entities.get(entity.getId()) != null)
bResult = false;
if (entity.getId() == null)
return false;
if ( Appointment.TYPE.equals( raplaType )) {
removeAppointment(entity);
}
entities.remove(entity.getId());
entitySet.remove( entity );
} else {
throw new RuntimeException("UNKNOWN TYPE. Can't remove object:" + entity.getRaplaType());
}
return bResult;
}
public void put(RefEntity entity) {
Assert.notNull(entity);
RaplaType raplaType = entity.getRaplaType();
Object id = entity.getId();
if (id == null)
throw new IllegalStateException("ID can't be null");
Set entitySet = (Set) entityMap.get(raplaType);
if (entitySet != null) {
if (Appointment.TYPE.equals( raplaType )) {
removeAppointment(entity);
appointmentsStart.add(entity);
}
entities.put(id,entity);
entitySet.remove( entity );
entitySet.add( entity );
} else {
throw new RuntimeException("UNKNOWN TYPE. Can't store object in cache: " + entity.getRaplaType());
}
}
public RefEntity get(Object id) {
if (id == null)
throw new RuntimeException("id is null");
return (RefEntity)entities.get(id);
}
private void removeAppointment(RefEntity entity) {
if (appointments.remove(entity)) {
// start date could have been changed, so we probably won't find it with a binary search
if (!appointmentsStart.remove(entity)) {
Iterator it = appointmentsStart.iterator();
while (it.hasNext())
if (entity.equals(it.next())) {
it.remove();
break;
}
}
}
}
public SortedSet getAppointments(User user,Date start,Date end) {
SortedSet appointmentSet = new TreeSet(new AppointmentStartComparator());
Iterator it;
if (end != null) {
// all appointments that start before the enddate
it = appointmentsStart.headSet(end).iterator();
//it = appointments.values().iterator();
} else {
it = appointmentsStart.iterator();
}
while (it.hasNext()) {
Appointment 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, false))
continue;
if (user == null || user.equals(appointment.getOwner()) ) {
appointmentSet.add(appointment);
}
}
return appointmentSet;
}
public List getReservations(User user, Date start, Date end) {
HashSet reservationSet = new HashSet();
Iterator it = getAppointments(user,start,end).iterator();
while (it.hasNext()) {
Appointment appointment = (Appointment) it.next();
reservationSet.add( appointment.getReservation() );
}
return new ArrayList(reservationSet);
}
public Collection getCollection(RaplaType type) {
Set entities = (Set) entityMap.get(type);
if ( Period.TYPE.equals( type)) {
entities = new TreeSet( entities);
}
if (entities != null) {
return entities;
} else {
throw new RuntimeException("UNKNOWN TYPE. Can't get collection: "
+ type);
}
}
public Iterator getIterator(RaplaType type) throws RaplaException {
Set entities = (Set) entityMap.get(type);
if (entities != null) {
return entities.iterator();
}
throw new RaplaException("Can't get iterator for " + type);
}
public void clearAll() {
passwords.clear();
Iterator it = entityMap.values().iterator();
while (it.hasNext()) {
((Set)it.next()).clear();
}
appointmentsStart.clear();
entities.clear();
initSuperCategory();
}
private void initSuperCategory() {
entities.put (LocalCache.SUPER_CATEGORY_ID, superCategory);
superCategory.setReadOnly( false );
categories.add( superCategory );
Category[] childs = superCategory.getCategories();
for (int i=0;i<childs.length;i++) {
superCategory.removeCategory( childs[i] );
}
}
public static Object SUPER_CATEGORY_ID = new SimpleIdentifier(Category.TYPE,0);
public CategoryImpl getSuperCategory() {
return (CategoryImpl) get(SUPER_CATEGORY_ID);
}
public Collection getAttributeList(Category category) {
HashSet result = new HashSet();
Iterator it = attributes.iterator();
while (it.hasNext()) {
Attribute attribute = (Attribute) it.next();
if (((RefEntity)attribute).isRefering((RefEntity)category))
result.add(attribute);
}
return result;
}
public Collection getDynamicTypeList(Category category) {
HashSet result = new HashSet();
Iterator it = getAttributeList(category).iterator();
while (it.hasNext()) {
result.add(((Attribute)it.next()).getDynamicType());
}
return result;
}
public Collection getReferers(RaplaType raplaType,RefEntity object) {
ArrayList result = new ArrayList();
Iterator it = getCollection(raplaType).iterator();
while (it.hasNext())
{
RefEntity referer = (RefEntity)it.next();
if (referer != null && referer.isRefering(object)) {
result.add(referer);
}
}
return result;
}
public User getUser(String username) {
Iterator it = users.iterator();
while (it.hasNext()) {
User user = (User) it.next();
if (user.getUsername().equals(username))
return user;
}
return null;
}
public Preferences getPreferences(User user) {
Iterator it = preferences.iterator();
while (it.hasNext()) {
Preferences pref = (Preferences) it.next();
if ( user == null && pref.getOwner() == null ) {
return pref;
}
if (user!= null && pref.getOwner() != null && user.equals(pref.getOwner())) {
return pref;
}
}
return null;
}
static public Object getId(RaplaType type,String str) throws ParseException {
if (str == null)
throw new ParseException("Id string for " + type + " can't be null", 0);
int index = str.lastIndexOf("_") + 1;
if (index>str.length())
throw new ParseException("invalid rapla-id '" + str + "'", index);
try {
return new SimpleIdentifier(type,Integer.parseInt(str.substring(index)));
} catch (NumberFormatException ex) {
throw new ParseException("invalid rapla-id '" + str + "'", index);
}
}
public DynamicType getDynamicType(String elementKey) {
Iterator it = dynamicTypes.iterator();
while (it.hasNext()) {
DynamicType dt = (DynamicType) it.next();
if (dt.getElementKey().equals(elementKey))
return dt;
}
return null;
}
public Iterator getVisibleEntities() {
return new NestedIterator(entityMap.keySet().iterator()) {
public Iterator getNestedIterator(Object key) {
RaplaType raplaType = (RaplaType)key;
if ( Reservation.TYPE.equals( raplaType ) ||
Appointment.TYPE.equals( raplaType ) )
return null;
Set set = (Set) entityMap.get( key);
return set.iterator();
}
};
}
public Iterator getAllEntities() {
return new NestedIterator(entityMap.keySet().iterator()) {
public Iterator getNestedIterator(Object raplaType) {
Set set = (Set) entityMap.get(raplaType);
return set.iterator();
}
/*
public Object next() {
Object obj = super.next();
System.out.println(obj);
return obj;
}
*/
};
}
// Implementation of EntityResolver
public RefEntity resolve(Object id) throws EntityNotFoundException {
if (!(id instanceof SimpleIdentifier))
new EntityNotFoundException("Unknown identifier class: " + id.getClass()
+ ". Only the SimpleIdentier class is supported.");
RefEntity entity = (RefEntity) get(id);
if (entity == null)
throw new EntityNotFoundException("Object for id [" + id.toString() + "] not found");
return entity;
}
public String getPassword(Object userId) {
return (String) passwords.get(userId);
}
public void putPassword(Object userId, String password) {
passwords.put(userId,password);
}
public void putAll( Collection list )
{
Iterator it = list.iterator();
while (it.hasNext()) {
put((RefEntity)it.next());
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -