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.components.util; import java.lang.reflect.Method; import java.net.URL; /** returns the codebase in an webstart application */ abstract public class JNLPUtil { final static String basicService = "javax.jnlp.BasicService"; final public static URL getCodeBase() throws Exception { try { Class<?> serviceManagerC = Class.forName("javax.jnlp.ServiceManager"); Class<?> basicServiceC = Class.forName( basicService ); //Class unavailableServiceException = Class.forName("javax.jnlp.UnavailableServiceException"); Method lookup = serviceManagerC.getMethod("lookup", new Class[] {String.class}); Method getCodeBase = basicServiceC.getMethod("getCodeBase", new Class[] {}); Object service = lookup.invoke( null, new Object[] { basicService }); return (URL) getCodeBase.invoke( service, new Object[] {}); } catch (ClassNotFoundException ex ) { throw new Exception( "Webstart not available :" + ex.getMessage()); } } }
04900db4-rob
src/org/rapla/components/util/JNLPUtil.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.components.util; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; /** miscellaneous util methods.*/ public abstract class Tools { /** same as new Object[0].*/ public static final Object[] EMPTY_ARRAY = new Object[0]; public static final Class<?>[] EMPTY_CLASS_ARRAY = new Class[0]; public static final String[] EMPTY_STRING_ARRAY = new String[0]; /** test if 2 char arrays match. */ public static boolean match(char[] p1, char[] p2) { boolean bMatch = true; if (p1.length == p2.length) { for (int i = 0; i<p1.length; i++) { if (p1[i] != p2[i]) { bMatch = false; break; } } } else { bMatch = false; } return bMatch; } private static boolean validStart(char c) { return (c == '_' || c =='-' || Character.isLetter(c)) ? true : false; } private static boolean validLetter(char c) { return (validStart(c) || Character.isDigit(c)); } /** Rudimentary tests if the string is a valid xml-tag.*/ public static boolean isKey(String key) { // A tag name must start with a letter (a-z, A-Z) or an underscore (_) and can contain letters, digits 0-9, the period (.), the underscore (_) or the hyphen (-). char[] c = key.toCharArray(); if (c.length == 0) return false; if (!validStart(c[0])) return false; for (int i=0;i<c.length;i++) { if (!validLetter(c[i])) return false; } return true; } /** same as substring(0,width-1) except that it will not not throw an <code>ArrayIndexOutOfBoundsException</code> if string.length()&lt;width. */ public static String left(String string,int width) { return string.substring(0, Math.min(string.length(), width -1)); } /** Convert a byte array into a printable format containing aString of hexadecimal digit characters (two per byte). * This method is taken form the apache jakarata * tomcat project. */ public static String convert(byte bytes[]) { StringBuffer sb = new StringBuffer(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { sb.append(convertDigit(bytes[i] >> 4)); sb.append(convertDigit(bytes[i] & 0x0f)); } return (sb.toString()); } /** Convert the specified value (0-15) to the corresponding hexadecimal digit. * This method is taken form the apache jakarata tomcat project. */ public static char convertDigit(int value) { value &= 0x0f; if (value >= 10) return ((char) (value - 10 + 'a')); else return ((char) (value + '0')); } public 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; } /** 1.3 compatibility method */ public static String[] split(String stringToSplit, char delimiter) { List<String> keys = new ArrayList<String>(); int lastIndex = 0; while( true ) { int index = stringToSplit.indexOf( delimiter,lastIndex); if ( index < 0) { String token = stringToSplit.substring( lastIndex ); if ( token.length() >= 0) { keys.add( token ); } break; } String token = stringToSplit.substring( lastIndex , index ); keys.add( token ); lastIndex = index + 1; } return keys.toArray( new String[] {}); } // /** 1.3 compatibility method */ // public static String replaceAll( String string, String stringToReplace, String newString ) { // if ( stringToReplace.equals( newString)) // return string; // int length = stringToReplace.length(); // int oldPos = 0; // while ( true ) { // int pos = string.indexOf( stringToReplace,oldPos); // if ( pos < 0 ) // return string; // // string = string.substring(0, pos) + newString + string.substring( pos + length); // oldPos = pos + 1; // if ( oldPos >= string.length() ) // return string; // // } // } /** reads a table from a csv file. You can specify a minimum number of columns */ public static String[][] csvRead(Reader reader, int expectedColumns) throws IOException { return csvRead(reader, ';', expectedColumns); } /** reads a table from a csv file. You can specify the seperator and a minimum number of columns */ public static String[][] csvRead(Reader reader, char seperator,int expectedColumns) throws IOException { //System.out.println( "Using Encoding " + reader.getEncoding() ); StringBuffer buf = new StringBuffer(); while (true) { int c = reader.read(); if ( c == -1 ) break; buf.append( (char) c ); } String[] lines = buf.toString().split(System.getProperty("line.separator")); //BJO //String[] lines = split( buf.toString(),'\n'); String[][] lineEntries = new String[ lines.length ][]; for ( int i=0;i<lines.length; i++ ) { String stringToSplit = lines[i]; //String firstIterator =stringToSplit.replaceAll("\"\"", "DOUBLEQUOTEQUOTE"); lineEntries[i] = split( stringToSplit,seperator); if ( lineEntries[i].length < expectedColumns ) { throw new IOException("Can't parse line " + i + ":" + stringToSplit + "Expected " + expectedColumns + " Entries. Found " + lineEntries[i].length); // BJO } } return lineEntries; } }
04900db4-rob
src/org/rapla/components/util/Tools.java
Java
gpl3
7,073
/*--------------------------------------------------------------------------* | 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.components.util; public class AssertionError extends RuntimeException { private static final long serialVersionUID = 1L; String text = ""; public AssertionError() { } public AssertionError(String text) { this.text = text; } public String toString() { return text; } }
04900db4-rob
src/org/rapla/components/util/AssertionError.java
Java
gpl3
1,279
package org.rapla.components.util; import java.io.Serializable; import java.util.Date; public final class TimeInterval implements Serializable { private static final long serialVersionUID = -8387919392038291664L; Date start; Date end; TimeInterval() { } public TimeInterval(Date start, Date end) { this.start = start; this.end = end; } public Date getStart() { return start; } public void setStart(Date start) { this.start = start; } public Date getEnd() { return end; } public void setEnd(Date end) { this.end = end; } public String toString() { return start + " - " + end; } public boolean equals(Object obj) { if (obj == null || !(obj instanceof TimeInterval) ) { return false; } TimeInterval other = (TimeInterval) obj; Date start2 = other.getStart(); Date end2 = other.getEnd(); if ( start == null ) { if (start != start2) { return false; } } else { if ( start2 == null || !start.equals(start2)) { return false; } } if ( end == null ) { if (end != end2) { return false; } } else { if ( end2 == null || !end.equals(end2)) { return false; } } return true; } @Override public int hashCode() { int hashCode; if ( start!=null ) { hashCode = start.hashCode(); if ( end!=null ) { hashCode *= end.hashCode(); } } else if ( end!=null ) { hashCode = end.hashCode(); } else { hashCode =super.hashCode(); } return hashCode; } public boolean overlaps(TimeInterval other) { Date start2 = other.getStart(); Date end2 = other.getEnd(); if ( start != null) { if ( end2 != null) { if ( !start.before(end2)) { return false; } } } if ( end != null) { if ( start2 != null) { if ( !start2.before(end)) { return false; } } } return true; } public TimeInterval union(TimeInterval interval) { Date start = getStart(); Date end = getEnd(); if ( interval == null ) { interval = new TimeInterval(start, end); } if ( start == null || (interval.getStart() != null && interval.getStart().after( start))) { interval = new TimeInterval( start, interval.getEnd()); } if ( end == null || ( interval.getEnd() != null && end.after( interval.getEnd()))) { interval = new TimeInterval( interval.getStart(), end); } return interval; } }
04900db4-rob
src/org/rapla/components/util/TimeInterval.java
Java
gpl3
2,426
/*--------------------------------------------------------------------------* | 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.components.util; public interface Command { public void execute() throws Exception; }
04900db4-rob
src/org/rapla/components/util/Command.java
Java
gpl3
1,038
package org.rapla.components.util; public class ParseDateException extends Exception { private static final long serialVersionUID = 1L; public ParseDateException(String message) { super(message); } }
04900db4-rob
src/org/rapla/components/util/ParseDateException.java
Java
gpl3
216
package org.rapla.components.util; import java.util.Date; import org.rapla.components.util.DateTools.TimeWithoutTimezone; import org.rapla.components.util.iterator.IntIterator; /** Provides methods for parsing and formating dates and times in the following format: <br> <code>2002-25-05</code> for dates and <code>13:00:00</code> for times. This is according to the xschema specification for dates and time and ISO8601 */ public class SerializableDateTimeFormat { public static SerializableDateTimeFormat INSTANCE = new SerializableDateTimeFormat(); // we ommit T private final static char DATE_TIME_SEPERATOR = 'T'; //private final static char DATE_TIME_SEPERATOR = ' '; private Date parseDate( String date, String time, boolean fillDate ) throws ParseDateException { if( date == null || date.length()==0 ) throwParseDateException("empty" ); long millis = parseDate_(date, fillDate); if ( time != null ) { long timeMillis = parseTime_(time); millis+= timeMillis; } // logger.log( "parsed to " + calendar.getTime() ); return new Date( millis); } private long parseTime_(String time) throws ParseDateException { int length = time.length(); if ( length <1) { throwParseTimeException( time ); } if ( time.charAt( length-1) == 'Z') { time = time.substring(0,length-1); } IntIterator it = new IntIterator( time, new char[]{':','.',','} ); if ( !it.hasNext() ) throwParseTimeException( time ); int hour = it.next(); if ( !it.hasNext() ) throwParseTimeException( time ); int minute = it.next(); int second; if ( it.hasNext() ) { second = it.next(); } else { second = 0; } int millisecond; if ( it.hasNext() ) { millisecond = it.next(); } else { millisecond = 0; } long result = DateTools.toTime( hour, minute,second, millisecond); return result; } private long parseDate_(String date, boolean fillDate) throws ParseDateException { int indexOfSeperator = indexOfSeperator(date); if ( indexOfSeperator > 0) { date = date.substring(0, indexOfSeperator); } IntIterator it = new IntIterator(date,'-'); if ( !it.hasNext() ) throwParseDateException( date ); int year = it.next(); if ( !it.hasNext() ) throwParseDateException( date); int month = it.next(); if ( !it.hasNext() ) throwParseDateException( date); int day = it.next(); if (fillDate ) { day+=1; } return DateTools.toDate( year, month, day); } private int indexOfSeperator(String date) { // First try the new ISO8601 int indexOfSeperator = date.indexOf( 'T' ); if ( indexOfSeperator<0) { //then search for a space indexOfSeperator = date.indexOf( ' ' ); } return indexOfSeperator; } private void throwParseDateException( String date) throws ParseDateException { throw new ParseDateException( "No valid date format: " + date); } private void throwParseTimeException( String time) throws ParseDateException { throw new ParseDateException( "No valid time format: " + time); } /** The date-string must be in the following format <strong>2001-10-21</strong>. The format of the time-string is <strong>18:00:00</strong>. @return The parsed date @throws ParseDateException when the date cannot be parsed. */ public Date parseDateTime( String date, String time) throws ParseDateException { return parseDate( date, time, false); } /** The format of the time-string is <strong>18:00:00</strong>. @return The parsed time @throws ParseDateException when the date cannot be parsed. */ public Date parseTime( String time) throws ParseDateException { if( time == null || time.length()==0 ) throwParseDateException("empty"); long millis = parseTime_( time); Date result = new Date( millis); return result; } /** The date-string must be in the following format <strong>2001-10-21</strong>. * @param fillDate if this flag is set the time will be 24:00 instead of 0:00 <strong> When this flag is set the time parameter should be null</strong> @return The parsed date @throws ParseDateException when the date cannot be parsed. */ public Date parseDate( String date, boolean fillDate ) throws ParseDateException { return parseDate( date, null, fillDate); } public Date parseTimestamp(String timestamp) throws ParseDateException { boolean fillDate = false; timestamp = timestamp.trim(); long millisDate = parseDate_(timestamp, fillDate); int indexOfSeperator = indexOfSeperator(timestamp); if ( timestamp.indexOf(':') >= indexOfSeperator && indexOfSeperator > 0) { String timeString = timestamp.substring( indexOfSeperator + 1); if ( timeString.length() > 0) { long time = parseTime_( timeString); millisDate+= time; } } Date result = new Date( millisDate); return result; } /** returns the time object in the following format: <strong>13:00:00</strong>. <br> */ public String formatTime( Date date ) { return formatTime(date, false); } private String formatTime(Date date, boolean includeMilliseconds) { StringBuilder buf = new StringBuilder(); if ( date == null) { date = new Date(); } TimeWithoutTimezone time = DateTools.toTime( date.getTime()); append( buf, time.hour, 2 ); buf.append( ':' ); append( buf, time.minute, 2 ); buf.append( ':' ); append( buf, time.second, 2 ); if ( includeMilliseconds) { buf.append('.'); append( buf, time.milliseconds, 4 ); } //buf.append( 'Z'); return buf.toString(); } /** returns the date object in the following format: <strong>2001-10-21</strong>. <br> @param adaptDay if the flag is set 2001-10-21 will be stored as 2001-10-20. This is usefull for end-dates: 2001-10-21 00:00 is then interpreted as 2001-10-20 24:00. */ public String formatDate( Date date, boolean adaptDay ) { StringBuilder buf = new StringBuilder(); DateTools.DateWithoutTimezone splitDate; splitDate = DateTools.toDate( date.getTime() - (adaptDay ? DateTools.MILLISECONDS_PER_DAY : 0)); append( buf, splitDate.year, 4 ); buf.append( '-' ); append( buf, splitDate.month, 2 ); buf.append( '-' ); append( buf, splitDate.day, 2 ); return buf.toString(); } public String formatTimestamp( Date date ) { StringBuilder builder = new StringBuilder(); builder.append(formatDate( date, false)); builder.append( DATE_TIME_SEPERATOR); builder.append( formatTime( date , true)); builder.append( 'Z'); String timestamp = builder.toString();; return timestamp; } /** same as formatDate(date, false). @see #formatDate(Date,boolean) */ public String formatDate( Date date ) { return formatDate( date, false ); } private void append( StringBuilder buf, int number, int minLength ) { int limit = 1; for ( int i=0;i<minLength-1;i++ ) { limit *= 10; if ( number<limit ) buf.append( '0' ); } buf.append( number ); } }
04900db4-rob
src/org/rapla/components/util/SerializableDateTimeFormat.java
Java
gpl3
7,376
/*--------------------------------------------------------------------------* | 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.components.util.iterator; import java.util.Iterator; import java.util.NoSuchElementException; /**Successivly iterates over the elements specified in the nested Iterators. Example of an recursive traversal of an Entity Tree: <pre> class RecursiveEntityIterator extends NestedIterator { public RecursiveEntityIterator(Iterator it) { super(it); } public Iterator getNestedIterator(Object obj) { return new RecursiveEntityIterator(((Entity)obj).getSubEntities()); } } </pre> */ public abstract class NestedIterator<T,S> implements Iterator<T>, Iterable<T> { protected Iterator<S> outerIt; protected Iterator<T> innerIt; T nextElement; boolean isInitialized; public NestedIterator(Iterable<S> outerIt) { this.outerIt = outerIt.iterator(); } private T nextElement() { while (outerIt.hasNext() || (innerIt != null && innerIt.hasNext())) { if (innerIt != null && innerIt.hasNext()) return innerIt.next(); innerIt = getNestedIterator(outerIt.next()).iterator(); } return null; } public abstract Iterable<T> getNestedIterator(S obj); public boolean hasNext() { if (!isInitialized) { nextElement = nextElement(); isInitialized = true; } return nextElement != null; } public void remove() { throw new UnsupportedOperationException(); } public T next() { if (!hasNext()) throw new NoSuchElementException(); T result = nextElement; nextElement = nextElement(); return result; } public Iterator<T> iterator() { return this; } }
04900db4-rob
src/org/rapla/components/util/iterator/NestedIterator.java
Java
gpl3
2,667
/*--------------------------------------------------------------------------* | 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.components.util.iterator; import java.util.Iterator; import java.util.NoSuchElementException; /** Filters the objects of an Iterator by overiding the isInIterator method*/ public abstract class FilterIterator<T> implements Iterator<T>, Iterable<T> { Iterator<? extends Object> it; Object obj; public FilterIterator(Iterable<? extends Object> it) { this.it = it.iterator(); obj = getNextObject(); } public boolean hasNext() { return obj != null; } protected abstract boolean isInIterator(Object obj); public void remove() { throw new UnsupportedOperationException(); } private Object getNextObject() { Object o; do { if ( !it.hasNext() ) { return null; } o = it.next(); } while (!isInIterator( o)); return o; } @SuppressWarnings("unchecked") public T next() { if ( obj == null) throw new NoSuchElementException(); Object result = obj; obj = getNextObject(); return (T)result; } public Iterator<T> iterator() { return this; } }
04900db4-rob
src/org/rapla/components/util/iterator/FilterIterator.java
Java
gpl3
2,122
<body> <p>Iterators used by Rapla.</p> </body>
04900db4-rob
src/org/rapla/components/util/iterator/package.html
HTML
gpl3
48
/*--------------------------------------------------------------------------* | 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.components.util.iterator; import java.util.Iterator; import java.util.NoSuchElementException; /** concatenates two Iterators */ public class IteratorChain<T> implements Iterator<T>, Iterable<T> { protected Iterator<T> firstIt; protected Iterator<T> secondIt; protected Iterator<T> thirdIt; public IteratorChain(Iterable<T> firstIt, Iterable<T> secondIt) { this( firstIt.iterator(), secondIt.iterator()); } public IteratorChain(Iterable<T> firstIt, Iterable<T> secondIt, Iterable<T> thirdIt) { this( firstIt.iterator(), secondIt.iterator(), thirdIt.iterator()); } public IteratorChain(Iterator<T> firstIt, Iterator<T> secondIt) { this.firstIt = firstIt; this.secondIt = secondIt; } public IteratorChain(Iterator<T> firstIt, Iterator<T> secondIt, Iterator<T> thirdIt) { this.firstIt = firstIt; this.secondIt = secondIt; this.thirdIt = thirdIt; } public boolean hasNext() { return (firstIt!=null && firstIt.hasNext()) || (secondIt != null && secondIt.hasNext()) || (thirdIt != null && thirdIt.hasNext()); } public void remove() { throw new UnsupportedOperationException(); } public T next() { if (firstIt!=null && !firstIt.hasNext()) { firstIt = null; } else if (secondIt!=null && !secondIt.hasNext()) { secondIt = null; } // else if (thirdIt!=null && !thirdIt.hasNext()) // { // thirdIt = null; // } if ( firstIt != null ) return firstIt.next(); else if ( secondIt != null) return secondIt.next(); else if (thirdIt != null) return thirdIt.next(); else throw new NoSuchElementException(); } public Iterator<T> iterator() { return this; } }
04900db4-rob
src/org/rapla/components/util/iterator/IteratorChain.java
Java
gpl3
2,844
/*--------------------------------------------------------------------------* | 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.components.util.iterator; import java.util.NoSuchElementException; /** This class can iterate over a string containing a list of integers. Its tuned for performance, so it will return int instead of Integer */ public class IntIterator { int parsePosition = 0; String text; char[] delimiter; int len; int next; boolean hasNext=false; char endingDelimiter; public IntIterator(String text,char delimiter) { this(text,new char[] {delimiter}); } public IntIterator(String text,char[] delimiter) { this.text = text; len = text.length(); this.delimiter = delimiter; parsePosition = 0; parseNext(); } public boolean hasNext() { return hasNext; } public int next() { if (!hasNext()) throw new NoSuchElementException(); int result = next; parseNext(); return result; } private void parseNext() { boolean isNegative = false; int relativePos = 0; next = 0; if (parsePosition == len) { hasNext = false; return; } while (parsePosition< len) { char c = text.charAt(parsePosition ); if (relativePos == 0 && c=='-') { isNegative = true; parsePosition++; continue; } boolean delimiterFound = false; for ( char d:delimiter) { if (c == d ) { parsePosition++; delimiterFound = true; break; } } if (delimiterFound || c == endingDelimiter ) { break; } int digit = c-'0'; if (digit<0 || digit>9) { hasNext = false; return; } next *= 10; next += digit; parsePosition++; relativePos++; } if (isNegative) next *= -1; hasNext = parsePosition > 0; } public int getPos() { return parsePosition; } }
04900db4-rob
src/org/rapla/components/util/iterator/IntIterator.java
Java
gpl3
2,832
/*--------------------------------------------------------------------------* | 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.components.util; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** Tools for manipulating dates. * At the moment of writing rapla internaly stores all appointments * in the GMT timezone. */ public abstract class DateTools { public static final int DAYS_PER_WEEK= 7; public static final long MILLISECONDS_PER_MINUTE = 1000 * 60; public static final long MILLISECONDS_PER_HOUR = MILLISECONDS_PER_MINUTE * 60; public static final long MILLISECONDS_PER_DAY = 24 * MILLISECONDS_PER_HOUR; public static final long MILLISECONDS_PER_WEEK = 7 * MILLISECONDS_PER_DAY; public static final int SUNDAY = 1, MONDAY = 2, TUESDAY = 3, WEDNESDAY = 4, THURSDAY = 5, FRIDAY = 6, SATURDAY = 7; public static int getHourOfDay(long date) { return (int) ((date % MILLISECONDS_PER_DAY)/ MILLISECONDS_PER_HOUR); } public static int getMinuteOfHour(long date) { return (int) ((date % MILLISECONDS_PER_HOUR)/ MILLISECONDS_PER_MINUTE); } public static int getMinuteOfDay(long date) { return (int) ((date % MILLISECONDS_PER_DAY)/ MILLISECONDS_PER_MINUTE); } public static String formatDate(Date date) { SerializableDateTimeFormat format = new SerializableDateTimeFormat(); String string = format.formatDate( date); return string; } public static String formatDate(Date date, @SuppressWarnings("unused") Locale locale) { // FIXME has to be replaced with locale implementation // DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT,locale); // format.setTimeZone(DateTools.getTimeZone()); // String string = format.format( date); // return string; return formatDate(date); } public static String formatTime(Date date) { SerializableDateTimeFormat format = new SerializableDateTimeFormat(); String string = format.formatTime( date); return string; } public static String formatDateTime(Date date) { SerializableDateTimeFormat format = new SerializableDateTimeFormat(); String dateString = format.formatDate( date); String timeString = format.formatTime( date); String string = dateString + " " + timeString; return string; } public static int getDaysInMonth(int year, int month) { int _month = month+1; if ( _month == 2) { if ( isLeapYear(year)) { return 29; } return 28; } else if ( _month == 4 || _month == 6 || _month == 9 || _month == 11 ) { return 30; } else { return 31; } } public static boolean isLeapYear(int year) { return year % 4 == 0 && ((year % 100) != 0 || (year % 400) == 0); } /** sets time of day to 0:00. @see #cutDate(Date) */ public static long cutDate(long date) { long dateModMillis = date % MILLISECONDS_PER_DAY; if ( dateModMillis == 0) { return date; } if ( date >= 0) { return (date - dateModMillis); } else { return (date - (MILLISECONDS_PER_DAY + dateModMillis)); } } public static boolean isMidnight(long date) { return cutDate( date ) == date ; } public static boolean isMidnight(Date date) { return isMidnight( date.getTime()); } /** sets time of day to 0:00. */ public static Date cutDate(Date date) { long time = date.getTime(); if ( time %MILLISECONDS_PER_DAY == 0) { return date; } return new Date(cutDate(time)); } private static TimeZone timeZone =TimeZone.getTimeZone("GMT"); /** same as TimeZone.getTimeZone("GMT"). */ public static TimeZone getTimeZone() { return timeZone; } /** sets time of day to 0:00 and increases day. @see #fillDate(Date) */ public static long fillDate(long date) { // cut date long cuttedDate = (date - (date % MILLISECONDS_PER_DAY)); return cuttedDate + MILLISECONDS_PER_DAY; } public static Date fillDate(Date date) { return new Date(fillDate(date.getTime())); } /** Monday 24:00 = tuesday 0:00. But the first means end of monday and the second start of tuesday. The default DateFormat always displays tuesday. If you want to edit the first interpretation in calendar components. call addDay() to add 1 day to the given date before displaying and subDay() for mapping a day back after editing. @see #subDay @see #addDays */ public static Date addDay(Date date) { return addDays( date, 1); } public static Date addYear(Date date) { return addYears(date, 1); } public static Date addWeeks(Date date, int weeks) { Date result = new Date(date.getTime() + MILLISECONDS_PER_WEEK * weeks); return result; } public static Date addYears(Date date, int yearModifier) { int monthModifier = 0; return modifyDate(date, yearModifier, monthModifier); } public static Date addMonth(Date startDate) { return addMonths(startDate, 1); } public static Date addMonths(Date startDate, int monthModifier) { int yearModifier = 0; return modifyDate(startDate, yearModifier, monthModifier); } private static Date modifyDate(Date startDate, int yearModifier, int monthModifier) { long original = startDate.getTime(); long millis = original - DateTools.cutDate( original ); DateWithoutTimezone date = toDate( original); int year = date.year + yearModifier; int month = date.month + monthModifier; if ( month < 1 ) { year += month/ 12 -1 ; month = ((month +11) % 12) + 1; } if ( month >12 ) { year += month/ 12; month = ((month -1) % 12) + 1; } int day = date.day ; long newDate = toDate(year, month, day); Date result = new Date( newDate + millis); return result; } /** see #addDay*/ public static Date addDays(Date date,long days) { return new Date(date.getTime() + MILLISECONDS_PER_DAY * days); } /** @see #addDay @see #subDays */ public static Date subDay(Date date) { return new Date(date.getTime() - MILLISECONDS_PER_DAY); } /** @see #addDay */ public static Date subDays(Date date,int days) { return new Date(date.getTime() - MILLISECONDS_PER_DAY * days); } /** returns if the two dates are one the same date. * Dates must be in GMT */ static public boolean isSameDay( Date d1, Date d2) { return cutDate( d1 ).equals( cutDate ( d2 )); } /** returns if the two dates are one the same date. * Dates must be in GMT */ static public boolean isSameDay( long d1, long d2) { return cutDate( d1 ) == cutDate ( d2 ); } /** returns the day of week SUNDAY = 1, MONDAY = 2, TUESDAY = 3, WEDNESDAY = 4, THURSDAY = 5, FRIDAY = 6, SATURDAY = 7 */ public static int getWeekday(Date date) { long days = countDays(0,date.getTime()); int weekday_zero = THURSDAY; int alt = (int) days%7; int weekday = weekday_zero + alt; if ( weekday > 7) { weekday -=7; } else if ( weekday <=0 ) { weekday += 7 ; } return weekday; } public static int getDayOfWeekInMonth(Date date) { DateWithoutTimezone date2 = toDate( date.getTime()); int day = date2.day; int occurances = (day-1) / 7 + 1; return occurances; } // public static int getWeekOfYear(Date date) // { // // 1970/1/1 is a thursday // long millis = date.getTime(); // long daysSince1970 = millis >= 0 ? millis/ MILLISECONDS_PER_DAY : ((millis + MILLISECONDS_PER_DAY - 1)/ MILLISECONDS_PER_DAY + 1) ; // int weekday = daysSince1970 + 4; // // } public static int getDayOfMonth(Date date) { DateWithoutTimezone date2 = toDate( date.getTime()); int result = date2.day; return result; } // /** uses the calendar-object for date comparison. // * Use this for non GMT Dates*/ // static public boolean isSameDay( Calendar calendar, Date d1, Date d2 ) { // calendar.setTime( d1 ); // int era1 = calendar.get( Calendar.ERA ); // int year1 = calendar.get( Calendar.YEAR ); // int day_of_year1 = calendar.get( Calendar.DAY_OF_YEAR ); // calendar.setTime( d2 ); // int era2 = calendar.get( Calendar.ERA ); // int year2 = calendar.get( Calendar.YEAR ); // int day_of_year2 = calendar.get( Calendar.DAY_OF_YEAR ); // return ( era1 == era2 && year1 == year2 && day_of_year1 == day_of_year2 ); // } static public long countDays(Date start,Date end) { return countDays(start.getTime(), end.getTime()); } static public long countDays(long start,long end) { return (cutDate(end) - cutDate(start)) / MILLISECONDS_PER_DAY; } static public long countMinutes(Date start, Date end) { return (end.getTime()- start.getTime())/ MILLISECONDS_PER_MINUTE; } static public long countMinutes(long start, long end){ return (end-start)/ MILLISECONDS_PER_MINUTE; } // static public Calendar createGMTCalendar() // { // return Calendar.getInstance( GMT); // } static int date_1970_1_1 = calculateJulianDayNumberAtNoon(1970, 1, 1); /** Return a the whole number, with no fraction. The JD at noon is 1 more than the JD at midnight. */ private static int calculateJulianDayNumberAtNoon(int y, int m, int d) { //http://www.hermetic.ch/cal_stud/jdn.htm int result = (1461 * (y + 4800 + (m - 14) / 12)) / 4 + (367 * (m - 2 - 12 * ((m - 14) / 12))) / 12 - (3 * ((y + 4900 + (m - 14) / 12) / 100)) / 4 + d - 32075; return result; } /** * * @param year * @param month ranges from 1-12 * @param day * @return */ public static long toDate(int year, int month, int day ) { int days = calculateJulianDayNumberAtNoon(year, month, day); int diff = days - date_1970_1_1; long millis = diff * MILLISECONDS_PER_DAY; return millis; } public static class DateWithoutTimezone { public int year; public int month; public int day; public String toString() { return year+"-" +month + "-" + day; } } public static class TimeWithoutTimezone { public int hour; public int minute; public int second; public int milliseconds; public String toString() { return hour+":" +minute + ":" + second + "." + milliseconds; } } public static TimeWithoutTimezone toTime(long millis) { long millisInDay = millis - DateTools.cutDate( millis); TimeWithoutTimezone result = new TimeWithoutTimezone(); result.hour = (int) (millisInDay / MILLISECONDS_PER_HOUR); result.minute = (int) ((millisInDay % MILLISECONDS_PER_HOUR) / MILLISECONDS_PER_MINUTE); result.second = (int) ((millisInDay % MILLISECONDS_PER_MINUTE) / 1000); result.milliseconds = (int) (millisInDay % 1000 ); return result; } public static long toTime(int hour, int minute, int second) { return toTime(hour, minute, second, 0); } public static long toTime(int hour, int minute, int second, int millisecond) { long millis = hour * MILLISECONDS_PER_HOUR; millis += minute * MILLISECONDS_PER_MINUTE; millis += second * 1000; millis += millisecond; return millis; } public static DateWithoutTimezone toDate(long millis) { // special case for negative milliseconds as day rounding needs to get the lower day int day = millis >= 0 ? (int) (millis/ MILLISECONDS_PER_DAY) : (int) (( millis + MILLISECONDS_PER_DAY -1) / MILLISECONDS_PER_DAY); int julianDateAtNoon = day + date_1970_1_1; DateWithoutTimezone result = fromJulianDayNumberAtNoon( julianDateAtNoon); return result; } private static DateWithoutTimezone fromJulianDayNumberAtNoon(int julianDateAtNoon) { //http://www.hermetic.ch/cal_stud/jdn.htm int l = julianDateAtNoon + 68569; int n = (4 * l) / 146097; l = l - (146097 * n + 3) / 4; int i = (4000 * (l + 1)) / 1461001; l = l - (1461 * i) / 4 + 31; int j = (80 * l) / 2447; int d = l - (2447 * j) / 80; l = j / 11; int m = j + 2 - (12 * l); int y = 100 * (n - 49) + i + l; DateWithoutTimezone dt = new DateWithoutTimezone(); dt.year = y; dt.month = m; dt.day = d; return dt; } /** returns the largest date null dates count as postive infinity*/ public static Date max(Date... param) { Date max = null; boolean set = false; for (Date d:param) { if ( !set) { max = d; set = true; } else if ( max != null ) { if ( d == null || max.before( d)) { max = d; } } } return max; } }
04900db4-rob
src/org/rapla/components/util/DateTools.java
Java
gpl3
14,003
package org.rapla.components.util; public interface Cancelable { public void cancel(); }
04900db4-rob
src/org/rapla/components/util/Cancelable.java
Java
gpl3
96
package org.rapla.components.util; public interface Predicate<T> { boolean apply(T t); }
04900db4-rob
src/org/rapla/components/util/Predicate.java
Java
gpl3
95
/*--------------------------------------------------------------------------* | 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.components.util; /** Some of the assert functionality of 1.4 for 1.3 versions of Rapla*/ public class Assert { static String NOT_NULL_ASSERTION = "notNull-Assertion"; static String IS_TRUE_ASSERTION = "isTrue-Assertion"; static String ASSERTION_FAIL = "Assertion fail"; static boolean _bActivate = true; public static void notNull(Object obj,String text) { if ( obj == null && isActivated()) { doAssert(getText(NOT_NULL_ASSERTION,text)); } } public static void notNull(Object obj) { if ( obj == null && isActivated()) { doAssert(getText(NOT_NULL_ASSERTION,"")); } } public static void isTrue(boolean condition,String text) { if ( !condition && isActivated()) { doAssert(getText(IS_TRUE_ASSERTION,text)); } // end of if () } public static void isTrue(boolean condition) { if ( !condition && isActivated()) { doAssert(getText(IS_TRUE_ASSERTION,"")); } // end of if () } public static void fail() throws AssertionError { doAssert(getText(ASSERTION_FAIL,"")); } public static void fail(String text) throws AssertionError { doAssert(getText(ASSERTION_FAIL,text)); } private static void doAssert(String text) throws AssertionError { System.err.println(text); throw new AssertionError(text); } static boolean isActivated() { return _bActivate; } static void setActivated(boolean bActivate) { _bActivate = bActivate; } static String getText(String type, String text) { return ( type + " failed '" + text + "'"); } }
04900db4-rob
src/org/rapla/components/util/Assert.java
Java
gpl3
2,616
package org.rapla.components.util.undo; import java.util.EventListener; public interface CommandHistoryChangedListener extends EventListener { public void historyChanged(); }
04900db4-rob
src/org/rapla/components/util/undo/CommandHistoryChangedListener.java
Java
gpl3
190
package org.rapla.components.util.undo; import java.util.ArrayList; import java.util.List; import java.util.Vector; /** * This is where all the committed actions are saved. * A list will be initialized, every action is an item of this list. * There is a list for the calendar view, and one for the edit view. * @author Jens Fritz * */ //Erstellt von Dominick Krickl-Vorreiter public class CommandHistory { private List<CommandUndo<?>> history = new ArrayList<CommandUndo<?>>(); private int current = -1; private int maxSize = 100; private Vector<CommandHistoryChangedListener> listenerList = new Vector<CommandHistoryChangedListener>(); private void fireChangeEvent() { for (CommandHistoryChangedListener listener: listenerList.toArray(new CommandHistoryChangedListener[] {})) { listener.historyChanged(); } } public <T extends Exception> boolean storeAndExecute(CommandUndo<T> cmd) throws T { while (!history.isEmpty() && (current < history.size() - 1)) { history.remove(history.size() - 1); } while (history.size() >= maxSize) { history.remove(0); current--; } if (cmd.execute()) { history.add(cmd); current++; fireChangeEvent(); return true; } else { return false; } } public void undo() throws Exception { if (!history.isEmpty() && (current >= 0)) { if (history.get(current).undo()) { current--; } fireChangeEvent(); } } public void redo() throws Exception { if (!history.isEmpty() && (current < history.size() - 1)) { if (history.get(current + 1).execute()) { current++; } fireChangeEvent(); } } public void clear() { history.clear(); current = -1; fireChangeEvent(); } public int size() { return history.size(); } public int getCurrent() { return current; } public int getMaxSize() { return maxSize; } public void setMaxSize(int maxSize) { if (maxSize > 0) { this.maxSize = maxSize; } } public boolean canUndo() { return current >= 0; } public boolean canRedo() { return current < history.size() - 1; } public String getRedoText() { if ( !canRedo()) { return ""; } else { return history.get(current + 1).getCommandoName(); } } public String getUndoText() { if ( !canUndo()) { return ""; } else { return history.get(current ).getCommandoName(); } } public void addCommandHistoryChangedListener(CommandHistoryChangedListener actionListener) { this.listenerList.add( actionListener); } public void removeCommandHistoryChangedListener(CommandHistoryChangedListener actionListener) { this.listenerList.remove( actionListener); } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Undo=["); for (int i=current;i>0;i--) { CommandUndo<?> command = history.get(i); builder.append(command.getCommandoName()); if ( i > 0) { builder.append(", "); } } builder.append("]"); builder.append(", "); builder.append("Redo=["); for (int i=current+1;i<history.size();i++) { CommandUndo<?> command = history.get(i); builder.append(command.getCommandoName()); if ( i < history.size() -1) { builder.append(", "); } } builder.append("]"); return builder.toString(); } }
04900db4-rob
src/org/rapla/components/util/undo/CommandHistory.java
Java
gpl3
3,624
package org.rapla.components.util.undo; //Erstellt von Dominick Krickl-Vorreiter public interface CommandUndo<T extends Exception> { // Der Rückgabewert signalisiert, ob alles korrekt ausgeführt wurde public boolean execute() throws T; public boolean undo() throws T; public String getCommandoName(); }
04900db4-rob
src/org/rapla/components/util/undo/CommandUndo.java
Java
gpl3
327
/*--------------------------------------------------------------------------* | 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.components.util; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Enumeration; import java.util.StringTokenizer; /** Some IOHelper methods. */ abstract public class IOUtil { /** returns the path of the url without the last path component */ public static URL getBase(URL url) { try { String file = url.getPath(); String separator = "/"; if (url.getProtocol().equals("file") && file.indexOf(File.separator)>0) { separator = File.separator; } int index = file.lastIndexOf(separator); String dir = (index<0) ? file: file.substring(0,index + 1); return new URL(url.getProtocol() ,url.getHost() ,url.getPort() ,dir); } catch ( MalformedURLException e) { // This should not happen e.printStackTrace(); throw new RuntimeException("Unknown error while getting the base of the url!"); } // end of try-catch } /** reads the content form an url into a ByteArray*/ public static byte[] readBytes(URL url) throws IOException { InputStream in = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); try { in = url.openStream(); byte[] buffer = new byte[1024]; int count = 0; do { out.write(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); return out.toByteArray(); } finally { if ( in != null) { in.close(); } // end of if () } } /** same as {@link URLDecoder#decode}. * But calls the deprecated method under 1.3. */ public static String decode(String s,String enc) throws UnsupportedEncodingException { return callEncodeDecode(URLDecoder.class,"decode",s,enc); } /** same as {@link URLEncoder#encode}. * But calls the deprecated method under 1.3. */ public static String encode(String s,String enc) throws UnsupportedEncodingException { return callEncodeDecode(URLEncoder.class,"encode",s,enc); } private static String callEncodeDecode(Class<?> clazz,String methodName,String s,String enc) throws UnsupportedEncodingException { Assert.notNull(s); Assert.notNull(enc); try { Method method = clazz.getMethod(methodName ,new Class[] { String.class ,String.class } ); return (String) method.invoke(null,new Object[] {s,enc}); } catch (NoSuchMethodException ex) { try { Method method = URLDecoder.class.getMethod(methodName ,new Class[] {String.class} ); return (String) method.invoke(null,new Object[] {s}); } catch (Exception ex2) { ex2.printStackTrace(); throw new IllegalStateException("Should not happen" + ex2.getMessage()); } } catch (InvocationTargetException ex) { throw (UnsupportedEncodingException) ex.getTargetException(); } catch (IllegalAccessException ex) { ex.printStackTrace(); throw new IllegalStateException("Should not happen" + ex.getMessage()); } } /** returns a BufferedInputStream from the url. If the url-protocol is "file" no url connection will be opened. */ public static InputStream getInputStream(URL url) throws IOException { if (url.getProtocol().equals("file")) { String path = decode(url.getPath(),"UTF-8"); return new BufferedInputStream(new FileInputStream(path)); } else { return new BufferedInputStream(url.openStream()); } // end of else } public static File getFileFrom(URL url) throws IOException { String path = decode(url.getPath(),"UTF-8"); return new File( path ); } /** copies a file. * @param srcPath the source-path. Thats the path of the file that should be copied. * @param destPath the destination-path */ public static void copy( String srcPath, String destPath) throws IOException{ copy( srcPath, destPath, false); } /** copies a file. * @param srcPath the source-path. Thats the path of the file that should be copied. * @param destPath the destination-path */ public static void copy( String srcPath, String destPath,boolean onlyOverwriteIfNewer ) throws IOException{ copy ( new File( srcPath ) , new File( destPath ), onlyOverwriteIfNewer ); } /** copies a file. */ public static void copy(File srcFile, File destFile, boolean onlyOverwriteIfNewer) throws IOException { if ( ! srcFile.exists() ) { throw new IOException( srcFile.getPath() + " doesn't exist!!"); } if ( destFile.exists() && destFile.lastModified() >= srcFile.lastModified() && onlyOverwriteIfNewer) { return; } FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream( srcFile ); out = new FileOutputStream( destFile); copyStreams ( in, out ); } finally { if ( in != null ) in.close(); if ( out != null ) out.close(); } } /** copies the contents of the input stream to the output stream. * @param in * @param out * @throws IOException */ public static void copyStreams( InputStream in, OutputStream out ) throws IOException { byte[] buf = new byte[ 32000 ]; int n = 0; while ( n != -1 ) { out.write( buf, 0, n ); n = in.read(buf, 0, buf.length ); } return; } public static void deleteAll(File f) { if (f.isDirectory()) { File[] files = f.listFiles(); for (File file:files) { deleteAll(file); } } f.delete(); } /** returns the relative path of file to base. * @throws IOException if position of file is not relative to base */ public static String getRelativePath(File base,File file) throws IOException { String filePath = file.getAbsoluteFile().getCanonicalPath(); String basePath = base.getAbsoluteFile().getCanonicalPath(); int start = filePath.indexOf(basePath); if (start != 0) throw new IOException(basePath + " not ancestor of " + filePath); return filePath.substring(basePath.length()); } /** returns the relative path of file to base. * same as {@link #getRelativePath(File, File)} but replaces windows-plattform-specific * file separator <code>\</code> with <code>/</code> * @throws IOException if position of file is not relative to base */ public static String getRelativeURL(File base,File file) throws IOException { StringBuffer result= new StringBuffer(getRelativePath(base,file)); for (int i=0;i<result.length();i++) { if (result.charAt(i) == '\\') result.setCharAt(i, '/'); } return result.toString(); } public static File[] getJarFiles(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()); } } } } return completeList.toArray(new File[] {}); } public static String getStackTraceAsString(Throwable ex) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(bytes,true); writer.println("<h2>" + ex.getMessage() +"</h2><br/>"); ex.printStackTrace(writer); while (true) { ex = ex.getCause(); if (ex != null) { writer.println("<br/><h2>Caused by: "+ ex.getMessage() + "</h2><br/>"); ex.printStackTrace(writer); } else { break; } } return bytes.toString(); } public static boolean isSigned() { try { final ClassLoader classLoader = IOUtil.class.getClassLoader(); { final Enumeration<URL> resources = classLoader.getResources("META-INF/RAPLA.SF"); if (resources.hasMoreElements() ) return true; } { final Enumeration<URL> resources = classLoader.getResources("META-INF/RAPLA.DSA"); if (resources.hasMoreElements() ) return true; } } catch ( IOException ex) { } return false; } }
04900db4-rob
src/org/rapla/components/util/IOUtil.java
Java
gpl3
11,232
package org.rapla.components.util.xml; import java.util.Collections; import java.util.Map; public class RaplaSAXAttributes { final Map<String,String> attributeMap; public RaplaSAXAttributes(Map<String,String> map) { this.attributeMap = map; } public String getValue(@SuppressWarnings("unused") String uri,String key) { return getValue( key); } public String getValue(String key) { return attributeMap.get( key); } public Map<String, String> getMap() { return Collections.unmodifiableMap( attributeMap); } }
04900db4-rob
src/org/rapla/components/util/xml/RaplaSAXAttributes.java
Java
gpl3
567
package org.rapla.components.util.xml; public interface RaplaSAXHandler { public void startElement(String namespaceURI, String localName, RaplaSAXAttributes atts) throws RaplaSAXParseException; public void endElement( String namespaceURI, String localName ) throws RaplaSAXParseException; public void characters( char[] ch, int start, int length ); }
04900db4-rob
src/org/rapla/components/util/xml/RaplaSAXHandler.java
Java
gpl3
393
/*---------------------------------------------------------------------------* | (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.components.util.xml; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; final public class XMLReaderAdapter { static SAXParserFactory spfvalidating; static SAXParserFactory spfnonvalidating; static private SAXParserFactory getFactory( boolean validating) { if ( validating && spfvalidating != null) { return spfvalidating; } if ( !validating && spfnonvalidating != null) { return spfnonvalidating; } SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(validating); if ( validating) { spfvalidating = spf; } else { spfnonvalidating = spf; } return spf; } public static XMLReader createXMLReader(boolean validating) throws SAXException { try { SAXParserFactory spf = getFactory(validating); return spf.newSAXParser().getXMLReader(); } catch (Exception ex2) { throw new SAXException("Couldn't create XMLReader " + ex2.getMessage(), ex2); } } }
04900db4-rob
src/org/rapla/components/util/xml/XMLReaderAdapter.java
Java
gpl3
2,058
package org.rapla.components.util.xml; import org.rapla.framework.logger.Logger; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class RaplaErrorHandler implements ErrorHandler { Logger logger; public RaplaErrorHandler(Logger logger) { this.logger = logger; } public void error(SAXParseException exception) throws SAXException { throw exception; } public void fatalError(SAXParseException exception) throws SAXException { throw exception; } public void warning(SAXParseException exception) throws SAXException { if (logger != null) logger.error("Warning: " + getString(exception)); } public String getString(SAXParseException exception) { // return "Line " + exception.getLineNumber() // + "\t Col " + exception.getColumnNumber() // + "\t " + return exception.getMessage(); } }
04900db4-rob
src/org/rapla/components/util/xml/RaplaErrorHandler.java
Java
gpl3
1,031
/*--------------------------------------------------------------------------* | 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.components.util.xml; import java.io.IOException; import java.util.Map; /** Provides some basic functionality for xml-file creation. This * is the SAX like alternative to the creation of a DOM Tree.*/ public class XMLWriter { Appendable appendable; //BufferedWriter writer; boolean xmlSQL = false; public void setWriter(Appendable writer) { this.appendable = writer; } public Appendable getWriter() { return this.appendable; } int level = 0; private void indent() throws IOException { if( !xmlSQL) //BJO do not indent for sql db, XML_VALUE column will be too small for (int i = 0; i < level * 3; i++) write(' '); } protected void increaseIndentLevel() { level ++; } protected void decreaseIndentLevel() { if (level > 0) level --; } public int getIndentLevel() { return level; } public void setIndentLevel(int level) { this.level = level; } public static String encode(String text) { boolean needsEncoding = false; int size = text.length(); for ( int i= 0; i<size && !needsEncoding; i++) { char c = text.charAt(i); switch ( c) { case '<': case '>': case '&': case '"': needsEncoding = true; break; } } if ( !needsEncoding ) return text; StringBuilder buf = new StringBuilder(); for ( int i= 0; i<size; i++) { char c = text.charAt(i); switch ( c) { case '<': buf.append("&lt;"); break; case '>': buf.append("&gt;"); break; case '&': buf.append("&amp;"); break; case '"': buf.append("&quot;"); break; default: buf.append(c); break; } // end of switch () } // end of for () return buf.toString(); } protected void printEncode(String text) throws IOException { if (text == null) return; write( encode(text) ); } protected void openTag(String start) throws IOException { indent(); write('<'); write(start); level++; } protected void openElement(String start) throws IOException { indent(); write('<'); write(start); write('>');newLine(); level++; } protected void openElementOnLine(String start) throws IOException { indent(); write('<'); write(start); write('>'); level++; } protected void att(Map<String,String> attributes) throws IOException{ for (Map.Entry<String, String> entry: attributes.entrySet()) { att(entry.getKey(),entry.getValue()); } } protected void att(String attribute,String value) throws IOException { write(' '); write(attribute); write('='); write('"'); printEncode(value); write('"'); } protected void closeTag() throws IOException { write('>');newLine(); } protected void closeTagOnLine() throws IOException{ write('>'); } protected void closeElementOnLine(String element) throws IOException { level--; write('<'); write('/'); write(element); write('>'); } protected void closeElement(String element) throws IOException { level--; indent(); write('<'); write('/'); write(element); write('>');newLine(); } protected void closeElementTag() throws IOException { level--; write('/'); write('>');newLine(); } /** writes the line to the specified PrintWriter */ public void println(String text) throws IOException { indent(); write(text);newLine(); } protected void newLine() throws IOException { appendable.append("\n"); } protected void write(String text) throws IOException { appendable.append( text); } protected void write(char c) throws IOException { appendable.append( c ); } /** writes the text to the specified PrintWriter */ public void print(String text) throws IOException { write(text); } /** writes the line to the specified PrintWriter */ public void println() throws IOException { newLine(); } public void setSQL(boolean sql) { this.xmlSQL = sql; } }
04900db4-rob
src/org/rapla/components/util/xml/XMLWriter.java
Java
gpl3
5,627
/*--------------------------------------------------------------------------* | 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.components.util.xml; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; public class RaplaContentHandler extends DefaultHandler { Locator locator; RaplaSAXHandler handler; public RaplaContentHandler(RaplaSAXHandler handler) { this.handler = handler; } public void setDocumentLocator( Locator locator ) { this.locator = locator; } final public void startElement( String namespaceURI, String localName, String qName, Attributes atts ) throws SAXException { try { Map<String,String> attributeMap; if ( atts != null) { int length = atts.getLength(); if ( length == 0) { attributeMap = Collections.emptyMap(); } else if ( length == 1) { String key = atts.getLocalName( 0); String value = atts.getValue( 0); attributeMap = Collections.singletonMap(key, value); } else { attributeMap = new LinkedHashMap<String, String>(); for ( int i=0;i<length;i++) { String key = atts.getLocalName( i); String value = atts.getValue( i); attributeMap.put( key, value); } } } else { attributeMap = Collections.emptyMap(); } handler.startElement( namespaceURI, localName, new RaplaSAXAttributes(attributeMap) ); } catch (RaplaSAXParseException ex) { throw new SAXParseException(ex.getMessage(), locator, ex); } catch (Exception ex) { throw new SAXException( ex ); } } final public void endElement( String namespaceURI, String localName, String qName ) throws SAXException { try { handler.endElement( namespaceURI, localName); } catch ( RaplaSAXParseException ex) { throw new SAXParseException(ex.getMessage(), locator, ex); } } final public void characters( char[] ch, int start, int length ) throws SAXException { handler.characters( ch, start, length ); } }
04900db4-rob
src/org/rapla/components/util/xml/RaplaContentHandler.java
Java
gpl3
3,236
package org.rapla.components.util.xml; import org.rapla.framework.RaplaException; public class RaplaSAXParseException extends RaplaException{ public RaplaSAXParseException(String text, Throwable cause) { super(text, cause); } /** * */ private static final long serialVersionUID = 1L; }
04900db4-rob
src/org/rapla/components/util/xml/RaplaSAXParseException.java
Java
gpl3
303
/*--------------------------------------------------------------------------* | 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.components.util.xml; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; /** Reads the data in xml format from an InputSource into the LocalCache and converts it to a newer version if necessary. */ public interface RaplaNonValidatedInput { public void read(String xml, RaplaSAXHandler handler, Logger logger) throws RaplaException; }
04900db4-rob
src/org/rapla/components/util/xml/RaplaNonValidatedInput.java
Java
gpl3
1,352
<body> <p>Some more helpful tools.</p> </body>
04900db4-rob
src/org/rapla/components/util/package.html
HTML
gpl3
48
/*--------------------------------------------------------------------------* | 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.components.util; import java.util.Vector; /** Creates a new thread that successively executes the queued command objects * @see Command * @deprecated use CommandScheduler instead */ @Deprecated public class CommandQueue { private Vector<Command> v = new Vector<Command>(); public synchronized void enqueue(Command object) { v.addElement( object ); } public synchronized Command dequeue() { if ( v.size() == 0) return null; Object firstElement =v.firstElement(); if ( firstElement != null) { v.removeElementAt( 0 ); } return (Command) firstElement; } public void dequeueAll() { while ( dequeue() != null){} } /** Creates a new Queue for Command Object. The commands will be executed in succession in a seperate Daemonthread. @see Command */ public static CommandQueue createCommandQueue() { CommandQueue commandQueue = new CommandQueue(); Thread eventThread= new MyEventThread(commandQueue); eventThread.setDaemon(true); eventThread.start(); return commandQueue; } static class MyEventThread extends Thread { CommandQueue commandQueue; MyEventThread(CommandQueue commandQueue) { this.commandQueue = commandQueue; } public void run() { try { while (true) { Command command = commandQueue.dequeue(); if (command == null) { sleep(100); continue; } try { command.execute(); } catch (Exception ex) { ex.printStackTrace(); } } } catch (InterruptedException ex) { } } } }
04900db4-rob
src/org/rapla/components/util/CommandQueue.java
Java
gpl3
2,853
package org.rapla; import java.util.Arrays; /** Object that encapsulates the login information. * For admin users it is possible to connect as an other user. */ public class ConnectInfo { String username; char[] password; String connectAs; public ConnectInfo(String username, char[] password, String connectAs) { this.username = username; this.password = password; this.connectAs = connectAs; } public ConnectInfo(String username, char[] password) { this( username, password, null); } public String getUsername() { return username; } public char[] getPassword() { return password; } public String getConnectAs() { return connectAs; } @Override public String toString() { return "ReconnectInfo [username=" + username + ", password=" + Arrays.toString(password) + ", connectAs=" + connectAs + "]"; } }
04900db4-rob
src/org/rapla/ConnectInfo.java
Java
gpl3
976
/*--------------------------------------------------------------------------* | 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.server; import org.rapla.facade.ClientFacade; import org.rapla.framework.RaplaContext; /** Encapsulates a StorageOperator. This service is responsible for <ul> <li>synchronizing update and remove request from clients and passing them to the storage-operator</li> <li>authentification of the clients</li> <li>notifying subscribed clients when the stored-data has changed</li> </ul> */ public interface ServerService { ClientFacade getFacade(); RaplaContext getContext(); }
04900db4-rob
src/org/rapla/server/ServerService.java
Java
gpl3
1,449
/*--------------------------------------------------------------------------* | 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.server; import org.rapla.entities.User; import org.rapla.framework.RaplaContextException; import org.rapla.framework.logger.Logger; /** An interface to access the SessionInformation. An implementation of * RemoteSession gets passed to the creation RaplaRemoteService.*/ public interface RemoteSession { boolean isAuthentified(); User getUser() throws RaplaContextException; Logger getLogger(); //String getAccessToken(); }
04900db4-rob
src/org/rapla/server/RemoteSession.java
Java
gpl3
1,385
package org.rapla.server.internal; import java.util.Date; import java.util.TimeZone; import org.rapla.components.util.DateTools; import org.rapla.server.TimeZoneConverter; public class TimeZoneConverterImpl implements TimeZoneConverter { TimeZone zone; TimeZone importExportTimeZone; public TimeZoneConverterImpl() { zone = DateTools.getTimeZone(); TimeZone systemTimezone = TimeZone.getDefault(); importExportTimeZone = systemTimezone; } public TimeZone getImportExportTimeZone() { return importExportTimeZone; } public void setImportExportTimeZone(TimeZone importExportTimeZone) { this.importExportTimeZone = importExportTimeZone; } public long fromRaplaTime(TimeZone timeZone,long raplaTime) { long offset = TimeZoneConverterImpl.getOffset(zone,timeZone, raplaTime); return raplaTime - offset; } public long toRaplaTime(TimeZone timeZone,long time) { long offset = TimeZoneConverterImpl.getOffset(zone,timeZone,time); return time + offset; } public Date fromRaplaTime(TimeZone timeZone,Date raplaTime) { return new Date( fromRaplaTime(timeZone, raplaTime.getTime())); } public Date toRaplaTime(TimeZone timeZone,Date time) { return new Date( toRaplaTime(timeZone, time.getTime())); } public static int getOffset(TimeZone zone1,TimeZone zone2,long time) { int offsetRapla = zone1.getOffset(time); int offsetSystem = zone2.getOffset(time); return offsetSystem - offsetRapla; } }
04900db4-rob
src/org/rapla/server/internal/TimeZoneConverterImpl.java
Java
gpl3
1,504
/*--------------------------------------------------------------------------* | 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.server.internal; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.servlet.http.HttpServletRequest; import net.fortuna.ical4j.model.TimeZoneRegistry; import net.fortuna.ical4j.model.TimeZoneRegistryFactory; import org.rapla.ConnectInfo; import org.rapla.RaplaMainContainer; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.entities.domain.Permission; import org.rapla.entities.internal.UserImpl; import org.rapla.facade.ClientFacade; import org.rapla.facade.RaplaComponent; import org.rapla.facade.internal.FacadeImpl; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.framework.internal.ComponentInfo; import org.rapla.framework.internal.ContainerImpl; import org.rapla.framework.internal.RaplaLocaleImpl; import org.rapla.framework.internal.RaplaMetaConfigInfo; import org.rapla.framework.logger.Logger; import org.rapla.plugin.export2ical.Export2iCalPlugin; import org.rapla.rest.gwtjsonrpc.common.FutureResult; import org.rapla.rest.gwtjsonrpc.common.ResultImpl; import org.rapla.rest.gwtjsonrpc.common.VoidResult; import org.rapla.rest.gwtjsonrpc.server.SignedToken; import org.rapla.rest.gwtjsonrpc.server.ValidToken; import org.rapla.rest.gwtjsonrpc.server.XsrfException; import org.rapla.rest.server.RaplaAPIPage; import org.rapla.rest.server.RaplaAuthRestPage; import org.rapla.rest.server.RaplaDynamicTypesRestPage; import org.rapla.rest.server.RaplaEventsRestPage; import org.rapla.rest.server.RaplaResourcesRestPage; import org.rapla.server.AuthenticationStore; import org.rapla.server.RaplaKeyStorage; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.server.RemoteMethodFactory; import org.rapla.server.RemoteSession; import org.rapla.server.ServerService; import org.rapla.server.ServerServiceContainer; import org.rapla.server.TimeZoneConverter; import org.rapla.servletpages.DefaultHTMLMenuEntry; import org.rapla.servletpages.RaplaAppletPageGenerator; import org.rapla.servletpages.RaplaIndexPageGenerator; import org.rapla.servletpages.RaplaJNLPPageGenerator; import org.rapla.servletpages.RaplaPageGenerator; import org.rapla.servletpages.RaplaStatusPageGenerator; import org.rapla.servletpages.RaplaStorePage; import org.rapla.storage.CachableStorageOperator; import org.rapla.storage.RaplaSecurityException; import org.rapla.storage.StorageOperator; import org.rapla.storage.StorageUpdateListener; import org.rapla.storage.UpdateResult; import org.rapla.storage.dbrm.LoginCredentials; import org.rapla.storage.dbrm.LoginTokens; import org.rapla.storage.dbrm.RemoteConnectionInfo; import org.rapla.storage.dbrm.RemoteMethodStub; import org.rapla.storage.dbrm.RemoteServer; import org.rapla.storage.dbrm.RemoteStorage; import org.rapla.storage.impl.server.LocalAbstractCachableOperator; /** Default implementation of StorageService. * <p>Sample configuration 1: <pre> &lt;storage id="storage" > &lt;store>file&lt;/store> &lt;/storage> </pre> * The store value contains the id of a storage-component. * Storage-Components are all components that implement the * <code>CachableStorageOperator<code> interface. * * </p> @see ServerService */ public class ServerServiceImpl extends ContainerImpl implements StorageUpdateListener, ServerServiceContainer, ServerService, ShutdownService, RemoteMethodFactory<RemoteServer>,RemoteMethodStub { @SuppressWarnings("rawtypes") public static Class<RemoteMethodFactory> REMOTE_METHOD_FACTORY = RemoteMethodFactory.class; static Class<RaplaPageGenerator> SERVLET_PAGE_EXTENSION = RaplaPageGenerator.class; protected CachableStorageOperator operator; protected I18nBundle i18n; List<PluginDescriptor<ServerServiceContainer>> pluginList; ClientFacade facade; private AuthenticationStore authenticationStore; SignedToken accessTokenSigner; SignedToken refreshTokenSigner; RemoteSessionImpl standaloneSession; ShutdownService shutdownService; // 5 Hours until the token expires int accessTokenValiditySeconds = 300 * 60; public ServerServiceImpl( RaplaContext parentContext, Configuration config, Logger logger) throws RaplaException { super( parentContext, config, logger ); addContainerProvidedComponent( TimeZoneConverter.class, TimeZoneConverterImpl.class); i18n = parentContext.lookup( RaplaComponent.RAPLA_RESOURCES ); Configuration login = config.getChild( "login" ); String username = login.getChild( "username" ).getValue( null ); String password = login.getChild( "password" ).getValue( "" ); RaplaContext context = getContext(); if ( config.getChildren("facade").length >0 ) { facade = m_context.lookup(ClientFacade.class); } else { // for old raplaserver.xconf facade = new FacadeImpl( context, config, getLogger().getChildLogger("serverfacade") ); } operator = (CachableStorageOperator) facade.getOperator(); addContainerProvidedComponentInstance( ServerService.class, this); addContainerProvidedComponentInstance( ShutdownService.class, this); addContainerProvidedComponentInstance( ServerServiceContainer.class, this); addContainerProvidedComponentInstance( CachableStorageOperator.class, operator ); addContainerProvidedComponentInstance( StorageOperator.class, operator ); addContainerProvidedComponentInstance( ClientFacade.class, facade ); addContainerProvidedComponent( SecurityManager.class, SecurityManager.class ); addRemoteMethodFactory(RemoteStorage.class,RemoteStorageImpl.class, null); addContainerProvidedComponentInstance( REMOTE_METHOD_FACTORY, this, RemoteServer.class.getName() ); // adds 5 basic pages to the webapplication addWebpage( "server",RaplaStatusPageGenerator.class); addWebpage( "json",RaplaAPIPage.class); addWebpage( "resources",RaplaResourcesRestPage.class); addWebpage( "events",RaplaEventsRestPage.class); addWebpage( "dynamictypes",RaplaDynamicTypesRestPage.class); addWebpage( "auth",RaplaAuthRestPage.class); addWebpage( "index",RaplaIndexPageGenerator.class ); addWebpage( "raplaclient.jnlp",RaplaJNLPPageGenerator.class ); addWebpage( "raplaclient",RaplaJNLPPageGenerator.class ); addWebpage( "raplaapplet",RaplaAppletPageGenerator.class ); addWebpage( "store",RaplaStorePage.class); addWebpage( "raplaclient.xconf",RaplaConfPageGenerator.class ); addWebpage( "raplaclient.xconf",RaplaConfPageGenerator.class); I18nBundle i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES); // Index page menu addContainerProvidedComponentInstance( RaplaServerExtensionPoints.HTML_MAIN_MENU_EXTENSION_POINT, new DefaultHTMLMenuEntry(context,i18n.getString( "start_rapla_with_webstart" ),"rapla/raplaclient.jnlp") ); addContainerProvidedComponentInstance( RaplaServerExtensionPoints.HTML_MAIN_MENU_EXTENSION_POINT, new DefaultHTMLMenuEntry(context,i18n.getString( "start_rapla_with_applet" ),"rapla?page=raplaapplet") ); addContainerProvidedComponentInstance( RaplaServerExtensionPoints.HTML_MAIN_MENU_EXTENSION_POINT, new DefaultHTMLMenuEntry(context,i18n.getString( "server_status" ),"rapla?page=server") ); standaloneSession = new RemoteSessionImpl(getContext(), "session"); operator.addStorageUpdateListener( this ); if ( username != null ) operator.connect( new ConnectInfo(username, password.toCharArray())); else operator.connect(); Set<String> pluginNames; //List<PluginDescriptor<ClientServiceContainer>> pluginList; try { pluginNames = context.lookup( RaplaMainContainer.PLUGIN_LIST); } catch (RaplaContextException ex) { throw new RaplaException (ex ); } pluginList = new ArrayList<PluginDescriptor<ServerServiceContainer>>( ); Logger pluginLogger = getLogger().getChildLogger("plugin"); for ( String plugin:pluginNames) { try { boolean found = false; try { Class<?> componentClass = ServerServiceImpl.class.getClassLoader().loadClass( plugin ); Method[] methods = componentClass.getMethods(); for ( Method method:methods) { if ( method.getName().equals("provideServices")) { Class<?> type = method.getParameterTypes()[0]; if (ServerServiceContainer.class.isAssignableFrom(type)) { found = true; } } } } catch (ClassNotFoundException e1) { } catch (Exception e1) { getLogger().warn(e1.getMessage()); continue; } if ( found ) { @SuppressWarnings("unchecked") PluginDescriptor<ServerServiceContainer> descriptor = (PluginDescriptor<ServerServiceContainer>) instanciate(plugin, null, logger); pluginList.add(descriptor); pluginLogger.info("Installed plugin "+plugin); } } catch (RaplaContextException e) { if (e.getCause() instanceof ClassNotFoundException) { pluginLogger.error("Could not instanciate plugin "+ plugin, e); } } } addContainerProvidedComponent(RaplaKeyStorage.class, RaplaKeyStorageImpl.class); try { RaplaKeyStorage keyStorage = getContext().lookup( RaplaKeyStorage.class); String secretKey = keyStorage.getRootKeyBase64(); accessTokenSigner = new SignedToken(accessTokenValiditySeconds , secretKey); refreshTokenSigner = new SignedToken(-1 , secretKey); } catch (Exception e) { throw new RaplaException( e.getMessage(), e); } Preferences preferences = operator.getPreferences( null, true ); //RaplaConfiguration encryptionConfig = preferences.getEntry(EncryptionService.CONFIG); //addRemoteMethodFactory( EncryptionService.class, EncryptionServiceFactory.class); RaplaConfiguration entry = preferences.getEntry(RaplaComponent.PLUGIN_CONFIG); String importExportTimeZone = TimeZone.getDefault().getID(); if ( entry != null) { Configuration find = entry.find("class", Export2iCalPlugin.PLUGIN_CLASS); if ( find != null) { String timeZone = find.getChild("TIMEZONE").getValue( null); if ( timeZone != null && !timeZone.equals("Etc/UTC")) { importExportTimeZone = timeZone; } } } String timezoneId = preferences.getEntryAsString(RaplaMainContainer.TIMEZONE, importExportTimeZone); RaplaLocale raplaLocale = context.lookup(RaplaLocale.class); TimeZoneConverter importExportLocale = context.lookup(TimeZoneConverter.class); try { TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry(); TimeZone timeZone = registry.getTimeZone(timezoneId); ((RaplaLocaleImpl) raplaLocale).setImportExportTimeZone( timeZone); ((TimeZoneConverterImpl) importExportLocale).setImportExportTimeZone( timeZone); if ( operator instanceof LocalAbstractCachableOperator) { ((LocalAbstractCachableOperator) operator).setTimeZone( timeZone); } } catch (Exception rc) { getLogger().error("Timezone " + timezoneId + " not found. " + rc.getMessage() + " Using system timezone " + importExportLocale.getImportExportTimeZone()); } initializePlugins( pluginList, preferences ); if ( context.has( AuthenticationStore.class ) ) { try { authenticationStore = context.lookup( AuthenticationStore.class ); getLogger().info( "Using AuthenticationStore " + authenticationStore.getName() ); } catch ( RaplaException ex) { getLogger().error( "Can't initialize configured authentication store. Using default authentication." , ex); } } // Provider<EntityStore> storeProvider = new Provider<EntityStore>() // { // public EntityStore get() { // return new EntityStore(operator, operator.getSuperCategory()); // } // // }; } @Override protected Map<String,ComponentInfo> getComponentInfos() { return new RaplaMetaConfigInfo(); } public <T> void addRemoteMethodFactory(Class<T> role, Class<? extends RemoteMethodFactory<T>> factory) { addRemoteMethodFactory(role, factory, null); } public <T> void addRemoteMethodFactory(Class<T> role, Class<? extends RemoteMethodFactory<T>> factory, Configuration configuration) { addContainerProvidedComponent(REMOTE_METHOD_FACTORY,factory, role.getName(), configuration); } protected RemoteMethodFactory<?> getRemoteMethod(String interfaceName) throws RaplaContextException { RemoteMethodFactory<?> factory = lookup( REMOTE_METHOD_FACTORY ,interfaceName); return factory; } public <T extends RaplaPageGenerator> void addWebpage(String pagename, Class<T> pageClass) { addWebpage(pagename, pageClass, null); } public <T extends RaplaPageGenerator> void addWebpage(String pagename, Class<T> pageClass, Configuration configuration) { String lowerCase = pagename.toLowerCase(); addContainerProvidedComponent(SERVLET_PAGE_EXTENSION,pageClass, lowerCase, configuration); } public RaplaPageGenerator getWebpage(String page) { try { String lowerCase = page.toLowerCase(); RaplaPageGenerator factory = lookup( SERVLET_PAGE_EXTENSION ,lowerCase); return factory; } catch (RaplaContextException ex) { Throwable cause = ex.getCause(); if ( cause != null) { getLogger().error(cause.getMessage(),cause); } return null; } } public void updateError( RaplaException ex ) { if ( getLogger() != null ) getLogger().error( ex.getMessage(), ex ); try { stop(); } catch ( Exception e ) { if ( getLogger() != null ) getLogger().error( e.getMessage() ); } } public void objectsUpdated(UpdateResult evt) { } /** * @see org.rapla.server.ServerService#getFacade() */ public ClientFacade getFacade() { return facade; } protected void initializePlugins( List<PluginDescriptor<ServerServiceContainer>> pluginList, Preferences preferences ) throws RaplaException { RaplaConfiguration raplaConfig = preferences.getEntry( RaplaComponent.PLUGIN_CONFIG); // Add plugin configs for ( Iterator<PluginDescriptor<ServerServiceContainer>> it = pluginList.iterator(); it.hasNext(); ) { PluginDescriptor<ServerServiceContainer> pluginDescriptor = it.next(); String pluginClassname = pluginDescriptor.getClass().getName(); Configuration pluginConfig = null; if ( raplaConfig != null ) { // TODO should be replaced with a more desciptve approach instead of looking for the config by guessing from the package name pluginConfig = raplaConfig.find( "class", pluginClassname ); // If no plugin config for server is found look for plugin config for client plugin if ( pluginConfig == null ) { pluginClassname = pluginClassname.replaceAll("ServerPlugin", "Plugin"); pluginClassname = pluginClassname.replaceAll(".server.", ".client."); pluginConfig = raplaConfig.find( "class", pluginClassname ); if ( pluginConfig == null) { pluginClassname = pluginClassname.replaceAll(".client.", "."); pluginConfig = raplaConfig.find( "class", pluginClassname ); } } } if ( pluginConfig == null ) { pluginConfig = new DefaultConfiguration( "plugin" ); } pluginDescriptor.provideServices( this, pluginConfig ); } lookupServicesFor(RaplaServerExtensionPoints.SERVER_EXTENSION ); } private void stop() { boolean wasConnected = operator.isConnected(); operator.removeStorageUpdateListener( this ); Logger logger = getLogger(); try { operator.disconnect(); } catch (RaplaException e) { logger.error( "Could not disconnect operator " , e); } finally { } if ( wasConnected ) { logger.info( "Storage service stopped" ); } } public void dispose() { stop(); super.dispose(); } public StorageOperator getOperator() { return operator; } public void storageDisconnected(String message) { try { stop(); } catch ( Exception e ) { if ( getLogger() != null ) getLogger().error( e.getMessage() ); } } // public byte[] dispatch(RemoteSession remoteSession, String methodName, Map<String,String> args ) throws Exception // { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // int indexRole = methodName.indexOf( "/" ); // String interfaceName = RemoteStorage.class.getName(); // if ( indexRole > 0 ) // { // interfaceName = methodName.substring( 0, indexRole ); // methodName = methodName.substring( indexRole + 1 ); // } // try // { // final Object serviceUncasted; // { // Logger debugLogger = getLogger().getChildLogger(interfaceName+"."+ methodName + ".arguments" ); // if ( debugLogger.isDebugEnabled()) // { // debugLogger.debug(args.toString()); // } // } // RemoteMethodFactory<?> factory = getRemoteMethod(interfaceName); // Class<?> interfaceClass = Class.forName( interfaceName); // // serviceUncasted = factory.createService( remoteSession); // Method method = findMethod( interfaceClass, methodName, args); // if ( method == null) // { // throw new RaplaException("Can't find method with name " + methodName); // } // Class<?>[] parameterTypes = method.getParameterTypes(); // Object[] convertedArgs = remoteMethodService.deserializeArguments(parameterTypes,args); // Object result = null; // try // { // result = method.invoke( serviceUncasted, convertedArgs); // } // catch (InvocationTargetException ex) // { // Throwable cause = ex.getCause(); // if (cause instanceof RaplaException) // { // throw (RaplaException)cause; // } // else // { // throw new RaplaException( cause.getMessage(), cause ); // } // } // User user = remoteSession.isAuthentified() ? remoteSession.getUser() : null; // // if ( result != null) // { // BufferedWriter outWriter = new BufferedWriter( new OutputStreamWriter( out,"utf-8")); // Appendable appendable = outWriter; // // we don't trasmit password settings in the general preference entry when the user is not an admin // remoteMethodService.serializeReturnValue(user, result, appendable); // outWriter.flush(); // } // else // { //// BufferedWriter outWriter = new BufferedWriter( new OutputStreamWriter( out,"utf-8")); //// outWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); //// outWriter.write("/n"); //// outWriter.write("<data/>"); //// outWriter.flush(); // } // out.flush(); // } // catch (EntityNotFoundException ex) // { // throw ex; // } // catch (DependencyException ex) // { // throw ex; // } // catch (RaplaNewVersionException ex) // { // throw ex; // } // catch (RaplaSecurityException ex) // { // getLogger().getChildLogger( interfaceName + "." + methodName).warn( ex.getMessage()); // throw ex; // } // catch ( Exception ex ) // { // getLogger().getChildLogger( interfaceName + "." + methodName).error( ex.getMessage(), ex ); // throw ex; // } // out.close(); // return out.toByteArray(); // } // private Method findMethod( Class inter,String methodName,Map<String,String> args) // { // Method[] methods = inter.getMethods(); // for ( Method method: methods) // { // if ( method.getName().equals( methodName) ) // { // Class<?>[] parameterTypes = method.getParameterTypes(); // Annotation[][] parameterAnnotations = method.getParameterAnnotations(); // int length = parameterTypes.length; // // Map // //for ( int i=0;) // if (parameterTypes.length == args.size()) // return method; // } // } // return null; // } public RemoteServer createService(final RemoteSession session) { return new RemoteServer() { public Logger getLogger() { if ( session != null) { return session.getLogger(); } else { return ServerServiceImpl.this.getLogger(); } } @Override public void setConnectInfo(RemoteConnectionInfo info) { } @Override public FutureResult<VoidResult> logout() { try { if ( session != null) { if ( session.isAuthentified()) { User user = session.getUser(); if ( user != null) { getLogger().getChildLogger("login").info( "Request Logout " + user.getUsername()); } ((RemoteSessionImpl)session).logout(); } } } catch (RaplaException ex) { return new ResultImpl<VoidResult>(ex); } return ResultImpl.VOID; } @Override public FutureResult<LoginTokens> login( String username, String password, String connectAs ) { LoginCredentials loginCredentials = new LoginCredentials(username,password,connectAs); return auth(loginCredentials); } @Override public FutureResult<LoginTokens> auth( LoginCredentials credentials ) { try { User user; String username = credentials.getUsername(); String password = credentials.getPassword(); String connectAs = credentials.getConnectAs(); boolean isStandalone = getContext().has( RemoteMethodStub.class); if ( isStandalone) { String toConnect = connectAs != null && !connectAs.isEmpty() ? connectAs : username; // don't check passwords in standalone version user = operator.getUser( toConnect); if ( user == null) { throw new RaplaSecurityException(i18n.getString("error.login")); } standaloneSession.setUser( user); } else { Logger logger = getLogger().getChildLogger("login"); user = authenticate(username, password, connectAs, logger); ((RemoteSessionImpl)session).setUser( user); } if ( connectAs != null && connectAs.length()> 0) { if (!operator.getUser( username).isAdmin()) { throw new SecurityException("Non admin user is requesting change user permission!"); } } FutureResult<LoginTokens> generateAccessToken = generateAccessToken(user); return generateAccessToken; } catch (RaplaException ex) { return new ResultImpl<LoginTokens>(ex); } } private FutureResult<LoginTokens> generateAccessToken(User user) throws RaplaException { try { String userId = user.getId(); Date now = operator.getCurrentTimestamp(); Date validUntil = new Date(now.getTime() + 1000 * accessTokenValiditySeconds); String signedToken = accessTokenSigner.newToken( userId, now); return new ResultImpl<LoginTokens>(new LoginTokens( signedToken, validUntil)); } catch (Exception e) { throw new RaplaException(e.getMessage()); } } @Override public FutureResult<String> getRefreshToken() { try { User user = getValidUser(session); RaplaKeyStorage keyStore = getContext().lookup(RaplaKeyStorage.class); Collection<String> apiKeys = keyStore.getAPIKeys(user); String refreshToken; if ( apiKeys.size() == 0) { refreshToken = null; } else { refreshToken = apiKeys.iterator().next(); } return new ResultImpl<String>(refreshToken); } catch (RaplaException ex) { return new ResultImpl<String>(ex); } } @Override public FutureResult<String> regenerateRefreshToken() { try { User user = getValidUser(session); RaplaKeyStorage keyStore = getContext().lookup(RaplaKeyStorage.class); Date now = operator.getCurrentTimestamp(); String generatedAPIKey = refreshTokenSigner.newToken(user.getId(), now); keyStore.storeAPIKey(user, "refreshToken",generatedAPIKey); return new ResultImpl<String>(generatedAPIKey); } catch (Exception ex) { return new ResultImpl<String>(ex); } } @Override public FutureResult<LoginTokens> refresh(String refreshToken) { try { User user = getUser(refreshToken, refreshTokenSigner); RaplaKeyStorage keyStore = getContext().lookup(RaplaKeyStorage.class); Collection<String> apiKeys = keyStore.getAPIKeys(user); if ( !apiKeys.contains( refreshToken)) { throw new RaplaSecurityException("refreshToken not valid"); } FutureResult<LoginTokens> generateAccessToken = generateAccessToken(user); return generateAccessToken; } catch (RaplaException ex) { return new ResultImpl<LoginTokens>(ex); } } public User getValidUser(final RemoteSession session) throws RaplaContextException, RaplaSecurityException { User user = session.getUser(); if ( user == null) { throw new RaplaSecurityException(i18n.getString("error.login")); } return user; } }; } public User authenticate(String username, String password,String connectAs, Logger logger) throws RaplaException,RaplaSecurityException { User user; String toConnect = connectAs != null && !connectAs.isEmpty() ? connectAs : username; logger.info( "User '" + username + "' is requesting login." ); if ( authenticationStore != null ) { logger.info("Checking external authentifiction for user " + username); boolean authenticateExternal; try { authenticateExternal = authenticationStore.authenticate( username, password ); } catch (RaplaException ex) { authenticateExternal= false; getLogger().error(ex.getMessage(), ex); } if (authenticateExternal) { logger.info("Successfull for " + username); //@SuppressWarnings("unchecked") user = operator.getUser( username ); if ( user == null ) { logger.info("User not found in localstore. Creating new Rapla user " + username); Date now = operator.getCurrentTimestamp(); UserImpl newUser = new UserImpl(now,now); newUser.setId( operator.createIdentifier( User.TYPE,1 )[0] ); user = newUser; } else { Set<Entity>singleton = Collections.singleton((Entity)user); Collection<Entity> editList = operator.editObjects( singleton, null ); user = (User)editList.iterator().next(); } boolean initUser ; try { Category groupCategory = operator.getSuperCategory().getCategory( Permission.GROUP_CATEGORY_KEY ); logger.info("Looking for update for rapla user '" + username + "' from external source."); initUser = authenticationStore.initUser( (User) user, username, password, groupCategory ); } catch (RaplaSecurityException ex){ throw new RaplaSecurityException(i18n.getString("error.login")); } if ( initUser ) { logger.info("Udating rapla user '" + username + "' from external source."); List<Entity>storeList = new ArrayList<Entity>(1); storeList.add( user); List<Entity>removeList = Collections.emptyList(); operator.storeAndRemove( storeList, removeList, null ); } else { logger.info("User '" + username + "' already up to date"); } } else { logger.info("Now trying to authenticate with local store '" + username + "'"); operator.authenticate( username, password ); } // do nothing } // if the authenticationStore can't authenticate the user is checked against the local database else { logger.info("Check password for " + username); operator.authenticate( username, password ); } if ( connectAs != null && connectAs.length() > 0) { logger.info("Successfull login for '" + username +"' acts as user '" + connectAs + "'"); } else { logger.info("Successfull login for '" + username + "'"); } user = operator.getUser(toConnect); if ( user == null) { throw new RaplaException("User with username '" + toConnect + "' not found"); } return user; } public void setShutdownService(ShutdownService shutdownService) { this.shutdownService = shutdownService; } public <T> T getWebserviceLocalStub(final Class<T> a) throws RaplaContextException { @SuppressWarnings("unchecked") RemoteMethodFactory<T> factory =lookup( REMOTE_METHOD_FACTORY ,a.getName()); T service = factory.createService( standaloneSession); return service; } public void shutdown(boolean restart) { if ( shutdownService != null) { shutdownService.shutdown(restart); } else { getLogger().error("Shutdown service not set"); } } public RemoteSession getRemoteSession(HttpServletRequest request) throws RaplaException { User user = getUser(request); RemoteSessionImpl remoteSession = new RemoteSessionImpl(getContext(), user != null ? user.getUsername() : "anonymous"); remoteSession.setUser( (User) user); // remoteSession.setAccessToken( token ); return remoteSession; } public User getUser(HttpServletRequest request) throws RaplaException { String token = request.getHeader("Authorization"); if ( token != null) { String bearerStr = "bearer"; int bearer = token.toLowerCase().indexOf(bearerStr); if ( bearer >= 0) { token = token.substring( bearer + bearerStr.length()).trim(); } } else { token = request.getParameter("access_token"); } User user = null; if ( token == null) { String username = request.getParameter("username"); if ( username != null) { user = getUserWithoutPassword(username); } } if ( user == null) { user = getUser( token, accessTokenSigner); } return user; } @SuppressWarnings("unchecked") @Override public <T> T createWebservice(Class<T> role, HttpServletRequest request) throws RaplaException { RemoteMethodFactory<T> remoteMethod = (RemoteMethodFactory<T>) getRemoteMethod( role.getName()); RemoteSession remoteSession = getRemoteSession(request); return remoteMethod.createService(remoteSession); } @Override public boolean hasWebservice(String interfaceName) { try { lookup( REMOTE_METHOD_FACTORY ,interfaceName); } catch (RaplaContextException e) { return false; } return true; } private User getUserWithoutPassword(String username) throws RaplaException { String connectAs = null; User user = authenticate(username, "", connectAs, getLogger()); return user; } private User getUser(String tokenString,SignedToken tokenSigner) throws RaplaException { if ( tokenString == null) { return null; } final int s = tokenString.indexOf('$'); if (s <= 0) { return null; } final String recvText = tokenString.substring(s + 1); try { Date now = operator.getCurrentTimestamp(); ValidToken checkToken = tokenSigner.checkToken(tokenString, recvText, now); if ( checkToken == null) { throw new RaplaSecurityException(RemoteStorage.USER_WAS_NOT_AUTHENTIFIED + " InvalidToken " + tokenString); } } catch (XsrfException e) { throw new RaplaSecurityException(e.getMessage(), e); } String userId = recvText; User user = operator.resolve( userId, User.class); return user; } }
04900db4-rob
src/org/rapla/server/internal/ServerServiceImpl.java
Java
gpl3
37,609
package org.rapla.server.internal; import org.rapla.entities.User; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.logger.Logger; import org.rapla.server.RemoteSession; /** Implementation of RemoteStorage as a RemoteService * @see org.rapla.storage.dbrm.RemoteStorage */ public class RemoteSessionImpl extends RaplaComponent implements RemoteSession { /** * */ User user; Logger logger; // private String accessToken; public RemoteSessionImpl(RaplaContext context, String clientName) { super( context ); logger = super.getLogger().getChildLogger(clientName); } public Logger getLogger() { return logger; } @Override public User getUser() throws RaplaContextException { if (user == null) throw new RaplaContextException("No user found in session."); return user; } @Override public boolean isAuthentified() { return user != null; } public void setUser( User user) { this.user = user; } // public void setAccessToken( String token) // { // this.accessToken = token; // } // // @Override // public String getAccessToken() { // return accessToken; // } public void logout() { this.setUser( null); } }
04900db4-rob
src/org/rapla/server/internal/RemoteSessionImpl.java
Java
gpl3
1,409
/*--------------------------------------------------------------------------* | 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.server.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.Ownable; 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.AppointmentFormater; import org.rapla.entities.domain.Permission; import org.rapla.entities.domain.Reservation; import org.rapla.facade.ClientFacade; import org.rapla.facade.Conflict; import org.rapla.facade.RaplaComponent; import org.rapla.facade.internal.FacadeImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; import org.rapla.storage.CachableStorageOperator; import org.rapla.storage.PreferencePatch; import org.rapla.storage.RaplaSecurityException; /** checks if the client can store or delete an entity */ public class SecurityManager { I18nBundle i18n; AppointmentFormater appointmentFormater; CachableStorageOperator operator; RaplaContext context; Logger logger; public SecurityManager(RaplaContext context) throws RaplaException { logger = context.lookup( Logger.class); operator = context.lookup( CachableStorageOperator.class); i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES); appointmentFormater = context.lookup(AppointmentFormater.class); this.context = context; } void checkWritePermissions(User user,Entity entity) throws RaplaSecurityException { if (user.isAdmin()) return; Object id = entity.getId(); if (id == null) throw new RaplaSecurityException("No id set"); boolean permitted = false; @SuppressWarnings("unchecked") Class<Entity> typeClass = entity.getRaplaType().getTypeClass(); Entity original = operator.tryResolve( entity.getId(), typeClass); // flag indicates if a user only exchanges allocatables (needs to have admin-access on the allocatable) boolean canExchange = false; boolean ownable = entity instanceof Ownable; if (ownable || entity instanceof Appointment) { User entityOwner; if ( ownable) { entityOwner = ((Ownable) entity).getOwner(); } else { entityOwner = ((Appointment) entity).getOwner(); } if (original == null) { permitted = entityOwner != null && user.isIdentical(entityOwner); if (getLogger().isDebugEnabled()) getLogger().debug("Permissions for new object " + entity + "\nUser check: " + user + " = " + entityOwner); } else { User originalOwner; if ( ownable) { originalOwner = ((Ownable) original).getOwner(); } else { originalOwner = ((Appointment) original).getOwner(); } if (getLogger().isDebugEnabled()) getLogger().debug("Permissions for existing object " + entity + "\nUser check: " + user + " = " + entityOwner + " = " + originalOwner); permitted = (originalOwner != null) && originalOwner.isIdentical(user) && originalOwner.isIdentical(entityOwner); if ( !permitted ) { canExchange = canExchange( user, entity, original ); permitted = canExchange; } } } if ( !permitted && entity instanceof Allocatable ){ if ( original == null ) { permitted = isRegisterer(user); } else { permitted = ((Allocatable)original).canModify( user ); } } if ( !permitted && original != null) { permitted = RaplaComponent.checkClassifiableModifyPermissions(original, user); } if (!permitted && entity instanceof Appointment) { final Reservation reservation = ((Appointment)entity).getReservation(); Reservation originalReservation = operator.tryResolve(reservation.getId(), Reservation.class); if ( originalReservation != null) { permitted = RaplaComponent.checkClassifiableModifyPermissions(originalReservation, user); } } if (!permitted) throw new RaplaSecurityException(i18n.format("error.modify_not_allowed", new Object []{ user.toString(),entity.toString()})); // Check if the user can change the reservation if ( Reservation.TYPE ==entity.getRaplaType() ) { Reservation reservation = (Reservation) entity ; Reservation originalReservation = (Reservation)original; Allocatable[] all = reservation.getAllocatables(); if ( originalReservation != null && canExchange ) { List<Allocatable> newAllocatabes = new ArrayList<Allocatable>( Arrays.asList(reservation.getAllocatables() ) ); newAllocatabes.removeAll( Arrays.asList( originalReservation.getAllocatables())); all = newAllocatabes.toArray( Allocatable.ALLOCATABLE_ARRAY); } if ( originalReservation == null) { Category group = getUserGroupsCategory().getCategory( Permission.GROUP_CAN_CREATE_EVENTS); if (group != null && !user.belongsTo(group)) { throw new RaplaSecurityException(i18n.format("error.create_not_allowed", new Object []{ user.toString(),entity.toString()})); } } checkPermissions( user, reservation, originalReservation , all); } } private Logger getLogger() { return logger; } protected boolean isRegisterer(User user) throws RaplaSecurityException { try { Category registererGroup = getUserGroupsCategory().getCategory(Permission.GROUP_REGISTERER_KEY); return user.belongsTo(registererGroup); } catch (RaplaException ex) { throw new RaplaSecurityException(ex ); } } public Category getUserGroupsCategory() throws RaplaSecurityException { Category userGroups = operator.getSuperCategory().getCategory(Permission.GROUP_CATEGORY_KEY); if ( userGroups == null) { throw new RaplaSecurityException("No category '" + Permission.GROUP_CATEGORY_KEY + "' available"); } return userGroups; } /** checks if the user just exchanges one allocatable or removes one. The user needs admin-access on the * removed allocatable and the newly inserted allocatable */ private boolean canExchange(User user,Entity entity,Entity original) { if ( Appointment.TYPE.equals( entity.getRaplaType() )) { return ((Appointment) entity).matches( (Appointment) original ); } if ( Reservation.TYPE.equals( entity.getRaplaType() )) { Reservation newReservation = (Reservation) entity; Reservation oldReservation = (Reservation) original; // We only need to check the length because we compare the appointments above. if ( newReservation.getAppointments().length != oldReservation.getAppointments().length ) { return false; } List<Allocatable> oldAllocatables = Arrays.asList(oldReservation.getAllocatables()); List<Allocatable> newAllocatables = Arrays.asList(newReservation.getAllocatables()); List<Allocatable> inserted = new ArrayList<Allocatable>(newAllocatables); List<Allocatable> removed = new ArrayList<Allocatable>(oldAllocatables); List<Allocatable> overlap = new ArrayList<Allocatable>(oldAllocatables); inserted.removeAll( oldAllocatables ); removed.removeAll( newAllocatables ); overlap.retainAll( inserted ); if ( inserted.size() == 0 && removed.size() == 0) { return false; } // he must have admin rights on all inserted resources Iterator<Allocatable> it = inserted.iterator(); while (it.hasNext()) { if (!canAllocateForOthers(it.next(),user)) { return false; } } // and he must have admin rights on all the removed resources it = removed.iterator(); while (it.hasNext()) { if (!canAllocateForOthers(it.next(),user)) { return false; } } // He can't change appointments, only exchange allocatables he has admin-priviliges for it = overlap.iterator(); while (it.hasNext()) { Allocatable all = it.next(); Appointment[] r1 = newReservation.getRestriction( all ); Appointment[] r2 = oldReservation.getRestriction( all ); boolean changed = false; if ( r1.length != r2.length ) { changed = true; } else { for ( int i=0; i< r1.length; i++ ) { if ( !r1[i].matches(r2[i]) ) { changed = true; } } } if ( changed && !canAllocateForOthers( all, user )) { return false; } } return true; } return false; } /** for Thierry, we can make this configurable in the next version */ private boolean canAllocateForOthers(Allocatable allocatable, User user) { // only admins, current behaviour return allocatable.canModify( user); // everyone who can allocate the resource anytime //return allocatable.canAllocate( user, null, null, operator.today()); // everyone //return true; } private void checkConflictsAllowed(User user, Allocatable allocatable, Conflict[] conflictsBefore, Conflict[] conflictsAfter) throws RaplaSecurityException { int nConflictsBefore = 0; int nConflictsAfter = 0; if ( allocatable.canCreateConflicts( user ) ) { return; } if ( conflictsBefore != null ) { for ( int i = 0; i < conflictsBefore.length; i++ ) { if ( conflictsBefore[i].getAllocatable().equals ( allocatable ) ) { nConflictsBefore ++; } } } for ( int i = 0; i < conflictsAfter.length; i++ ) { if ( conflictsAfter[i].getAllocatable().equals ( allocatable ) ) { nConflictsAfter ++; } } if ( nConflictsAfter > nConflictsBefore ) { String all = allocatable.getName( i18n.getLocale() ); throw new RaplaSecurityException( i18n.format("warning.no_conflict_permission", all ) ); } } private void checkPermissions( User user, Reservation r, Reservation original, Allocatable[] allocatables ) throws RaplaSecurityException { ClientFacade facade; try { facade = context.lookup(ClientFacade.class); } catch (RaplaContextException e) { throw new RaplaSecurityException(e.getMessage(), e); } Conflict[] conflictsBefore = null; Conflict[] conflictsAfter = null; try { conflictsAfter = facade.getConflicts( r ); if ( original != null ) { conflictsBefore = facade.getConflicts( original ); } } catch ( RaplaException ex ) { throw new RaplaSecurityException(" Can't check permissions due to:" + ex.getMessage(), ex ); } Appointment[] appointments = r.getAppointments(); // ceck if the user has the permisson to add allocations in the given time for (int i = 0; i < allocatables.length; i++ ) { Allocatable allocatable = allocatables[i]; checkConflictsAllowed( user, allocatable, conflictsBefore, conflictsAfter ); for (int j = 0; j < appointments.length; j++ ) { Appointment appointment = appointments[j]; Date today = operator.today(); if ( r.hasAllocated( allocatable, appointment ) && !FacadeImpl.hasPermissionToAllocate( user, appointment, allocatable, original,today ) ) { String all = allocatable.getName( i18n.getLocale() ); String app = appointmentFormater.getSummary( appointment ); String error = i18n.format("warning.no_reserve_permission" ,all ,app); throw new RaplaSecurityException( error ); } } } if (original == null ) return; Date today = operator.today(); // 1. calculate the deleted assignments from allocatable to appointments // 2. check if they were allowed to change in the specified time appointments = original.getAppointments(); allocatables = original.getAllocatables(); for (int i = 0; i < allocatables.length; i++ ) { Allocatable allocatable = allocatables[i]; for (int j = 0; j < appointments.length; j++ ) { Appointment appointment = appointments[j]; if ( original.hasAllocated( allocatable, appointment ) && !r.hasAllocated( allocatable, appointment ) ) { Date start = appointment.getStart(); Date end = appointment.getMaxEnd(); if ( !allocatable.canAllocate( user, start, end, today ) ) { String all = allocatable.getName( i18n.getLocale() ); String app = appointmentFormater.getSummary( appointment ); String error = i18n.format("warning.no_reserve_permission" ,all ,app); throw new RaplaSecurityException( error ); } } } } } public void checkRead(User user,Entity entity) throws RaplaSecurityException, RaplaException { RaplaType<?> raplaType = entity.getRaplaType(); if ( raplaType == Allocatable.TYPE) { Allocatable allocatable = (Allocatable) entity; if ( !allocatable.canReadOnlyInformation( user)) { throw new RaplaSecurityException(i18n.format("error.read_not_allowed",user, allocatable.getName( null))); } } if ( raplaType == Preferences.TYPE) { Ownable ownable = (Preferences) entity; User owner = ownable.getOwner(); if ( user != null && !user.isAdmin() && (owner == null || !user.equals( owner))) { throw new RaplaSecurityException(i18n.format("error.read_not_allowed", user, entity)); } } } public void checkWritePermissions(User user, PreferencePatch patch) throws RaplaSecurityException { String ownerId = patch.getUserId(); if ( user != null && !user.isAdmin() && (ownerId == null || !user.getId().equals( ownerId))) { throw new RaplaSecurityException("User " + user + " can't modify preferences " + ownerId); } } }
04900db4-rob
src/org/rapla/server/internal/SecurityManager.java
Java
gpl3
16,875
/*--------------------------------------------------------------------------* | 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.server.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TimeZone; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import org.rapla.RaplaMainContainer; import org.rapla.components.util.DateTools; import org.rapla.components.util.ParseDateException; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.components.util.TimeInterval; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.Category; import org.rapla.entities.DependencyException; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; 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.RaplaConfiguration; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Permission; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.domain.internal.ReservationImpl; 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.storage.EntityReferencer; import org.rapla.facade.ClientFacade; import org.rapla.facade.Conflict; import org.rapla.facade.RaplaComponent; import org.rapla.facade.internal.ConflictImpl; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.framework.TypedComponentRole; import org.rapla.framework.logger.Logger; import org.rapla.plugin.mail.MailPlugin; import org.rapla.plugin.mail.server.MailInterface; import org.rapla.rest.gwtjsonrpc.common.FutureResult; import org.rapla.rest.gwtjsonrpc.common.ResultImpl; import org.rapla.rest.gwtjsonrpc.common.VoidResult; import org.rapla.server.AuthenticationStore; import org.rapla.server.RemoteMethodFactory; import org.rapla.server.RemoteSession; import org.rapla.storage.CachableStorageOperator; import org.rapla.storage.PreferencePatch; import org.rapla.storage.RaplaNewVersionException; import org.rapla.storage.RaplaSecurityException; import org.rapla.storage.StorageOperator; import org.rapla.storage.StorageUpdateListener; import org.rapla.storage.UpdateEvent; import org.rapla.storage.UpdateResult; import org.rapla.storage.UpdateResult.Change; import org.rapla.storage.UpdateResult.Remove; import org.rapla.storage.dbrm.RemoteConnectionInfo; import org.rapla.storage.dbrm.RemoteStorage; import org.rapla.storage.impl.EntityStore; /** Provides an adapter for each client-session to their shared storage operator * Handles security and synchronizing aspects. */ public class RemoteStorageImpl implements RemoteMethodFactory<RemoteStorage>, StorageUpdateListener, Disposable { CachableStorageOperator operator; protected SecurityManager security; RaplaContext context; int cleanupPointVersion = 0; protected AuthenticationStore authenticationStore; Logger logger; ClientFacade facade; RaplaLocale raplaLocale; //private Map<String,Long> updateMap = new HashMap<String,Long>(); //private Map<String,Long> removeMap = new HashMap<String,Long>(); public RemoteStorageImpl(RaplaContext context) throws RaplaException { this.context = context; this.logger = context.lookup( Logger.class); facade = context.lookup( ClientFacade.class); raplaLocale = context.lookup( RaplaLocale.class); operator = (CachableStorageOperator)facade.getOperator(); operator.addStorageUpdateListener( this); security = context.lookup( SecurityManager.class); if ( context.has( AuthenticationStore.class ) ) { try { authenticationStore = context.lookup( AuthenticationStore.class ); getLogger().info( "Using AuthenticationStore " + authenticationStore.getName() ); } catch ( RaplaException ex) { getLogger().error( "Can't initialize configured authentication store. Using default authentication." , ex); } } Long repositoryVersion = operator.getCurrentTimestamp().getTime(); // Invalidate all clients for ( User user:operator.getUsers()) { String userId = user.getId(); needResourceRefresh.put( userId, repositoryVersion); needConflictRefresh.put( userId, repositoryVersion); } synchronized (invalidateMap) { invalidateMap.put( repositoryVersion, new TimeInterval( null, null)); } } public Logger getLogger() { return logger; } public I18nBundle getI18n() throws RaplaException { return context.lookup(RaplaComponent.RAPLA_RESOURCES); } static UpdateEvent createTransactionSafeUpdateEvent( UpdateResult updateResult ) { User user = updateResult.getUser(); UpdateEvent saveEvent = new UpdateEvent(); if ( user != null ) { saveEvent.setUserId( user.getId() ); } { Iterator<UpdateResult.Add> it = updateResult.getOperations( UpdateResult.Add.class ); while ( it.hasNext() ) { Entity newEntity = (Entity) ( it.next() ).getNew(); saveEvent.putStore( newEntity ); } } { Iterator<UpdateResult.Change> it = updateResult.getOperations( UpdateResult.Change.class ); while ( it.hasNext() ) { Entity newEntity = (Entity) ( it.next() ).getNew(); saveEvent.putStore( newEntity ); } } { Iterator<UpdateResult.Remove> it = updateResult.getOperations( UpdateResult.Remove.class ); while ( it.hasNext() ) { Entity removeEntity = (Entity) (it.next() ).getCurrent(); saveEvent.putRemove( removeEntity ); } } return saveEvent; } private Map<String,Long> needConflictRefresh = new ConcurrentHashMap<String,Long>(); private Map<String,Long> needResourceRefresh = new ConcurrentHashMap<String,Long>(); private SortedMap<Long, TimeInterval> invalidateMap = Collections.synchronizedSortedMap(new TreeMap<Long,TimeInterval>()); // Implementation of StorageUpdateListener public void objectsUpdated( UpdateResult evt ) { long repositoryVersion = operator.getCurrentTimestamp().getTime(); // notify the client for changes TimeInterval invalidateInterval = evt.calulateInvalidateInterval(); if ( invalidateInterval != null) { long oneHourAgo = repositoryVersion - DateTools.MILLISECONDS_PER_HOUR; // clear the entries that are older than one hour and replace them with a clear_all // that is set one hour in the past, to refresh all clients that have not been connected in the past hour on the next connect synchronized ( invalidateMap) { SortedMap<Long, TimeInterval> headMap = invalidateMap.headMap( oneHourAgo); if ( !headMap.isEmpty()) { Set<Long> toDelete = new TreeSet<Long>(headMap.keySet()); for ( Long key:toDelete) { invalidateMap.remove(key); } invalidateMap.put(oneHourAgo, new TimeInterval( null, null)); } invalidateMap.put(repositoryVersion, invalidateInterval); } } UpdateEvent safeResultEvent = createTransactionSafeUpdateEvent( evt ); if ( getLogger().isDebugEnabled() ) getLogger().debug( "Storage was modified. Calling notify." ); boolean addAllUsersToConflictRefresh = false; for ( Iterator<Entity>it = safeResultEvent.getStoreObjects().iterator(); it.hasNext(); ) { Entity obj = it.next(); if (!isTransferedToClient(obj)) { continue; } if ( obj instanceof Conflict) { addAllUsersToConflictRefresh = true; } if ( obj instanceof DynamicType) { addAllUsersToConflictRefresh = true; } // RaplaType<?> raplaType = obj.getRaplaType(); // if (raplaType == Conflict.TYPE) // { // String id = obj.getId(); // updateMap.remove( id ); // removeMap.remove( id ); // updateMap.put( id, new Long( repositoryVersion ) ); // } } // now we check if a the resources have changed in a way that a user needs to refresh all resources. That is the case, when // someone changes the permissions on one or more resource and that affects the visibility of that resource to a user, // so its either pushed to the client or removed from it. Set<Permission> invalidatePermissions = new HashSet<Permission>(); boolean addAllUsersToResourceRefresh = false; { Iterator<Remove> operations = evt.getOperations(UpdateResult.Remove.class); while ( operations.hasNext()) { Remove operation = operations.next(); Entity obj = operation.getCurrent(); if ( obj instanceof User) { String userId = obj.getId(); needConflictRefresh.remove( userId); needResourceRefresh.remove( userId); } if (!isTransferedToClient(obj)) { continue; } if ( obj instanceof Allocatable) { Permission[] oldPermissions = ((Allocatable)obj).getPermissions(); invalidatePermissions.addAll( Arrays.asList( oldPermissions)); } if ( obj instanceof DynamicType) { addAllUsersToResourceRefresh = true; addAllUsersToConflictRefresh = true; } if ( obj instanceof Conflict) { addAllUsersToConflictRefresh = true; } // if ( obj instanceof Conflict) // { // String id = obj.getId(); // updateMap.remove( id ); // removeMap.remove( id ); // removeMap.put( id, new Long( repositoryVersion ) ); // } } } if (addAllUsersToResourceRefresh || addAllUsersToConflictRefresh) { invalidateAll(repositoryVersion, addAllUsersToResourceRefresh,addAllUsersToConflictRefresh); } else { invalidate(evt, repositoryVersion, invalidatePermissions); } } private void invalidateAll(long repositoryVersion, boolean resourceRefreh, boolean conflictRefresh) { Collection<String> allUserIds = new ArrayList<String>(); try { Collection<User> allUsers = operator.getUsers(); for ( User user:allUsers) { String id = user.getId(); allUserIds.add( id); } } catch (RaplaException ex) { getLogger().error( ex.getMessage(), ex); // we stay with the old list. // keySet iterator from concurrent hashmap is thread safe Iterator<String> iterator = needResourceRefresh.keySet().iterator(); while ( iterator.hasNext()) { String id = iterator.next(); allUserIds.add( id); } } for ( String userId :allUserIds) { if (resourceRefreh ) { needResourceRefresh.put( userId, repositoryVersion); } if ( conflictRefresh) { needConflictRefresh.put( userId, repositoryVersion); } } } private void invalidate(UpdateResult evt, long repositoryVersion, Set<Permission> invalidatePermissions) { Collection<User> allUsers; try { allUsers = operator.getUsers(); } catch (RaplaException e) { // we need to invalidate all on an exception invalidateAll(repositoryVersion, true, true); return; } // We also check if a permission on a reservation has changed, so that it is no longer or new in the conflict list of a certain user. // If that is the case we trigger an invalidate of the conflicts for a user Set<User> usersResourceRefresh = new HashSet<User>(); Category superCategory = operator.getSuperCategory(); Set<Category> groupsConflictRefresh = new HashSet<Category>(); Set<User> usersConflictRefresh = new HashSet<User>(); Iterator<Change> operations = evt.getOperations(UpdateResult.Change.class); while ( operations.hasNext()) { Change operation = operations.next(); Entity newObject = operation.getNew(); if ( newObject.getRaplaType().is( Allocatable.TYPE) && isTransferedToClient(newObject)) { Allocatable newAlloc = (Allocatable) newObject; Allocatable current = (Allocatable) operation.getOld(); Permission[] oldPermissions = current.getPermissions(); Permission[] newPermissions = newAlloc.getPermissions(); // we leave this condition for a faster equals check if (oldPermissions.length == newPermissions.length) { for (int i=0;i<oldPermissions.length;i++) { Permission oldPermission = oldPermissions[i]; Permission newPermission = newPermissions[i]; if (!oldPermission.equals(newPermission)) { invalidatePermissions.add( oldPermission); invalidatePermissions.add( newPermission); } } } else { HashSet<Permission> newSet = new HashSet<Permission>(Arrays.asList(newPermissions)); HashSet<Permission> oldSet = new HashSet<Permission>(Arrays.asList(oldPermissions)); { HashSet<Permission> changed = new HashSet<Permission>( newSet); changed.removeAll( oldSet); invalidatePermissions.addAll(changed); } { HashSet<Permission> changed = new HashSet<Permission>(oldSet); changed.removeAll( newSet); invalidatePermissions.addAll(changed); } } } if ( newObject.getRaplaType().is( User.TYPE)) { User newUser = (User) newObject; User oldUser = (User) operation.getOld(); HashSet<Category> newGroups = new HashSet<Category>(Arrays.asList(newUser.getGroups())); HashSet<Category> oldGroups = new HashSet<Category>(Arrays.asList(oldUser.getGroups())); if ( !newGroups.equals( oldGroups) || newUser.isAdmin() != oldUser.isAdmin()) { usersResourceRefresh.add( newUser); } } if ( newObject.getRaplaType().is( Reservation.TYPE)) { Reservation newEvent = (Reservation) newObject; Reservation oldEvent = (Reservation) operation.getOld(); User newOwner = newEvent.getOwner(); User oldOwner = oldEvent.getOwner(); if ( newOwner != null && oldOwner != null && (newOwner.equals( oldOwner)) ) { usersConflictRefresh.add( newOwner); usersConflictRefresh.add( oldOwner); } Collection<Category> newGroup = RaplaComponent.getPermissionGroups( newEvent, superCategory, ReservationImpl.PERMISSION_MODIFY, false); Collection<Category> oldGroup = RaplaComponent.getPermissionGroups( oldEvent, superCategory, ReservationImpl.PERMISSION_MODIFY, false); if (newGroup != null && (oldGroup == null || !oldGroup.equals(newGroup))) { groupsConflictRefresh.addAll( newGroup); } if (oldGroup != null && (newGroup == null || !oldGroup.equals(newGroup))) { groupsConflictRefresh.addAll( oldGroup); } } } boolean addAllUsersToConflictRefresh = groupsConflictRefresh.contains( superCategory); Set<Category> groupsResourceRefrsesh = new HashSet<Category>(); if ( !invalidatePermissions.isEmpty() || ! addAllUsersToConflictRefresh || !! groupsConflictRefresh.isEmpty()) { for ( Permission permission:invalidatePermissions) { User user = permission.getUser(); if ( user != null) { usersResourceRefresh.add( user); } Category group = permission.getGroup(); if ( group != null) { groupsResourceRefrsesh.add( group); } if ( user == null && group == null) { usersResourceRefresh.addAll( allUsers); break; } } for ( User user:allUsers) { if ( usersResourceRefresh.contains( user)) { continue; } for (Category group:user.getGroups()) { if ( groupsResourceRefrsesh.contains( group)) { usersResourceRefresh.add( user); break; } if ( addAllUsersToConflictRefresh || groupsConflictRefresh.contains( group)) { usersConflictRefresh.add( user); break; } } } } for ( User user:usersResourceRefresh) { String userId = user.getId(); needResourceRefresh.put( userId, repositoryVersion); needConflictRefresh.put( userId, repositoryVersion); } for ( User user:usersConflictRefresh) { String userId = user.getId(); needConflictRefresh.put( userId, repositoryVersion); } } private boolean isTransferedToClient(RaplaObject obj) { RaplaType<?> raplaType = obj.getRaplaType(); if (raplaType == Appointment.TYPE || raplaType == Reservation.TYPE) { return false; } if ( obj instanceof DynamicType) { if (!DynamicTypeImpl.isTransferedToClient(( DynamicType) obj)) { return false; } } if ( obj instanceof Classifiable) { if (!DynamicTypeImpl.isTransferedToClient(( Classifiable) obj)) { return false; } } return true; } @Override public void dispose() { } public void updateError(RaplaException ex) { } public void storageDisconnected(String disconnectionMessage) { } public Class<RemoteStorage> getServiceClass() { return RemoteStorage.class; } @Override public RemoteStorage createService(final RemoteSession session) { return new RemoteStorage() { @Override public void setConnectInfo(RemoteConnectionInfo info) { // do nothing here } public FutureResult<UpdateEvent> getResources() { try { checkAuthentified(); User user = getSessionUser(); getLogger().debug ("A RemoteServer wants to get all resource-objects."); Date serverTime = operator.getCurrentTimestamp(); Collection<Entity> visibleEntities = operator.getVisibleEntities(user); UpdateEvent evt = new UpdateEvent(); evt.setUserId( user.getId()); for ( Entity entity: visibleEntities) { if ( isTransferedToClient(entity)) { if ( entity instanceof Preferences) { Preferences preferences = (Preferences)entity; User owner = preferences.getOwner(); if ( owner == null && !user.isAdmin()) { entity = removeServerOnlyPreferences(preferences); } } evt.putStore(entity); } } evt.setLastValidated(serverTime); return new ResultImpl<UpdateEvent>( evt); } catch (RaplaException ex ) { return new ResultImpl<UpdateEvent>(ex ); } } private Preferences removeServerOnlyPreferences(Preferences preferences) { Preferences clone = preferences.clone(); { //removeOldPluginConfigs(preferences, clone); for (String role :((PreferencesImpl)preferences).getPreferenceEntries()) { if ( role.contains(".server.")) { clone.removeEntry(role); } } } return clone; } // private void removeOldPluginConfigs(Preferences preferences, Preferences clone) { // List<String> adminOnlyPreferences = new ArrayList<String>(); // adminOnlyPreferences.add(MailPlugin.class.getCanonicalName()); // adminOnlyPreferences.add(JNDIPlugin.class.getCanonicalName()); // // RaplaConfiguration entry = preferences.getEntry(RaplaComponent.PLUGIN_CONFIG); // if ( entry != null) // { // RaplaConfiguration newConfig = entry.clone(); // for ( String className: adminOnlyPreferences) // { // DefaultConfiguration pluginConfig = (DefaultConfiguration)newConfig.find("class", className); // if ( pluginConfig != null) // { // newConfig.removeChild( pluginConfig); // boolean enabled = pluginConfig.getAttributeAsBoolean("enabled", false); // RaplaConfiguration newPluginConfig = new RaplaConfiguration(pluginConfig.getName()); // newPluginConfig.setAttribute("enabled", enabled); // newPluginConfig.setAttribute("class", className); // newConfig.addChild( newPluginConfig); // } // } // clone.putEntry(RaplaComponent.PLUGIN_CONFIG, newConfig); // } // } public FutureResult<List<String>> getTemplateNames() { try { checkAuthentified(); Collection<String> templateNames = operator.getTemplateNames(); return new ResultImpl<List<String>>(new ArrayList<String>(templateNames)); } catch (RaplaException ex ) { return new ResultImpl<List<String>>(ex); } } public FutureResult<UpdateEvent> getEntityRecursive(String... ids) { //synchronized (operator.getLock()) try { checkAuthentified(); Date repositoryVersion = operator.getCurrentTimestamp(); User sessionUser = getSessionUser(); ArrayList<Entity>completeList = new ArrayList<Entity>(); for ( String id:ids) { Entity entity = operator.resolve(id); if ( entity instanceof Classifiable) { if (!DynamicTypeImpl.isTransferedToClient(( Classifiable) entity)) { throw new RaplaSecurityException("Entity for id " + id + " is not transferable to the client"); } } if ( entity instanceof DynamicType) { if (!DynamicTypeImpl.isTransferedToClient(( DynamicType) entity)) { throw new RaplaSecurityException("Entity for id " + id + " is not transferable to the client"); } } if ( entity instanceof Reservation) { entity = checkAndMakeReservationsAnonymous(sessionUser, entity); } if ( entity instanceof Preferences) { entity = removeServerOnlyPreferences((Preferences)entity); } security.checkRead(sessionUser, entity); completeList.add( entity ); getLogger().debug("Get entity " + entity); } UpdateEvent evt = new UpdateEvent(); evt.setLastValidated(repositoryVersion); for ( Entity entity: completeList) { evt.putStore(entity); } return new ResultImpl<UpdateEvent>( evt); } catch (RaplaException ex ) { return new ResultImpl<UpdateEvent>(ex ); } } public FutureResult<List<ReservationImpl>> getReservations(String[] allocatableIds,Date start,Date end,Map<String,String> annotationQuery) { getLogger().debug ("A RemoteServer wants to reservations from ." + start + " to " + end); try { checkAuthentified(); User sessionUser = getSessionUser(); User user = null; // Reservations and appointments ArrayList<ReservationImpl> list = new ArrayList<ReservationImpl>(); List<Allocatable> allocatables = new ArrayList<Allocatable>(); if ( allocatableIds != null ) { for ( String id:allocatableIds) { Allocatable allocatable = operator.resolve(id, Allocatable.class); security.checkRead(sessionUser, allocatable); allocatables.add( allocatable); } } ClassificationFilter[] classificationFilters = null; Collection<Reservation> reservations = operator.getReservations(user,allocatables, start, end, classificationFilters,annotationQuery ); for (Reservation res:reservations) { if (isAllocatablesVisible(sessionUser, res)) { ReservationImpl safeRes = checkAndMakeReservationsAnonymous(sessionUser, res); list.add( safeRes); } } // for (Reservation r:reservations) // { // Iterable<Entity>subEntities = ((ParentEntity)r).getSubEntities(); // for (Entity appointments:subEntities) // { // completeList.add( appointments); // } getLogger().debug("Get reservations " + start + " " + end + ": " + reservations.size() + "," + list.size()); return new ResultImpl<List<ReservationImpl>>(list); } catch (RaplaException ex ) { return new ResultImpl<List<ReservationImpl>>(ex ); } } private ReservationImpl checkAndMakeReservationsAnonymous(User sessionUser,Entity entity) { ReservationImpl reservation =(ReservationImpl) entity; boolean canReadFromOthers = facade.canReadReservationsFromOthers(sessionUser); boolean reservationVisible = RaplaComponent.canRead( reservation, sessionUser, canReadFromOthers); // check if the user is allowed to read the reservation info if ( !reservationVisible ) { ReservationImpl clone = reservation.clone(); // we can safely change the reservation info here because we cloned it in transaction safe before DynamicType anonymousReservationType = operator.getDynamicType( StorageOperator.ANONYMOUSEVENT_TYPE); clone.setClassification( anonymousReservationType.newClassification()); clone.setReadOnly(); return clone; } else { return reservation; } } protected boolean isAllocatablesVisible(User sessionUser, Reservation res) { User owner = res.getOwner(); if (sessionUser.isAdmin() || owner == null || owner.equals(sessionUser) ) { return true; } for (Allocatable allocatable: res.getAllocatables()) { if (allocatable.canRead(sessionUser)) { return true; } } return true; } public FutureResult<VoidResult> restartServer() { try { checkAuthentified(); if (!getSessionUser().isAdmin()) throw new RaplaSecurityException("Only admins can restart the server"); context.lookup(ShutdownService.class).shutdown( true); return ResultImpl.VOID; } catch (RaplaException ex ) { return new ResultImpl<VoidResult>(ex ); } } public FutureResult<UpdateEvent> dispatch(UpdateEvent event) { try { Date currentTimestamp = operator.getCurrentTimestamp(); Date lastSynced = event.getLastValidated(); if ( lastSynced == null) { throw new RaplaException("client sync time is missing"); } if ( lastSynced.after( currentTimestamp)) { long diff = lastSynced.getTime() - currentTimestamp.getTime(); getLogger().warn("Timestamp of client " +diff + " ms after server "); lastSynced = currentTimestamp; } // LocalCache cache = operator.getCache(); // UpdateEvent event = createUpdateEvent( context,xml, cache ); User sessionUser = getSessionUser(); getLogger().info("Dispatching change for user " + sessionUser); if ( sessionUser != null) { event.setUserId(sessionUser.getId()); } dispatch_( event); getLogger().info("Change for user " + sessionUser + " dispatched."); UpdateEvent result = createUpdateEvent( lastSynced ); return new ResultImpl<UpdateEvent>(result ); } catch (RaplaException ex ) { return new ResultImpl<UpdateEvent>(ex ); } } public FutureResult<String> canChangePassword() { try { checkAuthentified(); Boolean result = operator.canChangePassword(); return new ResultImpl<String>( result.toString()); } catch (RaplaException ex ) { return new ResultImpl<String>(ex ); } } public FutureResult<VoidResult> changePassword(String username ,String oldPassword ,String newPassword ) { try { checkAuthentified(); User sessionUser = getSessionUser(); if (!sessionUser.isAdmin()) { if ( authenticationStore != null ) { throw new RaplaSecurityException("Rapla can't change your password. Authentication handled by ldap plugin." ); } operator.authenticate(username,new String(oldPassword)); } User user = operator.getUser(username); operator.changePassword(user,oldPassword.toCharArray(),newPassword.toCharArray()); return ResultImpl.VOID; } catch (RaplaException ex ) { return new ResultImpl<VoidResult>(ex ); } } public FutureResult<VoidResult> changeName(String username,String newTitle, String newSurename, String newLastname) { try { User changingUser = getSessionUser(); User user = operator.getUser(username); if ( changingUser.isAdmin() || user.equals( changingUser) ) { operator.changeName(user,newTitle,newSurename,newLastname); } else { throw new RaplaSecurityException("Not allowed to change email from other users"); } return ResultImpl.VOID; } catch (RaplaException ex ) { return new ResultImpl<VoidResult>(ex ); } } public FutureResult<VoidResult> changeEmail(String username,String newEmail) { try { User changingUser = getSessionUser(); User user = operator.getUser(username); if ( changingUser.isAdmin() || user.equals( changingUser) ) { operator.changeEmail(user,newEmail); } else { throw new RaplaSecurityException("Not allowed to change email from other users"); } return ResultImpl.VOID; } catch (RaplaException ex ) { return new ResultImpl<VoidResult>(ex ); } } public FutureResult<VoidResult> confirmEmail(String username,String newEmail) { try { User changingUser = getSessionUser(); User user = operator.getUser(username); if ( changingUser.isAdmin() || user.equals( changingUser) ) { String subject = getString("security_code"); Preferences prefs = operator.getPreferences( null, true ); String mailbody = "" + getString("send_code_mail_body_1") + user.getUsername() + ",\n\n" + getString("send_code_mail_body_2") + "\n\n" + getString("security_code") + Math.abs(user.getEmail().hashCode()) + "\n\n" + getString("send_code_mail_body_3") + "\n\n" + "-----------------------------------------------------------------------------------" + "\n\n" + getString("send_code_mail_body_4") + prefs.getEntryAsString(RaplaMainContainer.TITLE, getString("rapla.title")) + " " + getString("send_code_mail_body_5"); final MailInterface mail = context.lookup(MailInterface.class); final String defaultSender = prefs.getEntryAsString( MailPlugin.DEFAULT_SENDER_ENTRY, ""); mail.sendMail( defaultSender, newEmail,subject, "" + mailbody); } else { throw new RaplaSecurityException("Not allowed to change email from other users"); } return ResultImpl.VOID; } catch (RaplaException ex ) { return new ResultImpl<VoidResult>(ex ); } } private String getString(String key) throws RaplaException { return getI18n().getString( key); } public FutureResult<List<String>> createIdentifier(String type, int count) { try { RaplaType raplaType = RaplaType.find( type); checkAuthentified(); //User user = getSessionUser(); //check if authenified String[] result =operator.createIdentifier(raplaType, count); return new ResultImpl<List<String>>( Arrays.asList(result)); } catch (RaplaException ex ) { return new ResultImpl<List<String>>(ex ); } } public FutureResult<UpdateEvent> refresh(String lastSyncedTime) { try { checkAuthentified(); Date clientRepoVersion = SerializableDateTimeFormat.INSTANCE.parseTimestamp(lastSyncedTime); UpdateEvent event = createUpdateEvent(clientRepoVersion); return new ResultImpl<UpdateEvent>( event); } catch (RaplaException ex ) { return new ResultImpl<UpdateEvent>(ex ); } catch (ParseDateException e) { return new ResultImpl<UpdateEvent>(new RaplaException( e.getMessage()) ); } } public Logger getLogger() { return session.getLogger(); } private void checkAuthentified() throws RaplaSecurityException { if (!session.isAuthentified()) { throw new RaplaSecurityException(RemoteStorage.USER_WAS_NOT_AUTHENTIFIED); } } private User getSessionUser() throws RaplaException { return session.getUser(); } private void dispatch_(UpdateEvent evt) throws RaplaException { checkAuthentified(); try { User user; if ( evt.getUserId() != null) { user = operator.resolve(evt.getUserId(), User.class); } else { user = session.getUser(); } Collection<Entity>storeObjects = evt.getStoreObjects(); EntityStore store = new EntityStore(operator, operator.getSuperCategory()); store.addAll(storeObjects); for (EntityReferencer references:evt.getEntityReferences( true)) { references.setResolver( store); } for (Entity entity:storeObjects) { security.checkWritePermissions(user,entity); } List<PreferencePatch> preferencePatches = evt.getPreferencePatches(); for (PreferencePatch patch:preferencePatches) { security.checkWritePermissions(user,patch); } Collection<Entity>removeObjects = evt.getRemoveObjects(); for ( Entity entity:removeObjects) { security.checkWritePermissions(user,entity); } if (this.getLogger().isDebugEnabled()) this.getLogger().debug("Dispatching changes to " + operator.getClass()); operator.dispatch(evt); if (this.getLogger().isDebugEnabled()) this.getLogger().debug("Changes dispatched returning result."); } catch (DependencyException ex) { throw ex; } catch (RaplaNewVersionException ex) { throw ex; } catch (RaplaSecurityException ex) { this.getLogger().warn(ex.getMessage()); throw ex; } catch (RaplaException ex) { this.getLogger().error(ex.getMessage(),ex); throw ex; } catch (Exception ex) { this.getLogger().error(ex.getMessage(),ex); throw new RaplaException(ex); } catch (Error ex) { this.getLogger().error(ex.getMessage(),ex); throw ex; } } private UpdateEvent createUpdateEvent( Date lastSynced ) throws RaplaException { Date currentTimestamp = operator.getCurrentTimestamp(); if ( lastSynced.after( currentTimestamp)) { long diff = lastSynced.getTime() - currentTimestamp.getTime(); getLogger().warn("Timestamp of client " +diff + " ms after server "); lastSynced = currentTimestamp; } User user = getSessionUser(); UpdateEvent safeResultEvent = new UpdateEvent(); safeResultEvent.setLastValidated( currentTimestamp); TimeZone systemTimeZone = operator.getTimeZone(); int timezoneOffset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, currentTimestamp.getTime()); safeResultEvent.setTimezoneOffset( timezoneOffset ); //if ( lastSynced.before( currentTimestamp )) { String userId = user.getId(); TimeInterval invalidateInterval; { Long lastVersion = needConflictRefresh.get( userId ); if ( lastVersion != null && lastVersion > lastSynced.getTime()) { invalidateInterval = new TimeInterval( null, null); } else { invalidateInterval = getInvalidateInterval( lastSynced.getTime() ); } } boolean resourceRefresh; { Long lastVersion = needResourceRefresh.get( userId); resourceRefresh = ( lastVersion != null && lastVersion > lastSynced.getTime()); } safeResultEvent.setNeedResourcesRefresh( resourceRefresh); safeResultEvent.setInvalidateInterval( invalidateInterval); } if ( !safeResultEvent.isNeedResourcesRefresh()) { Collection<Entity> updatedEntities = operator.getUpdatedEntities(lastSynced ); for ( Entity obj: updatedEntities ) { processClientReadable( user, safeResultEvent, obj, false); } } return safeResultEvent; } protected void processClientReadable(User user,UpdateEvent safeResultEvent, Entity obj, boolean remove) { if ( !isTransferedToClient(obj)) { return; } boolean clientStore = true; if (user != null ) { // we don't transmit preferences for other users if ( obj instanceof Preferences) { Preferences preferences = (Preferences) obj; User owner = preferences.getOwner(); if ( owner != null && !owner.equals( user)) { clientStore = false; } else { obj = removeServerOnlyPreferences(preferences); } } else if ( obj instanceof Allocatable) { Allocatable alloc = (Allocatable) obj; if ( !alloc.canReadOnlyInformation(user)) { clientStore = false; } } else if ( obj instanceof Conflict) { Conflict conflict = (Conflict) obj; if ( !ConflictImpl.canModify( conflict, user, operator) ) { clientStore = false; } } } if ( clientStore) { if ( remove) { safeResultEvent.putRemove( obj ); } else { safeResultEvent.putStore( obj ); } } } // protected List<Entity>getDependentObjects( // Appointment appointment) { // List<Entity> toAdd = new ArrayList<Entity>(); // toAdd.add( (Entity)appointment); // @SuppressWarnings("unchecked") // ReservationImpl reservation = (ReservationImpl)appointment.getReservation(); // { // toAdd.add(reservation); // String id = reservation.getId(); // Entity inCache; // try { // inCache = operator.resolve( id); // } catch (EntityNotFoundException e) { // inCache = null; // } // if ( inCache != null && ((RefEntity)inCache).getVersion() > reservation.getVersion()) // { // getLogger().error("Try to send an older version of the reservation to the client " + reservation.getName( raplaLocale.getLocale())); // } // for (Entity ref:reservation.getSubEntities()) // { // toAdd.add( ref ); // } // } // if (!toAdd.contains(appointment)) // { // getLogger().error(appointment.toString() + " at " + raplaLocale.formatDate(appointment.getStart()) + " does refer to reservation " + reservation.getName( raplaLocale.getLocale()) + " but the reservation does not refer back."); // } // return toAdd; // } // private TimeInterval getInvalidateInterval( long clientRepositoryVersion) { TimeInterval interval = null; synchronized (invalidateMap) { for ( TimeInterval current:invalidateMap.tailMap( clientRepositoryVersion).values()) { if ( current != null) { interval = current.union( interval); } } return interval; } } public FutureResult<List<ConflictImpl>> getConflicts() { try { Set<Entity>completeList = new HashSet<Entity> (); User sessionUser = getSessionUser(); Collection<Conflict> conflicts = operator.getConflicts( sessionUser); List<ConflictImpl> result = new ArrayList<ConflictImpl>(); for ( Conflict conflict:conflicts) { result.add( (ConflictImpl) conflict); Entity conflictRef = (Entity)conflict; completeList.add(conflictRef); //completeList.addAll( getDependentObjects(conflict.getAppointment1())); //completeList.addAll( getDependentObjects(conflict.getAppointment2())); } //EntityList list = createList( completeList, repositoryVersion ); return new ResultImpl<List<ConflictImpl>>( result); } catch (RaplaException ex ) { return new ResultImpl<List<ConflictImpl>>(ex ); } } @Override public FutureResult<Date> getNextAllocatableDate( String[] allocatableIds, AppointmentImpl appointment,String[] reservationIds, Integer worktimestartMinutes, Integer worktimeendMinutes, Integer[] excludedDays, Integer rowsPerHour) { try { checkAuthentified(); List<Allocatable> allocatables = resolveAllocatables(allocatableIds); Collection<Reservation> ignoreList = resolveReservations(reservationIds); Date result = operator.getNextAllocatableDate(allocatables, appointment, ignoreList, worktimestartMinutes, worktimeendMinutes, excludedDays, rowsPerHour); return new ResultImpl<Date>( result); } catch (RaplaException ex ) { return new ResultImpl<Date>(ex ); } } @Override public FutureResult<BindingMap> getFirstAllocatableBindings(String[] allocatableIds, List<AppointmentImpl> appointments, String[] reservationIds) { try { checkAuthentified(); //Integer[][] result = new Integer[allocatableIds.length][]; List<Allocatable> allocatables = resolveAllocatables(allocatableIds); Collection<Reservation> ignoreList = resolveReservations(reservationIds); List<Appointment> asList = cast(appointments); Map<Allocatable, Collection<Appointment>> bindings = operator.getFirstAllocatableBindings(allocatables, asList, ignoreList); Map<String,List<String>> result = new LinkedHashMap<String,List<String>>(); for ( Allocatable alloc:bindings.keySet()) { Collection<Appointment> apps = bindings.get(alloc); if ( apps == null) { apps = Collections.emptyList(); } ArrayList<String> indexArray = new ArrayList<String>(apps.size()); for ( Appointment app: apps) { for (Appointment app2:appointments) { if (app2.equals(app )) { indexArray.add ( app.getId()); } } } result.put(alloc.getId(), indexArray); } return new ResultImpl<BindingMap>(new BindingMap(result)); } catch (RaplaException ex ) { return new ResultImpl<BindingMap>(ex); } } private List<Appointment> cast(List<AppointmentImpl> appointments) { List<Appointment> result = new ArrayList<Appointment>(appointments.size()); for (Appointment app:appointments) { result.add( app); } return result; } public FutureResult<List<ReservationImpl>> getAllAllocatableBindings(String[] allocatableIds, List<AppointmentImpl> appointments, String[] reservationIds) { try { Set<ReservationImpl> result = new HashSet<ReservationImpl>(); checkAuthentified(); List<Allocatable> allocatables = resolveAllocatables(allocatableIds); Collection<Reservation> ignoreList = resolveReservations(reservationIds); List<Appointment> asList = cast(appointments); Map<Allocatable, Map<Appointment, Collection<Appointment>>> bindings = operator.getAllAllocatableBindings(allocatables, asList, ignoreList); for (Allocatable alloc:bindings.keySet()) { Map<Appointment,Collection<Appointment>> appointmentBindings = bindings.get( alloc); for (Appointment app: appointmentBindings.keySet()) { Collection<Appointment> bound = appointmentBindings.get( app); if ( bound != null) { for ( Appointment appointment: bound) { ReservationImpl reservation = (ReservationImpl) appointment.getReservation(); if ( reservation != null) { result.add( reservation); } } } } } return new ResultImpl<List<ReservationImpl>>(new ArrayList<ReservationImpl>(result)); } catch (RaplaException ex) { return new ResultImpl<List<ReservationImpl>>(ex); } } private List<Allocatable> resolveAllocatables(String[] allocatableIds) throws RaplaException,EntityNotFoundException, RaplaSecurityException { List<Allocatable> allocatables = new ArrayList<Allocatable>(); User sessionUser = getSessionUser(); for ( String id:allocatableIds) { Allocatable entity = operator.resolve(id, Allocatable.class); allocatables.add( entity); security.checkRead(sessionUser, entity); } return allocatables; } private Collection<Reservation> resolveReservations(String[] ignoreList) { Set<Reservation> ignoreConflictsWith = new HashSet<Reservation>(); for (String reservationId: ignoreList) { try { Reservation entity = operator.resolve(reservationId, Reservation.class); ignoreConflictsWith.add( entity); } catch (EntityNotFoundException ex) { // Do nothing reservation not found and assumed new } } return ignoreConflictsWith; } // public void logEntityNotFound(String logMessage,String... referencedIds) // { // StringBuilder buf = new StringBuilder(); // buf.append("{"); // for (String id: referencedIds) // { // buf.append("{ id="); // if ( id != null) // { // buf.append(id.toString()); // buf.append(": "); // Entity refEntity = operator.tryResolve(id); // if ( refEntity != null ) // { // buf.append( refEntity.toString()); // } // else // { // buf.append("NOT FOUND"); // } // } // else // { // buf.append( "is null"); // } // // buf.append("}, "); // } // buf.append("}"); // getLogger().error("EntityNotFoundFoundExceptionOnClient "+ logMessage + " " + buf.toString()); // //return ResultImpl.VOID; // } }; } static public void convertToNewPluginConfig(RaplaContext context, String className, TypedComponentRole<RaplaConfiguration> newConfKey) throws RaplaContextException { ClientFacade facade = context.lookup( ClientFacade.class); // { // RaplaConfiguration entry = facade.getPreferences().getEntry(RaplaComponent.PLUGIN_CONFIG,null); // if ( entry == null ) // { // return; // } // DefaultConfiguration pluginConfig = (DefaultConfiguration)entry.find("class", className); // if ( pluginConfig == null) // { // return; // } // // only class and getEnabled // // } try { PreferencesImpl clone = (PreferencesImpl) facade.edit( facade.getSystemPreferences()); RaplaConfiguration entry = clone.getEntry(RaplaComponent.PLUGIN_CONFIG,null); RaplaConfiguration newPluginConfigEntry = entry.clone(); DefaultConfiguration pluginConfig = (DefaultConfiguration)newPluginConfigEntry.find("class", className); // we split the config entry in the plugin config and the new config entry; if ( pluginConfig != null) { context.lookup(Logger.class).info("Converting plugin conf " + className + " to preference entry " + newConfKey); newPluginConfigEntry.removeChild( pluginConfig); boolean enabled = pluginConfig.getAttributeAsBoolean("enabled", false); RaplaConfiguration newPluginConfig = new RaplaConfiguration(pluginConfig.getName()); newPluginConfig.setAttribute("enabled", enabled); newPluginConfig.setAttribute("class", className); newPluginConfigEntry.addChild( newPluginConfig); RaplaConfiguration newConfigEntry = new RaplaConfiguration( pluginConfig); newConfigEntry.setAttribute("enabled", null); newConfigEntry.setAttribute("class", null); clone.putEntry(newConfKey, newConfigEntry); clone.putEntry(RaplaComponent.PLUGIN_CONFIG, newPluginConfigEntry); facade.store( clone); } } catch (RaplaException ex) { if ( ex instanceof RaplaContextException) { throw (RaplaContextException)ex; } throw new RaplaContextException(ex.getMessage(),ex); } } }
04900db4-rob
src/org/rapla/server/internal/RemoteStorageImpl.java
Java
gpl3
56,702
package org.rapla.server.internal; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Collection; import java.util.Collections; import org.apache.commons.codec.binary.Base64; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; import org.rapla.server.RaplaKeyStorage; public class RaplaKeyStorageImpl extends RaplaComponent implements RaplaKeyStorage { //private static final String USER_KEYSTORE = "keystore"; private static final String ASYMMETRIC_ALGO = "RSA"; private static final TypedComponentRole<String> PUBLIC_KEY = new TypedComponentRole<String>("org.rapla.crypto.publicKey"); private static final TypedComponentRole<String> APIKEY = new TypedComponentRole<String>("org.rapla.crypto.server.refreshToken"); private static final TypedComponentRole<String> PRIVATE_KEY = new TypedComponentRole<String>("org.rapla.crypto.server.privateKey"); private String rootKey; private String rootPublicKey; private Base64 base64; CryptoHandler cryptoHandler; public String getRootKeyBase64() { return rootKey; } /** * Initializes the Url encryption plugin. * Checks whether an encryption key exists or not, reads an existing one from the configuration file * or generates a new one. The decryption and encryption ciphers are also initialized here. * * @param context * @param config * @throws RaplaException */ public RaplaKeyStorageImpl(RaplaContext context) throws RaplaException { super(context); byte[] linebreake = {}; // we use an url safe encoder for the keys this.base64 = new Base64(64, linebreake, true); rootKey = getQuery().getSystemPreferences().getEntryAsString(PRIVATE_KEY, null); rootPublicKey = getQuery().getSystemPreferences().getEntryAsString(PUBLIC_KEY, null); if ( rootKey == null || rootPublicKey == null) { try { generateRootKeyStorage(); } catch (NoSuchAlgorithmException e) { throw new RaplaException( e.getMessage()); } } cryptoHandler = new CryptoHandler( context,rootKey); } public LoginInfo decrypt(String encrypted) throws RaplaException { LoginInfo loginInfo = new LoginInfo(); String decrypt = cryptoHandler.decrypt(encrypted); String[] split = decrypt.split(":",2); loginInfo.login = split[0]; loginInfo.secret = split[1]; return loginInfo; } @Override public void storeAPIKey(User user,String clientId, String newApiKey) throws RaplaException { Preferences preferences = getQuery().getPreferences(user); Preferences edit = getModification().edit( preferences); edit.putEntry(APIKEY, newApiKey); getModification().store( edit); } @Override public Collection<String> getAPIKeys(User user) throws RaplaException { String annotation = getQuery().getPreferences(user).getEntryAsString(APIKEY, null); if (annotation == null) { return Collections.emptyList(); } Collection<String> keyList = Collections.singleton( annotation ); return keyList; } @Override public void removeAPIKey(User user, String apikey) throws RaplaException { throw new UnsupportedOperationException(); // Allocatable key= getAllocatable(user); // if ( key != null ) // { // Collection<String> keyList = parseList(key.getAnnotation(APIKEY)); // if (keyList == null || !keyList.contains(apikey)) // { // return; // } // key = getModification().edit( key ); // keyList.remove( apikey); // if ( keyList.size() > 0) // { // key.setAnnotation(APIKEY, null); // } // else // { // key.setAnnotation(APIKEY, serialize(keyList)); // } // // remove when no more annotations set // if (key.getAnnotationKeys().length == 0) // { // getModification().remove( key); // } // else // { // getModification().store( key); // } // } } @Override public LoginInfo getSecrets(User user, TypedComponentRole<String> tagName) throws RaplaException { String annotation = getQuery().getPreferences(user).getEntryAsString(tagName, null); if ( annotation == null) { return null; } return decrypt(annotation); } @Override public void storeLoginInfo(User user,TypedComponentRole<String> tagName,String login,String secret) throws RaplaException { Preferences preferences = getQuery().getPreferences(user); Preferences edit = getModification().edit( preferences); String loginPair = login +":" + secret; String encrypted = cryptoHandler.encrypt( loginPair); edit.putEntry(tagName, encrypted); getModification().store( edit); } // public Allocatable getOrCreate(User user) throws RaplaException { // Allocatable key= getAllocatable(user); // if ( key == null) // { // DynamicType dynamicType = getQuery().getDynamicType( StorageOperator.CRYPTO_TYPE); // Classification classification = dynamicType.newClassification(); // key = getModification().newAllocatable(classification, null ); // if ( user != null) // { // key.setOwner( user); // } // key.setClassification( classification); // } // else // { // key = getModification().edit( key); // } // return key; // } public void removeLoginInfo(User user, TypedComponentRole<String> tagName) throws RaplaException { Preferences preferences = getQuery().getPreferences(user); Preferences edit = getModification().edit( preferences); edit.putEntry(tagName, null); getModification().store( edit); } // // Allocatable getAllocatable(User user) throws RaplaException // { // Collection<Allocatable> store = getAllocatables(); // if ( store.size() > 0) // { // for ( Allocatable all:store) // { // User owner = all.getOwner(); // if ( user == null) // { // if ( owner == null ) // { // return all; // } // } // else // { // if ( owner != null && user.equals( owner)) // { // return all; // } // } // } // } // return null; // } // public Collection<Allocatable> getAllocatables() throws RaplaException // { // StorageOperator operator = getClientFacade().getOperator(); // DynamicType dynamicType = operator.getDynamicType( StorageOperator.CRYPTO_TYPE); // ClassificationFilter newClassificationFilter = dynamicType.newClassificationFilter(); // ClassificationFilter[] array = newClassificationFilter.toArray(); // Collection<Allocatable> store = operator.getAllocatables( array); // return store; // } private void generateRootKeyStorage() throws NoSuchAlgorithmException, RaplaException { getLogger().info("Generating new root key. This can take a while."); //Classification newClassification = dynamicType.newClassification(); //newClassification.setValue("name", "root"); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance( ASYMMETRIC_ALGO ); keyPairGen.initialize( 2048); KeyPair keyPair = keyPairGen.generateKeyPair(); getLogger().info("Root key generated"); PrivateKey privateKeyObj = keyPair.getPrivate(); this.rootKey = base64.encodeAsString(privateKeyObj.getEncoded()); PublicKey publicKeyObj = keyPair.getPublic(); this.rootPublicKey =base64.encodeAsString(publicKeyObj.getEncoded()); Preferences systemPreferences = getQuery().getSystemPreferences(); Preferences edit = getModification().edit( systemPreferences); edit.putEntry(PRIVATE_KEY, rootKey); edit.putEntry(PUBLIC_KEY, rootPublicKey); getModification().store( edit); } }
04900db4-rob
src/org/rapla/server/internal/RaplaKeyStorageImpl.java
Java
gpl3
8,354
package org.rapla.server.internal; import java.io.BufferedWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.LinkedHashMap; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.rapla.RaplaMainContainer; import org.rapla.facade.RaplaComponent; import org.rapla.framework.Configuration; import org.rapla.framework.RaplaContext; import org.rapla.servletpages.RaplaPageGenerator; public class RaplaConfPageGenerator extends RaplaComponent implements RaplaPageGenerator{ public RaplaConfPageGenerator(RaplaContext context) { super(context); } public void generatePage( ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws IOException { java.io.PrintWriter out = response.getWriter(); response.setContentType("application/xml;charset=utf-8"); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<rapla-config>"); Configuration conf = getService(RaplaMainContainer.RAPLA_MAIN_CONFIGURATION); //<!-- Use this to customize the rapla resources //<default-bundle>org.rapla.MyResources</default-bundle> //--> Configuration localeConf = conf.getChild("locale"); if ( localeConf != null) { printConfiguration( out, localeConf); } Configuration[] bundles = conf.getChildren("default-bundle"); for ( Configuration bundle: bundles) { printConfiguration( out, bundle); } String remoteId = null; Configuration[] clients = conf.getChildren("rapla-client"); for ( Configuration client: clients) { if ( client.getAttribute("id", "").equals( "client")) { remoteId = client.getChild("facade").getChild("store").getValue( "remote"); printConfiguration( out, client); break; } } if ( remoteId != null) { Configuration[] storages = conf.getChildren("remote-storage"); for ( Configuration storage: storages) { if ( storage.getAttribute("id", "").equals( remoteId)) { printConfiguration( out, storage); } } } else { // Config not found use default out.println("<rapla-client id=\"client\">"); out.println(" <facade id=\"facade\">"); out.println(" <store>remote</store>"); out.println(" </facade>"); out.println("</rapla-client>"); out.println(" "); out.println("<remote-storage id=\"remote\">"); out.println(" <server>${download-url}</server>"); out.println("</remote-storage>"); } out.println(" "); out.println("</rapla-config>"); out.close(); } private void printConfiguration(PrintWriter out, Configuration conf) throws IOException { ConfigurationWriter configurationWriter = new ConfigurationWriter(); BufferedWriter writer = new BufferedWriter( out); configurationWriter.setWriter( writer); configurationWriter.printConfiguration( conf); writer.flush(); } class ConfigurationWriter extends org.rapla.components.util.xml.XMLWriter { private void printConfiguration(Configuration element) throws 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/server/internal/RaplaConfPageGenerator.java
Java
gpl3
5,094
/*--------------------------------------------------------------------------* | 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.server.internal; public interface ShutdownService { void shutdown( boolean restart); }
04900db4-rob
src/org/rapla/server/internal/ShutdownService.java
Java
gpl3
1,049
package org.rapla.server.internal; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.Key; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class CryptoHandler extends RaplaComponent { String syncEncryptionAlg = "AES/ECB/PKCS5Padding"; private Cipher encryptionCipher; private Cipher decryptionCipher; private Base64 base64; private static final String ENCODING = "UTF-8"; public CryptoHandler( RaplaContext context,String pepper) throws RaplaException { super( context); try { byte[] linebreake = {}; this.base64 = new Base64(64, linebreake, true); initializeCiphers( pepper); } catch (Exception e) { throw new RaplaException( e.getMessage(),e); } } private void initializeCiphers(String pepper) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException { byte[] key = pepper.getBytes("UTF-8"); MessageDigest sha = MessageDigest.getInstance("SHA-1"); key = sha.digest(key); key = Arrays.copyOf(key, 16); // use only first 128 bit Key specKey = new SecretKeySpec(key, "AES"); this.encryptionCipher = Cipher.getInstance(syncEncryptionAlg); this.encryptionCipher.init(Cipher.ENCRYPT_MODE, specKey); this.decryptionCipher = Cipher.getInstance(syncEncryptionAlg); this.decryptionCipher.init(Cipher.DECRYPT_MODE, specKey); } public String encrypt(String toBeEncrypted) throws RaplaException{ try { return base64.encodeToString(this.encryptionCipher.doFinal(toBeEncrypted.getBytes(ENCODING))); } catch (Exception e) { throw new RaplaException(e.getMessage(), e); } } public String decrypt(String toBeDecryptedBase64) throws RaplaException{ try { return new String(this.decryptionCipher.doFinal(base64.decode(toBeDecryptedBase64.getBytes(ENCODING)))); } catch (Exception e) { throw new RaplaException(e.getMessage(), e); } } }
04900db4-rob
src/org/rapla/server/internal/CryptoHandler.java
Java
gpl3
2,334
package org.rapla.server; import org.rapla.framework.RaplaContextException; public interface RemoteMethodFactory<T> { public T createService(final RemoteSession remoteSession) throws RaplaContextException; }
04900db4-rob
src/org/rapla/server/RemoteMethodFactory.java
Java
gpl3
227
package org.rapla.server; import java.util.Date; import java.util.TimeZone; public interface TimeZoneConverter { /** returns the timezone configured via main options, this is per default the system timezon. This timezone is used for ical/exchange import/export If Rapla will support timezones in the future, than this will be the default timezone for all times. Now its only used on import and export. It works as with system time above. 10:00am GMT+0 is converted to 10:00am of the configured timezone on export and on import all times are converted to GMT+0. @see TimeZoneConverter#toRaplaTime(TimeZone, long) */ TimeZone getImportExportTimeZone(); long fromRaplaTime(TimeZone timeZone,long raplaTime); long toRaplaTime(TimeZone timeZone,long time); Date fromRaplaTime(TimeZone timeZone,Date raplaTime); /** * converts a common Date object into a Date object that * assumes that the user (being in the given timezone) is in the * UTC-timezone by adding the offset between UTC and the given timezone. * * <pre> * Example: If you pass the Date "2013 Jan 15 11:00:00 UTC" * and the TimeZone "GMT+1", this method will return a Date * "2013 Jan 15 12:00:00 UTC" which is effectivly 11:00:00 GMT+1 * </pre> * * @param timeZone * the orgin timezone * @param time * the Date object in the passed timezone * @see fromRaplaTime */ Date toRaplaTime(TimeZone timeZone,Date time); }
04900db4-rob
src/org/rapla/server/TimeZoneConverter.java
Java
gpl3
1,507
/*--------------------------------------------------------------------------* | 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.server; import org.rapla.entities.Category; import org.rapla.entities.User; import org.rapla.framework.RaplaException; public interface AuthenticationStore { /** returns, if the user can be authenticated. */ boolean authenticate(String username, String password) throws RaplaException; /** returns the name of the store */ String getName(); /** Initializes a user entity with the values provided by the authentication store. * @return <code>true</code> if the new user-object attributes (such as email, name, or groups) differ from the values stored before the method was executed, <code>false</code> otherwise. */ boolean initUser( User user, String username, String password, Category groupRootCategory) throws RaplaException; }
04900db4-rob
src/org/rapla/server/AuthenticationStore.java
Java
gpl3
1,722
package org.rapla.server; import java.util.Collection; import org.rapla.entities.User; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; public interface RaplaKeyStorage { public String getRootKeyBase64(); public LoginInfo getSecrets(User user, TypedComponentRole<String> tagName) throws RaplaException; public void storeLoginInfo(User user,TypedComponentRole<String> tagName,String login,String secret) throws RaplaException; public void removeLoginInfo(User user, TypedComponentRole<String> tagName) throws RaplaException; public void storeAPIKey(User user,String clientId,String apiKey) throws RaplaException; public Collection<String> getAPIKeys(User user) throws RaplaException; public void removeAPIKey(User user,String key) throws RaplaException; public class LoginInfo { public String login; public String secret; } }
04900db4-rob
src/org/rapla/server/RaplaKeyStorage.java
Java
gpl3
919
package org.rapla.server; import javax.servlet.http.HttpServletRequest; import org.rapla.entities.User; import org.rapla.framework.Configuration; import org.rapla.framework.Container; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaException; import org.rapla.servletpages.RaplaPageGenerator; public interface ServerServiceContainer extends Container { <T> void addRemoteMethodFactory( Class<T> service, Class<? extends RemoteMethodFactory<T>> factory); <T> void addRemoteMethodFactory( Class<T> service, Class<? extends RemoteMethodFactory<T>> factory, Configuration config); /** * You can add arbitrary serlvet pages to your rapla webapp. * * Example that adds a page with the name "my-page-name" and the class * "org.rapla.plugin.myplugin.MyPageGenerator". You can call this page with <code>rapla?page=my-page-name</code> * <p/> * In the provideService Method of your PluginDescriptor do the following <pre> container.addContainerProvidedComponent( RaplaExtensionPoints.SERVLET_PAGE_EXTENSION, "org.rapla.plugin.myplugin.MyPageGenerator", "my-page-name", config); </pre> *@see org.rapla.servletpages.RaplaPageGenerator */ <T extends RaplaPageGenerator> void addWebpage(String pagename, Class<T> pageClass); <T extends RaplaPageGenerator> void addWebpage(String pagename, Class<T> pageClass, Configuration config); /** @return null when the server doesn't have the webpage * @throws RaplaContextException */ RaplaPageGenerator getWebpage(String page); public User getUser(HttpServletRequest request) throws RaplaException; <T> T createWebservice(Class<T> role,HttpServletRequest request ) throws RaplaException; boolean hasWebservice(String interfaceName); }
04900db4-rob
src/org/rapla/server/ServerServiceContainer.java
Java
gpl3
1,800
package org.rapla.server; /** * a class implementing server extension is started automatically when the server is up and running and connected to a data store. * */ public interface ServerExtension { }
04900db4-rob
src/org/rapla/server/ServerExtension.java
Java
gpl3
215
package org.rapla.server; import org.rapla.framework.TypedComponentRole; import org.rapla.gui.SwingViewFactory; import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory; import org.rapla.servletpages.RaplaMenuGenerator; import org.rapla.servletpages.ServletRequestPreprocessor; /** Constant Pool of basic extension points of the Rapla server. * You can add your extension in the provideService Method of your PluginDescriptor * <pre> * container.addContainerProvidedComponent( REPLACE_WITH_EXTENSION_POINT_NAME, REPLACE_WITH_CLASS_IMPLEMENTING_EXTENSION, config); * </pre> * @see org.rapla.framework.PluginDescriptor */ public class RaplaServerExtensionPoints { /** add your own views to Rapla, by providing a org.rapla.gui.ViewFactory * @see SwingViewFactory * */ public static final Class<HTMLViewFactory> HTML_CALENDAR_VIEW_EXTENSION = HTMLViewFactory.class; /** A server extension is started automaticaly when the server is up and running and connected to a data store. A class added as service doesn't need to implement a specific interface and is instanciated automaticaly after server start. You can add a RaplaContext parameter to your constructor to get access to the services of rapla. * */ public static final Class<ServerExtension> SERVER_EXTENSION = ServerExtension.class; /** you can add servlet pre processer to manipulate request and response before standard processing is * done by rapla */ public static final Class<ServletRequestPreprocessor> SERVLET_REQUEST_RESPONSE_PREPROCESSING_POINT = ServletRequestPreprocessor.class; /** you can add your own entries on the index page Just add a HTMLMenuEntry to the list @see RaplaMenuGenerator * */ public static final TypedComponentRole<RaplaMenuGenerator> HTML_MAIN_MENU_EXTENSION_POINT = new TypedComponentRole<RaplaMenuGenerator>("org.rapla.servletpages"); //public final static TypedComponentRole<List<PluginDescriptor<ServerServiceContainer>>> SERVER_PLUGIN_LIST = new TypedComponentRole<List<PluginDescriptor<ServerServiceContainer>>>("server-plugin-list"); }
04900db4-rob
src/org/rapla/server/RaplaServerExtensionPoints.java
Java
gpl3
2,115
<body> <p> The server synchronizes and bundles the client requests and maintains a single storage for all its clients. It also provides the basic services for the server side plugins. For instance the notification plugin notifies sends email on a reservation change. </p> <p> The server is also responsible for enforcing the access policies. </p> </body>
04900db4-rob
src/org/rapla/server/package.html
HTML
gpl3
358
/*--------------------------------------------------------------------------* | 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.server; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.naming.Context; import javax.naming.InitialContext; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.rapla.ConnectInfo; import org.rapla.RaplaMainContainer; import org.rapla.RaplaStartupEnvironment; import org.rapla.client.ClientService; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientListenerAdapter; import org.rapla.components.util.IOUtil; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.User; import org.rapla.facade.RaplaComponent; import org.rapla.framework.Container; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaDefaultContext; import org.rapla.framework.RaplaException; import org.rapla.framework.ServiceListCreator; import org.rapla.framework.StartupEnvironment; import org.rapla.framework.internal.ContainerImpl; import org.rapla.framework.internal.RaplaJDKLoggingAdapter; import org.rapla.framework.logger.Logger; import org.rapla.server.internal.ServerServiceImpl; import org.rapla.server.internal.ShutdownService; import org.rapla.servletpages.RaplaPageGenerator; import org.rapla.servletpages.ServletRequestPreprocessor; import org.rapla.storage.ImportExportManager; import org.rapla.storage.StorageOperator; import org.rapla.storage.dbrm.RemoteMethodStub; import org.rapla.storage.dbrm.WrongRaplaVersionException; public class MainServlet extends HttpServlet { private static final String RAPLA_RPC_PATH = "/rapla/rpc/"; private static final long serialVersionUID = 1L; /** The default config filename is raplaserver.xconf*/ private ContainerImpl raplaContainer; public final static String DEFAULT_CONFIG_NAME = "raplaserver.xconf"; private Logger logger = null; private String startupMode =null; private String startupUser = null; private Integer port; private String contextPath; private String env_rapladatasource; private String env_raplafile; private Object env_rapladb; private Object env_raplamail; private Boolean env_development; private String downloadUrl; private String serverVersion; private ServerServiceImpl server; private Runnable shutdownCommand; private Collection<ServletRequestPreprocessor> processors; private ReadWriteLock restartLock = new ReentrantReadWriteLock(); // the following variables are only for non server startup private Semaphore guiMutex = new Semaphore(1); private ConnectInfo reconnect; private URL getConfigFile(String entryName, String defaultName) throws ServletException,IOException { String configName = getServletConfig().getInitParameter(entryName); if (configName == null) configName = defaultName; if (configName == null) throw new ServletException("Must specify " + entryName + " entry in web.xml !"); String realPath = getServletConfig().getServletContext().getRealPath("/WEB-INF/" + configName); if (realPath != null) { File configFile = new File(realPath); if (configFile.exists()) { URL configURL = configFile.toURI().toURL(); return configURL; } } URL configURL = getClass().getResource("/raplaserver.xconf"); if ( configURL == null) { String message = "ERROR: Config file not found " + configName; throw new ServletException(message); } else { return configURL; } } /** * Initializes Servlet and creates a <code>RaplaMainContainer</code> instance * * @exception ServletException if an error occurs */ synchronized public void init() throws ServletException { getLogger().info("Init RaplaServlet"); Collection<String> instanceCounter = null; String selectedContextPath = null; Context env; try { Context initContext = new InitialContext(); Context envContext = (Context)initContext.lookup("java:comp"); env = (Context)envContext.lookup("env"); } catch (Exception e) { env = null; getLogger().warn("No JNDI Enivronment found under java:comp or java:/comp"); } if ( env != null) { env_rapladatasource = lookupEnvString(env, "rapladatasource", true); env_raplafile = lookupEnvString(env,"raplafile", true); env_rapladb = lookupResource(env, "jdbc/rapladb", true); getLogger().info("Passed JNDI Environment rapladatasource=" + env_rapladatasource + " env_rapladb="+env_rapladb + " env_raplafile="+ env_raplafile); if ( env_rapladatasource == null || env_rapladatasource.trim().length() == 0 || env_rapladatasource.startsWith( "${")) { if ( env_rapladb != null) { env_rapladatasource = "rapladb"; } else if ( env_raplafile != null) { env_rapladatasource = "raplafile"; } else { getLogger().warn("Neither file nor database setup configured."); } } env_raplamail = lookupResource(env, "mail/Session", false); startupMode = lookupEnvString(env,"rapla_startup_mode", false); env_development = (Boolean) lookupEnvVariable(env, "rapla_development", false); @SuppressWarnings("unchecked") Collection<String> instanceCounterLookup = (Collection<String>) lookup(env,"rapla_instance_counter", false); instanceCounter = instanceCounterLookup; selectedContextPath = lookupEnvString(env,"rapla_startup_context", false); startupUser = lookupEnvString( env, "rapla_startup_user", false); shutdownCommand = (Runnable) lookup(env,"rapla_shutdown_command", false); port = (Integer) lookup(env,"rapla_startup_port", false); downloadUrl = (String) lookup(env,"rapla_download_url", false); } if ( startupMode == null) { startupMode = "server"; } contextPath = getServletContext().getContextPath(); if ( !contextPath.startsWith("/")) { contextPath = "/" + contextPath; } // don't startup server if contextPath is not selected if ( selectedContextPath != null) { if( !contextPath.equals(selectedContextPath)) return; } else if ( instanceCounter != null) { instanceCounter.add( contextPath); if ( instanceCounter.size() > 1) { String msg = ("Ignoring webapp ["+ contextPath +"]. Multiple context found in jetty container " + instanceCounter + " You can specify one via -Dorg.rapla.context=REPLACE_WITH_CONTEXT"); getLogger().error(msg); return; } } startServer(startupMode); if ( startupMode.equals("standalone") || startupMode.equals("client")) { try { guiMutex.acquire(); } catch (InterruptedException e) { } try { startGUI(startupMode); } catch (Exception ex) { exit(); throw new ServletException(ex); } } } private Object lookupResource(Context env, String lookupname, boolean log) { String newLookupname = getServletContext().getInitParameter(lookupname); if (newLookupname != null && newLookupname.length() > 0) { lookupname = newLookupname; } Object result = lookup(env,lookupname, log); return result; } private String lookupEnvString(Context env, String lookupname, boolean log) { Object result = lookupEnvVariable(env, lookupname, log); return (String) result; } private Object lookupEnvVariable(Context env, String lookupname, boolean log) { String newEnvname = getServletContext().getInitParameter(lookupname); if ( newEnvname != null) { getLogger().info("Using contextparam for " + lookupname + ": " + newEnvname); } if (newEnvname != null && newEnvname.length() > 0 ) { return newEnvname; } else { Object result = lookup(env,lookupname, log); return result; } } private Object lookup(Context env, String string, boolean warn) { try { Object result = env.lookup( string); if ( result == null && warn) { getLogger().warn("JNDI Entry "+ string + " not found"); } return result; } catch (Exception e) { if ( warn ) { getLogger().warn("JNDI Entry "+ string + " not found"); } return null; } } private void startGUI(final String startupMode) throws ServletException { ConnectInfo connectInfo = null; if (startupMode.equals("standalone")) { try { String username = startupUser; if ( username == null ) { username = getFirstAdmin(); } if ( username != null) { connectInfo = new ConnectInfo(username, "".toCharArray()); } } catch (RaplaException ex) { getLogger().error(ex.getMessage(),ex); } } startGUI( startupMode, connectInfo); if ( startupMode.equals("standalone") || startupMode.equals("client")) { try { guiMutex.acquire(); while ( reconnect != null ) { raplaContainer.dispose(); try { if ( startupMode.equals("client")) { initContainer(startupMode); } else if ( startupMode.equals("standalone")) { startServer("standalone"); } if ( startupMode.equals("standalone") && reconnect.getUsername() == null) { String username = getFirstAdmin(); if ( username != null) { reconnect= new ConnectInfo(username, "".toCharArray()); } } startGUI(startupMode, reconnect); guiMutex.acquire(); } catch (Exception ex) { getLogger().error("Error restarting client",ex); exit(); return; } } } catch (InterruptedException e) { } } } protected String getFirstAdmin() throws RaplaContextException, RaplaException { String username = null; StorageOperator operator = server.getContext().lookup(StorageOperator.class); for (User u:operator.getUsers()) { if ( u.isAdmin()) { username = u.getUsername(); break; } } return username; } public void startGUI( final String startupMode, ConnectInfo connectInfo) throws ServletException { try { if ( startupMode.equals("standalone") || startupMode.equals("client")) { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( ClassLoader.getSystemClassLoader()); ClientServiceContainer clientContainer = raplaContainer.getContext().lookup(ClientServiceContainer.class ); ClientService client = clientContainer.getContext().lookup( ClientService.class); client.addRaplaClientListener(new RaplaClientListenerAdapter() { public void clientClosed(ConnectInfo reconnect) { MainServlet.this.reconnect = reconnect; if ( reconnect != null) { guiMutex.release(); } else { exit(); } } public void clientAborted() { exit(); } }); clientContainer.start(connectInfo); } finally { Thread.currentThread().setContextClassLoader( contextClassLoader); } } else if (!startupMode.equals("server")) { exit(); } } catch( Exception e ) { getLogger().error("Could not start server", e); if ( raplaContainer != null) { raplaContainer.dispose(); } throw new ServletException( "Error during initialization see logs for details: " + e.getMessage(), e ); } // log("Rapla Servlet started"); } protected void startServer(final String startupMode) throws ServletException { try { initContainer(startupMode); if ( startupMode.equals("import")) { ImportExportManager manager = raplaContainer.getContext().lookup(ImportExportManager.class); manager.doImport(); exit(); } else if (startupMode.equals("export")) { ImportExportManager manager = raplaContainer.getContext().lookup(ImportExportManager.class); manager.doExport(); exit(); } else if ( startupMode.equals("server") || startupMode.equals("standalone") ) { String hint = serverContainerHint != null ? serverContainerHint :"*"; // Start the server via lookup // We start the standalone server before the client to prevent jndi lookup failures server = (ServerServiceImpl) raplaContainer.lookup( ServerServiceContainer.class, hint); processors = server.lookupServicesFor(RaplaServerExtensionPoints.SERVLET_REQUEST_RESPONSE_PREPROCESSING_POINT); final Logger logger = getLogger(); logger.info("Rapla server started"); if ( startupMode.equals("server")) { // if setShutdownService(startupMode); } else { raplaContainer.addContainerProvidedComponentInstance(RemoteMethodStub.class, server); } } } catch( Exception e ) { getLogger().error(e.getMessage(), e); String message = "Error during initialization see logs for details: " + e.getMessage(); if ( raplaContainer != null) { raplaContainer.dispose(); } if ( shutdownCommand != null) { shutdownCommand.run(); } throw new ServletException( message,e); } } protected void setShutdownService(final String startupMode) { server.setShutdownService( new ShutdownService() { public void shutdown(final boolean restart) { Lock writeLock; try { try { RaplaComponent.unlock( restartLock.readLock()); } catch (IllegalMonitorStateException ex) { getLogger().error("Error unlocking read for restart " + ex.getMessage()); } writeLock = RaplaComponent.lock( restartLock.writeLock(), 60); } catch (RaplaException ex) { getLogger().error("Can't restart server " + ex.getMessage()); return; } try { //acquired = requestCount.tryAcquire(maxRequests -1,10, TimeUnit.SECONDS); logger.info( "Stopping Server"); stopServer(); if ( restart) { try { logger.info( "Restarting Server"); MainServlet.this.startServer(startupMode); } catch (Exception e) { logger.error( "Error while restarting Server", e ); } } } finally { RaplaComponent.unlock(writeLock); } } }); } protected void initContainer(String startupMode) throws ServletException, IOException, MalformedURLException, Exception, RaplaContextException { URL configURL = getConfigFile("config-file",DEFAULT_CONFIG_NAME); //URL logConfigURL = getConfigFile("log-config-file","raplaserver.xlog").toURI().toURL(); RaplaStartupEnvironment env = new RaplaStartupEnvironment(); env.setStartupMode( StartupEnvironment.CONSOLE); env.setConfigURL( configURL ); if ( startupMode.equals( "client")) { if ( port != null) { String url = downloadUrl; if ( url == null) { url = "http://localhost:" + port+ contextPath; if (! url.endsWith("/")) { url += "/"; } } env.setDownloadURL( new URL(url)); } } // env.setContextRootURL( contextRootURL ); //env.setLogConfigURL( logConfigURL ); RaplaDefaultContext context = new RaplaDefaultContext(); if ( env_rapladatasource != null) { context.put(RaplaMainContainer.ENV_RAPLADATASOURCE, env_rapladatasource); } if ( env_raplafile != null) { context.put(RaplaMainContainer.ENV_RAPLAFILE, env_raplafile); } if ( env_rapladb != null) { context.put(RaplaMainContainer.ENV_RAPLADB, env_rapladb); } if ( env_raplamail != null) { context.put(RaplaMainContainer.ENV_RAPLAMAIL, env_raplamail); getLogger().info("Configured mail service via JNDI"); } if ( env_development != null && env_development) { context.put(RaplaMainContainer.ENV_DEVELOPMENT, Boolean.TRUE); } raplaContainer = new RaplaMainContainer( env, context ); logger = raplaContainer.getContext().lookup(Logger.class); if ( env_development != null && env_development) { addDevelopmentWarFolders(); } serverVersion = raplaContainer.getContext().lookup(RaplaComponent.RAPLA_RESOURCES).getString("rapla.version"); } // add the war folders of the plugins to jetty resource handler so that the files inside the war // folders can be served from within jetty, even when they are not located in the same folder. // The method will search the class path for plugin classes and then add the look for a war folder entry in the file hierarchy // so a plugin allways needs a plugin class for this to work @SuppressWarnings("unchecked") private void addDevelopmentWarFolders() { Thread currentThread = Thread.currentThread(); ClassLoader classLoader = currentThread.getContextClassLoader(); ClassLoader parent = null; try { Collection<File> webappFolders = ServiceListCreator.findPluginWebappfolders(logger); if ( webappFolders.size() < 1) { return; } parent = classLoader.getParent(); if ( parent != null) { currentThread.setContextClassLoader( parent); } // first we need to access the necessary classes via reflection (are all loaded, because webapplication is already initialized) final Class WebAppClassLoaderC = Class.forName("org.eclipse.jetty.webapp.WebAppClassLoader",false, parent); final Class WebAppContextC = Class.forName("org.eclipse.jetty.webapp.WebAppContext",false, parent); final Class ResourceCollectionC = Class.forName("org.eclipse.jetty.util.resource.ResourceCollection",false, parent); final Class FileResourceC = Class.forName("org.eclipse.jetty.util.resource.FileResource",false, parent); final Object webappContext = WebAppClassLoaderC.getMethod("getContext").invoke(classLoader); if (webappContext == null) { return; } final Object baseResource = WebAppContextC.getMethod("getBaseResource").invoke( webappContext); if ( baseResource != null && ResourceCollectionC.isInstance( baseResource) ) { //Resource[] resources = ((ResourceCollection) baseResource).getResources(); final Object[] resources = (Object[])ResourceCollectionC.getMethod("getResources").invoke( baseResource); Set list = new HashSet( Arrays.asList( resources)); for (File folder:webappFolders) { Object fileResource = FileResourceC.getConstructor( URL.class).newInstance( folder.toURI().toURL()); if ( !list.contains( fileResource)) { list.add( fileResource); getLogger().info("Adding " + fileResource + " to webapp folder"); } } Object[] array = list.toArray( resources); //((ResourceCollection) baseResource).setResources( array); ResourceCollectionC.getMethod("setResources", resources.getClass()).invoke( baseResource, new Object[] {array}); //ResourceCollectionC.getMethod(", parameterTypes) } } catch (ClassNotFoundException ex) { getLogger().info("Development mode not in jetty so war finder will be disabled"); } catch (Exception ex) { getLogger().error(ex.getMessage(), ex); } finally { if ( parent != null) { currentThread.setContextClassLoader( classLoader); } } } private void exit() { MainServlet.this.reconnect = null; guiMutex.release(); if ( shutdownCommand != null) { shutdownCommand.run(); } } public void service( HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException { RaplaPageGenerator servletPage; Lock readLock = null; try { try { readLock = RaplaComponent.lock( restartLock.readLock(), 25); RaplaContext context = server.getContext(); for (ServletRequestPreprocessor preprocessor: processors) { final HttpServletRequest newRequest = preprocessor.handleRequest(context, getServletContext(), request, response); if (newRequest != null) request = newRequest; if (response.isCommitted()) return; } } catch (RaplaException e) { java.io.PrintWriter out = null; try { response.setStatus( 500 ); out = response.getWriter(); out.println(IOUtil.getStackTraceAsString( e)); } catch (Exception ex) { getLogger().error("Error writing exception back to client " + e.getMessage()); } finally { if ( out != null) { out.close(); } } return; } String page = request.getParameter("page"); String requestURI =request.getRequestURI(); if ( page == null) { String raplaPrefix = "rapla/"; String contextPath = request.getContextPath(); String toParse; if (requestURI.startsWith( contextPath)) { toParse = requestURI.substring( contextPath.length()); } else { toParse = requestURI; } int pageContextIndex = toParse.lastIndexOf(raplaPrefix); if ( pageContextIndex>= 0) { page = toParse.substring( pageContextIndex + raplaPrefix.length()); int firstSeparator = page.indexOf('/'); if ( firstSeparator>1) { page = page.substring(0,firstSeparator ); } } } //String servletPath = request.getServletPath(); if ( requestURI.indexOf(RAPLA_RPC_PATH) >= 0) { handleOldRPCCall( request, response ); return; } // if ( requestURI.indexOf(RAPLA_JSON_PATH)>= 0) { // handleJSONCall( request, response, requestURI ); // return; // } if ( page == null || page.trim().length() == 0) { page = "index"; } servletPage = server.getWebpage( page); if ( servletPage == null) { response.setStatus( 404 ); java.io.PrintWriter out = null; try { out = response.getWriter(); String message = "404: Page " + page + " not found in Rapla context"; out.print(message); getLogger().getChildLogger("server.html.404").warn( message); } finally { if ( out != null) { out.close(); } } return; } ServletContext servletContext = getServletContext(); servletPage.generatePage( servletContext, request, response); } finally { try { RaplaComponent.unlock( readLock ); } catch (IllegalMonitorStateException ex) { // Released by the restarter } try { ServletOutputStream outputStream = response.getOutputStream(); outputStream.close(); } catch (Exception ex) { } } } /** serverContainerHint is useful when you have multiple server configurations in one config file e.g. in a test environment*/ public static String serverContainerHint = null; private void stopServer() { if ( raplaContainer == null) { return; } try { raplaContainer.dispose(); } catch (Exception ex) { String message = "Error while stopping server "; getLogger().error(message + ex.getMessage()); } } /** * Disposes of container manager and container instance. */ public void destroy() { stopServer(); } public RaplaContext getContext() { return raplaContainer.getContext(); } public Container getContainer() { return raplaContainer; } public void doImport() throws RaplaException { ImportExportManager manager = raplaContainer.getContext().lookup(ImportExportManager.class); manager.doImport(); } public void doExport() throws RaplaException { ImportExportManager manager = raplaContainer.getContext().lookup(ImportExportManager.class); manager.doExport(); } public Logger getLogger() { if ( logger == null) { return new RaplaJDKLoggingAdapter().get(); } return logger; } // only for old rapla versions, will be removed in 2.0 private void handleOldRPCCall( HttpServletRequest request, HttpServletResponse response ) throws IOException { String clientVersion = request.getParameter("v"); if ( clientVersion != null ) { String message = getVersionErrorText(request, clientVersion); response.addHeader("X-Error-Classname", WrongRaplaVersionException.class.getName()); response.addHeader("X-Error-Stacktrace", message ); response.setStatus( 500); } else { //if ( !serverVersion.equals( clientVersion ) ) String message = getVersionErrorText(request, ""); response.addHeader("X-Error-Stacktrace", message ); RaplaException e1= new RaplaException( message ); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); ObjectOutputStream exout = new ObjectOutputStream( outStream); exout.writeObject( e1); exout.flush(); exout.close(); byte[] out = outStream.toByteArray(); ServletOutputStream outputStream = null; try { outputStream = response.getOutputStream(); outputStream.write( out ); } catch (Exception ex) { getLogger().error( " Error writing exception back to client " + ex.getMessage()); } finally { if (outputStream != null) { outputStream.close(); } } response.setStatus( 500); } } // only for old rapla versions, will be removed in 2.0 private String getVersionErrorText(HttpServletRequest request,String clientVersion) { String requestUrl = request.getRequestURL().toString(); int indexOf = requestUrl.indexOf( "rpc/"); if (indexOf>=0 ) { requestUrl = requestUrl.substring( 0, indexOf) ; } String message; try { I18nBundle i18n = getContext().lookup(RaplaComponent.RAPLA_RESOURCES); message = i18n.format("error.wrong_rapla_version", clientVersion, serverVersion, requestUrl); } catch (Exception e) { message = "Update client from " + clientVersion + " to " + serverVersion + " on " + requestUrl + ". Click on the webstart or applet to update."; } return message; } // private void handleRPCCall( HttpServletRequest request, HttpServletResponse response, String requestURI ) // { // boolean dispatcherExceptionThrown = false; // try // { // handleLogin(request, response, requestURI); // final Map<String,String[]> originalMap = request.getParameterMap(); // final Map<String,String> parameterMap = makeSinglesAndRemoveVersion(originalMap); // final ServerServiceContainer serverContainer = getServer(); // RemoteServiceDispatcher serviceDispater=serverContainer.getContext().lookup( RemoteServiceDispatcher.class); // byte[] out; // try // { // out =null; // //out = serviceDispater.dispatch(remoteSession, methodName, parameterMap); // } // catch (Exception ex) // { // dispatcherExceptionThrown = true; // throw ex; // } // //String test = new String( out); // response.setContentType( "text/html; charset=utf-8"); // try // { // response.getOutputStream().write( out); // response.flushBuffer(); // response.getOutputStream().close(); // } // catch (Exception ex) // { // getLogger().error( " Error writing exception back to client " + ex.getMessage()); // } // } // catch (Exception e) // { // if ( !dispatcherExceptionThrown) // { // getLogger().error(e.getMessage(), e); // } // try // { // String message = e.getMessage(); // String name = e.getClass().getName(); // if ( message == null ) // { // message = name; // } // response.addHeader("X-Error-Stacktrace", message ); // response.addHeader("X-Error-Classname", name); //// String param = RemoteMethodSerialization.serializeExceptionParam( e); //// if ( param != null) //// { //// response.addHeader("X-Error-Param", param); //// } // response.setStatus( 500); // } // catch (Exception ex) // { // getLogger().error( " Error writing exception back to client " + e.getMessage(), ex); // } // } // } // private boolean isClientVersionSupported(String clientVersion) { // // add/remove supported client versions here // return clientVersion.equals(serverVersion) || clientVersion.equals("@doc.version@") ; // } // // private Map<String,String> makeSinglesAndRemoveVersion( Map<String, String[]> parameterMap ) // { // TreeMap<String,String> singlesMap = new TreeMap<String,String>(); // for (Iterator<String> it = parameterMap.keySet().iterator();it.hasNext();) // { // String key = it.next(); // if ( key.toLowerCase().equals("v")) // { // continue; // } // String[] values = parameterMap.get( key); // if ( values != null && values.length > 0 ) // { // singlesMap.put( key,values[0]); // } // else // { // singlesMap.put( key,null); // } // } // // return singlesMap; // // } }
04900db4-rob
src/org/rapla/server/MainServlet.java
Java
gpl3
33,053
package org.rapla.server; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; public class HTTPMethodOverrideFilter implements Filter { Collection<String> VALID_METHODS = Arrays.asList(new String[] {"GET","POST","DELETE","PUT","PATCH"}); @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { MethodOverrideWrapper wrapper = new MethodOverrideWrapper( (HttpServletRequest) request); chain.doFilter(wrapper, response); HttpServletResponse hresponse = (HttpServletResponse) response; hresponse.addHeader("Vary", "X-HTTP-Method-Override"); } private class MethodOverrideWrapper extends HttpServletRequestWrapper { public MethodOverrideWrapper(HttpServletRequest request) { super(request); } @Override public String getMethod() { String method = super.getMethod(); String newMethod = getHeader("X-HTTP-Method-Override"); if ("POST".equals(method) && newMethod != null && VALID_METHODS.contains(newMethod)) { method = newMethod; } return method; } } }
04900db4-rob
src/org/rapla/server/HTTPMethodOverrideFilter.java
Java
gpl3
1,777
<body> <p>This package contains the classes for initializing a rapla-system. It provides to default entry-points for starting a rapla system. That are the <code>MainApplet</code> the <code> <code>MainWebstart</code> and the <code>MainServer</code> classes. For starting Rapla use the Loader classes in the bootstrap package. </body>
04900db4-rob
src/org/rapla/package.html
HTML
gpl3
335
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import java.text.Collator; import java.util.Comparator; import java.util.Locale; import org.rapla.components.util.Assert; public class NamedComparator<T extends Named> implements Comparator<T> { Locale locale; Collator collator; public NamedComparator(Locale locale) { this.locale = locale; Assert.notNull( locale ); collator = Collator.getInstance(locale); } public int compare(Named o1,Named o2) { if ( o1.equals(o2)) return 0; Named r1 = o1; Named r2 = o2; int result = collator.compare( r1.getName(locale) ,r2.getName(locale) ); if ( result !=0 ) return result; else return (o1.hashCode() < o2.hashCode()) ? -1 : 1; } }
04900db4-rob
src/org/rapla/entities/NamedComparator.java
Java
gpl3
1,828
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; /** Some entities (especially dynamic-types and attributes) can have multiple names to allow easier reuse of created schemas or support for multi-language-environments. @see MultiLanguageNamed */ public class MultiLanguageName implements java.io.Serializable { // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; Map<String,String> mapLocales = new TreeMap<String,String>(); transient private boolean readOnly; public MultiLanguageName(String language,String translation) { setName(language,translation); } public MultiLanguageName(String[][] data) { for (int i=0;i<data.length;i++) setName(data[i][0],data[i][1]); } public MultiLanguageName() { } public void setReadOnly() { this.readOnly = true; } public boolean isReadOnly() { return this.readOnly; } public String getName(String language) { if ( language == null) { language = "en"; } String result = mapLocales.get(language); if (result == null) { result = mapLocales.get("en"); } if (result == null) { Iterator<String> it = mapLocales.values().iterator(); if (it.hasNext()) result = it.next(); } if (result == null) { result = ""; } return result; } public void setName(String language,String translation) { checkWritable(); setNameWithoutReadCheck(language, translation); } private void checkWritable() { if ( isReadOnly() ) throw new ReadOnlyException("Can't modify this multilanguage name."); } public void setTo(MultiLanguageName newName) { checkWritable(); mapLocales = new TreeMap<String,String>(newName.mapLocales); } public Collection<String> getAvailableLanguages() { return mapLocales.keySet(); } public Object clone() { MultiLanguageName newName= new MultiLanguageName(); newName.mapLocales.putAll(mapLocales); return newName; } public String toString() { return getName("en"); } @Deprecated public void setNameWithoutReadCheck(String language, String translation) { if (translation != null && !translation.trim().equals("")) { mapLocales.put(language,translation.trim()); } else { mapLocales.remove(language); } } }
04900db4-rob
src/org/rapla/entities/MultiLanguageName.java
Java
gpl3
3,633
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.internal; import java.util.Collection; import java.util.Date; import java.util.Locale; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.framework.RaplaException; public class UserImpl extends SimpleEntity implements User, ModifiableTimestamp { private String username = ""; private String email = ""; private String name = ""; private boolean admin = false; private Date lastChanged; private Date createDate; // The resolved references transient private Category[] groups; final public RaplaType<User> getRaplaType() {return TYPE;} UserImpl() { this(null,null); } public UserImpl(Date createDate,Date lastChanged) { this.createDate = createDate; this.lastChanged = lastChanged; } public Date getLastChanged() { return lastChanged; } @Deprecated public Date getLastChangeTime() { return lastChanged; } public Date getCreateTime() { return createDate; } public void setLastChanged(Date date) { checkWritable(); lastChanged = date; } public boolean isAdmin() {return admin;} public String getName() { final Allocatable person = getPerson(); if ( person != null) { return person.getName( null ); } return name; } public String getEmail() { final Allocatable person = getPerson(); if ( person != null) { final Classification classification = person.getClassification(); final Attribute attribute = classification.getAttribute("email"); return attribute != null ? (String)classification.getValue(attribute) : null; } return email; } public String getUsername() { return username; } public String toString() { return getUsername(); } public void setName(String name) { checkWritable(); this.name = name; } public void setEmail(String email) { checkWritable(); this.email = email; } public void setUsername(String username) { checkWritable(); this.username = username; } public void setAdmin(boolean bAdmin) { checkWritable(); this.admin=bAdmin; } public String getName(Locale locale) { final Allocatable person = getPerson(); if ( person != null) { return person.getName(locale); } final String name = getName(); if ( name == null || name.length() == 0) { return getUsername(); } else { return name; } } public void addGroup(Category group) { checkWritable(); if ( isRefering("groups", group.getId())) { return; } groups = null; add("groups",group); } public boolean removeGroup(Category group) { checkWritable(); return removeId(group.getId()); } public Category[] getGroups() { updateGroupArray(); return groups; } public boolean belongsTo( Category group ) { for (Category uGroup:getGroups()) { if (group.equals( uGroup) || group.isAncestorOf( uGroup)) { return true; } } return false; } private void updateGroupArray() { if (groups != null) return; synchronized ( this ) { Collection<Category> groupList = getList("groups", Category.class); groups = groupList.toArray(Category.CATEGORY_ARRAY); } } public User clone() { UserImpl clone = new UserImpl(); super.deepClone(clone); clone.groups = null; clone.username = username; clone.name = name; clone.email = email; clone.admin = admin; clone.lastChanged = lastChanged; clone.createDate = createDate; return clone; } public int compareTo(User o) { int result = toString().compareTo( o.toString()); if (result != 0) { return result; } else { return super.compareTo( o); } } public void setPerson(Allocatable person) throws RaplaException { checkWritable(); if ( person == null) { putEntity("person", null); return; } final Classification classification = person.getClassification(); final Attribute attribute = classification.getAttribute("email"); final String email = attribute != null ? (String)classification.getValue(attribute) : null; if ( email == null || email.length() == 0) { throw new RaplaException("Email of " + person + " not set. Linking to user needs an email "); } else { this.email = email; putEntity("person", (Entity) person); setName(person.getClassification().getName(null)); } } public Allocatable getPerson() { final Allocatable person = getEntity("person", Allocatable.class); return person; } }
04900db4-rob
src/org/rapla/entities/internal/UserImpl.java
Java
gpl3
6,506
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.internal; import java.util.Date; import org.rapla.entities.Timestamp; import org.rapla.entities.User; public interface ModifiableTimestamp extends Timestamp { /** updates the last-changed timestamp */ void setLastChanged(Date date); void setLastChangedBy( User user); }
04900db4-rob
src/org/rapla/entities/internal/ModifiableTimestamp.java
Java
gpl3
1,249
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.internal; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.rapla.components.util.Assert; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.ParentEntity; import org.rapla.entities.storage.internal.SimpleEntity; final public class CategoryImpl extends SimpleEntity implements Category, ParentEntity, ModifiableTimestamp { private MultiLanguageName name = new MultiLanguageName(); private String key; Set<CategoryImpl> childs = new LinkedHashSet<CategoryImpl>(); private Date lastChanged; private Date createDate; private Map<String,String> annotations = new LinkedHashMap<String,String>(); private transient Category parent; CategoryImpl() { } public CategoryImpl(Date createDate, Date lastChanged) { this.createDate = createDate; this.lastChanged = lastChanged; } @Override public void setResolver(EntityResolver resolver) { super.setResolver(resolver); for (CategoryImpl child:childs) { child.setParent( this); } } @Override public void addEntity(Entity entity) { childs.add( (CategoryImpl) entity); } public Date getLastChanged() { return lastChanged; } @Deprecated public Date getLastChangeTime() { return lastChanged; } public Date getCreateTime() { return createDate; } public void setLastChanged(Date date) { checkWritable(); lastChanged = date; for ( CategoryImpl child:childs) { child.setLastChanged( date); } } public RaplaType<Category> getRaplaType() {return TYPE;} void setParent(CategoryImpl parent) { putEntity("parent", parent); this.parent = parent; } public void removeParent() { removeWithKey("parent"); this.parent = null; } public Category getParent() { if ( parent == null) { parent = getEntity("parent", Category.class); } return parent; } public Category[] getCategories() { return childs.toArray(Category.CATEGORY_ARRAY); } @SuppressWarnings("unchecked") public Collection<CategoryImpl> getSubEntities() { return childs; } public boolean isAncestorOf(Category category) { if (category == null) return false; if (category.getParent() == null) return false; if (category.getParent().equals(this)) return true; else return isAncestorOf(category.getParent()); } public Category getCategory(String key) { for (Entity ref: getSubEntities()) { Category cat = (Category) ref; if (cat.getKey().equals(key)) return cat; } return null; } public boolean hasCategory(Category category) { return childs.contains(category); } public void addCategory(Category category) { checkWritable(); Assert.isTrue(category.getParent() == null || category.getParent().equals(this) ,"Category is already attached to a parent"); CategoryImpl categoryImpl = (CategoryImpl)category; if ( resolver != null) { Assert.isTrue( !categoryImpl.isAncestorOf( this), "Can't add a parent category to one of its ancestors."); } addEntity( (Entity) category); categoryImpl.setParent(this); } public int getRootPathLength() { Category parent = getParent(); if ( parent == null) { return 0; } else { int parentDepth = parent.getRootPathLength(); return parentDepth + 1; } } public int getDepth() { int max = 0; Category[] categories = getCategories(); for (int i=0;i<categories.length;i++) { int depth = categories[i].getDepth(); if (depth > max) max = depth; } return max + 1; } public void removeCategory(Category category) { checkWritable(); if ( findCategory( category ) == null) return; childs.remove(category); //if (category.getParent().equals(this)) ((CategoryImpl)category).setParent(null); } public Category findCategory(Category copy) { return (Category) super.findEntity((Entity)copy); } public MultiLanguageName getName() { return name; } public void setReadOnly() { super.setReadOnly( ); name.setReadOnly( ); } public String getName(Locale locale) { if ( locale == null) { locale = Locale.getDefault(); } return name.getName(locale.getLanguage()); } public String getKey() { return key; } public void setKey(String key) { checkWritable(); this.key = key; } public String getPath(Category rootCategory,Locale locale) { StringBuffer buf = new StringBuffer(); if (rootCategory != null && this.equals(rootCategory)) return ""; if (this.getParent() != null) { String path = this.getParent().getPath(rootCategory,locale); buf.append(path); if (path.length()>0) buf.append('/'); } buf.append(this.getName(locale)); return buf.toString(); } public List<String> getKeyPath(Category rootCategory) { LinkedList<String> result = new LinkedList<String>(); if (rootCategory != null && this.equals(rootCategory)) return result; Category cat = this; while (cat.getParent() != null) { Category parent = cat.getParent(); result.addFirst( parent.getKey()); cat = parent; if ( parent == this) { throw new IllegalStateException("Parent added as own child"); } } result.add( getKey()); return result; } public String toString() { MultiLanguageName name = getName(); if (name != null) { return name.toString() + " ID='" + getId() + "'"; } else { return getKey() + " " + getId(); } } public String getPathForCategory(Category searchCategory) throws EntityNotFoundException { List<String> keyPath = getPathForCategory(searchCategory, true); return getKeyPathString(keyPath); } public static String getKeyPathString(List<String> keyPath) { StringBuffer buf = new StringBuffer(); for (String category:keyPath) { buf.append('/'); buf.append(category); } if ( buf.length() > 0) { buf.deleteCharAt(0); } String pathForCategory = buf.toString(); return pathForCategory ; } public List<String> getPathForCategory(Category searchCategory, boolean fail) throws EntityNotFoundException { LinkedList<String> result = new LinkedList<String>(); Category category = searchCategory; Category parent = category.getParent(); if (category == this) return result; if (parent == null) throw new EntityNotFoundException("Category has no parents!"); while (true) { String entry ="category[key='" + category.getKey() + "']"; result.addFirst(entry); parent = category.getParent(); category = parent; if (parent == null) { if ( fail) { throw new EntityNotFoundException("Category not found!" + searchCategory); } return null; } if (parent.equals(this)) break; } return result; } public Category getCategoryFromPath(String path) throws EntityNotFoundException { int start = 0; int end = 0; int pos = 0; Category category = this; while (category != null) { start = path.indexOf("'",pos) + 1; if (start==0) break; end = path.indexOf("'",start); if (end < 0) throw new EntityNotFoundException("Invalid xpath expression: " + path); String key = path.substring(start,end); category = category.getCategory(key); pos = end + 1; } if (category == null) throw new EntityNotFoundException("could not resolve category xpath expression: " + path); return category; } public Category findCategory(Object copy) { return (Category) super.findEntity((Entity)copy); } public String getAnnotation(String key) { return annotations.get(key); } public String getAnnotation(String key, String defaultValue) { String annotation = getAnnotation( key ); return annotation != null ? annotation : defaultValue; } public void setAnnotation(String key,String annotation) throws IllegalAnnotationException { checkWritable(); if (annotation == null) { annotations.remove(key); return; } annotations.put(key,annotation); } public String[] getAnnotationKeys() { return annotations.keySet().toArray(RaplaObject.EMPTY_STRING_ARRAY); } @SuppressWarnings("unchecked") public Category clone() { CategoryImpl clone = new CategoryImpl(); super.deepClone(clone); clone.name = (MultiLanguageName) name.clone(); clone.parent = parent; clone.annotations = (HashMap<String,String>) ((HashMap<String,String>)annotations).clone(); clone.key = key; clone.lastChanged = lastChanged; clone.createDate = createDate; for (Entity ref:clone.getSubEntities()) { ((CategoryImpl)ref).setParent(clone); } return clone; } public int compareTo(Object o) { if ( o == this ) { return 0; } if ( equals( o )) { return 0; } Category c1= this; Category c2= (Category) o; if ( c1.isAncestorOf( c2)) { return -1; } if ( c2.isAncestorOf( c1)) { return 1; } while ( c1.getRootPathLength() > c2.getRootPathLength()) { c1 = c1.getParent(); } while ( c2.getRootPathLength() > c2.getRootPathLength()) { c2 = c2.getParent(); } while ( c1.getParent() != null && c2.getParent() != null && (!c1.getParent().equals( c2.getParent()))) { c1 = c1.getParent(); c2 = c2.getParent(); } //now the two categories have the same parent if ( c1.getParent() == null || c2.getParent() == null) { return super.compareTo( o); } Category parent = c1.getParent(); // We look who is first in the list Category[] categories = parent.getCategories(); for ( Category category: categories) { if ( category.equals( c1)) { return -1; } if ( category.equals( c2)) { return 1; } } return super.compareTo( o); } public void replace(Category category) { String id = category.getId(); CategoryImpl existingEntity = (CategoryImpl) findEntityForId(id); if ( existingEntity != null) { LinkedHashSet<CategoryImpl> newChilds = new LinkedHashSet<CategoryImpl>(); for ( CategoryImpl child: childs) { newChilds.add( ( child != existingEntity) ? child: (CategoryImpl)category); } childs = newChilds; } } }
04900db4-rob
src/org/rapla/entities/internal/CategoryImpl.java
Java
gpl3
13,186
<body> Contains the default implementations of the persistent entity-objects in rapla. @see <A HREF="http://rapla.sourceforge.net/">rapla.sourceforge.net</A> </body>
04900db4-rob
src/org/rapla/entities/internal/package.html
HTML
gpl3
168
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; /**This interface is a marker to distinct the different rapla classes * like Reservation, Allocatable and Category. * It is something like the java instanceof keyword. But it must be unique for each * class. This type-information is for examle used for mapping the correct storage-, * editing- mechanism to the class. */ public interface RaplaObject<T> extends Cloneable { public static final String[] EMPTY_STRING_ARRAY = new String[0]; RaplaType<T> getRaplaType(); T clone(); }
04900db4-rob
src/org/rapla/entities/RaplaObject.java
Java
gpl3
1,467
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas, Frithjof Kurtz | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.configuration.internal; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.rapla.components.util.iterator.NestedIterator; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.ClassificationFilterImpl; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityResolver; public abstract class AbstractClassifiableFilter implements EntityReferencer, DynamicTypeDependant, Serializable { private static final long serialVersionUID = 1L; List<ClassificationFilterImpl> classificationFilters; protected transient EntityResolver resolver; AbstractClassifiableFilter() { classificationFilters = new ArrayList<ClassificationFilterImpl>(); } public void setResolver( EntityResolver resolver) { this.resolver = resolver; for (ClassificationFilterImpl filter:classificationFilters) { filter.setResolver( resolver ); } } @Override public Iterable<ReferenceInfo> getReferenceInfo() { Iterable<ClassificationFilterImpl> classificatonFilterIterator = classificationFilters; return new NestedIterator<ReferenceInfo,ClassificationFilterImpl>(classificatonFilterIterator) { public Iterable<ReferenceInfo> getNestedIterator(ClassificationFilterImpl obj) { return obj.getReferenceInfo(); } }; } public void setClassificationFilter(List<ClassificationFilterImpl> classificationFilters) { if ( classificationFilters != null) this.classificationFilters = classificationFilters; else this.classificationFilters = Collections.emptyList(); } public boolean needsChange(DynamicType type) { for (ClassificationFilterImpl filter:classificationFilters) { if (filter.needsChange(type)) return true; } return false; } public void commitChange(DynamicType type) { for (ClassificationFilterImpl filter:classificationFilters) { if (filter.getType().equals(type)) filter.commitChange(type); } } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { boolean removed = false; List<ClassificationFilterImpl> newFilter = new ArrayList<ClassificationFilterImpl>( classificationFilters); for (Iterator<ClassificationFilterImpl> f=newFilter.iterator();f.hasNext();) { ClassificationFilterImpl filter = f.next(); if (filter.getType().equals(type)) { removed = true; f.remove(); } } if ( removed) { classificationFilters = newFilter; } } public ClassificationFilter[] getFilter() { return classificationFilters.toArray( ClassificationFilter.CLASSIFICATIONFILTER_ARRAY); } public String toString() { return classificationFilters.toString(); } }
04900db4-rob
src/org/rapla/entities/configuration/internal/AbstractClassifiableFilter.java
Java
gpl3
4,312
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.configuration.internal; import java.util.Date; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Set; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.entities.configuration.RaplaMap; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.internal.ModifiableTimestamp; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.facade.RaplaComponent; import org.rapla.framework.Configuration; import org.rapla.framework.TypedComponentRole; import org.rapla.storage.PreferencePatch; public class PreferencesImpl extends SimpleEntity implements Preferences ,ModifiableTimestamp , DynamicTypeDependant { private Date lastChanged; private Date createDate; RaplaMapImpl map = new RaplaMapImpl(); Set<String> removedKeys = new LinkedHashSet<String>(); final public RaplaType<Preferences> getRaplaType() {return TYPE;} private transient PreferencePatch patch = new PreferencePatch(); PreferencesImpl() { this(null,null); } public PreferencesImpl(Date createDate,Date lastChanged ) { super(); this.createDate = createDate; this.lastChanged = lastChanged; } public Date getLastChanged() { return lastChanged; } @Deprecated public Date getLastChangeTime() { return lastChanged; } public Date getCreateTime() { return createDate; } public void setLastChanged(Date date) { checkWritable(); lastChanged = date; } @Override public void putEntry(TypedComponentRole<CalendarModelConfiguration> role, CalendarModelConfiguration entry) { putEntryPrivate(role.getId(), entry); } @Override public void putEntry(TypedComponentRole<RaplaConfiguration> role, RaplaConfiguration entry) { putEntryPrivate(role.getId(), entry); } @Override public <T> void putEntry(TypedComponentRole<RaplaMap<T>> role, RaplaMap<T> entry) { putEntryPrivate(role.getId(), entry); } public void putEntryPrivate(String role,RaplaObject entry) { updateMap(role, entry); } private void updateMap(String role, Object entry) { checkWritable(); map.putPrivate(role, entry); patch.putPrivate( role, entry); if ( entry == null) { patch.addRemove( role); } } public void putEntryPrivate(String role,String entry) { updateMap(role, entry); } public void setResolver( EntityResolver resolver) { super.setResolver(resolver); map.setResolver(resolver); patch.setResolver(resolver); } public <T> T getEntry(String role) { return getEntry(role, null); } public <T> T getEntry(String role, T defaultValue) { try { @SuppressWarnings("unchecked") T result = (T) map.get( role ); if ( result == null) { return defaultValue; } return result; } catch ( ClassCastException ex) { throw new ClassCastException( "Stored entry is not of requested Type: " + ex.getMessage()); } } private String getEntryAsString(String role) { return (String) map.get( role ); } public String getEntryAsString(TypedComponentRole<String> role, String defaultValue) { String value = getEntryAsString( role.getId()); if ( value != null) return value; return defaultValue; } public Iterable<String> getPreferenceEntries() { return map.keySet(); } public void removeEntry(String role) { updateMap(role, null); } @Override public Iterable<ReferenceInfo> getReferenceInfo() { Iterable<ReferenceInfo> parentReferences = super.getReferenceInfo(); Iterable<ReferenceInfo> mapReferences = map.getReferenceInfo(); IteratorChain<ReferenceInfo> iteratorChain = new IteratorChain<ReferenceInfo>(parentReferences,mapReferences); return iteratorChain; } public boolean isEmpty() { return map.isEmpty(); } public PreferencesImpl clone() { PreferencesImpl clone = new PreferencesImpl(); super.deepClone(clone); clone.map = map.deepClone(); clone.createDate = createDate; clone.lastChanged = lastChanged; // we clear the patch on a clone clone.patch = new PreferencePatch(); clone.patch.setUserId( getOwnerId()); return clone; } @Override public void setOwner(User owner) { super.setOwner(owner); patch.setUserId( getOwnerId()); } public PreferencePatch getPatch() { return patch; } /** * @see org.rapla.entities.Named#getName(java.util.Locale) */ public String getName(Locale locale) { StringBuffer buf = new StringBuffer(); if ( getOwner() != null) { buf.append( "Preferences of "); buf.append( getOwner().getName( locale)); } else { buf.append( "Rapla Preferences!"); } return buf.toString(); } /* (non-Javadoc) * @see org.rapla.entities.configuration.Preferences#getEntryAsBoolean(java.lang.String, boolean) */ public Boolean getEntryAsBoolean(TypedComponentRole<Boolean> role, boolean defaultValue) { String entry = getEntryAsString( role.getId()); if ( entry == null) return defaultValue; return Boolean.valueOf(entry).booleanValue(); } /* (non-Javadoc) * @see org.rapla.entities.configuration.Preferences#getEntryAsInteger(java.lang.String, int) */ public Integer getEntryAsInteger(TypedComponentRole<Integer> role, int defaultValue) { String entry = getEntryAsString( role.getId()); if ( entry == null) return defaultValue; return Integer.parseInt(entry); } public boolean needsChange(DynamicType type) { return map.needsChange(type); } public void commitChange(DynamicType type) { map.commitChange(type); patch.commitChange(type); } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { map.commitRemove(type); patch.commitRemove(type); } public String toString() { return super.toString() + " " + map.toString(); } public <T extends RaplaObject> void putEntry(TypedComponentRole<T> role,T entry) { putEntryPrivate( role.getId(), entry); } public void applyPatch(PreferencePatch patch) { checkWritable(); Set<String> removedEntries = patch.getRemovedEntries(); for (String key:patch.keySet()) { Object value = patch.get( key); updateMap(key, value); } for ( String remove:removedEntries) { updateMap(remove, null); } } public <T extends RaplaObject> T getEntry(TypedComponentRole<T> role) { return getEntry( role, null); } public <T extends RaplaObject> T getEntry(TypedComponentRole<T> role, T defaultValue) { return getEntry( role.getId(), defaultValue); } public boolean hasEntry(TypedComponentRole<?> role) { return map.get( role.getId() ) != null; } public void putEntry(TypedComponentRole<Boolean> role, Boolean entry) { putEntry_(role, entry != null ? entry.toString(): null); } public void putEntry(TypedComponentRole<Integer> role, Integer entry) { putEntry_(role, entry != null ? entry.toString() : null); } public void putEntry(TypedComponentRole<String> role, String entry) { putEntry_(role, entry); } protected void putEntry_(TypedComponentRole<?> role, Object entry) { checkWritable(); String key = role.getId(); updateMap(key, entry); // if ( entry == null) // { // map.remove( id); // } // else // { // map.put( id ,entry.toString()); // } } public static String getPreferenceIdFromUser(String userId) { String preferenceId = (userId != null ) ? Preferences.ID_PREFIX + userId : SYSTEM_PREFERENCES_ID; return preferenceId.intern(); } @Deprecated public Configuration getOldPluginConfig(String pluginClassName) { RaplaConfiguration raplaConfig = getEntry(RaplaComponent.PLUGIN_CONFIG); Configuration pluginConfig = null; if ( raplaConfig != null) { pluginConfig = raplaConfig.find("class", pluginClassName); } if ( pluginConfig == null) { pluginConfig = new RaplaConfiguration("plugin"); } return pluginConfig; } // public static boolean isServerEntry(String configRole) { // if ( configRole == null) // { // return false; // } // if ( configRole.startsWith("server.") || configRole.contains(".server.")) // { // return true; // } // return false; // } }
04900db4-rob
src/org/rapla/entities/configuration/internal/PreferencesImpl.java
Java
gpl3
10,334
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.configuration.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.internal.ClassificationFilterImpl; import org.rapla.entities.storage.EntityResolver; import org.rapla.framework.RaplaException; public class CalendarModelConfigurationImpl extends AbstractClassifiableFilter implements CalendarModelConfiguration { // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; List<String> selected; List<String> typeList; String title; Date startDate; Date endDate; Date selectedDate; String view; Map<String,String> optionMap; boolean defaultEventTypes; boolean defaultResourceTypes; boolean resourceRootSelected; public CalendarModelConfigurationImpl( Collection<String> selected,Collection<RaplaType> idTypeList,boolean resourceRootSelected, ClassificationFilter[] filter, boolean defaultResourceTypes, boolean defaultEventTypes,String title, Date startDate, Date endDate, Date selectedDate,String view,Map<String,String> extensionMap) { if (selected != null) { this.selected = Collections.unmodifiableList(new ArrayList<String>(selected)); typeList = new ArrayList<String>(); for ( RaplaType type:idTypeList) { typeList.add(type.getLocalName()); } } else { this.selected = Collections.emptyList(); typeList = Collections.emptyList(); } this.view = view; this.resourceRootSelected = resourceRootSelected; this.defaultEventTypes = defaultEventTypes; this.defaultResourceTypes = defaultResourceTypes; this.title = title; this.startDate = startDate; this.endDate = endDate; this.selectedDate = selectedDate; List<ClassificationFilterImpl> filterList = new ArrayList<ClassificationFilterImpl>(); if ( filter != null) { for ( ClassificationFilter f:filter) { filterList.add((ClassificationFilterImpl)f); } } super.setClassificationFilter( filterList ); Map<String,String> map= new LinkedHashMap<String,String>(); if ( extensionMap != null) { map.putAll(extensionMap); } this.optionMap = Collections.unmodifiableMap( map); } CalendarModelConfigurationImpl() { } @Override public boolean isResourceRootSelected() { return resourceRootSelected; } public void setResolver( EntityResolver resolver) { super.setResolver( resolver ); } public RaplaType<CalendarModelConfiguration> getRaplaType() { return TYPE; } public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } public Date getSelectedDate() { return selectedDate; } public String getTitle() { return title; } public String getView() { return view; } public Collection<Entity> getSelected() { ArrayList<Entity> result = new ArrayList<Entity>(); for ( String id: selected) { Entity entity = resolver.tryResolve(id); if ( entity != null) { result.add( entity); } } return result; } @Override public Iterable<ReferenceInfo> getReferenceInfo() { Iterable<ReferenceInfo> references = super.getReferenceInfo(); List<ReferenceInfo> selectedInfo = new ArrayList<ReferenceInfo>(); int size = selected.size(); for ( int i = 0;i<size;i++) { String id = selected.get(0); String localname = typeList.get(0); Class<? extends Entity> type = null; RaplaType raplaType; try { raplaType = RaplaType.find(localname); Class typeClass = raplaType.getTypeClass(); if ( Entity.class.isAssignableFrom(typeClass )) { @SuppressWarnings("unchecked") Class<? extends Entity> casted = (Class<? extends Entity>)typeClass; type = casted; } } catch (RaplaException e) { } ReferenceInfo referenceInfo = new ReferenceInfo(id, type); selectedInfo.add( referenceInfo); } return new IteratorChain<ReferenceInfo>(references, selectedInfo); } public Map<String,String> getOptionMap() { return optionMap; } public boolean isDefaultEventTypes() { return defaultEventTypes; } public boolean isDefaultResourceTypes() { return defaultResourceTypes; } @SuppressWarnings("unchecked") static private void copy(CalendarModelConfigurationImpl source,CalendarModelConfigurationImpl dest) { dest.view = source.view; dest.defaultEventTypes = source.defaultEventTypes; dest.defaultResourceTypes = source.defaultResourceTypes; dest.title = source.title; dest.startDate = source.startDate; dest.endDate = source.endDate; dest.selectedDate = source.selectedDate; dest.resourceRootSelected = source.resourceRootSelected; dest.setResolver( source.resolver); List<ClassificationFilterImpl> newFilter = new ArrayList<ClassificationFilterImpl>(); for ( ClassificationFilterImpl f: source.classificationFilters) { ClassificationFilterImpl clone = f.clone(); newFilter.add( clone); } dest.setClassificationFilter(newFilter ); dest.selected = (List<String>)((ArrayList<String>)source.selected).clone(); LinkedHashMap<String, String> optionMap = new LinkedHashMap<String,String>(); optionMap.putAll(source.optionMap); dest.optionMap = Collections.unmodifiableMap(optionMap); } public void copy(CalendarModelConfiguration obj) { copy((CalendarModelConfigurationImpl)obj, this); } public CalendarModelConfiguration deepClone() { CalendarModelConfigurationImpl clone = new CalendarModelConfigurationImpl(); copy(this,clone); return clone; } public CalendarModelConfiguration clone() { return deepClone(); } public List<String> getSelectedIds() { return selected; } public String toString() { return super.toString() + ",selected=" + selected; } @Override public CalendarModelConfiguration cloneWithNewOptions(Map<String, String> newMap) { CalendarModelConfigurationImpl clone = (CalendarModelConfigurationImpl) deepClone(); clone.optionMap = Collections.unmodifiableMap( newMap); return clone; } }
04900db4-rob
src/org/rapla/entities/configuration/internal/CalendarModelConfigurationImpl.java
Java
gpl3
8,032
/*--------------------------------------------------------------------------* | C o//pyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.configuration.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.rapla.components.util.iterator.FilterIterator; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.components.util.iterator.NestedIterator; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.ReadOnlyException; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.entities.configuration.RaplaMap; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.internal.ReferenceHandler; /** Maps can only support one type value at a time. Especially a mixture out of references and other values is not supported*/ public class RaplaMapImpl implements EntityReferencer, DynamicTypeDependant, RaplaObject, RaplaMap { //this map stores all objects in the map private Map<String,String> constants; private Map<String,RaplaConfiguration> configurations; private Map<String,RaplaMapImpl> maps; private Map<String,CalendarModelConfigurationImpl> calendars; protected LinkReferenceHandler links; transient protected Map<String,Object> map; transient EntityResolver resolver; static private RaplaType[] SUPPORTED_TYPES = new RaplaType[] { Allocatable.TYPE, Category.TYPE, DynamicType.TYPE}; // this map only stores the references // this map only stores the child objects (not the references) public RaplaMapImpl() { } public <T> RaplaMapImpl( Collection<T> list) { this( makeMap(list) ); } public RaplaType getRaplaType() { return RaplaMap.TYPE; } private static <T> Map<String,T> makeMap(Collection<T> list) { Map<String,T> map = new TreeMap<String,T>(); int key = 0; for ( Iterator<T> it = list.iterator();it.hasNext();) { T next = it.next(); if ( next == null) { System.err.println("Adding null value in list" ); } map.put( new String( String.valueOf(key++)), next); } return map; } public RaplaMapImpl( Map<String,?> map) { for ( Iterator<String> it = map.keySet().iterator();it.hasNext();) { String key = it.next(); Object o = map.get(key ); putPrivate(key, o); } } /** This method is only used in storage operations, please dont use it from outside, as it skips type protection and resolving*/ public void putPrivate(String key, Object value) { cachedEntries = null; if ( value == null) { if (links != null) { links.removeWithKey(key); } if ( maps != null) { maps.remove( key); } if ( map != null) { map.remove( key); } if ( configurations != null) { configurations.remove(key); } if ( maps != null) { maps.remove(key); } if ( calendars != null) { calendars.remove(key); } if ( constants != null) { constants.remove(key); } return; } // if ( ! (value instanceof RaplaObject ) && !(value instanceof String) ) // { // } if ( value instanceof Entity) { Entity entity = (Entity) value; String id = entity.getId(); RaplaType raplaType = entity.getRaplaType(); if ( !isTypeSupportedAsLink( raplaType)) { throw new IllegalArgumentException("RaplaType " + raplaType + " cannot be stored as link in map"); } putIdPrivate(key, id, raplaType); } else if ( value instanceof RaplaConfiguration) { if ( configurations == null) { configurations = new LinkedHashMap<String,RaplaConfiguration>(); } configurations.put( key, (RaplaConfiguration) value); getMap().put(key, value); } else if ( value instanceof RaplaMap) { if ( maps == null) { maps = new LinkedHashMap<String,RaplaMapImpl>(); } maps.put( key, (RaplaMapImpl) value); getMap().put(key, value); } else if ( value instanceof CalendarModelConfiguration) { if ( calendars == null) { calendars = new LinkedHashMap<String,CalendarModelConfigurationImpl>(); } calendars.put( key, (CalendarModelConfigurationImpl) value); getMap().put(key, value); } else if ( value instanceof String) { if ( constants == null) { constants = new LinkedHashMap<String,String>(); } constants.put( key , (String) value); getMap().put(key, value); } else { throw new IllegalArgumentException("Map type not supported only category, dynamictype, allocatable, raplamap, raplaconfiguration or String."); } } private Map<String, Object> getMap() { if (links != null) { Map<String, ?> linkMap = links.getLinkMap(); @SuppressWarnings("unchecked") Map<String,Object> casted = (Map<String,Object>)linkMap; return casted; } if ( maps == null && configurations == null && constants == null && calendars == null) { return Collections.emptyMap(); } if ( map == null) { map = new LinkedHashMap<String,Object>(); fillMap(maps); fillMap(configurations); fillMap(constants); fillMap(calendars); } return map; } private void fillMap(Map<String, ?> map) { if ( map == null) { return; } this.map.putAll( map); } public void putIdPrivate(String key, String id, RaplaType raplaType) { cachedEntries = null; if ( links == null) { links = new LinkReferenceHandler(); links.setLinkType( raplaType.getLocalName()); if ( resolver != null) { links.setResolver( resolver); } } links.putId( key,id); map = null; } @Override public Iterable<ReferenceInfo> getReferenceInfo() { NestedIterator<ReferenceInfo,EntityReferencer> refIt = new NestedIterator<ReferenceInfo,EntityReferencer>( getEntityReferencers()) { public Iterable<ReferenceInfo> getNestedIterator(EntityReferencer obj) { Iterable<ReferenceInfo> referencedIds = obj.getReferenceInfo(); return referencedIds; } }; if ( links == null) { return refIt; } Iterable<ReferenceInfo> referencedLinks = links.getReferenceInfo(); return new IteratorChain<ReferenceInfo>( refIt, referencedLinks); } private Iterable<EntityReferencer> getEntityReferencers() { return new FilterIterator<EntityReferencer>( getMap().values()) { protected boolean isInIterator(Object obj) { return obj instanceof EntityReferencer; } }; } /* public Iterator getReferences() { return getReferenceHandler().getReferences(); } public boolean isRefering(Entity entity) { return getReferenceHandler().isRefering( entity); }*/ public void setResolver( EntityResolver resolver) { this.resolver = resolver; if ( links != null) { links.setResolver( resolver ); } setResolver( calendars); setResolver( maps ); map = null; } private void setResolver(Map<String,? extends EntityReferencer> map) { if ( map == null) { return; } for (EntityReferencer ref:map.values()) { ref.setResolver( resolver); } } public Object get(Object key) { if (links != null) { return links.getEntity((String)key); } return getMap().get(key); } /** * @see java.util.Map#clear() */ public void clear() { throw createReadOnlyException(); } protected ReadOnlyException createReadOnlyException() { return new ReadOnlyException("RaplaMap is readonly you must create a new Object"); } /** * @see java.util.Map#size() */ public int size() { return getMap().size(); } /** * @see java.util.Map#isEmpty() */ public boolean isEmpty() { return getMap().isEmpty(); } /** * @see java.util.Map#containsKey(java.lang.Object) */ public boolean containsKey(Object key) { return getMap().containsKey( key); } /** * @see java.util.Map#containsValue(java.lang.Object) */ public boolean containsValue(Object key) { return getMap().containsValue( key); } /** * @see java.util.Map#keySet() */ public Set<String> keySet() { return getMap().keySet(); } public boolean needsChange(DynamicType type) { for (Iterator it = getMap().values().iterator();it.hasNext();) { Object obj = it.next(); if ( obj instanceof DynamicTypeDependant) { if (((DynamicTypeDependant) obj).needsChange( type )) return true; } } return false; } public void commitChange(DynamicType type) { for (Object obj:getMap().values()) { if ( obj instanceof DynamicTypeDependant) { ((DynamicTypeDependant) obj).commitChange( type ); } } } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { for (Object obj:getMap().values()) { if ( obj instanceof DynamicTypeDependant) { ((DynamicTypeDependant) obj).commitRemove( type ); } } } /** Clones the entity and all subentities*/ public RaplaMapImpl deepClone() { RaplaMapImpl clone = new RaplaMapImpl(getMap()); clone.setResolver( resolver ); return clone; } // public Collection<RaplaObject> getLinkValues() // { // ArrayList<RaplaObject> result = new ArrayList<RaplaObject>(); // EntityResolver resolver = getReferenceHandler().getResolver(); // for (String id: getReferencedIds()) // { // result.add( resolver.tryResolve( id)); // } // return result; // // } /** Clones the entity while preserving the references to the subentities*/ public Object clone() { return deepClone(); } /** * @see java.util.Map#put(java.lang.Object, java.lang.Object) */ public Object put(Object key, Object value) { throw createReadOnlyException(); } public Object remove(Object arg0) { throw createReadOnlyException(); } /** * @see java.util.Map#putAll(java.util.Map) */ public void putAll(Map m) { throw createReadOnlyException(); } /** * @see java.util.Map#values() */ public Collection values() { if ( links == null) { return getMap().values(); } else { List<Entity> result = new ArrayList<Entity>(); Iterable<String> values = links.getReferencedIds(); for (String id: values) { Entity resolved = links.getResolver().tryResolve( id); result.add( resolved); } return result; } } public static final class LinkReferenceHandler extends ReferenceHandler { protected String linkType; transient private Class<? extends Entity> linkClass; protected Class<? extends Entity> getInfoClass(String key) { return getLinkClass(); } public Iterable<String> getReferencedIds() { Set<String> result = new HashSet<String>(); if (links != null) { for (List<String> entries:links.values()) { for ( String id: entries) { result.add(id); } } } return result; } public Entity getEntity(String key) { Class<? extends Entity> linkClass = getLinkClass(); return getEntity(key, linkClass); } private Class<? extends Entity> getLinkClass() { if ( linkClass != null) { return linkClass; } if ( linkType != null ) { for ( RaplaType type: SUPPORTED_TYPES ) { if (linkType.equals( type.getLocalName())) { @SuppressWarnings("unchecked") Class<? extends Entity> casted = type.getTypeClass(); this.linkClass = casted; return linkClass; } } } return null; } public void setLinkType(String type) { this.linkType = type; linkClass = null; } } class Entry implements Map.Entry<String, Object> { String key; String id; Entry(String key,String id) { this.key = key; this.id = id; if ( id == null) { throw new IllegalArgumentException("Empty id added"); } } public String getKey() { return key; } public Object getValue() { if ( id == null) { return null; } Entity resolve = links.getResolver().tryResolve( id ); return resolve; } public Object setValue(Object value) { throw new UnsupportedOperationException(); } public int hashCode() { return key.hashCode(); } @Override public boolean equals(Object obj) { return key.equals( ((Entry) obj).key); } public String toString() { Entity value = links.getResolver().tryResolve( id ); return key + "=" + ((value != null) ? value : "unresolvable_" + id); } } transient Set<Map.Entry<String, Object>> cachedEntries; public Set<Map.Entry<String, Object>> entrySet() { if ( links != null) { if ( cachedEntries == null) { cachedEntries = new HashSet<Map.Entry<String, Object>>(); for (String key:links.getReferenceKeys()) { String id = links.getId( key); if ( id == null) { System.err.println("Empty id " + id); } cachedEntries.add(new Entry( key, id)); } } return cachedEntries; } else { if ( cachedEntries == null) { cachedEntries = new HashSet<Map.Entry<String, Object>>(); for (Map.Entry<String,Object> entry:getMap().entrySet()) { if ( entry.getValue() == null) { System.err.println("Empty value for " + entry.getKey()); } cachedEntries.add((Map.Entry<String, Object>) entry); } } return cachedEntries; } } public String toString() { return entrySet().toString(); } public boolean isTypeSupportedAsLink(RaplaType raplaType) { for ( RaplaType type: SUPPORTED_TYPES ) { if ( type == raplaType) { return true; } } return false; } }
04900db4-rob
src/org/rapla/entities/configuration/internal/RaplaMapImpl.java
Java
gpl3
16,732
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.configuration; import java.io.Serializable; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; /** * This class adds just the get Type method to the DefaultConfiguration so that the config can be stored in a preference object * @author ckohlhaas * @version 1.00.00 * @since 2.03.00 */ public class RaplaConfiguration extends DefaultConfiguration implements RaplaObject, Serializable{ // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; public static final RaplaType<RaplaConfiguration> TYPE = new RaplaType<RaplaConfiguration>(RaplaConfiguration.class, "config"); public RaplaConfiguration() { super(); } /** Creates a RaplaConfinguration with one element of the specified name * @param name the element name * @param content The content of the element. Can be null. */ public RaplaConfiguration( String name, String content) { super(name, content); } public RaplaConfiguration(String localName) { super(localName); } public RaplaConfiguration(Configuration configuration) { super( configuration); } public RaplaType getRaplaType() { return TYPE; } public RaplaConfiguration replace( Configuration oldChild, Configuration newChild) { return (RaplaConfiguration) super.replace( oldChild, newChild); } @Override protected RaplaConfiguration newConfiguration(String localName) { return new RaplaConfiguration( localName); } public RaplaConfiguration clone() { return new RaplaConfiguration( this); } }
04900db4-rob
src/org/rapla/entities/configuration/RaplaConfiguration.java
Java
gpl3
2,703
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.configuration; import org.rapla.entities.Entity; import org.rapla.entities.Named; import org.rapla.entities.Ownable; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.Timestamp; import org.rapla.framework.TypedComponentRole; /** Preferences store user-specific Information. You can store arbitrary configuration objects under unique role names. Each role can contain 1-n configuration entries. @see org.rapla.entities.User */ public interface Preferences extends Entity<Preferences>,Ownable,Timestamp, Named { final RaplaType<Preferences> TYPE = new RaplaType<Preferences>(Preferences.class, "preferences"); final String ID_PREFIX = TYPE.getLocalName() + "_"; final String SYSTEM_PREFERENCES_ID = ID_PREFIX + "0"; /** returns if there are any preference-entries */ boolean isEmpty(); boolean hasEntry(TypedComponentRole<?> role); <T extends RaplaObject> T getEntry(TypedComponentRole<T> role); <T extends RaplaObject> T getEntry(TypedComponentRole<T> role, T defaultEntry); String getEntryAsString(TypedComponentRole<String> role, String defaultValue); Boolean getEntryAsBoolean(TypedComponentRole<Boolean> role, boolean defaultValue); Integer getEntryAsInteger(TypedComponentRole<Integer> role, int defaultValue); /** puts a new configuration entry to the role.*/ void putEntry(TypedComponentRole<Boolean> role,Boolean entry); void putEntry(TypedComponentRole<Integer> role,Integer entry); void putEntry(TypedComponentRole<String> role,String entry); void putEntry(TypedComponentRole<CalendarModelConfiguration> role,CalendarModelConfiguration entry); <T> void putEntry(TypedComponentRole<RaplaMap<T>> role,RaplaMap<T> entry); void putEntry(TypedComponentRole<RaplaConfiguration> role,RaplaConfiguration entry); void removeEntry(String role); }
04900db4-rob
src/org/rapla/entities/configuration/Preferences.java
Java
gpl3
2,870
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.configuration; import java.util.Collection; import java.util.Date; import java.util.Map; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.framework.TypedComponentRole; /** * * @author ckohlhaas * @version 1.00.00 * @since 2.03.00 */ public interface CalendarModelConfiguration extends RaplaObject<CalendarModelConfiguration> { public static final RaplaType<CalendarModelConfiguration> TYPE = new RaplaType<CalendarModelConfiguration>(CalendarModelConfiguration.class, "calendar"); public static final TypedComponentRole<CalendarModelConfiguration> CONFIG_ENTRY = new TypedComponentRole<CalendarModelConfiguration>("org.rapla.DefaultSelection"); public static final TypedComponentRole<RaplaMap<CalendarModelConfiguration>> EXPORT_ENTRY = new TypedComponentRole<RaplaMap<CalendarModelConfiguration>>("org.rapla.plugin.autoexport"); public Date getStartDate(); public Date getEndDate(); public Date getSelectedDate(); public String getTitle(); public String getView(); public Collection<Entity> getSelected(); public Map<String,String> getOptionMap(); //public Configuration get public ClassificationFilter[] getFilter(); public boolean isDefaultEventTypes(); public boolean isDefaultResourceTypes(); public boolean isResourceRootSelected(); public CalendarModelConfiguration cloneWithNewOptions(Map<String, String> newMap); }
04900db4-rob
src/org/rapla/entities/configuration/CalendarModelConfiguration.java
Java
gpl3
2,501
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.configuration; import java.util.Map; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; /** * This Map can hold only Objects of type RaplaObject and String * (It cannot hold references to appointments or attributes) * @see RaplaObject */ public interface RaplaMap<T> extends RaplaObject, Map<String,T> { public static final RaplaType<RaplaMap> TYPE = new RaplaType<RaplaMap>(RaplaMap.class, "map"); }
04900db4-rob
src/org/rapla/entities/configuration/RaplaMap.java
Java
gpl3
1,391
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import org.rapla.framework.RaplaException; /** Thrown if the same key is used by another object. */ public class UniqueKeyException extends RaplaException { private static final long serialVersionUID = 1L; public UniqueKeyException(String text) { super(text); } }
04900db4-rob
src/org/rapla/entities/UniqueKeyException.java
Java
gpl3
1,268
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import org.rapla.framework.RaplaException; public class EntityNotFoundException extends RaplaException { private static final long serialVersionUID = 1L; Comparable id; public EntityNotFoundException(String text) { this(text, null); } public EntityNotFoundException(String text, Comparable id) { super(text); this.id = id; } public Comparable getId() { return id; } }
04900db4-rob
src/org/rapla/entities/EntityNotFoundException.java
Java
gpl3
1,425
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; public interface CategoryAnnotations{ String KEY_NAME_COLOR="color"; String GROUP_ADMIN_KEY = "admin"; String GROUP_REGISTERER_KEY = "registerer"; String GROUP_MODIFY_PREFERENCES_KEY = "modify-preferences"; String GROUP_CAN_READ_EVENTS_FROM_OTHERS = "read-events-from-others"; String GROUP_CAN_CREATE_EVENTS = "create-events"; String GROUP_CAN_EDIT_TEMPLATES = "edit-templates"; }
04900db4-rob
src/org/rapla/entities/CategoryAnnotations.java
Java
gpl3
1,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; /** This Exception is thrown when the application wants to write to a read-only entity. You should use the edit method to get a writable version of the entity. */ public class ReadOnlyException extends RuntimeException { private static final long serialVersionUID = 1L; public ReadOnlyException(Object object) { super("Can't modify entity [" + object + "]. Use the edit-method to get a writable version!"); } }
04900db4-rob
src/org/rapla/entities/ReadOnlyException.java
Java
gpl3
1,411
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; /**Should be implemented by objects which can be uniquely associated with a User. */ public interface Ownable { void setOwner(User owner); User getOwner(); }
04900db4-rob
src/org/rapla/entities/Ownable.java
Java
gpl3
1,142
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; public interface Annotatable { void setAnnotation(String key, String annotation) throws IllegalAnnotationException; //<T extends RaplaAnnotation> String getAnnotation(Class<T> annotation); //<T extends RaplaAnnotation> String getAnnotation(Class<T> annotation, T defaultValue); String getAnnotation(String key); String getAnnotation(String key, String defaultValue); String[] getAnnotationKeys(); }
04900db4-rob
src/org/rapla/entities/Annotatable.java
Java
gpl3
1,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.entities; /* @see MultiLanguageName */ public interface MultiLanguageNamed extends Named { MultiLanguageName getName(); }
04900db4-rob
src/org/rapla/entities/MultiLanguageNamed.java
Java
gpl3
1,089
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import java.util.Arrays; import java.util.Collection; import org.rapla.framework.RaplaException; public class DependencyException extends RaplaException { private static final long serialVersionUID = 1L; Collection<String> dependentObjects; public DependencyException(String message,String[] dependentObjectsNames) { this(message, Arrays.asList(dependentObjectsNames)); } public DependencyException(String message,Collection<String> dependentObjectsNames) { super(message); this.dependentObjects = dependentObjectsNames ; } public Collection<String> getDependencies() { return dependentObjects; } }
04900db4-rob
src/org/rapla/entities/DependencyException.java
Java
gpl3
1,651
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import java.util.Locale; /** Hierarchical categorization of information. * Categories can be used as attribute values. * @see org.rapla.entities.dynamictype.Attribute */ public interface Category extends MultiLanguageNamed,Entity<Category>,Timestamp, Annotatable, Comparable { final RaplaType<Category> TYPE = new RaplaType<Category>(Category.class, "category"); final String SUPER_CATEGORY_ID = TYPE.getLocalName() + "_0"; /** add a sub-category. * This category is set as parent of the passed category.*/ void addCategory(Category category); /** remove a sub-category */ void removeCategory(Category category); /** returns all subcategories */ Category[] getCategories(); /** returns the subcategory with the specified key. * null if subcategory was not found. */ Category getCategory(String key); /** find a sub-category in that equals the specified category. */ Category findCategory(Category copy); /** Returns the parent of this category or null if the category has no parent.*/ Category getParent(); /** returns true if the passed category is a direct child of this category */ boolean hasCategory(Category category); /** set the key of the category. The can be used in the getCategory() method for lookup. */ void setKey(String key); /** returns the key of the category */ String getKey(); /** returns true this category is an ancestor * (parent or parent of parent, ...) of the specified * category */ boolean isAncestorOf(Category category); /** returns the path form the rootCategory to this category. * Path elements are the category-names in the selected locale separated * with the / operator. If the rootCategory is null the path will be calculated * to the top-most parent. * Example: <strong>area51/aliencell</strong> */ String getPath(Category rootCategory,Locale locale); /** returns the max depth of the cildrens */ int getDepth(); /** returns the number of ancestors. * (How many Time you must call getParent() until you receive null) */ int getRootPathLength(); Category[] CATEGORY_ARRAY = new Category[0]; }
04900db4-rob
src/org/rapla/entities/Category.java
Java
gpl3
3,192
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import org.rapla.framework.RaplaException; public class IllegalAnnotationException extends RaplaException { private static final long serialVersionUID = 1L; public IllegalAnnotationException(String text) { super(text); } public IllegalAnnotationException(String text, Exception ex) { super(text, ex); } }
04900db4-rob
src/org/rapla/entities/IllegalAnnotationException.java
Java
gpl3
1,322
<body> Contains the interfaces of the persistent entity-objects in rapla. </body>
04900db4-rob
src/org/rapla/entities/package.html
HTML
gpl3
85
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import java.util.Comparator; import org.rapla.entities.domain.Allocatable; import org.rapla.framework.RaplaException; /** The User-Class is mainly for authentication-purpose */ public interface User extends Entity<User>, Named, Comparable, Timestamp { final RaplaType<User> TYPE = new RaplaType<User>(User.class,"user"); /** returns the loginname */ String getUsername(); /** returns the complete name of user */ String getName(); /** returns the email of the user */ String getEmail(); /** returns if the user has admin-privilige */ boolean isAdmin(); void setPerson(Allocatable person) throws RaplaException; Allocatable getPerson(); void setUsername(String username); void setName(String name); void setEmail(String email); void setAdmin(boolean isAdmin); void addGroup(Category group); boolean removeGroup(Category group); Category[] getGroups(); boolean belongsTo( Category group ); public static User[] USER_ARRAY = new User[0]; Comparator<User> USER_COMPARATOR= new Comparator<User>() { @SuppressWarnings("unchecked") @Override public int compare(User u1, User u2) { if ( u2 == null) { return 1; } if ( u1==u2 || u1.equals(u2)) return 0; int result = String.CASE_INSENSITIVE_ORDER.compare( u1.getUsername() ,u2.getUsername() ); if ( result !=0 ) return result; result = u1.compareTo( u2 ); return result; } }; }
04900db4-rob
src/org/rapla/entities/User.java
Java
gpl3
2,786
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import java.util.Date; public interface Timestamp { /** returns the creation date of the object. */ Date getCreateTime(); /** returns the date of last change of the object. */ Date getLastChanged(); /**@deprecated use getLastChanged instead */ Date getLastChangeTime(); User getLastChangedBy(); //String getId(); }
04900db4-rob
src/org/rapla/entities/Timestamp.java
Java
gpl3
1,314
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; public interface AttributeAnnotations { String KEY_EDIT_VIEW = "edit-view"; String VALUE_EDIT_VIEW_MAIN = "main-view"; String VALUE_EDIT_VIEW_ADDITIONAL = "additional-view"; String VALUE_EDIT_VIEW_NO_VIEW = "no-view"; String KEY_EXPECTED_ROWS = "expected-rows"; String KEY_EXPECTED_COLUMNS = "expected-columns"; String KEY_COLOR = "color"; String KEY_EMAIL = "email"; String KEY_CATEGORIZATION = "categorization"; String KEY_PERMISSION_MODIFY = "permission_modify"; String KEY_PERMISSION_READ = "permission_read"; }
04900db4-rob
src/org/rapla/entities/dynamictype/AttributeAnnotations.java
Java
gpl3
1,556
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; import org.rapla.entities.Annotatable; import org.rapla.entities.Entity; import org.rapla.entities.MultiLanguageNamed; import org.rapla.entities.RaplaType; import org.rapla.entities.Timestamp; /** In rapla it is possible to dynamicly classify a reservation, resource or person with customized attributes. You can for example define a dynamicType called <em>room</em> with the attributes <em>name</em> and <em>seats</em> and classify all your room-resources as <em>room</em>. */ public interface DynamicType extends Entity<DynamicType>,MultiLanguageNamed,Annotatable, Timestamp { final RaplaType<DynamicType> TYPE = new RaplaType<DynamicType>(DynamicType.class, "dynamictype"); Attribute[] getAttributes(); /** returns null if the attribute is not found */ Attribute getAttribute(String key); void addAttribute(Attribute attribute); /** find an attribute in the dynamic type that equals the specified attribute This is usefull if you have the * persistant version of an attribute and want to discover the editable version in the working copy of a dynamic type */ String findAttribute(Attribute attribute); boolean hasAttribute(Attribute attribute); void removeAttribute(Attribute attribute); /** exchange the two attribute positions */ void exchangeAttributes(int index1, int index2); /** @deprecated use setKey instead*/ @Deprecated() void setElementKey(String elementKey); /** @deprecated use getKey instead*/ @Deprecated() String getElementKey(); void setKey(String key); String getKey(); /* creates a new classification and initializes it with the attribute defaults * @throws IllegalStateException when called from a non persistant instance of DynamicType */ Classification newClassification(); /* creates a new classification * @throws IllegalStateException when called from a non persistant instance of DynamicType */ Classification newClassification(boolean useDefaults); /* creates a new classification and tries to fill it with the values of the originalClassification. * @throws IllegalStateException when called from a non persistant instance of DynamicType */ Classification newClassification(Classification originalClassification); /* @throws IllegalStateException when called from a non persistant instance of DynamicType */ ClassificationFilter newClassificationFilter(); final DynamicType[] DYNAMICTYPE_ARRAY = new DynamicType[0]; }
04900db4-rob
src/org/rapla/entities/dynamictype/DynamicType.java
Java
gpl3
3,500
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; import java.util.Collection; import java.util.Locale; import org.rapla.entities.Named; /** A Classification is an instance of a DynamicType. It holds the * attribute values for the attributesof the corresponding type. You * need one classification for each object you want to * classify. */ public interface Classification extends Named,Cloneable { DynamicType getType(); String getName(Locale locale); String getNamePlaning(Locale locale); Attribute[] getAttributes(); Attribute getAttribute(String key); void setValue(Attribute attribute,Object value); <T> void setValues(Attribute attribute,Collection<T> values); /** calls setValue(getAttribute(key),value)*/ void setValue(String key,Object value); /** calls getValue(getAttribte(key))*/ Object getValue(Attribute attribute); Object getValue(String key); Collection<Object> getValues(Attribute attribute); /** returns the value as a String in the selected locale.*/ String getValueAsString(Attribute attribute,Locale locale); Object clone(); }
04900db4-rob
src/org/rapla/entities/dynamictype/Classification.java
Java
gpl3
2,062
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; import java.util.Iterator; /** <p>A new ClassificationFilter for a classifications belonging to the same DynamicType can be created by the newClassificationFilter of the corresponding DynamicType object. </p> <p>You can set rules for the attributes of the DynamicType. A Classification (object implementing Classifiable) is matched by the filter when the conditions for each attribute-rule are matched (AND - function).</p> <p>A condition is an array of size 2, the first field contains the operator of the condition and the second the test value. When an attribute-rule has more than one condition, at least one of the conditions must be matched (OR - function ) . </p> <p> The following Example matches all classifications with a title-value that contains either "rapla" or "sourceforge" ,a size-value that is > 5 and a category-department-value that is either the departmentA or the departmentB. </p> <pre> DynamicType eventType = facade.getDynamicType("event"); ClassificationFilter f = eventType.newClassificationFilter(); f.addRule( "title" ,new Object { {"contains", "rapla"} ,{"contains", "sourceforge"} }); f.addRule( "size" ,new Object{ {">", new Integer(5)} }); Category departemntCategory = facade.getRootCategory().getCategory("departments"); Category departmentA = departmentCategory.getCategory("departmentA"); Category departmentB = departmentCategory.getCategory("departmentB"); f.addRule( "department" ,new Object{ {"=", departmentA} ,{ "=", departmentB} }); </pre> @see Classification */ public interface ClassificationFilter extends Cloneable { DynamicType getType(); /** Defines a rule for the passed attribute. */ void setRule(int index, String attributeName,Object[][] conditions); void setRule(int index, Attribute attribute,Object[][] conditions); /** appends a rule. * @see #setRule*/ void addRule(String attributeName,Object[][] conditions); /** shortcut to * <pre> * f.addRule( attributeName ,new Object{ {"=", object}} }); * </pre> * @param attributeName * @param object */ void addEqualsRule( String attributeName,Object object); /** shortcut to * <pre> * f.addRule( attributeName ,new Object{ {"is", object}} }); * </pre> * @param attributeName * @param object */ void addIsRule( String attributeName,Object object); int ruleSize(); Iterator<? extends ClassificationFilterRule> ruleIterator(); void removeAllRules(); void removeRule(int index); boolean matches(Classification classification); ClassificationFilter clone(); final ClassificationFilter[] CLASSIFICATIONFILTER_ARRAY = new ClassificationFilter[0]; ClassificationFilter[] toArray(); class Util { static public boolean matches(ClassificationFilter[] filters, Classifiable classifiable) { Classification classification = classifiable.getClassification(); for (int i = 0; i < filters.length; i++) { if (filters[i].matches(classification)) { return true; } } return false; } } }
04900db4-rob
src/org/rapla/entities/dynamictype/ClassificationFilter.java
Java
gpl3
4,626
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype.internal; import java.util.Date; import org.rapla.components.util.ParseDateException; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.ClassificationFilterRule; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.storage.internal.ReferenceHandler; public final class ClassificationFilterRuleImpl extends ReferenceHandler implements ClassificationFilterRule ,java.io.Serializable { // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; String[] operators; String[] ruleValues; String attributeId; ClassificationFilterRuleImpl() { } ClassificationFilterRuleImpl(Attribute attribute, String[] operators,Object[] ruleValues) { attributeId = attribute.getId(); DynamicType type = attribute.getDynamicType(); if ( type== null) { throw new IllegalArgumentException("Attribute type cannot be null"); } putEntity("dynamictype",type); this.operators = operators; this.ruleValues = new String[ruleValues.length]; RaplaType refType = attribute.getRefType(); for (int i=0;i<ruleValues.length;i++) { Object ruleValue = ruleValues[i]; if (ruleValue instanceof Entity) { putEntity(String.valueOf(i),(Entity)ruleValue); //unresolvedRuleValues[i] = ((Entity)ruleValues[i]).getId(); } else if (refType != null && (ruleValue instanceof String) /*&& refType.isId(ruleValue)*/) { putId(String.valueOf(i),(String)ruleValue); } else { setValue(i, ruleValue); } } } public boolean needsChange(Attribute typeAttribute) { Object[] ruleValues = getValues(); for (int i=0;i<ruleValues.length;i++) if (typeAttribute.needsChange(ruleValues[i])) return true; return false; } public void commitChange(Attribute typeAttribute) { Object[] ruleValues = getValues(); for (int i=0;i<ruleValues.length;i++) { Object oldValue = ruleValues[i]; Object newValue = typeAttribute.convertValue(oldValue); setValue(i, newValue); } } /** find the attribute of the given type that matches the id */ private Attribute findAttribute(DynamicType type,Object id) { Attribute[] typeAttributes = type.getAttributes(); for (int i=0; i<typeAttributes.length; i++) { if (((Entity)typeAttributes[i]).getId().equals(id)) { return typeAttributes[i]; } } return null; } public Attribute getAttribute() { DynamicType dynamicType = getDynamicType(); return findAttribute(dynamicType, attributeId); } public DynamicType getDynamicType() { return getEntity("dynamictype", DynamicType.class); } @Override protected Class<? extends Entity> getInfoClass(String key) { if ( key.equals("dynamictype")) { return DynamicType.class; } Attribute attribute = getAttribute(); if ( key.length() > 0 && Character.isDigit(key.charAt(0))) { //int index = Integer.parseInt(key); AttributeType type = attribute.getType(); if (type == AttributeType.CATEGORY ) { return Category.class; } else if ( type == AttributeType.ALLOCATABLE) { return Allocatable.class; } } return null; } public String[] getOperators() { return this.operators; } public Object[] getValues() { Object[] result = new Object[operators.length]; Attribute attribute = getAttribute(); for (int i=0;i<operators.length;i++) { Object value = getValue(attribute,i); result[i] = value; } return result; } private Object getValue(Attribute attribute, int index) { AttributeType type = attribute.getType(); if (type == AttributeType.CATEGORY ) { return getEntity(String.valueOf(index), Category.class); } else if (type == AttributeType.ALLOCATABLE) { return getEntity(String.valueOf(index), Allocatable.class); } String stringValue = ruleValues[index]; if ( stringValue == null) { return null; } if (type == AttributeType.STRING) { return stringValue; } else if (type == AttributeType.BOOLEAN) { return Boolean.parseBoolean( stringValue); } else if (type == AttributeType.INT ) { return Long.parseLong(stringValue); } else if (type == AttributeType.DATE) { try { return SerializableDateTimeFormat.INSTANCE.parseTimestamp( stringValue); } catch (ParseDateException e) { return null; } } else { throw new IllegalStateException("Attributetype " + type + " not supported in filter"); } } private void setValue(int i, Object ruleValue) { String newValue; if (ruleValue instanceof Entity) { putEntity(String.valueOf(i), (Entity)ruleValue); newValue = null; } else if ( ruleValue instanceof Date) { Date date = (Date) ruleValue; newValue= SerializableDateTimeFormat.INSTANCE.formatTimestamp(date); } else { newValue = ruleValue != null ? ruleValue.toString() : null; removeId( String.valueOf( i)); } ruleValues[i] = newValue; } boolean matches(Object value) { //String[] ruleOperators = getOperators(); Attribute attribute = getAttribute(); for (int i=0;i<operators.length;i++) { String operator = operators[i]; if (matches(attribute,operator,i,value)) return true; } return false; } private boolean matches(Attribute attribute,String operator,int index,Object value) { AttributeType type = attribute.getType(); Object ruleValue = getValue(attribute, index); if (type == AttributeType.CATEGORY) { Category category = (Category) ruleValue; if (category == null) { return (value == null); } if ( operator.equals("=") ) { return value != null && category.isIdentical((Category)value); } else if ( operator.equals("is") ) { return value != null && (category.isIdentical((Category)value) || category.isAncestorOf((Category)value)); } } else if (type == AttributeType.ALLOCATABLE) { Allocatable allocatable = (Allocatable) ruleValue; if (allocatable == null) { return (value == null); } if ( operator.equals("=") ) { return value != null && allocatable.isIdentical((Allocatable)value); } else if ( operator.equals("is") ) { return value != null && (allocatable.isIdentical((Allocatable)value) ); // || category.isAncestorOf((Category)value)); } } else if (type == AttributeType.STRING) { if (ruleValue == null) { return (value == null); } if ( operator.equals("is") || operator.equals("=")) { return value != null && value.equals( ruleValue ); } else if ( operator.equals("contains") ) { String string = ((String)ruleValue).toLowerCase(); if (string == null) return true; string = string.trim(); if (value == null) return string.length() == 0; return (((String)value).toLowerCase().indexOf(string)>=0); } else if ( operator.equals("starts") ) { String string = ((String)ruleValue).toLowerCase(); if (string == null) return true; string = string.trim(); if (value == null) return string.length() == 0; return (((String)value).toLowerCase().startsWith(string)); } } else if (type == AttributeType.BOOLEAN) { Boolean boolean1 = (Boolean)ruleValue; Boolean boolean2 = (Boolean)value; if (boolean1 == null) { return (boolean2 == null || boolean2.booleanValue()); } if (boolean2 == null) { return !boolean1.booleanValue(); } return (boolean1.equals(boolean2)); } else if (type == AttributeType.INT || type ==AttributeType.DATE) { if(ruleValue == null) { if (operator.equals("<>")) if(value == null) return false; else return true; else if (operator.equals("=")) if(value == null) return true; else return false; else return false; } if(value == null) return false; long long1 = type == AttributeType.INT ? ((Long) value).longValue() : ((Date) value).getTime(); long long2 = type == AttributeType.INT ? ((Long) ruleValue).longValue() : ((Date) ruleValue).getTime(); if (operator.equals("<")) { return long1 < long2; } else if (operator.equals("=")) { return long1 == long2; } else if (operator.equals(">")) { return long1 > long2; } else if (operator.equals(">=")) { return long1 >= long2; } else if (operator.equals("<=")) { return long1 >= long2; } else if (operator.equals("<>")) { return long1 != long2; } } return false; } public String toString() { StringBuilder buf = new StringBuilder(); buf.append(getAttribute().getKey()); Object[] values = getValues(); String[] operators = getOperators(); for ( int i=0;i<values.length;i++) { String operator = i<operators.length ? operators[i] : "="; buf.append(" " + operator + " "); buf.append(values[i]); buf.append(", "); } return buf.toString(); } }
04900db4-rob
src/org/rapla/entities/dynamictype/internal/ClassificationFilterRuleImpl.java
Java
gpl3
12,267
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.RaplaType; import org.rapla.entities.ReadOnlyException; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.entities.dynamictype.internal.ParsedText.EvalContext; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.UnresolvableReferenceExcpetion; /** Use the method <code>newClassification()</code> of class <code>DynamicType</code> to * create a classification. Once created it is not possible to change the * type of a classifiction. But you can replace the classification of an * object implementing <code>Classifiable</code> with a new one. * @see DynamicType * @see org.rapla.entities.dynamictype.Classifiable */ public class ClassificationImpl implements Classification,DynamicTypeDependant, EntityReferencer { private String typeId; private String type; private Map<String,List<String>> data = new LinkedHashMap<String,List<String>>(); private transient boolean readOnly = false; private transient TextCache name; private transient TextCache namePlaning; private transient EntityResolver resolver; /** stores the nonreference values like integers,boolean and string.*/ //HashMap<String,Object> attributeValueMap = new HashMap<String,Object>(1); /** stores the references to the dynamictype and the reference values */ //transient ReferenceHandler referenceHandler = new ReferenceHandler(data); class TextCache { String nameString; ParsedText lastParsedAnnotation; public String getName(Locale locale, String keyNameFormat) { DynamicTypeImpl type = (DynamicTypeImpl)getType(); ParsedText parsedAnnotation = type.getParsedAnnotation( keyNameFormat ); if ( parsedAnnotation == null) { return type.toString(); } if (nameString != null) { if (parsedAnnotation.equals(lastParsedAnnotation)) return nameString; } lastParsedAnnotation = parsedAnnotation; EvalContext evalContext = new EvalContext(locale) { public Classification getClassification() { return ClassificationImpl.this; } }; nameString = parsedAnnotation.formatName(evalContext).trim(); return nameString; } } public ClassificationImpl() { } ClassificationImpl(DynamicTypeImpl dynamicType) { typeId = dynamicType.getId(); type = dynamicType.getKey(); } public void setResolver( EntityResolver resolver) { this.resolver = resolver; } public void setReadOnly() { this.readOnly = true; } public boolean isReadOnly() { return readOnly; } public void checkWritable() { if ( readOnly ) throw new ReadOnlyException( this ); } @Override public Iterable<ReferenceInfo> getReferenceInfo() { List<ReferenceInfo> result = new ArrayList<ReferenceInfo>(); String parentId = getParentId(); result.add( new ReferenceInfo(parentId, DynamicType.class) ); DynamicTypeImpl type = getType(); for ( Map.Entry<String,List<String>> entry:data.entrySet()) { String key = entry.getKey(); Attribute attribute = type.getAttribute(key); RaplaType refType = attribute.getRefType(); if ( attribute == null || refType == null) { continue; } List<String> values = entry.getValue(); if (values != null ) { @SuppressWarnings("unchecked") Class<? extends Entity> class1 = refType.getTypeClass(); for ( String value:values) { result.add(new ReferenceInfo(value, class1) ); } } } return result; } private String getParentId() { if (typeId != null) return typeId; if (type == null) { throw new UnresolvableReferenceExcpetion( "type and parentId are both not set"); } DynamicType dynamicType = resolver.getDynamicType( type); if ( dynamicType == null) { throw new UnresolvableReferenceExcpetion( type); } typeId = dynamicType.getId(); return typeId; } public DynamicTypeImpl getType() { if ( resolver == null) { throw new IllegalStateException("Resolver not set on "+ toString()); } String parentId = getParentId(); DynamicTypeImpl type = (DynamicTypeImpl) resolver.tryResolve( parentId, DynamicType.class); if ( type == null) { throw new UnresolvableReferenceExcpetion(DynamicType.class +":" + parentId + " " +data); } return type; } public String getName(Locale locale) { // display name = Title of event if ( name == null) { name = new TextCache(); } return name.getName(locale, DynamicTypeAnnotations.KEY_NAME_FORMAT); } public String getNamePlaning(Locale locale) { if ( namePlaning == null) { namePlaning = new TextCache(); } return namePlaning.getName(locale, DynamicTypeAnnotations.KEY_NAME_FORMAT_PLANNING); } public String getValueAsString(Attribute attribute,Locale locale) { Collection values = getValues(attribute); StringBuilder buf = new StringBuilder(); boolean first = true; for ( Object value: values) { if (first) { first = false; } else { buf.append(", "); } buf.append( ((AttributeImpl)attribute).getValueAsString( locale, value)); } String result = buf.toString(); return result; } public Attribute getAttribute(String key) { return getType().getAttribute(key); } public Attribute[] getAttributes() { return getType().getAttributes(); } public boolean needsChange(DynamicType newType) { if ( !hasType (newType )) { return false; } DynamicTypeImpl type = getType(); if ( !newType.getKey().equals( type.getKey())) return true; for (String key:data.keySet()) { Attribute attribute = getType().getAttribute(key); if ( attribute == null) { return true; } String attributeId = attribute.getId(); if (type.hasAttributeChanged( (DynamicTypeImpl)newType , attributeId)) return true; } return false; } boolean hasType(DynamicType type) { return getType().equals( type); } public void commitChange(DynamicType type) { if ( !hasType (type )) { return; } Collection<String> removedKeys = new ArrayList<String>(); Map<Attribute,Attribute> attributeMapping = new HashMap<Attribute,Attribute>(); for (String key:data.keySet()) { Attribute attribute = getType().getAttribute(key); Attribute attribute2 = type.getAttribute(key); // key now longer availabe so remove it if ( attribute2 == null) { removedKeys.add( key ); } if ( attribute == null) { continue; } String attId = attribute.getId(); Attribute newAtt = findAttributeById(type, attId); if ( newAtt != null) { attributeMapping.put(attribute, newAtt); } } for (Attribute attribute: attributeMapping.keySet()) { Collection<Object> convertedValues = new ArrayList<Object>(); Collection<?> valueCollection = getValues( attribute); Attribute newAttribute = attributeMapping.get( attribute); for (Object oldValue: valueCollection) { Object newValue = newAttribute.convertValue(oldValue); if ( newValue != null) { convertedValues.add( newValue); } } setValues(newAttribute, convertedValues); } for (String key:removedKeys) { data.remove( key ); } this.type = type.getKey(); name = null; namePlaning = null; } /** find the attribute of the given type that matches the id */ private Attribute findAttributeById(DynamicType type,String id) { Attribute[] typeAttributes = type.getAttributes(); for (int i=0; i<typeAttributes.length; i++) { String key2 = typeAttributes[i].getId(); if (key2.equals(id)) { return typeAttributes[i]; } } return null; } public void setValue(String key,Object value) { Attribute attribute = getAttribute( key ); if ( attribute == null ) { throw new NoSuchElementException("No attribute found for key " + key); } setValue( attribute,value); } public Object getValue(String key) { Attribute attribute = getAttribute( key ); if ( attribute == null ) { throw new NoSuchElementException("No attribute found for key " + key); } return getValue(getAttribute(key)); } public void setValue(Attribute attribute,Object value) { checkWritable(); if ( value != null && !(value instanceof Collection<?>)) { value = Collections.singleton( value); } setValues(attribute, (Collection<?>) value); } public <T> void setValues(Attribute attribute,Collection<T> values) { checkWritable(); String attributeKey = attribute.getKey(); if ( values == null || values.isEmpty()) { data.remove(attributeKey); name = null; namePlaning = null; return; } ArrayList<String> newValues = new ArrayList<String>(); for (Object value:values) { String stringValue = ((AttributeImpl)attribute).toStringValue(value); if ( stringValue != null) { newValues.add(stringValue); } } data.put(attributeKey,newValues); //isNameUpToDate = false; name = null; namePlaning = null; } public <T> void addValue(Attribute attribute,T value) { checkWritable(); String attributeKey = attribute.getKey(); String stringValue = ((AttributeImpl)attribute).toStringValue( value); if ( stringValue == null) { return; } List<String> l = data.get(attributeKey); if ( l == null) { l = new ArrayList<String>(); data.put(attributeKey, l); } l.add(stringValue); } public Collection<Object> getValues(Attribute attribute) { if ( attribute == null ) { throw new NullPointerException("Attribute can't be null"); } String attributeKey = attribute.getKey(); // first lookup in attribute map List<String> list = data.get(attributeKey); if ( list == null || list.size() == 0) { return Collections.emptyList(); } List<Object> result = new ArrayList<Object>(); for (String value:list) { Object obj; try { obj = ((AttributeImpl)attribute).fromString(resolver,value); result.add( obj); } catch (EntityNotFoundException e) { } } return result; } public Object getValue(Attribute attribute) { if ( attribute == null ) { throw new NullPointerException("Attribute can't be null"); } String attributeKey = attribute.getKey(); // first lookup in attribute map List<String> o = data.get(attributeKey); if ( o == null || o.size() == 0) { return null; } String stringRep = o.get(0); Object fromString; try { fromString = ((AttributeImpl)attribute).fromString(resolver, stringRep); return fromString; } catch (EntityNotFoundException e) { throw new IllegalStateException(e.getMessage()); } } public ClassificationImpl clone() { ClassificationImpl clone = new ClassificationImpl((DynamicTypeImpl)getType()); //clone.referenceHandler = (ReferenceHandler) referenceHandler.clone((Map<String, List<String>>) ((HashMap<String, List<String>>)data).clone()); //clone.attributeValueMap = (HashMap<String,Object>) attributeValueMap.clone(); for ( Map.Entry<String,List<String>> entry: data.entrySet()) { String key = entry.getKey(); List<String> value = new ArrayList<String>(entry.getValue()); clone.data.put(key, value); } clone.resolver = resolver; clone.typeId = getParentId(); clone.type = type; clone.name = null; clone.namePlaning = null; clone.readOnly = false;// clones are always writable return clone; } public String toString() { try { StringBuilder builder = new StringBuilder(); boolean first = true; builder.append("{"); for ( Attribute attribute:getAttributes()) { if ( !first) { builder.append(", "); } else { first = false; } String key = attribute.getKey(); String valueAsString = getValueAsString(attribute, null); builder.append(key); builder.append(':'); builder.append(valueAsString); } builder.append("}"); return builder.toString(); } catch (Exception ex) { return data.toString(); } } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { throw new CannotExistWithoutTypeException(); } }
04900db4-rob
src/org/rapla/entities/dynamictype/internal/ClassificationImpl.java
Java
gpl3
15,581
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.components.util.iterator.NestedIterator; import org.rapla.entities.Entity; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.entities.dynamictype.internal.ParsedText.EvalContext; import org.rapla.entities.dynamictype.internal.ParsedText.Function; import org.rapla.entities.dynamictype.internal.ParsedText.ParseContext; import org.rapla.entities.internal.ModifiableTimestamp; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.ParentEntity; import org.rapla.entities.storage.internal.SimpleEntity; final public class DynamicTypeImpl extends SimpleEntity implements DynamicType, ParentEntity, ModifiableTimestamp { private Date lastChanged; private Date createDate; // added an attribute array for performance reasons List<AttributeImpl> attributes = new ArrayList<AttributeImpl>(); MultiLanguageName name = new MultiLanguageName(); String key = ""; //Map<String,String> unparsedAnnotations = new HashMap<String,String>(); Map<String,ParsedText> annotations = new HashMap<String,ParsedText>(); transient DynamicTypeParseContext parseContext = new DynamicTypeParseContext(this); transient Map<String,AttributeImpl> attributeIndex; public DynamicTypeImpl() { this( new Date(),new Date()); } public DynamicTypeImpl(Date createDate, Date lastChanged) { this.createDate = createDate; this.lastChanged = lastChanged; } public void setResolver( EntityResolver resolver) { super.setResolver( resolver); for (AttributeImpl child:attributes) { child.setParent( this); } for ( ParsedText annotation: annotations.values()) { try { annotation.init(parseContext); } catch (IllegalAnnotationException e) { } } } public RaplaType<DynamicType> getRaplaType() {return TYPE;} public boolean isInternal() { boolean result =key.startsWith("rapla:"); return result; } public Classification newClassification() { return newClassification( true ); } public Classification newClassification(boolean useDefaults) { if ( !isReadOnly()) { throw new IllegalStateException("You can only create Classifications from a persistant Version of DynamicType"); } final ClassificationImpl classification = new ClassificationImpl(this); if ( resolver != null) { classification.setResolver( resolver); } // Array could not be up todate final Attribute[] attributes2 = getAttributes(); if ( useDefaults) { for ( Attribute att: attributes2) { final Object defaultValue = att.defaultValue(); if ( defaultValue != null) { classification.setValue(att, defaultValue); } } } return classification; } public Classification newClassification(Classification original) { if ( !isReadOnly()) { throw new IllegalStateException("You can only create Classifications from a persistant Version of DynamicType"); } final ClassificationImpl newClassification = (ClassificationImpl) newClassification(true); { Attribute[] attributes = original.getAttributes(); for (int i=0;i<attributes.length;i++) { Attribute originalAttribute = attributes[i]; String attributeKey = originalAttribute.getKey(); Attribute newAttribute = newClassification.getAttribute( attributeKey ); Object defaultValue = originalAttribute.defaultValue(); Object originalValue = original.getValue( attributeKey ); if ( newAttribute != null && newAttribute.getType().equals( originalAttribute.getType())) { Object newDefaultValue = newAttribute.defaultValue(); // If the default value of the new type differs from the old one and the value is the same as the old default then use the new default if ( newDefaultValue != null && ((defaultValue == null && originalValue == null )|| (defaultValue != null && originalValue != null && !newDefaultValue.equals(defaultValue) && (originalValue.equals( defaultValue))))) { newClassification.setValue( newAttribute, newDefaultValue); } else { newClassification.setValue( newAttribute, newAttribute.convertValue( originalValue )); } } } return newClassification; } } public ClassificationFilter newClassificationFilter() { if ( !isReadOnly()) { throw new IllegalStateException("You can only create ClassificationFilters from a persistant Version of DynamicType"); } ClassificationFilterImpl classificationFilterImpl = new ClassificationFilterImpl(this); if ( resolver != null) { classificationFilterImpl.setResolver( resolver); } return classificationFilterImpl; } public MultiLanguageName getName() { return name; } public void setReadOnly() { super.setReadOnly(); name.setReadOnly( ); } public String getName(Locale locale) { if ( locale == null) { return name.getName( null); } String language = locale.getLanguage(); return name.getName(language); } public String getAnnotation(String key) { ParsedText parsedAnnotation = annotations.get(key); if ( parsedAnnotation != null) { return parsedAnnotation.getExternalRepresentation(parseContext); } else { return null; } } @Deprecated public Date getLastChangeTime() { return lastChanged; } @Override public Date getLastChanged() { return lastChanged; } public Date getCreateTime() { return createDate; } public void setLastChanged(Date date) { checkWritable(); lastChanged = date; } @Override public Iterable<ReferenceInfo> getReferenceInfo() { return new IteratorChain<ReferenceInfo>(super.getReferenceInfo(), new NestedIterator<ReferenceInfo,AttributeImpl>( attributes ) { public Iterable<ReferenceInfo> getNestedIterator(AttributeImpl obj) { return obj.getReferenceInfo(); } } ); } @Override public void addEntity(Entity entity) { Attribute attribute = (Attribute) entity; attributes.add((AttributeImpl) attribute); if (attribute.getDynamicType() != null && !this.isIdentical(attribute.getDynamicType())) throw new IllegalStateException("Attribute '" + attribute + "' belongs to another dynamicType :" + attribute.getDynamicType()); ((AttributeImpl) attribute).setParent(this); } public String getAnnotation(String key, String defaultValue) { String annotation = getAnnotation( key ); return annotation != null ? annotation : defaultValue; } public void setAnnotation(String key,String annotation) throws IllegalAnnotationException { checkWritable(); if (annotation == null) { annotations.remove(key); return; } ParsedText parsedText = new ParsedText(annotation); parsedText.init(parseContext); annotations.put(key,parsedText); } public String[] getAnnotationKeys() { return annotations.keySet().toArray(RaplaObject.EMPTY_STRING_ARRAY); } @Deprecated public void setElementKey(String elementKey) { setKey(elementKey); } public void setKey(String key) { checkWritable(); this.key = key; for ( ParsedText text:annotations.values()) { text.updateFormatString(parseContext); } } public String getElementKey() { return getKey(); } public String getKey() { return key; } /** exchange the two attribute positions */ public void exchangeAttributes(int index1, int index2) { checkWritable(); Attribute[] attribute = getAttributes(); Attribute attribute1 = attribute[index1]; Attribute attribute2 = attribute[index2]; List<AttributeImpl> newMap = new ArrayList<AttributeImpl>(); for (int i=0;i<attribute.length;i++) { Attribute att; if (i == index1) att = attribute2; else if (i == index2) att = attribute1; else att = attribute[i]; newMap.add((AttributeImpl) att); } attributes = newMap; } /** find an attribute in the dynamic-type that equals the specified attribute. */ public Attribute findAttributeForId(Object id) { Attribute[] typeAttributes = getAttributes(); for (int i=0; i<typeAttributes.length; i++) { if (((Entity)typeAttributes[i]).getId().equals(id)) { return typeAttributes[i]; } } return null; } /** * @param attributeImpl * @param key */ public void keyChanged(AttributeImpl attributeImpl, String key) { attributeIndex = null; for ( ParsedText text:annotations.values()) { text.updateFormatString(parseContext); } } public void removeAttribute(Attribute attribute) { checkWritable(); String matchingAttributeKey = findAttribute( attribute ); if ( matchingAttributeKey == null) { return; } attributes.remove( attribute); if (this.equals(attribute.getDynamicType())) { if (((AttributeImpl) attribute).isReadOnly()) { throw new IllegalArgumentException("Attribute is not writable. It does not belong to the same dynamictype instance"); } ((AttributeImpl) attribute).setParent(null); } } public String findAttribute(Attribute attribute) { for ( AttributeImpl att: attributes ) { if (att.equals( attribute)) { return att.getKey(); } } return null; } public void addAttribute(Attribute attribute) { checkWritable(); if ( hasAttribute(attribute)) { return; } addEntity(attribute); attributeIndex = null; } public boolean hasAttribute(Attribute attribute) { return attributes.contains( attribute ); } public Attribute[] getAttributes() { return attributes.toArray(Attribute.ATTRIBUTE_ARRAY); } public AttributeImpl getAttribute(String key) { if ( attributeIndex == null) { attributeIndex = new HashMap<String, AttributeImpl>(); for ( AttributeImpl att:attributes) { attributeIndex.put( att.getKey(), att); } } AttributeImpl attributeImpl = attributeIndex.get( key); return attributeImpl; } public ParsedText getParsedAnnotation(String key) { return annotations.get( key ); } @SuppressWarnings("unchecked") public Collection<AttributeImpl> getSubEntities() { return attributes; } public DynamicTypeImpl clone() { DynamicTypeImpl clone = new DynamicTypeImpl(); super.deepClone(clone); clone.lastChanged = lastChanged; clone.createDate = createDate; clone.name = (MultiLanguageName) name.clone(); clone.key = key; for (AttributeImpl att:clone.getSubEntities()) { ((AttributeImpl)att).setParent(clone); } clone.annotations = new LinkedHashMap<String, ParsedText>(); DynamicTypeParseContext parseContext = new DynamicTypeParseContext(clone); for (Map.Entry<String,ParsedText> entry: annotations.entrySet()) { String annotation = entry.getKey(); ParsedText parsedAnnotation =entry.getValue(); String parsedValue = parsedAnnotation.getExternalRepresentation(parseContext); try { clone.setAnnotation(annotation, parsedValue); } catch (IllegalAnnotationException e) { throw new IllegalStateException("Can't parse annotation back", e); } } return clone; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(" ["); buf.append ( super.toString()) ; buf.append("] key="); buf.append( getKey() ); buf.append(": "); if ( attributes != null ) { Attribute[] att = getAttributes(); for ( int i=0;i<att.length; i++){ if ( i> 0) buf.append(", "); buf.append( att[i].getKey()); } } return buf.toString(); } /** * @param newType * @param attributeId */ public boolean hasAttributeChanged(DynamicTypeImpl newType, String attributeId) { Attribute oldAttribute = findAttributeForId(attributeId ); Attribute newAttribute = newType.findAttributeForId(attributeId ); if ( oldAttribute == null && newAttribute == null) { return false; } if ((newAttribute == null ) || ( oldAttribute == null)) { return true; } String newKey = newAttribute.getKey(); String oldKey = oldAttribute.getKey(); if ( !newKey.equals( oldKey )) { return true; } if ( !newAttribute.getType().equals( oldAttribute.getType())) { return true; } { String[] keys = newAttribute.getConstraintKeys(); String[] oldKeys = oldAttribute.getConstraintKeys(); if ( keys.length != oldKeys.length) { return true; } for ( int i=0;i< keys.length;i++) { if ( !keys[i].equals( oldKeys[i]) ) return true; Object oldConstr = oldAttribute.getConstraint( keys[i]); Object newConstr = newAttribute.getConstraint( keys[i]); if ( oldConstr == null && newConstr == null) continue; if ( oldConstr == null || newConstr == null) return true; if ( !oldConstr.equals( newConstr)) return true; } } return false; } public static boolean isInternalType(Classifiable classifiable) { boolean isRaplaType =false; Classification classification = classifiable.getClassification(); if ( classification != null ) { String classificationType = classification.getType().getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); if ( classificationType != null && classificationType.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE)) { isRaplaType = true; } } return isRaplaType; } static class DynamicTypeParseContext implements ParseContext { private DynamicTypeImpl type; DynamicTypeParseContext( DynamicType type) { this.type = (DynamicTypeImpl)type; } public Function resolveVariableFunction(String variableName) throws IllegalAnnotationException { Attribute attribute = type.getAttribute(variableName); if (attribute != null) { return new AttributeFunction(attribute); } else if (variableName.equals(type.getKey())) { return new TypeFunction(type); } return null; } class AttributeFunction extends ParsedText.Function { Object id; AttributeFunction(Attribute attribute ) { super("attribute:"+attribute.getKey()); id =attribute.getId() ; } protected String getName() { Attribute attribute = findAttribute( type); if ( attribute != null) { return attribute.getKey(); } return name; } public Attribute eval(EvalContext context) { Classification classification = context.getClassification(); DynamicTypeImpl type = (DynamicTypeImpl) classification.getType(); return findAttribute(type); } public Attribute findAttribute(DynamicTypeImpl type) { Attribute attribute = type.findAttributeForId( id ); if ( attribute!= null) { return attribute; } return null; } @Override public String getRepresentation( ParseContext context) { Attribute attribute = type.findAttributeForId( id ); if ( attribute!= null) { return attribute.getKey(); } return ""; } } class TypeFunction extends ParsedText.Function { Object id; TypeFunction(DynamicType type) { super("type:"+type.getKey()); id = type.getId() ; } public String eval(EvalContext context) { DynamicTypeImpl type = (DynamicTypeImpl) context.getClassification().getType(); return type.getName( context.getLocale()); } @Override public String getRepresentation( ParseContext context) { if ( type.getId().equals( id ) ) { return type.getKey(); } return ""; } } } public static boolean isTransferedToClient(Classifiable classifiable) { if ( classifiable == null) { return false; } DynamicType type = classifiable.getClassification().getType(); boolean result = isTransferedToClient(type); return result; } public static boolean isTransferedToClient(DynamicType type) { String annotation = type.getAnnotation( DynamicTypeAnnotations.KEY_TRANSFERED_TO_CLIENT); if ( annotation == null) { return true; } return !annotation.equals( DynamicTypeAnnotations.VALUE_TRANSFERED_TO_CLIENT_NEVER); } }
04900db4-rob
src/org/rapla/entities/dynamictype/internal/DynamicTypeImpl.java
Java
gpl3
19,511
/*--------------------------------------------------------------------------* | Copyright (C) 21006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype.internal; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.rapla.components.util.DateTools; import org.rapla.components.util.ParseDateException; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.ConstraintIds; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.framework.RaplaException; final public class AttributeImpl extends SimpleEntity implements Attribute { public static final MultiLanguageName TRUE_TRANSLATION = new MultiLanguageName(); public static final MultiLanguageName FALSE_TRANSLATION = new MultiLanguageName(); static { TRUE_TRANSLATION.setName("en", "yes"); FALSE_TRANSLATION.setName("en", "no"); } private MultiLanguageName name = new MultiLanguageName(); private AttributeType type; private String key; private boolean multiSelect; private boolean bOptional = false; private Map<String,String> annotations = new LinkedHashMap<String,String>(); private String defaultValue =null; private transient DynamicTypeImpl parent; public final static AttributeType DEFAULT_TYPE = AttributeType.STRING; public AttributeImpl() { this.type = DEFAULT_TYPE; } public AttributeImpl(AttributeType type) { setType(type); } void setParent(DynamicTypeImpl parent) { this.parent = parent; } public DynamicType getDynamicType() { return parent; } final public RaplaType<Attribute> getRaplaType() {return TYPE;} public RaplaType getRefType() { if (type == null) { return null; } if ( type.equals(AttributeType.CATEGORY)) { return Category.TYPE; } else if ( type.equals( AttributeType.ALLOCATABLE)) { return Allocatable.TYPE; } return null; } public AttributeType getType() { return type; } public void setType(AttributeType type) { checkWritable(); Object oldValue = defaultValue; if ( type.equals( AttributeType.CATEGORY)) { oldValue = getEntity("default.category", Category.class); } this.type = type; setDefaultValue(convertValue( oldValue)); } public MultiLanguageName getName() { return name; } public void setReadOnly() { super.setReadOnly( ); name.setReadOnly( ); } public String getName(Locale locale) { return name.getName(locale.getLanguage()); } public String getKey() { return key; } public void setConstraint(String key,Object constraint) { checkWritable(); setContraintWithoutWritableCheck(key, constraint); } public void setContraintWithoutWritableCheck(String key,Object constraint) { if ( getConstraintClass( key ) == Category.class || getConstraintClass( key ) == DynamicType.class) { String refID = "constraint." + key; if ( constraint == null) { removeWithKey( refID); } else if ( constraint instanceof Entity) { putEntity(refID,(Entity)constraint); } else if ( constraint instanceof String) { putId(refID,(String)constraint); } } if ( key.equals( ConstraintIds.KEY_MULTI_SELECT)) { multiSelect = true; } } @Override protected Class<? extends Entity> getInfoClass(String key) { Class<? extends Entity> infoClass = super.getInfoClass(key); if ( infoClass == null) { if ( key.equals( "default.category")) { return Category.class; } if ( key.startsWith( "constraint.")) { String constraintKey = key.substring( "constraint.".length()); Class<?> constraintClass = getConstraintClass( constraintKey); if ( !constraintClass.equals(String.class)) { @SuppressWarnings("unchecked") Class<? extends Entity> casted = (Class<? extends Entity>) constraintClass; return casted; } } } return infoClass; } public void setDefaultValue(Object object) { checkWritable(); if ( type.equals( AttributeType.CATEGORY)) { putEntity("default.category",(Entity)object); defaultValue = null; } else { defaultValue = (String) convertValue(object, AttributeType.STRING); } } public Object getConstraint(String key) { if ( key.equals(ConstraintIds.KEY_MULTI_SELECT)) { return multiSelect; } Class<?> constraintClass = getConstraintClass( key ); if ( constraintClass == Category.class || constraintClass == DynamicType.class) { @SuppressWarnings("unchecked") Class<? extends Entity> class1 = (Class<? extends Entity>) constraintClass; return getEntity("constraint." + key, class1); } return null; } public Class<?> getConstraintClass(String key) { if (key.equals(ConstraintIds.KEY_ROOT_CATEGORY)) { return Category.class; } if (key.equals(ConstraintIds.KEY_DYNAMIC_TYPE)) { return DynamicType.class; } if (key.equals(ConstraintIds.KEY_MULTI_SELECT)) { return Boolean.class; } return String.class; } public String[] getConstraintKeys() { if (type.equals( AttributeType.CATEGORY)) { return new String[] {ConstraintIds.KEY_ROOT_CATEGORY, ConstraintIds.KEY_MULTI_SELECT}; } if (type.equals( AttributeType.ALLOCATABLE)) { return new String[] {ConstraintIds.KEY_DYNAMIC_TYPE, ConstraintIds.KEY_MULTI_SELECT}; } else { return new String[0]; } } public void setKey(String key) { checkWritable(); this.key = key; if ( parent != null) { parent.keyChanged( this, key); } } public boolean isValid(Object obj) { return true; } public boolean isOptional() { return bOptional; } public void setOptional(boolean bOptional) { checkWritable(); this.bOptional = bOptional; } public Object defaultValue() { Object value; if ( type.equals( AttributeType.CATEGORY)) { value = getEntity("default.category", Category.class); } else { value = convertValue(defaultValue); } return value; } public boolean needsChange(Object value) { if (value == null) return false; if (type.equals( AttributeType.STRING )) { return !(value instanceof String); } if (type.equals( AttributeType.INT )) { return !(value instanceof Long); } if (type.equals( AttributeType.DATE )) { return !(value instanceof Date); } if (type.equals( AttributeType.BOOLEAN )) { return !(value instanceof Boolean); } if (type.equals( AttributeType.ALLOCATABLE )) { return !(value instanceof Allocatable); } if (type.equals( AttributeType.CATEGORY )) { if (!(value instanceof Category)) return true; Category temp = (Category) value; // look if the attribute category is a ancestor of the value category Category rootCategory = (Category) getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); if ( rootCategory != null) { boolean change = !rootCategory.isAncestorOf( temp ); return change; } return false; } return false; } public Object convertValue(Object value) { return convertValue(value, type); } private Object convertValue(Object value, AttributeType type) { if (type.equals( AttributeType.STRING )) { if (value == null) return null; if (value instanceof Date) { return new SerializableDateTimeFormat().formatDate( (Date) value); } // if (value instanceof Category) // { // return ((Category) value).get // } return value.toString(); } if (type.equals( AttributeType.DATE )) { if (value == null) return null; else if (value instanceof Date) return value; try { return new SerializableDateTimeFormat().parseDate( value.toString(), false); } catch (ParseDateException e) { return null; } } if (type.equals( AttributeType.INT )) { if (value == null) return null; if (value instanceof Boolean) return ((Boolean) value).booleanValue() ? new Long(1) : new Long(0); String str = value.toString().trim().toLowerCase(); try { return new Long(str); } catch (NumberFormatException ex) { return null; } } if (type.equals( AttributeType.BOOLEAN )) { if (value == null) return Boolean.FALSE; String str = value.toString().trim().toLowerCase(); if (str.equals("")) { return Boolean.FALSE; } if (str.equals("0") || str.equals("false")) return Boolean.FALSE; else return Boolean.TRUE; } if (type.equals( AttributeType.ALLOCATABLE)) { // we try to convert ids if ( value instanceof String) { Entity result = resolver.tryResolve( (String) value); if ( result != null && result instanceof Allocatable) { return (Allocatable) result; } } return null; } if (type.equals( AttributeType.CATEGORY )) { if (value == null) return null; Category rootCategory = (Category) getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); if (value instanceof Category) { Category temp = (Category) value; if ( rootCategory != null ) { if (rootCategory.isAncestorOf( temp )) { return value; } // if the category can't be found under the root then we check if we find a category path with the same keys List<String> keyPathRootCategory = ((CategoryImpl)rootCategory).getKeyPath( null); List<String> keyPath = ((CategoryImpl)temp).getKeyPath( null); List<String> nonCommonPath = new ArrayList<String>(); boolean differInKeys = false; // for ( int i=0;i<keyPath.size();i++) { String key = keyPath.get(i); String rootCatKey = keyPathRootCategory.size() > i ? keyPathRootCategory.get( i ) : null; if ( rootCatKey == null || !key.equals(rootCatKey)) { differInKeys = true; } if ( differInKeys) { nonCommonPath.add( key); } } Category parentCategory = rootCategory; Category newCategory = null; //we first check for the whole keypath this covers root changes from b to c, when c contains the b substructure including b // a // / \ // |b| |c| // / / // d b // / // d for ( String key: nonCommonPath) { newCategory = parentCategory.getCategory( key); if ( newCategory == null) { break; } else { parentCategory = newCategory; } } //if we don't find a category we also check if a keypath that contains on less entry // covers root changes from b to c when c contains directly the b substructure but not b itself // a // / \ // |b| |c| // / / // d d // if ( newCategory == null && nonCommonPath.size() > 1) { List<String> subList = nonCommonPath.subList(1, nonCommonPath.size()); for ( String key: subList) { newCategory = parentCategory.getCategory( key); if ( newCategory == null) { break; } else { parentCategory = newCategory; } } } return newCategory; } } else if ( value instanceof String) { Entity result = resolver.tryResolve( (String) value); if ( result != null && result instanceof Category) { return (Category) result; } } if ( rootCategory != null) { Category category = rootCategory.getCategory(value.toString()); if ( category == null) { return null; } return category; } } return null; } public String getAnnotation(String key) { return annotations.get(key); } public String getAnnotation(String key, String defaultValue) { String annotation = getAnnotation( key ); return annotation != null ? annotation : defaultValue; } public void setAnnotation(String key,String annotation) throws IllegalAnnotationException { checkWritable(); if (annotation == null) { annotations.remove(key); return; } // multiselect is now a constraint so we keep this for backward compatibility with old data format if ( key.equals( ConstraintIds.KEY_MULTI_SELECT)) { multiSelect = annotation != null && annotation.equalsIgnoreCase("true"); } else { annotations.put(key,annotation); } } public String[] getAnnotationKeys() { return annotations.keySet().toArray(RaplaObject.EMPTY_STRING_ARRAY); } public Attribute clone() { AttributeImpl clone = new AttributeImpl(); super.deepClone(clone); clone.name = (MultiLanguageName) name.clone(); @SuppressWarnings("unchecked") HashMap<String,String> annotationClone = (HashMap<String,String>) ((HashMap<String,String>) annotations).clone(); clone.annotations = annotationClone; clone.type = getType(); clone.multiSelect = multiSelect; clone.setKey(getKey()); clone.setOptional(isOptional()); String[] constraintKeys = getConstraintKeys(); for ( int i = 0;i < constraintKeys.length; i++) { String key = constraintKeys[ i ]; clone.setConstraint( key, getConstraint(key)); } clone.setDefaultValue( defaultValue()); return clone; } public String toString() { MultiLanguageName name = getName(); if (name != null) { return name.toString()+ " ID='" + getId() + "'"; } else { return getKey() + " " + getId(); } } @SuppressWarnings("deprecation") static public Object parseAttributeValue(Attribute attribute,String text) throws RaplaException { AttributeType type = attribute.getType(); final String trim = text.trim(); EntityResolver resolver = ((AttributeImpl)attribute).getResolver(); if (type.equals( AttributeType.STRING )) { return text; } else if (type.equals( AttributeType.ALLOCATABLE)) { String path = trim; if (path.length() == 0) { return null; } if ( resolver != null) { if ( resolver.tryResolve( path, Allocatable.class) != null) { return path; } } if (org.rapla.storage.OldIdMapping.isTextId(Allocatable.TYPE,path)) { return path ; } return null; } else if (type.equals( AttributeType.CATEGORY )) { String path = trim; if (path.length() == 0) { return null; } if ( resolver != null) { if ( resolver.tryResolve( path) != null) { return path; } } if (org.rapla.storage.OldIdMapping.isTextId(Category.TYPE,path) ) { String id = org.rapla.storage.OldIdMapping.getId( Category.TYPE, path); return id ; } else { CategoryImpl rootCategory = (CategoryImpl)attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); if (rootCategory == null) { //System.out.println( attribute.getConstraintKeys()); throw new RaplaException("Can't find " + ConstraintIds.KEY_ROOT_CATEGORY + " for attribute " + attribute); } Category categoryFromPath = rootCategory.getCategoryFromPath(path); if ( categoryFromPath == null) { // TODO call convert that tries to convert from a string path } return categoryFromPath; } } else if (trim.length() == 0) { return null; } else if (type.equals(AttributeType.BOOLEAN)) { return trim.equalsIgnoreCase("true") || trim.equals("1") ? Boolean.TRUE : Boolean.FALSE; } else if (type.equals( AttributeType.DATE )) { try { return new SerializableDateTimeFormat().parseDate( trim, false); } catch (ParseDateException e) { throw new RaplaException( e.getMessage(), e); } } else if (type.equals( AttributeType.INT)) { try { return new Long( trim ); } catch (NumberFormatException ex) { throw new RaplaException( ex.getMessage()); } } throw new RaplaException("Unknown attribute type: " + type ); } public static String attributeValueToString( Attribute attribute, Object value, boolean idOnly) throws EntityNotFoundException { AttributeType type = attribute.getType(); if (type.equals( AttributeType.ALLOCATABLE )) { return ((Entity)value).getId().toString(); } if (type.equals( AttributeType.CATEGORY )) { CategoryImpl rootCategory = (CategoryImpl) attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); if ( idOnly) { return ((Entity)value).getId().toString(); } else { return rootCategory.getPathForCategory((Category)value) ; } } else if (type.equals( AttributeType.DATE )) { return new SerializableDateTimeFormat().formatDate( (Date)value ) ; } else { return value.toString() ; } } static public class IntStrategy { String[] constraintKeys = new String[] {"min","max"}; public String[] getConstraintKeys() { return constraintKeys; } public boolean needsChange(Object value) { return !(value instanceof Long); } public Object convertValue(Object value) { if (value == null) return null; if (value instanceof Boolean) return ((Boolean) value).booleanValue() ? new Long(1) : new Long(0); String str = value.toString().trim().toLowerCase(); try { return new Long(str); } catch (NumberFormatException ex) { return null; } } } public String getValueAsString(Locale locale,Object value) { if (value == null) return ""; if (value instanceof Category) { Category rootCategory = (Category) getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); return ((Category) value).getPath(rootCategory, locale); } if (value instanceof Allocatable) { return ((Allocatable) value).getName( locale); } if (value instanceof Date) { return DateTools.formatDate((Date) value, locale); } if (value instanceof Boolean) { return getBooleanTranslation(locale, (Boolean) value); } else { return value.toString(); } } public static String getBooleanTranslation(Locale locale, Boolean value) { if (locale == null) { locale = Locale.getDefault(); } String language = locale.getLanguage(); if ( (Boolean) value) { return TRUE_TRANSLATION.getName( language); } else { return FALSE_TRANSLATION.getName( language); } } public String toStringValue( Object value) { String stringValue = null; RaplaType refType = getRefType(); if (refType != null) { if ( value instanceof Entity) { stringValue = ((Entity) value).getId(); } else { stringValue = value.toString(); } } else if (type.equals( AttributeType.DATE )) { return new SerializableDateTimeFormat().formatDate((Date)value); } else if ( value != null) { stringValue = value.toString(); } return stringValue; } public Object fromString(EntityResolver resolver, String value) throws EntityNotFoundException { RaplaType refType = getRefType(); if (refType != null) { Entity resolved = resolver.resolve( value ); return resolved; } Object result; try { result = parseAttributeValue(this, value); } catch (RaplaException e) { throw new IllegalStateException("Value not parsable"); } return result; } }
04900db4-rob
src/org/rapla/entities/dynamictype/internal/AttributeImpl.java
Java
gpl3
24,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.entities.dynamictype.internal; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.rapla.components.util.Assert; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.components.util.iterator.NestedIterator; import org.rapla.entities.ReadOnlyException; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.ClassificationFilterRule; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.UnresolvableReferenceExcpetion; public final class ClassificationFilterImpl implements ClassificationFilter ,DynamicTypeDependant ,EntityReferencer ,java.io.Serializable { // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; private String typeId; transient boolean readOnly; List<ClassificationFilterRuleImpl> list = new LinkedList<ClassificationFilterRuleImpl>(); transient boolean arrayUpToDate = false; transient ClassificationFilterRuleImpl[] rulesArray; transient EntityResolver resolver; ClassificationFilterImpl() { } ClassificationFilterImpl(DynamicTypeImpl dynamicType) { typeId = dynamicType.getId(); } public void setResolver( EntityResolver resolver) { this.resolver = resolver; for (Iterator<ClassificationFilterRuleImpl> it=list.iterator();it.hasNext();) { it.next().setResolver( resolver ); } } public DynamicType getType() { DynamicType type = resolver.tryResolve(typeId, DynamicType.class); if ( type == null) { throw new UnresolvableReferenceExcpetion(typeId); } //DynamicType dynamicType = (DynamicType) referenceHandler.getEntity("parent"); return type; } @Override public Iterable<ReferenceInfo> getReferenceInfo() { return new IteratorChain<ReferenceInfo> ( Collections.singleton( new ReferenceInfo(typeId, DynamicType.class)) ,new NestedIterator<ReferenceInfo,ClassificationFilterRuleImpl>( list ) { public Iterable<ReferenceInfo> getNestedIterator(ClassificationFilterRuleImpl obj) { return obj.getReferenceInfo(); } } ); } public void setReadOnly(boolean enable) { this.readOnly = enable; } public boolean isReadOnly() { return readOnly; } public void checkWritable() { if ( readOnly ) throw new ReadOnlyException( this ); } public void addRule(String attributeName, Object[][] conditions) { setRule(ruleSize(), attributeName, conditions); } public void setRule(int index, String attributeName,Object[][] conditions) { setRule( index, getType().getAttribute( attributeName), conditions); } public void setRule(int index, Attribute attribute,Object[][] conditions) { checkWritable(); Assert.notNull( attribute ); String[] operators = new String[conditions.length]; Object[] ruleValues = new Object[conditions.length]; for (int i=0;i<conditions.length;i++) { operators[i] = conditions[i][0].toString().trim(); checkOperator(operators[i]); ruleValues[i] = conditions[i][1]; } ClassificationFilterRuleImpl rule = new ClassificationFilterRuleImpl( attribute, operators, ruleValues); if ( resolver != null) { rule.setResolver( resolver); } // System.out.println("Rule " + index + " for '" + dynamicType + "' added. " + " Attribute " + rule.attribute + " Params: " + rule.params[0]); if (index < list.size() ) list.set(index, rule); else list.add(index, rule); arrayUpToDate = false; } private void checkOperator(String operator) { if (operator.equals("<")) return; if (operator.equals(">")) return; if (operator.equals("=")) return; if (operator.equals("contains")) return; if (operator.equals("starts")) return; if (operator.equals("is")) return; if (operator.equals("<=")) return; if (operator.equals(">=")) return; if (operator.equals("<>")) return; throw new IllegalArgumentException("operator '" + operator + "' not supported!"); } public void addEqualsRule( String attributeName, Object object ) { addRule( attributeName, new Object[][] {{"=",object}}); } public void addIsRule( String attributeName, Object object ) { addRule( attributeName, new Object[][] {{"is",object}}); } public int ruleSize() { return list.size(); } public Iterator<? extends ClassificationFilterRule> ruleIterator() { return list.iterator(); } public void removeAllRules() { checkWritable(); list.clear(); arrayUpToDate = false; } public void removeRule(int index) { checkWritable(); list.remove(index); arrayUpToDate = false; //System.out.println("Rule " + index + " for '" + dynamicType + "' removed."); } private ClassificationFilterRuleImpl[] getRules() { if (!arrayUpToDate) rulesArray = list.toArray(new ClassificationFilterRuleImpl[0]); arrayUpToDate = true; return rulesArray; } public boolean matches(Classification classification) { if (!getType().equals(classification.getType())) return false; ClassificationFilterRuleImpl[] rules = getRules(); for (int i=0;i<rules.length;i++) { ClassificationFilterRuleImpl rule = rules[i]; Attribute attribute = rule.getAttribute(); if ( attribute != null) { Collection<Object> values = classification.getValues(attribute); if ( values.size() == 0) { if (!rule.matches( null)) { return false; } } else { boolean matchesOne= false; for (Object value: values) { if (rule.matches( value)) matchesOne = true; } if ( !matchesOne ) { return false; } } } } return true; } boolean hasType(DynamicType type) { return getType().equals( type); } public boolean needsChange(DynamicType newType) { if (!hasType( newType )) return false; if ( !newType.getKey().equals( getType().getKey())) return true; ClassificationFilterRuleImpl[] rules = getRules(); for (int i=0;i<rules.length;i++) { ClassificationFilterRuleImpl rule = rules[i]; Attribute attribute = rule.getAttribute(); if ( attribute == null ) { return true; } String id = attribute.getId(); if (((DynamicTypeImpl)getType()).hasAttributeChanged( (DynamicTypeImpl)newType , id)) return true; Attribute newAttribute = newType.getAttribute(attribute.getKey()); if ( newAttribute == null) { return true; } if (rule.needsChange(newAttribute)) { return true; } } return false; } public void commitChange(DynamicType type) { if (!hasType(type)) return; Iterator<ClassificationFilterRuleImpl> it = list.iterator(); while (it.hasNext()) { ClassificationFilterRuleImpl rule = it.next(); Attribute attribute = rule.getAttribute(); if ( attribute == null ) { it.remove(); continue; } Object id = attribute.getId(); Attribute typeAttribute = ((DynamicTypeImpl)type).findAttributeForId(id ); if (typeAttribute == null) { it.remove(); } else { rule.commitChange(typeAttribute); } } arrayUpToDate = false; } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { throw new CannotExistWithoutTypeException(); } public ClassificationFilterImpl clone() { ClassificationFilterImpl clone = new ClassificationFilterImpl((DynamicTypeImpl)getType()); clone.resolver = resolver; clone.list = new LinkedList<ClassificationFilterRuleImpl>(); Iterator<ClassificationFilterRuleImpl> it = list.iterator(); while (it.hasNext()) { ClassificationFilterRuleImpl rule = it.next(); Attribute attribute = rule.getAttribute(); if ( attribute != null) { ClassificationFilterRuleImpl clone2 =new ClassificationFilterRuleImpl(attribute,rule.getOperators(),rule.getValues()); clone.list.add(clone2); } } clone.readOnly = false;// clones are always writable clone.arrayUpToDate = false; return clone; } public ClassificationFilter[] toArray() { return new ClassificationFilter[] {this}; } public String toString() { StringBuilder buf = new StringBuilder(); buf.append(getType().getKey() +": "); for ( ClassificationFilterRule rule: getRules()) { buf.append(rule.toString()); buf.append(", "); } return buf.toString(); } }
04900db4-rob
src/org/rapla/entities/dynamictype/internal/ClassificationFilterImpl.java
Java
gpl3
11,142
/** * */ package org.rapla.entities.dynamictype.internal; import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import org.rapla.components.util.DateTools; import org.rapla.components.util.TimeInterval; import org.rapla.entities.Category; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.Named; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classification; import org.rapla.rest.GwtIncompatible; /** * Enables text replacement of variables like {name} {email} with corresponding attribute values * Also some functions like {substring(name,1,2)} are available for simple text processing * */ public class ParsedText implements Serializable { private static final long serialVersionUID = 1; /** the terminal format elements*/ transient List<String> nonVariablesList; /** the variable format elements*/ transient List<Function> variablesList ; // used for fast storage of text without variables transient private String first; String formatString; ParsedText() { } public ParsedText(String formatString) { this.formatString = formatString; } public void init( ParseContext context) throws IllegalAnnotationException { variablesList = new ArrayList<Function>(); nonVariablesList = new ArrayList<String>(); int pos = 0; int length = formatString.length(); List<String> variableContent = new ArrayList<String>(); while (pos < length) { int start = formatString.indexOf('{',pos) + 1; if (start < 1) { nonVariablesList.add(formatString.substring(pos, length )); break; } int end = formatString.indexOf('}',start); if (end < 1 ) throw new IllegalAnnotationException("Closing bracket } missing! in " + formatString); nonVariablesList.add(formatString.substring(pos, start -1)); String key = formatString.substring(start,end).trim(); variableContent.add( key ); pos = end + 1; } for ( String content: variableContent) { Function func =parseFunctions(context,content); variablesList.add( func); } if ( variablesList.isEmpty() ) { if (nonVariablesList.size()>0) { first = nonVariablesList.iterator().next(); } variablesList = null; nonVariablesList = null; } } public void updateFormatString(ParseContext context) { formatString = getExternalRepresentation(context); } public String getExternalRepresentation(ParseContext context) { if ( nonVariablesList == null) { return first; } StringBuffer buf = new StringBuffer(); for (int i=0; i<nonVariablesList.size(); i++) { buf.append(nonVariablesList.get(i)); if ( i < variablesList.size() ) { Function variable = variablesList.get(i); String representation = variable.getRepresentation(context); buf.append("{"); buf.append( representation); buf.append("}"); } } return buf.toString(); } public String formatName(EvalContext context) { if ( nonVariablesList == null) { return first; } StringBuffer buf = new StringBuffer(); for (int i=0; i<nonVariablesList.size(); i++) { buf.append(nonVariablesList.get(i)); if ( i < variablesList.size()) { Function function = variablesList.get(i); Object result = function.eval(context); String stringResult = toString(result, context); buf.append( stringResult); } } return buf.toString(); } Function parseFunctions(ParseContext context,String content) throws IllegalAnnotationException { StringBuffer functionName = new StringBuffer(); for ( int i=0;i<content.length();i++) { char c = content.charAt(i); if ( c == '(' ) { int depth = 0; for ( int j=i+1;j<content.length();j++) { if ( functionName.length() == 0) { throw new IllegalAnnotationException("Function name missing"); } char c2 = content.charAt(j); if ( c2== ')') { if ( depth == 0) { String recursiveContent = content.substring(i+1,j); String function = functionName.toString(); return parseArguments( context,function,recursiveContent); } else { depth--; } } if ( c2 == '(' ) { depth++; } } } else if ( c== ')') { throw new IllegalAnnotationException("Opening parenthis missing."); } else { functionName.append( c); } } String variableName = functionName.toString().trim(); if ( variableName.startsWith("'") && (variableName.endsWith("'")) || (variableName.startsWith("\"") && variableName.endsWith("\"") ) && variableName.length() > 1) { String constant = variableName.substring(1, variableName.length() - 1); return new StringVariable(constant); } Function varFunction = context.resolveVariableFunction( variableName); if (varFunction != null) { return varFunction; } else { try { Long l = Long.parseLong( variableName.trim() ); return new IntVariable( l); } catch (NumberFormatException ex) { } // try // { // Double d = Double.parseDouble( variableName); // } catch (NumberFormatException ex) // { // } throw new IllegalAnnotationException("Attribute for key '" + variableName + "' not found. You have probably deleted or renamed the attribute. " ); } } private Function parseArguments(ParseContext context,String functionName, String content) throws IllegalAnnotationException { int depth = 0; List<Function> args = new ArrayList<Function>(); StringBuffer currentArg = new StringBuffer(); for ( int i=0;i<content.length();i++) { char c = content.charAt(i); if ( c == '(' ) { depth++; } else if ( c == ')' ) { depth --; } if ( c != ',' || depth > 0) { currentArg.append( c); } if ( depth == 0) { if ( c == ',' || i == content.length()-1) { String arg = currentArg.toString(); Function function = parseFunctions(context,arg); args.add(function); currentArg = new StringBuffer(); } } } if ( functionName.equals("key")) { return new KeyFunction(args); } if ( functionName.equals("parent")) { return new ParentFunction(args); } if ( functionName.equals("substring")) { return new SubstringFunction(args); } if ( functionName.equals("if")) { return new IfFunction(args); } if ( functionName.equals("equals")) { return new EqualsFunction(args); } else { throw new IllegalAnnotationException("Unknown function '"+ functionName + "'" ); } //return new SubstringFunction(functionName, args); } static public abstract class Function { String name; List<Function> args; public Function( String name,List<Function> args ) { this.name = name; this.args = args; } public Function(String name) { this.name = name; this.args = Collections.emptyList(); } protected String getName() { return name; } public abstract Object eval(EvalContext context); public String getRepresentation( ParseContext context) { StringBuffer buf = new StringBuffer(); buf.append(getName()); for ( int i=0;i<args.size();i++) { if ( i == 0) { buf.append("("); } else { buf.append(","); } buf.append( args.get(i).getRepresentation(context)); if ( i == args.size() - 1) { buf.append(")"); } } return buf.toString(); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(getName()); for ( int i=0;i<args.size();i++) { if ( i == 0) { buf.append("("); } else { buf.append(", "); } buf.append( args.get(i).toString()); if ( i == args.size() - 1) { buf.append(")"); } } return buf.toString(); } } class KeyFunction extends Function { Function arg; public KeyFunction( List<Function> args) throws IllegalAnnotationException { super( "key", args); if ( args.size() != 1) { throw new IllegalAnnotationException("Key Function expects one argument!"); } arg = args.get(0); //testMethod(); } @GwtIncompatible private void testMethod() throws IllegalAnnotationException { Method method; try { Class<? extends Function> class1 = arg.getClass(); method = class1.getMethod("eval", new Class[] {EvalContext.class}); } catch (Exception e) { String message = e.getMessage(); throw new IllegalAnnotationException( "Could not parse method for internal error : " + message); } if ( !method.getReturnType().isAssignableFrom(Attribute.class)) { if ( !method.getReturnType().isAssignableFrom(Category.class)) { throw new IllegalAnnotationException("Key Function expects an attribute variable or a function which returns a category"); } } } @Override public String eval(EvalContext context) { Object obj = arg.eval( context); if ( obj == null || !(obj instanceof RaplaObject)) { return ""; } RaplaObject raplaObject = (RaplaObject) obj; RaplaType raplaType = raplaObject.getRaplaType(); if ( raplaType == Category.TYPE) { Category category = (Category) raplaObject; String key = category.getKey(); return key; } else if ( raplaType == Attribute.TYPE) { Classification classification = context.getClassification(); Object result = classification.getValue((Attribute) raplaObject); if ( result instanceof Category) { String key = ((Category) result).getKey(); return key; } } return ""; } } class IntVariable extends Function { Long l; public IntVariable( Long l) { super( "long"); this.l = l; } @Override public Long eval(EvalContext context) { return l; } public String getRepresentation( ParseContext context) { return l.toString(); } public String toString() { return l.toString(); } } class StringVariable extends Function { String s; public StringVariable( String s) { super( "string"); this.s = s; } @Override public String eval(EvalContext context) { return s; } public String getRepresentation( ParseContext context) { return "\"" + s.toString() + "\""; } public String toString() { return s.toString(); } } class ParentFunction extends Function { Function arg; public ParentFunction( List<Function> args) throws IllegalAnnotationException { super( "parent", args); if ( args.size() != 1) { throw new IllegalAnnotationException("Parent Function expects one argument!"); } arg = args.get(0); //testMethod(); } @GwtIncompatible private void testMethod() throws IllegalAnnotationException { Method method; try { Class<? extends Function> class1 = arg.getClass(); method = class1.getMethod("eval", new Class[] {EvalContext.class}); } catch (Exception e) { throw new IllegalAnnotationException( "Could not parse method for internal error : " + e.getMessage()); } if ( !method.getReturnType().isAssignableFrom(Attribute.class)) { if ( !method.getReturnType().isAssignableFrom(Category.class)) { throw new IllegalAnnotationException("Parent Function expects an attribute variable or a function which returns a category"); } } } @Override public Category eval(EvalContext context) { Object obj = arg.eval( context); if ( obj == null || !(obj instanceof RaplaObject)) { return null; } RaplaObject raplaObject = (RaplaObject)obj; RaplaType raplaType = raplaObject.getRaplaType(); if ( raplaType == Category.TYPE) { Category category = (Category) raplaObject; return category.getParent(); } else if ( raplaType == Attribute.TYPE) { Classification classification = context.getClassification(); Object result = classification.getValue((Attribute) raplaObject); if ( result instanceof Category) { return ((Category) result).getParent(); } } return null; } } class SubstringFunction extends Function { Function content; Function start; Function end; public SubstringFunction( List<Function> args) throws IllegalAnnotationException { super( "substring", args); if ( args.size() != 3) { throw new IllegalAnnotationException("Substring Function expects 3 argument!"); } content = args.get(0); start = args.get(1); end = args.get(2); //testMethod(); } @GwtIncompatible private void testMethod() throws IllegalAnnotationException { { Method method; try { Class<? extends Function> class1 = start.getClass(); method = class1.getMethod("eval", new Class[] {EvalContext.class}); } catch (Exception e) { throw new IllegalAnnotationException( "Could not parse method for internal error : " + e.getMessage()); } if ( !method.getReturnType().isAssignableFrom(Long.class)) { throw new IllegalAnnotationException( "Substring method expects a Long parameter as second argument"); } } { Method method; try { Class<? extends Function> class1 = end.getClass(); method = class1.getMethod("eval", new Class[] {EvalContext.class}); } catch (Exception e) { throw new IllegalAnnotationException( "Could not parse method for internal error : " + e.getMessage()); } if ( !method.getReturnType().isAssignableFrom(Long.class)) { throw new IllegalAnnotationException( "Substring method expects a Long parameter as third argument"); } } } @Override public String eval(EvalContext context) { Object result =content.eval( context); String stringResult = ParsedText.this.toString( result, context); if ( stringResult == null) { return stringResult; } Long firstIndex = (Long)start.eval( context); Long lastIndex = (Long) end.eval( context); if ( firstIndex == null) { return null; } else if ( lastIndex == null) { return stringResult.substring( Math.min(firstIndex.intValue(), stringResult.length()) ); } else { return stringResult.substring( Math.min(firstIndex.intValue(), stringResult.length()) , Math.min(lastIndex.intValue(), stringResult.length()) ); } } } class IfFunction extends Function { Function condition; Function conditionTrue; Function conditionFalse; public IfFunction( List<Function> args) throws IllegalAnnotationException { super( "if", args); if ( args.size() != 3) { throw new IllegalAnnotationException("if function expects 3 argument!"); } condition = args.get(0); conditionTrue = args.get(1); conditionFalse = args.get(2); testMethod(); } /** * @throws IllegalAnnotationException */ private void testMethod() throws IllegalAnnotationException { } @Override public Object eval(EvalContext context) { Object condResult =condition.eval( context); Object resultCond = ParsedText.this.getValueForIf( condResult, context); boolean isTrue; if ( resultCond != null) { isTrue = Boolean.parseBoolean(resultCond.toString()); } else { isTrue = false; } Function resultFunction = isTrue ? conditionTrue : conditionFalse; Object result = resultFunction.eval(context); return result; } } class EqualsFunction extends Function { Function arg1; Function arg2; public EqualsFunction( List<Function> args) throws IllegalAnnotationException { super( "equals", args); if ( args.size() != 2) { throw new IllegalAnnotationException("equals function expects 2 argument!"); } arg1 = args.get(0); arg2 = args.get(1); testMethod(); } @SuppressWarnings("unused") private void testMethod() throws IllegalAnnotationException { } @Override public Boolean eval(EvalContext context) { Object evalResult1 = arg1.eval( context); Object evalResult2 =arg2.eval( context); if ( evalResult1 == null || evalResult2 == null) { return evalResult1 == evalResult2; } return evalResult1.equals( evalResult2); } } private Object getValueForIf(Object result, EvalContext context) { if ( result instanceof Attribute) { Attribute attribute = (Attribute) result; Classification classification = context.getClassification(); return classification.getValue(attribute); } return result; } private String toString(Object result, EvalContext context) { if ( result == null) { return ""; } Locale locale = context.getLocale(); if ( result instanceof Collection) { StringBuffer buf = new StringBuffer(); Collection<?> collection = (Collection<?>) result; int i=0; for ( Object obj: collection) { if ( i>0) { buf.append(", "); } buf.append(toString(obj, context)); i++; } return buf.toString(); } else if ( result instanceof TimeInterval) { Date start = ((TimeInterval) result).getStart(); Date end = ((TimeInterval) result).getEnd(); if ( DateTools.cutDate( end ).equals( end)) { end = DateTools.subDay(end); } StringBuffer buf = new StringBuffer(); buf.append( DateTools.formatDate( start, locale)); if ( end != null && end.after(start)) { buf.append( "-"); buf.append( DateTools.formatDate( end, locale)); } return buf.toString(); } else if ( result instanceof Date) { Date date = (Date) result; StringBuffer buf = new StringBuffer(); buf.append( DateTools.formatDate( date, locale)); return buf.toString(); } else if ( result instanceof Attribute) { Attribute attribute = (Attribute) result; Classification classification = context.getClassification(); return classification.getValueAsString(attribute, locale); } else if ( result instanceof Named) { return ((Named) result).getName( locale); } return result.toString(); } public interface ParseContext { Function resolveVariableFunction(String variableName) throws IllegalAnnotationException; } static public class EvalContext { private Locale locale; public EvalContext( Locale locale) { this.locale = locale; } /** override this method if you can return a classification object in the context. Than the use of attributes is possible*/ public Classification getClassification() { return null; } public Locale getLocale() { return locale; } } }
04900db4-rob
src/org/rapla/entities/dynamictype/internal/ParsedText.java
Java
gpl3
19,559
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; public interface ConstraintIds{ String KEY_ROOT_CATEGORY="root-category"; String KEY_DYNAMIC_TYPE="dynamic-type"; String KEY_MULTI_SELECT = "multi-select"; }
04900db4-rob
src/org/rapla/entities/dynamictype/ConstraintIds.java
Java
gpl3
1,165
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; public interface DynamicTypeAnnotations { String KEY_NAME_FORMAT="nameformat"; String KEY_NAME_FORMAT_PLANNING="nameformat_planing"; String KEY_CLASSIFICATION_TYPE="classification-type"; String VALUE_CLASSIFICATION_TYPE_RESOURCE="resource"; String VALUE_CLASSIFICATION_TYPE_RESERVATION="reservation"; String VALUE_CLASSIFICATION_TYPE_PERSON="person"; String VALUE_CLASSIFICATION_TYPE_RAPLATYPE="rapla"; String KEY_COLORS="colors"; String VALUE_COLORS_AUTOMATED = "rapla:automated"; String VALUE_COLORS_COLOR_ATTRIBUTE = "color"; String VALUE_COLORS_DISABLED = "rapla:disabled"; String KEY_CONFLICTS="conflicts"; String VALUE_CONFLICTS_NONE="never"; String VALUE_CONFLICTS_ALWAYS="always"; String VALUE_CONFLICTS_WITH_OTHER_TYPES="withOtherTypes"; String KEY_TRANSFERED_TO_CLIENT = "transferedToClient"; String VALUE_TRANSFERED_TO_CLIENT_NEVER = "never"; String KEY_LOCATION="location"; }
04900db4-rob
src/org/rapla/entities/dynamictype/DynamicTypeAnnotations.java
Java
gpl3
1,936
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; import org.rapla.entities.Annotatable; import org.rapla.entities.Entity; import org.rapla.entities.MultiLanguageNamed; import org.rapla.entities.RaplaType; /** Attributes are to DynamicTypes, what properties are to Beans. Currently Rapla supports the following types: <li>string</li> <li>int</li> <li>date</li> <li>boolean</li> <li>rapla:category</li> @see DynamicType */ public interface Attribute extends Entity<Attribute>,MultiLanguageNamed,Annotatable { final RaplaType<Attribute> TYPE = new RaplaType<Attribute>(Attribute.class, "attribute"); AttributeType getType(); RaplaType getRefType(); /** Set the type of the Attribute. <strong>Warning:</strong> Changing the type after initialization can lead to data loss, if there are already classifications that use this attribute and the classification value can't be converted to the new type. Example a non numerical string can't be converted to an int.*/ void setType(AttributeType type); void setKey(String key); /** The Key is identifier in string-form. Keys could be helpfull for interaction with other modules. An Invoice-Plugin could work on attributes with a "price" key. Keys also allow for a better readability of the XML-File. Changing of a key is possible, but should be used with care. */ String getKey(); Object defaultValue(); /** converts the passed value to fit the attributes type. Example Conversions are: <ul> <li>to string: The result of the method toString() will be the new value.</li> <li>boolean to int: The new value will be 1 when the oldValue is true. Otherwise it is 0.</li> <li>other types to int: First the value will be converted to string-type. And then the trimmed string will be parsed for Integer-values. If that is not possible the new value will be null</li> <li>to boolean: First the value will be converted to string-type. If the trimmed string equals "0" or "false" the new value is false. Otherwise it is true</li> </ul> */ Object convertValue(Object oldValue); /** Checks if the passed value matches the attribute type or needs conversion. @see #convertValue */ boolean needsChange(Object value); boolean isValid(Object object); boolean isOptional(); void setOptional(boolean bOptional); Object getConstraint(String key); Class<?> getConstraintClass(String key); void setConstraint(String key,Object constraint); String[] getConstraintKeys(); DynamicType getDynamicType(); public static final Attribute[] ATTRIBUTE_ARRAY = new Attribute[0]; void setDefaultValue(Object value); }
04900db4-rob
src/org/rapla/entities/dynamictype/Attribute.java
Java
gpl3
3,766
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; /** Attributes are to DynamicTypes, what properties are to Beans. Currently Rapla supports the following types: <li>string</li> <li>int</li> <li>date</li> <li>boolean</li> <li>rapla:category</li> <li>rapla:allocatable</li> @see DynamicType */ public enum AttributeType { STRING("string"), INT("int"), DATE("date"), BOOLEAN("boolean"), CATEGORY("rapla:category"), ALLOCATABLE("rapla:allocatable"); private String type; private AttributeType(String type) { this.type = type; } public boolean is(AttributeType other) { if ( other == null) return false; return type.equals( other.type); } public static AttributeType findForString(String string ) { for (AttributeType type:values()) { if ( type.type.equals( string)) { return type; } } return null; } public String toString() { return type; } }
04900db4-rob
src/org/rapla/entities/dynamictype/AttributeType.java
Java
gpl3
2,006
package org.rapla.entities.dynamictype; public interface RaplaAnnotation { }
04900db4-rob
src/org/rapla/entities/dynamictype/RaplaAnnotation.java
Java
gpl3
79
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; /** This Interfaces is implemented by all Rapla-Objects that can * have classification information: Reservation, Resource, Person. * @see Classification */ public interface Classifiable { Classification getClassification(); void setClassification(Classification classification); final Classifiable[] CLASSIFIABLE_ARRAY = new Classifiable[0]; }
04900db4-rob
src/org/rapla/entities/dynamictype/Classifiable.java
Java
gpl3
1,352
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.dynamictype; public interface ClassificationFilterRule { public Attribute getAttribute(); public String[] getOperators(); public Object[] getValues(); }
04900db4-rob
src/org/rapla/entities/dynamictype/ClassificationFilterRule.java
Java
gpl3
1,133
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.rapla.framework.RaplaException; /** * Enumeration Pattern for all Rapla objects. You should not instanciate Objects of this type, * there is only one instance of RaplaType for each class of objects. You can get it via * the object interface. E.g. Reservation.TYPE or Allocatable.TYPE */ public class RaplaType<T> { private Class<T> type; private String localname; private static Map<Class<? extends RaplaObject>,RaplaType> registeredTypes = new HashMap<Class<? extends RaplaObject>,RaplaType>(); private static Map<String,RaplaType> registeredTypeNames = new HashMap<String,RaplaType>(); public RaplaType(Class<T> clazz, String localname) { // @SuppressWarnings("unchecked") // Class<? extends RaplaObject> clazz2 = clazz; this.type = clazz; this.localname = localname; if ( registeredTypes == null) { registeredTypes = new HashMap<Class<? extends RaplaObject>,RaplaType>(); registeredTypeNames = new HashMap<String,RaplaType>(); } if ( registeredTypes.get( clazz ) != null) { throw new IllegalStateException( "Type already registered"); } @SuppressWarnings("unchecked") Class<? extends RaplaObject> casted = (Class<? extends RaplaObject>) type; registeredTypes.put( casted, this); registeredTypeNames.put( localname, this); } static public RaplaType find( String typeName) throws RaplaException { RaplaType raplaType = registeredTypeNames.get( typeName); if (raplaType != null) { return raplaType; } throw new RaplaException("Cant find Raplatype for name" + typeName); } static public <T extends RaplaObject> RaplaType<T> get(Class<T> clazz) { @SuppressWarnings("unchecked") RaplaType<T> result = registeredTypes.get( clazz); return result; } public boolean is(RaplaType other) { if ( other == null) return false; return type.equals( other.type); } public String getLocalName() { return localname; } public String toString() { return type.getName(); } public boolean equals( Object other) { if ( !(other instanceof RaplaType)) return false; return is( (RaplaType)other); } public int hashCode() { return type.hashCode(); } public Class<T> getTypeClass() { return type; } @SuppressWarnings("unchecked") public static <T extends RaplaObject> Set<T> retainObjects(Collection<? extends RaplaObject> set,Collection<T> col) { HashSet<RaplaObject> tempSet = new HashSet<RaplaObject>(set.size()); tempSet.addAll(set); tempSet.retainAll(col); if (tempSet.size() >0) { HashSet<T> result = new HashSet<T>(); for ( RaplaObject t : tempSet) { result.add( (T)t); } return result; } else { return Collections.emptySet(); } } }
04900db4-rob
src/org/rapla/entities/RaplaType.java
Java
gpl3
4,117
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities; import java.util.Locale; public interface Named { String getName(Locale locale); }
04900db4-rob
src/org/rapla/entities/Named.java
Java
gpl3
1,057