code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/*--------------------------------------------------------------------------* | 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; } }
04900db4-rob
src/org/rapla/entities/domain/AppointmentStartComparator.java
Java
gpl3
1,455
/*--------------------------------------------------------------------------* | 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; } }
04900db4-rob
src/org/rapla/entities/domain/ReservationStartComparator.java
Java
gpl3
2,681
/*--------------------------------------------------------------------------* | 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 ); }
04900db4-rob
src/org/rapla/entities/domain/AppointmentFormater.java
Java
gpl3
1,384
/*--------------------------------------------------------------------------* | 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; } }
04900db4-rob
src/org/rapla/entities/domain/internal/AppointmentImpl.java
Java
gpl3
31,638
/*--------------------------------------------------------------------------* | 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(); } }
04900db4-rob
src/org/rapla/entities/domain/internal/PermissionImpl.java
Java
gpl3
10,505
/*--------------------------------------------------------------------------* | 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); } }
04900db4-rob
src/org/rapla/entities/domain/internal/AllocatableImpl.java
Java
gpl3
14,296
/*--------------------------------------------------------------------------* | 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; } }
04900db4-rob
src/org/rapla/entities/domain/internal/PeriodImpl.java
Java
gpl3
2,903
/*--------------------------------------------------------------------------* | 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; } }
04900db4-rob
src/org/rapla/entities/domain/internal/RepeatingImpl.java
Java
gpl3
13,980
/*--------------------------------------------------------------------------* | 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(); } }
04900db4-rob
src/org/rapla/entities/domain/internal/ReservationImpl.java
Java
gpl3
20,845
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(); } }
04900db4-rob
src/org/rapla/entities/domain/Template.java
Java
gpl3
896
/*--------------------------------------------------------------------------* | 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]; }
04900db4-rob
src/org/rapla/entities/domain/Period.java
Java
gpl3
1,622
/*--------------------------------------------------------------------------* | 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(); }
04900db4-rob
src/org/rapla/entities/domain/Allocatable.java
Java
gpl3
3,682
/*--------------------------------------------------------------------------* | 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(); }
04900db4-rob
src/org/rapla/entities/domain/Repeating.java
Java
gpl3
3,472
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; } }
04900db4-rob
src/org/rapla/entities/domain/AppointmentBlockStartComparator.java
Java
gpl3
1,007
/*--------------------------------------------------------------------------* | 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(); } }
04900db4-rob
src/org/rapla/entities/domain/RepeatingEnding.java
Java
gpl3
2,532
/*--------------------------------------------------------------------------* | 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; } }
04900db4-rob
src/org/rapla/entities/domain/RepeatingType.java
Java
gpl3
1,997
/*--------------------------------------------------------------------------* | 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]; }
04900db4-rob
src/org/rapla/entities/domain/Appointment.java
Java
gpl3
5,580
/*--------------------------------------------------------------------------* | 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)); } }
04900db4-rob
src/org/rapla/entities/domain/AppointmentBlock.java
Java
gpl3
3,108
/*--------------------------------------------------------------------------* | 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]; }
04900db4-rob
src/org/rapla/entities/domain/Permission.java
Java
gpl3
6,076
<body> The main domain entities of rapla (reservations and resources) are located in this package. Take a look for a good overview of the rapla api. </body>
04900db4-rob
src/org/rapla/entities/domain/package.html
HTML
gpl3
167
/*--------------------------------------------------------------------------* | 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"; }
04900db4-rob
src/org/rapla/entities/domain/ResourceAnnotations.java
Java
gpl3
1,144
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; } }
04900db4-rob
src/org/rapla/entities/domain/ReservationHelper.java
Java
gpl3
2,200
/*--------------------------------------------------------------------------* | 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"; }
04900db4-rob
src/org/rapla/entities/domain/RaplaObjectAnnotations.java
Java
gpl3
1,230
/*--------------------------------------------------------------------------* | 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(); }
04900db4-rob
src/org/rapla/entities/domain/Reservation.java
Java
gpl3
4,797
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; } }
04900db4-rob
src/org/rapla/entities/domain/AppointmentBlockEndComparator.java
Java
gpl3
1,014
/*--------------------------------------------------------------------------* | 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(); } }
04900db4-rob
src/org/rapla/entities/storage/internal/ReferenceHandler.java
Java
gpl3
9,093
/*--------------------------------------------------------------------------* | 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 ); } }
04900db4-rob
src/org/rapla/entities/storage/internal/SimpleEntity.java
Java
gpl3
8,323
/*--------------------------------------------------------------------------* | 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); }
04900db4-rob
src/org/rapla/entities/storage/EntityResolver.java
Java
gpl3
1,834
/*--------------------------------------------------------------------------* | 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); }
04900db4-rob
src/org/rapla/entities/storage/ParentEntity.java
Java
gpl3
1,734
/*--------------------------------------------------------------------------* | 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; }
04900db4-rob
src/org/rapla/entities/storage/DynamicTypeDependant.java
Java
gpl3
2,205
/*--------------------------------------------------------------------------* | 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(); }
04900db4-rob
src/org/rapla/entities/storage/RefEntity.java
Java
gpl3
1,358
/*--------------------------------------------------------------------------* | 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() ); } } }
04900db4-rob
src/org/rapla/entities/storage/EntityReferencer.java
Java
gpl3
2,419
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); } }
04900db4-rob
src/org/rapla/entities/storage/UnresolvableReferenceExcpetion.java
Java
gpl3
426
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; }
04900db4-rob
src/org/rapla/entities/storage/CannotExistWithoutTypeException.java
Java
gpl3
392
/*--------------------------------------------------------------------------* | 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]; }
04900db4-rob
src/org/rapla/entities/Entity.java
Java
gpl3
2,182
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; import java.util.Date; import java.util.Iterator; import java.util.List; import org.rapla.components.util.DateTools; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentFormater; import org.rapla.entities.domain.Period; import org.rapla.entities.domain.Repeating; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; /** default implementation of appointment formater */ public class AppointmentFormaterImpl implements AppointmentFormater { I18nBundle i18n; RaplaLocale loc; public AppointmentFormaterImpl(RaplaContext context) throws RaplaException { i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES); loc = context.lookup(RaplaLocale.class); } protected RaplaLocale getRaplaLocale() { return loc; } protected I18nBundle getI18n() { return i18n; } protected String getString(String key) { return i18n.getString(key); } public String getShortSummary(Appointment appointment) { String time = loc.formatTime(appointment.getStart()); Repeating repeating = appointment.getRepeating(); final boolean wholeDaysSet = appointment.isWholeDaysSet(); final String timeString = wholeDaysSet ? "" :" " + time; String weekday = loc.getWeekday(appointment.getStart()); if (repeating != null) { if (repeating.isWeekly()) { return weekday + timeString; } if (repeating.isDaily()) return getString("daily") + " " + time; if (repeating.isMonthly()) return getWeekdayOfMonth( appointment.getStart() ) + weekday + timeString; if (repeating.isYearly()) return getDayOfMonth( appointment.getStart() ) + loc.getMonth(appointment.getStart()) +" " + timeString; } String date = loc.formatDate(appointment.getStart()); return weekday + " " +date + " " + timeString; } public String getVeryShortSummary(Appointment appointment) { Repeating repeating = appointment.getRepeating(); if (repeating != null) { if (repeating.isWeekly()) return getRaplaLocale().getWeekday(appointment.getStart()); if (repeating.isDaily()) { String time = getRaplaLocale().formatTime(appointment.getStart()); return time; } if (repeating.isMonthly()) { return getRaplaLocale().getWeekday(appointment.getStart()); } } String date = getRaplaLocale().formatDateShort(appointment.getStart()); return date; } public String getSummary( Appointment a ) { StringBuffer buf = new StringBuffer(); Repeating repeating = a.getRepeating(); final boolean wholeDaysSet = a.isWholeDaysSet(); Date start = a.getStart(); Date end = a.getEnd(); if ( repeating == null ) { buf.append( loc.getWeekday( start ) ); buf.append( ' ' ); buf.append( loc.formatDate( start ) ); if (!wholeDaysSet && !( end.equals( DateTools.cutDate(end)) && start.equals(DateTools.cutDate( start)))) { buf.append( ' ' ); buf.append( loc.formatTime( start ) ); if ( isSameDay( start, end ) || (end.equals( DateTools.cutDate(end)) && isSameDay( DateTools.fillDate( start), end)) ) { buf.append( '-' ); } else { buf.append( " - " ); buf.append( loc.getWeekday( end ) ); buf.append( ' ' ); buf.append( loc.formatDate( end ) ); buf.append( ' ' ); } buf.append( loc.formatTime( end ) ); } else if ( end.getTime() - start.getTime() > DateTools.MILLISECONDS_PER_DAY) { buf.append( " - " ); buf.append( loc.getWeekday( DateTools.addDays(end,-1 )) ); buf.append( ' ' ); buf.append( loc.formatDate( DateTools.addDays(end,-1 )) ); } } else if ( repeating.isWeekly() || repeating.isMonthly() || repeating.isYearly()) { if( repeating.isMonthly()) { buf.append( getWeekdayOfMonth( start )); } if (repeating.isYearly()) { buf.append( getDayOfMonth( start ) ); buf.append( loc.getMonth( start ) ); } else { buf.append( loc.getWeekday( start ) ); } if (wholeDaysSet) { if ( end.getTime() - start.getTime() > DateTools.MILLISECONDS_PER_DAY) { if ( end.getTime() - start.getTime() <= DateTools.MILLISECONDS_PER_DAY * 6 ) { buf.append( " - " ); buf.append( loc.getWeekday( end ) ); } else { buf.append( ' ' ); buf.append( loc.formatDate( start ) ); buf.append( " - " ); buf.append( loc.getWeekday( end ) ); buf.append( ' ' ); buf.append( loc.formatDate( end ) ); } } } else { buf.append( ' ' ); if ( isSameDay( start, end ) ) { buf.append( loc.formatTime( start ) ); buf.append( '-' ); buf.append( loc.formatTime( end ) ); } else if ( end.getTime() - start.getTime() <= DateTools.MILLISECONDS_PER_DAY * 6 ) { buf.append( loc.formatTime( start ) ); buf.append( " - " ); buf.append( loc.getWeekday( end ) ); buf.append( ' ' ); buf.append( loc.formatTime( end ) ); } else { buf.append( loc.formatDate( start ) ); buf.append( ' ' ); buf.append( loc.formatTime( start ) ); buf.append( " - " ); buf.append( loc.getWeekday( end ) ); buf.append( ' ' ); buf.append( loc.formatDate( end ) ); buf.append( ' ' ); buf.append( loc.formatTime( end ) ); } } if ( repeating.isWeekly()) { buf.append( ' ' ); buf.append( getInterval( repeating ) ); } if ( repeating.isMonthly()) { buf.append(" " + getString("monthly")); } if ( repeating.isYearly()) { buf.append(" " + getString("yearly")); } } else if ( repeating.isDaily() ) { long days =(end.getTime() - start.getTime()) / (DateTools.MILLISECONDS_PER_HOUR * 24 ); if ( !a.isWholeDaysSet()) { buf.append( loc.formatTime( start ) ); if ( days <1) { buf.append( '-' ); buf.append( loc.formatTime( end ) ); } buf.append( ' ' ); } buf.append( getInterval( repeating ) ); } return buf.toString(); } private String getWeekdayOfMonth( Date date ) { StringBuffer b = new StringBuffer(); int numb = DateTools.getDayOfWeekInMonth( date ); b.append( String.valueOf(numb)); b.append( '.'); b.append( ' '); return b.toString(); } private String getDayOfMonth( Date date ) { StringBuffer b = new StringBuffer(); int numb = DateTools.getDayOfMonth( date ); b.append( String.valueOf(numb)); b.append( '.'); b.append( ' '); return b.toString(); } private boolean isSameDay( Date d1, Date d2 ) { return DateTools.isSameDay(d1, d2); } public String getExceptionSummary( Repeating r ) { StringBuffer buf = new StringBuffer(); buf.append(getString("appointment.exceptions")); buf.append(": "); Date[] exc = r.getExceptions(); for ( int i=0;i<exc.length;i++) { if (i>0) buf.append(", "); buf.append( getRaplaLocale().formatDate( exc[i] ) ); } return buf.toString(); } private String getInterval( Repeating r ) { StringBuffer buf = new StringBuffer(); if ( r.getInterval() == 1 ) { buf.append( getString( r.getType().toString() ) ); } else { String fString ="weekly"; if ( r.isWeekly() ) { fString = getString( "weeks" ); } if ( r.isDaily() ) { fString = getString( "days" ); } buf.append( getI18n().format( "interval.format", "" + r.getInterval(), fString ) ); } return buf.toString(); } private boolean isPeriodicaly(Period period, Repeating r) { Appointment a = r.getAppointment(); if (r.getEnd().after( period.getEnd() ) ) return false; if ( r.isWeekly() ) { return ( DateTools.cutDate(a.getStart().getTime()) - period.getStart().getTime() ) <= DateTools.MILLISECONDS_PER_DAY * 6 && ( DateTools.cutDate(period.getEnd().getTime()) - r.getEnd().getTime() ) <= DateTools.MILLISECONDS_PER_DAY * 6 ; } else if ( r.isDaily() ) { return isSameDay( a.getStart(), period.getStart() ) && isSameDay( r.getEnd(), period.getEnd() ) ; } return false; } public String getSummary( Repeating r , List<Period> periods) { if ( r.getEnd() != null && !r.isFixedNumber() ) { Iterator<Period> it = periods.iterator(); while ( it.hasNext() ) { Period period = it.next(); if ( isPeriodicaly(period, r)) return getI18n().format("in_period.format" ,period.getName(loc.getLocale()) ); } } return getSummary(r); } public String getSummary( Repeating r ) { Appointment a = r.getAppointment(); StringBuffer buf = new StringBuffer(); String startDate = loc.formatDate( a.getStart() ); buf.append( getI18n().format("format.repeat_from", startDate) ); buf.append( ' ' ); // print end date, when end is given if ( r.getEnd() != null) { String endDate = loc.formatDate( DateTools.subDay(r.getEnd()) ); buf.append( getI18n().format("format.repeat_until", endDate) ); buf.append( ' ' ); } // print number of repeating if number is gt 0 and fixed times if ( r.getNumber()>=0 && r.isFixedNumber() ) { buf.append( getI18n().format("format.repeat_n_times", String.valueOf(r.getNumber())) ); buf.append( ' ' ); } // print never ending if end is null if (r.getEnd() == null ){ buf.append( getString("repeating.forever") ); buf.append( ' ' ); } return buf.toString(); } }
04900db4-rob
src/org/rapla/AppointmentFormaterImpl.java
Java
gpl3
13,042
package org.rapla.bootstrap; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; @SuppressWarnings({ "rawtypes", "unchecked" }) public class CustomJettyStarter { public static final String USAGE = new String ( "Usage : \n" + "[-?|-c PATH_TO_CONFIG_FILE] [ACTION]\n" + "Possible actions:\n" + " standalone : Starts the rapla-gui with embedded server (this is the default)\n" + " server : Starts the rapla-server \n" + " client : Starts the rapla-client \n" + " import : Import from file into the database\n" + " export : Export from database into file\n" + "the config file is jetty.xml generally located in etc/jetty.xml" ); public static void main(final String[] args) throws Exception { String property = System.getProperty("org.rapla.disableHostChecking"); if ( Boolean.parseBoolean( property)) { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); } new CustomJettyStarter().start( args); } Class ServerC ; Class ConfigurationC; Class ConnectorC; Class ResourceC; Class EnvEntryC; Class LifeCyleC; Class LifeCyleListenerC; // Class DeploymentManagerC; // Class ContextHandlerC; // Class WebAppContextC; // Class AppC; // Class AppProviderC; // Class ServletHandlerC; // Class ServletHolderC; ClassLoader loader; Method stopMethod; Logger logger = Logger.getLogger(getClass().getName()); String startupMode; String startupUser; /** parse startup parameters. The parse format: <pre> [-?|-c PATH_TO_CONFIG_FILE] [ACTION] </pre> Possible map entries: <ul> <li>config: the config-file</li> <li>action: the start action</li> </ul> @return a map with the parameter-entries or null if format is invalid or -? is used */ public static Map<String,String> parseParams( String[] args ) { boolean bInvalid = false; Map<String,String> map = new HashMap<String,String>(); String config = null; String action = null; // Investigate the passed arguments for ( int i = 0; i < args.length; i++ ) { String arg = args[i].toLowerCase(); if ( arg.equals( "-c" ) ) { if ( i + 1 == args.length ) { bInvalid = true; break; } config = args[++i]; continue; } if ( arg.equals( "-?" ) ) { bInvalid = true; break; } if ( arg.substring( 0, 1 ).equals( "-" ) ) { bInvalid = true; break; } if (action == null) { action = arg; } } if ( bInvalid ) { return null; } if ( config != null ) map.put( "config", config ); if ( action != null ) map.put( "action", action ); return map; } public void start(final String[] arguments) throws Exception { Map<String, String> parseParams = parseParams(arguments); String configFiles = parseParams.get("config"); if ( configFiles == null) { configFiles = "etc/jetty.xml"; String property = System.getProperty("jetty.home"); if (property != null) { if ( !property.endsWith("/")) { property += "/"; } configFiles = property + configFiles; } } startupMode =System.getProperty("org.rapla.startupMode"); if (startupMode == null) { startupMode = parseParams.get("action"); } if (startupMode == null) { startupMode = "standalone"; } startupUser =System.getProperty("org.rapla.startupUser"); boolean isServer = startupMode.equals("server"); final boolean removeConnectors = !isServer; if ( isServer) { System.setProperty( "java.awt.headless", "true" ); } loader = Thread.currentThread().getContextClassLoader(); Class<?> LoadingProgressC= null; final Object progressBar; if ( startupMode.equals("standalone" ) || startupMode.equals("client" )) { LoadingProgressC = loader.loadClass("org.rapla.bootstrap.LoadingProgress"); progressBar = LoadingProgressC.getMethod("getInstance").invoke(null); LoadingProgressC.getMethod("start", int.class, int.class).invoke( progressBar, 1,4); } else { progressBar = null; } final String contextPath = System.getProperty("org.rapla.context",null); final String downloadUrl = System.getProperty("org.rapla.serverUrl",null); final String[] jettyArgs = configFiles.split(","); final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); AccessController.doPrivileged(new PrivilegedAction<Object>() { boolean started; boolean shutdownShouldRun; public Object run() { try { Properties properties = new Properties(); // Add System Properties Enumeration<?> ensysprop = System.getProperties().propertyNames(); while (ensysprop.hasMoreElements()) { String name = (String)ensysprop.nextElement(); properties.put(name,System.getProperty(name)); } //loader.loadClass("org.rapla.bootstrap.JNDIInit").newInstance(); ServerC =loader.loadClass("org.eclipse.jetty.server.Server"); stopMethod = ServerC.getMethod("stop"); ConfigurationC =loader.loadClass("org.eclipse.jetty.xml.XmlConfiguration"); ConnectorC = loader.loadClass("org.eclipse.jetty.server.Connector"); ResourceC = loader.loadClass("org.eclipse.jetty.util.resource.Resource"); EnvEntryC = loader.loadClass("org.eclipse.jetty.plus.jndi.EnvEntry"); LifeCyleC = loader.loadClass( "org.eclipse.jetty.util.component.LifeCycle"); LifeCyleListenerC = loader.loadClass( "org.eclipse.jetty.util.component.LifeCycle$Listener"); // DeploymentManagerC = loader.loadClass("org.eclipse.jetty.deploy.DeploymentManager"); // ContextHandlerC = loader.loadClass("org.eclipse.jetty.server.handler.ContextHandler"); // WebAppContextC = loader.loadClass("org.eclipse.jetty.webapp.WebAppContext"); // AppC = loader.loadClass("org.eclipse.jetty.deploy.App"); // AppProviderC = loader.loadClass("org.eclipse.jetty.deploy.AppProvider"); // ServletHandlerC = loader.loadClass("org.eclipse.jetty.servlet.ServletHandler"); // ServletHolderC = loader.loadClass("org.eclipse.jetty.servlet.ServletHolder"); // For all arguments, load properties or parse XMLs Object last = null; Object[] obj = new Object[jettyArgs.length]; for (int i = 0; i < jettyArgs.length; i++) { String configFile = jettyArgs[i]; Object newResource = ResourceC.getMethod("newResource",String.class).invoke(null,configFile); if (configFile.toLowerCase(Locale.ENGLISH).endsWith(".properties")) { properties.load((InputStream)ResourceC.getMethod("getInputStream").invoke(newResource)); } else { URL url = (URL)ResourceC.getMethod("getURL").invoke(newResource); Object configuration = ConfigurationC.getConstructor(URL.class).newInstance(url); if (last != null) ((Map)ConfigurationC.getMethod("getIdMap").invoke(configuration)).putAll((Map)ConfigurationC.getMethod("getIdMap").invoke(last)); if (properties.size() > 0) { Map<String, String> props = new HashMap<String, String>(); for (Object key : properties.keySet()) { props.put(key.toString(),String.valueOf(properties.get(key))); } ((Map)ConfigurationC.getMethod("getProperties").invoke( configuration)).putAll( props); } Object configuredObject = ConfigurationC.getMethod("configure").invoke(configuration); Integer port = null; if ( ServerC.isInstance(configuredObject)) { final Object server = configuredObject; Object[] connectors = (Object[]) ServerC.getMethod("getConnectors").invoke(server); for (Object c: connectors) { port = (Integer) ConnectorC.getMethod("getPort").invoke(c); if ( removeConnectors) { ServerC.getMethod("removeConnector", ConnectorC).invoke(server, c); } } final Method shutdownMethod = ServerC.getMethod("stop"); InvocationHandler proxy = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); if ( name.toLowerCase(Locale.ENGLISH).indexOf("started")>=0) { if ( shutdownShouldRun) { shutdownMethod.invoke( server); } else { started = true; } } return null; } }; Class<?>[] interfaces = new Class[] {LifeCyleListenerC}; Object proxyInstance = Proxy.newProxyInstance(loader, interfaces, proxy); ServerC.getMethod("addLifeCycleListener", LifeCyleListenerC).invoke(server, proxyInstance); Constructor newJndi = EnvEntryC.getConstructor(String.class,Object.class); Method addBean = ServerC.getMethod("addBean", Object.class); if ( !startupMode.equals("server")) { addBean.invoke(server, newJndi.newInstance("rapla_startup_user", startupUser)); addBean.invoke(server, newJndi.newInstance("rapla_startup_mode", startupMode)); addBean.invoke(server, newJndi.newInstance("rapla_download_url", downloadUrl)); addBean.invoke(server, newJndi.newInstance("rapla_instance_counter", new ArrayList<String>())); if ( contextPath != null) { addBean.invoke(server, newJndi.newInstance("rapla_startup_context", contextPath)); } } addBean.invoke(server, newJndi.newInstance("rapla_startup_port", port)); { Runnable shutdownCommand = new Runnable() { public void run() { if ( started) { try { shutdownMethod.invoke(server); } catch (Exception ex) { logger.log(Level.SEVERE,ex.getMessage(),ex); } } else { shutdownShouldRun = true; } } }; addBean.invoke(server, newJndi.newInstance("rapla_shutdown_command", shutdownCommand)); } } obj[i] = configuredObject; last = configuration; } } // For all objects created by XmlConfigurations, start them if they are lifecycles. for (int i = 0; i < obj.length; i++) { if (LifeCyleC.isInstance(obj[i])) { Object o =obj[i]; if ( !(Boolean)LifeCyleC.getMethod("isStarted").invoke(o)) { LifeCyleC.getMethod("start").invoke(o); } } } } catch (Exception e) { exception.set(e); } return null; } }); if ( progressBar != null && LoadingProgressC != null) { LoadingProgressC.getMethod("close").invoke( progressBar); } Throwable th = exception.get(); if (th != null) { if (th instanceof RuntimeException) throw (RuntimeException)th; else if (th instanceof Exception) throw (Exception)th; else if (th instanceof Error) throw (Error)th; throw new Error(th); } } // void doStart(final Object server, String passedContext) // { // try // { // Object bean = ServerC.getMethod("getBean", Class.class).invoke(server, DeploymentManagerC); // Map<String, Object> raplaServletMap = new LinkedHashMap<String, Object>(); // Collection<?> apps = (Collection<?>) DeploymentManagerC.getMethod("getApps").invoke(bean); // for (Object handler:apps) // { // // Object context_ = AppC.getMethod("getContextHandler").invoke(handler); // String contextPath = (String) ContextHandlerC.getMethod("getContextPath").invoke(context_); // Object[] servlets = (Object[]) ContextHandlerC.getMethod("getChildHandlersByClass", Class.class).invoke(context_, ServletHandlerC); // for ( Object childHandler : servlets) // { // Object servlet = ServletHandlerC.getMethod("getServlet",String.class).invoke( childHandler,"RaplaServer"); // if ( servlet != null) // { // raplaServletMap.put(contextPath, servlet); // } // } // } // // Set<String> keySet = raplaServletMap.keySet(); // if ( keySet.size() == 0) // { // logger.log(Level.SEVERE,"No rapla context found in jetty container."); // stopMethod.invoke(server); // } // else if ( keySet.size() > 1 && passedContext == null) // { // logger.log(Level.SEVERE,"Multiple context found in jetty container " + keySet +" Please specify one via -Dorg.rapla.context=REPLACE_WITH_CONTEXT"); // stopMethod.invoke(server); // } // else // { // //Class MainServletC = loader.loadClass("org.rapla.MainServlet"); // Object servletHolder = passedContext == null ? raplaServletMap.values().iterator().next(): raplaServletMap.get( passedContext); // if ( servletHolder != null) // { // // Object servlet = ServletHolderC.getMethod("getServlet").invoke( servletHolder); // PropertyChangeListener castedHack = (PropertyChangeListener)servlet; // castedHack.propertyChange( new PropertyChangeEvent(server, startupMode, null, shutdownCommand)); // } // else // { // logger.log(Level.SEVERE,"Rapla context ' " + passedContext +"' not found."); // stopMethod.invoke(server); // } // } // } // catch (Exception ex) // { // logger.log(Level.SEVERE,ex.getMessage(),ex); // try { // stopMethod.invoke(server); // } catch (Exception e) { // logger.log(Level.SEVERE,e.getMessage(),e); // } // } // } }
04900db4-rob
src/org/rapla/bootstrap/CustomJettyStarter.java
Java
gpl3
17,110
package org.rapla.bootstrap; import java.io.IOException; public class RaplaClientLoader { public static void main(String[] args) throws IOException { RaplaJettyLoader.main(new String[] {"client"}); } }
04900db4-rob
src/org/rapla/bootstrap/RaplaClientLoader.java
Java
gpl3
226
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.bootstrap; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker; import java.awt.Toolkit; import java.awt.image.ImageObserver; import java.net.URL; import javax.swing.JProgressBar; final public class LoadingProgress { static LoadingProgress instance; JProgressBar progressBar; Frame frame; ImageObserver observer; Image image; Component canvas; int maxValue; static public LoadingProgress getInstance() { if ( instance == null) { instance = new LoadingProgress(); } return instance; } public boolean isStarted() { return frame != null; } /** this method creates the progress bar */ public void start(int startValue, int maxValue) { this.maxValue = maxValue; frame = new Frame() { private static final long serialVersionUID = 1L; public void paint(Graphics g) { super.paint(g); g.drawRect(0, 0, getWidth() - 1, getHeight() - 1); } }; observer = new ImageObserver() { public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h) { if ((flags & ALLBITS) != 0) { canvas.repaint(); } return (flags & (ALLBITS | ABORT | ERROR)) == 0; } }; frame.setBackground(new Color(255, 255, 204)); canvas = new Component() { private static final long serialVersionUID = 1L; public void paint(Graphics g) { g.drawImage(image, 0, 0, observer); } }; Toolkit toolkit = Toolkit.getDefaultToolkit(); URL url = LoadingProgress.class.getResource("/org/rapla/bootstrap/tafel.png"); // Variables (integer pixels) for... // ... the width of the border around the picture int borderwidth = 4; // ... the height of the border around the picture int borderheight = 4; // ... the width of the picture within the frame int picturewidth = 356; // ... the height of the picture within the frame int pictureheight = 182; // ... calculating the frame width int framewidth = borderwidth + borderheight + picturewidth; // ... calculating the frame height int frameheight = borderwidth + borderheight + pictureheight; // ... width of the loading progress bar int progresswidth = 150; // ... height of the loading progress bar int progressheight = 15; image = toolkit.createImage(url); frame.setResizable(false); frame.setLayout(null); progressBar = new JProgressBar(0, maxValue); progressBar.setValue(startValue); // set the bounds to position the progressbar and set width and height progressBar.setBounds(158, 130, progresswidth, progressheight); progressBar.repaint(); // we have to add the progressbar first to get it infront of the picture frame.add(progressBar); frame.add(canvas); // width and height of the canvas equal to those of the picture inside // but here we need the borderwidth as X and the borderheight as Y value canvas.setBounds(borderwidth, borderheight, picturewidth, pictureheight); try { // If run on jdk < 1.4 this will throw a MethodNotFoundException // frame.setUndecorated(true); Frame.class.getMethod("setUndecorated", new Class[] { boolean.class }).invoke(frame, new Object[] { new Boolean(true) }); } catch (Exception ex) { } // we grab the actual size of the screen Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // to make sure the starting dialog is positioned in the middle of // the screen and has the width and height we specified for the frame frame.setBounds((screenSize.width / 2) - (picturewidth / 2), (screenSize.height / 2) - (pictureheight / 2), framewidth, frameheight); frame.validate(); frame.setVisible(true); frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); MediaTracker mt = new MediaTracker(frame); mt.addImage(image, 0); try { mt.waitForID(0); } catch (InterruptedException e) { } } public void advance() { if ( frame == null) { return; } int oldValue = progressBar.getValue(); if (oldValue < maxValue) progressBar.setValue(oldValue + 1); progressBar.repaint(); } public void close() { if ( frame != null) { frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); frame.dispose(); frame = null; } } }
04900db4-rob
src/org/rapla/bootstrap/LoadingProgress.java
Java
gpl3
5,419
package org.rapla.bootstrap; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.StringTokenizer; /** Puts all jar-files from the libdirs into the classpath and start the mainClass. Usage: <code> Syntax: baseDir libdir1,libdir2,... mainClass arg1 arg2 ... Will put all jar-files from the libdirs into the classpath and start the mainClass baseDir: replace with the path, from wich you want the lib-dirs to resolve. libdir[1-n]: Lib-Directories relativ to the base jars."); mainClass: The Java-Class you want to start after loading the jars. arg[1-n]: Example: ./lib common,client org.rapla.Main rapla loads the jars in lib/common and lib/client and starts org.rapla.Main with the argument rapla </code> */ public class RaplaLoader { /** returns all *.jar files in the directories passed in dirList relative to the baseDir */ public static File[] getJarFilesAndClassesFolder(String baseDir,String dirList) throws IOException { ArrayList<File> completeList = new ArrayList<File>(); StringTokenizer tokenizer = new StringTokenizer(dirList,","); while (tokenizer.hasMoreTokens()) { File jarDir = new File(baseDir,tokenizer.nextToken()); if (jarDir.exists() && jarDir.isDirectory()) { File[] jarFiles = jarDir.listFiles(); for (int i = 0; i < jarFiles.length; i++) { if ( jarFiles[i].getAbsolutePath().endsWith(".jar") ) { completeList.add(jarFiles[i].getCanonicalFile()); } } completeList.add( jarDir.getCanonicalFile() ); } } return completeList.toArray(new File[] {}); } private static void printUsage() { System.out.println("Syntax: baseDir libdir1,libdir2,... mainClass arg1 arg2 ..."); System.out.println(); System.out.println("Will put all jar-files from the libdirs into the classpath and start the mainClass"); System.out.println(); System.out.println(" baseDir: replace with the path, from wich you want the lib-dirs to resolve."); System.out.println(" libdir[1-n]: Lib-Directories relativ to the base jars."); System.out.println(" mainClass: The Java-Class you want to start after loading the jars."); System.out.println(" arg[1-n]: "); System.out.println(); System.out.println(" Example: ./lib common,client org.rapla.Main rapla "); System.out.println("loads the jars in lib/common and lib/client and "); System.out.println(" starts org.rapla.Main with the argument rapla"); } public static void main(String[] args) { String baseDir; String dirList; String classname; String[] applicationArgs; if (args.length <3) { printUsage(); System.exit(1); } baseDir=args[0]; dirList=args[1]; classname=args[2]; applicationArgs = new String[args.length-3]; for (int i=0;i<applicationArgs.length;i++) { applicationArgs[i] = args[i+3]; } start( baseDir, dirList, classname, "main",new Object[] {applicationArgs} ); } public static void start( String baseDir, String dirList, String classname, String methodName,Object[] applicationArgs ) { try{ ClassLoader classLoader = getJarClassloader(baseDir, dirList); Thread.currentThread().setContextClassLoader(classLoader); startMain(classLoader,classname,methodName,applicationArgs); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } } private static ClassLoader getJarClassloader(String baseDir, String dirList) throws IOException, MalformedURLException { File[] jarFiles = getJarFilesAndClassesFolder(baseDir,dirList); URL[] urls = new URL[jarFiles.length]; for (int i = 0; i < jarFiles.length; i++) { urls[i] = jarFiles[i].toURI().toURL(); //System.out.println(urls[i]); } ClassLoader classLoader = new URLClassLoader ( urls ,RaplaLoader.class.getClassLoader() ); return classLoader; } private static void startMain(ClassLoader classLoader,String classname, String methodName,Object[] args) throws Exception { Class<?> startClass = classLoader.loadClass(classname); Class<?>[] argTypes = new Class[args.length]; for ( int i=0;i<args.length;i++) { argTypes[i] = args[i].getClass(); } Method mainMethod = startClass.getMethod(methodName,argTypes); mainMethod.invoke(null, args); } // public static void startFromWar( String baseDir, String dirList,String warfile, String classname, String methodName,Object[] applicationArgs ) // { // try{ // ClassLoader loader = getJarClassloader(baseDir, dirList); // Thread.currentThread().setContextClassLoader(loader); // Class<?> forName = loader.loadClass("org.slf4j.bridge.SLF4JBridgeHandler"); // forName.getMethod("removeHandlersForRootLogger", new Class[] {}).invoke(null, new Object[] {}); // forName.getMethod("install", new Class[] {}).invoke(null, new Object[] {}); // loader.loadClass("org.rapla.bootstrap.JNDIInit").newInstance(); // // File file = new File(baseDir, warfile); // ClassLoader classLoader; // if (file.exists()) // { // Class<?> webappContextClass = loader.loadClass("org.eclipse.jetty.webapp.WebAppContext"); // //org.eclipse.jetty.webapp.WebAppContext context = new org.eclipse.jetty.webapp.WebAppContext("webapps/rapla.war","/"); // Constructor<?> const1 = webappContextClass.getConstructor(String.class, String.class); // Object context = const1.newInstance(new Object[] {file.getPath(),"/"}); // Class<?> webappClassLoaderClass = loader.loadClass("org.eclipse.jetty.webapp.WebAppClassLoader"); // Class<?> contextClass = loader.loadClass("org.eclipse.jetty.webapp.WebAppClassLoader$Context"); // //org.eclipse.jetty.webapp.WebAppClassLoader classLoader = new org.eclipse.jetty.webapp.WebAppClassLoader(parentClassLoader, context); // Constructor<?> const2 = webappClassLoaderClass.getConstructor(ClassLoader.class, contextClass); // classLoader = (ClassLoader) const2.newInstance(loader, context); // webappContextClass.getMethod("setClassLoader", ClassLoader.class).invoke( context,classLoader); // Class<?> configurationClass = loader.loadClass("org.eclipse.jetty.webapp.WebInfConfiguration"); // Object config = configurationClass.newInstance(); // configurationClass.getMethod("preConfigure", webappContextClass).invoke(config, context); // configurationClass.getMethod("configure", webappContextClass).invoke(config, context); // } // else // { // classLoader = loader; // System.err.println("War " + warfile + " not found. Using original classpath."); // } // startMain(classLoader,classname,methodName,applicationArgs); // } catch (Exception ex) { // ex.printStackTrace(); // System.exit(1); // } // } }
04900db4-rob
src/org/rapla/bootstrap/RaplaLoader.java
Java
gpl3
7,632
package org.rapla.bootstrap; import java.io.File; import java.io.IOException; public class RaplaServerAsServiceLoader { public static void main(String[] args) throws IOException { System.setProperty( "java.awt.headless", "true" ); String baseDir = System.getProperty("jetty.home"); if ( baseDir == null) { baseDir = "../.."; System.setProperty( "jetty.home", new File(baseDir ).getCanonicalPath() ); } RaplaServerLoader.main( args); } }
04900db4-rob
src/org/rapla/bootstrap/RaplaServerAsServiceLoader.java
Java
gpl3
497
package org.rapla.bootstrap; import java.io.IOException; public class RaplaStandaloneLoader { public static void main(String[] args) throws IOException { // This is for backwards compatibility if ( args.length > 0 && args[0].equals( "client")) { RaplaJettyLoader.main(new String[] {"client"}); } else { RaplaJettyLoader.main(new String[] {"standalone"}); } } }
04900db4-rob
src/org/rapla/bootstrap/RaplaStandaloneLoader.java
Java
gpl3
399
package org.rapla.bootstrap; import java.io.IOException; public class RaplaServerLoader { public static void main(String[] args) throws IOException { System.setProperty( "java.awt.headless", "true" ); RaplaJettyLoader.main(new String[] {"server"}); } }
04900db4-rob
src/org/rapla/bootstrap/RaplaServerLoader.java
Java
gpl3
282
package org.rapla.bootstrap; import java.io.File; import java.io.IOException; public class RaplaJettyLoader { public static void main(String[] args) throws IOException { String baseDir = System.getProperty("jetty.home"); if ( baseDir == null) { baseDir = "."; System.setProperty( "jetty.home", new File(baseDir ).getCanonicalPath() ); } for ( String arg:args) { if ( arg != null && arg.toLowerCase().equals("server")) { System.setProperty( "java.awt.headless", "true" ); } } String dirList = "lib,lib/logging,lib/ext,resources"; String classname = "org.rapla.bootstrap.CustomJettyStarter"; String methodName = "main"; //System.setProperty( "java.awt.headless", "true" ); String test = "Starting rapla from " + System.getProperty("jetty.home"); System.out.println(test ); RaplaLoader.start( baseDir,dirList, classname,methodName, new Object[] {args }); } }
04900db4-rob
src/org/rapla/bootstrap/RaplaJettyLoader.java
Java
gpl3
1,049
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ /** A Facade Interface for manipulating the stored data. * This abstraction allows Rapla to store the data * in many ways. <BR> * Currently implemented are the storage in an XML-File * ,the storage in an SQL-DBMS and storage over a * network connection. * @see org.rapla.storage.dbsql.DBOperator * @see org.rapla.storage.dbfile.XMLOperator * @see org.rapla.storage.dbrm.RemoteOperator * @author Christopher Kohlhaas */ package org.rapla.storage; import java.util.Collection; import java.util.Date; import java.util.Map; import org.rapla.ConnectInfo; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.storage.EntityResolver; import org.rapla.facade.Conflict; import org.rapla.framework.RaplaException; public interface StorageOperator extends EntityResolver { public static final int MAX_DEPENDENCY = 20; public final static String UNRESOLVED_RESOURCE_TYPE = "rapla:unresolvedResource"; public final static String ANONYMOUSEVENT_TYPE = "rapla:anonymousEvent"; public final static String SYNCHRONIZATIONTASK_TYPE = "rapla:synchronizationTask"; public final static String DEFAUTL_USER_TYPE = "rapla:defaultUser"; public final static String PERIOD_TYPE = "rapla:period"; User connect() throws RaplaException; User connect(ConnectInfo connectInfo) throws RaplaException; boolean isConnected(); /** Refreshes the data. This could be helpful if the storage * operator uses a cache and does not support "Active Monitoring" * of the original data */ void refresh() throws RaplaException; void disconnect() throws RaplaException; /** should return a clone of the object. <strong>Never</strong> edit the original, <strong>always</strong> edit the object returned by editObject.*/ Collection<Entity> editObjects(Collection<Entity> obj, User user) throws RaplaException; Map<String,Entity> getFromId(Collection<String> idSet, boolean throwEntityNotFound) throws RaplaException; Map<Entity,Entity> getPersistant(Collection<? extends Entity> entity) throws RaplaException; /** Stores and/or removes entities and specifies a user that is responsible for the changes. * Notifies all registered StorageUpdateListeners after a successful storage.*/ void storeAndRemove(Collection<Entity> storeObjects,Collection<Entity> removeObjects,User user) throws RaplaException; String[] createIdentifier(RaplaType raplaType, int count) throws RaplaException; Collection<User> getUsers() throws RaplaException; Collection<DynamicType> getDynamicTypes() throws RaplaException; /** returns the user or null if a user with the given username was not found. */ User getUser(String username) throws RaplaException; Preferences getPreferences(User user, boolean createIfNotNull) throws RaplaException; /** returns the reservations of the specified user, sorted by name. * @param allocatables * @param reservationFilters * @param annotationQuery */ Collection<Reservation> getReservations(User user,Collection<Allocatable> allocatables, Date start,Date end, ClassificationFilter[] reservationFilters, Map<String, String> annotationQuery) throws RaplaException; Collection<Allocatable> getAllocatables(ClassificationFilter[] filters) throws RaplaException; Category getSuperCategory(); /** changes the password for the user */ void changePassword(User user,char[] oldPassword,char[] newPassword) throws RaplaException; /** changes the name for the passed user. If a person is connected then all three fields are used. Otherwise only lastname is used*/ void changeName(User user,String title, String firstname, String surname) throws RaplaException; /** changes the name for the user */ void changeEmail(User user,String newEmail) throws RaplaException; void confirmEmail(User user, String newEmail) throws RaplaException; boolean canChangePassword() throws RaplaException; void addStorageUpdateListener(StorageUpdateListener updateListener); void removeStorageUpdateListener(StorageUpdateListener updateListener); /** returns the beginning of the current day. Uses getCurrentTimstamp. */ Date today(); /** returns the date and time in seconds for creation. Server time will be used if in client/server mode. Note that this is always the utc time */ Date getCurrentTimestamp(); boolean supportsActiveMonitoring(); Map<Allocatable,Collection<Appointment>> getFirstAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException; Map<Allocatable, Map<Appointment,Collection<Appointment>>> getAllAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException; Date getNextAllocatableDate(Collection<Allocatable> allocatables,Appointment appointment, Collection<Reservation> ignoreList, Integer worktimeStartMinutes,Integer worktimeEndMinutes, Integer[] excludedDays, Integer rowsPerHour) throws RaplaException; Collection<Conflict> getConflicts(User user) throws RaplaException; Collection<String> getTemplateNames() throws RaplaException; }
04900db4-rob
src/org/rapla/storage/StorageOperator.java
Java
gpl3
6,607
package org.rapla.storage; import org.rapla.entities.Entity; public interface UpdateOperation { public Entity getCurrent(); }
04900db4-rob
src/org/rapla/storage/UpdateOperation.java
Java
gpl3
131
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.impl; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.rapla.components.util.Assert; import org.rapla.components.util.TimeInterval; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.Named; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.internal.ModifiableTimestamp; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityReferencer.ReferenceInfo; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.RefEntity; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.framework.logger.Logger; import org.rapla.storage.LocalCache; import org.rapla.storage.PreferencePatch; import org.rapla.storage.StorageOperator; import org.rapla.storage.StorageUpdateListener; import org.rapla.storage.UpdateEvent; import org.rapla.storage.UpdateResult; /** * An abstract implementation of the StorageOperator-Interface. It operates on a * LocalCache-Object and doesn't implement connect, isConnected, refresh, * createIdentifier and disconnect. <b>!!WARNING!!</b> This operator is not * thread-safe. {@link org.rapla.server.internal.ServerServiceImpl} for an * example of an thread-safe wrapper around this storageoperator. * * @see LocalCache */ public abstract class AbstractCachableOperator implements StorageOperator { protected RaplaLocale raplaLocale; final List<StorageUpdateListener> storageUpdateListeners = new Vector<StorageUpdateListener>(); Map<String,String> createdPreferenceIds = new HashMap<String,String>(); protected LocalCache cache; protected I18nBundle i18n; protected RaplaContext context; Logger logger; protected ReadWriteLock lock = new ReentrantReadWriteLock(); public AbstractCachableOperator(RaplaContext context, Logger logger) throws RaplaException { this.logger = logger; this.context = context; raplaLocale = context.lookup(RaplaLocale.class); i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES); Assert.notNull(raplaLocale.getLocale()); cache = new LocalCache(); } public Logger getLogger() { return logger; } public User connect() throws RaplaException { return connect(null); } // Implementation of StorageOperator public <T extends Entity> T editObject(T o, User user)throws RaplaException { Set<Entity>singleton = Collections.singleton( (Entity)o); Collection<Entity> list = editObjects( singleton, user); Entity first = list.iterator().next(); @SuppressWarnings("unchecked") T casted = (T) first; return casted; } public Collection<Entity> editObjects(Collection<Entity>list, User user)throws RaplaException { checkConnected(); Collection<Entity> toEdit = new LinkedHashSet<Entity>(); // read lock Map<Entity,Entity> persistantMap = getPersistant(list); // read unlock for (Entity o:list) { Entity persistant = persistantMap.get(o); Entity refEntity = editObject(o, persistant, user); toEdit.add( refEntity); } return toEdit; } protected Entity editObject(Entity newObj, Entity persistant, User user) { final SimpleEntity clone; if ( persistant != null) { clone = (SimpleEntity) persistant.clone(); } else { clone = (SimpleEntity) newObj.clone(); } SimpleEntity refEntity = clone; if (refEntity instanceof ModifiableTimestamp) { ((ModifiableTimestamp) refEntity).setLastChangedBy(user); } return (Entity) refEntity; } public void storeAndRemove(final Collection<Entity> storeObjects, final Collection<Entity>removeObjects, final User user) throws RaplaException { checkConnected(); UpdateEvent evt = new UpdateEvent(); if (user != null) { evt.setUserId(user.getId()); } for (Entity obj : storeObjects) { if ( obj instanceof Preferences) { PreferencePatch patch = ((PreferencesImpl)obj).getPatch(); evt.putPatch( patch); } else { evt.putStore(obj); } } for (Entity entity : removeObjects) { RaplaType type = entity.getRaplaType(); if (Appointment.TYPE ==type || Category.TYPE == type || Attribute.TYPE == type) { String name = getName( entity); throw new RaplaException(getI18n().format("error.remove_object",name)); } evt.putRemove(entity); } dispatch(evt); } /** * implement this method to implement the persistent mechanism. By default it * calls <li>check()</li> <li>update()</li> <li>fireStorageUpdate()</li> <li> * fireTriggerEvents()</li> You should not call dispatch directly from the * client. Use storeObjects and removeObjects instead. */ public abstract void dispatch(UpdateEvent evt) throws RaplaException; public Collection<User> getUsers() throws RaplaException { checkConnected(); Lock readLock = readLock(); try { Collection<User> collection = cache.getUsers(); // We return a clone to avoid synchronization Problems return new LinkedHashSet<User>(collection); } finally { unlock(readLock); } } public Collection<DynamicType> getDynamicTypes() throws RaplaException { checkConnected(); Lock readLock = readLock(); try { Collection<DynamicType> collection = cache.getDynamicTypes(); // We return a clone to avoid synchronization Problems return new ArrayList<DynamicType>( collection); } finally { unlock(readLock); } } public Collection<Allocatable> getAllocatables(ClassificationFilter[] filters) throws RaplaException { Collection<Allocatable> allocatables = new LinkedHashSet<Allocatable>(); checkConnected(); Lock readLock = readLock(); try { Collection<Allocatable> collection = cache.getAllocatables(); // We return a clone to avoid synchronization Problems allocatables.addAll(collection); } finally { unlock(readLock); } removeFilteredClassifications(allocatables, filters); return allocatables; } protected void removeFilteredClassifications( Collection<? extends Classifiable> list, ClassificationFilter[] filters) { if (filters == null) { // remove internal types if not specified in filters to remain backwards compatibility Iterator<? extends Classifiable> it = list.iterator(); while (it.hasNext()) { Classifiable classifiable = it.next(); if ( DynamicTypeImpl.isInternalType(classifiable) ) { it.remove(); } } return; } Iterator<? extends Classifiable> it = list.iterator(); while (it.hasNext()) { Classifiable classifiable = it.next(); if (!ClassificationFilter.Util.matches(filters, classifiable)) { it.remove(); } } } public User getUser(final String username) throws RaplaException { checkConnected(); Lock readLock = readLock(); try { return cache.getUser(username); } finally { unlock(readLock); } } Map<String,PreferencesImpl> emptyPreferencesProxy = new ConcurrentHashMap<String, PreferencesImpl>(); public Preferences getPreferences(final User user, boolean createIfNotNull) throws RaplaException { checkConnected(); // Test if user is already stored if (user != null) { resolve(user.getId(), User.class); } String userId = user != null ? user.getId() : null; String preferenceId = PreferencesImpl.getPreferenceIdFromUser(userId); PreferencesImpl pref = (PreferencesImpl) cache.tryResolve( preferenceId, Preferences.class); if (pref == null && createIfNotNull ) { PreferencesImpl preferencesImpl = emptyPreferencesProxy.get( preferenceId); if ( preferencesImpl != null) { return preferencesImpl; } } if (pref == null && createIfNotNull) { PreferencesImpl newPref = newPreferences(userId); newPref.setReadOnly( ); pref = newPref; emptyPreferencesProxy.put(preferenceId , pref); } return pref; } private PreferencesImpl newPreferences(final String userId) throws EntityNotFoundException { Date now = getCurrentTimestamp(); String id = PreferencesImpl.getPreferenceIdFromUser(userId); PreferencesImpl newPref = new PreferencesImpl(now,now); newPref.setResolver( this); if ( userId != null) { User user = resolve( userId, User.class); newPref.setOwner(user); } newPref.setId( id ); return newPref; } public Category getSuperCategory() { return cache.getSuperCategory(); } public synchronized void addStorageUpdateListener(StorageUpdateListener listener) { storageUpdateListeners.add(listener); } public synchronized void removeStorageUpdateListener(StorageUpdateListener listener) { storageUpdateListeners.remove(listener); } public synchronized StorageUpdateListener[] getStorageUpdateListeners() { return storageUpdateListeners.toArray(new StorageUpdateListener[] {}); } protected Lock writeLock() throws RaplaException { return RaplaComponent.lock( lock.writeLock(), 60); } protected Lock readLock() throws RaplaException { return RaplaComponent.lock( lock.readLock(), 10); } protected void unlock(Lock lock) { RaplaComponent.unlock( lock ); } protected I18nBundle getI18n() { return i18n; } protected void fireStorageUpdated(final UpdateResult evt) { StorageUpdateListener[] listeners = getStorageUpdateListeners(); for (int i = 0; i < listeners.length; i++) { listeners[i].objectsUpdated(evt); } } protected void fireUpdateError(final RaplaException ex) { if (storageUpdateListeners.size() == 0) return; StorageUpdateListener[] listeners = getStorageUpdateListeners(); for (int i = 0; i < listeners.length; i++) { listeners[i].updateError(ex); } } protected void fireStorageDisconnected(String message) { if (storageUpdateListeners.size() == 0) return; StorageUpdateListener[] listeners = getStorageUpdateListeners(); for (int i = 0; i < listeners.length; i++) { listeners[i].storageDisconnected(message); } } // End of StorageOperator interface protected void checkConnected() throws RaplaException { if (!isConnected()) { throw new RaplaException(getI18n().format("error.connection_closed", "")); } } @Override public Map<String,Entity> getFromId(Collection<String> idSet, boolean throwEntityNotFound) throws RaplaException { Lock readLock = readLock(); try { Map<String, Entity> result= new LinkedHashMap<String,Entity>(); for ( String id:idSet) { Entity persistant = (throwEntityNotFound ? cache.resolve(id) : cache.tryResolve(id)); if ( persistant != null) { result.put( id,persistant); } } return result; } finally { unlock(readLock); } } @Override public Map<Entity,Entity> getPersistant(Collection<? extends Entity> list) throws RaplaException { Map<String,Entity> idMap = new LinkedHashMap<String,Entity>(); for ( Entity key: list) { String id = key.getId().toString(); idMap.put( id, key); } Map<Entity,Entity> result = new LinkedHashMap<Entity,Entity>(); Set<String> keySet = idMap.keySet(); Map<String,Entity> resolvedList = getFromId( keySet, false); for (Entity entity:resolvedList.values()) { String id = entity.getId().toString(); Entity key = idMap.get( id); if ( key != null ) { result.put( key, entity); } } return result; } /** * @throws RaplaException */ protected void setResolver(Collection<? extends Entity> entities) throws RaplaException { for (Entity entity: entities) { if (entity instanceof EntityReferencer) { ((EntityReferencer)entity).setResolver(this); } } // It is important to do the read only later because some resolve might involve write to referenced objects for (Entity entity: entities) { if (entity instanceof RefEntity) { ((RefEntity)entity).setReadOnly(); } } } protected void testResolve(Collection<? extends Entity> entities) throws EntityNotFoundException { EntityStore store = new EntityStore( this, getSuperCategory()); store.addAll( entities); for (Entity entity: entities) { if (entity instanceof EntityReferencer) { ((EntityReferencer)entity).setResolver(store); } } for (Entity entity: entities) { if (entity instanceof EntityReferencer) { testResolve(store, (EntityReferencer)entity); } } } private void testResolve(EntityResolver resolver, EntityReferencer referencer) throws EntityNotFoundException { Iterable<ReferenceInfo> referencedIds =referencer.getReferenceInfo(); for ( ReferenceInfo id:referencedIds) { testResolve(resolver, referencer, id); } } private void testResolve(EntityResolver resolver, EntityReferencer obj, ReferenceInfo reference) throws EntityNotFoundException { Class<? extends Entity> class1 = reference.getType(); String id = reference.getId(); if (tryResolve(resolver,id, class1) == null) { String prefix = (class1!= null) ? class1.getName() : " unkown type"; throw new EntityNotFoundException(prefix + " with id " + id + " not found for " + obj); } } protected String getName(Object object) { if (object == null) return null; if (object instanceof Named) return (((Named) object).getName(i18n.getLocale())); return object.toString(); } protected String getString(String key) { return getI18n().getString(key); } public DynamicType getDynamicType(String key) { Lock readLock = null; try { readLock = readLock(); } catch (RaplaException e) { // this is not so dangerous getLogger().warn("Returning type " + key + " without read lock "); } try { return cache.getDynamicType( key); } finally { unlock(readLock); } } @Override public Entity tryResolve(String id) { return tryResolve( id, null); } @Override public Entity resolve(String id) throws EntityNotFoundException { return resolve( id, null); } @Override public <T extends Entity> T tryResolve(String id,Class<T> entityClass) { Lock readLock = null; try { readLock = readLock(); } catch (RaplaException e) { getLogger().warn("Returning object for id " + id + " without read lock "); } try { return tryResolve(cache,id, entityClass); } finally { unlock(readLock); } } @Override public <T extends Entity> T resolve(String id,Class<T> entityClass) throws EntityNotFoundException { Lock readLock; try { readLock = readLock(); } catch (RaplaException e) { throw new EntityNotFoundException( e.getMessage() + " " +e.getCause()); } try { return resolve(cache,id, entityClass); } finally { unlock(readLock); } } protected <T extends Entity> T resolve(EntityResolver resolver,String id,Class<T> entityClass) throws EntityNotFoundException { T entity = tryResolve(resolver,id, entityClass); SimpleEntity.checkResolveResult(id, entityClass, entity); return entity; } protected <T extends Entity> T tryResolve(EntityResolver resolver,String id,Class<T> entityClass) { return resolver.tryResolve(id, entityClass); } /** Writes the UpdateEvent in the cache */ protected UpdateResult update(final UpdateEvent evt) throws RaplaException { HashMap<Entity,Entity> oldEntities = new HashMap<Entity,Entity>(); // First make a copy of the old entities Collection<Entity>storeObjects = new LinkedHashSet<Entity>(evt.getStoreObjects()); for (Entity entity : storeObjects) { Entity persistantEntity = findPersistant(entity); if ( persistantEntity == null) { continue; } if (getLogger().isDebugEnabled()) { getLogger().debug("Storing old: " + entity); } if ( persistantEntity instanceof Appointment || ((persistantEntity instanceof Category) && storeObjects.contains( ((Category) persistantEntity).getParent()))) { throw new RaplaException( persistantEntity.getRaplaType() + " can only be stored via parent entity "); // we ingore subentities, because these are added as bellow via addSubentites. The originals will be contain false parent references (to the new parents) when copy is called } else { Entity oldEntity = persistantEntity; oldEntities.put(persistantEntity, oldEntity); } } Collection<PreferencePatch> preferencePatches = evt.getPreferencePatches(); for ( PreferencePatch patch:preferencePatches) { String userId = patch.getUserId(); PreferencesImpl oldEntity = cache.getPreferencesForUserId( userId); PreferencesImpl clone; if ( oldEntity == null) { clone = newPreferences( userId); } else { clone = oldEntity.clone(); } clone.applyPatch( patch); oldEntities.put(clone, oldEntity); storeObjects.add( clone); } List<Entity>updatedEntities = new ArrayList<Entity>(); // Then update the new entities for (Entity entity : storeObjects) { Entity persistant = findPersistant(entity); // do nothing, because the persitantVersion is always read only if (persistant == entity) { continue; } if ( entity instanceof Category) { Category category = (Category)entity; CategoryImpl parent = (CategoryImpl)category.getParent(); if ( parent != null) { parent.replace( category); } } cache.put(entity); updatedEntities.add(entity); } Collection<Entity> removeObjects = evt.getRemoveObjects(); Collection<Entity> toRemove = new HashSet<Entity>(); for (Entity entity : removeObjects) { Entity persistantVersion = findPersistant(entity); if (persistantVersion != null) { cache.remove(persistantVersion); ((RefEntity)persistantVersion).setReadOnly(); } toRemove.add( entity); } setResolver(updatedEntities); TimeInterval invalidateInterval = evt.getInvalidateInterval(); String userId = evt.getUserId(); return createUpdateResult(oldEntities, updatedEntities, toRemove, invalidateInterval, userId); } protected Entity findPersistant(Entity entity) { @SuppressWarnings("unchecked") Class<? extends Entity> typeClass = entity.getRaplaType().getTypeClass(); Entity persistantEntity = cache.tryResolve(entity.getId(), typeClass); return persistantEntity; } protected UpdateResult createUpdateResult( Map<Entity,Entity> oldEntities, Collection<Entity>updatedEntities, Collection<Entity>toRemove, TimeInterval invalidateInterval, String userId) throws EntityNotFoundException { User user = null; if (userId != null) { user = resolve(cache,userId, User.class); } UpdateResult result = new UpdateResult(user); if ( invalidateInterval != null) { result.setInvalidateInterval( invalidateInterval); } for (Entity toUpdate:updatedEntities) { Entity newEntity = toUpdate; Entity oldEntity = oldEntities.get(toUpdate); if (oldEntity != null) { result.addOperation(new UpdateResult.Change( newEntity, oldEntity)); } else { result.addOperation(new UpdateResult.Add( newEntity)); } } for (Entity entity:toRemove) { result.addOperation(new UpdateResult.Remove(entity)); } return result; } }
04900db4-rob
src/org/rapla/storage/impl/AbstractCachableOperator.java
Java
gpl3
21,633
package org.rapla.storage.impl.server; import java.util.Collection; import java.util.SortedSet; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; public interface AllocationMap { SortedSet<Appointment> getAppointments(Allocatable allocatable); Collection<Allocatable> getAllocatables(); }
04900db4-rob
src/org/rapla/storage/impl/server/AllocationMap.java
Java
gpl3
348
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.impl.server; import org.rapla.framework.Configuration; import org.rapla.framework.ConfigurationException; import org.rapla.framework.Container; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; import org.rapla.storage.CachableStorageOperator; import org.rapla.storage.CachableStorageOperatorCommand; import org.rapla.storage.ImportExportManager; import org.rapla.storage.LocalCache; /** Imports the content of on store into another. Export does an import with source and destination exchanged. <p>Configuration:</p> <pre> <importexport id="importexport" activation="request"> <source>raplafile</source> <dest>rapladb</dest> </importexport> </pre> */ public class ImportExportManagerImpl implements ImportExportManager { Container container; String sourceString; String destString; Logger logger; public ImportExportManagerImpl(RaplaContext context,Configuration configuration) throws RaplaException { this.logger = context.lookup( Logger.class); this.container = context.lookup( Container.class); try { sourceString = configuration.getChild("source").getValue(); destString = configuration.getChild("dest").getValue(); } catch (ConfigurationException e) { throw new RaplaException( e); } } protected Logger getLogger() { return logger.getChildLogger("importexport"); } /* Import the source into dest. */ public void doImport() throws RaplaException { Logger logger = getLogger(); logger.info("Import from " + sourceString + " into " + destString); CachableStorageOperator source = getSource(); source.connect(); CachableStorageOperator destination = getDestination(); doConvert(source,destination); logger.info("Import completed"); } /* Export the dest into source. */ public void doExport() throws RaplaException { Logger logger = getLogger(); logger.info("Export from " + destString + " into " + sourceString); CachableStorageOperator destination = getDestination(); destination.connect(); CachableStorageOperator source = getSource(); doConvert(destination,source); logger.info("Export completed"); } private void doConvert(final CachableStorageOperator cachableStorageOperator1,final CachableStorageOperator cachableStorageOperator2) throws RaplaException { cachableStorageOperator1.runWithReadLock( new CachableStorageOperatorCommand() { public void execute(LocalCache cache) throws RaplaException { cachableStorageOperator2.saveData(cache); } }); } @Override public CachableStorageOperator getSource() throws RaplaException { CachableStorageOperator lookup = container.lookup(CachableStorageOperator.class, sourceString); return lookup; } @Override public CachableStorageOperator getDestination() throws RaplaException { CachableStorageOperator lookup = container.lookup(CachableStorageOperator.class, destString); return lookup; } }
04900db4-rob
src/org/rapla/storage/impl/server/ImportExportManagerImpl.java
Java
gpl3
4,091
package org.rapla.storage.impl.server; import java.util.HashSet; import java.util.Set; import org.rapla.entities.domain.Appointment; class AllocationChange { public Set<Appointment> toChange = new HashSet<Appointment>(); public Set<Appointment> toRemove= new HashSet<Appointment>(); public String toString() { return "toChange="+toChange.toString() + ";toRemove=" + toRemove.toString(); } }
04900db4-rob
src/org/rapla/storage/impl/server/AllocationChange.java
Java
gpl3
420
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.impl.server; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TimeZone; import java.util.TreeSet; import java.util.UUID; import java.util.concurrent.locks.Lock; import org.rapla.components.util.Cancelable; import org.rapla.components.util.Command; import org.rapla.components.util.CommandScheduler; import org.rapla.components.util.DateTools; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.components.util.TimeInterval; import org.rapla.components.util.Tools; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.entities.Category; import org.rapla.entities.DependencyException; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.Named; import org.rapla.entities.Ownable; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.Timestamp; import org.rapla.entities.UniqueKeyException; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentStartComparator; import org.rapla.entities.domain.Permission; import org.rapla.entities.domain.RaplaObjectAnnotations; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.ResourceAnnotations; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.entities.dynamictype.internal.AttributeImpl; import org.rapla.entities.dynamictype.internal.ClassificationImpl; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.internal.ModifiableTimestamp; import org.rapla.entities.internal.UserImpl; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityReferencer.ReferenceInfo; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.RefEntity; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.facade.Conflict; import org.rapla.facade.RaplaComponent; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; import org.rapla.server.internal.TimeZoneConverterImpl; import org.rapla.storage.CachableStorageOperator; import org.rapla.storage.CachableStorageOperatorCommand; import org.rapla.storage.IdCreator; import org.rapla.storage.LocalCache; import org.rapla.storage.RaplaNewVersionException; import org.rapla.storage.RaplaSecurityException; import org.rapla.storage.UpdateEvent; import org.rapla.storage.UpdateOperation; import org.rapla.storage.UpdateResult; import org.rapla.storage.impl.AbstractCachableOperator; import org.rapla.storage.impl.EntityStore; public abstract class LocalAbstractCachableOperator extends AbstractCachableOperator implements Disposable, CachableStorageOperator, IdCreator { /** * set encryption if you want to enable password encryption. Possible values * are "sha" or "md5". */ private String encryption = "sha-1"; private ConflictFinder conflictFinder; private Map<String,SortedSet<Appointment>> appointmentMap; private SortedSet<Timestamp> timestampSet; private TimeZone systemTimeZone = TimeZone.getDefault(); private CommandScheduler scheduler; private Cancelable cleanConflictsTask; MessageDigest md; protected void addInternalTypes(LocalCache cache) throws RaplaException { { DynamicTypeImpl type = new DynamicTypeImpl(); String key = UNRESOLVED_RESOURCE_TYPE; type.setKey(key); type.setId( key); type.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{"+key + "}"); type.getName().setName("en", "anonymous"); type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON); type.setResolver( this); type.setReadOnly( ); cache.put( type); } { DynamicTypeImpl type = new DynamicTypeImpl(); String key = ANONYMOUSEVENT_TYPE; type.setKey(key); type.setId( key); type.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{"+key + "}"); type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION); type.getName().setName("en", "anonymous"); type.setResolver( this); cache.put( type); } { DynamicTypeImpl type = new DynamicTypeImpl(); String key = DEFAUTL_USER_TYPE; type.setKey(key); type.setId( key); type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE); //type.setAnnotation(DynamicTypeAnnotations.KEY_TRANSFERED_TO_CLIENT, DynamicTypeAnnotations.VALUE_TRANSFERED_TO_CLIENT_NEVER); addAttributeWithInternalId(type,"surname", AttributeType.STRING); addAttributeWithInternalId(type,"firstname", AttributeType.STRING); addAttributeWithInternalId(type,"email", AttributeType.STRING); type.setResolver( this); type.setReadOnly(); cache.put( type); } { DynamicTypeImpl type = new DynamicTypeImpl(); String key = PERIOD_TYPE; type.setKey(key); type.setId( key); type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE); type.setAnnotation(DynamicTypeAnnotations.KEY_TRANSFERED_TO_CLIENT, null); addAttributeWithInternalId(type,"name", AttributeType.STRING); addAttributeWithInternalId(type,"start", AttributeType.DATE); addAttributeWithInternalId(type,"end", AttributeType.DATE); type.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}"); type.setResolver( this); type.setReadOnly(); cache.put( type); } { DynamicTypeImpl type = new DynamicTypeImpl(); String key = SYNCHRONIZATIONTASK_TYPE; type.setKey(key); type.setId( key); type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE); type.setAnnotation(DynamicTypeAnnotations.KEY_TRANSFERED_TO_CLIENT, DynamicTypeAnnotations.VALUE_TRANSFERED_TO_CLIENT_NEVER); addAttributeWithInternalId(type,"objectId", AttributeType.STRING); addAttributeWithInternalId(type,"externalObjectId",AttributeType.STRING); addAttributeWithInternalId(type,"status",AttributeType.STRING); addAttributeWithInternalId(type,"retries", AttributeType.STRING); type.setResolver( this); type.setReadOnly(); cache.put( type); } } public LocalAbstractCachableOperator(RaplaContext context, Logger logger) throws RaplaException { super( context, logger); scheduler = context.lookup( CommandScheduler.class); try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RaplaException( e.getMessage() ,e); } } public void runWithReadLock(CachableStorageOperatorCommand cmd) throws RaplaException { Lock readLock = readLock(); try { cmd.execute( cache ); } finally { unlock( readLock); } } public List<Reservation> getReservations(User user, Collection<Allocatable> allocatables, Date start, Date end, ClassificationFilter[] filters,Map<String,String> annotationQuery) throws RaplaException { boolean excludeExceptions = false; HashSet<Reservation> reservationSet = new HashSet<Reservation>(); if (allocatables == null || allocatables.size() ==0) { allocatables = Collections.singleton( null); } for ( Allocatable allocatable: allocatables) { Lock readLock = readLock(); SortedSet<Appointment> appointments; try { appointments = getAppointments( allocatable); } finally { unlock( readLock); } SortedSet<Appointment> appointmentSet = AppointmentImpl.getAppointments(appointments,user,start,end, excludeExceptions); for (Appointment appointment:appointmentSet) { Reservation reservation = appointment.getReservation(); if ( !match(reservation, annotationQuery) ) { continue; } // Ignore Templates if not explicitly requested // FIXME this special case should be refactored, so one can get all reservations in one method else if ( RaplaComponent.isTemplate( reservation) && (annotationQuery == null || !annotationQuery.containsKey(RaplaObjectAnnotations.KEY_TEMPLATE) )) { continue; } if ( !reservationSet.contains( reservation)) { reservationSet.add( reservation ); } } } ArrayList<Reservation> result = new ArrayList<Reservation>(reservationSet); removeFilteredClassifications(result, filters); return result; } public boolean match(Reservation reservation, Map<String, String> annotationQuery) { if ( annotationQuery != null) { for (String key : annotationQuery.keySet()) { String annotationParam = annotationQuery.get( key); String annotation = reservation.getAnnotation( key); if ( annotation == null || annotationParam == null) { if (annotationParam!= null) { return false; } } else { if ( !annotation.equals(annotationParam)) { return false; } } } } return true; } public Collection<String> getTemplateNames() throws RaplaException { Lock readLock = readLock(); Collection<? extends Reservation> reservations; try { reservations = cache.getReservations(); } finally { unlock(readLock); } //Reservation[] reservations = cache.getReservations(user, start, end, filters.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY)); Set<String> templates = new LinkedHashSet<String>(); for ( Reservation r:reservations) { String templateName = r.getAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE); if ( templateName != null) { templates.add( templateName); } } return templates; } @Override public String createId(RaplaType raplaType) throws RaplaException { return UUID.randomUUID().toString(); } public String createId(RaplaType raplaType,String seed) throws RaplaException { byte[] data = new byte[16]; data = md.digest( seed.getBytes()); if ( data.length != 16 ) { throw new RaplaException("Wrong algorithm"); } data[6] &= 0x0f; /* clear version */ data[6] |= 0x40; /* set to version 4 */ data[8] &= 0x3f; /* clear variant */ data[8] |= 0x80; /* set to IETF variant */ long msb = 0; long lsb = 0; for (int i=0; i<8; i++) msb = (msb << 8) | (data[i] & 0xff); for (int i=8; i<16; i++) lsb = (lsb << 8) | (data[i] & 0xff); long mostSigBits = msb; long leastSigBits = lsb; UUID uuid = new UUID( mostSigBits, leastSigBits); return uuid.toString(); } public String[] createIdentifier(RaplaType raplaType, int count) throws RaplaException { String[] ids = new String[ count]; for ( int i=0;i<count;i++) { ids[i] = createId(raplaType); } return ids; } public Date today() { long time = getCurrentTimestamp().getTime(); long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time); Date raplaTime = new Date(time + offset); return DateTools.cutDate( raplaTime); } public Date getCurrentTimestamp() { long time = System.currentTimeMillis(); return new Date( time); } public void setTimeZone( TimeZone timeZone) { systemTimeZone = timeZone; } public TimeZone getTimeZone() { return systemTimeZone; } public String authenticate(String username, String password) throws RaplaException { Lock readLock = readLock(); try { getLogger().info("Check password for User " + username); User user = cache.getUser(username); if (user != null) { String userId = user.getId(); if (checkPassword(userId, password)) { return userId; } } getLogger().warn("Login failed for " + username); throw new RaplaSecurityException(i18n.getString("error.login")); } finally { unlock( readLock ); } } public boolean canChangePassword() throws RaplaException { return true; } public void changePassword(User user, char[] oldPassword,char[] newPassword) throws RaplaException { getLogger().info("Change password for User " + user.getUsername()); String userId = user.getId(); String password = new String(newPassword); if (encryption != null) password = encrypt(encryption, password); Lock writeLock = writeLock( ); try { cache.putPassword(userId, password); } finally { unlock( writeLock ); } User editObject = editObject(user, null); List<Entity> editList = new ArrayList<Entity>(1); editList.add(editObject); Collection<Entity>removeList = Collections.emptyList(); // synchronization will be done in the dispatch method storeAndRemove(editList, removeList, user); } public void changeName(User user, String title,String firstname, String surname) throws RaplaException { User editableUser = editObject(user, user); Allocatable personReference = editableUser.getPerson(); if (personReference == null) { editableUser.setName(surname); storeUser(editableUser); } else { Allocatable editablePerson = editObject(personReference, null); Classification classification = editablePerson.getClassification(); { Attribute attribute = classification.getAttribute("title"); if (attribute != null) { classification.setValue(attribute, title); } } { Attribute attribute = classification.getAttribute("firstname"); if (attribute != null) { classification.setValue(attribute, firstname); } } { Attribute attribute = classification.getAttribute("surname"); if (attribute != null) { classification.setValue(attribute, surname); } } ArrayList<Entity> arrayList = new ArrayList<Entity>(); arrayList.add(editableUser); arrayList.add(editablePerson); Collection<Entity> storeObjects = arrayList; Collection<Entity> removeObjects = Collections.emptySet(); // synchronization will be done in the dispatch method storeAndRemove(storeObjects, removeObjects, null); } } public void changeEmail(User user, String newEmail) throws RaplaException { User editableUser = user.isReadOnly() ? editObject(user, (User) user) : user; Allocatable personReference = editableUser.getPerson(); ArrayList<Entity>arrayList = new ArrayList<Entity>(); Collection<Entity>storeObjects = arrayList; Collection<Entity>removeObjects = Collections.emptySet(); storeObjects.add(editableUser); if (personReference == null) { editableUser.setEmail(newEmail); } else { Allocatable editablePerson = editObject(personReference, null); Classification classification = editablePerson.getClassification(); classification.setValue("email", newEmail); storeObjects.add(editablePerson); } storeAndRemove(storeObjects, removeObjects, null); } protected void resolveInitial(Collection<? extends Entity> entities,EntityResolver resolver) throws RaplaException { testResolve(entities); for (Entity entity: entities) { if ( entity instanceof EntityReferencer) { ((EntityReferencer)entity).setResolver(resolver); } } processUserPersonLink(entities); // It is important to do the read only later because some resolve might involve write to referenced objects for (Entity entity: entities) { ((RefEntity)entity).setReadOnly(); } } protected void processUserPersonLink(Collection<? extends Entity> entities) throws RaplaException { // resolve emails Map<String,Allocatable> resolvingMap = new HashMap<String,Allocatable>(); for (Entity entity: entities) { if ( entity instanceof Allocatable) { Allocatable allocatable = (Allocatable) entity; final Classification classification = allocatable.getClassification(); final Attribute attribute = classification.getAttribute("email"); if ( attribute != null) { final String email = (String)classification.getValue(attribute); if ( email != null ) { resolvingMap.put( email, allocatable); } } } } for ( Entity entity: entities) { if ( entity.getRaplaType().getTypeClass() == User.class) { User user = (User)entity; String email = user.getEmail(); if ( email != null && email.trim().length() > 0) { Allocatable person = resolvingMap.get(email); if ( person != null) { user.setPerson(person); } } } } } public void confirmEmail(User user, String newEmail) throws RaplaException { throw new RaplaException("Email confirmation must be done in the remotestorage class"); } public Collection<Conflict> getConflicts(User user) throws RaplaException { Lock readLock = readLock(); try { return conflictFinder.getConflicts( user); } finally { unlock( readLock ); } } boolean disposing; public void dispose() { // prevent reentrance in dispose synchronized ( this) { if ( disposing) { getLogger().warn("Disposing is called twice",new RaplaException("")); return; } disposing = true; } try { if ( cleanConflictsTask != null) { cleanConflictsTask.cancel(); } forceDisconnect(); } finally { disposing = false; } } protected void forceDisconnect() { try { disconnect(); } catch (Exception ex) { getLogger().error("Error during disconnect ", ex); } } /** performs Integrity constraints check */ protected void check(final UpdateEvent evt, final EntityStore store) throws RaplaException { Set<Entity> storeObjects = new HashSet<Entity>(evt.getStoreObjects()); //Set<Entity> removeObjects = new HashSet<Entity>(evt.getRemoveObjects()); checkConsistency(evt, store); checkUnique(evt,store); checkReferences(evt, store); checkNoDependencies(evt, store); checkVersions(storeObjects); } protected void updateLastChanged(UpdateEvent evt) throws RaplaException { Date currentTime = getCurrentTimestamp(); String userId = evt.getUserId(); User lastChangedBy = ( userId != null) ? resolve(userId,User.class) : null; for ( Entity e: evt.getStoreObjects()) { if ( e instanceof ModifiableTimestamp) { ModifiableTimestamp modifiableTimestamp = (ModifiableTimestamp)e; Date lastChangeTime = modifiableTimestamp.getLastChanged(); if ( lastChangeTime != null && lastChangeTime.equals( currentTime)) { // wait 1 ms to increase timestamp try { Thread.sleep(1); } catch (InterruptedException e1) { throw new RaplaException( e1.getMessage(), e1); } currentTime = getCurrentTimestamp(); } modifiableTimestamp.setLastChanged( currentTime); modifiableTimestamp.setLastChangedBy( lastChangedBy ); } } } class TimestampComparator implements Comparator<Timestamp> { public int compare(Timestamp o1, Timestamp o2) { if ( o1 == o2) { return 0; } Date d1 = o1.getLastChanged(); Date d2 = o2.getLastChanged(); // if d1 is null and d2 is not then d1 is before d2 if ( d1 == null && d2 != null ) { return -1; } // if d2 is null and d1 is not then d2 is before d1 if ( d1 != null && d2 == null) { return 1; } if ( d1 != null && d2 != null) { int result = d1.compareTo( d2); if ( result != 0) { return result; } } String id1 = (o1 instanceof Entity) ? ((Entity)o1).getId() : o1.toString(); String id2 = (o2 instanceof Entity) ? ((Entity)o2).getId() : o2.toString(); if ( id1 == null) { if ( id2 == null) { throw new IllegalStateException("Can't compare two entities without ids"); } else { return -1; } } else if ( id2 == null) { return 1; } return id1.compareTo( id2 ); } } protected void initIndizes() { timestampSet = new TreeSet<Timestamp>(new TimestampComparator()); timestampSet.addAll( cache.getDynamicTypes()); timestampSet.addAll( cache.getReservations()); timestampSet.addAll( cache.getAllocatables()); timestampSet.addAll( cache.getUsers()); // The appointment map appointmentMap = new HashMap<String, SortedSet<Appointment>>(); for ( Reservation r: cache.getReservations()) { for ( Appointment app:((ReservationImpl)r).getAppointmentList()) { Reservation reservation = app.getReservation(); Allocatable[] allocatables = reservation.getAllocatablesFor(app); { Collection<Appointment> list = getAndCreateList(appointmentMap,null); list.add( app); } for ( Allocatable alloc:allocatables) { Collection<Appointment> list = getAndCreateList(appointmentMap,alloc); list.add( app); } } } Date today2 = today(); AllocationMap allocationMap = new AllocationMap() { public SortedSet<Appointment> getAppointments(Allocatable allocatable) { return LocalAbstractCachableOperator.this.getAppointments(allocatable); } @SuppressWarnings("unchecked") public Collection<Allocatable> getAllocatables() { return (Collection)cache.getAllocatables(); } }; // The conflict map conflictFinder = new ConflictFinder(allocationMap, today2, getLogger(), this); long delay = DateTools.MILLISECONDS_PER_HOUR; long period = DateTools.MILLISECONDS_PER_HOUR; Command cleanUpConflicts = new Command() { @Override public void execute() throws Exception { removeOldConflicts(); } }; cleanConflictsTask = scheduler.schedule( cleanUpConflicts, delay, period); } /** updates the bindings of the resources and returns a map with all processed allocation changes*/ private void updateIndizes(UpdateResult result) { Map<Allocatable,AllocationChange> toUpdate = new HashMap<Allocatable,AllocationChange>(); List<Allocatable> removedAllocatables = new ArrayList<Allocatable>(); for (UpdateOperation operation: result.getOperations()) { Entity current = operation.getCurrent(); RaplaType raplaType = current.getRaplaType(); if ( raplaType == Reservation.TYPE ) { if ( operation instanceof UpdateResult.Remove) { Reservation old = (Reservation) current; for ( Appointment app: old.getAppointments() ) { updateBindings( toUpdate, old, app, true); } } if ( operation instanceof UpdateResult.Add) { Reservation newReservation = (Reservation) ((UpdateResult.Add) operation).getNew(); for ( Appointment app: newReservation.getAppointments() ) { updateBindings( toUpdate, newReservation,app, false); } } if ( operation instanceof UpdateResult.Change) { Reservation oldReservation = (Reservation) ((UpdateResult.Change) operation).getOld(); Reservation newReservation =(Reservation) ((UpdateResult.Change) operation).getNew(); Appointment[] oldAppointments = oldReservation.getAppointments(); for ( Appointment oldApp: oldAppointments) { updateBindings( toUpdate, oldReservation, oldApp, true); } Appointment[] newAppointments = newReservation.getAppointments(); for ( Appointment newApp: newAppointments) { updateBindings( toUpdate, newReservation, newApp, false); } } } if ( raplaType == Allocatable.TYPE ) { if ( operation instanceof UpdateResult.Remove) { Allocatable old = (Allocatable) current; removedAllocatables.add( old); } } if (raplaType == Allocatable.TYPE || raplaType == Reservation.TYPE || raplaType == DynamicType.TYPE || raplaType == User.TYPE || raplaType == Preferences.TYPE || raplaType == Category.TYPE ) { if ( operation instanceof UpdateResult.Remove) { Timestamp old = (Timestamp) current; timestampSet.remove( old); } if ( operation instanceof UpdateResult.Add) { Timestamp newEntity = (Timestamp) ((UpdateResult.Add) operation).getNew(); timestampSet.add( newEntity); } if ( operation instanceof UpdateResult.Change) { Timestamp newEntity = (Timestamp) ((UpdateResult.Change) operation).getNew(); Timestamp oldEntity = (Timestamp) ((UpdateResult.Change) operation).getOld(); timestampSet.remove( oldEntity); timestampSet.add( newEntity); } } } for ( Allocatable alloc: removedAllocatables) { SortedSet<Appointment> sortedSet = appointmentMap.get( alloc); if ( sortedSet != null && !sortedSet.isEmpty()) { getLogger().error("Removing non empty appointment map for resource " + alloc + " Appointments:" + sortedSet); } appointmentMap.remove( alloc); } Date today = today(); // processes the conflicts and adds the changes to the result conflictFinder.updateConflicts(toUpdate,result, today, removedAllocatables); checkAbandonedAppointments(); } @Override public Collection<Entity> getUpdatedEntities(final Date timestamp) throws RaplaException { Timestamp fromElement = new Timestamp() { @Override public User getLastChangedBy() { return null; } @Override public Date getLastChanged() { return timestamp; } @Override public Date getLastChangeTime() { return getLastChanged(); } @Override public Date getCreateTime() { return timestamp; } }; Lock lock = readLock(); Collection<Entity> result = new ArrayList<Entity>(); try { SortedSet<Timestamp> tailSet = timestampSet.tailSet(fromElement); for ( Timestamp entry : tailSet) { result.add( (Entity) entry ); } } finally { unlock(lock); } return result; } protected void updateBindings(Map<Allocatable, AllocationChange> toUpdate,Reservation reservation,Appointment app, boolean remove) { Set<Allocatable> allocatablesToProcess = new HashSet<Allocatable>(); allocatablesToProcess.add( null); if ( reservation != null) { Allocatable[] allocatablesFor = reservation.getAllocatablesFor( app); allocatablesToProcess.addAll( Arrays.asList(allocatablesFor)); // This double check is very imperformant and will be removed in the future, if it doesnt show in test runs // if ( remove) // { // Collection<Allocatable> allocatables = cache.getCollection(Allocatable.class); // for ( Allocatable allocatable:allocatables) // { // SortedSet<Appointment> appointmentSet = this.appointmentMap.get( allocatable.getId()); // if ( appointmentSet == null) // { // continue; // } // for (Appointment app1:appointmentSet) // { // if ( app1.equals( app)) // { // if ( !allocatablesToProcess.contains( allocatable)) // { // getLogger().error("Old reservation " + reservation.toString() + " has not the correct allocatable information. Using full search for appointment " + app + " and resource " + allocatable ) ; // allocatablesToProcess.add(allocatable); // } // } // } // } // } } else { getLogger().error("Appointment without reservation found " + app + " ignoring."); } for ( Allocatable allocatable: allocatablesToProcess) { AllocationChange updateSet; if ( allocatable != null) { updateSet = toUpdate.get( allocatable); if ( updateSet == null) { updateSet = new AllocationChange(); toUpdate.put(allocatable, updateSet); } } else { updateSet = null; } if ( remove) { Collection<Appointment> appointmentSet = getAndCreateList(appointmentMap,allocatable); // binary search could fail if the appointment has changed since the last add, which should not // happen as we only put and search immutable objects in the map. But the method is left here as a failsafe // with a log messaget if (!appointmentSet.remove( app)) { getLogger().error("Appointent has changed, so its not found in indexed binding map. Removing via full search"); // so we need to traverse all appointment Iterator<Appointment> it = appointmentSet.iterator(); while (it.hasNext()) { if (app.equals(it.next())) { it.remove(); break; } } } if ( updateSet != null) { updateSet.toRemove.add( app); } } else { SortedSet<Appointment> appointmentSet = getAndCreateList(appointmentMap, allocatable); appointmentSet.add(app); if ( updateSet != null) { updateSet.toChange.add( app); } } } } static final SortedSet<Appointment> EMPTY_SORTED_SET = Collections.unmodifiableSortedSet( new TreeSet<Appointment>()); protected SortedSet<Appointment> getAppointments(Allocatable allocatable) { String allocatableId = allocatable != null ? allocatable.getId() : null; SortedSet<Appointment> s = appointmentMap.get( allocatableId); if ( s == null) { return EMPTY_SORTED_SET; } return Collections.unmodifiableSortedSet(s); } private SortedSet<Appointment> getAndCreateList(Map<String,SortedSet<Appointment>> appointmentMap,Allocatable alloc) { String allocationId = alloc != null ? alloc.getId() : null; SortedSet<Appointment> set = appointmentMap.get( allocationId); if ( set == null) { set = new TreeSet<Appointment>(new AppointmentStartComparator()); appointmentMap.put(allocationId, set); } return set; } @Override protected UpdateResult update(UpdateEvent evt) throws RaplaException { UpdateResult update = super.update(evt); updateIndizes(update); return update; } public void removeOldConflicts() throws RaplaException { Map<Entity,Entity> oldEntities = new LinkedHashMap<Entity,Entity>(); Collection<Entity>updatedEntities = new LinkedHashSet<Entity>(); Collection<Entity>toRemove = new LinkedHashSet<Entity>(); TimeInterval invalidateInterval = null; String userId = null; UpdateResult result = createUpdateResult(oldEntities, updatedEntities, toRemove, invalidateInterval, userId); //Date today = getCurrentTimestamp(); Date today = today(); Lock readLock = readLock(); try { conflictFinder.removeOldConflicts(result, today); } finally { unlock( readLock); } fireStorageUpdated( result ); } protected void preprocessEventStorage(final UpdateEvent evt) throws RaplaException { EntityStore store = new EntityStore(this, this.getSuperCategory()); Collection<Entity>storeObjects = evt.getStoreObjects(); store.addAll(storeObjects); for (Entity entity:storeObjects) { if (getLogger().isDebugEnabled()) getLogger().debug("Contextualizing " + entity); ((EntityReferencer)entity).setResolver( store); // add all child categories to store if ( entity instanceof Category) { Set<Category> children = getAllCategories( (Category)entity); store.addAll(children); } } Collection<Entity>removeObjects = evt.getRemoveObjects(); store.addAll( removeObjects ); for ( Entity entity:removeObjects) { ((EntityReferencer)entity).setResolver( store); } // add transitve changes to event addClosure( evt, store ); // check event for inconsistencies check( evt, store); // update last changed date updateLastChanged( evt ); } /** * Create a closure for all objects that should be updated. The closure * contains all objects that are sub-entities of the entities and all * objects and all other objects that are affected by the update: e.g. * Classifiables when the DynamicType changes. The method will recursivly * proceed with all discovered objects. */ protected void addClosure(final UpdateEvent evt,EntityStore store) throws RaplaException { Collection<Entity> storeObjects = new ArrayList<Entity>(evt.getStoreObjects()); Collection<Entity> removeObjects = new ArrayList<Entity>(evt.getRemoveObjects()); for (Entity entity: storeObjects) { addStoreOperationsToClosure(evt, store,entity); } for (Entity entity: storeObjects) { // update old classifiables, that may not been update before via a change event // that could be the case if an old reservation is restored via undo but the dynamic type changed in between. // The undo cache does not notice the change in type if ( entity instanceof Classifiable && entity instanceof Timestamp) { Date lastChanged = ((Timestamp) entity).getLastChanged(); ClassificationImpl classification = (ClassificationImpl) ((Classifiable) entity).getClassification(); DynamicTypeImpl dynamicType = classification.getType(); Date typeLastChanged = dynamicType.getLastChanged(); if ( typeLastChanged != null && lastChanged != null && typeLastChanged.after( lastChanged)) { if (classification.needsChange(dynamicType)) { addChangedDependencies(evt, store, dynamicType, entity, false); } } } // TODO add conversion of classification filters or other dynamictypedependent that are stored in preferences // for (PreferencePatch patch:evt.getPreferencePatches()) // { // for (String key: patch.keySet()) // { // Object object = patch.get( key); // if ( object instanceof DynamicTypeDependant) // { // // } // } // } } for (Entity object: removeObjects) { addRemoveOperationsToClosure(evt, store, object); } Set<Entity> deletedCategories = getDeletedCategories(storeObjects); for (Entity entity: deletedCategories) { evt.putRemove(entity); } } protected void addStoreOperationsToClosure(UpdateEvent evt, EntityStore store,Entity entity) throws RaplaException { if (getLogger().isDebugEnabled() && !evt.getStoreObjects().contains(entity)) { getLogger().debug("Adding " + entity + " to store closure"); } evt.putStore(entity); if (DynamicType.TYPE == entity.getRaplaType()) { DynamicTypeImpl dynamicType = (DynamicTypeImpl) entity; addChangedDynamicTypeDependant(evt,store, dynamicType, false); } } private void addRemoveOperationsToClosure(UpdateEvent evt,EntityStore store,Entity entity) throws RaplaException { if (getLogger().isDebugEnabled() && !evt.getRemoveObjects().contains(entity)) { getLogger().debug("Adding " + entity + " to remove closure"); } evt.putRemove(entity); if (DynamicType.TYPE == entity.getRaplaType()) { DynamicTypeImpl dynamicType = (DynamicTypeImpl) entity; addChangedDynamicTypeDependant(evt, store,dynamicType, true); } // If entity is a user, remove the preference object if (User.TYPE == entity.getRaplaType()) { addRemovedUserDependant(evt, store,(User) entity); } } // protected void setCache(final LocalCache cache) { // super.setCache( cache); // if ( idTable == null) // { // idTable = new IdTable(); // } // idTable.setCache(cache); // } // protected void addChangedDynamicTypeDependant(UpdateEvent evt, EntityStore store,DynamicTypeImpl type, boolean toRemove) throws RaplaException { List<Entity> referencingEntities = getReferencingEntities( type, store); Iterator<Entity>it = referencingEntities.iterator(); while (it.hasNext()) { Entity entity = it.next(); if (!(entity instanceof DynamicTypeDependant)) { continue; } DynamicTypeDependant dependant = (DynamicTypeDependant) entity; // Classifiables need update? if (!dependant.needsChange(type) && !toRemove) continue; if (getLogger().isDebugEnabled()) getLogger().debug("Classifiable " + entity + " needs change!"); // Classifiables are allready on the store list addChangedDependencies(evt, store, type, entity, toRemove); } } private void addChangedDependencies(UpdateEvent evt,EntityStore store, DynamicTypeImpl type, Entity entity,boolean toRemove) throws EntityNotFoundException, RaplaException { DynamicTypeDependant dependant; if (evt.getStoreObjects().contains(entity)) { dependant = (DynamicTypeDependant) evt.findEntity(entity); } else { // no, then create a clone of the classfiable object and add to list User user = null; if (evt.getUserId() != null) { user = resolve(cache,evt.getUserId(), User.class); } @SuppressWarnings("unchecked") Class<Entity> entityType = entity.getRaplaType().getTypeClass(); Entity persistant = store.tryResolve(entity.getId(), entityType); dependant = (DynamicTypeDependant) editObject( entity, persistant, user); // replace or add the modified entity addStoreOperationsToClosure(evt, store,(Entity) dependant); } if (toRemove) { try { dependant.commitRemove(type); } catch (CannotExistWithoutTypeException ex) { // getLogger().warn(ex.getMessage(),ex); } } else { dependant.commitChange(type); } } protected void addRemovedUserDependant(UpdateEvent evt, EntityStore store,User user) throws RaplaException { PreferencesImpl preferences = cache.getPreferencesForUserId(user.getId()); if (preferences != null) { evt.putRemove(preferences); } List<Entity>referencingEntities = getReferencingEntities( user, store); Iterator<Entity>it = referencingEntities.iterator(); while (it.hasNext()) { Entity entity = it.next(); // Remove internal resources automatically if the owner is deleted if ( entity instanceof Classifiable && entity instanceof Ownable) { DynamicType type = ((Classifiable) entity).getClassification().getType(); if (((DynamicTypeImpl)type).isInternal()) { User owner = ((Ownable)entity).getOwner(); if ( owner != null && owner.equals( user)) { evt.putRemove( entity); continue; } } } if (entity instanceof Timestamp) { Timestamp timestamp = (Timestamp) entity; User lastChangedBy = timestamp.getLastChangedBy(); if ( lastChangedBy == null || !lastChangedBy.equals( user) ) { continue; } if ( entity instanceof Ownable ) { User owner = ((Ownable)entity).getOwner(); // we do nothing if the user is also owner, that dependencies need to be resolved manually if ( owner != null && owner.equals(user)) { continue; } } if (evt.getStoreObjects().contains(entity)) { ((SimpleEntity)evt.findEntity(entity)).setLastChangedBy(null); } else { @SuppressWarnings("unchecked") Class<? extends Entity> typeClass = entity.getRaplaType().getTypeClass(); Entity persistant= cache.tryResolve( entity.getId(), typeClass); Entity dependant = editObject( entity, persistant, user); ((SimpleEntity)dependant).setLastChangedBy( null ); addStoreOperationsToClosure(evt, store, dependant); } } } } /** * returns all entities that depend one the passed entities. In most cases * one object depends on an other object if it has a reference to it. * * @param entity */ final protected Set<Entity> getDependencies(Entity entity, EntityStore store) { RaplaType type = entity.getRaplaType(); final Collection<Entity>referencingEntities; if (Category.TYPE == type || DynamicType.TYPE == type || Allocatable.TYPE == type || User.TYPE == type) { HashSet<Entity> dependencyList = new HashSet<Entity>(); referencingEntities = getReferencingEntities(entity, store); dependencyList.addAll(referencingEntities); return dependencyList; } return Collections.emptySet(); } protected List<Entity> getReferencingEntities(Entity entity, EntityStore store) { List<Entity> result = new ArrayList<Entity>(); addReferers(cache.getReservations(), entity, result); addReferers(cache.getAllocatables(), entity, result); addReferers(cache.getUsers(), entity, result); addReferers(cache.getDynamicTypes(), entity, result); Iterable<Preferences> preferenceList = getPreferences(store); addReferers(preferenceList, entity, result); return result; } private Iterable<Preferences> getPreferences(EntityStore store) { List<Preferences> preferenceList = new ArrayList<Preferences>(); for ( User user:cache.getUsers()) { PreferencesImpl preferences = cache.getPreferencesForUserId( user.getId() ); if ( preferences != null) { preferenceList.add( preferences); } } PreferencesImpl systemPreferences = cache.getPreferencesForUserId( null); if ( systemPreferences != null) { preferenceList.add( systemPreferences ); } return preferenceList; } private void addReferers(Iterable<? extends Entity> refererList,Entity object, List<Entity> result) { for ( Entity referer: refererList) { if (referer != null && !referer.isIdentical(object) ) { for (ReferenceInfo info:((EntityReferencer)referer).getReferenceInfo()) { if (info.isReferenceOf(object) ) { result.add(referer); } } } } } private int countDynamicTypes(Collection<? extends RaplaObject> entities, String classificationType) throws RaplaException { Iterator<? extends RaplaObject> it = entities.iterator(); int count = 0; while (it.hasNext()) { RaplaObject entity = it.next(); if (DynamicType.TYPE != entity.getRaplaType()) continue; DynamicType type = (DynamicType) entity; String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); if ( annotation == null) { throw new RaplaException(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE + " not set for " + type); } if (annotation.equals( classificationType)) { count++; } } return count; } // Count dynamic-types to ensure that there is least one dynamic type left private void checkDynamicType(Collection<Entity>entities, String[] classificationTypes) throws RaplaException { int count = 0; for ( String classificationType: classificationTypes) { count += countDynamicTypes(entities, classificationType); } Collection<? extends DynamicType> allTypes = cache.getDynamicTypes(); int countAll = 0; for ( String classificationType: classificationTypes) { countAll = countDynamicTypes(allTypes, classificationType); } if (count >= 0 && count >= countAll) { throw new RaplaException(i18n.getString("error.one_type_requiered")); } } /** * Check if the references of each entity refers to an object in cache or in * the passed collection. */ final protected void checkReferences(UpdateEvent evt, EntityStore store) throws RaplaException { for (EntityReferencer entity: evt.getEntityReferences(false)) { for (ReferenceInfo info: entity.getReferenceInfo()) { String id = info.getId(); // Reference in cache or store? if (store.tryResolve(id, info.getType()) != null) continue; throw new EntityNotFoundException(i18n.format("error.reference_not_stored", info.getType() + ":" + id)); } } } /** * check if we find an object with the same name. If a different object * (different id) with the same unique attributes is found a * UniqueKeyException will be thrown. */ final protected void checkUnique(final UpdateEvent evt, final EntityStore store) throws RaplaException { for (Entity entity : evt.getStoreObjects()) { String name = ""; Entity entity2 = null; if (DynamicType.TYPE == entity.getRaplaType()) { DynamicType type = (DynamicType) entity; name = type.getKey(); entity2 = (Entity) store.getDynamicType(name); if (entity2 != null && !entity2.equals(entity)) throwNotUnique(name); } if (Category.TYPE == entity.getRaplaType()) { Category category = (Category) entity; Category[] categories = category.getCategories(); for (int i = 0; i < categories.length; i++) { String key = categories[i].getKey(); for (int j = i + 1; j < categories.length; j++) { String key2 = categories[j].getKey(); if (key == key2 || (key != null && key.equals(key2)) ) { throwNotUnique(key); } } } } if (User.TYPE == entity.getRaplaType()) { name = ((User) entity).getUsername(); if (name == null || name.trim().length() == 0) { String message = i18n.format("error.no_entry_for", getString("username")); throw new RaplaException(message); } // FIXME Replace with store.getUser for the rare case that two users with the same username are stored in one operation entity2 = cache.getUser(name); if (entity2 != null && !entity2.equals(entity)) throwNotUnique(name); } } } private void throwNotUnique(String name) throws UniqueKeyException { throw new UniqueKeyException(i18n.format("error.not_unique", name)); } /** * compares the version of the cached entities with the versions of the new * entities. Throws an Exception if the newVersion != cachedVersion */ protected void checkVersions(Collection<Entity>entities) throws RaplaException { for (Entity entity: entities) { // Check Versions Entity persistantVersion = findPersistant(entity); // If the entities are newer, everything is o.k. if (persistantVersion != null && persistantVersion != entity) { if (( persistantVersion instanceof Timestamp)) { Date lastChangeTimePersistant = ((Timestamp)persistantVersion).getLastChanged(); Date lastChangeTime = ((Timestamp)entity).getLastChanged(); if ( lastChangeTimePersistant != null && lastChangeTime != null && lastChangeTimePersistant.after( lastChangeTime) ) { getLogger().warn( "There is a newer version for: " + entity.getId() + " stored version :" + SerializableDateTimeFormat.INSTANCE.formatTimestamp(lastChangeTimePersistant) + " version to store :" + SerializableDateTimeFormat.INSTANCE.formatTimestamp(lastChangeTime)); throw new RaplaNewVersionException(getI18n().format( "error.new_version", entity.toString())); } } } } } /** Check if the objects are consistent, so that they can be safely stored. */ protected void checkConsistency(UpdateEvent evt, EntityStore store) throws RaplaException { for (EntityReferencer referencer : evt.getEntityReferences(false)) { for (ReferenceInfo referenceInfo:referencer.getReferenceInfo()) { Entity reference = store.resolve( referenceInfo.getId(), referenceInfo.getType()); if (reference instanceof Preferences || reference instanceof Conflict || reference instanceof Reservation || reference instanceof Appointment ) { throw new RaplaException("The current version of Rapla doesn't allow references to objects of type " + reference.getRaplaType()); } } } for (Entity entity : evt.getStoreObjects()) { CategoryImpl superCategory = store.getSuperCategory(); if (Category.TYPE == entity.getRaplaType()) { if (entity.equals(superCategory)) { // Check if the user group is missing Category userGroups = ((Category) entity).getCategory(Permission.GROUP_CATEGORY_KEY); if (userGroups == null) { throw new RaplaException("The category with the key '" + Permission.GROUP_CATEGORY_KEY + "' is missing."); } } else { // check if the category to be stored has a parent Category category = (Category) entity; Category parent = category.getParent(); if (parent == null) { throw new RaplaException("The category " + category + " needs a parent."); } else { int i = 0; while ( true) { if ( parent == null) { throw new RaplaException("Category needs to be a child of super category."); } else if ( parent.equals( superCategory)) { break; } parent = parent.getParent(); i++; if ( i>80) { throw new RaplaException("infinite recursion detection for category " + category); } } } } } } } protected void checkNoDependencies(final UpdateEvent evt, final EntityStore store) throws RaplaException { Collection<Entity> removeEntities = evt.getRemoveObjects(); Collection<Entity> storeObjects = new HashSet<Entity>(evt.getStoreObjects()); HashSet<Entity> dep = new HashSet<Entity>(); Set<Entity> deletedCategories = getDeletedCategories(storeObjects); IteratorChain<Entity> iteratorChain = new IteratorChain<Entity>( deletedCategories,removeEntities); for (Entity entity : iteratorChain) { // First we add the dependencies from the stored object list for (Entity obj : storeObjects) { if ( obj instanceof EntityReferencer) { if (isRefering((EntityReferencer)obj, entity )) { dep.add(obj); } } } // we check if the user deletes himself if ( entity instanceof User) { String eventUserId = evt.getUserId(); if (eventUserId != null && eventUserId.equals( entity.getId())) { List<String> emptyList = Collections.emptyList(); throw new DependencyException("User can't delete himself", emptyList); } } // Than we add the dependencies from the cache. It is important that // we don't add the dependencies from the stored object list here, // because a dependency could be removed in a stored object Set<Entity> dependencies = getDependencies(entity, store); for (Entity dependency : dependencies) { if (!storeObjects.contains(dependency) && !removeEntities.contains( dependency)) { // only add the first 21 dependencies; if (dep.size() > MAX_DEPENDENCY ) { break; } dep.add(dependency); } } } // CKO We skip this check as the admin should have the possibility to deny a user read to allocatables objects even if he has reserved it prior // for (Entity entity : storeObjects) { // if ( entity.getRaplaType() == Allocatable.TYPE) // { // Allocatable alloc = (Allocatable) entity; // for (Entity reference:getDependencies(entity)) // { // if ( reference instanceof Ownable) // { // User user = ((Ownable) reference).getOwner(); // if (user != null && !alloc.canReadOnlyInformation(user)) // { // throw new DependencyException( "User " + user.getUsername() + " refers to " + getName(alloc) + ". Read permission is required.", Collections.singleton( getDependentName(reference))); // } // } // } // } // } if (dep.size() > 0) { Collection<String> names = new ArrayList<String>(); for (Entity obj: dep) { String string = getDependentName(obj); names.add(string); } throw new DependencyException(getString("error.dependencies"),names.toArray( new String[]{})); } // Count dynamic-types to ensure that there is least one dynamic type // for reservations and one for resources or persons checkDynamicType(removeEntities, new String[] {DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION}); checkDynamicType(removeEntities, new String[] {DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE,DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON}); } private boolean isRefering(EntityReferencer referencer, Entity entity) { for (ReferenceInfo info : referencer.getReferenceInfo()) { if ( info.isReferenceOf(entity)) { return true; } } return false; } private Set<Entity> getDeletedCategories(Iterable<Entity> storeObjects) { Set<Entity> deletedCategories = new HashSet<Entity>(); for (Entity entity : storeObjects) { if ( entity.getRaplaType() == Category.TYPE) { Category newCat = (Category) entity; Category old = tryResolve(entity.getId(), Category.class); if ( old != null) { Set<Category> oldSet = getAllCategories( old); Set<Category> newSet = getAllCategories( newCat); oldSet.removeAll( newSet); deletedCategories.addAll( oldSet ); } } } return deletedCategories; } private Set<Category> getAllCategories(Category old) { HashSet<Category> result = new HashSet<Category>(); result.add( old); for (Category child : old.getCategories()) { result.addAll( getAllCategories(child)); } return result; } protected String getDependentName(Entity obj) { StringBuffer buf = new StringBuffer(); if (obj instanceof Reservation) { buf.append(getString("reservation")); } else if (obj instanceof Preferences) { buf.append(getString("preferences")); } else if (obj instanceof Category) { buf.append(getString("categorie")); } else if (obj instanceof Allocatable) { buf.append(getString("resources_persons")); } else if (obj instanceof User) { buf.append(getString("user")); } else if (obj instanceof DynamicType) { buf.append(getString("dynamictype")); } if (obj instanceof Named) { Locale locale = i18n.getLocale(); final String string = ((Named) obj).getName(locale); buf.append(": " + string); } else { buf.append(obj.toString()); } if (obj instanceof Reservation) { Reservation reservation = (Reservation)obj; Appointment[] appointments = reservation.getAppointments(); if ( appointments.length > 0) { buf.append(" "); Date start = appointments[0].getStart(); buf.append(raplaLocale.formatDate(start)); } String template = reservation.getAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE); if ( template != null) { buf.append(" in template " + template); } } final Object idFull = obj.getId(); if (idFull != null) { String idShort = idFull.toString(); int dot = idShort.lastIndexOf('.'); buf.append(" (" + idShort.substring(dot + 1) + ")"); } String string = buf.toString(); return string; } private void storeUser(User refUser) throws RaplaException { ArrayList<Entity> arrayList = new ArrayList<Entity>(); arrayList.add(refUser); Collection<Entity> storeObjects = arrayList; Collection<Entity> removeObjects = Collections.emptySet(); storeAndRemove(storeObjects, removeObjects, null); } protected String encrypt(String encryption, String password) throws RaplaException { MessageDigest md; try { md = MessageDigest.getInstance(encryption); } catch (NoSuchAlgorithmException ex) { throw new RaplaException(ex); } synchronized (md) { md.reset(); md.update(password.getBytes()); return encryption + ":" + Tools.convert(md.digest()); } } private boolean checkPassword(String userId, String password) throws RaplaException { if (userId == null) return false; String correct_pw = cache.getPassword(userId); if (correct_pw == null) { return false; } if (correct_pw.equals(password)) { return true; } int columIndex = correct_pw.indexOf(":"); if (columIndex > 0 && correct_pw.length() > 20) { String encryptionGuess = correct_pw.substring(0, columIndex); if (encryptionGuess.contains("sha") || encryptionGuess.contains("md5")) { password = encrypt(encryptionGuess, password); if (correct_pw.equals(password)) { return true; } } } return false; } @Override public Map<Allocatable,Collection<Appointment>> getFirstAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException { Lock readLock = readLock(); Map<Allocatable, Map<Appointment, Collection<Appointment>>> allocatableBindings; try { allocatableBindings = getAllocatableBindings(allocatables, appointments, ignoreList,true); } finally { unlock( readLock); } Map<Allocatable, Collection<Appointment>> map = new HashMap<Allocatable, Collection<Appointment>>(); for ( Map.Entry<Allocatable, Map<Appointment, Collection<Appointment>>> entry: allocatableBindings.entrySet()) { Allocatable alloc = entry.getKey(); Collection<Appointment> list = entry.getValue().keySet(); map.put( alloc, list); } return map; } @Override public Map<Allocatable, Map<Appointment,Collection<Appointment>>> getAllAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException { Lock readLock = readLock(); try { return getAllocatableBindings( allocatables, appointments, ignoreList, false); } finally { unlock( readLock ); } } public Map<Allocatable, Map<Appointment,Collection<Appointment>>> getAllocatableBindings(Collection<Allocatable> allocatables,Collection<Appointment> appointments, Collection<Reservation> ignoreList, boolean onlyFirstConflictingAppointment) { Map<Allocatable, Map<Appointment,Collection<Appointment>>> map = new HashMap<Allocatable, Map<Appointment,Collection<Appointment>>>(); for ( Allocatable allocatable:allocatables) { String annotation = allocatable.getAnnotation( ResourceAnnotations.KEY_CONFLICT_CREATION); boolean holdBackConflicts = annotation != null && annotation.equals( ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE); if ( holdBackConflicts) { continue; } SortedSet<Appointment> appointmentSet = getAppointments( allocatable); if ( appointmentSet == null) { continue; } map.put(allocatable, new HashMap<Appointment,Collection<Appointment>>() ); for (Appointment appointment:appointments) { Set<Appointment> conflictingAppointments = AppointmentImpl.getConflictingAppointments(appointmentSet, appointment, ignoreList, onlyFirstConflictingAppointment); if ( conflictingAppointments.size() > 0) { Map<Appointment,Collection<Appointment>> appMap = map.get( allocatable); if ( appMap == null) { appMap = new HashMap<Appointment, Collection<Appointment>>(); map.put( allocatable, appMap); } appMap.put( appointment, conflictingAppointments); } } } return map; } @Override public Date getNextAllocatableDate(Collection<Allocatable> allocatables,Appointment appointment,Collection<Reservation> ignoreList,Integer worktimeStartMinutes,Integer worktimeEndMinutes, Integer[] excludedDays, Integer rowsPerHour) throws RaplaException { Lock readLock = readLock(); try { Appointment newState = appointment; Date firstStart = appointment.getStart(); boolean startDateExcluded = isExcluded(excludedDays, firstStart); boolean wholeDay = appointment.isWholeDaysSet(); boolean inWorktime = inWorktime(appointment, worktimeStartMinutes,worktimeEndMinutes); if ( rowsPerHour == null || rowsPerHour <=1) { rowsPerHour = 1; } for ( int i=0;i<366*24 *rowsPerHour ;i++) { newState = ((AppointmentImpl) newState).clone(); Date start = newState.getStart(); long millisToAdd = wholeDay ? DateTools.MILLISECONDS_PER_DAY : (DateTools.MILLISECONDS_PER_HOUR / rowsPerHour ); Date newStart = new Date(start.getTime() + millisToAdd); if (!startDateExcluded && isExcluded(excludedDays, newStart)) { continue; } newState.move( newStart ); if ( !wholeDay && inWorktime && !inWorktime(newState, worktimeStartMinutes, worktimeEndMinutes)) { continue; } if (!isAllocated(allocatables, newState, ignoreList)) { return newStart; } } return null; } finally { unlock( readLock ); } } private boolean inWorktime(Appointment appointment, Integer worktimeStartMinutes, Integer worktimeEndMinutes) { long start = appointment.getStart().getTime(); int minuteOfDayStart = DateTools.getMinuteOfDay( start ); long end = appointment.getEnd().getTime(); int minuteOfDayEnd = DateTools.getMinuteOfDay( end ) + (int) DateTools.countDays(start, end) * 24 * 60; boolean inWorktime = (worktimeStartMinutes == null || worktimeStartMinutes<= minuteOfDayStart) && ( worktimeEndMinutes == null || worktimeEndMinutes >= minuteOfDayEnd); return inWorktime; } private boolean isExcluded(Integer[] excludedDays, Date date) { Integer weekday = DateTools.getWeekday( date); if (excludedDays != null) { for ( Integer day:excludedDays) { if ( day.equals( weekday)) { return true; } } } return false; } private boolean isAllocated(Collection<Allocatable> allocatables, Appointment appointment, Collection<Reservation> ignoreList) throws RaplaException { Map<Allocatable, Collection<Appointment>> firstAllocatableBindings = getFirstAllocatableBindings(allocatables, Collections.singleton( appointment) , ignoreList); for (Map.Entry<Allocatable, Collection<Appointment>> entry: firstAllocatableBindings.entrySet()) { if (entry.getValue().size() > 0) { return true; } } return false; } public Collection<Entity> getVisibleEntities(final User user)throws RaplaException { Lock readLock = readLock(); try { return cache.getVisibleEntities(user); } finally { unlock(readLock); } } // this check is only there to detect rapla bugs in the conflict api and can be removed if it causes performance issues private void checkAbandonedAppointments() { Collection<? extends Allocatable> allocatables = cache.getAllocatables(); Logger logger = getLogger().getChildLogger("appointmentcheck"); try { for ( Allocatable allocatable:allocatables) { SortedSet<Appointment> appointmentSet = this.appointmentMap.get( allocatable.getId()); if ( appointmentSet == null) { continue; } for (Appointment app:appointmentSet) { { SimpleEntity original = (SimpleEntity)app; String id = original.getId(); if ( id == null ) { logger.error( "Empty id for " + original); continue; } Appointment persistant = cache.tryResolve( id, Appointment.class ); if ( persistant == null ) { logger.error( "appointment not stored in cache " + original ); continue; } } Reservation reservation = app.getReservation(); if (reservation == null) { logger.error("Appointment without a reservation stored in cache " + app ); appointmentSet.remove( app); continue; } else if (!reservation.hasAllocated( allocatable, app)) { logger.error("Allocation is not stored correctly for " + reservation + " " + app + " " + allocatable + " removing binding for " + app); appointmentSet.remove( app); continue; } else { { Reservation original = reservation; String id = original.getId(); if ( id == null ) { logger.error( "Empty id for " + original); continue; } Reservation persistant = cache.tryResolve( id, Reservation.class ); if ( persistant != null ) { Date lastChanged = original.getLastChanged(); Date persistantLastChanged = persistant.getLastChanged(); if (persistantLastChanged != null && !persistantLastChanged.equals(lastChanged)) { logger.error( "Reservation stored in cache is not the same as in allocation store " + original ); continue; } } else { logger.error( "Reservation not stored in cache " + original + " removing binding for " + app); appointmentSet.remove( app); continue; } } } } } } catch (Exception ex) { logger.error(ex.getMessage(), ex); } } protected void createDefaultSystem(LocalCache cache) throws RaplaException { EntityStore store = new EntityStore( null, cache.getSuperCategory() ); DynamicTypeImpl resourceType = newDynamicType(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE,"resource"); setName(resourceType.getName(), "resource"); add(store, resourceType); DynamicTypeImpl personType = newDynamicType(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON,"person"); setName(personType.getName(), "person"); add(store, personType); DynamicTypeImpl eventType = newDynamicType(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION, "event"); setName(eventType.getName(), "event"); add(store, eventType); String[] userGroups = new String[] {Permission.GROUP_REGISTERER_KEY, Permission.GROUP_MODIFY_PREFERENCES_KEY,Permission.GROUP_CAN_READ_EVENTS_FROM_OTHERS, Permission.GROUP_CAN_CREATE_EVENTS, Permission.GROUP_CAN_EDIT_TEMPLATES}; Date now = getCurrentTimestamp(); CategoryImpl groupsCategory = new CategoryImpl(now,now); groupsCategory.setKey("user-groups"); setName( groupsCategory.getName(), groupsCategory.getKey()); setNew( groupsCategory); store.put( groupsCategory); for ( String catName: userGroups) { CategoryImpl group = new CategoryImpl(now,now); group.setKey( catName); setNew(group); setName( group.getName(), group.getKey()); groupsCategory.addCategory( group); store.put( group); } cache.getSuperCategory().addCategory( groupsCategory); UserImpl admin = new UserImpl(now,now); admin.setUsername("admin"); admin.setAdmin( true); setNew(admin); store.put( admin); Collection<Entity> list = store.getList(); cache.putAll( list ); testResolve( list); setResolver( list); UserImpl user = cache.getUser("admin"); String password =""; cache.putPassword( user.getId(), password ); cache.getSuperCategory().setReadOnly(); AllocatableImpl allocatable = new AllocatableImpl(now, now); allocatable.setResolver( this); allocatable.addPermission(allocatable.newPermission()); Classification classification = cache.getDynamicType("resource").newClassification(); allocatable.setClassification(classification); setNew(allocatable); classification.setValue("name", getString("test_resource")); allocatable.setOwner( user); cache.put( allocatable); } private void add(EntityStore list, DynamicTypeImpl type) { list.put( type); for (Attribute att:type.getAttributes()) { list.put((Entity) att); } } private Attribute createStringAttribute(String key, String name) throws RaplaException { Attribute attribute = newAttribute(AttributeType.STRING, null); attribute.setKey(key); setName(attribute.getName(), name); return attribute; } private void addAttributeWithInternalId(DynamicType dynamicType,String key, AttributeType type) throws RaplaException { String id = "rapla_"+ dynamicType.getKey() + "_" +key; Attribute attribute = newAttribute(type, id); attribute.setKey(key); setName(attribute.getName(), key); dynamicType.addAttribute( attribute); } private DynamicTypeImpl newDynamicType(String classificationType, String key) throws RaplaException { DynamicTypeImpl dynamicType = new DynamicTypeImpl(); dynamicType.setAnnotation("classification-type", classificationType); dynamicType.setKey(key); setNew(dynamicType); if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE)) { dynamicType.addAttribute(createStringAttribute("name", "name")); dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}"); dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS,"automatic"); } else if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)) { dynamicType.addAttribute(createStringAttribute("name","eventname")); dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}"); dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS, null); } else if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON)) { dynamicType.addAttribute(createStringAttribute("surname", "surname")); dynamicType.addAttribute(createStringAttribute("firstname", "firstname")); dynamicType.addAttribute(createStringAttribute("email", "email")); dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT, "{surname} {firstname}"); dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS, null); } dynamicType.setResolver( this); return dynamicType; } private Attribute newAttribute(AttributeType attributeType,String id) throws RaplaException { AttributeImpl attribute = new AttributeImpl(attributeType); if ( id == null) { setNew(attribute); } else { ((RefEntity)attribute).setId(id); } attribute.setResolver( this); return attribute; } private <T extends Entity> void setNew(T entity) throws RaplaException { RaplaType raplaType = entity.getRaplaType(); String id = createIdentifier(raplaType,1)[0]; ((RefEntity)entity).setId(id); } private void setName(MultiLanguageName name, String to) { String currentLang = i18n.getLang(); name.setName("en", to); try { String translation = i18n.getString( to); name.setName(currentLang, translation); } catch (Exception ex) { } } }
04900db4-rob
src/org/rapla/storage/impl/server/LocalAbstractCachableOperator.java
Java
gpl3
72,785
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.impl.server; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.rapla.components.util.DateTools; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.AppointmentBlockEndComparator; import org.rapla.entities.domain.AppointmentBlockStartComparator; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.ResourceAnnotations; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.storage.EntityResolver; import org.rapla.facade.Conflict; import org.rapla.facade.RaplaComponent; import org.rapla.facade.internal.ConflictImpl; import org.rapla.framework.logger.Logger; import org.rapla.storage.UpdateResult; import org.rapla.storage.UpdateResult.Change; class ConflictFinder { AllocationMap allocationMap; Map<Allocatable,Set<Conflict>> conflictMap; Logger logger; EntityResolver resolver; public ConflictFinder( AllocationMap allocationMap, Date today, Logger logger, EntityResolver resolver) { this.logger = logger; this.allocationMap = allocationMap; conflictMap = new HashMap<Allocatable, Set<Conflict>>(); long startTime = System.currentTimeMillis(); int conflictSize = 0; for (Allocatable allocatable:allocationMap.getAllocatables()) { Set<Conflict> conflictList = Collections.emptySet(); Set<Conflict> newConflicts = updateConflicts(allocatable, null, today, conflictList); conflictMap.put( allocatable, newConflicts); conflictSize+= newConflicts.size(); } logger.info("Conflict initialization found " + conflictSize + " conflicts and took " + (System.currentTimeMillis()- startTime) + "ms. " ); this.resolver = resolver; } private Set<Conflict> updateConflicts(Allocatable allocatable,AllocationChange change, Date today, Set<Conflict> oldList ) { if ( isConflictIgnored(allocatable)) { return Collections.emptySet(); } Set<Appointment> allAppointments = allocationMap.getAppointments(allocatable); Set<Appointment> changedAppointments; Set<Appointment> removedAppointments; if ( change == null) { changedAppointments = allAppointments; removedAppointments = new TreeSet<Appointment>(); } else { changedAppointments = change.toChange; removedAppointments = change.toRemove; } Set<String> foundConflictIds = new HashSet<String>(); Set<Conflict> conflictList = new HashSet<Conflict>( );//conflictMap.get(allocatable); { Set<String> idList1 = getIds( removedAppointments); Set<String> idList2 = getIds( changedAppointments); for ( Conflict conflict:oldList) { if (endsBefore(conflict, today) || contains(conflict, idList1) || contains(conflict, idList2)) { continue; } conflictList.add( conflict ); } } { SortedSet<AppointmentBlock> allAppointmentBlocksSortedByStartDescending = null;//new TreeSet<AppointmentBlock>(new InverseComparator<AppointmentBlock>(new AppointmentBlockStartComparator())); SortedSet<AppointmentBlock> allAppointmentBlocks = createBlocks(today,allAppointments, new AppointmentBlockEndComparator(), allAppointmentBlocksSortedByStartDescending); SortedSet<AppointmentBlock> appointmentBlocks = createBlocks(today,changedAppointments, new AppointmentBlockStartComparator(), null); // Check the conflicts for each time block for (AppointmentBlock appBlock:appointmentBlocks) { final Appointment appointment1 = appBlock.getAppointment(); long start = appBlock.getStart(); long end = appBlock.getEnd(); /* * Shrink the set of all time blocks down to those with a start date which is * later than or equal to the start date of the block */ AppointmentBlock compareBlock = new AppointmentBlock(start, start, appointment1,false); final SortedSet<AppointmentBlock> tailSet = allAppointmentBlocks.tailSet(compareBlock); // Check all time blocks which start after or at the same time as the block which is being checked for (AppointmentBlock appBlock2:tailSet) { // If the start date of the compared block is after the end date of the block, skip the appointment if (appBlock2.getStart() > end) { break; } final Appointment appointment2 = appBlock2.getAppointment(); // we test that in the next step if ( appBlock == appBlock2 || appBlock2.includes( appBlock) || appointment1.equals( appointment2) ) { continue; } // Check if the corresponding appointments of both blocks overlap each other if (!appointment2.equals( appointment1) && appointment2.overlaps(appointment1)) { String id = ConflictImpl.createId(allocatable.getId(), appointment1.getId(), appointment2.getId()); if ( foundConflictIds.contains(id )) { continue; } // Add appointments to conflict list if (ConflictImpl.isConflictWithoutCheck(appointment1, appointment2, today)) { final ConflictImpl conflict = new ConflictImpl(allocatable,appointment1, appointment2, today, id); conflictList.add(conflict); foundConflictIds.add( id); } } } // we now need to check overlaps with appointments that start before and end after the appointment //AppointmentBlock compareBlock2 = new AppointmentBlock(end, end, appointment1,false); //SortedSet<AppointmentBlock> descending = allAppointmentBlocksSortedByStartDescending.tailSet(compareBlock); for (AppointmentBlock appBlock2:tailSet) { final Appointment appointment2 = appBlock2.getAppointment(); if ( appBlock == appBlock2 || !appBlock2.includes( appBlock) || appointment2.equals( appointment1) ) { continue; } String id = ConflictImpl.createId(allocatable.getId(), appointment1.getId(), appointment2.getId()); if ( foundConflictIds.contains(id )) { continue; } if (ConflictImpl.isConflictWithoutCheck(appointment1, appointment2, today)) { final ConflictImpl conflict = new ConflictImpl(allocatable,appointment1, appointment2, today, id); conflictList.add(conflict); foundConflictIds.add( id); } } } } if ( conflictList.isEmpty()) { return Collections.emptySet(); } return conflictList; } public Set<String> getIds(Collection<? extends Entity> list) { if ( list.isEmpty()) { return Collections.emptySet(); } Set<String> idList = new HashSet<String>(); for ( Entity entity:list) { idList.add( entity.getId()); } return idList; } private boolean isConflictIgnored(Allocatable allocatable) { String annotation = allocatable.getAnnotation(ResourceAnnotations.KEY_CONFLICT_CREATION); if ( annotation != null && annotation.equals(ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE)) { return true; } return false; } private boolean contains(Conflict conflict, Set<String> idList) { String appointment1 = conflict.getAppointment1(); String appointment2 = conflict.getAppointment2(); return( idList.contains( appointment1) || idList.contains( appointment2)); } private SortedSet<AppointmentBlock> createBlocks(Date today, Set<Appointment> appointmentSet,final Comparator<AppointmentBlock> comparator, SortedSet<AppointmentBlock> additionalSet) { // overlaps will be checked 260 weeks (5 years) from now on long maxCheck = System.currentTimeMillis() + DateTools.MILLISECONDS_PER_WEEK * 260; // Create a new set of time blocks, ordered by their start dates SortedSet<AppointmentBlock> allAppointmentBlocks = new TreeSet<AppointmentBlock>(comparator); if ( appointmentSet.isEmpty()) { return allAppointmentBlocks; } //Appointment last = appointmentSet.last(); // Get all time blocks of all appointments for (Appointment appointment:appointmentSet) { // Get the end date of the appointment (if repeating, end date of last occurence) Date maxEnd = appointment.getMaxEnd(); // Check if the appointment is repeating forever if ( maxEnd == null || maxEnd.getTime() > maxCheck) { // If the repeating has no end, set the end to the start of the last appointment in the set + 100 weeks (~2 years) maxEnd = new Date(maxCheck); } if ( maxEnd.before( today)) { continue; } if ( RaplaComponent.isTemplate(appointment.getReservation())) { continue; } Reservation r1 = appointment.getReservation(); DynamicType type1 = r1 != null ? r1.getClassification().getType() : null; String annotation1 = ConflictImpl.getConflictAnnotation( type1); if ( ConflictImpl.isNoConflicts( annotation1 ) ) { continue; } /* * If the appointment has a repeating, get all single time blocks of it. If it is no * repeating, this will just create one block, which is equal to the appointment * itself. */ Date start = appointment.getStart(); if ( start.before( today)) { start = today; } ((AppointmentImpl)appointment).createBlocks(start, DateTools.fillDate(maxEnd), allAppointmentBlocks,additionalSet); } return allAppointmentBlocks; } /** * Determines all conflicts which occur after a given start date. * if user is passed then only returns conflicts the user can modify * * @param allocatables */ public Collection<Conflict> getConflicts( User user) { Collection<Conflict> conflictList = new HashSet<Conflict>(); for ( Allocatable allocatable: conflictMap.keySet()) { Set<Conflict> set = conflictMap.get( allocatable); if ( set != null) { for ( Conflict conflict: set) { if (ConflictImpl.canModify(conflict,user,resolver)) { conflictList.add(conflict); } } } } return conflictList; } private boolean endsBefore(Conflict conflict,Date date ) { Appointment appointment1 = getAppointment( conflict.getAppointment1()); Appointment appointment2 = getAppointment( conflict.getAppointment2()); if ( appointment1 == null || appointment2 == null) { return false; } boolean result = ConflictImpl.endsBefore( appointment1, appointment2, date); return result; } private Appointment getAppointment(String id) { return resolver.tryResolve(id, Appointment.class); } public void updateConflicts(Map<Allocatable, AllocationChange> toUpdate,UpdateResult evt, Date today,Collection<Allocatable> removedAllocatables) { Iterator<Change> it = evt.getOperations(UpdateResult.Change.class); while (it.hasNext()) { Change next = it.next(); RaplaObject current = next.getNew(); if ( current.getRaplaType() == Allocatable.TYPE) { Allocatable old = (Allocatable) next.getOld(); Allocatable newAlloc = (Allocatable) next.getNew(); if ( old != null && newAlloc != null ) { if (isConflictIgnored(old) != isConflictIgnored(newAlloc)) { // add an recalculate all if holdbackconflicts changed toUpdate.put( newAlloc, null); } } } } for ( Allocatable alloc: removedAllocatables) { Set<Conflict> sortedSet = conflictMap.get( alloc); if ( sortedSet != null && !sortedSet.isEmpty()) { logger.error("Removing non empty conflict map for resource " + alloc + " Appointments:" + sortedSet); } conflictMap.remove( alloc); } Set<Conflict> added = new HashSet<Conflict>(); // this will recalculate the conflicts for that resource and the changed appointments for ( Map.Entry<Allocatable, AllocationChange> entry:toUpdate.entrySet()) { Allocatable allocatable = entry.getKey(); AllocationChange changedAppointments = entry.getValue(); if ( changedAppointments == null) { conflictMap.remove( allocatable); } Set<Conflict> conflictListBefore = conflictMap.get(allocatable); if ( conflictListBefore == null) { conflictListBefore = new LinkedHashSet<Conflict>(); } Set<Conflict> conflictListAfter = updateConflicts( allocatable, changedAppointments, today, conflictListBefore); conflictMap.put( allocatable, conflictListAfter); //User user = evt.getUser(); for ( Conflict conflict: conflictListBefore) { boolean isRemoved = !conflictListAfter.contains(conflict); if ( isRemoved ) { evt.addOperation( new UpdateResult.Remove(conflict)); } } for ( Conflict conflict: conflictListAfter) { boolean isNew = !conflictListBefore.contains(conflict); if ( isNew ) { evt.addOperation( new UpdateResult.Add(conflict)); added.add( conflict); } } } // so now we have the new conflicts, but what if a reservation or appointment changed without affecting the allocation but still // the conflict is still the same but the name could change, so we must somehow indicate the clients displaying that conflict, that they need to refresh the name, // because the involving reservations are not automatically pushed to the client // first we create a list with all changed appointments. Notice if a reservation is changed all the appointments will change to Map<Allocatable, Set<String>> appointmentUpdateMap = new LinkedHashMap<Allocatable, Set<String>>(); for (@SuppressWarnings("rawtypes") RaplaObject obj:evt.getChanged()) { if ( obj.getRaplaType().equals( Reservation.TYPE)) { Reservation reservation = (Reservation) obj; for (Appointment app: reservation.getAppointments()) { for ( Allocatable alloc:reservation.getAllocatablesFor( app)) { Set<String> set = appointmentUpdateMap.get( alloc); if ( set == null) { set = new HashSet<String>(); appointmentUpdateMap.put(alloc, set); } set.add( app.getId()); } } } } // then we create a map and look for any conflict that has changed appointment. This could still contain old appointment references Map<Conflict,Conflict> toUpdateConflicts = new LinkedHashMap<Conflict, Conflict>(); for ( Allocatable alloc: appointmentUpdateMap.keySet()) { Set<String> changedAppointments = appointmentUpdateMap.get( alloc); Set<Conflict> conflicts = conflictMap.get( alloc); if ( conflicts != null) { for ( Conflict conflict:conflicts) { String appointment1Id = conflict.getAppointment1(); String appointment2Id = conflict.getAppointment2(); boolean contains1 = changedAppointments.contains( appointment1Id); boolean contains2 = changedAppointments.contains( appointment2Id); if ( contains1 || contains2) { Conflict oldConflict = conflict; Appointment appointment1 = getAppointment( appointment1Id); Appointment appointment2 = getAppointment( appointment2Id); Conflict newConflict = new ConflictImpl( alloc, appointment1, appointment2, today); toUpdateConflicts.put( oldConflict, newConflict); } } } } // we update the conflict with the new appointment references ArrayList<Conflict> updateList = new ArrayList<Conflict>( toUpdateConflicts.keySet()); for ( Conflict oldConflict:updateList) { Conflict newConflict = toUpdateConflicts.get( oldConflict); Set<Conflict> conflicts = conflictMap.get( oldConflict.getAllocatable()); conflicts.remove( oldConflict); conflicts.add( newConflict); // we add a change operation // TODO Note that this list also contains the NEW conflicts, but the UpdateResult.NEW could still contain the old conflicts //if ( added.contains( oldConflict)) { evt.addOperation( new UpdateResult.Change( newConflict, oldConflict)); } } } // private SortedSet<Appointment> getAndCreateListId(Map<Allocatable,SortedSet<Appointment>> appointmentMap,Allocatable alloc) { // SortedSet<Appointment> set = appointmentMap.get( alloc); // if ( set == null) // { // set = new TreeSet<Appointment>(); // appointmentMap.put(alloc, set); // } // return set; // } // private Appointment getAppointment( // SortedSet<Appointment> changedAppointments, Appointment appointment) { // Appointment foundAppointment = changedAppointments.tailSet( appointment).iterator().next(); // return foundAppointment; // } public void removeOldConflicts(UpdateResult result, Date today) { for (Set<Conflict> sortedSet: conflictMap.values()) { Iterator<Conflict> it = sortedSet.iterator(); while (it.hasNext()) { Conflict conflict = it.next(); if ( endsBefore( conflict,today)) { it.remove(); result.addOperation( new UpdateResult.Remove(conflict)); } } } } }
04900db4-rob
src/org/rapla/storage/impl/server/ConflictFinder.java
Java
gpl3
19,294
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.impl; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import org.rapla.components.util.Assert; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.internal.SimpleEntity; public class EntityStore implements EntityResolver { HashMap<String,Entity> entities = new LinkedHashMap<String,Entity>(); HashMap<String,DynamicType> dynamicTypes = new HashMap<String,DynamicType>(); HashMap<String,String> passwordList = new HashMap<String,String>(); CategoryImpl superCategory; EntityResolver parent; public EntityStore(EntityResolver parent,Category superCategory) { this.parent = parent; this.superCategory = (CategoryImpl) superCategory; } public void addAll(Collection<? extends Entity>collection) { Iterator<? extends Entity>it = collection.iterator(); while (it.hasNext()) { put(it.next()); } } public void put(Entity entity) { String id = entity.getId(); Assert.notNull(id); if ( entity.getRaplaType() == DynamicType.TYPE) { DynamicType dynamicType = (DynamicType) entity; dynamicTypes.put ( dynamicType.getKey(), dynamicType); } if ( entity.getRaplaType() == Category.TYPE) { for (Category child:((Category)entity).getCategories()) { put( child); } } entities.put(id,entity); } public DynamicType getDynamicType(String key) { DynamicType type = dynamicTypes.get( key); if ( type == null && parent != null) { type = parent.getDynamicType( key); } return type; } public Collection<Entity>getList() { return entities.values(); } public CategoryImpl getSuperCategory() { return superCategory; } public void putPassword( String userid, String password ) { passwordList.put(userid, password); } public String getPassword( String userid) { return passwordList.get(userid); } public Entity resolve(String id) throws EntityNotFoundException { return resolve(id, null); } public <T extends Entity> T resolve(String id,Class<T> entityClass) throws EntityNotFoundException { T entity = tryResolve(id, entityClass); SimpleEntity.checkResolveResult(id, entityClass, entity); return entity; } @Override public Entity tryResolve(String id) { return tryResolve(id, null); } @Override public <T extends Entity> T tryResolve(String id,Class<T> entityClass) { Assert.notNull( id); Entity entity = entities.get(id); if (entity != null) { @SuppressWarnings("unchecked") T casted = (T) entity; return casted; } if ( id.equals( superCategory.getId()) && (entityClass == null || Category.class.isAssignableFrom( entityClass))) { @SuppressWarnings("unchecked") T casted = (T) superCategory; return casted; } if (parent != null) { return parent.tryResolve(id, entityClass); } return null; } }
04900db4-rob
src/org/rapla/storage/impl/EntityStore.java
Java
gpl3
4,564
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.rapla.components.util.TimeInterval; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.facade.ModificationEvent; public class UpdateResult implements ModificationEvent { private User user; private List<UpdateOperation> operations = new ArrayList<UpdateOperation>(); Set<RaplaType> modified = new HashSet<RaplaType>(); boolean switchTemplateMode = false; public UpdateResult(User user) { this.user = user; } public void addOperation(final UpdateOperation operation) { if ( operation == null) throw new IllegalStateException( "Operation can't be null" ); operations.add(operation); Entity current = operation.getCurrent(); if ( current != null) { RaplaType raplaType = current.getRaplaType(); modified.add( raplaType); } } public User getUser() { return user; } public Set<Entity> getRemoved() { return getObject( Remove.class); } public Set<Entity> getChangeObjects() { return getObject( Change.class); } public Set<Entity> getAddObjects() { return getObject( Add.class); } @SuppressWarnings("unchecked") public <T extends UpdateOperation> Iterator<T> getOperations( final Class<T> operationClass) { Iterator<UpdateOperation> operationsIt = operations.iterator(); if ( operationClass == null) throw new IllegalStateException( "OperationClass can't be null" ); List<T> list = new ArrayList<T>(); while ( operationsIt.hasNext() ) { UpdateOperation obj = operationsIt.next(); if ( operationClass.equals( obj.getClass())) { list.add( (T)obj ); } } return list.iterator(); } public Iterable<UpdateOperation> getOperations() { return Collections.unmodifiableCollection(operations); } protected <T extends UpdateOperation> Set<Entity> getObject( final Class<T> operationClass ) { Set<Entity> set = new HashSet<Entity>(); if ( operationClass == null) throw new IllegalStateException( "OperationClass can't be null" ); Iterator<? extends UpdateOperation> it= getOperations( operationClass); while (it.hasNext() ) { UpdateOperation next = it.next(); Entity current = next.getCurrent(); set.add( current); } return set; } static public class Add implements UpdateOperation { Entity newObj; // the object in the state when it was added public Add( Entity newObj) { this.newObj = newObj; } public Entity getCurrent() { return newObj; } public Entity getNew() { return newObj; } public String toString() { return "Add " + newObj; } } static public class Remove implements UpdateOperation { Entity currentObj; // the actual represantation of the object public Remove(Entity currentObj) { this.currentObj = currentObj; } public Entity getCurrent() { return currentObj; } public String toString() { return "Remove " + currentObj; } } static public class Change implements UpdateOperation{ Entity newObj; // the object in the state when it was changed Entity oldObj; // the object in the state before it was changed public Change( Entity newObj, Entity oldObj) { this.newObj = newObj; this.oldObj = oldObj; } public Entity getCurrent() { return newObj; } public Entity getNew() { return newObj; } public Entity getOld() { return oldObj; } public String toString() { return "Change " + oldObj + " to " + newObj; } } TimeInterval timeInterval; public void setInvalidateInterval(TimeInterval timeInterval) { this.timeInterval = timeInterval; } public TimeInterval getInvalidateInterval() { return timeInterval; } public TimeInterval calulateInvalidateInterval() { TimeInterval currentInterval = null; { Iterator<Change> operations = getOperations( Change.class); while (operations.hasNext()) { Change change = operations.next(); currentInterval = expandInterval( change.getNew(), currentInterval); currentInterval = expandInterval( change.getOld(), currentInterval); } } { Iterator<Add> operations = getOperations( Add.class); while (operations.hasNext()) { Add change = operations.next(); currentInterval = expandInterval( change.getNew(), currentInterval); } } { Iterator<Remove> operations = getOperations( Remove.class); while (operations.hasNext()) { Remove change = operations.next(); currentInterval = expandInterval( change.getCurrent(), currentInterval); } } return currentInterval; } private TimeInterval expandInterval(RaplaObject obj, TimeInterval currentInterval) { RaplaType type = obj.getRaplaType(); if ( type == Reservation.TYPE) { for ( Appointment app:((ReservationImpl)obj).getAppointmentList()) { currentInterval = invalidateInterval( currentInterval, app); } } return currentInterval; } private TimeInterval invalidateInterval(TimeInterval oldInterval,Appointment appointment) { Date start = appointment.getStart(); Date end = appointment.getMaxEnd(); TimeInterval interval = new TimeInterval(start, end).union( oldInterval); return interval; } public boolean hasChanged(Entity object) { return getChanged().contains(object); } public boolean isRemoved(Entity object) { return getRemoved().contains( object); } public boolean isModified(Entity object) { return hasChanged(object) || isRemoved( object); } /** returns the modified objects from a given set. * @deprecated use the retainObjects instead in combination with getChanged*/ public <T extends RaplaObject> Set<T> getChanged(Collection<T> col) { return RaplaType.retainObjects(getChanged(),col); } /** returns the modified objects from a given set. * @deprecated use the retainObjects instead in combination with getChanged*/ public <T extends RaplaObject> Set<T> getRemoved(Collection<T> col) { return RaplaType.retainObjects(getRemoved(),col); } public Set<Entity> getChanged() { Set<Entity> result = new HashSet<Entity>(getAddObjects()); result.addAll(getChangeObjects()); return result; } public boolean isModified(RaplaType raplaType) { return modified.contains( raplaType) ; } public boolean isModified() { return !operations.isEmpty() || switchTemplateMode; } public boolean isEmpty() { return !isModified() && timeInterval == null; } public void setSwitchTemplateMode(boolean b) { switchTemplateMode = b; } public boolean isSwitchTemplateMode() { return switchTemplateMode; } }
04900db4-rob
src/org/rapla/storage/UpdateResult.java
Java
gpl3
8,651
package org.rapla.storage; import org.rapla.framework.RaplaException; public class RaplaNewVersionException extends RaplaException { private static final long serialVersionUID = 1L; public RaplaNewVersionException(String text) { super(text); } }
04900db4-rob
src/org/rapla/storage/RaplaNewVersionException.java
Java
gpl3
269
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.rapla.components.util.ParseDateException; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.components.util.TimeInterval; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.internal.UserImpl; import org.rapla.entities.storage.EntityReferencer; import org.rapla.facade.Conflict; import org.rapla.facade.internal.ConflictImpl; public class UpdateEvent { transient Map listMap;// = new HashMap<Class, List<Entity>>(); List<CategoryImpl> categories = createList(Category.class); List<DynamicTypeImpl> types = createList(DynamicType.class); List<UserImpl> users = createList(User.class); List<PreferencePatch> preferencesPatches = new ArrayList<PreferencePatch>(); List<PreferencesImpl> preferences = createList(Preferences.class); List<AllocatableImpl> resources = createList(Allocatable.class); List<ReservationImpl> reservations = createList(Reservation.class); List<ConflictImpl> conflicts = createList(Conflict.class); private Set<String> removeSet = new LinkedHashSet<String>(); private Set<String> storeSet = new LinkedHashSet<String>(); private String userId; private boolean needResourcesRefresh = false; private TimeInterval invalidateInterval; private String lastValidated; private int timezoneOffset; public UpdateEvent() { } private <T> List<T> createList(@SuppressWarnings("unused") Class<? super T> clazz) { ArrayList<T> list = new ArrayList<T>(); return list; } public void setUserId( String userId) { this.userId = userId; } public String getUserId() { return userId; } private void addRemove(Entity entity) { removeSet.add( entity.getId()); add( entity); } private void addStore(Entity entity) { storeSet.add( entity.getId()); add( entity); } @SuppressWarnings("unchecked") public Map<Class, Collection<Entity>> getListMap() { if ( listMap == null) { listMap = new HashMap<Class,Collection<Entity>>(); listMap.put( Preferences.class,preferences); listMap.put( Allocatable.class,resources); listMap.put(Category.class, categories); listMap.put(User.class, users); listMap.put(DynamicType.class, types); listMap.put(Reservation.class, reservations); listMap.put(Conflict.class, conflicts); } return listMap; } private void add(Entity entity) { @SuppressWarnings("unchecked") Class<? extends RaplaType> class1 = entity.getRaplaType().getTypeClass(); Collection<Entity> list = getListMap().get( class1); if ( list == null) { //listMap.put( class1, list); throw new IllegalArgumentException(entity.getRaplaType() + " can't be stored "); } list.add( entity); } public void putPatch(PreferencePatch patch) { preferencesPatches.add( patch); } public Collection<Entity> getRemoveObjects() { HashSet<Entity> objects = new LinkedHashSet<Entity>(); for ( Collection<Entity> list:getListMap().values()) { for ( Entity entity:list) { if ( removeSet.contains( entity.getId())) { objects.add(entity); } } } return objects; } public Collection<Entity> getStoreObjects() { // Needs to be a linked hashset to keep the order of the entities HashSet<Entity> objects = new LinkedHashSet<Entity>(); for ( Collection<Entity> list:getListMap().values()) { for ( Entity entity:list) { if ( storeSet.contains( entity.getId())) { objects.add(entity); } } } return objects; } public Collection<EntityReferencer> getEntityReferences(boolean includeRemove) { HashSet<EntityReferencer> objects = new HashSet<EntityReferencer>(); for ( Collection<Entity> list:getListMap().values()) { for ( Entity entity:list) { String id = entity.getId(); boolean contains = storeSet.contains( id) || (includeRemove && removeSet.contains( id)); if ( contains && entity instanceof EntityReferencer) { EntityReferencer references = (EntityReferencer)entity; objects.add(references); } } } for ( PreferencePatch patch:preferencesPatches) { objects.add(patch); } return objects; } public List<PreferencePatch> getPreferencePatches() { return preferencesPatches; } /** use this method if you want to avoid adding the same Entity twice.*/ public void putStore(Entity entity) { if (!storeSet.contains(entity.getId())) addStore(entity); } /** use this method if you want to avoid adding the same Entity twice.*/ public void putRemove(Entity entity) { if (!removeSet.contains(entity.getId())) addRemove(entity); } /** find an entity in the update-event that matches the passed original. Returns null * if no such entity is found. */ public Entity findEntity(Entity original) { String originalId = original.getId(); if (!storeSet.contains( originalId)) { if (!removeSet.contains( originalId)) { return null; } } for ( Collection<Entity> list:getListMap().values()) { for ( Entity entity:list) { if ( entity.getId().equals( originalId)) { return entity; } } } throw new IllegalStateException("Entity in store/remove set but not found in list"); } public void setLastValidated( Date serverTime ) { if ( serverTime == null) { this.lastValidated = null; } this.lastValidated = SerializableDateTimeFormat.INSTANCE.formatTimestamp(serverTime); } public void setInvalidateInterval(TimeInterval invalidateInterval) { this.invalidateInterval = invalidateInterval; } public TimeInterval getInvalidateInterval() { return invalidateInterval; } public boolean isNeedResourcesRefresh() { return needResourcesRefresh; } public void setNeedResourcesRefresh(boolean needResourcesRefresh) { this.needResourcesRefresh = needResourcesRefresh; } public Collection<Entity> getAllObjects() { HashSet<Entity> objects = new HashSet<Entity>(); for ( Collection<Entity> list:getListMap().values()) { for ( Entity entity:list) { objects.add(entity); } } return objects; } public boolean isEmpty() { boolean isEmpty = removeSet.isEmpty() && storeSet.isEmpty() && invalidateInterval == null; return isEmpty; } public Date getLastValidated() { if ( lastValidated == null) { return null; } try { return SerializableDateTimeFormat.INSTANCE.parseTimestamp(lastValidated); } catch (ParseDateException e) { throw new IllegalStateException(e.getMessage()); } } public int getTimezoneOffset() { return timezoneOffset; } public void setTimezoneOffset(int timezoneOffset) { this.timezoneOffset = timezoneOffset; } }
04900db4-rob
src/org/rapla/storage/UpdateEvent.java
Java
gpl3
9,070
package org.rapla.storage; import java.util.LinkedHashSet; import java.util.Set; import org.rapla.entities.configuration.internal.RaplaMapImpl; public class PreferencePatch extends RaplaMapImpl { String userId; Set<String> removedEntries = new LinkedHashSet<String>(); public void addRemove(String role) { removedEntries.add( role); } public void setUserId(String userId) { this.userId = userId; } public String getUserId() { return userId; } public Set<String> getRemovedEntries() { return removedEntries; } @Override public String toString() { return "Patch for " + userId + " " + super.toString() + " Removed " + removedEntries.toString(); } }
04900db4-rob
src/org/rapla/storage/PreferencePatch.java
Java
gpl3
778
package org.rapla.storage; import org.rapla.entities.RaplaType; import org.rapla.framework.RaplaException; @Deprecated public class OldIdMapping { static public String getId(RaplaType type,String str) throws RaplaException { if (str == null) throw new RaplaException("Id string for " + type + " can't be null"); int index = str.lastIndexOf("_") + 1; if (index>str.length()) throw new RaplaException("invalid rapla-id '" + str + "'"); try { return getId(type,Integer.parseInt(str.substring(index))); } catch (NumberFormatException ex) { throw new RaplaException("invalid rapla-id '" + str + "'"); } } static public boolean isTextId( RaplaType type,String content ) { if ( content == null) { return false; } content = content.trim(); if ( isNumeric( content)) { return true; } String KEY_START = type.getLocalName() + "_"; boolean idContent = (content.indexOf( KEY_START ) >= 0 && content.length() > 0); return idContent; } static private boolean isNumeric(String text) { int length = text.length(); if ( length == 0) { return false; } for ( int i=0;i<length;i++) { char ch = text.charAt(i); if (!Character.isDigit(ch)) { return false; } } return true; } public static int parseId(String id) { int indexOf = id.indexOf("_"); String keyPart = id.substring( indexOf + 1); return Integer.parseInt(keyPart); } static public String getId(RaplaType type,int id) { return type.getLocalName() + "_" + id; } static public boolean isId( RaplaType type,Object object) { if (object instanceof String) { return ((String)object).startsWith(type.getLocalName()); } return false; } static public Integer getKey(RaplaType type,String id) { String keyPart = id.substring(type.getLocalName().length()+1); Integer key = Integer.parseInt( keyPart ); return key; } }
04900db4-rob
src/org/rapla/storage/OldIdMapping.java
Java
gpl3
2,199
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ /** A StorageOperator that operates on a LocalCache-Object. */ package org.rapla.storage; import java.util.Collection; import java.util.Date; import java.util.TimeZone; import org.rapla.entities.Entity; import org.rapla.entities.User; import org.rapla.framework.RaplaException; public interface CachableStorageOperator extends StorageOperator { void runWithReadLock(CachableStorageOperatorCommand cmd) throws RaplaException; void dispatch(UpdateEvent evt) throws RaplaException; String authenticate(String username,String password) throws RaplaException; void saveData(LocalCache cache) throws RaplaException; public Collection<Entity> getVisibleEntities(final User user) throws RaplaException; public Collection<Entity> getUpdatedEntities(Date timestamp) throws RaplaException; TimeZone getTimeZone(); //DynamicType getUnresolvedAllocatableType(); //DynamicType getAnonymousReservationType(); }
04900db4-rob
src/org/rapla/storage/CachableStorageOperator.java
Java
gpl3
1,901
package org.rapla.storage; import org.rapla.framework.RaplaException; public interface CachableStorageOperatorCommand { public void execute( LocalCache cache) throws RaplaException; }
04900db4-rob
src/org/rapla/storage/CachableStorageOperatorCommand.java
Java
gpl3
194
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage; import org.rapla.framework.RaplaException; /** * This exception is thrown on an invalid login, * or when a client tries to access data without * the proper permissions. */ public class RaplaSecurityException extends RaplaException { private static final long serialVersionUID = 1L; public RaplaSecurityException(String text) { super(text); } public RaplaSecurityException(Throwable throwable) { super(throwable); } public RaplaSecurityException(String text,Throwable ex) { super(text,ex); } }
04900db4-rob
src/org/rapla/storage/RaplaSecurityException.java
Java
gpl3
1,531
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage; import org.rapla.framework.RaplaException; public interface StorageUpdateListener { public void objectsUpdated(UpdateResult evt); public void updateError(RaplaException ex); public void storageDisconnected(String disconnectionMessage); }
04900db4-rob
src/org/rapla/storage/StorageUpdateListener.java
Java
gpl3
1,216
package org.rapla.storage.dbrm; import org.rapla.framework.RaplaException; public class RaplaConnectException extends RaplaException { private static final long serialVersionUID = 1L; public RaplaConnectException(String text) { super(text, null); } public RaplaConnectException( Throwable cause) { super(cause.getMessage(), cause); } }
04900db4-rob
src/org/rapla/storage/dbrm/RaplaConnectException.java
Java
gpl3
382
package org.rapla.storage.dbrm; public class RaplaRestartingException extends RaplaConnectException { private static final long serialVersionUID = 1L; public RaplaRestartingException() { super("Connection to server aborted. Restarting client."); } }
04900db4-rob
src/org/rapla/storage/dbrm/RaplaRestartingException.java
Java
gpl3
287
package org.rapla.storage.dbrm; import java.util.Date; public class LoginTokens { String accessToken; Date validUntil; @SuppressWarnings("unused") private LoginTokens() { } public LoginTokens(String accessToken, Date validUntil) { this.accessToken = accessToken; this.validUntil = validUntil; } public String getAccessToken() { return accessToken; } public Date getValidUntil() { return validUntil; } }
04900db4-rob
src/org/rapla/storage/dbrm/LoginTokens.java
Java
gpl3
509
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Praktikum Gruppe2?, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbrm; import org.rapla.framework.RaplaException; public interface RestartServer { public void restartServer() throws RaplaException; }
04900db4-rob
src/org/rapla/storage/dbrm/RestartServer.java
Java
gpl3
1,107
/*--------------------------------------------------------------------------* | Copyright (C) 2006 ?, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbrm; import java.util.Date; import java.util.List; import java.util.Map; import javax.jws.WebParam; import javax.jws.WebService; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.facade.internal.ConflictImpl; import org.rapla.framework.RaplaException; import org.rapla.rest.gwtjsonrpc.common.FutureResult; import org.rapla.rest.gwtjsonrpc.common.RemoteJsonService; import org.rapla.rest.gwtjsonrpc.common.ResultType; import org.rapla.rest.gwtjsonrpc.common.VoidResult; import org.rapla.storage.UpdateEvent; @WebService public interface RemoteStorage extends RemoteJsonService { final String USER_WAS_NOT_AUTHENTIFIED = "User was not authentified"; @ResultType(String.class) FutureResult<String> canChangePassword(); @ResultType(VoidResult.class) FutureResult<VoidResult> changePassword(String username,String oldPassword,String newPassword); @ResultType(VoidResult.class) FutureResult<VoidResult> changeName(String username, String newTitle,String newSurename,String newLastname); @ResultType(VoidResult.class) FutureResult<VoidResult> changeEmail(String username,String newEmail); @ResultType(VoidResult.class) FutureResult<VoidResult> confirmEmail(String username,String newEmail); @ResultType(UpdateEvent.class) FutureResult<UpdateEvent> getResources() throws RaplaException; /** delegates the corresponding method in the StorageOperator. * @param annotationQuery */ @ResultType(value=ReservationImpl.class,container=List.class) FutureResult<List<ReservationImpl>> getReservations(@WebParam(name="resources")String[] allocatableIds,@WebParam(name="start")Date start,@WebParam(name="end")Date end, @WebParam(name="annotations")Map<String, String> annotationQuery); @ResultType(UpdateEvent.class) FutureResult<UpdateEvent> getEntityRecursive(String... id); @ResultType(UpdateEvent.class) FutureResult<UpdateEvent> refresh(String clientRepoVersion); @ResultType(VoidResult.class) FutureResult<VoidResult> restartServer(); @ResultType(UpdateEvent.class) FutureResult<UpdateEvent> dispatch(UpdateEvent event); @ResultType(value=String.class,container=List.class) FutureResult<List<String>> getTemplateNames(); @ResultType(value=String.class,container=List.class) FutureResult<List<String>> createIdentifier(String raplaType, int count); @ResultType(value=ConflictImpl.class,container=List.class) FutureResult<List<ConflictImpl>> getConflicts(); @ResultType(BindingMap.class) FutureResult<BindingMap> getFirstAllocatableBindings(String[] allocatableIds, List<AppointmentImpl> appointments, String[] reservationIds); @ResultType(value=ReservationImpl.class,container=List.class) FutureResult<List<ReservationImpl>> getAllAllocatableBindings(String[] allocatables, List<AppointmentImpl> appointments, String[] reservationIds); @ResultType(Date.class) FutureResult<Date> getNextAllocatableDate(String[] allocatableIds, AppointmentImpl appointment,String[] reservationIds, Integer worktimeStartMinutes, Integer worktimeEndMinutes, Integer[] excludedDays, Integer rowsPerHour); //void logEntityNotFound(String logMessage,String... referencedIds) throws RaplaException; public static class BindingMap { Map<String,List<String>> bindings; BindingMap() { } public BindingMap(Map<String,List<String>> bindings) { this.bindings = bindings; } public Map<String,List<String>> get() { return bindings; } } void setConnectInfo(RemoteConnectionInfo info); }
04900db4-rob
src/org/rapla/storage/dbrm/RemoteStorage.java
Java
gpl3
4,596
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbrm; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.locks.Lock; import org.rapla.ConnectInfo; import org.rapla.components.util.Assert; import org.rapla.components.util.Cancelable; import org.rapla.components.util.Command; import org.rapla.components.util.CommandScheduler; import org.rapla.components.util.DateTools; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.components.util.TimeInterval; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentStartComparator; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.storage.EntityResolver; import org.rapla.facade.Conflict; import org.rapla.facade.UpdateModule; import org.rapla.facade.internal.ConflictImpl; import org.rapla.framework.Configuration; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.internal.ContextTools; import org.rapla.framework.logger.Logger; import org.rapla.rest.gwtjsonrpc.common.AsyncCallback; import org.rapla.rest.gwtjsonrpc.common.FutureResult; import org.rapla.storage.RaplaSecurityException; import org.rapla.storage.UpdateEvent; import org.rapla.storage.UpdateResult; import org.rapla.storage.impl.AbstractCachableOperator; /** This operator can be used to modify and access data over the * network. It needs an server-process providing the StorageService * (usually this is the default rapla-server). * <p>Sample configuration: <pre> &lt;remote-storage id="web"> &lt;/remote-storate> </pre> */ public class RemoteOperator extends AbstractCachableOperator implements RestartServer,Disposable { private boolean bSessionActive = false; String userId; RemoteServer remoteServer; RemoteStorage remoteStorage; protected CommandScheduler commandQueue; Date lastSyncedTimeLocal; Date lastSyncedTime; int timezoneOffset; ConnectInfo connectInfo; Configuration config; RemoteConnectionInfo connectionInfo; public RemoteOperator(RaplaContext context, Logger logger, Configuration config, RemoteServer remoteServer, RemoteStorage remoteStorage) throws RaplaException { super( context, logger ); this.config = config; this.remoteServer = remoteServer; this.remoteStorage = remoteStorage; commandQueue = context.lookup( CommandScheduler.class); this.connectionInfo = new RemoteConnectionInfo(); remoteStorage.setConnectInfo( connectionInfo ); remoteServer.setConnectInfo( connectionInfo ); if ( config != null) { String serverConfig = config.getChild("server").getValue("${downloadServer}"); final String serverURL= ContextTools.resolveContext(serverConfig, context ); connectionInfo.setServerURL(serverURL); } } public RemoteConnectionInfo getRemoteConnectionInfo() { return connectionInfo; } synchronized public User connect(ConnectInfo connectInfo) throws RaplaException { if ( connectInfo == null) { throw new RaplaException("RemoteOperator doesn't support anonymous connect"); } if (isConnected()) return null; getLogger().info("Connecting to server and starting login.."); Lock writeLock = writeLock(); try { User user = loginAndLoadData(connectInfo); connectionInfo.setReAuthenticateCommand(new FutureResult<String>() { @Override public String get() throws Exception { getLogger().info("Refreshing access token."); return loginWithoutDisconnect(); } @Override public String get(long wait) throws Exception { return get(); } @Override public void get(AsyncCallback<String> callback) { try { String string = get(); callback.onSuccess(string); } catch (Exception e) { callback.onFailure(e); } } }); initRefresh(); return user; } finally { unlock(writeLock); } } private User loginAndLoadData(ConnectInfo connectInfo) throws RaplaException { this.connectInfo = connectInfo; String username = this.connectInfo.getUsername(); login(); getLogger().info("login successfull"); User user = loadData(username); bSessionActive = true; return user; } protected String login() throws RaplaException { try { return loginWithoutDisconnect(); } catch (RaplaException ex){ disconnect(); throw ex; } catch (Exception ex){ disconnect(); throw new RaplaException(ex); } } private String loginWithoutDisconnect() throws Exception, RaplaSecurityException { String connectAs = this.connectInfo.getConnectAs(); String password = new String( this.connectInfo.getPassword()); String username = this.connectInfo.getUsername(); RemoteServer serv1 = getRemoteServer(); LoginTokens loginToken = serv1.login(username,password, connectAs).get(); String accessToken = loginToken.getAccessToken(); if ( accessToken != null) { connectionInfo.setAccessToken( accessToken); return accessToken; } else { throw new RaplaSecurityException("Invalid Access token"); } } public Date getCurrentTimestamp() { if (lastSyncedTime == null) { return new Date(System.currentTimeMillis()); } // no matter what the client clock says we always sync to the server clock long passedMillis = System.currentTimeMillis()- lastSyncedTimeLocal.getTime(); if ( passedMillis < 0) { passedMillis = 0; } long correctTime = this.lastSyncedTime.getTime() + passedMillis; Date date = new Date(correctTime); return date; } public Date today() { long time = getCurrentTimestamp().getTime(); Date raplaTime = new Date(time + timezoneOffset); return DateTools.cutDate( raplaTime); } Cancelable timerTask; int intervalLength; private final void initRefresh() { Command refreshTask = new Command() { public void execute() { try { // test if the remote operator is writable // if not we skip until the next update cycle Lock writeLock = lock.writeLock(); boolean tryLock = writeLock.tryLock(); if ( tryLock) { writeLock.unlock(); } if (isConnected() && tryLock) { refresh(); } } catch (RaplaConnectException e) { getLogger().error("Error connecting " + e.getMessage()); } catch (RaplaException e) { getLogger().error("Error refreshing.", e); } } }; intervalLength = UpdateModule.REFRESH_INTERVAL_DEFAULT; if (isConnected()) { try { intervalLength = getPreferences(null, true).getEntryAsInteger(UpdateModule.REFRESH_INTERVAL_ENTRY, UpdateModule.REFRESH_INTERVAL_DEFAULT); } catch (RaplaException e) { getLogger().error("Error refreshing.", e); } } if ( timerTask != null) { timerTask.cancel(); } timerTask = commandQueue.schedule(refreshTask, 0, intervalLength); } public void dispose() { if ( timerTask != null) { timerTask.cancel(); } } // public String getConnectionName() { // if ( connector != null) // { // return connector.getInfo(); // } // else // { // return "standalone"; // } // } // // private void doConnect() throws RaplaException { // boolean bFailed = true; // try { // bFailed = false; // } catch (Exception e) { // throw new RaplaException(i18n.format("error.connect",getConnectionName()),e); // } finally { // if (bFailed) // disconnect(); // } // } public boolean isConnected() { return bSessionActive; } public boolean supportsActiveMonitoring() { return true; } synchronized public void refresh() throws RaplaException { String clientRepoVersion = getClientRepoVersion(); RemoteStorage serv = getRemoteStorage(); try { UpdateEvent evt = serv.refresh( clientRepoVersion).get(); refresh( evt); } catch (EntityNotFoundException ex) { getLogger().error("Refreshing all resources due to " + ex.getMessage(), ex); refreshAll(); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } private String getClientRepoVersion() { return SerializableDateTimeFormat.INSTANCE.formatTimestamp(lastSyncedTime); } synchronized public void restartServer() throws RaplaException { getLogger().info("Restart in progress ..."); String message = i18n.getString("restart_server"); // isRestarting = true; try { RemoteStorage serv = getRemoteStorage(); serv.restartServer().get(); fireStorageDisconnected(message); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } synchronized public void disconnect() throws RaplaException { connectionInfo.setAccessToken( null); this.connectInfo = null; connectionInfo.setReAuthenticateCommand(null); disconnect("Disconnection from Server initiated"); } /** disconnect from the server */ synchronized public void disconnect(String message) throws RaplaException { boolean wasConnected = bSessionActive; getLogger().info("Disconnecting from server"); try { bSessionActive = false; cache.clearAll(); } catch (Exception e) { throw new RaplaException("Could not disconnect", e); } if ( wasConnected) { RemoteServer serv1 = getRemoteServer(); try { serv1.logout().get(); } catch (RaplaConnectException ex) { getLogger().warn( ex.getMessage()); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } fireStorageDisconnected(message); } } @Override protected void setResolver(Collection<? extends Entity> entities) throws RaplaException { // don't resolve entities in standalone mode if (context.has(RemoteMethodStub.class)) { return; } super.setResolver(entities); } @Override protected void testResolve(Collection<? extends Entity> entities) throws EntityNotFoundException { // don't resolve entities in standalone mode if (context.has(RemoteMethodStub.class)) { return; } super.testResolve(entities); } private User loadData(String username) throws RaplaException { getLogger().debug("Getting Data.."); RemoteStorage serv = getRemoteStorage(); try { UpdateEvent evt = serv.getResources().get(); this.userId = evt.getUserId(); if ( userId != null) { cache.setClientUserId( userId); } updateTimestamps(evt); Collection<Entity> storeObjects = evt.getStoreObjects(); cache.clearAll(); testResolve( storeObjects); setResolver( storeObjects ); for( Entity entity:storeObjects) { cache.put(entity); } getLogger().debug("Data flushed"); if ( username != null) { if ( userId == null) { throw new EntityNotFoundException("User with username "+ username + " not found in result"); } User user = cache.resolve( userId, User.class); return user; } else { return null; } } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } public void updateTimestamps(UpdateEvent evt) throws RaplaException { if ( evt.getLastValidated() == null) { throw new RaplaException("Server sync time is missing"); } lastSyncedTimeLocal = new Date(System.currentTimeMillis()); lastSyncedTime = evt.getLastValidated(); timezoneOffset = evt.getTimezoneOffset(); //long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time); } protected void checkConnected() throws RaplaException { if ( !bSessionActive ) { throw new RaplaException("Not logged in or connection closed!"); } } public void dispatch(UpdateEvent evt) throws RaplaException { checkConnected(); // Store on server if (getLogger().isDebugEnabled()) { Iterator<Entity>it =evt.getStoreObjects().iterator(); while (it.hasNext()) { Entity entity = it.next(); getLogger().debug("dispatching store for: " + entity); } it =evt.getRemoveObjects().iterator(); while (it.hasNext()) { Entity entity = it.next(); getLogger().debug("dispatching remove for: " + entity); } } RemoteStorage serv = getRemoteStorage(); evt.setLastValidated(lastSyncedTime); try { UpdateEvent serverClosure =serv.dispatch( evt ).get(); refresh(serverClosure); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } public String[] createIdentifier(RaplaType raplaType, int count) throws RaplaException { RemoteStorage serv = getRemoteStorage(); try { List<String> id = serv.createIdentifier(raplaType.getLocalName(), count).get(); return id.toArray(new String[] {}); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } private RemoteStorage getRemoteStorage() { return remoteStorage; } private RemoteServer getRemoteServer() { return remoteServer; } public boolean canChangePassword() throws RaplaException { RemoteStorage remoteMethod = getRemoteStorage(); try { String canChangePassword = remoteMethod.canChangePassword().get(); boolean result = canChangePassword != null && canChangePassword.equalsIgnoreCase("true"); return result; } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } @Override public void changePassword(User user,char[] oldPassword,char[] newPassword) throws RaplaException { try { RemoteStorage remoteMethod = getRemoteStorage(); String username = user.getUsername(); remoteMethod.changePassword(username, new String(oldPassword),new String(newPassword)).get(); refresh(); } catch (RaplaSecurityException ex) { throw new RaplaSecurityException(i18n.getString("error.wrong_password")); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } @Override public void changeEmail(User user, String newEmail) throws RaplaException { try { RemoteStorage remoteMethod = getRemoteStorage(); String username = user.getUsername(); remoteMethod.changeEmail(username,newEmail).get(); refresh(); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } @Override public void confirmEmail(User user, String newEmail) throws RaplaException { try { RemoteStorage remoteMethod = getRemoteStorage(); String username = user.getUsername(); remoteMethod.confirmEmail(username,newEmail).get(); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } @Override public void changeName(User user, String newTitle, String newFirstname, String newSurname) throws RaplaException { try { RemoteStorage remoteMethod = getRemoteStorage(); String username = user.getUsername(); remoteMethod.changeName(username,newTitle, newFirstname, newSurname).get(); refresh(); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } public Map<String,Entity> getFromId(Collection<String> idSet, boolean throwEntityNotFound) throws RaplaException { RemoteStorage serv = getRemoteStorage(); String[] array = idSet.toArray(new String[] {}); Map<String,Entity> result = new HashMap<String,Entity>(); try { UpdateEvent entityList = serv.getEntityRecursive( array).get(); Collection<Entity> list = entityList.getStoreObjects(); Lock lock = readLock(); try { testResolve( list); setResolver( list ); } finally { unlock(lock); } for (Entity entity:list) { String id = entity.getId(); if ( idSet.contains( id )) { result.put( id, entity); } } } catch (EntityNotFoundException ex) { if ( throwEntityNotFound) { throw ex; } } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } return result; } @Override protected <T extends Entity> T tryResolve(EntityResolver resolver,String id,Class<T> entityClass) { Assert.notNull( id); T entity = super.tryResolve(resolver,id, entityClass); if ( entity != null) { return entity; } if ( entityClass != null && Allocatable.class.isAssignableFrom(entityClass)) { AllocatableImpl unresolved = new AllocatableImpl(null, null); unresolved.setId( id); unresolved.setClassification( getDynamicType(UNRESOLVED_RESOURCE_TYPE).newClassification()); @SuppressWarnings("unchecked") T casted = (T) unresolved; return casted; } return null; } public List<Reservation> getReservations(User user,Collection<Allocatable> allocatables,Date start,Date end,ClassificationFilter[] filters, Map<String,String> annotationQuery) throws RaplaException { RemoteStorage serv = getRemoteStorage(); // if a refresh is due, we assume the system went to sleep so we refresh before we continue if ( intervalLength > 0 && lastSyncedTime != null && (lastSyncedTime.getTime() + intervalLength * 2) < getCurrentTimestamp().getTime()) { getLogger().info("cache not uptodate. Refreshing first."); refresh(); } String[] allocatableId = getIdList(allocatables); try { List<ReservationImpl> list =serv.getReservations(allocatableId,start, end, annotationQuery).get(); Lock lock = readLock(); try { testResolve( list); setResolver( list ); } finally { unlock(lock); } List<Reservation> result = new ArrayList<Reservation>(); Iterator it = list.iterator(); while ( it.hasNext()) { Object object = it.next(); Reservation next = (Reservation)object; result.add( next); } removeFilteredClassifications(result, filters); return result; } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } public List<String> getTemplateNames() throws RaplaException { checkConnected(); RemoteStorage serv = getRemoteStorage(); try { List<String> result = serv.getTemplateNames().get(); return result; } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } protected String[] getIdList(Collection<? extends Entity> entities) { List<String> idList = new ArrayList<String>(); if ( entities != null ) { for ( Entity entity:entities) { if (entity != null) idList.add( ((Entity)entity).getId().toString()); } } String[] ids = idList.toArray(new String[] {}); return ids; } synchronized private void refresh(UpdateEvent evt) throws RaplaException { updateTimestamps(evt); if ( evt.isNeedResourcesRefresh()) { refreshAll(); return; } UpdateResult result = null; testResolve(evt.getStoreObjects()); setResolver(evt.getStoreObjects()); // we don't test the references of the removed objects setResolver(evt.getRemoveObjects()); if ( bSessionActive && !evt.isEmpty() ) { getLogger().debug("Objects updated!"); Lock writeLock = writeLock(); try { result = update(evt); } finally { unlock(writeLock); } } if ( result != null && !result.isEmpty()) { fireStorageUpdated(result); } } protected void refreshAll() throws RaplaException,EntityNotFoundException { UpdateResult result; Collection<Entity> oldEntities; Lock readLock = readLock(); try { User user = cache.resolve( userId, User.class); oldEntities = cache.getVisibleEntities(user); } finally { unlock(readLock); } Lock writeLock = writeLock(); try { loadData(null); } finally { unlock(writeLock); } Collection<Entity> newEntities; readLock = readLock(); try { User user = cache.resolve( userId, User.class); newEntities = cache.getVisibleEntities(user); } finally { unlock(readLock); } HashSet<Entity> updated = new HashSet<Entity>(newEntities); Set<Entity> toRemove = new HashSet<Entity>(oldEntities); Set<Entity> toUpdate = new HashSet<Entity>(oldEntities); toRemove.removeAll(newEntities); updated.removeAll( toRemove); toUpdate.retainAll(newEntities); HashMap<Entity,Entity> oldEntityMap = new HashMap<Entity,Entity>(); for ( Entity update: toUpdate) { @SuppressWarnings("unchecked") Class<? extends Entity> typeClass = update.getRaplaType().getTypeClass(); Entity newEntity = cache.tryResolve( update.getId(), typeClass); if ( newEntity != null) { oldEntityMap.put( newEntity, update); } } TimeInterval invalidateInterval = new TimeInterval( null,null); result = createUpdateResult(oldEntityMap, updated, toRemove, invalidateInterval, userId); fireStorageUpdated(result); } @Override public Map<Allocatable, Collection<Appointment>> getFirstAllocatableBindings( Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException { checkConnected(); RemoteStorage serv = getRemoteStorage(); String[] allocatableIds = getIdList(allocatables); //AppointmentImpl[] appointmentArray = appointments.toArray( new AppointmentImpl[appointments.size()]); String[] reservationIds = getIdList(ignoreList); List<AppointmentImpl> appointmentList = new ArrayList<AppointmentImpl>(); Map<String,Appointment> appointmentMap= new HashMap<String,Appointment>(); for ( Appointment app: appointments) { appointmentList.add( (AppointmentImpl) app); appointmentMap.put( app.getId(), app); } try { Map<String, List<String>> resultMap = serv.getFirstAllocatableBindings(allocatableIds, appointmentList, reservationIds).get().get(); HashMap<Allocatable, Collection<Appointment>> result = new HashMap<Allocatable, Collection<Appointment>>(); for ( Allocatable alloc:allocatables) { List<String> list = resultMap.get( alloc.getId()); if ( list != null) { Collection<Appointment> appointmentBinding = new ArrayList<Appointment>(); for ( String id:list) { Appointment e = appointmentMap.get( id); if ( e != null) { appointmentBinding.add( e); } } result.put( alloc, appointmentBinding); } } return result; } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } @Override public Map<Allocatable, Map<Appointment, Collection<Appointment>>> getAllAllocatableBindings( Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException { checkConnected(); RemoteStorage serv = getRemoteStorage(); String[] allocatableIds = getIdList(allocatables); List<AppointmentImpl> appointmentArray = Arrays.asList(appointments.toArray( new AppointmentImpl[]{})); String[] reservationIds = getIdList(ignoreList); List<ReservationImpl> serverResult; try { serverResult = serv.getAllAllocatableBindings(allocatableIds, appointmentArray, reservationIds).get(); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } testResolve( serverResult); setResolver( serverResult ); SortedSet<Appointment> allAppointments = new TreeSet<Appointment>(new AppointmentStartComparator()); for ( ReservationImpl reservation: serverResult) { allAppointments.addAll(reservation.getAppointmentList()); } Map<Allocatable, Map<Appointment,Collection<Appointment>>> result = new HashMap<Allocatable, Map<Appointment,Collection<Appointment>>>(); for ( Allocatable alloc:allocatables) { Map<Appointment,Collection<Appointment>> appointmentBinding = new HashMap<Appointment, Collection<Appointment>>(); for (Appointment appointment: appointments) { SortedSet<Appointment> appointmentSet = getAppointments(alloc, allAppointments ); boolean onlyFirstConflictingAppointment = false; Set<Appointment> conflictingAppointments = AppointmentImpl.getConflictingAppointments(appointmentSet, appointment, ignoreList, onlyFirstConflictingAppointment); appointmentBinding.put( appointment, conflictingAppointments); } result.put( alloc, appointmentBinding); } return result; } @Override public Date getNextAllocatableDate(Collection<Allocatable> allocatables,Appointment appointment, Collection<Reservation> ignoreList, Integer worktimeStartMinutes,Integer worktimeEndMinutes, Integer[] excludedDays, Integer rowsPerHour) throws RaplaException { checkConnected(); RemoteStorage serv = getRemoteStorage(); String[] allocatableIds = getIdList(allocatables); String[] reservationIds = getIdList(ignoreList); try { Date result = serv.getNextAllocatableDate(allocatableIds, (AppointmentImpl)appointment, reservationIds, worktimeStartMinutes, worktimeEndMinutes, excludedDays, rowsPerHour).get(); return result; } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } static private SortedSet<Appointment> getAppointments(Allocatable alloc, SortedSet<Appointment> allAppointments) { SortedSet<Appointment> result = new TreeSet<Appointment>(new AppointmentStartComparator()); for ( Appointment appointment:allAppointments) { Reservation reservation = appointment.getReservation(); if ( reservation.hasAllocated( alloc, appointment)) { result.add( appointment); } } return result; } @Override public Collection<Conflict> getConflicts(User user) throws RaplaException { checkConnected(); RemoteStorage serv = getRemoteStorage(); try { List<ConflictImpl> list = serv.getConflicts().get(); testResolve( list); setResolver( list); List<Conflict> result = new ArrayList<Conflict>(); Iterator it = list.iterator(); while ( it.hasNext()) { Object object = it.next(); if ( object instanceof Conflict) { Conflict next = (Conflict)object; result.add( next); } } return result; } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException(ex); } } // @Override // protected void logEntityNotFound(Entity obj, EntityNotFoundException ex) { // RemoteStorage serv = getRemoteStorage(); // Comparable id = ex.getId(); // try { // if ( obj instanceof ConflictImpl) // { // Iterable<String> referencedIds = ((ConflictImpl)obj).getReferencedIds(); // List<String> ids = new ArrayList<String>(); // for (String refId:referencedIds) // { // ids.add( refId); // } // serv.logEntityNotFound( id + " not found in conflict :",ids.toArray(new String[0])); // } // else if ( id != null ) // { // serv.logEntityNotFound("Not found", id.toString() ); // } // } catch (Exception e) { // getLogger().error("Can't call server logging for " + ex.getMessage() + " due to " + e.getMessage(), e); // } // } }
04900db4-rob
src/org/rapla/storage/dbrm/RemoteOperator.java
Java
gpl3
31,991
/*--------------------------------------------------------------------------* | Copyright (C) 2006 ?, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbrm; import javax.jws.WebParam; import javax.jws.WebService; import org.rapla.rest.gwtjsonrpc.common.FutureResult; import org.rapla.rest.gwtjsonrpc.common.RemoteJsonService; import org.rapla.rest.gwtjsonrpc.common.ResultType; import org.rapla.rest.gwtjsonrpc.common.VoidResult; @WebService public interface RemoteServer extends RemoteJsonService { @ResultType(LoginTokens.class) FutureResult<LoginTokens> login(@WebParam(name="username") String username,@WebParam(name="password") String password,@WebParam(name="connectAs") String connectAs); @ResultType(LoginTokens.class) FutureResult<LoginTokens> auth(@WebParam(name="credentials") LoginCredentials credentials); @ResultType(VoidResult.class) FutureResult<VoidResult> logout(); @ResultType(String.class) FutureResult<String> getRefreshToken(); @ResultType(String.class) FutureResult<String> regenerateRefreshToken(); @ResultType(String.class) FutureResult<LoginTokens> refresh(@WebParam(name="refreshToken") String refreshToken); void setConnectInfo(RemoteConnectionInfo info); }
04900db4-rob
src/org/rapla/storage/dbrm/RemoteServer.java
Java
gpl3
2,040
package org.rapla.storage.dbrm; public class LoginCredentials { private String username; private String password; private String connectAs; public LoginCredentials(String username, String password, String connectAs) { super(); this.username = username; this.password = password; this.connectAs = connectAs; } public String getUsername() { return username; } public String getPassword() { return password; } public String getConnectAs() { return connectAs; } }
04900db4-rob
src/org/rapla/storage/dbrm/LoginCredentials.java
Java
gpl3
571
package org.rapla.storage.dbrm; import org.rapla.rest.gwtjsonrpc.common.FutureResult; public class RemoteConnectionInfo { String accessToken; FutureResult<String> reAuthenticateCommand; String serverURL; StatusUpdater statusUpdater; public void setStatusUpdater(StatusUpdater statusUpdater) { this.statusUpdater = statusUpdater; } public StatusUpdater getStatusUpdater() { return statusUpdater; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public void setServerURL(String serverURL) { this.serverURL = serverURL; } public String get() { return serverURL; } public void setReAuthenticateCommand(FutureResult<String> reAuthenticateCommand) { this.reAuthenticateCommand = reAuthenticateCommand; } public String getRefreshToken() throws Exception { return reAuthenticateCommand.get(); } public FutureResult<String> getReAuthenticateCommand() { return reAuthenticateCommand; } public String getAccessToken() { return accessToken; } public String getServerURL() { return serverURL; } }
04900db4-rob
src/org/rapla/storage/dbrm/RemoteConnectionInfo.java
Java
gpl3
1,237
package org.rapla.storage.dbrm; import org.rapla.framework.RaplaContextException; public interface RemoteMethodStub { <T> T getWebserviceLocalStub(Class<T> role) throws RaplaContextException; }
04900db4-rob
src/org/rapla/storage/dbrm/RemoteMethodStub.java
Java
gpl3
206
package org.rapla.storage.dbrm; public interface StatusUpdater { enum Status { READY, BUSY } void setStatus( Status status); }
04900db4-rob
src/org/rapla/storage/dbrm/StatusUpdater.java
Java
gpl3
164
package org.rapla.storage.dbrm; import org.rapla.framework.RaplaException; public class WrongRaplaVersionException extends RaplaException { private static final long serialVersionUID = 1L; public WrongRaplaVersionException(String text) { super(text); } }
04900db4-rob
src/org/rapla/storage/dbrm/WrongRaplaVersionException.java
Java
gpl3
280
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbrm; import org.rapla.framework.RaplaContextException; /** provides a mechanism to invoke a remote service on the server. * The server must provide a RemoteService for the specified serviceName. * The RemoteOperator provides the Service RemoteServiceCaller * @request the webservices in the constructor instead. see RemoteOperator for an example*/ public interface RemoteServiceCaller { <T> T getRemoteMethod(Class<T> a ) throws RaplaContextException; }
04900db4-rob
src/org/rapla/storage/dbrm/RemoteServiceCaller.java
Java
gpl3
1,436
package org.rapla.storage.dbrm; import java.io.FileNotFoundException; import java.lang.reflect.Method; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.rapla.entities.DependencyException; import org.rapla.entities.EntityNotFoundException; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaSynchronizationException; import org.rapla.rest.client.HTTPJsonConnector; import org.rapla.rest.gwtjsonrpc.common.FutureResult; import org.rapla.rest.gwtjsonrpc.common.JSONParserWrapper; import org.rapla.rest.gwtjsonrpc.common.ResultImpl; import org.rapla.rest.gwtjsonrpc.common.ResultType; import org.rapla.storage.RaplaNewVersionException; import org.rapla.storage.RaplaSecurityException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class RaplaHTTPConnector extends HTTPJsonConnector { //private String clientVersion; public RaplaHTTPConnector() { // clientVersion = i18n.getString("rapla.version"); } private JsonArray serializeArguments(Class<?>[] parameterTypes, Object[] args) { final GsonBuilder gb = JSONParserWrapper.defaultGsonBuilder().disableHtmlEscaping(); JsonArray params = new JsonArray(); Gson serializer = gb.disableHtmlEscaping().create(); for ( int i=0;i< parameterTypes.length;i++) { Class<?> type = parameterTypes[i]; Object arg = args[i]; JsonElement jsonTree = serializer.toJsonTree(arg, type); params.add( jsonTree); } return params; } private Gson createJsonMapper() { Gson gson = JSONParserWrapper.defaultGsonBuilder().disableHtmlEscaping().create(); return gson; } private Object deserializeReturnValue(Class<?> returnType, JsonElement element) { Gson gson = createJsonMapper(); Object result = gson.fromJson(element, returnType); return result; } private List deserializeReturnList(Class<?> returnType, JsonArray list) { Gson gson = createJsonMapper(); List<Object> result = new ArrayList<Object>(); for (JsonElement element:list ) { Object obj = gson.fromJson(element, returnType); result.add( obj); } return result; } private Set deserializeReturnSet(Class<?> returnType, JsonArray list) { Gson gson = createJsonMapper(); Set<Object> result = new LinkedHashSet<Object>(); for (JsonElement element:list ) { Object obj = gson.fromJson(element, returnType); result.add( obj); } return result; } private Map deserializeReturnMap(Class<?> returnType, JsonObject map) { Gson gson = createJsonMapper(); Map<String,Object> result = new LinkedHashMap<String,Object>(); for (Entry<String, JsonElement> entry:map.entrySet() ) { String key = entry.getKey(); JsonElement element = entry.getValue(); Object obj = gson.fromJson(element, returnType); result.put(key,obj); } return result; } private RaplaException deserializeExceptionObject(JsonObject result) { JsonObject errorElement = result.getAsJsonObject("error"); JsonObject data = errorElement.getAsJsonObject("data"); JsonElement message = errorElement.get("message"); @SuppressWarnings("unused") JsonElement code = errorElement.get("code"); if ( data != null) { JsonArray paramObj = (JsonArray) data.get("params"); JsonElement jsonElement = data.get("exception"); JsonElement stacktrace = data.get("stacktrace"); if ( jsonElement != null) { String classname = jsonElement.getAsString(); List<String> params = new ArrayList<String>(); if ( paramObj != null) { for ( JsonElement param:paramObj) { params.add(param.toString()); } } RaplaException ex = deserializeException(classname, message.toString(), params); try { if ( stacktrace != null) { List<StackTraceElement> trace = new ArrayList<StackTraceElement>(); for (JsonElement element:stacktrace.getAsJsonArray()) { StackTraceElement ste = createJsonMapper().fromJson( element, StackTraceElement.class); trace.add( ste); } ex.setStackTrace( trace.toArray( new StackTraceElement[] {})); } } catch (Exception ex3) { // Can't get stacktrace } return ex; } } return new RaplaException( message.toString()); } private JsonObject sendCall_(String requestMethod, URL methodURL, JsonElement jsonObject, String authenticationToken) throws Exception { try { return sendCall(requestMethod, methodURL, jsonObject, authenticationToken); } catch (SocketException ex) { throw new RaplaConnectException( ex); } catch (UnknownHostException ex) { throw new RaplaConnectException( ex); } catch (FileNotFoundException ex) { throw new RaplaConnectException( ex); } } public FutureResult call(Class<?> service, String methodName, Object[] args,final RemoteConnectionInfo serverInfo) throws Exception { String serviceUrl =service.getName(); Method method = findMethod(service, methodName); String serverURL = serverInfo.getServerURL(); if ( !serverURL.endsWith("/")) { serverURL+="/"; } URL baseUrl = new URL(serverURL); URL methodURL = new URL(baseUrl,"rapla/json/" + serviceUrl ); boolean loginCmd = methodURL.getPath().endsWith("login") || methodName.contains("login"); JsonObject element = serializeCall(method, args); FutureResult<String> authExpiredCommand = serverInfo.getReAuthenticateCommand(); String accessToken = loginCmd ? null: serverInfo.getAccessToken(); JsonObject resultMessage = sendCall_("POST",methodURL, element, accessToken); JsonElement errorElement = resultMessage.get("error"); if ( errorElement != null) { RaplaException ex = deserializeExceptionObject(resultMessage); // if authorization expired String message = ex.getMessage(); boolean b = message != null && message.indexOf( RemoteStorage.USER_WAS_NOT_AUTHENTIFIED)>=0 && !loginCmd; if ( !b || authExpiredCommand == null ) { throw ex; } // try to get a new one String newAuthCode; try { newAuthCode = authExpiredCommand.get(); } catch (RaplaException e) { throw e; } catch (Exception e) { throw new RaplaException(e.getMessage(), e); } // try the same call again with the new result, this time with no auth code failed fallback resultMessage = sendCall_( "POST", methodURL, element, newAuthCode); } JsonElement resultElement = resultMessage.get("result"); Class resultType; Object resultObject; ResultType resultTypeAnnotation = method.getAnnotation(ResultType.class); if ( resultTypeAnnotation != null) { resultType = resultTypeAnnotation.value(); Class container = resultTypeAnnotation.container(); if ( List.class.equals(container) ) { if ( !resultElement.isJsonArray()) { throw new RaplaException("Array expected as json result in " + service + "." + methodName); } resultObject = deserializeReturnList(resultType, resultElement.getAsJsonArray()); } else if ( Set.class.equals(container) ) { if ( !resultElement.isJsonArray()) { throw new RaplaException("Array expected as json result in " + service + "." + methodName); } resultObject = deserializeReturnSet(resultType, resultElement.getAsJsonArray()); } else if ( Map.class.equals( container) ) { if ( !resultElement.isJsonObject()) { throw new RaplaException("JsonObject expected as json result in " + service + "." + methodName); } resultObject = deserializeReturnMap(resultType, resultElement.getAsJsonObject()); } else if ( Object.class.equals( container) ) { resultObject = deserializeReturnValue(resultType, resultElement); } else { throw new RaplaException("Array expected as json result in " + service + "." + methodName); } } else { resultType = method.getReturnType(); resultObject = deserializeReturnValue(resultType, resultElement); } @SuppressWarnings("unchecked") ResultImpl result = new ResultImpl(resultObject); return result; } public Method findMethod(Class<?> service, String methodName) throws RaplaException { Method method = null; for (Method m:service.getMethods()) { if ( m.getName().equals( methodName)) { method = m; } } if ( method == null) { throw new RaplaException("Method "+ methodName + " not found in " + service.getClass() ); } return method; } public JsonObject serializeCall(Method method, Object[] args) { Class<?>[] parameterTypes = method.getParameterTypes(); JsonElement params = serializeArguments(parameterTypes, args); JsonObject element = new JsonObject(); element.addProperty("jsonrpc", "2.0"); element.addProperty("method", method.getName()); element.add("params",params); element.addProperty("id", "1"); return element; } public RaplaException deserializeException(String classname, String message, List<String> params) { String error = ""; if ( message != null) { error+=message; } if ( classname != null) { if ( classname.equals( WrongRaplaVersionException.class.getName())) { return new WrongRaplaVersionException( message); } else if ( classname.equals(RaplaNewVersionException.class.getName())) { return new RaplaNewVersionException( message); } else if ( classname.equals( RaplaSecurityException.class.getName())) { return new RaplaSecurityException( message); } else if ( classname.equals( RaplaSynchronizationException.class.getName())) { return new RaplaSynchronizationException( message); } else if ( classname.equals( RaplaConnectException.class.getName())) { return new RaplaConnectException( message); } else if ( classname.equals( EntityNotFoundException.class.getName())) { // if ( param != null) // { // String id = (String)convertFromString( String.class, param); // return new EntityNotFoundException( message, id); // } return new EntityNotFoundException( message); } else if ( classname.equals( DependencyException.class.getName())) { if ( params != null) { return new DependencyException( message,params); } //Collection<String> depList = Collections.emptyList(); return new DependencyException( message, new String[] {}); } else { error = classname + " " + error; } } return new RaplaException( error); } // private void addParams(Appendable writer, Map<String,String> args ) throws IOException // { // writer.append( "v="+URLEncoder.encode(clientVersion,"utf-8")); // for (Iterator<String> it = args.keySet().iterator();it.hasNext();) // { // writer.append( "&"); // String key = it.next(); // String value= args.get( key); // { // String pair = key; // writer.append( pair); // if ( value != null) // { // writer.append("="+ URLEncoder.encode(value,"utf-8")); // } // } // // } // } }
04900db4-rob
src/org/rapla/storage/dbrm/RaplaHTTPConnector.java
Java
gpl3
13,145
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; 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.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.internal.UserImpl; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.ParentEntity; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.framework.Provider; public class LocalCache implements EntityResolver { Map<String,String> passwords = new HashMap<String,String>(); Map<String,Entity> entities; Map<String,DynamicTypeImpl> dynamicTypes; Map<String,UserImpl> users; Map<String,AllocatableImpl> resources; Map<String,ReservationImpl> reservations; private String clientUserId; public LocalCache() { entities = new HashMap<String,Entity>(); // top-level-entities reservations = new LinkedHashMap<String,ReservationImpl>(); users = new LinkedHashMap<String,UserImpl>(); resources = new LinkedHashMap<String,AllocatableImpl>(); dynamicTypes = new LinkedHashMap<String,DynamicTypeImpl>(); initSuperCategory(); } public String getClientUserId() { return clientUserId; } /** use this to prohibit reservations and preferences (except from system and current user) to be stored in the cache*/ public void setClientUserId(String clientUserId) { this.clientUserId = clientUserId; } /** @return true if the entity has been removed and false if the entity was not found*/ public boolean remove(Entity entity) { RaplaType raplaType = entity.getRaplaType(); boolean bResult = true; String entityId = entity.getId(); bResult = entities.remove(entityId) != null; Map<String,? extends Entity> entitySet = getMap(raplaType); if (entitySet != null) { if (entityId == null) return false; entitySet.remove( entityId ); } if ( entity instanceof ParentEntity) { Collection<Entity> subEntities = ((ParentEntity) entity).getSubEntities(); for (Entity child:subEntities) { remove( child); } } return bResult; } @SuppressWarnings("unchecked") private Map<String,Entity> getMap(RaplaType type) { if ( type == Reservation.TYPE) { return (Map)reservations; } if ( type == Allocatable.TYPE) { return (Map)resources; } if ( type == DynamicType.TYPE) { return (Map)dynamicTypes; } if ( type == User.TYPE) { return (Map)users; } return null; } public void put(Entity entity) { Assert.notNull(entity); RaplaType raplaType = entity.getRaplaType(); String id = entity.getId(); if (id == null) throw new IllegalStateException("ID can't be null"); String clientUserId = getClientUserId(); if ( clientUserId != null ) { if (raplaType == Reservation.TYPE || raplaType == Appointment.TYPE ) { throw new IllegalArgumentException("Can't store reservations or appointments in client cache"); } if (raplaType == Preferences.TYPE ) { String owner = ((PreferencesImpl)entity).getId("owner"); if ( owner != null && !owner.equals( clientUserId)) { throw new IllegalArgumentException("Can't store non system preferences for other users in client cache"); } } } // first remove the old children from the map Entity oldEntity = entities.get( entity); if (oldEntity != null && oldEntity instanceof ParentEntity) { Collection<Entity> subEntities = ((ParentEntity) oldEntity).getSubEntities(); for (Entity child:subEntities) { remove( child); } } entities.put(id,entity); Map<String,Entity> entitySet = getMap(raplaType); if (entitySet != null) { entitySet.put( entity.getId() ,entity); } else { //throw new RuntimeException("UNKNOWN TYPE. Can't store object in cache: " + entity.getRaplaType()); } // then put the new children if ( entity instanceof ParentEntity) { Collection<Entity> subEntities = ((ParentEntity) entity).getSubEntities(); for (Entity child:subEntities) { put( child); } } } public Entity get(Comparable id) { if (id == null) throw new RuntimeException("id is null"); return entities.get(id); } // @SuppressWarnings("unchecked") // private <T extends Entity> Collection<T> getCollection(RaplaType type) { // Map<String,? extends Entity> entities = entityMap.get(type); // // if (entities != null) { // return (Collection<T>) entities.values(); // } else { // throw new RuntimeException("UNKNOWN TYPE. Can't get collection: " // + type); // } // } // // @SuppressWarnings("unchecked") // private <T extends RaplaObject> Collection<T> getCollection(Class<T> clazz) { // RaplaType type = RaplaType.get(clazz); // Collection<T> collection = (Collection<T>) getCollection(type); // return new LinkedHashSet(collection); // } public void clearAll() { passwords.clear(); reservations.clear(); users.clear(); resources.clear(); dynamicTypes.clear(); entities.clear(); initSuperCategory(); } private void initSuperCategory() { CategoryImpl superCategory = new CategoryImpl(null, null); superCategory.setId(Category.SUPER_CATEGORY_ID); superCategory.setKey("supercategory"); superCategory.getName().setName("en", "Root"); entities.put (Category.SUPER_CATEGORY_ID, superCategory); Category[] childs = superCategory.getCategories(); for (int i=0;i<childs.length;i++) { superCategory.removeCategory( childs[i] ); } } public CategoryImpl getSuperCategory() { return (CategoryImpl) get(Category.SUPER_CATEGORY_ID); } public UserImpl getUser(String username) { for (UserImpl user:users.values()) { if (user.getUsername().equals(username)) return user; } for (UserImpl user:users.values()) { if (user.getUsername().equalsIgnoreCase(username)) return user; } return null; } public PreferencesImpl getPreferencesForUserId(String userId) { String preferenceId = PreferencesImpl.getPreferenceIdFromUser(userId); PreferencesImpl pref = (PreferencesImpl) tryResolve( preferenceId, Preferences.class); return pref; } public DynamicType getDynamicType(String elementKey) { for (DynamicType dt:dynamicTypes.values()) { if (dt.getKey().equals(elementKey)) return dt; } return null; } public List<Entity> getVisibleEntities(final User user) { List<Entity> result = new ArrayList<Entity>(); result.add( getSuperCategory()); result.addAll(getDynamicTypes()); result.addAll(getUsers()); for (Allocatable alloc: getAllocatables()) { if (user.isAdmin() || alloc.canReadOnlyInformation( user)) { result.add( alloc); } } // add system preferences { PreferencesImpl preferences = getPreferencesForUserId( null ); if ( preferences != null) { result.add( preferences); } } // add user preferences { String userId = user.getId(); Assert.notNull( userId); PreferencesImpl preferences = getPreferencesForUserId( userId ); if ( preferences != null) { result.add( preferences); } } return result; } // Implementation of EntityResolver @Override public Entity resolve(String id) throws EntityNotFoundException { return resolve(id, null); } public <T extends Entity> T resolve(String id,Class<T> entityClass) throws EntityNotFoundException { T entity = tryResolve(id, entityClass); SimpleEntity.checkResolveResult(id, entityClass, entity); return entity; } @Override public Entity tryResolve(String id) { return tryResolve(id, null); } @Override public <T extends Entity> T tryResolve(String id,Class<T> entityClass) { if (id == null) throw new RuntimeException("id is null"); Entity entity = entities.get(id); @SuppressWarnings("unchecked") T casted = (T) entity; return casted; } public String getPassword(String userId) { return passwords.get(userId); } public void putPassword(String userId, String password) { passwords.put(userId,password); } public void putAll( Collection<? extends Entity> list ) { for ( Entity entity: list) { put( entity); } } public Provider<Category> getSuperCategoryProvider() { return new Provider<Category>() { public Category get() { return getSuperCategory(); } }; } @SuppressWarnings("unchecked") public Collection<User> getUsers() { return (Collection)users.values(); } @SuppressWarnings("unchecked") public Collection<Allocatable> getAllocatables() { return (Collection)resources.values(); } @SuppressWarnings("unchecked") public Collection<Reservation> getReservations() { return (Collection)reservations.values(); } @SuppressWarnings("unchecked") public Collection<DynamicType> getDynamicTypes() { return (Collection)dynamicTypes.values(); } }
04900db4-rob
src/org/rapla/storage/LocalCache.java
Java
gpl3
11,990
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import org.rapla.entities.Category; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.RaplaObject; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Permission; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.entities.internal.CategoryImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class AllocatableWriter extends ClassifiableWriter { public AllocatableWriter(RaplaContext sm) throws RaplaException { super(sm); } public void printAllocatable(Allocatable allocatable) throws IOException,RaplaException { String tagName; DynamicType type = allocatable.getClassification().getType(); String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); if ( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON.equals(annotation)) { tagName = "rapla:person"; } else if( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE.equals(annotation)) { tagName = "rapla:resource"; } else if( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE.equals(annotation)) { tagName = "rapla:extension"; } else { throw new RaplaException("No or unknown classification type '" + annotation + "' set for " + allocatable.toString() + " ignoring "); } openTag(tagName); printId(allocatable); printOwner(allocatable); printTimestamp(allocatable ); closeTag(); printAnnotations( allocatable); printClassification(allocatable.getClassification()); Permission[] permissions = allocatable.getPermissions(); for ( int i = 0; i < permissions.length; i++ ){ printPermission(permissions[i]); } closeElement(tagName); } public void writeObject(RaplaObject object) throws IOException, RaplaException { printAllocatable( (Allocatable) object); } protected void printPermission(Permission p) throws IOException,RaplaException { openTag("rapla:permission"); if ( p.getUser() != null ) { att("user", getId( p.getUser() )); } else if ( p.getGroup() != null ) { att( "group", getGroupPath( p.getGroup() ) ); } if ( p.getMinAdvance() != null ) { att ( "min-advance", p.getMinAdvance().toString() ); } if ( p.getMaxAdvance() != null ) { att ( "max-advance", p.getMaxAdvance().toString() ); } if ( p.getStart() != null ) { att ( "start-date", dateTimeFormat.formatDate( p.getStart() ) ); } if ( p.getEnd() != null ) { att ( "end-date", dateTimeFormat.formatDate( p.getEnd() ) ); } if ( p.getAccessLevel() != Permission.ALLOCATE_CONFLICTS ) { att("access", Permission.ACCESS_LEVEL_NAMEMAP.get( p.getAccessLevel() ) ); } closeElementTag(); } private String getGroupPath( Category category) throws EntityNotFoundException { Category rootCategory = getSuperCategory().getCategory(Permission.GROUP_CATEGORY_KEY); return ((CategoryImpl) rootCategory ).getPathForCategory(category); } }
04900db4-rob
src/org/rapla/storage/xml/AllocatableWriter.java
Java
gpl3
4,421
package org.rapla.storage.xml; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import org.rapla.entities.Category; import org.rapla.entities.RaplaObject; 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.Period; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.DynamicType; public class RaplaEntityComparator implements Comparator<RaplaObject> { Map<RaplaType,Integer> ordering = new HashMap<RaplaType,Integer>(); public RaplaEntityComparator() { int i=0; ordering.put( Category.TYPE,new Integer(i++)); ordering.put( DynamicType.TYPE, new Integer(i++)); ordering.put( User.TYPE,new Integer(i++)); ordering.put( Allocatable.TYPE, new Integer(i++)); ordering.put( Preferences.TYPE,new Integer(i++) ); ordering.put( Period.TYPE, new Integer(i++) ); ordering.put( Reservation.TYPE,new Integer(i++)); } public int compare( RaplaObject o1, RaplaObject o2) { RaplaObject r1 = o1; RaplaObject r2 = o2; RaplaType t1 = r1.getRaplaType(); RaplaType t2 = r2.getRaplaType(); Integer ord1 = ordering.get( t1); Integer ord2 = ordering.get( t2); if ( o1 == o2) { return 0; } if ( ord1 != null && ord2 != null) { if (ord1.intValue()>ord2.intValue()) { return 1; } if (ord1.intValue()<ord2.intValue()) { return -1; } } if ( ord1 != null && ord2 == null) { return -1; } if ( ord2 != null && ord1 == null) { return 1; } if ( o1.hashCode() > o2.hashCode()) { return 1; } else { return -1; } } }
04900db4-rob
src/org/rapla/storage/xml/RaplaEntityComparator.java
Java
gpl3
2,110
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.LinkedHashMap; import org.rapla.entities.RaplaObject; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.framework.Configuration; import org.rapla.framework.ConfigurationException; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class RaplaConfigurationWriter extends RaplaXMLWriter { public RaplaConfigurationWriter(RaplaContext sm) throws RaplaException { super(sm); } public void writeObject(RaplaObject type) throws IOException, RaplaException { RaplaConfiguration raplaConfig = (RaplaConfiguration) type ; openElement("rapla:" + RaplaConfiguration.TYPE.getLocalName()); try { printConfiguration(raplaConfig ); } catch (ConfigurationException ex) { throw new RaplaException( ex ); } closeElement("rapla:" + RaplaConfiguration.TYPE.getLocalName()); } /** * Serialize each Configuration element. This method is called recursively. * Original code for this method is taken from the org.apache.framework.configuration.DefaultConfigurationSerializer class * @throws ConfigurationException if an error occurs * @throws IOException if an error occurs */ private void printConfiguration(final Configuration element ) throws ConfigurationException, RaplaException, IOException { LinkedHashMap<String, String> attr = new LinkedHashMap<String, String>(); String[] attrNames = element.getAttributeNames(); if( null != attrNames ) { for( int i = 0; i < attrNames.length; i++ ) { String key = attrNames[ i ]; String value = element.getAttribute( attrNames[ i ], "" ); attr.put( key, value); } } String qName = element.getName(); openTag(qName); att(attr); Configuration[] children = element.getChildren(); if (children.length > 0) { closeTag(); for( int i = 0; i < children.length; i++ ) { printConfiguration( children[ i ] ); } closeElement(qName); } else { String value = element.getValue( null ); if (null == value) { closeElementTag(); } else { closeTagOnLine(); print(value); closeElementOnLine(qName); println(); } } } }
04900db4-rob
src/org/rapla/storage/xml/RaplaConfigurationWriter.java
Java
gpl3
3,612
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.RaplaObject; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.framework.Configuration; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.internal.SAXConfigurationHandler; public class RaplaConfigurationReader extends RaplaXMLReader { boolean delegating = false; public RaplaConfigurationReader(RaplaContext context) throws RaplaException { super(context); } SAXConfigurationHandler configurationHandler = new SAXConfigurationHandler(); @Override public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts) throws RaplaSAXParseException { if ( RAPLA_NS.equals(namespaceURI) && localName.equals("config")) return; delegating = true; configurationHandler.startElement(namespaceURI,localName, atts); } @Override public void processEnd(String namespaceURI,String localName) throws RaplaSAXParseException { if ( RAPLA_NS.equals(namespaceURI) && localName.equals("config")) { return; } configurationHandler.endElement(namespaceURI, localName); delegating = false; } @Override public void processCharacters(char[] ch,int start,int length) { if ( delegating ){ configurationHandler.characters(ch,start,length); } } public RaplaObject getType() { return new RaplaConfiguration(getConfiguration()); } private Configuration getConfiguration() { Configuration conf = configurationHandler.getConfiguration(); return conf; } }
04900db4-rob
src/org/rapla/storage/xml/RaplaConfigurationReader.java
Java
gpl3
2,839
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.Date; import java.util.Map; import org.rapla.components.util.ParseDateException; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.Ownable; 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.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.AttributeImpl; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.framework.logger.Logger; import org.rapla.storage.IdCreator; import org.rapla.storage.impl.EntityStore; public class RaplaXMLReader extends DelegationHandler implements Namespaces { EntityStore store; Logger logger; IdCreator idTable; RaplaContext context; Map<String,RaplaType> localnameMap; Map<RaplaType,RaplaXMLReader> readerMap; SerializableDateTimeFormat dateTimeFormat; I18nBundle i18n; Date now; public static class TimestampDates { public Date createTime; public Date changeTime; } public RaplaXMLReader( RaplaContext context ) throws RaplaException { logger = context.lookup( Logger.class ); this.context = context; this.i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES); this.store = context.lookup( EntityStore.class); this.idTable = context.lookup( IdCreator.class ); RaplaLocale raplaLocale = context.lookup( RaplaLocale.class ); dateTimeFormat = raplaLocale.getSerializableFormat(); this.localnameMap = context.lookup( PreferenceReader.LOCALNAMEMAPENTRY ); this.readerMap = context.lookup( PreferenceReader.READERMAP ); now = new Date(); } public TimestampDates readTimestamps(RaplaSAXAttributes atts) throws RaplaSAXParseException { String createdAt = atts.getValue( "", "created-at"); String lastChanged = atts.getValue( "", "last-changed"); Date createTime = null; Date changeTime = createTime; if (createdAt != null) { createTime = parseTimestamp( createdAt); } else { createTime = now; } if (lastChanged != null) { changeTime = parseTimestamp( lastChanged); } else { changeTime = createTime; } if ( changeTime.after( now) ) { getLogger().warn("Last changed is in the future " +lastChanged + ". Taking current time as new timestamp."); changeTime = now; } if ( createTime.after( now) ) { getLogger().warn("Create time is in the future " +createTime + ". Taking current time as new timestamp."); createTime = now; } TimestampDates result = new TimestampDates(); result.createTime = createTime; result.changeTime = changeTime; return result; } public RaplaType getTypeForLocalName( String localName ) throws RaplaSAXParseException { RaplaType type = localnameMap.get( localName ); if (type == null) throw createSAXParseException( "No type declared for localname " + localName ); return type; } /** * @param raplaType * @throws RaplaSAXParseException */ protected RaplaXMLReader getChildHandlerForType( RaplaType raplaType ) throws RaplaSAXParseException { RaplaXMLReader childReader = readerMap.get( raplaType ); if (childReader == null) { throw createSAXParseException( "No Reader declared for type " + raplaType ); } addChildHandler( childReader ); return childReader; } protected Logger getLogger() { return logger; } public I18nBundle getI18n() { return i18n; } public Long parseLong( String text ) throws RaplaSAXParseException { try { return new Long( text ); } catch (NumberFormatException ex) { throw createSAXParseException( "No valid number format: " + text ); } } public Boolean parseBoolean( String text ) { return new Boolean( text ); } public Date parseDate( String date, boolean fillDate ) throws RaplaSAXParseException { try { return dateTimeFormat.parseDate( date, fillDate ); } catch (ParseDateException ex) { throw createSAXParseException( ex.getMessage() ); } } public Date parseDateTime( String date, String time ) throws RaplaSAXParseException { try { return dateTimeFormat.parseDateTime( date, time ); } catch (ParseDateException ex) { throw createSAXParseException( ex.getMessage() ); } } public Date parseTimestamp( String timestamp ) throws RaplaSAXParseException { try { return dateTimeFormat.parseTimestamp(timestamp); } catch (ParseDateException ex) { throw createSAXParseException( ex.getMessage() ); } } protected String getString( RaplaSAXAttributes atts, String key, String defaultString ) { String str = atts.getValue( "", key ); return (str != null) ? str : defaultString; } protected String getString( RaplaSAXAttributes atts, String key ) throws RaplaSAXParseException { String str = atts.getValue( "", key ); if (str == null) throw createSAXParseException( "Attribute " + key + " not found!" ); return str; } /** return the new id */ protected String setId( Entity entity, RaplaSAXAttributes atts ) throws RaplaSAXParseException { String idString = atts.getValue( "id" ); String id = getId( entity.getRaplaType(), idString ); ((SimpleEntity)entity).setId( id ); return id; } /** return the new id */ protected Object setNewId( Entity entity ) throws RaplaSAXParseException { try { String id = idTable.createId( entity.getRaplaType() ); ((SimpleEntity)entity).setId( id ); return id; } catch (RaplaException ex) { throw createSAXParseException( ex.getMessage() ); } } protected <T extends SimpleEntity&Ownable> void setOwner( T ownable, RaplaSAXAttributes atts ) throws RaplaSAXParseException { String ownerString = atts.getValue( "owner" ); if (ownerString != null) { ownable.putId("owner", getId( User.TYPE, ownerString ) ); } // No else case as no owner should still be possible and there should be no default owner } protected void setLastChangedBy(SimpleEntity entity, RaplaSAXAttributes atts) { String lastChangedBy = atts.getValue( "last-changed-by"); if ( lastChangedBy != null) { try { User user = resolve(User.TYPE,lastChangedBy ); entity.setLastChangedBy( user ); } catch (RaplaSAXParseException ex) { getLogger().warn("Can't find user " + lastChangedBy + " in entity " + entity.getId()); } } } @SuppressWarnings("deprecation") protected String getId( RaplaType type, String str ) throws RaplaSAXParseException { try { final String id; if ( str.equals(Category.SUPER_CATEGORY_ID)) { id = Category.SUPER_CATEGORY_ID; } else if (org.rapla.storage.OldIdMapping.isTextId(type, str)) { id = idTable.createId(type, str); } else { id = str; } return id; } catch (RaplaException ex) { ex.printStackTrace(); throw createSAXParseException( ex.getMessage() ); } } void throwEntityNotFound( String type, Integer id ) throws RaplaSAXParseException { throw createSAXParseException( type + " with id '" + id + "' not found." ); } public RaplaObject getType() throws RaplaSAXParseException { throw createSAXParseException( "Method getType() not implemented by subclass " + this.getClass().getName() ); } protected CategoryImpl getSuperCategory() { return store.getSuperCategory(); } public DynamicType getDynamicType( String keyref ) { return store.getDynamicType( keyref); } protected <T extends Entity> T resolve( RaplaType<T> type, String str ) throws RaplaSAXParseException { try { String id = getId( type, str ); Class<T> typeClass = type.getTypeClass(); T resolved = store.resolve( id, typeClass ); return resolved; } catch (EntityNotFoundException ex) { throw createSAXParseException(ex.getMessage() , ex); } } protected Object parseAttributeValue( Attribute attribute, String text ) throws RaplaSAXParseException { try { AttributeType type = attribute.getType(); if ( type == AttributeType.CATEGORY ) { text = getId(Category.TYPE, text); } else if ( type == AttributeType.ALLOCATABLE ) { text = getId(Allocatable.TYPE, text); } return AttributeImpl.parseAttributeValue( attribute, text); } catch (RaplaException ex) { throw createSAXParseException( ex.getMessage() ); } } public void add(Entity entity) throws RaplaSAXParseException{ if ( entity instanceof Classifiable) { if ((( Classifiable) entity).getClassification() == null) { throw createSAXParseException("Classification can't be null"); } } store.put(entity); } protected Category getCategoryFromPath( String path ) throws RaplaSAXParseException { try { return getSuperCategory().getCategoryFromPath( path ); } catch (Exception ex) { throw createSAXParseException( ex.getMessage() ); } } protected Category getGroup(String groupKey) throws RaplaSAXParseException{ CategoryImpl groupCategory = (CategoryImpl) getSuperCategory().getCategory( Permission.GROUP_CATEGORY_KEY ); if (groupCategory == null) { throw createSAXParseException( Permission.GROUP_CATEGORY_KEY + " category not found" ); } try { return groupCategory.getCategoryFromPath( groupKey ); } catch (Exception ex) { throw createSAXParseException( ex.getMessage(),ex ); } } protected void putPassword( String userid, String password ) { store.putPassword( userid, password); } protected void setCurrentTranslations(MultiLanguageName name) { String lang = i18n.getLang(); boolean contains = name.getAvailableLanguages().contains( lang); if (!contains) { try { String translation = i18n.getString( name.getName("en")); name.setName( lang, translation); } catch (Exception ex) { } } } static public String wrapRaplaDataTag(String xml) { StringBuilder dataElement = new StringBuilder(); dataElement.append("<rapla:data "); for (int i=0;i<RaplaXMLWriter.NAMESPACE_ARRAY.length;i++) { String prefix = RaplaXMLWriter.NAMESPACE_ARRAY[i][1]; String uri = RaplaXMLWriter.NAMESPACE_ARRAY[i][0]; if ( prefix == null) { dataElement.append("xmlns="); } else { dataElement.append("xmlns:" + prefix + "="); } dataElement.append("\""); dataElement.append( uri ); dataElement.append("\" "); } dataElement.append(">"); dataElement.append( xml ); dataElement.append( "</rapla:data>"); String xmlWithNamespaces = dataElement.toString(); return xmlWithNamespaces; } }
04900db4-rob
src/org/rapla/storage/xml/RaplaXMLReader.java
Java
gpl3
13,976
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import org.rapla.components.util.Assert; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.Annotatable; import org.rapla.entities.Category; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.AttributeImpl; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class DynamicTypeReader extends RaplaXMLReader { DynamicTypeImpl dynamicType; MultiLanguageName currentName = null; String currentLang = null; String constraintKey = null; AttributeImpl attribute = null; String annotationKey = null; boolean isAttributeActive = false; boolean isDynamictypeActive = false; HashMap<String,String> typeAnnotations = new LinkedHashMap<String,String>(); HashMap<String,String> attributeAnnotations = new LinkedHashMap<String,String>(); private HashMap<String, Map<Attribute,String>> unresolvedDynamicTypeConstraints = new HashMap<String, Map<Attribute,String>>(); public DynamicTypeReader( RaplaContext context ) throws RaplaException { super( context ); unresolvedDynamicTypeConstraints.clear(); } @Override public void processElement( String namespaceURI, String localName, RaplaSAXAttributes atts ) throws RaplaSAXParseException { if (localName.equals( "element" )) { String qname = getString( atts, "name" ); String name = qname.substring( qname.indexOf( ":" ) + 1 ); Assert.notNull( name ); //System.out.println("NAME: " + qname + " Level " + level + " Entry " + entryLevel); if (!isDynamictypeActive) { isDynamictypeActive = true; typeAnnotations.clear(); TimestampDates ts = readTimestamps( atts); dynamicType = new DynamicTypeImpl(ts.createTime, ts.changeTime); if (atts.getValue( "id" )!=null) { setId( dynamicType, atts ); } else { setNewId( dynamicType ); } currentName = dynamicType.getName(); dynamicType.setKey( name ); // because the dynamic types refered in the constraints could be loaded after their first reference we resolve all prior unresolved constraint bindings to that type when the type is loaded Map<Attribute,String> constraintMap = unresolvedDynamicTypeConstraints.get( name ); if ( constraintMap != null) { for (Map.Entry<Attribute,String> entry: constraintMap.entrySet()) { Attribute att = entry.getKey(); String constraintKey = entry.getValue(); // now set the unresolved constraint, we need to ignore readonly check, because the type may be already closed ((AttributeImpl)att).setContraintWithoutWritableCheck(constraintKey, dynamicType); } } unresolvedDynamicTypeConstraints.remove( name); } else { isAttributeActive = true; attribute = new AttributeImpl(); currentName = attribute.getName(); attribute.setKey( name ); Assert.notNull( name, "key attribute cannot be null" ); if (atts.getValue("id") != null) { setId( attribute, atts ); } else { setNewId( attribute ); } attributeAnnotations.clear(); } } if (localName.equals( "constraint" ) && namespaceURI.equals( RAPLA_NS )) { constraintKey = atts.getValue( "name" ); startContent(); } if (localName.equals( "default" )) { startContent(); } // if no attribute type is set if (localName.equals( "data" ) && namespaceURI.equals( RELAXNG_NS ) && attribute.getType().equals( AttributeImpl.DEFAULT_TYPE )) { String typeName = atts.getValue( "type" ); if (typeName == null) throw createSAXParseException( "element relax:data is requiered!" ); AttributeType type = AttributeType.findForString( typeName ); if (type == null) { getLogger().error( "AttributeType '" + typeName + "' not found. Using string."); type = AttributeType.STRING; } attribute.setType( type ); } if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS )) { annotationKey = atts.getValue( "key" ); Assert.notNull( annotationKey, "key attribute cannot be null" ); startContent(); } if (localName.equals( "name" ) && namespaceURI.equals( ANNOTATION_NS )) { startContent(); currentLang = atts.getValue( "lang" ); Assert.notNull( currentLang ); } } private void addAnnotations( Annotatable annotatable, Map<String,String> annotations ) { for (Iterator<Map.Entry<String,String>> it = annotations.entrySet().iterator(); it.hasNext();) { Map.Entry<String,String> entry = it.next(); String key = entry.getKey(); String annotation = entry.getValue(); try { annotatable.setAnnotation( key, annotation ); } catch (IllegalAnnotationException e) { getLogger().error("Can't parse annotation " + e.getMessage(), e); //throw createSAXParseException( e.getMessage() ); } } } @Override public void processEnd( String namespaceURI, String localName ) throws RaplaSAXParseException { if (localName.equals( "element" )) { if (!isAttributeActive) { addAnnotations( dynamicType, typeAnnotations ); setCurrentTranslations(dynamicType.getName()); dynamicType.setResolver( store); add( dynamicType ); // We ensure the dynamic type is not modified anymore dynamicType.setReadOnly( ); isDynamictypeActive = false; } else { addAnnotations( attribute, attributeAnnotations ); //System.out.println("Adding attribute " + attribute + " to " + dynamicType); setCurrentTranslations(attribute.getName()); dynamicType.addAttribute( attribute ); add( attribute ); isAttributeActive = false; } } else if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS )) { String annotationValue = readContent().trim(); if (isAttributeActive) { attributeAnnotations.put( annotationKey, annotationValue ); } else { typeAnnotations.put( annotationKey, annotationValue ); } } else if (localName.equals( "optional" ) && namespaceURI.equals( RELAXNG_NS )) { attribute.setOptional( true ); } else if (localName.equals( "name" ) && namespaceURI.equals( ANNOTATION_NS )) { Assert.notNull( currentName ); currentName.setName( currentLang, readContent() ); } else if (localName.equals( "constraint" ) && namespaceURI.equals( RAPLA_NS )) { String content = readContent().trim(); Object constraint = null; if (attribute.getConstraintClass( constraintKey ) == Category.class) { @SuppressWarnings("deprecation") boolean idContent = org.rapla.storage.OldIdMapping.isTextId(Category.TYPE, content ); if (idContent) { String id = getId( Category.TYPE, content ); constraint = store.tryResolve( id, Category.class ); if ( constraint == null) { getLogger().error("Can't resolve root category for " + dynamicType.getKey() + "." + attribute.getKey() + " id is " + id + " (" + content + ")"); } } else { constraint = getCategoryFromPath( content ); } } else if (attribute.getConstraintClass( constraintKey ) == DynamicType.class) { @SuppressWarnings("deprecation") boolean idContent = org.rapla.storage.OldIdMapping.isTextId( DynamicType.TYPE, content ); if (idContent) { constraint = content.trim(); } else { String elementKey = content; // check if the dynamic type refers to itself if (elementKey.equals( dynamicType.getKey())) { constraint = dynamicType; } else { // this only works if the dynamic type is already loaded constraint = getDynamicType(elementKey); // so we cache the contraint attributes in a map to be filled when the types are loaded if (constraint == null) { Map<Attribute,String> collection = unresolvedDynamicTypeConstraints.get( elementKey); if ( collection == null) { collection = new HashMap<Attribute,String>(); unresolvedDynamicTypeConstraints.put( elementKey, collection); } collection.put( attribute, constraintKey); } } } } else if (attribute.getConstraintClass( constraintKey ) == Integer.class) { constraint = parseLong( content ); } else if (attribute.getConstraintClass( constraintKey ) == Boolean.class) { constraint = parseBoolean( content ); } else { constraint = content; } attribute.setConstraint( constraintKey, constraint ); } if (localName.equals( "default" ) && namespaceURI.equals( RAPLA_NS )) { String content = readContent().trim(); final Object defaultValue; final AttributeType type = attribute.getType(); if (type == AttributeType.CATEGORY) { @SuppressWarnings("deprecation") boolean idContent = org.rapla.storage.OldIdMapping.isTextId(Category.TYPE, content ); if (idContent) { defaultValue = resolve( Category.TYPE, content ); } else { defaultValue = getCategoryFromPath( content ); } } else { Object value; try { value = parseAttributeValue(attribute, content); } catch (RaplaException e) { value = null; } defaultValue = value; } attribute.setDefaultValue(defaultValue ); } } }
04900db4-rob
src/org/rapla/storage/xml/DynamicTypeReader.java
Java
gpl3
13,364
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.Collection; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; class ClassifiableWriter extends RaplaXMLWriter { public ClassifiableWriter(RaplaContext sm) throws RaplaException { super(sm); } protected void printClassification(Classification classification) throws IOException,RaplaException { if (classification == null) return; DynamicType dynamicType = classification.getType(); boolean internal = ((DynamicTypeImpl)dynamicType).isInternal(); String namespacePrefix = internal ? "ext:" : "dynatt:"; String elementKey = dynamicType.getKey(); if ( internal ) { if (!elementKey.startsWith("rapla:")) { throw new RaplaException("keys for internal type must start with rapla:"); } elementKey = elementKey.substring("rapla:".length() ); } else { if (elementKey.startsWith("rapla:")) { throw new RaplaException("keys for non internal type can't start with rapla:"); } } String elementName = namespacePrefix + elementKey; Attribute[] attributes = classification.getAttributes(); if ( attributes.length == 0) { openTag(elementName); } else { openElement(elementName); } for (int i=0;i<attributes.length;i++) { Attribute attribute = attributes[i]; Collection<?> values = classification.getValues(attribute); for ( Object value:values) { String attributeName = namespacePrefix + attribute.getKey(); openElementOnLine(attributeName); printAttributeValue(attribute, value); closeElementOnLine(attributeName); println(); } } if ( attributes.length == 0) { closeElementTag(); } else { closeElement(elementName); } } }
04900db4-rob
src/org/rapla/storage/xml/ClassifiableWriter.java
Java
gpl3
3,106
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.Iterator; import java.util.Map; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.configuration.RaplaMap; import org.rapla.entities.configuration.internal.RaplaMapImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class RaplaMapWriter extends RaplaXMLWriter { public RaplaMapWriter(RaplaContext sm) throws RaplaException { super(sm); } public void writeObject(RaplaObject type) throws IOException, RaplaException { writeMap_((RaplaMapImpl) type ); } private void writeMap_(RaplaMapImpl map ) throws IOException, RaplaException { openElement("rapla:" + RaplaMap.TYPE.getLocalName()); for (Iterator<String> it = map.keySet().iterator();it.hasNext();) { Object key = it.next(); Object obj = map.get( key); printEntityReference( key, obj); } closeElement("rapla:" + RaplaMap.TYPE.getLocalName()); } public void writeMap(Map<String,String> map ) throws IOException { openElement("rapla:" + RaplaMap.TYPE.getLocalName()); for (Map.Entry<String,String> entry:map.entrySet()) { String key = entry.getKey(); String obj = entry.getValue(); openTag("rapla:mapentry"); att("key", key.toString()); if ( obj instanceof String) { String value = (String) obj; att("value", value); closeElementTag(); } } closeElement("rapla:" + RaplaMap.TYPE.getLocalName()); } private void printEntityReference(Object key,Object obj) throws RaplaException, IOException { if (obj == null) { getLogger().warn( "Map contains empty value under key " + key ); return; } int start = getIndentLevel(); openTag("rapla:mapentry"); att("key", key.toString()); if ( obj instanceof String) { String value = (String) obj; att("value", value); closeElementTag(); return; } closeTag(); if ( obj instanceof Entity ) { printReference( (Entity) obj); } else { RaplaObject raplaObj = (RaplaObject) obj; getWriterFor( raplaObj.getRaplaType()).writeObject( raplaObj ); } setIndentLevel( start+1 ); closeElement("rapla:mapentry"); setIndentLevel( start ); } }
04900db4-rob
src/org/rapla/storage/xml/RaplaMapWriter.java
Java
gpl3
3,586
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import org.rapla.entities.Category; import org.rapla.entities.RaplaObject; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class CategoryWriter extends RaplaXMLWriter { public CategoryWriter(RaplaContext sm) throws RaplaException { super(sm); } public void printRaplaType(RaplaObject type) throws RaplaException, IOException { printCategory( (Category) type); } public void printCategory(Category category) throws IOException,RaplaException { printCategory( category, true); } public void printCategory(Category category,boolean printSubcategories) throws IOException,RaplaException { openTag("rapla:category"); printTimestamp( category); if (isPrintId()) { printId(category); Category parent = category.getParent(); if ( parent != null) { att("parentid", getId( parent)); } } att("key",category.getKey()); closeTag(); printTranslation(category.getName()); printAnnotations( category, false); if ( printSubcategories ) { Category[] categories = category.getCategories(); for (int i=0;i<categories.length;i++) printCategory(categories[i]); } closeElement("rapla:category"); } public void writeObject(RaplaObject persistant) throws RaplaException, IOException { printCategory( (Category) persistant, false); } }
04900db4-rob
src/org/rapla/storage/xml/CategoryWriter.java
Java
gpl3
2,569
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import org.rapla.components.util.Assert; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.Annotatable; import org.rapla.entities.Category; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.User; import org.rapla.entities.domain.Permission; import org.rapla.entities.domain.ResourceAnnotations; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.domain.internal.PermissionImpl; import org.rapla.entities.storage.internal.ReferenceHandler; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class AllocatableReader extends RaplaXMLReader { private DynAttReader dynAttHandler; private AllocatableImpl allocatable; private String annotationKey; private Annotatable currentAnnotatable; public AllocatableReader( RaplaContext context ) throws RaplaException { super( context ); dynAttHandler = new DynAttReader( context ); addChildHandler( dynAttHandler ); } @Override public void processElement( String namespaceURI, String localName, RaplaSAXAttributes atts ) throws RaplaSAXParseException { if (namespaceURI.equals( DYNATT_NS ) || namespaceURI.equals( EXTENSION_NS )) { if ( localName.equals("rapla:crypto")) { return; } dynAttHandler.setClassifiable( allocatable ); delegateElement( dynAttHandler, namespaceURI, localName, atts ); return; } if (!namespaceURI.equals( RAPLA_NS )) return; if (localName.equals( "permission" )) { PermissionImpl permission = new PermissionImpl(); permission.setResolver( store ); // process user String userString = atts.getValue( "user" ); ReferenceHandler referenceHandler = permission.getReferenceHandler(); if (userString != null) { referenceHandler.putId("user", getId(User.TYPE,userString)); } // process group String groupId = atts.getValue( "groupidref" ); if (groupId != null) { referenceHandler.putId("group", getId(Category.TYPE,groupId)); } else { String groupName = atts.getValue( "group" ); if (groupName != null) { Category group= getGroup( groupName); permission.setGroup( group); } } String startDate = getString( atts, "start-date", null ); if (startDate != null) { permission.setStart( parseDate( startDate, false ) ); } String endDate = getString( atts, "end-date", null ); if (endDate != null) { permission.setEnd( parseDate( endDate, false ) ); } String minAdvance = getString( atts, "min-advance", null ); if (minAdvance != null) { permission.setMinAdvance( parseLong( minAdvance ).intValue() ); } String maxAdvance = getString( atts, "max-advance", null ); if (maxAdvance != null) { permission.setMaxAdvance( parseLong( maxAdvance ).intValue() ); } String accessLevel = getString( atts, "access", Permission.ACCESS_LEVEL_NAMEMAP.get( Permission.ALLOCATE_CONFLICTS ) ); Integer matchingLevel = Permission.ACCESS_LEVEL_NAMEMAP.findAccessLevel( accessLevel ); if (matchingLevel == null) { throw createSAXParseException( "Unknown access level '" + accessLevel + "'" ); } permission.setAccessLevel( matchingLevel ); allocatable.addPermission( permission ); } else if (localName.equals( "annotation" ) ) { annotationKey = atts.getValue( "key" ); Assert.notNull( annotationKey, "key attribute cannot be null" ); startContent(); } else { TimestampDates ts = readTimestamps( atts); allocatable = new AllocatableImpl(ts.createTime, ts.changeTime); allocatable.setResolver( store ); currentAnnotatable = allocatable; setId( allocatable, atts ); // support old holdback conflicts behaviour { String holdBackString = getString( atts, "holdbackconflicts", "false" ); if ( Boolean.valueOf( holdBackString ) ) { try { allocatable.setAnnotation(ResourceAnnotations.KEY_CONFLICT_CREATION, ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE); } catch (IllegalAnnotationException e) { throw createSAXParseException(e.getMessage(),e); } } } setLastChangedBy(allocatable, atts); setOwner(allocatable, atts); } } @Override public void processEnd( String namespaceURI, String localName ) throws RaplaSAXParseException { if (!namespaceURI.equals( RAPLA_NS )) return; if (localName.equals( "resource" ) || localName.equals( "person" ) ) { if (allocatable.getPermissions().length == 0) allocatable.addPermission( new PermissionImpl() ); add( allocatable ); } else if (localName.equals( "extension" ) ) { if ( allocatable.getClassification() != null) { add( allocatable ); } } else if (localName.equals( "annotation" ) ) { try { String annotationValue = readContent().trim(); currentAnnotatable.setAnnotation( annotationKey, annotationValue ); } catch (IllegalAnnotationException ex) { } } } }
04900db4-rob
src/org/rapla/storage/xml/AllocatableReader.java
Java
gpl3
7,231
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.Map; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; public class PreferenceReader extends RaplaXMLReader { public static final TypedComponentRole<Map<String,RaplaType>> LOCALNAMEMAPENTRY = new TypedComponentRole<Map<String,RaplaType>>("org.rapla.storage.xml.localnameMap"); public static final TypedComponentRole<Map<RaplaType,RaplaXMLReader>> READERMAP = new TypedComponentRole<Map<RaplaType,RaplaXMLReader>>("org.rapla.storage.xml.readerMap"); PreferencesImpl preferences; String configRole; User owner; RaplaXMLReader childReader; String stringValue = null; public PreferenceReader(RaplaContext sm) throws RaplaException { super(sm); } public void setUser( User owner) { this.owner = owner; } @Override public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts) throws RaplaSAXParseException { if ( RAPLA_NS.equals(namespaceURI) && localName.equals("data")) { return; } if (localName.equals("preferences")) { TimestampDates ts = readTimestamps(atts); preferences = new PreferencesImpl(ts.createTime, ts.changeTime); preferences.setResolver( store); if ( owner == null ) { preferences.setId( Preferences.SYSTEM_PREFERENCES_ID); } else { preferences.setOwner( owner ); preferences.setId( Preferences.ID_PREFIX + owner.getId()); } return; } if (localName.equals("entry")) { configRole = getString(atts,"key"); stringValue = getString(atts,"value", null); // ignore old entry if ( stringValue != null) { preferences.putEntryPrivate( configRole,stringValue ); } return; } RaplaType raplaTypeName = getTypeForLocalName(localName ); childReader = getChildHandlerForType( raplaTypeName ); delegateElement(childReader,namespaceURI,localName,atts); } public Preferences getPreferences() { return preferences; } public RaplaObject getChildType() throws RaplaSAXParseException { return childReader.getType(); } @Override public void processEnd(String namespaceURI,String localName) throws RaplaSAXParseException { if (!namespaceURI.equals(RAPLA_NS)) return; if (localName.equals("preferences")) { add(preferences); } if (localName.equals("entry") && stringValue == null) { RaplaObject type = childReader.getType(); preferences.putEntryPrivate(configRole, type); } } }
04900db4-rob
src/org/rapla/storage/xml/PreferenceReader.java
Java
gpl3
4,237
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.configuration.RaplaMap; import org.rapla.entities.configuration.internal.RaplaMapImpl; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class RaplaMapReader extends RaplaXMLReader { String key; RaplaMapImpl entityMap; RaplaXMLReader childReader; public RaplaMapReader(RaplaContext sm) throws RaplaException { super(sm); } @Override public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts) throws RaplaSAXParseException { if ( !RAPLA_NS.equals(namespaceURI)) return; if (localName.equals(RaplaMap.TYPE.getLocalName())) { entityMap = new RaplaMapImpl(); return; } if (localName.equals("mapentry")) { key= getString(atts, "key"); String value = getString( atts, "value", null); if ( value != null) { try { entityMap.putPrivate( key, value ); } catch (ClassCastException ex) { getLogger().error("Mixed maps are currently not supported.", ex); } } return; } String refid = getString( atts, "idref", null); String keyref = getString( atts, "keyref", null); RaplaType raplaType = getTypeForLocalName( localName ); if ( refid != null) { childReader = null; // We ignore the old references from 1.7 if ( entityMap.isTypeSupportedAsLink(raplaType)) { return; } String id = getId( raplaType, refid); entityMap.putIdPrivate( key, id, raplaType); } else if ( keyref != null) { childReader = null; DynamicType type = getDynamicType( keyref ); if ( type != null) { String id = ((Entity) type).getId(); entityMap.putIdPrivate( key, id, DynamicType.TYPE); } } else { childReader = getChildHandlerForType( raplaType ); delegateElement( childReader, namespaceURI, localName, atts); } } @Override public void processEnd(String namespaceURI,String localName) throws RaplaSAXParseException { if ( !RAPLA_NS.equals(namespaceURI) ) return; if ( childReader != null ) { RaplaObject type = childReader.getType(); try { entityMap.putPrivate( key, type); } catch (ClassCastException ex) { getLogger().error("Mixed maps are currently not supported.", ex); } } childReader = null; } public RaplaMap getEntityMap() { return entityMap; } public RaplaObject getType() { //reservation.getReferenceHandler().put() return getEntityMap(); } }
04900db4-rob
src/org/rapla/storage/xml/RaplaMapReader.java
Java
gpl3
4,233
/*--------------------------------------------------------------------------* | | | 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.xml; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.rapla.components.util.Assert; import org.rapla.components.util.TimeInterval; import org.rapla.entities.Category; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.storage.LocalCache; /** Stores the data from the local cache in XML-format to a print-writer.*/ public class RaplaMainWriter extends RaplaXMLWriter { protected final static String OUTPUT_FILE_VERSION="1.1"; String encoding = "utf-8"; protected LocalCache cache; public RaplaMainWriter(RaplaContext context, LocalCache cache) throws RaplaException { super(context); this.cache = cache; Assert.notNull(cache); } public void setWriter( Appendable writer ) { super.setWriter( writer ); for ( RaplaXMLWriter xmlWriter: writerMap.values()) { xmlWriter.setWriter( writer ); } } public void setEncoding(String encoding) { this.encoding = encoding; } public void printContent() throws IOException,RaplaException { printHeader( 0, null, false ); printCategories(); println(); printDynamicTypes(); println(); ((PreferenceWriter)getWriterFor(Preferences.TYPE)).printPreferences( cache.getPreferencesForUserId( null )); println(); printUsers(); println(); printAllocatables(); println(); printReservations(); println(); closeElement("rapla:data"); } public void printDynamicTypes() throws IOException,RaplaException { openElement("relax:grammar"); DynamicTypeWriter dynamicTypeWriter = (DynamicTypeWriter)getWriterFor(DynamicType.TYPE); for( DynamicType type:cache.getDynamicTypes()) { if ((( DynamicTypeImpl) type).isInternal()) { continue; } dynamicTypeWriter.printDynamicType(type); println(); } printStartPattern(); closeElement("relax:grammar"); } private void printStartPattern() throws IOException { openElement("relax:start"); openElement("relax:choice"); for( DynamicType type:cache.getDynamicTypes()) { if ((( DynamicTypeImpl) type).isInternal()) { continue; } openTag("relax:ref"); att("name",type.getKey()); closeElementTag(); } closeElement("relax:choice"); closeElement("relax:start"); } public void printCategories() throws IOException,RaplaException { openElement("rapla:categories"); CategoryWriter categoryWriter = (CategoryWriter)getWriterFor(Category.TYPE); Category[] categories = cache.getSuperCategory().getCategories(); for (int i=0;i<categories.length;i++) { categoryWriter.printCategory(categories[i]); } closeElement("rapla:categories"); } public void printUsers() throws IOException,RaplaException { openElement("rapla:users"); UserWriter userWriter = (UserWriter)getWriterFor(User.TYPE); println("<!-- Users of the system -->"); for (User user:cache.getUsers()) { String userId = user.getId(); PreferencesImpl preferences = cache.getPreferencesForUserId( userId); String password = cache.getPassword(userId); userWriter.printUser( user, password, preferences); } closeElement("rapla:users"); } public void printAllocatables() throws IOException,RaplaException { openElement("rapla:resources"); println("<!-- resources -->"); // Print all resources that are not persons AllocatableWriter allocatableWriter = (AllocatableWriter)getWriterFor(Allocatable.TYPE); Collection<Allocatable> allAllocatables = cache.getAllocatables(); Map<String,List<Allocatable>> map = new LinkedHashMap<String,List<Allocatable>>(); for (DynamicType type:cache.getDynamicTypes()) { map.put( type.getId(), new ArrayList<Allocatable>()); } for (Allocatable allocatable:allAllocatables) { Classification classification = allocatable.getClassification(); String id = classification.getType().getId(); List<Allocatable> list = map.get( id); list.add( allocatable); } // Print all Persons for ( String id : map.keySet()) { List<Allocatable> list = map.get( id); for (Allocatable allocatable:list) { allocatableWriter.printAllocatable(allocatable); } } println(); closeElement("rapla:resources"); } void printReservations() throws IOException, RaplaException { openElement("rapla:reservations"); ReservationWriter reservationWriter = (ReservationWriter)getWriterFor(Reservation.TYPE); for (Reservation reservation: cache.getReservations()) { reservationWriter.printReservation( reservation ); } closeElement("rapla:reservations"); } private void printHeader(long repositoryVersion, TimeInterval invalidateInterval, boolean resourcesRefresh) throws IOException { println("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?><!--*- coding: " + encoding + " -*-->"); openTag("rapla:data"); for (int i=0;i<NAMESPACE_ARRAY.length;i++) { String prefix = NAMESPACE_ARRAY[i][1]; String uri = NAMESPACE_ARRAY[i][0]; if ( prefix == null) { att("xmlns", uri); } else { att("xmlns:" + prefix, uri); } println(); } att("version", RaplaMainWriter.OUTPUT_FILE_VERSION); if ( repositoryVersion > 0) { att("repositoryVersion", String.valueOf(repositoryVersion)); } if ( resourcesRefresh) { att("resourcesRefresh", "true"); } if ( invalidateInterval != null) { Date startDate = invalidateInterval.getStart(); Date endDate = invalidateInterval.getEnd(); String start; if ( startDate == null) { startDate = new Date(0); } start = dateTimeFormat.formatDate( startDate); att("startDate", start); if ( endDate != null) { String end = dateTimeFormat.formatDate( endDate); att("endDate", end); } } closeTag(); } }
04900db4-rob
src/org/rapla/storage/xml/RaplaMainWriter.java
Java
gpl3
7,953
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.Date; import org.rapla.entities.RaplaObject; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class ReservationWriter extends ClassifiableWriter { public ReservationWriter(RaplaContext sm) throws RaplaException { super(sm); } protected void printReservation(Reservation r) throws IOException,RaplaException { openTag("rapla:reservation"); printId(r); printOwner(r); printTimestamp(r); closeTag(); printAnnotations( r, false); // System.out.println(((Entity)r).getId() + " Name: " + r.getName() +" User: " + r.getUser()); printClassification(r.getClassification()); { Appointment[] appointments = r.getAppointments(); for (int i = 0; i< appointments.length; i ++) { printAppointment(appointments[i], true); } } Allocatable[] allocatables = r.getAllocatables(); // Print allocatables that dont have a restriction for (int i=0; i< allocatables.length; i ++) { Allocatable allocatable = allocatables[i]; if (r.getRestriction( allocatable ).length > 0 ) { continue; } openTag("rapla:allocate"); printIdRef( allocatable ); closeElementTag(); } closeElement("rapla:reservation"); } public void writeObject( RaplaObject object ) throws IOException, RaplaException { printReservation( (Reservation) object); } public void printAppointment(Appointment appointment, boolean includeAllocations) throws IOException { openTag("rapla:appointment"); // always print the id //if (isPrintId()) { printId( appointment ); //} att("start-date",dateTimeFormat.formatDate( appointment.getStart())); if (appointment.isWholeDaysSet()) { boolean bCut = appointment.getEnd().after(appointment.getStart()); att("end-date",dateTimeFormat.formatDate(appointment.getEnd(),bCut)); } else { att("start-time",dateTimeFormat.formatTime( appointment.getStart())); att("end-date",dateTimeFormat.formatDate( appointment.getEnd())); att("end-time",dateTimeFormat.formatTime( appointment.getEnd())); } Reservation reservation = appointment.getReservation(); Allocatable[] allocatables; if ( reservation != null) { allocatables = reservation.getRestrictedAllocatables(appointment); } else { allocatables = Allocatable.ALLOCATABLE_ARRAY; } if (appointment.getRepeating() == null && allocatables.length == 0) { closeElementTag(); } else { closeTag(); if (appointment.getRepeating() != null) { printRepeating(appointment.getRepeating()); } if ( includeAllocations) { for (int i=0; i< allocatables.length; i ++) { Allocatable allocatable = allocatables[i]; openTag("rapla:allocate"); printIdRef( allocatable ); closeElementTag(); } } closeElement("rapla:appointment"); } } private void printRepeating(Repeating r) throws IOException { openTag("rapla:repeating"); if (r.getInterval()!=1) att("interval",String.valueOf(r.getInterval())); att("type",r.getType().toString()); if (r.isFixedNumber()) { att("number",String.valueOf(r.getNumber())); } else { if (r.getEnd() != null) att("end-date" ,dateTimeFormat.formatDate(r.getEnd(),true)); } Date[] exceptions = r.getExceptions(); if (exceptions.length==0) { closeElementTag(); return; } closeTag(); for (int i=0;i<exceptions.length;i++) { openElement("rapla:exception"); openTag("rapla:date"); att("date",dateTimeFormat.formatDate( exceptions[i])); closeElementTag(); closeElement("rapla:exception"); } closeElement("rapla:repeating"); } }
04900db4-rob
src/org/rapla/storage/xml/ReservationWriter.java
Java
gpl3
5,584
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import org.rapla.entities.Category; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.RaplaObject; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.domain.Permission; import org.rapla.entities.internal.CategoryImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class UserWriter extends RaplaXMLWriter { public UserWriter(RaplaContext sm) throws RaplaException { super(sm); } public void printUser(User user, String password, Preferences preferences) throws IOException,RaplaException { openTag("rapla:user"); printId(user); printTimestamp( user); att("username",user.getUsername()); if ( password != null ) { att("password",password); } att("name",user.getName()); att("email",user.getEmail()); // Allocatable person = user.getPerson(); // if ( person != null) // { // att("person", person.getId()); // } att("isAdmin",String.valueOf(user.isAdmin())); closeTag(); Category[] groups = user.getGroups(); for ( int i = 0; i < groups.length; i++ ) { Category group = groups[i]; String groupPath = getGroupPath( group ); try { openTag("rapla:group"); att( "key", groupPath ); closeElementTag(); } catch (Exception ex) { getLogger().error(ex.getMessage(), ex); } } if ( preferences != null) { PreferenceWriter preferenceWriter = (PreferenceWriter) getWriterFor(Preferences.TYPE); preferenceWriter.setIndentLevel( getIndentLevel() ); preferenceWriter.printPreferences(preferences); } closeElement("rapla:user"); } public void writeObject(RaplaObject object) throws IOException, RaplaException { printUser( (User) object,null,null); } private String getGroupPath( Category category) throws EntityNotFoundException { Category rootCategory = getSuperCategory().getCategory(Permission.GROUP_CATEGORY_KEY); return ((CategoryImpl) rootCategory ).getPathForCategory(category); } }
04900db4-rob
src/org/rapla/storage/xml/UserWriter.java
Java
gpl3
3,401
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.rapla.components.util.DateTools; import org.rapla.components.util.TimeInterval; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.Category; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Period; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.facade.Conflict; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class RaplaMainReader extends RaplaXMLReader { private Map<String,RaplaXMLReader> localnameTable = new HashMap<String,RaplaXMLReader>(); public final static String INPUT_FILE_VERSION = RaplaMainWriter.OUTPUT_FILE_VERSION; private TimeInterval invalidateInterval = null; private boolean resourcesRefresh = false; public RaplaMainReader( RaplaContext context ) throws RaplaException { super( context ); // Setup the delegation classes localnameTable.put( "grammar", readerMap.get( DynamicType.TYPE ) ); localnameTable.put( "element", readerMap.get( DynamicType.TYPE ) ); localnameTable.put( "user", readerMap.get( User.TYPE ) ); localnameTable.put( "category", readerMap.get( Category.TYPE ) ); localnameTable.put( "preferences", readerMap.get( Preferences.TYPE ) ); localnameTable.put( "resource", readerMap.get( Allocatable.TYPE ) ); localnameTable.put( "person", readerMap.get( Allocatable.TYPE ) ); localnameTable.put( "extension", readerMap.get( Allocatable.TYPE ) ); localnameTable.put( "period", readerMap.get( Period.TYPE ) ); localnameTable.put( "reservation", readerMap.get( Reservation.TYPE ) ); localnameTable.put( "conflict", readerMap.get( Conflict.TYPE ) ); localnameTable.put( "remove", readerMap.get( "remove") ); localnameTable.put( "store", readerMap.get( "store") ); localnameTable.put( "reference", readerMap.get( "reference") ); addChildHandler( readerMap.values() ); } private void addChildHandler( Collection<? extends DelegationHandler> collection ) { Iterator<? extends DelegationHandler> it = collection.iterator(); while (it.hasNext()) addChildHandler( it.next() ); } /** checks the version of the input-file. throws WrongVersionException if the file-version is not supported by the reader. */ private void processHead( String uri, String name, RaplaSAXAttributes atts ) throws RaplaSAXParseException { try { String version = null; getLogger().debug( "Getting version." ); if (name.equals( "data" ) && uri.equals( RAPLA_NS )) { version = atts.getValue( "version" ); if (version == null) throw createSAXParseException( "Could not get Version" ); } String start = atts.getValue( "startDate"); String end = atts.getValue( "endDate"); if ( start != null || end != null) { Date startDate = start!= null ? parseDate(start, false) : null; Date endDate = end!= null ? parseDate(end, true) : null; if ( startDate != null && startDate.getTime() < DateTools.MILLISECONDS_PER_DAY) { startDate = null; } invalidateInterval = new TimeInterval(startDate, endDate); } String resourcesRefresh = atts.getValue( "resourcesRefresh"); if ( resourcesRefresh != null) { this.resourcesRefresh = Boolean.parseBoolean( resourcesRefresh); } if (name.equals( "DATA" )) { version = atts.getValue( "version" ); if (version == null) { version = "0.1"; } } if (version == null) throw createSAXParseException( "Invalid Format. Could not read data." ); if (!version.equals( INPUT_FILE_VERSION )) { double versionNr; try { versionNr = new Double(version).doubleValue(); } catch (NumberFormatException ex) { throw new RaplaException("Invalid version tag (double-value expected)!"); } // get the version number of the data-schema if (versionNr > new Double(RaplaMainReader.INPUT_FILE_VERSION).doubleValue()) throw new RaplaException("This version of Rapla cannot read files with a version-number" + " greater than " + RaplaMainReader.INPUT_FILE_VERSION + ", try out the latest version."); getLogger().warn( "Older version detected. " ); } getLogger().debug( "Found compatible version-number." ); // We've got the right version. We can proceed. } catch (Exception ex) { throw createSAXParseException(ex.getMessage(),ex); } } @Override public void processElement( String namespaceURI, String localName, RaplaSAXAttributes atts ) throws RaplaSAXParseException { if (level == 1) { processHead( namespaceURI, localName, atts ); return; } if ( !namespaceURI.equals(RAPLA_NS) && !namespaceURI.equals(RELAXNG_NS)) { // Ignore unknown namespace return; } // lookup delegation-handler for the localName DelegationHandler handler = localnameTable.get( localName ); // Ignore unknown elements if (handler != null) { delegateElement( handler, namespaceURI, localName, atts ); } } public TimeInterval getInvalidateInterval() { return invalidateInterval; } public boolean isResourcesRefresh() { return resourcesRefresh; } }
04900db4-rob
src/org/rapla/storage/xml/RaplaMainReader.java
Java
gpl3
7,399
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.Stack; import org.rapla.components.util.Assert; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.Annotatable; import org.rapla.entities.Category; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.internal.CategoryImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class CategoryReader extends RaplaXMLReader { MultiLanguageName currentName = null; Annotatable currentAnnotatable = null; String currentLang = null; Stack<CategoryImpl> categoryStack = new Stack<CategoryImpl>(); CategoryImpl superCategory; String annotationKey = null; CategoryImpl lastProcessedCategory = null; boolean readOnlyThisCategory; public CategoryReader( RaplaContext context ) throws RaplaException { super( context ); superCategory = getSuperCategory(); currentName = superCategory.getName(); } public void setReadOnlyThisCategory( boolean enable ) { readOnlyThisCategory = enable; } @Override public void processElement( String namespaceURI, String localName, RaplaSAXAttributes atts ) throws RaplaSAXParseException { if (localName.equals( "category" ) && namespaceURI.equals( RAPLA_NS )) { String key = atts.getValue( "key" ); Assert.notNull( key ); TimestampDates ts = readTimestamps( atts); CategoryImpl category = new CategoryImpl(ts.createTime, ts.changeTime ); category.setKey( key ); currentName = category.getName(); currentAnnotatable = category; if (atts.getValue( "id" )!=null) { setId( category, atts ); } else { setNewId( category ); } if (!readOnlyThisCategory) { if ( !categoryStack.empty() ) { Category parent = categoryStack.peek(); parent.addCategory( category); } else { String parentId = atts.getValue( "parentid"); if ( parentId!= null) { if (parentId.equals(Category.SUPER_CATEGORY_ID)) { if ( !superCategory.isReadOnly()) { superCategory.addCategory( category); } category.putEntity("parent", superCategory); } else { String parentIdN = getId( Category.TYPE, parentId); category.putId("parent", parentIdN); } } else { if (atts.getValue( "id" )==null) { superCategory.addCategory( category); } else { // It is the super categorycategory.getReferenceHandler().put("parent", superCategory); } } } } categoryStack.push( category ); /* Category test = category; String output = ""; while (test != null) { output = "/" + test.getKey() + output; test = test.getParent(); } // System.out.println("Storing category " + output ); */ } if (localName.equals( "name" ) && namespaceURI.equals( ANNOTATION_NS )) { startContent(); currentLang = atts.getValue( "lang" ); Assert.notNull( currentLang ); } if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS )) { annotationKey = atts.getValue( "key" ); Assert.notNull( annotationKey, "key attribute cannot be null" ); startContent(); } } @Override public void processEnd( String namespaceURI, String localName ) throws RaplaSAXParseException { if (localName.equals( "category" )) { // Test Namespace uris here for possible xerces bug if (namespaceURI.equals( "" )) { throw createSAXParseException( " category namespace empty. Possible Xerces Bug. Download a newer version of xerces." ); } CategoryImpl category = categoryStack.pop(); setCurrentTranslations( category.getName()); if (!readOnlyThisCategory) { add( category ); } lastProcessedCategory = category; } else if (localName.equals( "name" ) && namespaceURI.equals( ANNOTATION_NS )) { String translation = readContent(); currentName.setName( currentLang, translation ); } else if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS )) { try { String annotationValue = readContent().trim(); currentAnnotatable.setAnnotation( annotationKey, annotationValue ); } catch (IllegalAnnotationException ex) { } } } public CategoryImpl getCurrentCategory() { return lastProcessedCategory; } }
04900db4-rob
src/org/rapla/storage/xml/CategoryReader.java
Java
gpl3
6,727
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.Date; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.domain.Permission; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.dynamictype.Classification; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.storage.StorageOperator; public class PeriodReader extends DynAttReader { public PeriodReader(RaplaContext context) throws RaplaException { super(context); } static int idCount = 0 ; @Override public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts) throws RaplaSAXParseException { if (namespaceURI.equals(RAPLA_NS) && localName.equals("period")) { AllocatableImpl period = new AllocatableImpl(new Date(), new Date()); Classification classification = store.getDynamicType(StorageOperator.PERIOD_TYPE).newClassification(); classification.setValue("name", getString(atts,"name")); classification.setValue("start",parseDate(getString(atts,"start"),false)); classification.setValue("end",parseDate(getString(atts,"end"),true)); period.setClassification( classification); Permission newPermission = period.newPermission(); newPermission.setAccessLevel( Permission.READ); period.addPermission( newPermission); String id = atts.getValue("id"); if ( id != null) { period.setId(id); } else { period.setId("period_"+idCount); idCount++; } add(period); } } }
04900db4-rob
src/org/rapla/storage/xml/PeriodReader.java
Java
gpl3
2,774
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.Date; import org.rapla.entities.Category; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.RaplaObject; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.internal.CategoryImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; /** Stores the data from the local cache in XML-format to a print-writer.*/ public class DynamicTypeWriter extends RaplaXMLWriter { public DynamicTypeWriter(RaplaContext sm) throws RaplaException { super(sm); } public void printDynamicType(DynamicType type) throws IOException,RaplaException { openTag("relax:define"); att("name",type.getKey()); closeTag(); openTag("relax:element"); att("name","dynatt:" + type.getKey()); if (isPrintId()) { att("id",getId(type)); } printTimestamp( type ); closeTag(); printTranslation(type.getName()); printAnnotations(type); Attribute att[] = type.getAttributes(); for (int i = 0; i< att.length; i ++) { printAttribute(att[i]); } closeElement("relax:element"); closeElement("relax:define"); } public void writeObject(RaplaObject type) throws IOException, RaplaException { printDynamicType( (DynamicType) type ); } private String getCategoryPath( Category category) throws EntityNotFoundException { Category rootCategory = getSuperCategory(); if ( category != null && rootCategory.equals( category) ) { return ""; } return ((CategoryImpl) rootCategory ).getPathForCategory(category); } protected void printAttribute(Attribute attribute) throws IOException,RaplaException { if (attribute.isOptional()) openElement("relax:optional"); openTag("relax:element"); att("name",attribute.getKey()); // if (isPrintId()) // att("id",getId(attribute)); AttributeType type = attribute.getType(); closeTag(); printTranslation( attribute.getName() ); printAnnotations( attribute ); String[] constraintKeys = attribute.getConstraintKeys(); openTag("relax:data"); att("type", type.toString()); closeElementTag(); for (int i = 0; i<constraintKeys.length; i++ ) { String key = constraintKeys[i]; Object constraint = attribute.getConstraint( key ); // constraint not set if (constraint == null) continue; openTag("rapla:constraint"); att("name", key ); closeTagOnLine(); if ( constraint instanceof Category) { Category category = (Category) constraint; print( getCategoryPath( category ) ); } else if ( constraint instanceof DynamicType) { DynamicType dynamicType = (DynamicType) constraint; print( dynamicType.getKey() ); } else if ( constraint instanceof Date) { final String formatDate = dateTimeFormat.formatDate( (Date) constraint); print( formatDate); } else { print( constraint.toString()); } closeElementOnLine("rapla:constraint"); println(); } Object defaultValue = attribute.defaultValue(); if ( defaultValue != null) { openTag("rapla:default"); closeTagOnLine(); if ( defaultValue instanceof Category) { Category category = (Category) defaultValue; print( getCategoryPath( category ) ); } else if ( defaultValue instanceof Date) { final String formatDate = dateTimeFormat.formatDate( (Date) defaultValue); print( formatDate); } else { print( defaultValue.toString()); } closeElementOnLine("rapla:default"); println(); } closeElement("relax:element"); if (attribute.isOptional()) closeElement("relax:optional"); } }
04900db4-rob
src/org/rapla/storage/xml/DynamicTypeWriter.java
Java
gpl3
5,396
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.components.util.xml.XMLWriter; import org.rapla.entities.Annotatable; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.Ownable; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.Timestamp; import org.rapla.entities.User; 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.framework.Provider; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; /** Stores the data from the local cache in XML-format to a print-writer.*/ abstract public class RaplaXMLWriter extends XMLWriter implements Namespaces { //protected NamespaceSupport namespaceSupport = new NamespaceSupport(); private boolean isPrintId; private Map<String,RaplaType> localnameMap; Logger logger; Map<RaplaType,RaplaXMLWriter> writerMap; protected RaplaContext context; protected SerializableDateTimeFormat dateTimeFormat = SerializableDateTimeFormat.INSTANCE; Provider<Category> superCategory; public RaplaXMLWriter( RaplaContext context) throws RaplaException { this.context = context; enableLogging( context.lookup( Logger.class)); this.writerMap =context.lookup( PreferenceWriter.WRITERMAP ); this.localnameMap = context.lookup(PreferenceReader.LOCALNAMEMAPENTRY); this.isPrintId = context.has(IOContext.PRINTID); this.superCategory = context.lookup( IOContext.SUPERCATEGORY); // namespaceSupport.pushContext(); // for (int i=0;i<NAMESPACE_ARRAY.length;i++) { // String prefix = NAMESPACE_ARRAY[i][1]; // String uri = NAMESPACE_ARRAY[i][0]; // if ( prefix != null) { // namespaceSupport.declarePrefix(prefix, uri); // } // } } public Category getSuperCategory() { return superCategory.get(); } public void enableLogging(Logger logger) { this.logger = logger; } protected Logger getLogger() { return logger; } protected void printTimestamp(Timestamp stamp) throws IOException { final Date createTime = stamp.getCreateTime(); final Date lastChangeTime = stamp.getLastChanged(); if ( createTime != null) { att("created-at", SerializableDateTimeFormat.INSTANCE.formatTimestamp( createTime)); } if ( lastChangeTime != null) { att("last-changed", SerializableDateTimeFormat.INSTANCE.formatTimestamp( lastChangeTime)); } User user = stamp.getLastChangedBy(); if ( user != null) { att("last-changed-by", getId(user)); } } protected void printTranslation(MultiLanguageName name) throws IOException { Iterator<String> it= name.getAvailableLanguages().iterator(); while (it.hasNext()) { String lang = it.next(); String value = name.getName(lang); openTag("doc:name"); att("lang",lang); closeTagOnLine(); printEncode(value); closeElementOnLine("doc:name"); println(); } } protected void printAnnotations(Annotatable annotatable, boolean includeTags) throws IOException{ String[] keys = annotatable.getAnnotationKeys(); if ( keys.length == 0 ) return; if ( includeTags) { openElement("doc:annotations"); } for (String key:keys) { String value = annotatable.getAnnotation(key); openTag("rapla:annotation"); att("key", key); closeTagOnLine(); printEncode(value); closeElementOnLine("rapla:annotation"); println(); } if ( includeTags) { closeElement("doc:annotations"); } } protected void printAnnotations(Annotatable annotatable) throws IOException{ printAnnotations(annotatable, true); } protected void printAttributeValue(Attribute attribute, Object value) throws IOException,RaplaException { if ( value == null) { return; } AttributeType type = attribute.getType(); if (type.equals(AttributeType.ALLOCATABLE)) { print(getId((Entity)value)); } else if (type.equals(AttributeType.CATEGORY)) { CategoryImpl rootCategory = (CategoryImpl) attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); if ( !(value instanceof Category)) { throw new RaplaException("Wrong attribute value Category expected but was " + value.getClass()); } Category categoryValue = (Category)value; if (rootCategory == null) { getLogger().error("root category missing for attriubte " + attribute); } else { String keyPathString = getKeyPath(rootCategory, categoryValue); print( keyPathString); } } else if (type.equals(AttributeType.DATE) ) { final Date date; if ( value instanceof Date) date = (Date)value; else date = null; printEncode( dateTimeFormat.formatDate( date ) ); } else { printEncode( value.toString() ); } } private String getKeyPath(CategoryImpl rootCategory, Category categoryValue) throws EntityNotFoundException { List<String> pathForCategory = rootCategory.getPathForCategory(categoryValue, true ); String keyPathString = CategoryImpl.getKeyPathString(pathForCategory); return keyPathString; } protected void printOwner(Ownable obj) throws IOException { User user = obj.getOwner(); if (user == null) return; att("owner", getId(user)); } protected void printReference(Entity entity) throws IOException, EntityNotFoundException { String localName = entity.getRaplaType().getLocalName(); openTag("rapla:" + localName); if ( entity.getRaplaType() == DynamicType.TYPE ) { att("keyref", ((DynamicType)entity).getKey()); } else if ( entity.getRaplaType() == Category.TYPE && !isPrintId()) { String path = getKeyPath( (CategoryImpl)getSuperCategory(), (Category) entity); att("keyref", path); } else { att("idref",getId( entity)); } closeElementTag(); } protected String getId(Entity entity) { Comparable id2 = entity.getId(); return id2.toString(); } protected RaplaXMLWriter getWriterFor(RaplaType raplaType) throws RaplaException { RaplaXMLWriter writer = writerMap.get(raplaType); if ( writer == null) { throw new RaplaException("No writer for type " + raplaType); } writer.setIndentLevel( getIndentLevel()); writer.setWriter( getWriter()); return writer; } protected void printId(Entity entity) throws IOException { att("id", getId( entity )); } protected void printIdRef(Entity entity) throws IOException { att("idref", getId( entity ) ); } /** Returns if the ids should be saved, even when keys are * available. */ public boolean isPrintId() { return isPrintId; } /** * @throws IOException */ public void writeObject(@SuppressWarnings("unused") RaplaObject object) throws IOException, RaplaException { throw new RaplaException("Method not implemented by subclass " + this.getClass().getName()); } public String getLocalNameForType(RaplaType raplaType) throws RaplaException{ for (Iterator<Map.Entry<String,RaplaType>> it = localnameMap.entrySet().iterator();it.hasNext();) { Map.Entry<String,RaplaType> entry =it.next(); if (entry.getValue().equals( raplaType)) { return entry.getKey(); } } throw new RaplaException("No writer declared for Type " + raplaType ); } }
04900db4-rob
src/org/rapla/storage/xml/RaplaXMLWriter.java
Java
gpl3
9,741
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.Collection; import java.util.Map; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.RaplaMap; import org.rapla.entities.configuration.internal.CalendarModelConfigurationImpl; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class RaplaCalendarSettingsWriter extends ClassificationFilterWriter { /** * @param sm * @throws RaplaException */ public RaplaCalendarSettingsWriter(RaplaContext sm) throws RaplaException { super(sm); } public void writeObject(RaplaObject type) throws IOException, RaplaException { CalendarModelConfigurationImpl calendar = (CalendarModelConfigurationImpl) type ; openTag("rapla:" + CalendarModelConfiguration.TYPE.getLocalName()); att("title", calendar.getTitle()); att("view", calendar.getView()); Map<String,String> extensionMap = calendar.getOptionMap(); final String saveDate = extensionMap != null ? extensionMap.get( CalendarModel.SAVE_SELECTED_DATE) : "false" ; boolean saveDateActive = saveDate != null && saveDate.equals("true"); if ( calendar.getSelectedDate() != null && saveDateActive) { att("date", dateTimeFormat.formatDate( calendar.getSelectedDate())); } if ( calendar.getStartDate() != null && saveDateActive) { att("startdate", dateTimeFormat.formatDate( calendar.getStartDate())); } if ( calendar.getEndDate() != null && saveDateActive) { att("enddate", dateTimeFormat.formatDate( calendar.getEndDate())); } if ( calendar.isResourceRootSelected()) { att("rootSelected","true"); } closeTag(); Collection<Entity> selectedObjects = calendar.getSelected(); if (selectedObjects != null && selectedObjects.size() > 0) { openElement("selected"); for ( Entity entity:selectedObjects) { printReference( entity); } closeElement("selected"); } if (extensionMap != null && extensionMap.size() > 0) { openElement("options"); RaplaMapWriter writer = (RaplaMapWriter)getWriterFor( RaplaMap.TYPE); writer.writeMap( extensionMap); closeElement("options"); } ClassificationFilter[] filter =calendar.getFilter() ; if ( filter.length> 0) { openElement("filter"); for (ClassificationFilter f:filter) { final DynamicType dynamicType = f.getType(); final String annotation = dynamicType.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); boolean eventType = annotation != null && annotation.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION); if (( eventType && !calendar.isDefaultEventTypes()) || (!eventType && !calendar.isDefaultResourceTypes()) ) { printClassificationFilter( f ); } } closeElement("filter"); } closeElement("rapla:" + CalendarModelConfiguration.TYPE.getLocalName()); } }
04900db4-rob
src/org/rapla/storage/xml/RaplaCalendarSettingsWriter.java
Java
gpl3
4,617
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.Date; import org.rapla.components.util.Assert; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.Annotatable; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.RepeatingType; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class ReservationReader extends RaplaXMLReader { ReservationImpl reservation; private String allocatableId = null; private AppointmentImpl appointment = null; private Repeating repeating = null; private DynAttReader dynAttHandler; private String annotationKey; private Annotatable currentAnnotatable; public ReservationReader( RaplaContext context) throws RaplaException { super( context); dynAttHandler = new DynAttReader( context); addChildHandler(dynAttHandler); } @Override public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts) throws RaplaSAXParseException { if (namespaceURI.equals( DYNATT_NS ) || namespaceURI.equals( EXTENSION_NS )) { dynAttHandler.setClassifiable(reservation); delegateElement(dynAttHandler,namespaceURI,localName,atts); return; } if (!namespaceURI.equals(RAPLA_NS)) return; if ( localName.equals( "reservation" ) ) { TimestampDates ts = readTimestamps( atts); reservation = new ReservationImpl( ts.createTime, ts.changeTime ); reservation.setResolver( store ); currentAnnotatable = reservation; setId(reservation, atts); setLastChangedBy( reservation, atts); setOwner(reservation, atts); } if (localName.equals("appointment")) { String id = atts.getValue("id"); String startDate=atts.getValue("start-date"); String endDate= atts.getValue("end-date"); if (endDate == null) endDate = startDate; String startTime = atts.getValue("start-time"); String endTime = atts.getValue("end-time"); Date start; Date end; if (startTime != null && endTime != null) { start = parseDateTime(startDate,startTime); end = parseDateTime(endDate,endTime); } else { start = parseDate(startDate,false); end = parseDate(endDate,true); } appointment= new AppointmentImpl(start,end); appointment.setWholeDays(startTime== null && endTime==null); if (id!=null) { setId(appointment, atts); } else { setNewId(appointment); } addAppointment(appointment); } if (localName.equals("repeating")) { String type =atts.getValue("type"); String interval =atts.getValue("interval"); String enddate =atts.getValue("end-date"); String number =atts.getValue("number"); appointment.setRepeatingEnabled(true); repeating = appointment.getRepeating(); repeating.setType( RepeatingType.findForString( type)); if (interval != null) { repeating.setInterval(Integer.valueOf(interval).intValue()); } if (enddate != null) { repeating.setEnd(parseDate(enddate,true)); } else if (number != null) { repeating.setNumber(Integer.valueOf(number).intValue()); } else { repeating.setEnd(null); } /* if (getLogger().enabled(6)) getLogger().log(6, "Repeating " + repeating.toString() ); */ } if (localName.equals("allocate")) { String id = getString( atts, "idref" ); allocatableId = getId( Allocatable.TYPE, id); reservation.addId("resources", allocatableId ); if ( appointment != null ) { reservation.addRestrictionForId( allocatableId, appointment.getId()); } } if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS )) { annotationKey = atts.getValue( "key" ); Assert.notNull( annotationKey, "key attribute cannot be null" ); startContent(); } if (localName.equals("exception")) { } if (localName.equals("date")) { String dateString =atts.getValue("date"); if (dateString != null && repeating != null) repeating.addException(parseDate(dateString,false)); } } protected void addAppointment(Appointment appointment) { reservation.addAppointment(appointment); } @Override public void processEnd(String namespaceURI,String localName) throws RaplaSAXParseException { if (!namespaceURI.equals(RAPLA_NS)) return; if (localName.equals("appointment") && appointment != null ) { add(appointment); appointment = null; } if (localName.equals("reservation")) { add(reservation); } if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS )) { try { String annotationValue = readContent().trim(); currentAnnotatable.setAnnotation( annotationKey, annotationValue ); } catch (IllegalAnnotationException ex) { } } } }
04900db4-rob
src/org/rapla/storage/xml/ReservationReader.java
Java
gpl3
7,145
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.Category; import org.rapla.entities.internal.UserImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class UserReader extends RaplaXMLReader { UserImpl user; PreferenceReader preferenceHandler; public UserReader( RaplaContext context ) throws RaplaException { super( context ); preferenceHandler = new PreferenceReader( context ); addChildHandler( preferenceHandler ); } @Override public void processElement( String namespaceURI, String localName, RaplaSAXAttributes atts ) throws RaplaSAXParseException { if (!namespaceURI.equals( RAPLA_NS )) return; if (localName.equals( "user" )) { TimestampDates ts = readTimestamps( atts); user = new UserImpl(ts.createTime, ts.changeTime); String id = setId( user, atts ); // String idString = getString(atts, "person",null); // if ( idString != null) // { // String personId = getId(Allocatable.TYPE,idString); // user.putId("person",personId); // } user.setUsername( getString( atts, "username", "" ) ); user.setName( getString( atts, "name", "" ) ); user.setEmail( getString( atts, "email", "" ) ); user.setAdmin( getString( atts, "isAdmin", "false" ).equals( "true" ) ); String password = getString( atts, "password", null ); preferenceHandler.setUser( user ); if ( password != null) { putPassword( id, password ); } } if (localName.equals( "group" )) { String groupId = atts.getValue( "idref" ); if (groupId !=null) { String newGroupId = getId(Category.TYPE, groupId); user.addId("groups",newGroupId); } else { String groupKey = getString( atts, "key" ); Category group = getGroup( groupKey); if (group != null) { user.addGroup( group ); } } } if (localName.equals( "preferences" )) { delegateElement( preferenceHandler, namespaceURI, localName, atts ); } } @Override public void processEnd( String namespaceURI, String localName ) throws RaplaSAXParseException { if (!namespaceURI.equals( RAPLA_NS )) return; if (localName.equals( "user" )) { preferenceHandler.setUser( null ); add( user ); } } }
04900db4-rob
src/org/rapla/storage/xml/UserReader.java
Java
gpl3
3,911