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.storage.xml; public interface Namespaces { String RAPLA_NS = "http://rapla.sourceforge.net/rapla"; String RELAXNG_NS = "http://relaxng.org/ns/structure/1.0"; String DYNATT_NS = "http://rapla.sourceforge.net/dynamictype"; String EXTENSION_NS = "http://rapla.sourceforge.net/extension"; String ANNOTATION_NS = "http://rapla.sourceforge.net/annotation"; String[][] NAMESPACE_ARRAY = { {RAPLA_NS,"rapla"} ,{RELAXNG_NS,"relax"} ,{DYNATT_NS,"dynatt"} ,{EXTENSION_NS,"ext"} ,{ANNOTATION_NS,"doc"} }; }
04900db4-rob
src/org/rapla/storage/xml/Namespaces.java
Java
gpl3
1,521
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.Iterator; import org.rapla.components.util.Assert; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.ClassificationFilterRule; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; class ClassificationFilterWriter extends RaplaXMLWriter { public ClassificationFilterWriter(RaplaContext sm) throws RaplaException { super(sm); } public void printClassificationFilter(ClassificationFilter f) throws IOException,RaplaException { openTag("rapla:classificationfilter"); att("dynamictype", f.getType().getKey()); closeTag(); for (Iterator<? extends ClassificationFilterRule> it = f.ruleIterator();it.hasNext();) { ClassificationFilterRule rule = it.next(); printClassificationFilterRule(rule); } closeElement("rapla:classificationfilter"); } private void printClassificationFilterRule(ClassificationFilterRule rule) throws IOException,RaplaException { Attribute attribute = rule.getAttribute(); Assert.notNull( attribute ); String[] operators = rule.getOperators(); Object[] values = rule.getValues(); openTag("rapla:rule"); att("attribute", attribute.getKey()); closeTag(); for (int i=0;i<operators.length;i++) { openTag("rapla:orCond"); att("operator", operators[i]); closeTagOnLine(); if (values[i] != null) printAttributeValue(attribute, values[i]); closeElementOnLine("rapla:orCond"); println(); } closeElement("rapla:rule"); } }
04900db4-rob
src/org/rapla/storage/xml/ClassificationFilterWriter.java
Java
gpl3
2,753
package org.rapla.storage.xml; import java.util.HashMap; import java.util.Map; import org.rapla.entities.Category; 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.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Period; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.facade.Conflict; import org.rapla.framework.Provider; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaDefaultContext; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; import org.rapla.storage.IdCreator; import org.rapla.storage.impl.EntityStore; public class IOContext { protected Map<String,RaplaType> getLocalnameMap() { //WARNING We can't use RaplaType.getRegisteredTypes() because the class could not be registered on load time Map<String,RaplaType> localnameMap = new HashMap<String,RaplaType>(); localnameMap.put( Reservation.TYPE.getLocalName(), Reservation.TYPE); localnameMap.put( Appointment.TYPE.getLocalName(), Appointment.TYPE); localnameMap.put( Allocatable.TYPE.getLocalName(), Allocatable.TYPE); localnameMap.put( User.TYPE.getLocalName(), User.TYPE); localnameMap.put( Preferences.TYPE.getLocalName(), Preferences.TYPE); localnameMap.put( Period.TYPE.getLocalName(), Period.TYPE); localnameMap.put( Category.TYPE.getLocalName(), Category.TYPE); localnameMap.put( DynamicType.TYPE.getLocalName(), DynamicType.TYPE); localnameMap.put( Attribute.TYPE.getLocalName(), Attribute.TYPE); localnameMap.put( RaplaConfiguration.TYPE.getLocalName(), RaplaConfiguration.TYPE); localnameMap.put( RaplaMap.TYPE.getLocalName(), RaplaMap.TYPE); localnameMap.put( CalendarModelConfiguration.TYPE.getLocalName(), CalendarModelConfiguration.TYPE); localnameMap.put( Conflict.TYPE.getLocalName(), Conflict.TYPE); return localnameMap; } protected void addReaders(Map<RaplaType,RaplaXMLReader> readerMap,RaplaContext context) throws RaplaException { readerMap.put( Category.TYPE,new CategoryReader( context)); readerMap.put( Preferences.TYPE, new PreferenceReader(context) ); readerMap.put( DynamicType.TYPE, new DynamicTypeReader(context) ); readerMap.put( User.TYPE, new UserReader(context)); readerMap.put( Allocatable.TYPE, new AllocatableReader(context) ); readerMap.put( Period.TYPE, new PeriodReader(context) ); readerMap.put( Reservation.TYPE,new ReservationReader(context)); readerMap.put( RaplaConfiguration.TYPE, new RaplaConfigurationReader(context)); readerMap.put( RaplaMap.TYPE, new RaplaMapReader(context)); readerMap.put( CalendarModelConfiguration.TYPE, new RaplaCalendarSettingsReader(context) ); } protected void addWriters(Map<RaplaType,RaplaXMLWriter> writerMap,RaplaContext context) throws RaplaException { writerMap.put( Category.TYPE,new CategoryWriter(context)); writerMap.put( Preferences.TYPE,new PreferenceWriter(context) ); writerMap.put( DynamicType.TYPE,new DynamicTypeWriter(context)); writerMap.put( User.TYPE, new UserWriter(context) ); writerMap.put( Allocatable.TYPE, new AllocatableWriter(context) ); writerMap.put( Reservation.TYPE,new ReservationWriter(context)); writerMap.put( RaplaConfiguration.TYPE,new RaplaConfigurationWriter(context) ); writerMap.put( RaplaMap.TYPE, new RaplaMapWriter(context) ); writerMap.put( Preferences.TYPE, new PreferenceWriter(context) ); writerMap.put( CalendarModelConfiguration.TYPE, new RaplaCalendarSettingsWriter(context) ); } public RaplaDefaultContext createInputContext(RaplaContext parentContext, EntityStore store, IdCreator idTable) throws RaplaException { RaplaDefaultContext ioContext = new RaplaDefaultContext( parentContext); ioContext.put(EntityStore.class, store); ioContext.put(IdCreator.class,idTable); ioContext.put(PreferenceReader.LOCALNAMEMAPENTRY, getLocalnameMap()); Map<RaplaType,RaplaXMLReader> readerMap = new HashMap<RaplaType,RaplaXMLReader>(); ioContext.put(PreferenceReader.READERMAP, readerMap); addReaders( readerMap, ioContext); return ioContext; } public static TypedComponentRole<Boolean> PRINTID = new TypedComponentRole<Boolean>( IOContext.class.getName() + ".idonly"); public static TypedComponentRole<Provider<Category>> SUPERCATEGORY = new TypedComponentRole<Provider<Category>>( IOContext.class.getName() + ".supercategory"); public RaplaDefaultContext createOutputContext(RaplaContext parentContext, Provider<Category> superCategory,boolean includeIds) throws RaplaException { RaplaDefaultContext ioContext = new RaplaDefaultContext( parentContext); if ( includeIds) { ioContext.put(PRINTID, Boolean.TRUE); } if ( superCategory != null) { ioContext.put( SUPERCATEGORY, superCategory); } ioContext.put(PreferenceReader.LOCALNAMEMAPENTRY, getLocalnameMap()); Map<RaplaType,RaplaXMLWriter> writerMap = new HashMap<RaplaType,RaplaXMLWriter>(); ioContext.put(PreferenceWriter.WRITERMAP, writerMap); addWriters( writerMap, ioContext ); return ioContext; } }
04900db4-rob
src/org/rapla/storage/xml/IOContext.java
Java
gpl3
5,802
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; public class WrongXMLVersionException extends Exception { private static final long serialVersionUID = 1L; String version; public WrongXMLVersionException(String version) { super("Wrong Version Exception " + version); this.version = version; } public String getVersion() { return version; } }
04900db4-rob
src/org/rapla/storage/xml/WrongXMLVersionException.java
Java
gpl3
1,321
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.Collection; import java.util.HashSet; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXHandler; import org.rapla.components.util.xml.RaplaSAXParseException; import org.xml.sax.SAXException; class DelegationHandler implements RaplaSAXHandler { StringBuffer currentText = null; DelegationHandler parent = null; DelegationHandler delegate = null; int level = 0; int entryLevel = 0; Collection<DelegationHandler> childHandlers; private void setParent( DelegationHandler parent ) { this.parent = parent; } public void addChildHandler( DelegationHandler childHandler ) { if (childHandlers == null) childHandlers = new HashSet<DelegationHandler>(); childHandlers.add( childHandler ); childHandler.setParent( this ); } public void startElement(String namespaceURI, String localName, RaplaSAXAttributes atts) throws RaplaSAXParseException { //printToSystemErr( localName, atts ); if (delegate != null) { delegate.startElement( namespaceURI, localName, atts ); } else { level++; processElement( namespaceURI, localName, atts ); } } // protected void printToSystemErr( String localName, Attributes atts ) // { // int len = atts.getLength(); // StringBuffer buf = new StringBuffer(); // for ( int i = 0; i<len;i++) // { // buf.append( " "); // buf.append( atts.getLocalName( i )); // buf.append( "="); // buf.append( atts.getValue( i )); // // } // System.err.println(localName + buf.toString()); // } final public void endElement( String namespaceURI, String localName ) throws RaplaSAXParseException { if (delegate != null) { delegate.endElement( namespaceURI, localName); //After this call the delegate can be null again. } if (delegate == null) { processEnd( namespaceURI, localName ); //Check if end of delegation reached if (entryLevel == level && parent != null) { parent.stopDelegation(); } level--; } } final public void characters( char[] ch, int start, int length ) { if (delegate != null) { delegate.characters( ch, start, length ); } else { processCharacters( ch, start, length ); } } /** * @param namespaceURI * @param localName * @param atts * @throws RaplaSAXParseException */ public void processElement( String namespaceURI, String localName, RaplaSAXAttributes atts ) throws RaplaSAXParseException { } /** * @param namespaceURI * @param localName * @throws RaplaSAXParseException */ public void processEnd( String namespaceURI, String localName ) throws RaplaSAXParseException { } /* Call this method to delegate the processessing of the encountered element with all its subelements to another DelegationHandler. */ public final void delegateElement( DelegationHandler child, String namespaceURI, String localName, RaplaSAXAttributes atts ) throws RaplaSAXParseException { //System.out.println("Start delegation for " + localName); delegate = child; delegate.setDelegateLevel( level ); delegate.processElement( namespaceURI, localName, atts ); } private void stopDelegation() { delegate = null; } private void setDelegateLevel( int level ) { this.entryLevel = level; this.level = level; } public void startContent() { currentText = new StringBuffer(); } public String readContent() { if (currentText == null) return null; String result = currentText.toString(); currentText = null; return result; } public RaplaSAXParseException createSAXParseException( String message ) { return createSAXParseException( message, null); } public RaplaSAXParseException createSAXParseException( String message,Exception cause ) { return new RaplaSAXParseException( message, cause); } /** * @throws SAXException */ public void processCharacters( char ch[], int start, int length ) { if (currentText != null) currentText.append( ch, start, length ); } }
04900db4-rob
src/org/rapla/storage/xml/DelegationHandler.java
Java
gpl3
5,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.storage.xml; import java.util.ArrayList; import java.util.Collection; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; class ClassificationFilterReader extends RaplaXMLReader { DynamicType dynamicType; ClassificationFilter filter; Attribute attribute; String operator; Collection<ClassificationFilter> filterList = new ArrayList<ClassificationFilter>(); Collection<Object[]> conditions = new ArrayList<Object[]>(); int ruleCount; private boolean defaultResourceTypes = true; private boolean defaultEventTypes = true; public ClassificationFilterReader(RaplaContext sm) throws RaplaException { super(sm); } public void clear() { filterList.clear(); defaultResourceTypes = true; defaultEventTypes = true; } public ClassificationFilter[] getFilters() { return filterList.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY); } @Override public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts) throws RaplaSAXParseException { if (localName.equals("classificationfilter")) { String id = atts.getValue("dynamictypeidref"); if ( id != null) { dynamicType = resolve(DynamicType.TYPE,id); } else { String typeName = getString(atts,"dynamictype"); dynamicType = getDynamicType( typeName ); if (dynamicType == null) { getLogger().error("Error reading filter with " + DynamicType.TYPE.getLocalName() + " " + typeName,null); return; } } final String annotation = dynamicType.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); boolean eventType = annotation != null && annotation.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION); if (eventType ) { defaultEventTypes = false; } else { defaultResourceTypes = false; } filter = dynamicType.newClassificationFilter(); ruleCount = 0; filterList.add(filter); } if (localName.equals("rule")) { String id = atts.getValue("attributeidref"); if ( id != null) { attribute = resolve(Attribute.TYPE, id); } else { String attributeName = getString(atts,"attribute"); attribute = dynamicType.getAttribute(attributeName); if (attribute == null) { getLogger().error("Error reading filter with " + dynamicType +" Attribute: " + attributeName,null); return; } } conditions.clear(); } if (localName.equals("orCond")) { operator = getString(atts,"operator"); startContent(); } } @Override public void processEnd(String namespaceURI,String localName) throws RaplaSAXParseException { if (localName.equals("rule") && filter != null) { final Object[][] array = conditions.toArray(new Object[][] {} ); filter.setRule(ruleCount ++ ,attribute ,array ); } if (localName.equals("orCond") && attribute!= null) { Object value = parseAttributeValue(attribute, readContent().trim()); conditions.add(new Object[] {operator,value}); } } public boolean isDefaultResourceTypes() { return defaultResourceTypes; } public boolean isDefaultEventTypes() { return defaultEventTypes; } }
04900db4-rob
src/org/rapla/storage/xml/ClassificationFilterReader.java
Java
gpl3
5,209
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.Map; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; public class PreferenceWriter extends RaplaXMLWriter { public static final TypedComponentRole<Map<RaplaType,RaplaXMLWriter>> WRITERMAP = new TypedComponentRole<Map<RaplaType,RaplaXMLWriter>>( "org.rapla.storage.xml.writerMap"); public PreferenceWriter(RaplaContext sm) throws RaplaException { super(sm); } protected void printPreferences(Preferences preferences) throws IOException,RaplaException { if ( preferences != null && !preferences.isEmpty()) { openTag("rapla:preferences"); //printTimestamp( preferences); closeTag(); PreferencesImpl impl = (PreferencesImpl)preferences; for (String role:impl.getPreferenceEntries()) { Object entry = impl.getEntry(role); if ( entry instanceof String) { openTag("rapla:entry"); att("key", role ); att("value", (String)entry); closeElementTag(); } if ( entry instanceof RaplaObject) { openTag("rapla:entry"); att("key", role ); closeTag(); RaplaObject raplaObject = (RaplaObject)entry; RaplaType raplaType = raplaObject.getRaplaType(); RaplaXMLWriter writer = getWriterFor( raplaType); writer.writeObject( raplaObject ); closeElement("rapla:entry"); } } closeElement("rapla:preferences"); } } public void writeObject(RaplaObject object) throws IOException, RaplaException { printPreferences( (Preferences) object); } }
04900db4-rob
src/org/rapla/storage/xml/PreferenceWriter.java
Java
gpl3
3,086
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.ClassificationImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; class DynAttReader extends RaplaXMLReader { Classifiable classifiable; ClassificationImpl classification; Attribute attribute; public DynAttReader(RaplaContext context) throws RaplaException { super(context); } public void setClassifiable(Classifiable classifiable) { this.classifiable = classifiable; } @Override public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts) throws RaplaSAXParseException { if (level == entryLevel) { DynamicType dynamicType; String id = atts.getValue("idref"); if ( id!= null) { dynamicType = resolve(DynamicType.TYPE,id); } else { String typeName = Namespaces.EXTENSION_NS.equals(namespaceURI) ? "rapla:" + localName : localName; if ( typeName.equals("rapla:crypto")) { return; } dynamicType = getDynamicType(typeName); if (dynamicType == null) throw createSAXParseException( "Dynanic type with name '" + typeName + "' not found." ); } Classification newClassification = dynamicType.newClassification(false); classification = (ClassificationImpl)newClassification; classifiable.setClassification(classification); classification.setResolver( store); } if (level > entryLevel) { String id = atts.getValue("idref"); if ( id != null) { attribute = resolve(Attribute.TYPE,id); } else { attribute = classification.getAttribute(localName); } if (attribute == null) //ignore attributes not found in the classification return; startContent(); } } @Override public void processEnd(String namespaceURI,String localName) throws RaplaSAXParseException { if (level > entryLevel) { String content = readContent(); if (content != null) { Object value = parseAttributeValue(attribute, content); classification.addValue( attribute, value); } } } }
04900db4-rob
src/org/rapla/storage/xml/DynAttReader.java
Java
gpl3
3,742
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.internal.CalendarModelConfigurationImpl; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class RaplaCalendarSettingsReader extends RaplaXMLReader { CalendarModelConfiguration settings; String title; String view; Date selectedDate; Date startDate; Date endDate; boolean resourceRootSelected; ClassificationFilter[] filter; RaplaMapReader optionMapReader; ClassificationFilterReader classificationFilterHandler; List<String> idList; List<RaplaType> idTypeList; Map<String,String> optionMap; public RaplaCalendarSettingsReader(RaplaContext context) throws RaplaException { super( context ); optionMapReader= new RaplaMapReader(context); classificationFilterHandler = new ClassificationFilterReader(context); addChildHandler( optionMapReader ); addChildHandler( classificationFilterHandler ); } @Override public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts) throws RaplaSAXParseException { if (localName.equals("calendar")) { filter = null; classificationFilterHandler.clear(); title = getString( atts,"title"); view = getString( atts,"view"); selectedDate = getDate( atts, "date"); startDate = getDate( atts, "startdate"); endDate = getDate( atts, "enddate"); resourceRootSelected = getString(atts, "rootSelected", "false").equalsIgnoreCase("true"); idList = Collections.emptyList(); idTypeList = Collections.emptyList(); optionMap = Collections.emptyMap(); } if (localName.equals("selected")) { idList = new ArrayList<String>(); idTypeList = new ArrayList<RaplaType>(); } if (localName.equals("options")) { delegateElement( optionMapReader, namespaceURI, localName, atts); } if (localName.equals("filter")) { classificationFilterHandler.clear(); delegateElement( classificationFilterHandler, namespaceURI, localName, atts); } String refid = getString( atts, "idref", null); String keyref = getString( atts, "keyref", null); if ( refid != null) { RaplaType raplaType = getTypeForLocalName( localName ); String id = getId( raplaType, refid); idList.add( id); idTypeList.add( raplaType); } else if ( keyref != null) { DynamicType type = getDynamicType( keyref ); idList.add( type.getId()); idTypeList.add( DynamicType.TYPE); } } private Date getDate(RaplaSAXAttributes atts, String key ) throws RaplaSAXParseException { String dateString = getString( atts,key, null); if ( dateString != null) { return parseDate( dateString, false ); } else { return null; } } @Override public void processEnd(String namespaceURI,String localName) { if (localName.equals("calendar")) { boolean defaultResourceTypes = classificationFilterHandler.isDefaultResourceTypes(); boolean defaultEventTypes = classificationFilterHandler.isDefaultEventTypes(); settings = new CalendarModelConfigurationImpl( idList,idTypeList, resourceRootSelected,filter, defaultResourceTypes, defaultEventTypes,title,startDate, endDate, selectedDate, view, optionMap); } if (localName.equals("selected")) { } if (localName.equals("options")) { @SuppressWarnings("unchecked") Map<String,String> entityMap = optionMapReader.getEntityMap(); optionMap = entityMap; } if (localName.equals("filter")) { filter = classificationFilterHandler.getFilters(); } } public RaplaObject getType() { //reservation.getReferenceHandler().put() return settings; } }
04900db4-rob
src/org/rapla/storage/xml/RaplaCalendarSettingsReader.java
Java
gpl3
5,613
<body> Provides classes and interfaces for serialization and deserialization of the entities. </body>
04900db4-rob
src/org/rapla/storage/package.html
HTML
gpl3
104
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage; import org.rapla.framework.RaplaException; /** Imports the content of on store into another. Export does an import with source and destination exchanged. */ public interface ImportExportManager { void doImport() throws RaplaException; void doExport() throws RaplaException; CachableStorageOperator getSource() throws RaplaException; CachableStorageOperator getDestination() throws RaplaException; }
04900db4-rob
src/org/rapla/storage/ImportExportManager.java
Java
gpl3
1,381
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage; import org.rapla.entities.RaplaType; import org.rapla.framework.RaplaException; public interface IdCreator { public String createId(RaplaType raplaType) throws RaplaException; public String createId(RaplaType type, String seed) throws RaplaException; }
04900db4-rob
src/org/rapla/storage/IdCreator.java
Java
gpl3
1,238
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, of which license fullfill the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbsql.pre18; import java.io.BufferedWriter; import java.io.IOException; import java.io.StringWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.rapla.components.util.Assert; import org.rapla.components.util.DateTools; import org.rapla.components.util.xml.RaplaNonValidatedInput; import org.rapla.entities.Annotatable; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Period; import org.rapla.entities.domain.Permission; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.RepeatingType; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.ResourceAnnotations; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.domain.internal.PeriodImpl; import org.rapla.entities.domain.internal.PermissionImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.AttributeImpl; import org.rapla.entities.dynamictype.internal.ClassificationImpl; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.internal.UserImpl; import org.rapla.entities.storage.EntityResolver; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; import org.rapla.storage.OldIdMapping; import org.rapla.storage.StorageOperator; import org.rapla.storage.dbsql.TableDef; import org.rapla.storage.xml.CategoryReader; import org.rapla.storage.xml.PreferenceReader; import org.rapla.storage.xml.RaplaXMLReader; import org.rapla.storage.xml.RaplaXMLWriter; @Deprecated public class RaplaPre18SQL { private final List<RaplaTypeStorage> stores = new ArrayList<RaplaTypeStorage>(); private final Logger logger; RaplaContext context; PreferenceStorage preferencesStorage; PeriodStorage periodStorage; public RaplaPre18SQL( RaplaContext context) throws RaplaException{ this.context = context; logger = context.lookup( Logger.class); // The order is important. e.g. appointments can only be loaded if the reservation they are refering to are already loaded. stores.add(new CategoryStorage( context)); stores.add(new DynamicTypeStorage( context)); stores.add(new UserStorage( context)); stores.add(new AllocatableStorage( context)); stores.add(new PreferenceStorage( context)); ReservationStorage reservationStorage = new ReservationStorage( context); stores.add(reservationStorage); AppointmentStorage appointmentStorage = new AppointmentStorage( context); stores.add(appointmentStorage); // now set delegate because reservation storage should also use appointment storage reservationStorage.setAppointmentStorage( appointmentStorage); periodStorage = new PeriodStorage(context); } private List<OldEntityStorage<?>> getStoresWithChildren() { List<OldEntityStorage<?>> storages = new ArrayList<OldEntityStorage<?>>(); for ( RaplaTypeStorage store:stores) { storages.add( store); @SuppressWarnings("unchecked") Collection<OldEntityStorage<?>> subStores = store.getSubStores(); storages.addAll( subStores); } return storages; } protected Logger getLogger() { return logger; } synchronized public void loadAll(Connection con) throws SQLException,RaplaException { for (OldEntityStorage storage:stores) { load(con, storage); } load(con,periodStorage); for (Map.Entry<String,PeriodImpl> entry:periodStorage.getPeriods().entrySet()) { Period value = entry.getValue(); AllocatableImpl period = new AllocatableImpl(new Date(), new Date()); EntityResolver cache = periodStorage.getCache(); Classification classification = cache.getDynamicType(StorageOperator.PERIOD_TYPE).newClassification(); classification.setValue("name", value.getName()); classification.setValue("start",value.getStart()); classification.setValue("end",value.getEnd()); period.setClassification( classification); Permission newPermission = period.newPermission(); newPermission.setAccessLevel( Permission.READ); period.addPermission( newPermission); String id = entry.getKey(); period.setId(id); } } protected void load(Connection con, OldEntityStorage storage) throws SQLException, RaplaException { storage.setConnection(con); try { storage.loadAll(); } finally { storage.setConnection( null); } } public void createOrUpdateIfNecessary(Connection con, Map<String, TableDef> schema) throws SQLException, RaplaException { // Upgrade db if necessary for (OldEntityStorage<?> storage:getStoresWithChildren()) { storage.setConnection(con); try { storage.createOrUpdateIfNecessary( schema); } finally { storage.setConnection( null); } } } public Map<String, String> getIdColumns() { Map<String,String> idColumns = new LinkedHashMap<String,String>(); for (OldEntityStorage<?> storage:getStoresWithChildren()) { String tableName = storage.getTableName(); String idColumn =storage.getIdColumn(); if (idColumn != null) { idColumns.put(tableName, idColumn); } } return idColumns; } public void dropAll(Connection con) throws SQLException { List<OldEntityStorage<?>> storesWithChildren = getStoresWithChildren(); for (OldEntityStorage<?> storage:storesWithChildren) { storage.setConnection(con); try { storage.dropTable(); } finally { storage.setConnection( null); } } } } @Deprecated abstract class RaplaTypeStorage<T extends Entity<T>> extends OldEntityStorage<T> { RaplaType raplaType; RaplaTypeStorage( RaplaContext context, RaplaType raplaType, String tableName, String[] entries) throws RaplaException { super( context,tableName, entries ); this.raplaType = raplaType; } boolean canStore(Entity entity) { return entity.getRaplaType() == raplaType; } protected String getXML(RaplaObject type) throws RaplaException { RaplaXMLWriter dynamicTypeWriter = getWriterFor( type.getRaplaType()); StringWriter stringWriter = new StringWriter(); BufferedWriter bufferedWriter = new BufferedWriter(stringWriter); dynamicTypeWriter.setWriter( bufferedWriter ); dynamicTypeWriter.setSQL( true ); try { dynamicTypeWriter.writeObject(type); bufferedWriter.flush(); } catch (IOException ex) { throw new RaplaException( ex); } return stringWriter.getBuffer().toString(); } protected RaplaXMLReader processXML(RaplaType type, String xml) throws RaplaException { RaplaXMLReader reader = getReaderFor( type); if ( xml== null || xml.trim().length() <= 10) { throw new RaplaException("Can't load " + type); } String xmlWithNamespaces = RaplaXMLReader.wrapRaplaDataTag(xml); RaplaNonValidatedInput parser = getReader(); parser.read(xmlWithNamespaces, reader, logger); return reader; } } @Deprecated class PeriodStorage extends OldEntityStorage { Map<String,PeriodImpl> result = new LinkedHashMap<String,PeriodImpl>(); public PeriodStorage(RaplaContext context) throws RaplaException { super(context,"PERIOD",new String[] {"ID INTEGER NOT NULL PRIMARY KEY","NAME VARCHAR(255) NOT NULL","PERIOD_START DATETIME NOT NULL","PERIOD_END DATETIME NOT NULL"}); } public EntityResolver getCache() { return cache; } @Override protected void load(ResultSet rset) throws SQLException { String id = OldIdMapping.getId(Period.TYPE, rset.getInt(1)); String name = getString(rset,2, null); if ( name == null) { getLogger().warn("Name is null for " + id + ". Ignored"); } java.util.Date von = getDate(rset,3); java.util.Date bis = getDate(rset,4); PeriodImpl period = new PeriodImpl(name,von,bis); result.put(id, period); } Map<String,PeriodImpl> getPeriods() { return result; } } @Deprecated class CategoryStorage extends RaplaTypeStorage<Category> { Map<Category,Integer> orderMap = new HashMap<Category,Integer>(); Map<Category,String> categoriesWithoutParent = new TreeMap<Category,String>(new Comparator<Category>() { public int compare( Category o1, Category o2 ) { if ( o1.equals( o2)) { return 0; } int ordering1 = ( orderMap.get( o1 )).intValue(); int ordering2 = (orderMap.get( o2 )).intValue(); if ( ordering1 < ordering2) { return -1; } if ( ordering1 > ordering2) { return 1; } if (o1.hashCode() > o2.hashCode()) { return -1; } else { return 1; } } } ); public CategoryStorage(RaplaContext context) throws RaplaException { super(context,Category.TYPE, "CATEGORY",new String[] {"ID INTEGER NOT NULL PRIMARY KEY","PARENT_ID INTEGER KEY","CATEGORY_KEY VARCHAR(100) NOT NULL","DEFINITION TEXT NOT NULL","PARENT_ORDER INTEGER"}); } @Override public void createOrUpdateIfNecessary(Map<String, TableDef> schema) throws SQLException, RaplaException { super.createOrUpdateIfNecessary( schema); checkAndAdd(schema, "DEFINITION"); checkAndAdd(schema, "PARENT_ORDER"); checkAndRetype(schema, "DEFINITION"); } public RaplaXMLReader getReaderFor( RaplaType type) throws RaplaException { RaplaXMLReader reader = super.getReaderFor( type ); if ( type.equals( Category.TYPE ) ) { ((CategoryReader) reader).setReadOnlyThisCategory( true); } return reader; } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { String id = readId(rset, 1, Category.class); String parentId = readId(rset, 2, Category.class, true); String xml = getText( rset, 4 ); Integer order = getInt(rset, 5 ); CategoryImpl category; if ( xml != null && xml.length() > 10 ) { category = ((CategoryReader)processXML( Category.TYPE, xml )).getCurrentCategory(); //cache.remove( category ); } else { getLogger().warn("Category has empty xml field. Ignoring."); return; } category.setId( id); put( category ); orderMap.put( category, order); // parentId can also be null categoriesWithoutParent.put( category, parentId); } @Override public void loadAll() throws RaplaException, SQLException { categoriesWithoutParent.clear(); super.loadAll(); // then we rebuild the hierarchy Iterator<Map.Entry<Category,String>> it = categoriesWithoutParent.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Category,String> entry = it.next(); String parentId = entry.getValue(); Category category = entry.getKey(); Category parent; Assert.notNull( category ); if ( parentId != null) { parent = entityStore.resolve( parentId ,Category.class); } else { parent = getSuperCategory(); } Assert.notNull( parent ); parent.addCategory( category ); } } } @Deprecated class AllocatableStorage extends RaplaTypeStorage<Allocatable> { Map<String,Classification> classificationMap = new HashMap<String,Classification>(); Map<String,Allocatable> allocatableMap = new HashMap<String,Allocatable>(); AttributeValueStorage<Allocatable> resourceAttributeStorage; PermissionStorage permissionStorage; public AllocatableStorage(RaplaContext context ) throws RaplaException { super(context,Allocatable.TYPE,"RAPLA_RESOURCE",new String [] {"ID INTEGER NOT NULL PRIMARY KEY","TYPE_KEY VARCHAR(100) NOT NULL","OWNER_ID INTEGER","CREATION_TIME TIMESTAMP","LAST_CHANGED TIMESTAMP","LAST_CHANGED_BY INTEGER DEFAULT NULL"}); resourceAttributeStorage = new AttributeValueStorage<Allocatable>(context,"RESOURCE_ATTRIBUTE_VALUE", "RESOURCE_ID",classificationMap, allocatableMap); permissionStorage = new PermissionStorage( context, allocatableMap); addSubStorage(resourceAttributeStorage); addSubStorage(permissionStorage ); } @Override public void createOrUpdateIfNecessary( Map<String, TableDef> schema) throws SQLException, RaplaException { checkRenameTable( schema,"RESOURCE"); super.createOrUpdateIfNecessary( schema); checkAndAdd( schema, "OWNER_ID"); checkAndAdd( schema, "CREATION_TIME"); checkAndAdd( schema, "LAST_CHANGED"); checkAndAdd( schema, "LAST_CHANGED_BY"); checkAndConvertIgnoreConflictsField(schema); } protected void checkAndConvertIgnoreConflictsField(Map<String, TableDef> schema) throws SQLException, RaplaException { TableDef tableDef = schema.get(tableName); String columnName = "IGNORE_CONFLICTS"; if (tableDef.getColumn(columnName) != null) { getLogger().warn("Patching Database for table " + tableName + " converting " + columnName + " column to conflictCreation annotation in RESOURCE_ATTRIBUTE_VALUE"); Map<String, Boolean> map = new HashMap<String,Boolean>(); { String sql = "SELECT ID," + columnName +" from " + tableName ; Statement stmt = null; ResultSet rset = null; try { stmt = con.createStatement(); rset = stmt.executeQuery(sql); while (rset.next ()) { String id= readId(rset,1, Allocatable.class); Boolean ignoreConflicts = getInt( rset, 2 ) == 1; map.put( id, ignoreConflicts); } } finally { if (rset != null) rset.close(); if (stmt!=null) stmt.close(); } } { PreparedStatement stmt = null; try { String valueString = " (RESOURCE_ID,ATTRIBUTE_KEY,ATTRIBUTE_VALUE)"; String table = "RESOURCE_ATTRIBUTE_VALUE"; String insertSql = "insert into " + table + valueString + " values (" + getMarkerList(3) + ")"; stmt = con.prepareStatement(insertSql); int count = 0; for ( String id:map.keySet()) { Boolean entry = map.get( id); if ( entry != null && entry == true) { int idInt = OldIdMapping.parseId(id); stmt.setInt( 1, idInt ); setString(stmt,2, AttributeValueStorage.ANNOTATION_PREFIX + ResourceAnnotations.KEY_CONFLICT_CREATION); setString(stmt,3, ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE); stmt.addBatch(); count++; } } if ( count > 0) { stmt.executeBatch(); } } catch (SQLException ex) { throw ex; } finally { if (stmt!=null) stmt.close(); } } con.commit(); } checkAndDrop(schema,columnName); } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { String id= readId(rset,1, Allocatable.class); String typeKey = getString(rset,2 , null); final Date createDate = getTimestampOrNow( rset, 4); final Date lastChanged = getTimestampOrNow( rset, 5); AllocatableImpl allocatable = new AllocatableImpl(createDate, lastChanged); allocatable.setLastChangedBy( resolveFromId(rset, 6, User.class) ); allocatable.setId( id); allocatable.setResolver( entityStore); DynamicType type = null; if ( typeKey != null) { type = getDynamicType(typeKey ); } if ( type == null) { getLogger().error("Allocatable with id " + id + " has an unknown type " + typeKey + ". Try ignoring it"); return; } allocatable.setOwner( resolveFromId(rset, 3, User.class) ); Classification classification = type.newClassification(false); allocatable.setClassification( classification ); classificationMap.put( id, classification ); allocatableMap.put( id, allocatable); put( allocatable ); } @Override public void loadAll() throws RaplaException, SQLException { classificationMap.clear(); super.loadAll(); } } @Deprecated class ReservationStorage extends RaplaTypeStorage<Reservation> { Map<String,Classification> classificationMap = new HashMap<String,Classification>(); Map<String,Reservation> reservationMap = new HashMap<String,Reservation>(); AttributeValueStorage<Reservation> attributeValueStorage; // appointmentstorage is not a sub store but a delegate AppointmentStorage appointmentStorage; public ReservationStorage(RaplaContext context) throws RaplaException { super(context,Reservation.TYPE, "EVENT",new String [] {"ID INTEGER NOT NULL PRIMARY KEY","TYPE_KEY VARCHAR(100) NOT NULL","OWNER_ID INTEGER NOT NULL","CREATION_TIME TIMESTAMP","LAST_CHANGED TIMESTAMP","LAST_CHANGED_BY INTEGER DEFAULT NULL"}); attributeValueStorage = new AttributeValueStorage<Reservation>(context,"EVENT_ATTRIBUTE_VALUE","EVENT_ID", classificationMap, reservationMap); addSubStorage(attributeValueStorage); } public void setAppointmentStorage(AppointmentStorage appointmentStorage) { this.appointmentStorage = appointmentStorage; } @Override public void createOrUpdateIfNecessary( Map<String, TableDef> schema) throws SQLException, RaplaException { super.createOrUpdateIfNecessary( schema); checkAndAdd(schema, "LAST_CHANGED_BY"); } @Override public void setConnection(Connection con) throws SQLException { super.setConnection(con); appointmentStorage.setConnection(con); } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { final Date createDate = getTimestampOrNow(rset,4); final Date lastChanged = getTimestampOrNow(rset,5); ReservationImpl event = new ReservationImpl(createDate, lastChanged); String id = readId(rset,1,Reservation.class); event.setId( id); event.setResolver( entityStore); String typeKey = getString(rset,2,null); DynamicType type = null; if ( typeKey != null) { type = getDynamicType(typeKey ); } if ( type == null) { getLogger().error("Reservation with id " + id + " has an unknown type " + typeKey + ". Try ignoring it"); return; } User user = resolveFromId(rset, 3, User.class); if ( user == null ) { return; } event.setOwner( user ); event.setLastChangedBy( resolveFromId(rset, 6, User.class) ); Classification classification = type.newClassification(false); event.setClassification( classification ); classificationMap.put( id, classification ); reservationMap.put( id, event ); put( event ); } @Override public void loadAll() throws RaplaException, SQLException { classificationMap.clear(); super.loadAll(); } } @Deprecated class AttributeValueStorage<T extends Entity<T>> extends OldEntityStorage<T> { Map<String,Classification> classificationMap; Map<String,? extends Annotatable> annotableMap; final String foreignKeyName; // TODO Write conversion script to update all old entries to new entries public final static String OLD_ANNOTATION_PREFIX = "annotation:"; public final static String ANNOTATION_PREFIX = "rapla:"; public AttributeValueStorage(RaplaContext context,String tablename, String foreignKeyName, Map<String,Classification> classificationMap, Map<String, ? extends Annotatable> annotableMap) throws RaplaException { super(context, tablename, new String[]{foreignKeyName + " INTEGER NOT NULL KEY","ATTRIBUTE_KEY VARCHAR(100)","ATTRIBUTE_VALUE VARCHAR(20000)"}); this.foreignKeyName = foreignKeyName; this.classificationMap = classificationMap; this.annotableMap = annotableMap; } @Override public void createOrUpdateIfNecessary( Map<String, TableDef> schema) throws SQLException, RaplaException { super.createOrUpdateIfNecessary( schema); checkAndRename( schema, "VALUE", "ATTRIBUTE_VALUE"); checkAndRetype(schema, "ATTRIBUTE_VALUE"); } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { Class<? extends Entity> idClass = foreignKeyName.indexOf("RESOURCE")>=0 ? Allocatable.class : Reservation.class; String classifiableId = readId(rset, 1, idClass); String attributekey = rset.getString( 2 ); boolean annotationPrefix = attributekey.startsWith(ANNOTATION_PREFIX); boolean oldAnnotationPrefix = attributekey.startsWith(OLD_ANNOTATION_PREFIX); if ( annotationPrefix || oldAnnotationPrefix) { String annotationKey = attributekey.substring( annotationPrefix ? ANNOTATION_PREFIX.length() : OLD_ANNOTATION_PREFIX.length()); Annotatable annotatable = annotableMap.get(classifiableId); if (annotatable != null) { String valueAsString = rset.getString( 3); if ( rset.wasNull() || valueAsString == null) { annotatable.setAnnotation(annotationKey, null); } else { annotatable.setAnnotation(annotationKey, valueAsString); } } else { getLogger().warn("No resource or reservation found for the id " + classifiableId + " ignoring."); } } else { ClassificationImpl classification = (ClassificationImpl) classificationMap.get(classifiableId); if ( classification == null) { getLogger().warn("No resource or reservation found for the id " + classifiableId + " ignoring."); return; } Attribute attribute = classification.getType().getAttribute( attributekey ); if ( attribute == null) { getLogger().error("DynamicType '" +classification.getType() +"' doesnt have an attribute with the key " + attributekey + " Current allocatable/reservation Id " + classifiableId + ". Ignoring attribute."); return; } String valueAsString = rset.getString( 3); if ( valueAsString != null ) { Object value = AttributeImpl.parseAttributeValue(attribute, valueAsString); classification.addValue( attribute, value); } } } } @Deprecated class PermissionStorage extends OldEntityStorage<Allocatable> { Map<String,Allocatable> allocatableMap; public PermissionStorage(RaplaContext context,Map<String,Allocatable> allocatableMap) throws RaplaException { super(context,"PERMISSION",new String[] {"RESOURCE_ID INTEGER NOT NULL KEY","USER_ID INTEGER","GROUP_ID INTEGER","ACCESS_LEVEL INTEGER NOT NULL","MIN_ADVANCE INTEGER","MAX_ADVANCE INTEGER","START_DATE DATETIME","END_DATE DATETIME"}); this.allocatableMap = allocatableMap; } protected void load(ResultSet rset) throws SQLException, RaplaException { String allocatableIdInt = readId(rset, 1, Allocatable.class); Allocatable allocatable = allocatableMap.get(allocatableIdInt); if ( allocatable == null) { getLogger().warn("Could not find resource object with id "+ allocatableIdInt + " for permission. Maybe the resource was deleted from the database."); return; } PermissionImpl permission = new PermissionImpl(); permission.setUser( resolveFromId(rset, 2, User.class)); permission.setGroup( resolveFromId(rset, 3, Category.class)); Integer accessLevel = getInt( rset, 4); // We multiply the access levels to add a more access levels between. if ( accessLevel !=null) { if ( accessLevel < 5) { accessLevel *= 100; } permission.setAccessLevel( accessLevel ); } permission.setMinAdvance( getInt(rset,5)); permission.setMaxAdvance( getInt(rset,6)); permission.setStart(getDate(rset, 7)); permission.setEnd(getDate(rset, 8)); // We need to add the permission at the end to ensure its unique. Permissions are stored in a set and duplicates are removed during the add method allocatable.addPermission( permission ); } } @Deprecated class AppointmentStorage extends RaplaTypeStorage<Appointment> { AppointmentExceptionStorage appointmentExceptionStorage; AllocationStorage allocationStorage; public AppointmentStorage(RaplaContext context) throws RaplaException { super(context, Appointment.TYPE,"APPOINTMENT",new String [] {"ID INTEGER NOT NULL PRIMARY KEY","EVENT_ID INTEGER NOT NULL KEY","APPOINTMENT_START DATETIME NOT NULL","APPOINTMENT_END DATETIME NOT NULL","REPETITION_TYPE VARCHAR(255)","REPETITION_NUMBER INTEGER","REPETITION_END DATETIME","REPETITION_INTERVAL INTEGER"}); appointmentExceptionStorage = new AppointmentExceptionStorage(context); allocationStorage = new AllocationStorage( context); addSubStorage(appointmentExceptionStorage); addSubStorage(allocationStorage); } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { String id = readId(rset, 1, Appointment.class); Reservation event = resolveFromId(rset, 2, Reservation.class); if ( event == null) { return; } Date start = getDate(rset,3); Date end = getDate(rset,4); boolean wholeDayAppointment = start.getTime() == DateTools.cutDate( start.getTime()) && end.getTime() == DateTools.cutDate( end.getTime()); AppointmentImpl appointment = new AppointmentImpl(start, end); appointment.setId( id); appointment.setWholeDays( wholeDayAppointment); event.addAppointment( appointment ); String repeatingType = getString( rset,5, null); if ( repeatingType != null ) { appointment.setRepeatingEnabled( true ); Repeating repeating = appointment.getRepeating(); repeating.setType( RepeatingType.findForString( repeatingType ) ); Date repeatingEnd = getDate(rset, 7); if ( repeatingEnd != null ) { repeating.setEnd( repeatingEnd); } else { Integer number = getInt( rset, 6); if ( number != null) { repeating.setNumber( number); } else { repeating.setEnd( null ); } } Integer interval = getInt( rset,8); if ( interval != null) repeating.setInterval( interval); } put( appointment ); } } @Deprecated class AllocationStorage extends OldEntityStorage<Appointment> { public AllocationStorage(RaplaContext context) throws RaplaException { super(context,"ALLOCATION",new String [] {"APPOINTMENT_ID INTEGER NOT NULL KEY", "RESOURCE_ID INTEGER NOT NULL", "OPTIONAL INTEGER"}); } @Override public void createOrUpdateIfNecessary( Map<String, TableDef> schema) throws SQLException, RaplaException { super.createOrUpdateIfNecessary( schema); checkAndAdd( schema, "OPTIONAL"); } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { Appointment appointment =resolveFromId(rset,1, Appointment.class); if ( appointment == null) { return; } ReservationImpl event = (ReservationImpl) appointment.getReservation(); Allocatable allocatable = resolveFromId(rset, 2, Allocatable.class); if ( allocatable == null) { return; } if ( !event.hasAllocated( allocatable ) ) { event.addAllocatable( allocatable ); } Appointment[] appointments = event.getRestriction( allocatable ); Appointment[] newAppointments = new Appointment[ appointments.length+ 1]; System.arraycopy(appointments,0, newAppointments, 0, appointments.length ); newAppointments[ appointments.length] = appointment; if (event.getAppointmentList().size() > newAppointments.length ) { event.setRestriction( allocatable, newAppointments ); } else { event.setRestriction( allocatable, new Appointment[] {} ); } } } @Deprecated class AppointmentExceptionStorage extends OldEntityStorage<Appointment> { public AppointmentExceptionStorage(RaplaContext context) throws RaplaException { super(context,"APPOINTMENT_EXCEPTION",new String [] {"APPOINTMENT_ID INTEGER NOT NULL KEY","EXCEPTION_DATE DATETIME NOT NULL"}); } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { Appointment appointment = resolveFromId( rset, 1, Appointment.class); if ( appointment == null) { return; } Repeating repeating = appointment.getRepeating(); if ( repeating != null) { Date date = getDate(rset,2 ); repeating.addException( date ); } } @Override public void dropTable() throws SQLException { super.dropTable(); } } @Deprecated class DynamicTypeStorage extends RaplaTypeStorage<DynamicType> { public DynamicTypeStorage(RaplaContext context) throws RaplaException { super(context, DynamicType.TYPE,"DYNAMIC_TYPE", new String [] {"ID INTEGER NOT NULL PRIMARY KEY","TYPE_KEY VARCHAR(100) NOT NULL","DEFINITION TEXT NOT NULL"}); } @Override public void createOrUpdateIfNecessary(Map<String, TableDef> schema) throws SQLException, RaplaException { super.createOrUpdateIfNecessary(schema); checkAndRetype(schema, "DEFINITION"); } protected void load(ResultSet rset) throws SQLException,RaplaException { String xml = getText(rset,3); processXML( DynamicType.TYPE, xml ); } } @Deprecated class PreferenceStorage extends RaplaTypeStorage<Preferences> { public PreferenceStorage(RaplaContext context) throws RaplaException { super(context,Preferences.TYPE,"PREFERENCE", new String [] {"USER_ID INTEGER KEY","ROLE VARCHAR(255) NOT NULL","STRING_VALUE VARCHAR(10000)","XML_VALUE TEXT"}); } @Override public void createOrUpdateIfNecessary(Map<String, TableDef> schema) throws SQLException, RaplaException { super.createOrUpdateIfNecessary(schema); checkAndRetype(schema, "STRING_VALUE"); checkAndRetype(schema, "XML_VALUE"); } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { //findPreferences //check if value set // yes read value // no read xml String userId = readId(rset, 1,User.class, true); User owner ; if ( userId == null || userId.equals(OldIdMapping.getId(User.TYPE, 0)) ) { userId = null; owner = null; } else { User user = entityStore.tryResolve( userId, User.class); if ( user != null) { owner = user; } else { getLogger().warn("User with id " + userId + " not found ingnoring preference entry."); return; } } String configRole = getString( rset, 2, null); String preferenceId = PreferencesImpl.getPreferenceIdFromUser(userId); if ( configRole == null) { getLogger().warn("Configuration role for " + preferenceId + " is null. Ignoring preference entry."); return; } String value = getString( rset,3, null); // if (PreferencesImpl.isServerEntry(configRole)) // { // entityStore.putServerPreferences(owner,configRole, value); // return; // } PreferencesImpl preferences = preferenceId != null ? (PreferencesImpl) entityStore.tryResolve( preferenceId, Preferences.class ): null; if ( preferences == null) { Date now =getCurrentTimestamp(); preferences = new PreferencesImpl(now,now); preferences.setId(preferenceId); preferences.setOwner(owner); put( preferences ); } if ( value!= null) { preferences.putEntryPrivate(configRole, value); } else { String xml = getText(rset, 4); if ( xml != null && xml.length() > 0) { PreferenceReader contentHandler = (PreferenceReader) processXML( Preferences.TYPE, xml ); RaplaObject type = contentHandler.getChildType(); preferences.putEntryPrivate(configRole, type); } } } } @Deprecated class UserStorage extends RaplaTypeStorage<User> { UserGroupStorage groupStorage; public UserStorage(RaplaContext context) throws RaplaException { super( context,User.TYPE, "RAPLA_USER", new String [] {"ID INTEGER NOT NULL PRIMARY KEY","USERNAME VARCHAR(100) NOT NULL","PASSWORD VARCHAR(100)","NAME VARCHAR(255) NOT NULL","EMAIL VARCHAR(255) NOT NULL","ISADMIN INTEGER NOT NULL"}); groupStorage = new UserGroupStorage( context ); addSubStorage( groupStorage ); } @Override public void createOrUpdateIfNecessary(Map<String, TableDef> schema) throws SQLException, RaplaException { super.createOrUpdateIfNecessary(schema); } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { String userId = readId(rset,1, User.class ); String username = getString(rset,2, null); if ( username == null) { getLogger().warn("Username is null for " + userId + " Ignoring user."); } String name = getString(rset,4,""); String email = getString(rset,5,""); boolean isAdmin = rset.getInt(6) == 1; Date currentTimestamp = getCurrentTimestamp(); Date createDate = currentTimestamp; Date lastChanged = currentTimestamp; UserImpl user = new UserImpl(createDate, lastChanged); user.setId( userId ); user.setUsername( username ); user.setName( name ); user.setEmail( email ); user.setAdmin( isAdmin ); String password = getString(rset,3, null); if ( password != null) { putPassword(userId,password); } put(user); } } @Deprecated class UserGroupStorage extends OldEntityStorage<User> { public UserGroupStorage(RaplaContext context) throws RaplaException { super(context,"RAPLA_USER_GROUP", new String [] {"USER_ID INTEGER NOT NULL KEY","CATEGORY_ID INTEGER NOT NULL"}); } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { User user = resolveFromId(rset, 1,User.class); if ( user == null) { return; } Category category = resolveFromId(rset, 2, Category.class); if ( category == null) { return; } user.addGroup( category); } }
04900db4-rob
src/org/rapla/storage/dbsql/pre18/RaplaPre18SQL.java
Java
gpl3
37,911
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbsql.pre18; import java.sql.Clob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import java.util.TimeZone; import org.rapla.components.util.DateTools; import org.rapla.components.util.xml.RaplaNonValidatedInput; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.RaplaType; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.storage.EntityResolver; 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.server.internal.TimeZoneConverterImpl; import org.rapla.storage.LocalCache; import org.rapla.storage.OldIdMapping; import org.rapla.storage.dbsql.ColumnDef; import org.rapla.storage.dbsql.TableDef; import org.rapla.storage.impl.EntityStore; import org.rapla.storage.xml.PreferenceReader; import org.rapla.storage.xml.PreferenceWriter; import org.rapla.storage.xml.RaplaXMLReader; import org.rapla.storage.xml.RaplaXMLWriter; @Deprecated public abstract class OldEntityStorage<T extends Entity<T>> { String insertSql; String updateSql; String deleteSql; String selectSql; String deleteAllSql; //String searchForIdSql; RaplaContext context; protected LocalCache cache; protected EntityStore entityStore; private RaplaLocale raplaLocale; Collection<OldEntityStorage<T>> subStores = new ArrayList<OldEntityStorage<T>>(); protected Connection con; int lastParameterIndex; /** first paramter is 1 */ protected final String tableName; protected Logger logger; String dbProductName = ""; protected Map<String,ColumnDef> columns = new LinkedHashMap<String,ColumnDef>(); Calendar datetimeCal; protected OldEntityStorage( RaplaContext context, String table,String[] entries) throws RaplaException { this.context = context; if ( context.has( EntityStore.class)) { this.entityStore = context.lookup( EntityStore.class); } if ( context.has( LocalCache.class)) { this.cache = context.lookup( LocalCache.class); } this.raplaLocale = context.lookup( RaplaLocale.class); datetimeCal =Calendar.getInstance( getSystemTimeZone()); logger = context.lookup( Logger.class); lastParameterIndex = entries.length; tableName = table; for ( String unparsedEntry: entries) { ColumnDef col = new ColumnDef(unparsedEntry); columns.put( col.getName(), col); } createSQL(columns.values()); if (getLogger().isDebugEnabled()) { getLogger().debug(insertSql); getLogger().debug(updateSql); getLogger().debug(deleteSql); getLogger().debug(selectSql); getLogger().debug(deleteAllSql); } } protected Date getDate( ResultSet rset,int column) throws SQLException { java.sql.Timestamp timestamp = rset.getTimestamp( column, datetimeCal); if (rset.wasNull() || timestamp == null) { return null; } long time = timestamp.getTime(); TimeZone systemTimeZone = getSystemTimeZone(); long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time); Date returned = new Date(time + offset); return returned; } // Always use gmt for storing timestamps protected Date getTimestampOrNow(ResultSet rset, int column) throws SQLException { Date currentTimestamp = getCurrentTimestamp(); java.sql.Timestamp timestamp = rset.getTimestamp( column, datetimeCal); if (rset.wasNull() || timestamp == null) { return currentTimestamp; } Date date = new Date( timestamp.getTime()); if ( date != null) { if ( date.after( currentTimestamp)) { getLogger().error("Timestamp in table " + tableName + " in the future. Ignoring."); } else { return date; } } return currentTimestamp; } public Date getCurrentTimestamp() { long time = System.currentTimeMillis(); return new Date( time); } public String getIdColumn() { for (Map.Entry<String, ColumnDef> entry:columns.entrySet()) { String column = entry.getKey(); ColumnDef def = entry.getValue(); if ( def.isPrimary()) { return column; } } return null; } public String getTableName() { return tableName; } protected TimeZone getSystemTimeZone() { return TimeZone.getDefault(); } protected void setDate(PreparedStatement stmt,int column, Date time) throws SQLException { if ( time != null) { TimeZone systemTimeZone = getSystemTimeZone(); // same as TimeZoneConverterImpl.fromRaplaTime long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time.getTime()); long timeInMillis = time.getTime() - offset; stmt.setTimestamp( column, new java.sql.Timestamp( timeInMillis), datetimeCal); } else { stmt.setObject(column, null, Types.TIMESTAMP); } } protected void setTimestamp(PreparedStatement stmt,int column, Date time) throws SQLException { if ( time != null) { TimeZone systemTimeZone = getSystemTimeZone(); // same as TimeZoneConverterImpl.fromRaplaTime long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time.getTime()); long timeInMillis = time.getTime() - offset; stmt.setTimestamp( column, new java.sql.Timestamp( timeInMillis), datetimeCal); } else { stmt.setObject(column, null, Types.TIMESTAMP); } } protected void setId(PreparedStatement stmt, int column, Entity<?> entity) throws SQLException { if ( entity != null) { int groupId = getId( (Entity) entity); stmt.setInt( column, groupId ); } else { stmt.setObject(column, null, Types.INTEGER); } } protected String readId(ResultSet rset, int column, Class<? extends Entity> class1) throws SQLException, RaplaException { return readId(rset, column, class1, false); } protected String readId(ResultSet rset, int column, Class<? extends Entity> class1, boolean nullAllowed) throws SQLException, RaplaException { RaplaType type = RaplaType.get( class1); Integer id = rset.getInt( column ); if ( rset.wasNull() || id == null ) { if ( nullAllowed ) { return null; } throw new RaplaException("Id can't be null for " + tableName); } return OldIdMapping.getId(type,id); } protected <S extends Entity> S resolveFromId(ResultSet rset, int column, Class<S> class1) throws SQLException { RaplaType type = RaplaType.get( class1); Integer id = rset.getInt( column ); if (rset.wasNull() || id == null) { return null; } try { Entity resolved = entityStore.resolve(OldIdMapping.getId(type,id), class1); @SuppressWarnings("unchecked") S casted = (S) resolved; return casted; } catch ( EntityNotFoundException ex) { getLogger().warn("Could not find " + type +" with id "+ id + " in the " + tableName + " table. Ignoring." ); return null; } } protected void setInt(PreparedStatement stmt, int column, Integer number) throws SQLException { if ( number != null) { stmt.setInt( column, number.intValue() ); } else { stmt.setObject(column, null, Types.INTEGER); } } protected String getString(ResultSet rset,int index, String defaultString) throws SQLException { String value = rset.getString(index); if (rset.wasNull() || value == null) { return defaultString; } return value; } protected Integer getInt( ResultSet rset,int column) throws SQLException { Integer value = rset.getInt( column); if (rset.wasNull() || value == null) { return null; } return value; } protected void setLong(PreparedStatement stmt, int column, Long number) throws SQLException { if ( number != null) { stmt.setLong( column, number.longValue() ); } else { stmt.setObject(column, null, Types.BIGINT); } } protected void setString(PreparedStatement stmt, int column, String object) throws SQLException { if ( object == null) { stmt.setObject( column, null, Types.VARCHAR); } else { stmt.setString( column, object); } } protected Logger getLogger() { return logger; } public List<String> getCreateSQL() { List<String> createSQL = new ArrayList<String>(); StringBuffer buf = new StringBuffer(); String table = tableName; buf.append("CREATE TABLE " + table + " ("); List<String> keyCreates = new ArrayList<String>(); boolean first= true; for (ColumnDef col: columns.values()) { if (first) { first = false; } else { buf.append( ", "); } boolean includePrimaryKey = true; boolean includeDefaults = false; String colSql = getColumnCreateStatemet(col, includePrimaryKey, includeDefaults); buf.append(colSql); if ( col.isKey() && !col.isPrimary()) { String colName = col.getName(); String keyCreate = createKeySQL(table, colName); keyCreates.add(keyCreate); } } buf.append(")"); String sql = buf.toString(); createSQL.add( sql); createSQL.addAll( keyCreates); return createSQL; } protected void createSQL(Collection<ColumnDef> entries) { String idString = entries.iterator().next().getName(); String table = tableName; selectSql = "select " + getEntryList(entries) + " from " + table ; deleteSql = "delete from " + table + " where " + idString + "= ?"; String valueString = " (" + getEntryList(entries) + ")"; insertSql = "insert into " + table + valueString + " values (" + getMarkerList(entries.size()) + ")"; updateSql = "update " + table + " set " + getUpdateList(entries) + " where " + idString + "= ?"; deleteAllSql = "delete from " + table; //searchForIdSql = "select id from " + table + " where id = ?"; } //CREATE INDEX KEY_ALLOCATION_APPOINTMENT ON ALLOCATION(APPOINTMENT_ID); private String createKeySQL(String table, String colName) { return "create index KEY_"+ table + "_" + colName + " on " + table + "(" + colName +")"; } /** * @throws RaplaException */ public void createOrUpdateIfNecessary( Map<String,TableDef> schema) throws SQLException, RaplaException { String tablename = tableName; if (schema.get (tablename) != null ) { return; } getLogger().info("Creating table " + tablename); for (String createSQL : getCreateSQL()) { Statement stmt = con.createStatement(); try { stmt.execute(createSQL ); } finally { stmt.close(); } con.commit(); } schema.put( tablename, new TableDef(tablename,columns.values())); } protected ColumnDef getColumn(String name) { return columns.get( name); } protected void checkAndAdd(Map<String, TableDef> schema, String columnName) throws SQLException { ColumnDef col = getColumn(columnName); if ( col == null) { throw new IllegalArgumentException("Column " + columnName + " not found in table schema " + tableName); } String name = col.getName(); TableDef tableDef = schema.get(tableName); if (tableDef.getColumn(name) == null) { getLogger().warn("Patching Database for table " + tableName + " adding column "+ name); { String sql = "ALTER TABLE " + tableName + " ADD COLUMN "; sql += getColumnCreateStatemet( col, true, true); Statement stmt = con.createStatement(); try { stmt.execute( sql); } finally { stmt.close(); } con.commit(); } if ( col.isKey() && !col.isPrimary()) { String sql = createKeySQL(tableName, name); getLogger().info("Adding index for " + name); Statement stmt = con.createStatement(); try { stmt.execute( sql); } finally { stmt.close(); } con.commit(); } } } protected String getDatabaseProductType(String type) { if ( isHsqldb()) { if ( type.equals("TEXT")) { return "VARCHAR(16777216)"; } } if ( isMysql()) { if ( type.equals("TEXT")) { return "LONGTEXT"; } } if ( isH2()) { if ( type.equals("TEXT")) { return "CLOB"; } } else { if ( type.equals("DATETIME")) { return "TIMESTAMP"; } } return type; } protected void checkAndRename( Map<String, TableDef> schema, String oldColumnName, String newColumnName) throws SQLException { String errorPrefix = "Can't rename " + oldColumnName + " " + newColumnName + " in table " + tableName; TableDef tableDef = schema.get(tableName); if (tableDef.getColumn( newColumnName) != null ) { return; } ColumnDef oldColumn = tableDef.getColumn( oldColumnName); if (oldColumn == null) { throw new SQLException(errorPrefix + " old column " + oldColumnName + " not found."); } ColumnDef newCol = getColumn(newColumnName); if ( newCol == null) { throw new IllegalArgumentException("Column " + newColumnName + " not found in table schema " + tableName); } getLogger().warn("Patching Database for table " + tableName + " renaming column "+ oldColumnName + " to " + newColumnName); String sql = "ALTER TABLE " + tableName + " RENAME COLUMN " + oldColumnName + " TO " + newColumnName; if ( isMysql()) { sql = "ALTER TABLE " + tableName + " CHANGE COLUMN " +oldColumnName + " "; String columnSql = getColumnCreateStatemet(newCol, false, true); sql+= columnSql; } Statement stmt = con.createStatement(); try { stmt.execute( sql); } finally { stmt.close(); } con.commit(); tableDef.removeColumn( oldColumnName); tableDef.addColumn( newCol); } protected void checkAndRetype(Map<String, TableDef> schema, String columnName) throws RaplaException { TableDef tableDef = schema.get(tableName); ColumnDef oldDef = tableDef.getColumn( columnName); ColumnDef newDef = getColumn(columnName); if (oldDef == null || newDef == null) { throw new RaplaException("Can't retype column " + columnName + " it is not found"); } boolean includePrimaryKey = false; boolean includeDefaults = false; String stmt1 = getColumnCreateStatemet(oldDef, includePrimaryKey, includeDefaults); String stmt2 = getColumnCreateStatemet(newDef, includePrimaryKey, includeDefaults); if ( stmt1.equals( stmt2)) { return; } String columnSql = getColumnCreateStatemet(newDef, false, true); getLogger().warn("Column "+ tableName + "."+ columnName + " change from '" + stmt1+ "' to new type '" + columnSql + "'"); getLogger().warn("You should patch the database accordingly."); // We do not autopatch colum types yet // String sql = "ALTER TABLE " + tableName + " ALTER COLUMN " ; // sql+= columnSql; // con.createStatement().execute(sql); } protected String getColumnCreateStatemet(ColumnDef col, boolean includePrimaryKey, boolean includeDefaults) { StringBuffer buf = new StringBuffer(); String colName = col.getName(); buf.append(colName); String type = getDatabaseProductType(col.getType()); buf.append(" " + type); if ( col.isNotNull()) { buf.append(" NOT NULL"); } else { buf.append(" NULL"); } if ( includeDefaults) { if ( type.equals("TIMESTAMP")) { if ( !isHsqldb() && !isH2()) { buf.append( " DEFAULT " + "'2000-01-01 00:00:00'"); } } else if ( col.getDefaultValue() != null) { buf.append( " DEFAULT " + col.getDefaultValue()); } } if (includePrimaryKey && col.isPrimary()) { buf.append(" PRIMARY KEY"); } String columnSql =buf.toString(); return columnSql; } protected boolean isMysql() { boolean result = dbProductName.indexOf("mysql") >=0; return result; } protected boolean isHsqldb() { boolean result = dbProductName.indexOf("hsql") >=0; return result; } protected boolean isPostgres() { boolean result = dbProductName.indexOf("postgres") >=0; return result; } protected boolean isH2() { boolean result = dbProductName.indexOf("h2") >=0; return result; } protected void checkRenameTable( Map<String, TableDef> tableMap, String oldTableName) throws SQLException { boolean isOldTableName = false; if ( tableMap.get( oldTableName) != null) { isOldTableName = true; } if ( tableMap.get(tableName) != null) { isOldTableName = false; } if ( isOldTableName) { getLogger().warn("Table " + tableName + " not found. Patching Database : Renaming " + oldTableName + " to "+ tableName); String sql = "ALTER TABLE " + oldTableName + " RENAME TO " + tableName + ""; Statement stmt = con.createStatement(); try { stmt.execute( sql); } finally { stmt.close(); } con.commit(); tableMap.put( tableName, tableMap.get( oldTableName)); tableMap.remove( oldTableName); } } protected void checkAndDrop(Map<String, TableDef> schema, String columnName) throws SQLException { TableDef tableDef = schema.get(tableName); if (tableDef.getColumn(columnName) != null) { String sql = "ALTER TABLE " + tableName + " DROP COLUMN " + columnName; Statement stmt = con.createStatement(); try { stmt.execute( sql); } finally { stmt.close(); } } con.commit(); } public void dropTable() throws SQLException { getLogger().info("Dropping table " + tableName); String sql = "DROP TABLE " + tableName ; Statement stmt = con.createStatement(); try { stmt.execute( sql); } finally { stmt.close(); } con.commit(); } protected void addSubStorage(OldEntityStorage<T> subStore) { subStores.add(subStore); } public Collection<OldEntityStorage<T>> getSubStores() { return subStores; } public void setConnection(Connection con) throws SQLException { this.con= con; for (OldEntityStorage<T> subStore: subStores) { subStore.setConnection(con); } if ( con != null) { String databaseProductName = con.getMetaData().getDatabaseProductName(); if ( databaseProductName != null) { Locale locale = Locale.ENGLISH; dbProductName = databaseProductName.toLowerCase(locale); } } } public Locale getLocale() { return raplaLocale.getLocale(); } protected String getEntryList(Collection<ColumnDef> entries) { StringBuffer buf = new StringBuffer(); for (ColumnDef col: entries) { if (buf.length() > 0 ) { buf.append(", "); } buf.append(col.getName()); } return buf.toString(); } protected String getMarkerList(int length) { StringBuffer buf = new StringBuffer(); for (int i=0;i<length; i++) { buf.append('?'); if (i < length - 1) { buf.append(','); } } return buf.toString(); } protected String getUpdateList(Collection<ColumnDef> entries) { StringBuffer buf = new StringBuffer(); for (ColumnDef col: entries) { if (buf.length() > 0 ) { buf.append(", "); } buf.append(col.getName()); buf.append("=? "); } return buf.toString(); } public static void executeBatchedStatement(Connection con,String sql) throws SQLException { Statement stmt = null; try { stmt = con.createStatement(); StringTokenizer tokenizer = new StringTokenizer(sql,";"); while (tokenizer.hasMoreTokens()) stmt.executeUpdate(tokenizer.nextToken()); } finally { if (stmt!=null) stmt.close(); } } public static int getId(Entity entity) { String id = (String) entity.getId(); return OldIdMapping.parseId(id); } public void loadAll() throws SQLException,RaplaException { Statement stmt = null; ResultSet rset = null; try { stmt = con.createStatement(); rset = stmt.executeQuery(selectSql); while (rset.next ()) { load(rset); } } finally { if (rset != null) rset.close(); if (stmt!=null) stmt.close(); } for (OldEntityStorage storage: subStores) { storage.loadAll(); } } abstract protected void load(ResultSet rs) throws SQLException,RaplaException; public RaplaNonValidatedInput getReader() throws RaplaException { return lookup( RaplaNonValidatedInput.class); } public RaplaXMLReader getReaderFor( RaplaType type) throws RaplaException { Map<RaplaType,RaplaXMLReader> readerMap = lookup( PreferenceReader.READERMAP); return readerMap.get( type); } public RaplaXMLWriter getWriterFor( RaplaType type) throws RaplaException { Map<RaplaType,RaplaXMLWriter> writerMap = lookup( PreferenceWriter.WRITERMAP ); return writerMap.get( type); } protected <S> S lookup( TypedComponentRole<S> role) throws RaplaException { try { return context.lookup( role); } catch (RaplaContextException e) { throw new RaplaException( e); } } protected <S> S lookup( Class<S> role) throws RaplaException { try { return context.lookup( role); } catch (RaplaContextException e) { throw new RaplaException( e); } } protected void put( Entity entity) { entityStore.put( entity); } protected EntityResolver getResolver() { return entityStore; } protected void putPassword( String userId, String password ) { entityStore.putPassword( userId, password); } protected DynamicType getDynamicType( String typeKey ) { return entityStore.getDynamicType( typeKey); } protected Category getSuperCategory() { if ( cache != null) { return cache.getSuperCategory(); } return entityStore.getSuperCategory(); } protected String getText(ResultSet rset, int columnIndex) throws SQLException { String xml = null; if ( isMysql()) { Clob clob = rset.getClob( columnIndex ); if ( clob!= null) { int length = (int)clob.length(); if ( length > 0) { xml = clob.getSubString(1, length); // String xml = rset.getString( 4); } } } else { xml = rset.getString(columnIndex); } return xml; } }
04900db4-rob
src/org/rapla/storage/dbsql/pre18/OldEntityStorage.java
Java
gpl3
24,508
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbsql; import org.rapla.framework.RaplaException; public class RaplaDBException extends RaplaException { private static final long serialVersionUID = 1L; public RaplaDBException(String text) { super(text); } public RaplaDBException(Throwable throwable) { super(throwable); } public RaplaDBException(String text,Throwable ex) { super(text,ex); } }
04900db4-rob
src/org/rapla/storage/dbsql/RaplaDBException.java
Java
gpl3
1,377
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbsql; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Driver; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.locks.Lock; import javax.sql.DataSource; import org.rapla.ConnectInfo; import org.rapla.components.util.xml.RaplaNonValidatedInput; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.framework.Configuration; import org.rapla.framework.ConfigurationException; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaDefaultContext; import org.rapla.framework.RaplaException; import org.rapla.framework.internal.ContextTools; import org.rapla.framework.logger.Logger; import org.rapla.storage.CachableStorageOperator; import org.rapla.storage.CachableStorageOperatorCommand; import org.rapla.storage.IdCreator; import org.rapla.storage.ImportExportManager; import org.rapla.storage.LocalCache; import org.rapla.storage.UpdateEvent; import org.rapla.storage.UpdateResult; import org.rapla.storage.impl.EntityStore; import org.rapla.storage.impl.server.LocalAbstractCachableOperator; import org.rapla.storage.xml.IOContext; import org.rapla.storage.xml.RaplaMainWriter; /** This Operator is used to store the data in a SQL-DBMS.*/ public class DBOperator extends LocalAbstractCachableOperator { private String driverClassname; protected String datasourceName; protected String user; protected String password; protected String dbURL; protected Driver dbDriver; protected boolean isConnected; Properties dbProperties = new Properties(); boolean bSupportsTransactions = false; boolean hsqldb = false; private String backupEncoding; private String backupFileName; Object lookup; String connectionName; public DBOperator(RaplaContext context, Logger logger,Configuration config) throws RaplaException { super( context, logger); String backupFile = config.getChild("backup").getValue(""); if (backupFile != null) backupFileName = ContextTools.resolveContext( backupFile, context); backupEncoding = config.getChild( "encoding" ).getValue( "utf-8" ); datasourceName = config.getChild("datasource").getValue(null); // dont use datasource (we have to configure a driver ) if ( datasourceName == null) { try { driverClassname = config.getChild("driver").getValue(); dbURL = ContextTools.resolveContext( config.getChild("url").getValue(), context); getLogger().info("Data:" + dbURL); } catch (ConfigurationException e) { throw new RaplaException( e ); } dbProperties.setProperty("user", config.getChild("user").getValue("") ); dbProperties.setProperty("password", config.getChild("password").getValue("") ); hsqldb = config.getChild("hsqldb-shutdown").getValueAsBoolean( false ); try { dbDriver = (Driver) getClass().getClassLoader().loadClass(driverClassname).newInstance(); } catch (ClassNotFoundException e) { throw new RaplaException("DB-Driver not found: " + driverClassname + "\nCheck classpath!"); } catch (Exception e) { throw new RaplaException("Could not instantiate DB-Driver: " + driverClassname, e); } } else { try { lookup = ContextTools.resolveContextObject(datasourceName, context ); } catch (RaplaContextException ex) { throw new RaplaDBException("Datasource " + datasourceName + " not found"); } } } public boolean supportsActiveMonitoring() { return false; } public String getConnectionName() { if ( connectionName != null) { return connectionName; } if ( datasourceName != null) { return datasourceName; } return dbURL; } public Connection createConnection() throws RaplaException { boolean withTransactionSupport = true; return createConnection(withTransactionSupport); } public Connection createConnection(boolean withTransactionSupport) throws RaplaException { Connection connection = null; try { //datasource lookup Object source = lookup; // if ( lookup instanceof String) // { // InitialContext ctx = new InitialContext(); // source = ctx.lookup("java:comp/env/"+ lookup); // } // else // { // source = lookup; // } if ( source != null) { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { try { Thread.currentThread().setContextClassLoader(source.getClass().getClassLoader()); } catch (Exception ex) { } try { DataSource ds = (DataSource) source; connection = ds.getConnection(); } catch (ClassCastException ex) { String text = "Datasource object " + source.getClass() + " does not implement a datasource interface."; getLogger().error( text); throw new RaplaDBException(text); } } finally { try { Thread.currentThread().setContextClassLoader(contextClassLoader); } catch (Exception ex) { } } } // or driver initialization else { connection = dbDriver.connect(dbURL, dbProperties); connectionName = dbURL; if (connection == null) { throw new RaplaDBException("No driver found for: " + dbURL + "\nCheck url!"); } } if ( withTransactionSupport) { bSupportsTransactions = connection.getMetaData().supportsTransactions(); if (bSupportsTransactions) { connection.setAutoCommit( false ); } else { getLogger().warn("No Transaction support"); } } else { connection.setAutoCommit( true ); } //connection.createStatement().execute( "ALTER TABLE RESOURCE RENAME TO RAPLA_RESOURCE"); // connection.commit(); return connection; } catch (Throwable ex) { if ( connection != null) { close(connection); } if ( ex instanceof RaplaDBException) { throw (RaplaDBException) ex; } throw new RaplaDBException("DB-Connection aborted",ex); } } synchronized public User connect(ConnectInfo connectInfo) throws RaplaException { if (isConnected()) { return null; } getLogger().debug("Connecting: " + getConnectionName()); loadData(); initIndizes(); isConnected = true; getLogger().debug("Connected"); return null; } public boolean isConnected() { return isConnected; } final public void refresh() throws RaplaException { getLogger().warn("Incremental refreshs are not supported"); } synchronized public void disconnect() throws RaplaException { if (!isConnected()) return; backupData(); getLogger().info("Disconnecting: " + getConnectionName()); cache.clearAll(); //idTable.setCache( cache ); // HSQLDB Special if ( hsqldb ) { String sql ="SHUTDOWN COMPACT"; try { Connection connection = createConnection(); Statement statement = connection.createStatement(); statement.execute(sql); statement.close(); } catch (SQLException ex) { throw new RaplaException( ex); } } isConnected = false; fireStorageDisconnected(""); getLogger().info("Disconnected"); } public final void loadData() throws RaplaException { Connection c = null; Lock writeLock = writeLock(); try { c = createConnection(); connectionName = c.getMetaData().getURL(); getLogger().info("Using datasource " + c.getMetaData().getDatabaseProductName() +": " + connectionName); if (upgradeDatabase(c)) { close( c); c = null; c = createConnection(); } cache.clearAll(); addInternalTypes(cache); loadData( c, cache ); if ( getLogger().isDebugEnabled()) getLogger().debug("Entities contextualized"); if ( getLogger().isDebugEnabled()) getLogger().debug("All ConfigurationReferences resolved"); } catch (RaplaException ex) { throw ex; } catch (Exception ex) { throw new RaplaException( ex); } finally { unlock(writeLock); close ( c ); c = null; } } @SuppressWarnings("deprecation") private boolean upgradeDatabase(Connection c) throws SQLException, RaplaException, RaplaContextException { Map<String, TableDef> schema = loadDBSchema(c); TableDef dynamicTypeDef = schema.get("DYNAMIC_TYPE"); boolean empty = false; int oldIdColumnCount = 0; int unpatchedTables = 0; if ( dynamicTypeDef != null) { PreparedStatement prepareStatement = null; ResultSet set = null; try { prepareStatement = c.prepareStatement("select * from DYNAMIC_TYPE"); set = prepareStatement.executeQuery(); empty = !set.next(); } finally { if ( set != null) { set.close(); } if ( prepareStatement != null) { prepareStatement.close(); } } { org.rapla.storage.dbsql.pre18.RaplaPre18SQL raplaSQLOutput = new org.rapla.storage.dbsql.pre18.RaplaPre18SQL(createOutputContext(cache)); Map<String,String> idColumnMap = raplaSQLOutput.getIdColumns(); oldIdColumnCount = idColumnMap.size(); for ( Map.Entry<String, String> entry:idColumnMap.entrySet()) { String table = entry.getKey(); String idColumnName = entry.getValue(); TableDef tableDef = schema.get(table); if ( tableDef != null) { ColumnDef idColumn = tableDef.getColumn(idColumnName); if ( idColumn == null) { throw new RaplaException("Id column not found"); } if ( idColumn.isIntType()) { unpatchedTables++; // else if ( type.toLowerCase().contains("varchar")) // { // patchedTables++; // } } } } } } else { empty = true; } if ( !empty && (unpatchedTables == oldIdColumnCount && unpatchedTables > 0)) { getLogger().warn("Old database schema detected. Initializing conversion!"); org.rapla.storage.dbsql.pre18.RaplaPre18SQL raplaSQLOutput = new org.rapla.storage.dbsql.pre18.RaplaPre18SQL(createOutputContext(cache)); raplaSQLOutput.createOrUpdateIfNecessary( c, schema); CachableStorageOperator sourceOperator = context.lookup(ImportExportManager.class).getSource(); if ( sourceOperator == this) { throw new RaplaException("Can't export old db data, because no data export is set."); } LocalCache cache =new LocalCache(); cache.clearAll(); addInternalTypes(cache); loadOldData(c, cache ); getLogger().info("Old database loaded in memory. Now exporting to xml: " + sourceOperator); sourceOperator.saveData(cache); getLogger().info("XML export done."); //close( c); } if ( empty || unpatchedTables > 0 ) { CachableStorageOperator sourceOperator = context.lookup(ImportExportManager.class).getSource(); if ( sourceOperator == this) { throw new RaplaException("Can't import, because db is configured as source."); } if ( unpatchedTables > 0) { getLogger().info("Reading data from xml."); } else { getLogger().warn("Empty database. Importing data from " + sourceOperator); } sourceOperator.connect(); if ( unpatchedTables > 0) { org.rapla.storage.dbsql.pre18.RaplaPre18SQL raplaSQLOutput = new org.rapla.storage.dbsql.pre18.RaplaPre18SQL(createOutputContext(cache)); getLogger().warn("Dropping database tables and reimport from " + sourceOperator); raplaSQLOutput.dropAll(c); // we need to load the new schema after dropping schema = loadDBSchema(c); } { RaplaSQL raplaSQLOutput = new RaplaSQL(createOutputContext(cache)); raplaSQLOutput.createOrUpdateIfNecessary( c, schema); } close( c); c = null; c = createConnection(); final Connection conn = c; sourceOperator.runWithReadLock( new CachableStorageOperatorCommand() { @Override public void execute(LocalCache cache) throws RaplaException { try { saveData(conn, cache); } catch (SQLException ex) { throw new RaplaException(ex.getMessage(),ex); } } }); return true; } return false; } private Map<String, TableDef> loadDBSchema(Connection c) throws SQLException { Map<String,TableDef> tableMap = new LinkedHashMap<String,TableDef>(); List<String> catalogList = new ArrayList<String>(); DatabaseMetaData metaData = c.getMetaData(); { ResultSet set = metaData.getCatalogs(); try { while (set.next()) { String name = set.getString("TABLE_CAT"); catalogList.add( name); } } finally { set.close(); } } List<String> schemaList = new ArrayList<String>(); { ResultSet set = metaData.getSchemas(); try { while (set.next()) { String name = set.getString("TABLE_SCHEM"); String cat = set.getString("TABLE_CATALOG"); schemaList.add( name); if ( cat != null) { catalogList.add( name); } } } finally { set.close(); } } if ( catalogList.isEmpty()) { catalogList.add( null); } Map<String,Set<String>> tables = new LinkedHashMap<String, Set<String>>(); for ( String cat: catalogList) { LinkedHashSet<String> tableSet = new LinkedHashSet<String>(); String[] types = new String[] {"TABLE"}; tables.put( cat, tableSet); { ResultSet set = metaData.getTables(cat, null, null, types); try { while (set.next()) { String name = set.getString("TABLE_NAME"); tableSet.add( name); } } finally { set.close(); } } } for ( String cat: catalogList) { Set<String> tableNameSet = tables.get( cat); for ( String tableName: tableNameSet ) { ResultSet set = metaData.getColumns(null, null,tableName, null); try { while (set.next()) { String table = set.getString("TABLE_NAME").toUpperCase(Locale.ENGLISH); TableDef tableDef = tableMap.get( table); if ( tableDef == null ) { tableDef = new TableDef(table); tableMap.put( table,tableDef ); } ColumnDef columnDef = new ColumnDef( set); tableDef.addColumn( columnDef); } } finally { set.close(); } } } return tableMap; } public void dispatch(UpdateEvent evt) throws RaplaException { UpdateResult result; Lock writeLock = writeLock(); try { preprocessEventStorage(evt); Connection connection = createConnection(); try { executeEvent(connection,evt); if (bSupportsTransactions) { getLogger().debug("Commiting"); connection.commit(); } } catch (Exception ex) { try { if (bSupportsTransactions) { connection.rollback(); getLogger().error("Doing rollback for: " + ex.getMessage()); throw new RaplaDBException(getI18n().getString("error.rollback"),ex); } else { String message = getI18n().getString("error.no_rollback"); getLogger().error(message); forceDisconnect(); throw new RaplaDBException(message,ex); } } catch (SQLException sqlEx) { String message = "Unrecoverable error while storing"; getLogger().error(message, sqlEx); forceDisconnect(); throw new RaplaDBException(message,sqlEx); } } finally { close( connection ); } result = super.update(evt); } finally { unlock( writeLock ); } fireStorageUpdated(result); } /** * @param evt * @throws RaplaException */ protected void executeEvent(Connection connection,UpdateEvent evt) throws RaplaException, SQLException { // execute updates RaplaSQL raplaSQLOutput = new RaplaSQL(createOutputContext(cache)); Collection<Entity> storeObjects = evt.getStoreObjects(); raplaSQLOutput.store( connection, storeObjects); raplaSQLOutput.storePatches( connection, evt.getPreferencePatches()); Collection<Entity> removeObjects = evt.getRemoveObjects(); for (Entity entityStore: removeObjects) { Comparable id = entityStore.getId(); Entity entity = cache.get(id); if (entity != null) raplaSQLOutput.remove( connection, entity); } } public void removeAll() throws RaplaException { Connection connection = createConnection(); try { RaplaSQL raplaSQLOutput = new RaplaSQL(createOutputContext(cache)); raplaSQLOutput.removeAll( connection ); connection.commit(); // do something here getLogger().info("DB cleared"); } catch (SQLException ex) { throw new RaplaException(ex); } finally { close( connection ); } } public synchronized void saveData(LocalCache cache) throws RaplaException { Connection connection = createConnection(); try { Map<String, TableDef> schema = loadDBSchema(connection); RaplaSQL raplaSQLOutput = new RaplaSQL(createOutputContext(cache)); raplaSQLOutput.createOrUpdateIfNecessary( connection, schema); saveData(connection, cache); } catch (SQLException ex) { throw new RaplaException(ex); } finally { close( connection ); } } protected void saveData(Connection connection, LocalCache cache) throws RaplaException, SQLException { String connectionName = getConnectionName(); getLogger().info("Importing Data into " + connectionName); RaplaSQL raplaSQLOutput = new RaplaSQL(createOutputContext(cache)); // if (dropOldTables) // { // getLogger().info("Droping all data from " + connectionName); // raplaSQLOutput.dropAndRecreate( connection ); // } // else { getLogger().info("Deleting all old Data from " + connectionName); raplaSQLOutput.removeAll( connection ); } getLogger().info("Inserting new Data into " + connectionName); raplaSQLOutput.createAll( connection ); if ( !connection.getAutoCommit()) { connection.commit(); } // do something here getLogger().info("Import complete for " + connectionName); } private void close(Connection connection) { if ( connection == null) { return; } try { getLogger().debug("Closing " + connection); connection.close(); } catch (SQLException e) { getLogger().error( "Can't close connection to database ", e); } } protected void loadData(Connection connection, LocalCache cache) throws RaplaException, SQLException { EntityStore entityStore = new EntityStore(cache, cache.getSuperCategory()); RaplaSQL raplaSQLInput = new RaplaSQL(createInputContext(entityStore, this)); raplaSQLInput.loadAll( connection ); Collection<Entity> list = entityStore.getList(); cache.putAll( list); resolveInitial( list, this); cache.getSuperCategory().setReadOnly(); for (User user:cache.getUsers()) { String id = user.getId(); String password = entityStore.getPassword( id); cache.putPassword(id, password); } } @SuppressWarnings("deprecation") protected void loadOldData(Connection connection, LocalCache cache) throws RaplaException, SQLException { EntityStore entityStore = new EntityStore(cache, cache.getSuperCategory()); IdCreator idCreator = new IdCreator() { @Override public String createId(RaplaType type, String seed) throws RaplaException { String id = org.rapla.storage.OldIdMapping.getId(type, seed); return id; } @Override public String createId(RaplaType raplaType) throws RaplaException { throw new RaplaException("Can't create new ids in " + getClass().getName() + " this class is import only for old data "); } }; RaplaDefaultContext inputContext = createInputContext(entityStore, idCreator); org.rapla.storage.dbsql.pre18.RaplaPre18SQL raplaSQLInput = new org.rapla.storage.dbsql.pre18.RaplaPre18SQL(inputContext); raplaSQLInput.loadAll( connection ); Collection<Entity> list = entityStore.getList(); cache.putAll( list); resolveInitial( list, cache); cache.getSuperCategory().setReadOnly(); for (User user:cache.getUsers()) { String id = user.getId(); String password = entityStore.getPassword( id); cache.putPassword(id, password); } } private RaplaDefaultContext createInputContext( EntityStore store, IdCreator idCreator) throws RaplaException { RaplaDefaultContext inputContext = new IOContext().createInputContext(context, store, idCreator); RaplaNonValidatedInput xmlAdapter = context.lookup(RaplaNonValidatedInput.class); inputContext.put(RaplaNonValidatedInput.class,xmlAdapter); return inputContext; } private RaplaDefaultContext createOutputContext(LocalCache cache) throws RaplaException { RaplaDefaultContext outputContext = new IOContext().createOutputContext(context, cache.getSuperCategoryProvider(),true); outputContext.put( LocalCache.class, cache); return outputContext; } //implement backup at disconnect final public void backupData() throws RaplaException { try { if (backupFileName.length()==0) return; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); writeData(buffer); byte[] data = buffer.toByteArray(); buffer.close(); OutputStream out = new FileOutputStream(backupFileName); out.write(data); out.close(); getLogger().info("Backup data to: " + backupFileName); } catch (IOException e) { getLogger().error("Backup error: " + e.getMessage()); throw new RaplaException(e.getMessage()); } } private void writeData( OutputStream out ) throws IOException, RaplaException { RaplaContext outputContext = new IOContext().createOutputContext( context,cache.getSuperCategoryProvider(), true ); RaplaMainWriter writer = new RaplaMainWriter( outputContext, cache ); writer.setEncoding(backupEncoding); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out,backupEncoding)); writer.setWriter(w); writer.printContent(); } }
04900db4-rob
src/org/rapla/storage/dbsql/DBOperator.java
Java
gpl3
27,497
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbsql; import java.sql.Clob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TimeZone; import org.rapla.components.util.DateTools; import org.rapla.components.util.xml.RaplaNonValidatedInput; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.RaplaType; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.storage.EntityResolver; 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.server.internal.TimeZoneConverterImpl; import org.rapla.storage.LocalCache; import org.rapla.storage.impl.EntityStore; import org.rapla.storage.xml.PreferenceReader; import org.rapla.storage.xml.PreferenceWriter; import org.rapla.storage.xml.RaplaXMLReader; import org.rapla.storage.xml.RaplaXMLWriter; abstract class EntityStorage<T extends Entity<T>> implements Storage<T> { String insertSql; String updateSql; String deleteSql; String selectSql; String deleteAllSql; //String searchForIdSql; RaplaContext context; protected LocalCache cache; protected EntityStore entityStore; private RaplaLocale raplaLocale; Collection<Storage<T>> subStores = new ArrayList<Storage<T>>(); protected Connection con; int lastParameterIndex; /** first paramter is 1 */ protected final String tableName; protected Logger logger; String dbProductName = ""; protected Map<String,ColumnDef> columns = new LinkedHashMap<String,ColumnDef>(); Calendar datetimeCal; protected EntityStorage( RaplaContext context, String table,String[] entries) throws RaplaException { this.context = context; if ( context.has( EntityStore.class)) { this.entityStore = context.lookup( EntityStore.class); } if ( context.has( LocalCache.class)) { this.cache = context.lookup( LocalCache.class); } this.raplaLocale = context.lookup( RaplaLocale.class); datetimeCal =Calendar.getInstance( getSystemTimeZone()); logger = context.lookup( Logger.class); lastParameterIndex = entries.length; tableName = table; for ( String unparsedEntry: entries) { ColumnDef col = new ColumnDef(unparsedEntry); columns.put( col.getName(), col); } createSQL(columns.values()); if (getLogger().isDebugEnabled()) { getLogger().debug(insertSql); getLogger().debug(updateSql); getLogger().debug(deleteSql); getLogger().debug(selectSql); getLogger().debug(deleteAllSql); } } protected Date getDate( ResultSet rset,int column) throws SQLException { java.sql.Timestamp timestamp = rset.getTimestamp( column, datetimeCal); if (rset.wasNull() || timestamp == null) { return null; } long time = timestamp.getTime(); TimeZone systemTimeZone = getSystemTimeZone(); long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time); Date returned = new Date(time + offset); return returned; } // Always use gmt for storing timestamps protected Date getTimestampOrNow(ResultSet rset, int column) throws SQLException { Date currentTimestamp = getCurrentTimestamp(); java.sql.Timestamp timestamp = rset.getTimestamp( column, datetimeCal); if (rset.wasNull() || timestamp == null) { return currentTimestamp; } Date date = new Date( timestamp.getTime()); if ( date != null) { if ( date.after( currentTimestamp)) { getLogger().error("Timestamp in table " + tableName + " in the future. Ignoring."); } else { return date; } } return currentTimestamp; } public Date getCurrentTimestamp() { long time = System.currentTimeMillis(); return new Date( time); } public String getIdColumn() { for (Map.Entry<String, ColumnDef> entry:columns.entrySet()) { String column = entry.getKey(); ColumnDef def = entry.getValue(); if ( def.isPrimary()) { return column; } } return null; } public String getTableName() { return tableName; } protected TimeZone getSystemTimeZone() { return TimeZone.getDefault(); } protected void setDate(PreparedStatement stmt,int column, Date time) throws SQLException { if ( time != null) { TimeZone systemTimeZone = getSystemTimeZone(); // same as TimeZoneConverterImpl.fromRaplaTime long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time.getTime()); long timeInMillis = time.getTime() - offset; stmt.setTimestamp( column, new java.sql.Timestamp( timeInMillis), datetimeCal); } else { stmt.setObject(column, null, Types.TIMESTAMP); } } protected void setTimestamp(PreparedStatement stmt,int column, Date time) throws SQLException { if ( time != null) { TimeZone systemTimeZone = getSystemTimeZone(); // same as TimeZoneConverterImpl.fromRaplaTime long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time.getTime()); long timeInMillis = time.getTime() - offset; stmt.setTimestamp( column, new java.sql.Timestamp( timeInMillis), datetimeCal); } else { stmt.setObject(column, null, Types.TIMESTAMP); } } protected void setId(PreparedStatement stmt, int column, Entity<?> entity) throws SQLException { setId( stmt, column, entity != null ? entity.getId() : null); } protected void setId(PreparedStatement stmt, int column, String id) throws SQLException { if ( id != null) { stmt.setString( column, id ); } else { stmt.setObject(column, null, Types.VARCHAR); } } protected String readId(ResultSet rset, int column, Class<? extends Entity> class1) throws SQLException, RaplaException { return readId(rset, column, class1, false); } protected String readId(ResultSet rset, int column, @SuppressWarnings("unused") Class<? extends Entity> class1, boolean nullAllowed) throws SQLException, RaplaException { String id = rset.getString( column ); if ( rset.wasNull() || id == null ) { if ( nullAllowed ) { return null; } throw new RaplaException("Id can't be null for " + tableName ); } return id; } protected <S extends Entity> S resolveFromId(ResultSet rset, int column, Class<S> class1) throws SQLException { String id = rset.getString( column ); if (rset.wasNull() || id == null) { return null; } try { Entity resolved = entityStore.resolve(id, class1); @SuppressWarnings("unchecked") S casted = (S) resolved; return casted; } catch ( EntityNotFoundException ex) { getLogger().warn("Could not find " + class1.getName() +" with id "+ id + " in the " + tableName + " table. Ignoring." ); return null; } } protected void setInt(PreparedStatement stmt, int column, Integer number) throws SQLException { if ( number != null) { stmt.setInt( column, number.intValue() ); } else { stmt.setObject(column, null, Types.INTEGER); } } protected String getString(ResultSet rset,int index, String defaultString) throws SQLException { String value = rset.getString(index); if (rset.wasNull() || value == null) { return defaultString; } return value; } protected Integer getInt( ResultSet rset,int column) throws SQLException { Integer value = rset.getInt( column); if (rset.wasNull() || value == null) { return null; } return value; } protected void setLong(PreparedStatement stmt, int column, Long number) throws SQLException { if ( number != null) { stmt.setLong( column, number.longValue() ); } else { stmt.setObject(column, null, Types.BIGINT); } } protected void setString(PreparedStatement stmt, int column, String object) throws SQLException { if ( object == null) { stmt.setObject( column, null, Types.VARCHAR); } else { stmt.setString( column, object); } } protected Logger getLogger() { return logger; } public List<String> getCreateSQL() { List<String> createSQL = new ArrayList<String>(); StringBuffer buf = new StringBuffer(); String table = tableName; buf.append("CREATE TABLE " + table + " ("); List<String> keyCreates = new ArrayList<String>(); boolean first= true; for (ColumnDef col: columns.values()) { if (first) { first = false; } else { buf.append( ", "); } boolean includePrimaryKey = true; boolean includeDefaults = false; String colSql = getColumnCreateStatemet(col, includePrimaryKey, includeDefaults); buf.append(colSql); if ( col.isKey() && !col.isPrimary()) { String colName = col.getName(); String keyCreate = createKeySQL(table, colName); keyCreates.add(keyCreate); } } buf.append(")"); String sql = buf.toString(); createSQL.add( sql); createSQL.addAll( keyCreates); return createSQL; } protected void createSQL(Collection<ColumnDef> entries) { String idString = entries.iterator().next().getName(); String table = tableName; selectSql = "select " + getEntryList(entries) + " from " + table ; deleteSql = "delete from " + table + " where " + idString + "= ?"; String valueString = " (" + getEntryList(entries) + ")"; insertSql = "insert into " + table + valueString + " values (" + getMarkerList(entries.size()) + ")"; updateSql = "update " + table + " set " + getUpdateList(entries) + " where " + idString + "= ?"; deleteAllSql = "delete from " + table; //searchForIdSql = "select id from " + table + " where id = ?"; } //CREATE INDEX KEY_ALLOCATION_APPOINTMENT ON ALLOCATION(APPOINTMENT_ID); private String createKeySQL(String table, String colName) { return "create index KEY_"+ table + "_" + colName + " on " + table + "(" + colName +")"; } public void createOrUpdateIfNecessary( Map<String,TableDef> schema) throws SQLException, RaplaException { String tablename = tableName; if (schema.get (tablename) != null ) { return; } getLogger().info("Creating table " + tablename); for (String createSQL : getCreateSQL()) { Statement stmt = con.createStatement(); try { stmt.execute(createSQL ); } finally { stmt.close(); } con.commit(); } schema.put( tablename, new TableDef(tablename,columns.values())); } protected ColumnDef getColumn(String name) { return columns.get( name); } protected void checkAndAdd(Map<String, TableDef> schema, String columnName) throws SQLException { ColumnDef col = getColumn(columnName); if ( col == null) { throw new IllegalArgumentException("Column " + columnName + " not found in table schema " + tableName); } String name = col.getName(); TableDef tableDef = schema.get(tableName); if (tableDef.getColumn(name) == null) { getLogger().warn("Patching Database for table " + tableName + " adding column "+ name); { String sql = "ALTER TABLE " + tableName + " ADD COLUMN "; sql += getColumnCreateStatemet( col, true, true); Statement stmt = con.createStatement(); try { stmt.execute( sql); } finally { stmt.close(); } con.commit(); } if ( col.isKey() && !col.isPrimary()) { String sql = createKeySQL(tableName, name); getLogger().info("Adding index for " + name); Statement stmt = con.createStatement(); try { stmt.execute( sql); } finally { stmt.close(); } con.commit(); } } } protected String getDatabaseProductType(String type) { if ( type.equals("TEXT")) { if ( isHsqldb()) { return "VARCHAR(16777216)"; } if ( isMysql()) { return "LONGTEXT"; } if ( isH2()) { return "CLOB"; } } if ( type.equals("DATETIME")) { if ( !isH2() && !isMysql()) { return "TIMESTAMP"; } } return type; } protected void checkAndRename( Map<String, TableDef> schema, String oldColumnName, String newColumnName) throws SQLException { String errorPrefix = "Can't rename " + oldColumnName + " " + newColumnName + " in table " + tableName; TableDef tableDef = schema.get(tableName); if (tableDef.getColumn( newColumnName) != null ) { return; } ColumnDef oldColumn = tableDef.getColumn( oldColumnName); if (oldColumn == null) { throw new SQLException(errorPrefix + " old column " + oldColumnName + " not found."); } ColumnDef newCol = getColumn(newColumnName); if ( newCol == null) { throw new IllegalArgumentException("Column " + newColumnName + " not found in table schema " + tableName); } getLogger().warn("Patching Database for table " + tableName + " renaming column "+ oldColumnName + " to " + newColumnName); String sql = "ALTER TABLE " + tableName + " RENAME COLUMN " + oldColumnName + " TO " + newColumnName; if ( isMysql()) { sql = "ALTER TABLE " + tableName + " CHANGE COLUMN " +oldColumnName + " "; String columnSql = getColumnCreateStatemet(newCol, false, true); sql+= columnSql; } Statement stmt = con.createStatement(); try { stmt.execute( sql); } finally { stmt.close(); } con.commit(); tableDef.removeColumn( oldColumnName); tableDef.addColumn( newCol); } protected void checkAndRetype(Map<String, TableDef> schema, String columnName) throws RaplaException { TableDef tableDef = schema.get(tableName); ColumnDef oldDef = tableDef.getColumn( columnName); ColumnDef newDef = getColumn(columnName); if (oldDef == null || newDef == null) { throw new RaplaException("Can't retype column " + columnName + " it is not found"); } boolean includePrimaryKey = false; boolean includeDefaults = false; String stmt1 = getColumnCreateStatemet(oldDef, includePrimaryKey, includeDefaults); String stmt2 = getColumnCreateStatemet(newDef, includePrimaryKey, includeDefaults); if ( stmt1.equals( stmt2)) { return; } String columnSql = getColumnCreateStatemet(newDef, false, true); getLogger().warn("Column "+ tableName + "."+ columnName + " change from '" + stmt1+ "' to new type '" + columnSql + "'"); getLogger().warn("You should patch the database accordingly."); // We do not autopatch colum types yet // String sql = "ALTER TABLE " + tableName + " ALTER COLUMN " ; // sql+= columnSql; // con.createStatement().execute(sql); } protected String getColumnCreateStatemet(ColumnDef col, boolean includePrimaryKey, boolean includeDefaults) { StringBuffer buf = new StringBuffer(); String colName = col.getName(); buf.append(colName); String type = getDatabaseProductType(col.getType()); buf.append(" " + type); if ( col.isNotNull()) { buf.append(" NOT NULL"); } else { buf.append(" NULL"); } if ( includeDefaults) { if ( type.equals("TIMESTAMP")) { if ( !isHsqldb() && !isH2()) { buf.append( " DEFAULT " + "'2000-01-01 00:00:00'"); } } else if ( col.getDefaultValue() != null) { buf.append( " DEFAULT " + col.getDefaultValue()); } } if (includePrimaryKey && col.isPrimary()) { buf.append(" PRIMARY KEY"); } String columnSql =buf.toString(); return columnSql; } protected boolean isMysql() { boolean result = dbProductName.indexOf("mysql") >=0; return result; } protected boolean isHsqldb() { boolean result = dbProductName.indexOf("hsql") >=0; return result; } protected boolean isPostgres() { boolean result = dbProductName.indexOf("postgres") >=0; return result; } protected boolean isH2() { boolean result = dbProductName.indexOf("h2") >=0; return result; } protected void checkRenameTable( Map<String, TableDef> tableMap, String oldTableName) throws SQLException { boolean isOldTableName = false; if ( tableMap.get( oldTableName) != null) { isOldTableName = true; } if ( tableMap.get(tableName) != null) { isOldTableName = false; } if ( isOldTableName) { getLogger().warn("Table " + tableName + " not found. Patching Database : Renaming " + oldTableName + " to "+ tableName); String sql = "ALTER TABLE " + oldTableName + " RENAME TO " + tableName + ""; Statement stmt = con.createStatement(); try { stmt.execute( sql); } finally { stmt.close(); } con.commit(); tableMap.put( tableName, tableMap.get( oldTableName)); tableMap.remove( oldTableName); } } protected void checkAndDrop(Map<String, TableDef> schema, String columnName) throws SQLException { TableDef tableDef = schema.get(tableName); if (tableDef.getColumn(columnName) != null) { String sql = "ALTER TABLE " + tableName + " DROP COLUMN " + columnName; Statement stmt = con.createStatement(); try { stmt.execute( sql); } finally { stmt.close(); } } con.commit(); } @Override public void dropTable() throws SQLException { getLogger().info("Dropping table " + tableName); String sql = "DROP TABLE " + tableName ; Statement stmt = con.createStatement(); try { stmt.execute( sql); } finally { stmt.close(); } con.commit(); } protected void addSubStorage(Storage<T> subStore) { subStores.add(subStore); } public Collection<Storage<T>> getSubStores() { return subStores; } public void setConnection(Connection con) throws SQLException { this.con= con; for (Storage<T> subStore: subStores) { subStore.setConnection(con); } if ( con != null) { String databaseProductName = con.getMetaData().getDatabaseProductName(); if ( databaseProductName != null) { Locale locale = Locale.ENGLISH; dbProductName = databaseProductName.toLowerCase(locale); } } } public Locale getLocale() { return raplaLocale.getLocale(); } protected String getEntryList(Collection<ColumnDef> entries) { StringBuffer buf = new StringBuffer(); for (ColumnDef col: entries) { if (buf.length() > 0 ) { buf.append(", "); } buf.append(col.getName()); } return buf.toString(); } protected String getMarkerList(int length) { StringBuffer buf = new StringBuffer(); for (int i=0;i<length; i++) { buf.append('?'); if (i < length - 1) { buf.append(','); } } return buf.toString(); } protected String getUpdateList(Collection<ColumnDef> entries) { StringBuffer buf = new StringBuffer(); for (ColumnDef col: entries) { if (buf.length() > 0 ) { buf.append(", "); } buf.append(col.getName()); buf.append("=? "); } return buf.toString(); } public static void executeBatchedStatement(Connection con,String sql) throws SQLException { Statement stmt = null; try { stmt = con.createStatement(); StringTokenizer tokenizer = new StringTokenizer(sql,";"); while (tokenizer.hasMoreTokens()) stmt.executeUpdate(tokenizer.nextToken()); } finally { if (stmt!=null) stmt.close(); } } public void loadAll() throws SQLException,RaplaException { Statement stmt = null; ResultSet rset = null; try { stmt = con.createStatement(); rset = stmt.executeQuery(selectSql); while (rset.next ()) { load(rset); } } finally { if (rset != null) rset.close(); if (stmt!=null) stmt.close(); } for (Storage storage: subStores) { storage.loadAll(); } } public void insert(Iterable<T> entities) throws SQLException,RaplaException { for (Storage<T> storage: subStores) { storage.insert(entities); } PreparedStatement stmt = null; try { stmt = con.prepareStatement(insertSql); int count = 0; for ( T entity: entities) { count+= write(stmt, entity); } if ( count > 0) { stmt.executeBatch(); } } catch (SQLException ex) { throw ex; } finally { if (stmt!=null) stmt.close(); } } // public void update(Collection<Entity>> entities ) throws SQLException,RaplaException { // for (Storage<T> storage: subStores) { // storage.delete( entities ); // storage.insert( entities); // } // PreparedStatement stmt = null; // try { // stmt = con.prepareStatement( updateSql); // int count = 0; // for (Entity entity: entities) // { // int id = getId( entity ); // stmt.setInt( lastParameterIndex + 1,id ); // count+=write(stmt, entity); // } // if ( count > 0) // { // stmt.executeBatch(); // } // } finally { // if (stmt!=null) // stmt.close(); // } // } // public void save(Collection<Entity>> entities) throws SQLException,RaplaException { // Collection<Entity>> toUpdate = new ArrayList<Entity>>(); // Collection<Entity>> toInsert = new ArrayList<Entity>>(); // for (Entity entity:entities) // { // // if (cache.tryResolve( entity.getId())!= null) { // toUpdate.add( entity ); // } else { // toInsert.add( entity ); // } // } // if ( !toInsert.isEmpty()) // { // insert( toInsert); // } // if ( !toUpdate.isEmpty()) // { // update( toUpdate); // } // } public void save( Iterable<T> entities ) throws RaplaException, SQLException{ deleteEntities( entities ); insert( entities ); } public void deleteEntities(Iterable<T> entities) throws SQLException, RaplaException { Set<String> ids = new HashSet<String>(); for ( T entity: entities) { ids.add( entity.getId()); } deleteIds(ids); } public void deleteIds(Collection<String> ids) throws SQLException, RaplaException { for (Storage<T> storage: subStores) { storage.deleteIds( ids); } PreparedStatement stmt = null; try { stmt = con.prepareStatement(deleteSql); for ( String id: ids) { stmt.setString(1,id); stmt.addBatch(); } if ( ids.size() > 0) { stmt.executeBatch(); } } finally { if (stmt!=null) stmt.close(); } } public void deleteAll() throws SQLException { for (Storage<T> subStore: subStores) { subStore.deleteAll(); } executeBatchedStatement(con,deleteAllSql); } abstract protected int write(PreparedStatement stmt,T entity) throws SQLException,RaplaException; abstract protected void load(ResultSet rs) throws SQLException,RaplaException; public RaplaNonValidatedInput getReader() throws RaplaException { return lookup( RaplaNonValidatedInput.class); } public RaplaXMLReader getReaderFor( RaplaType type) throws RaplaException { Map<RaplaType,RaplaXMLReader> readerMap = lookup( PreferenceReader.READERMAP); return readerMap.get( type); } public RaplaXMLWriter getWriterFor( RaplaType type) throws RaplaException { Map<RaplaType,RaplaXMLWriter> writerMap = lookup( PreferenceWriter.WRITERMAP ); return writerMap.get( type); } protected <S> S lookup( TypedComponentRole<S> role) throws RaplaException { try { return context.lookup( role); } catch (RaplaContextException e) { throw new RaplaException( e); } } protected <S> S lookup( Class<S> role) throws RaplaException { try { return context.lookup( role); } catch (RaplaContextException e) { throw new RaplaException( e); } } protected void put( Entity entity) { entityStore.put( entity); } protected EntityResolver getResolver() { return entityStore; } protected void putPassword( String userId, String password ) { entityStore.putPassword( userId, password); } protected DynamicType getDynamicType( String typeKey ) { return entityStore.getDynamicType( typeKey); } protected Category getSuperCategory() { if ( cache != null) { return cache.getSuperCategory(); } return entityStore.getSuperCategory(); } protected void setText(PreparedStatement stmt, int columIndex, String xml) throws SQLException { if ( isHsqldb() || isH2()) { if (xml != null) { Clob clob = con.createClob(); clob.setString(1, xml); stmt.setClob( columIndex, clob); } else { stmt.setObject( columIndex, null, Types.CLOB); } } else { stmt.setString( columIndex, xml); } } protected String getText(ResultSet rset, int columnIndex) throws SQLException { String xml = null; if ( isMysql()) { Clob clob = rset.getClob( columnIndex ); if ( clob!= null) { int length = (int)clob.length(); if ( length > 0) { xml = clob.getSubString(1, length); // String xml = rset.getString( 4); } } } else { xml = rset.getString(columnIndex); } return xml; } }
04900db4-rob
src/org/rapla/storage/dbsql/EntityStorage.java
Java
gpl3
28,357
package org.rapla.storage.dbsql; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Locale; public class ColumnDef { String name; boolean key; boolean primary; boolean notNull; String type; String defaultValue; public ColumnDef(String unparsedEntry) { // replace all double " " with single " " while (true) { String replaceAll = unparsedEntry.replaceAll(" ", " ").trim(); if ( replaceAll.equals( unparsedEntry)) { break; } unparsedEntry = replaceAll; } String[] split = unparsedEntry.split(" "); name = split[0]; type = split[1]; for ( int i=2;i< split.length;i++) { String s = split[i]; if ( s.equalsIgnoreCase("KEY")) { key = true; } if ( s.equalsIgnoreCase("PRIMARY")) { primary = true; } if ( s.equalsIgnoreCase("NOT") && i<split.length -1 && split[i+1].equals("NULL")) { notNull = true; } if ( s.equalsIgnoreCase("DEFAULT") && i<split.length -1) { defaultValue = split[i+1]; } } } public ColumnDef(ResultSet set) throws SQLException { name = set.getString("COLUMN_NAME").toUpperCase(Locale.ENGLISH); type = set.getString("TYPE_NAME").toUpperCase(Locale.ENGLISH); int nullableInt = set.getInt( "NULLABLE"); notNull = nullableInt <=0; int charLength = set.getInt("CHAR_OCTET_LENGTH"); if ( type.equals("VARCHAR") && charLength>0) { type +="("+charLength+")"; } /* int nullbable = set. COLUMN_NAME String => column name DATA_TYPE int => SQL type from java.sql.Types TYPE_NAME String => Data source dependent type name, for a UDT the type name is fully qualified COLUMN_SIZE int => column size. BUFFER_LENGTH is not used. DECIMAL_DIGITS int => the number of fractional digits. Null is returned for data types where DECIMAL_DIGITS is not applicable. NUM_PREC_RADIX int => Radix (typically either 10 or 2) NULLABLE int => is NULL allowed. */ } public String getName() { return name; } public boolean isKey() { return key; } public boolean isPrimary() { return primary; } public boolean isNotNull() { return notNull; } public String getType() { return type; } public String getDefaultValue() { return defaultValue; } @Override public String toString() { return "Column [name=" + name + ", key=" + key + ", primary=" + primary + ", notNull=" + notNull + ", type=" + type + ", defaultValue=" + defaultValue + "]"; } public boolean isIntType() { if ( type == null) { return false; } String lowerCase = type.toLowerCase(); return (lowerCase.contains("int")); } }
04900db4-rob
src/org/rapla/storage/dbsql/ColumnDef.java
Java
gpl3
2,676
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, of which license fullfill the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbsql; import java.io.BufferedWriter; import java.io.IOException; import java.io.StringWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.rapla.components.util.Assert; import org.rapla.components.util.DateTools; import org.rapla.components.util.xml.RaplaNonValidatedInput; import org.rapla.entities.Annotatable; import org.rapla.entities.Category; 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.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.Repeating; import org.rapla.entities.domain.RepeatingType; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.domain.internal.PermissionImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.AttributeImpl; import org.rapla.entities.dynamictype.internal.ClassificationImpl; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.internal.UserImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; import org.rapla.storage.PreferencePatch; import org.rapla.storage.xml.CategoryReader; import org.rapla.storage.xml.PreferenceReader; import org.rapla.storage.xml.RaplaXMLReader; import org.rapla.storage.xml.RaplaXMLWriter; class RaplaSQL { private final List<RaplaTypeStorage> stores = new ArrayList<RaplaTypeStorage>(); private final Logger logger; RaplaContext context; PreferenceStorage preferencesStorage; RaplaSQL( RaplaContext context) throws RaplaException{ this.context = context; logger = context.lookup( Logger.class); // The order is important. e.g. appointments can only be loaded if the reservation they are refering to are already loaded. stores.add(new CategoryStorage( context)); stores.add(new DynamicTypeStorage( context)); stores.add(new UserStorage( context)); stores.add(new AllocatableStorage( context)); preferencesStorage = new PreferenceStorage( context); stores.add(preferencesStorage); ReservationStorage reservationStorage = new ReservationStorage( context); stores.add(reservationStorage); AppointmentStorage appointmentStorage = new AppointmentStorage( context); stores.add(appointmentStorage); // now set delegate because reservation storage should also use appointment storage reservationStorage.setAppointmentStorage( appointmentStorage); } private List<Storage<?>> getStoresWithChildren() { List<Storage<?>> storages = new ArrayList<Storage<?>>(); for ( RaplaTypeStorage store:stores) { storages.add( store); @SuppressWarnings("unchecked") Collection<Storage<?>> subStores = store.getSubStores(); storages.addAll( subStores); } return storages; } protected Logger getLogger() { return logger; } /*************************************************** * Create everything * ***************************************************/ synchronized public void createAll(Connection con) throws SQLException,RaplaException { for (RaplaTypeStorage storage: stores) { storage.setConnection(con); try { storage.insertAll(); } finally { storage.setConnection( null); } } } synchronized public void removeAll(Connection con) throws SQLException { for (RaplaTypeStorage storage: stores) { storage.setConnection(con); try { storage.deleteAll(); } finally { storage.setConnection( null); } } } synchronized public void loadAll(Connection con) throws SQLException,RaplaException { for (Storage storage:stores) { storage.setConnection(con); try { storage.loadAll(); } finally { storage.setConnection( null); } } } @SuppressWarnings("unchecked") synchronized public void remove(Connection con,Entity entity) throws SQLException,RaplaException { if ( Attribute.TYPE == entity.getRaplaType() ) return; for (RaplaTypeStorage storage:stores) { if (storage.canStore(entity)) { storage.setConnection(con); try { List<Entity>list = new ArrayList<Entity>(); list.add( entity); storage.deleteEntities(list); } finally { storage.setConnection(null); } return; } } throw new RaplaException("No Storage-Sublass matches this object: " + entity.getClass()); } @SuppressWarnings("unchecked") synchronized public void store(Connection con, Collection<Entity>entities) throws SQLException,RaplaException { Map<Storage,List<Entity>> store = new LinkedHashMap<Storage, List<Entity>>(); for ( Entity entity:entities) { if ( Attribute.TYPE == entity.getRaplaType() ) continue; boolean found = false; for ( RaplaTypeStorage storage: stores) { if (storage.canStore(entity)) { List<Entity>list = store.get( storage); if ( list == null) { list = new ArrayList<Entity>(); store.put( storage, list); } list.add( entity); found = true; } } if (!found) { throw new RaplaException("No Storage-Sublass matches this object: " + entity.getClass()); } } for ( Storage storage: store.keySet()) { storage.setConnection(con); try { List<Entity>list = store.get( storage); storage.save(list); } finally { storage.setConnection( null); } } } public void createOrUpdateIfNecessary(Connection con, Map<String, TableDef> schema) throws SQLException, RaplaException { // Upgrade db if necessary for (Storage<?> storage:getStoresWithChildren()) { storage.setConnection(con); try { storage.createOrUpdateIfNecessary( schema); } finally { storage.setConnection( null); } } } public void storePatches(Connection connection, List<PreferencePatch> preferencePatches) throws SQLException, RaplaException { PreferenceStorage storage = preferencesStorage; storage.setConnection( connection); try { preferencesStorage.storePatches( preferencePatches); } finally { storage.setConnection( null); } } } abstract class RaplaTypeStorage<T extends Entity<T>> extends EntityStorage<T> { RaplaType raplaType; RaplaTypeStorage( RaplaContext context, RaplaType raplaType, String tableName, String[] entries) throws RaplaException { super( context,tableName, entries ); this.raplaType = raplaType; } boolean canStore(Entity entity) { return entity.getRaplaType() == raplaType; } abstract void insertAll() throws SQLException,RaplaException; protected String getXML(RaplaObject type) throws RaplaException { RaplaXMLWriter dynamicTypeWriter = getWriterFor( type.getRaplaType()); StringWriter stringWriter = new StringWriter(); BufferedWriter bufferedWriter = new BufferedWriter(stringWriter); dynamicTypeWriter.setWriter( bufferedWriter ); dynamicTypeWriter.setSQL( true ); try { dynamicTypeWriter.writeObject(type); bufferedWriter.flush(); } catch (IOException ex) { throw new RaplaException( ex); } return stringWriter.getBuffer().toString(); } protected RaplaXMLReader processXML(RaplaType type, String xml) throws RaplaException { RaplaXMLReader reader = getReaderFor( type); if ( xml== null || xml.trim().length() <= 10) { throw new RaplaException("Can't load " + type); } String xmlWithNamespaces = RaplaXMLReader.wrapRaplaDataTag(xml); RaplaNonValidatedInput parser = getReader(); parser.read(xmlWithNamespaces, reader, logger); return reader; } } class CategoryStorage extends RaplaTypeStorage<Category> { Map<Category,Integer> orderMap = new HashMap<Category,Integer>(); Map<Category,String> categoriesWithoutParent = new TreeMap<Category,String>(new Comparator<Category>() { public int compare( Category o1, Category o2 ) { if ( o1.equals( o2)) { return 0; } int ordering1 = ( orderMap.get( o1 )).intValue(); int ordering2 = (orderMap.get( o2 )).intValue(); if ( ordering1 < ordering2) { return -1; } if ( ordering1 > ordering2) { return 1; } if (o1.hashCode() > o2.hashCode()) { return -1; } else { return 1; } } } ); public CategoryStorage(RaplaContext context) throws RaplaException { super(context,Category.TYPE, "CATEGORY",new String[] {"ID VARCHAR(255) NOT NULL PRIMARY KEY","PARENT_ID VARCHAR(255) KEY","CATEGORY_KEY VARCHAR(255) NOT NULL","DEFINITION TEXT NOT NULL","PARENT_ORDER INTEGER"}); } @Override public void deleteEntities(Iterable<Category> entities) throws SQLException,RaplaException { Set<String> idList = new HashSet<String>(); for ( Category cat:entities) { idList.addAll( getIds( cat.getId())); } deleteIds(idList); } @Override public void insert(Iterable<Category> entities) throws SQLException, RaplaException { Set<Category> transitiveCategories = new LinkedHashSet<Category>(); for ( Category cat: entities) { transitiveCategories.add( cat); transitiveCategories.addAll(getAllChilds( cat )); } super.insert(transitiveCategories); } private Collection<Category> getAllChilds(Category cat) { Set<Category> allChilds = new LinkedHashSet<Category>(); allChilds.add( cat); for ( Category child: cat.getCategories()) { allChilds.addAll(getAllChilds( child )); } return allChilds; } private Collection<String> getIds(String parentId) throws SQLException, RaplaException { Set<String> childIds = new HashSet<String>(); String sql = "SELECT ID FROM CATEGORY WHERE PARENT_ID=?"; PreparedStatement stmt = null; ResultSet rset = null; try { stmt = con.prepareStatement(sql); setString(stmt,1, parentId); rset = stmt.executeQuery(); while (rset.next ()) { String id = readId(rset, 1, Category.class); childIds.add( id); } } finally { if (rset != null) rset.close(); if (stmt!=null) stmt.close(); } Set<String> result = new HashSet<String>(); for (String childId : childIds) { result.addAll( getIds( childId)); } result.add( parentId); return result; } @Override protected int write(PreparedStatement stmt,Category category) throws SQLException, RaplaException { Category root = getSuperCategory(); if ( category.equals( root )) return 0; setId( stmt,1, category); setId( stmt,2, category.getParent()); int order = getOrder( category); String xml = getXML( category ); setString(stmt,3, category.getKey()); setText(stmt,4, xml); setInt( stmt,5, order); stmt.addBatch(); return 1; } private int getOrder( Category category ) { Category parent = category.getParent(); if ( parent == null) { return 0; } Category[] childs = parent.getCategories(); for ( int i=0;i<childs.length;i++) { if ( childs[i].equals( category)) { return i; } } getLogger().error("Category not found in parent"); return 0; } public RaplaXMLReader getReaderFor( RaplaType type) throws RaplaException { RaplaXMLReader reader = super.getReaderFor( type ); if ( type.equals( Category.TYPE ) ) { ((CategoryReader) reader).setReadOnlyThisCategory( true); } return reader; } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { String id = readId(rset, 1, Category.class); String parentId = readId(rset, 2, Category.class, true); String xml = getText( rset, 4 ); Integer order = getInt(rset, 5 ); CategoryImpl category; if ( xml != null && xml.length() > 10 ) { category = ((CategoryReader)processXML( Category.TYPE, xml )).getCurrentCategory(); //cache.remove( category ); } else { getLogger().warn("Category has empty xml field. Ignoring."); return; } category.setId( id); put( category ); orderMap.put( category, order); // parentId can also be null categoriesWithoutParent.put( category, parentId); } @Override public void loadAll() throws RaplaException, SQLException { categoriesWithoutParent.clear(); super.loadAll(); // then we rebuild the hierarchy Iterator<Map.Entry<Category,String>> it = categoriesWithoutParent.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Category,String> entry = it.next(); String parentId = entry.getValue(); Category category = entry.getKey(); Category parent; Assert.notNull( category ); if ( parentId != null) { parent = entityStore.resolve( parentId ,Category.class); } else { parent = getSuperCategory(); } Assert.notNull( parent ); parent.addCategory( category ); } } @Override void insertAll() throws SQLException, RaplaException { CategoryImpl superCategory = cache.getSuperCategory(); Set<Category> childs = new HashSet<Category>(); addChildren(childs, superCategory); insert( childs); } private void addChildren(Collection<Category> list, Category category) { for (Category child:category.getCategories()) { list.add( child ); addChildren(list, child); } } } class AllocatableStorage extends RaplaTypeStorage<Allocatable> { Map<String,Classification> classificationMap = new HashMap<String,Classification>(); Map<String,Allocatable> allocatableMap = new HashMap<String,Allocatable>(); AttributeValueStorage<Allocatable> resourceAttributeStorage; PermissionStorage permissionStorage; public AllocatableStorage(RaplaContext context ) throws RaplaException { super(context,Allocatable.TYPE,"RAPLA_RESOURCE",new String [] {"ID VARCHAR(255) NOT NULL PRIMARY KEY","TYPE_KEY VARCHAR(255) NOT NULL","OWNER_ID VARCHAR(255)","CREATION_TIME TIMESTAMP","LAST_CHANGED TIMESTAMP","LAST_CHANGED_BY VARCHAR(255) DEFAULT NULL"}); resourceAttributeStorage = new AttributeValueStorage<Allocatable>(context,"RESOURCE_ATTRIBUTE_VALUE", "RESOURCE_ID",classificationMap, allocatableMap); permissionStorage = new PermissionStorage( context, allocatableMap); addSubStorage(resourceAttributeStorage); addSubStorage(permissionStorage ); } @Override void insertAll() throws SQLException, RaplaException { insert( cache.getAllocatables()); } @Override protected int write(PreparedStatement stmt,Allocatable entity) throws SQLException,RaplaException { AllocatableImpl allocatable = (AllocatableImpl) entity; String typeKey = allocatable.getClassification().getType().getKey(); setId(stmt, 1, entity); setString(stmt,2, typeKey ); org.rapla.entities.Timestamp timestamp = allocatable; setId(stmt,3, allocatable.getOwner() ); setTimestamp(stmt, 4,timestamp.getCreateTime() ); setTimestamp(stmt, 5,timestamp.getLastChanged() ); setId( stmt,6,timestamp.getLastChangedBy() ); stmt.addBatch(); return 1; } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { String id= readId(rset,1, Allocatable.class); String typeKey = getString(rset,2 , null); final Date createDate = getTimestampOrNow( rset, 4); final Date lastChanged = getTimestampOrNow( rset, 5); AllocatableImpl allocatable = new AllocatableImpl(createDate, lastChanged); allocatable.setLastChangedBy( resolveFromId(rset, 6, User.class) ); allocatable.setId( id); allocatable.setResolver( entityStore); DynamicType type = null; if ( typeKey != null) { type = getDynamicType(typeKey ); } if ( type == null) { getLogger().error("Allocatable with id " + id + " has an unknown type " + typeKey + ". Try ignoring it"); return; } allocatable.setOwner( resolveFromId(rset, 3, User.class) ); Classification classification = type.newClassification(false); allocatable.setClassification( classification ); classificationMap.put( id, classification ); allocatableMap.put( id, allocatable); put( allocatable ); } @Override public void loadAll() throws RaplaException, SQLException { classificationMap.clear(); super.loadAll(); } } class ReservationStorage extends RaplaTypeStorage<Reservation> { Map<String,Classification> classificationMap = new HashMap<String,Classification>(); Map<String,Reservation> reservationMap = new HashMap<String,Reservation>(); AttributeValueStorage<Reservation> attributeValueStorage; // appointmentstorage is not a sub store but a delegate AppointmentStorage appointmentStorage; public ReservationStorage(RaplaContext context) throws RaplaException { super(context,Reservation.TYPE, "EVENT",new String [] {"ID VARCHAR(255) NOT NULL PRIMARY KEY","TYPE_KEY VARCHAR(255) NOT NULL","OWNER_ID VARCHAR(255) NOT NULL","CREATION_TIME TIMESTAMP","LAST_CHANGED TIMESTAMP","LAST_CHANGED_BY VARCHAR(255) DEFAULT NULL"}); attributeValueStorage = new AttributeValueStorage<Reservation>(context,"EVENT_ATTRIBUTE_VALUE","EVENT_ID", classificationMap, reservationMap); addSubStorage(attributeValueStorage); } public void setAppointmentStorage(AppointmentStorage appointmentStorage) { this.appointmentStorage = appointmentStorage; } @Override void insertAll() throws SQLException, RaplaException { insert( cache.getReservations()); } @Override public void save(Iterable<Reservation> entities) throws RaplaException, SQLException { super.save(entities); Collection<Appointment> appointments = new ArrayList<Appointment>(); for (Reservation r: entities) { appointments.addAll( Arrays.asList(r.getAppointments())); } appointmentStorage.insert( appointments ); } @Override public void setConnection(Connection con) throws SQLException { super.setConnection(con); appointmentStorage.setConnection(con); } @Override protected int write(PreparedStatement stmt,Reservation event) throws SQLException,RaplaException { String typeKey = event.getClassification().getType().getKey(); setId(stmt,1, event ); setString(stmt,2, typeKey ); setId(stmt,3, event.getOwner() ); org.rapla.entities.Timestamp timestamp = event; setTimestamp( stmt,4,timestamp.getCreateTime()); setTimestamp( stmt,5,timestamp.getLastChanged()); setId(stmt, 6, timestamp.getLastChangedBy()); stmt.addBatch(); return 1; } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { final Date createDate = getTimestampOrNow(rset,4); final Date lastChanged = getTimestampOrNow(rset,5); ReservationImpl event = new ReservationImpl(createDate, lastChanged); String id = readId(rset,1,Reservation.class); event.setId( id); event.setResolver( entityStore); String typeKey = getString(rset,2,null); DynamicType type = null; if ( typeKey != null) { type = getDynamicType(typeKey ); } if ( type == null) { getLogger().error("Reservation with id " + id + " has an unknown type " + typeKey + ". Try ignoring it"); return; } User user = resolveFromId(rset, 3, User.class); if ( user == null ) { return; } event.setOwner( user ); event.setLastChangedBy( resolveFromId(rset, 6, User.class) ); Classification classification = type.newClassification(false); event.setClassification( classification ); classificationMap.put( id, classification ); reservationMap.put( id, event ); put( event ); } @Override public void loadAll() throws RaplaException, SQLException { classificationMap.clear(); super.loadAll(); } @Override public void deleteEntities(Iterable<Reservation> entities) throws SQLException, RaplaException { super.deleteEntities(entities); deleteAppointments(entities); } private void deleteAppointments(Iterable<Reservation> entities) throws SQLException, RaplaException { Set<String> ids = new HashSet<String>(); String sql = "SELECT ID FROM APPOINTMENT WHERE EVENT_ID=?"; for (Reservation entity:entities) { PreparedStatement stmt = null; ResultSet rset = null; try { stmt = con.prepareStatement(sql); String eventId = entity.getId(); setString(stmt,1, eventId); rset = stmt.executeQuery(); while (rset.next ()) { String appointmentId = readId(rset, 1, Appointment.class); ids.add( appointmentId); } } finally { if (rset != null) rset.close(); if (stmt!=null) stmt.close(); } } // and delete them appointmentStorage.deleteIds( ids); } } class AttributeValueStorage<T extends Entity<T>> extends EntityStorage<T> { Map<String,Classification> classificationMap; Map<String,? extends Annotatable> annotableMap; final String foreignKeyName; // TODO Write conversion script to update all old entries to new entries public final static String OLD_ANNOTATION_PREFIX = "annotation:"; public final static String ANNOTATION_PREFIX = "rapla:"; public AttributeValueStorage(RaplaContext context,String tablename, String foreignKeyName, Map<String,Classification> classificationMap, Map<String, ? extends Annotatable> annotableMap) throws RaplaException { super(context, tablename, new String[]{foreignKeyName + " VARCHAR(255) NOT NULL KEY","ATTRIBUTE_KEY VARCHAR(255)","ATTRIBUTE_VALUE VARCHAR(20000)"}); this.foreignKeyName = foreignKeyName; this.classificationMap = classificationMap; this.annotableMap = annotableMap; } @Override protected int write(PreparedStatement stmt,T classifiable) throws EntityNotFoundException, SQLException { Classification classification = ((Classifiable)classifiable).getClassification(); Attribute[] attributes = classification.getAttributes(); int count =0; for (int i=0;i<attributes.length;i++) { Attribute attribute = attributes[i]; Collection<Object> values = classification.getValues( attribute ); for (Object value: values) { String valueAsString; if ( value instanceof Category || value instanceof Allocatable) { Entity casted = (Entity) value; valueAsString = casted.getId(); } else { valueAsString = AttributeImpl.attributeValueToString( attribute, value, true); } setId(stmt,1, classifiable); setString(stmt,2, attribute.getKey()); setString(stmt,3, valueAsString); stmt.addBatch(); count++; } } Annotatable annotatable = (Annotatable)classifiable; for ( String key: annotatable.getAnnotationKeys()) { String valueAsString = annotatable.getAnnotation( key); setId(stmt,1, classifiable); setString(stmt,2, ANNOTATION_PREFIX + key); setString(stmt,3, valueAsString); stmt.addBatch(); count++; } return count; } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { Class<? extends Entity> idClass = foreignKeyName.indexOf("RESOURCE")>=0 ? Allocatable.class : Reservation.class; String classifiableId = readId(rset, 1, idClass); String attributekey = rset.getString( 2 ); boolean annotationPrefix = attributekey.startsWith(ANNOTATION_PREFIX); boolean oldAnnotationPrefix = attributekey.startsWith(OLD_ANNOTATION_PREFIX); if ( annotationPrefix || oldAnnotationPrefix) { String annotationKey = attributekey.substring( annotationPrefix ? ANNOTATION_PREFIX.length() : OLD_ANNOTATION_PREFIX.length()); Annotatable annotatable = annotableMap.get(classifiableId); if (annotatable != null) { String valueAsString = rset.getString( 3); if ( rset.wasNull() || valueAsString == null) { annotatable.setAnnotation(annotationKey, null); } else { annotatable.setAnnotation(annotationKey, valueAsString); } } else { getLogger().warn("No resource or reservation found for the id " + classifiableId + " ignoring."); } } else { ClassificationImpl classification = (ClassificationImpl) classificationMap.get(classifiableId); if ( classification == null) { getLogger().warn("No resource or reservation found for the id " + classifiableId + " ignoring."); return; } Attribute attribute = classification.getType().getAttribute( attributekey ); if ( attribute == null) { getLogger().error("DynamicType '" +classification.getType() +"' doesnt have an attribute with the key " + attributekey + " Current allocatable/reservation Id " + classifiableId + ". Ignoring attribute."); return; } String valueAsString = rset.getString( 3); if ( valueAsString != null ) { Object value = AttributeImpl.parseAttributeValue(attribute, valueAsString); classification.addValue( attribute, value); } } } } class PermissionStorage extends EntityStorage<Allocatable> { Map<String,Allocatable> allocatableMap; public PermissionStorage(RaplaContext context,Map<String,Allocatable> allocatableMap) throws RaplaException { super(context,"PERMISSION",new String[] {"RESOURCE_ID VARCHAR(255) NOT NULL KEY","USER_ID VARCHAR(255)","GROUP_ID VARCHAR(255)","ACCESS_LEVEL INTEGER NOT NULL","MIN_ADVANCE INTEGER","MAX_ADVANCE INTEGER","START_DATE DATETIME","END_DATE DATETIME"}); this.allocatableMap = allocatableMap; } protected int write(PreparedStatement stmt, Allocatable allocatable) throws SQLException, RaplaException { int count = 0; for (Permission s:allocatable.getPermissions()) { setId(stmt,1,allocatable); setId(stmt,2,s.getUser()); setId(stmt,3,s.getGroup()); setInt(stmt,4, s.getAccessLevel()); setInt( stmt,5, s.getMinAdvance()); setInt( stmt,6, s.getMaxAdvance()); setDate(stmt,7, s.getStart()); setDate(stmt,8, s.getEnd()); stmt.addBatch(); count ++; } return count; } protected void load(ResultSet rset) throws SQLException, RaplaException { String allocatableIdInt = readId(rset, 1, Allocatable.class); Allocatable allocatable = allocatableMap.get(allocatableIdInt); if ( allocatable == null) { getLogger().warn("Could not find resource object with id "+ allocatableIdInt + " for permission. Maybe the resource was deleted from the database."); return; } PermissionImpl permission = new PermissionImpl(); permission.setUser( resolveFromId(rset, 2, User.class)); permission.setGroup( resolveFromId(rset, 3, Category.class)); Integer accessLevel = getInt( rset, 4); // We multiply the access levels to add a more access levels between. if ( accessLevel !=null) { if ( accessLevel < 5) { accessLevel *= 100; } permission.setAccessLevel( accessLevel ); } permission.setMinAdvance( getInt(rset,5)); permission.setMaxAdvance( getInt(rset,6)); permission.setStart(getDate(rset, 7)); permission.setEnd(getDate(rset, 8)); // We need to add the permission at the end to ensure its unique. Permissions are stored in a set and duplicates are removed during the add method allocatable.addPermission( permission ); } } class AppointmentStorage extends RaplaTypeStorage<Appointment> { AppointmentExceptionStorage appointmentExceptionStorage; AllocationStorage allocationStorage; public AppointmentStorage(RaplaContext context) throws RaplaException { super(context, Appointment.TYPE,"APPOINTMENT",new String [] {"ID VARCHAR(255) NOT NULL PRIMARY KEY","EVENT_ID VARCHAR(255) NOT NULL KEY","APPOINTMENT_START DATETIME NOT NULL","APPOINTMENT_END DATETIME NOT NULL","REPETITION_TYPE VARCHAR(255)","REPETITION_NUMBER INTEGER","REPETITION_END DATETIME","REPETITION_INTERVAL INTEGER"}); appointmentExceptionStorage = new AppointmentExceptionStorage(context); allocationStorage = new AllocationStorage( context); addSubStorage(appointmentExceptionStorage); addSubStorage(allocationStorage); } @Override void insertAll() throws SQLException, RaplaException { Collection<Reservation> reservations = cache.getReservations(); Collection<Appointment> appointments = new LinkedHashSet<Appointment>(); for (Reservation r: reservations) { appointments.addAll( Arrays.asList(r.getAppointments())); } insert( appointments); } @Override protected int write(PreparedStatement stmt,Appointment appointment) throws SQLException,RaplaException { setId( stmt, 1, appointment); setId( stmt, 2, appointment.getReservation()); setDate(stmt, 3, appointment.getStart()); setDate(stmt, 4, appointment.getEnd()); Repeating repeating = appointment.getRepeating(); if ( repeating == null) { setString( stmt,5, null); setInt( stmt,6, null); setDate( stmt,7, null); setInt( stmt,8, null); } else { setString( stmt,5, repeating.getType().toString()); int number = repeating.getNumber(); setInt(stmt, 6, number >= 0 ? number : null); setDate(stmt, 7, repeating.getEnd()); setInt(stmt,8, repeating.getInterval()); } stmt.addBatch(); return 1; } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { String id = readId(rset, 1, Appointment.class); Reservation event = resolveFromId(rset, 2, Reservation.class); if ( event == null) { return; } Date start = getDate(rset,3); Date end = getDate(rset,4); boolean wholeDayAppointment = start.getTime() == DateTools.cutDate( start.getTime()) && end.getTime() == DateTools.cutDate( end.getTime()); AppointmentImpl appointment = new AppointmentImpl(start, end); appointment.setId( id); appointment.setWholeDays( wholeDayAppointment); event.addAppointment( appointment ); String repeatingType = getString( rset,5, null); if ( repeatingType != null ) { appointment.setRepeatingEnabled( true ); Repeating repeating = appointment.getRepeating(); repeating.setType( RepeatingType.findForString( repeatingType ) ); Date repeatingEnd = getDate(rset, 7); if ( repeatingEnd != null ) { repeating.setEnd( repeatingEnd); } else { Integer number = getInt( rset, 6); if ( number != null) { repeating.setNumber( number); } else { repeating.setEnd( null ); } } Integer interval = getInt( rset,8); if ( interval != null) repeating.setInterval( interval); } put( appointment ); } } class AllocationStorage extends EntityStorage<Appointment> { public AllocationStorage(RaplaContext context) throws RaplaException { super(context,"ALLOCATION",new String [] {"APPOINTMENT_ID VARCHAR(255) NOT NULL KEY", "RESOURCE_ID VARCHAR(255) NOT NULL", "PARENT_ORDER INTEGER"}); } @Override protected int write(PreparedStatement stmt, Appointment appointment) throws SQLException, RaplaException { Reservation event = appointment.getReservation(); int count = 0; for (Allocatable allocatable: event.getAllocatablesFor(appointment)) { setId(stmt,1, appointment); setId(stmt,2, allocatable); stmt.setObject(3, null); stmt.addBatch(); count++; } return count; } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { Appointment appointment =resolveFromId(rset,1, Appointment.class); if ( appointment == null) { return; } ReservationImpl event = (ReservationImpl) appointment.getReservation(); Allocatable allocatable = resolveFromId(rset, 2, Allocatable.class); if ( allocatable == null) { return; } if ( !event.hasAllocated( allocatable ) ) { event.addAllocatable( allocatable ); } Appointment[] appointments = event.getRestriction( allocatable ); Appointment[] newAppointments = new Appointment[ appointments.length+ 1]; System.arraycopy(appointments,0, newAppointments, 0, appointments.length ); newAppointments[ appointments.length] = appointment; if (event.getAppointmentList().size() > newAppointments.length ) { event.setRestriction( allocatable, newAppointments ); } else { event.setRestriction( allocatable, new Appointment[] {} ); } } } class AppointmentExceptionStorage extends EntityStorage<Appointment> { public AppointmentExceptionStorage(RaplaContext context) throws RaplaException { super(context,"APPOINTMENT_EXCEPTION",new String [] {"APPOINTMENT_ID VARCHAR(255) NOT NULL KEY","EXCEPTION_DATE DATETIME NOT NULL"}); } @Override protected int write(PreparedStatement stmt, Appointment entity) throws SQLException, RaplaException { Repeating repeating = entity.getRepeating(); int count = 0; if ( repeating == null) { return count; } for (Date exception: repeating.getExceptions()) { setId( stmt, 1, entity ); setDate( stmt,2, exception); stmt.addBatch(); count++; } return count; } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { Appointment appointment = resolveFromId( rset, 1, Appointment.class); if ( appointment == null) { return; } Repeating repeating = appointment.getRepeating(); if ( repeating != null) { Date date = getDate(rset,2 ); repeating.addException( date ); } } } class DynamicTypeStorage extends RaplaTypeStorage<DynamicType> { public DynamicTypeStorage(RaplaContext context) throws RaplaException { super(context, DynamicType.TYPE,"DYNAMIC_TYPE", new String [] {"ID VARCHAR(255) NOT NULL PRIMARY KEY","TYPE_KEY VARCHAR(255) NOT NULL","DEFINITION TEXT NOT NULL"});//, "CREATION_TIME TIMESTAMP","LAST_CHANGED TIMESTAMP","LAST_CHANGED_BY INTEGER DEFAULT NULL"}); } @Override protected int write(PreparedStatement stmt, DynamicType type) throws SQLException, RaplaException { if (((DynamicTypeImpl) type).isInternal()) { return 0; } setId(stmt,1,type); setString(stmt,2, type.getKey()); setText(stmt,3, getXML( type) ); // setDate(stmt, 4,timestamp.getCreateTime() ); // setDate(stmt, 5,timestamp.getLastChanged() ); // setId( stmt,6,timestamp.getLastChangedBy() ); stmt.addBatch(); return 1; } @Override void insertAll() throws SQLException, RaplaException { insert( cache.getDynamicTypes()); } protected void load(ResultSet rset) throws SQLException,RaplaException { String xml = getText(rset,3); processXML( DynamicType.TYPE, xml ); // final Date createDate = getDate( rset, 4); // final Date lastChanged = getDate( rset, 5); // // AllocatableImpl allocatable = new AllocatableImpl(createDate, lastChanged); // allocatable.setLastChangedBy( resolveFromId(rset, 6, User.class) ); } } class PreferenceStorage extends RaplaTypeStorage<Preferences> { public PreferenceStorage(RaplaContext context) throws RaplaException { super(context,Preferences.TYPE,"PREFERENCE", new String [] {"USER_ID VARCHAR(255) KEY","ROLE VARCHAR(255) NOT NULL","STRING_VALUE VARCHAR(10000)","XML_VALUE TEXT"}); } class PatchEntry { String userId; String role; } public void storePatches(List<PreferencePatch> preferencePatches) throws RaplaException, SQLException { for ( PreferencePatch patch:preferencePatches) { String userId = patch.getUserId(); PreparedStatement stmt = null; try { String deleteSqlWithRole = deleteSql + " and role=?"; stmt = con.prepareStatement(deleteSqlWithRole); for ( String role: patch.getRemovedEntries()) { setId(stmt, 1, userId); setString(stmt,2,role); stmt.addBatch(); } for ( String role: patch.keySet()) { setId(stmt, 1, userId); setString(stmt,2,role); stmt.addBatch(); } } finally { if (stmt!=null) stmt.close(); } } PreparedStatement stmt = null; try { stmt = con.prepareStatement(insertSql); int count = 0; for ( PreferencePatch patch:preferencePatches) { String userId = patch.getUserId(); for ( String role:patch.keySet()) { Object entry = patch.get( role); insterEntry(stmt, userId, role, entry); count++; } } if ( count > 0) { stmt.executeBatch(); } } catch (SQLException ex) { throw ex; } finally { if (stmt!=null) stmt.close(); } } @Override void insertAll() throws SQLException, RaplaException { List<Preferences> preferences = new ArrayList<Preferences>(); { PreferencesImpl systemPrefs = cache.getPreferencesForUserId(null); if ( systemPrefs != null) { preferences.add( systemPrefs); } } Collection<User> users = cache.getUsers(); for ( User user:users) { String userId = user.getId(); PreferencesImpl userPrefs = cache.getPreferencesForUserId(userId); if ( userPrefs != null) { preferences.add( userPrefs); } } insert( preferences); } @Override protected int write(PreparedStatement stmt, Preferences entity) throws SQLException, RaplaException { PreferencesImpl preferences = (PreferencesImpl) entity; User user = preferences.getOwner(); String userId = user != null ? user.getId():null; int count = 0; for (String role:preferences.getPreferenceEntries()) { Object entry = preferences.getEntry(role); insterEntry(stmt, userId, role, entry); count++; } return count; } private void insterEntry(PreparedStatement stmt, String userId, String role, Object entry) throws SQLException, RaplaException { setString( stmt, 1, userId); setString( stmt,2, role); String xml; String entryString; if ( entry instanceof String) { entryString = (String) entry; xml = null; } else { //System.out.println("Role " + role + " CHILDREN " + conf.getChildren().length); entryString = null; xml = getXML( (RaplaObject)entry); } setString( stmt,3, entryString); setText(stmt, 4, xml); stmt.addBatch(); } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { //findPreferences //check if value set // yes read value // no read xml String userId = readId(rset, 1,User.class, true); User owner; if ( userId == null || userId.equals(Preferences.SYSTEM_PREFERENCES_ID) ) { owner = null; } else { User user = entityStore.tryResolve( userId,User.class); if ( user != null) { owner = user; } else { getLogger().warn("User with id " + userId + " not found ingnoring preference entry."); return; } } String configRole = getString( rset, 2, null); String preferenceId = PreferencesImpl.getPreferenceIdFromUser(userId); if ( configRole == null) { getLogger().warn("Configuration role for " + preferenceId + " is null. Ignoring preference entry."); return; } String value = getString( rset,3, null); // if (PreferencesImpl.isServerEntry(configRole)) // { // entityStore.putServerPreferences(owner,configRole, value); // return; // } PreferencesImpl preferences = preferenceId != null ? (PreferencesImpl) entityStore.tryResolve( preferenceId, Preferences.class ): null; if ( preferences == null) { Date now =getCurrentTimestamp(); preferences = new PreferencesImpl(now,now); preferences.setId(preferenceId); preferences.setOwner(owner); put( preferences ); } if ( value!= null) { preferences.putEntryPrivate(configRole, value); } else { String xml = getText(rset, 4); if ( xml != null && xml.length() > 0) { PreferenceReader contentHandler = (PreferenceReader) processXML( Preferences.TYPE, xml ); RaplaObject type = contentHandler.getChildType(); preferences.putEntryPrivate(configRole, type); } } } @Override public void deleteEntities( Iterable<Preferences> entities) throws SQLException { PreparedStatement stmt = null; boolean deleteNullUserPreference = false; try { stmt = con.prepareStatement(deleteSql); boolean empty = true; for ( Preferences preferences: entities) { User user = preferences.getOwner(); if ( user == null) { deleteNullUserPreference = true; } empty = false; setId( stmt,1, user); stmt.addBatch(); } if ( !empty) { stmt.executeBatch(); } } finally { if (stmt!=null) stmt.close(); } if ( deleteNullUserPreference ) { PreparedStatement deleteNullStmt = con.prepareStatement("DELETE FROM " + tableName + " WHERE USER_ID IS NULL OR USER_ID=0"); deleteNullStmt.execute(); } } } class UserStorage extends RaplaTypeStorage<User> { UserGroupStorage groupStorage; public UserStorage(RaplaContext context) throws RaplaException { super( context,User.TYPE, "RAPLA_USER", new String [] {"ID VARCHAR(255) NOT NULL PRIMARY KEY","USERNAME VARCHAR(255) NOT NULL","PASSWORD VARCHAR(255)","NAME VARCHAR(255) NOT NULL","EMAIL VARCHAR(255) NOT NULL","ISADMIN INTEGER NOT NULL", "CREATION_TIME TIMESTAMP", "LAST_CHANGED TIMESTAMP"}); groupStorage = new UserGroupStorage( context ); addSubStorage( groupStorage ); } @Override void insertAll() throws SQLException, RaplaException { insert( cache.getUsers()); } @Override protected int write(PreparedStatement stmt,User user) throws SQLException, RaplaException { setId(stmt, 1, user); setString(stmt,2,user.getUsername()); String password = cache.getPassword(user.getId()); setString(stmt,3,password); //setId(stmt,4,user.getPerson()); setString(stmt,4,user.getName()); setString(stmt,5,user.getEmail()); stmt.setInt(6,user.isAdmin()?1:0); setTimestamp(stmt, 7, user.getCreateTime() ); setTimestamp(stmt, 8, user.getLastChanged() ); stmt.addBatch(); return 1; } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { String userId = readId(rset,1, User.class ); String username = getString(rset,2, null); if ( username == null) { getLogger().warn("Username is null for " + userId + " Ignoring user."); } String password = getString(rset,3, null); //String personId = readId(rset,4, Allocatable.class, true); String name = getString(rset,4,""); String email = getString(rset,5,""); boolean isAdmin = rset.getInt(6) == 1; Date createDate = getTimestampOrNow( rset, 7); Date lastChanged = getTimestampOrNow( rset, 8); UserImpl user = new UserImpl(createDate, lastChanged); // if ( personId != null) // { // user.putId("person", personId); // } user.setId( userId ); user.setUsername( username ); user.setName( name ); user.setEmail( email ); user.setAdmin( isAdmin ); if ( password != null) { putPassword(userId,password); } put(user); } } class UserGroupStorage extends EntityStorage<User> { public UserGroupStorage(RaplaContext context) throws RaplaException { super(context,"RAPLA_USER_GROUP", new String [] {"USER_ID VARCHAR(255) NOT NULL KEY","CATEGORY_ID VARCHAR(255) NOT NULL"}); } @Override protected int write(PreparedStatement stmt, User entity) throws SQLException, RaplaException { setId( stmt,1, entity); int count = 0; for (Category category:entity.getGroups()) { setId(stmt, 2, category); stmt.addBatch(); count++; } return count; } @Override protected void load(ResultSet rset) throws SQLException, RaplaException { User user = resolveFromId(rset, 1,User.class); if ( user == null) { return; } Category category = resolveFromId(rset, 2, Category.class); if ( category == null) { return; } user.addGroup( category); } }
04900db4-rob
src/org/rapla/storage/dbsql/RaplaSQL.java
Java
gpl3
50,193
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbsql; import java.sql.Connection; import java.sql.SQLException; import java.util.Collection; import java.util.List; import java.util.Map; import org.rapla.entities.Entity; import org.rapla.framework.RaplaException; interface Storage<T extends Entity<T>> { void loadAll() throws SQLException,RaplaException; void deleteAll() throws SQLException; void setConnection(Connection con) throws SQLException; void save( Iterable<T> entities) throws SQLException,RaplaException ; void insert( Iterable<T> entities) throws SQLException,RaplaException ; // void update( Collection<Entity>> entities) throws SQLException,RaplaException ; void deleteIds(Collection<String> ids) throws SQLException,RaplaException ; public List<String> getCreateSQL(); void createOrUpdateIfNecessary( Map<String, TableDef> schema) throws SQLException, RaplaException; void dropTable() throws SQLException; }
04900db4-rob
src/org/rapla/storage/dbsql/Storage.java
Java
gpl3
1,884
<body> Serialization of the reservation-data in a SQL-DBMS. </body>
04900db4-rob
src/org/rapla/storage/dbsql/package.html
HTML
gpl3
69
package org.rapla.storage.dbsql; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; public class TableDef { public TableDef(String table) { this.tablename = table; } Map<String,ColumnDef> columns = new LinkedHashMap<String,ColumnDef>(); String tablename; public void addColumn(ColumnDef column) { columns.put( column.getName(), column); } public TableDef(String tablename, Collection<ColumnDef> columns) { this.tablename = tablename; for ( ColumnDef def: columns){ addColumn( def); } } public ColumnDef getColumn(String name) { ColumnDef columnDef = columns.get( name.toUpperCase(Locale.ENGLISH)); return columnDef; } public String toString() { return "TableDef [columns=" + columns + ", tablename=" + tablename + "]"; } public void removeColumn(String oldColumnName) { columns.remove( oldColumnName); } }
04900db4-rob
src/org/rapla/storage/dbsql/TableDef.java
Java
gpl3
916
<body> Serialization of the reservation-data in an XML file </body>
04900db4-rob
src/org/rapla/storage/dbfile/package.html
HTML
gpl3
70
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbfile; import java.io.IOException; import java.io.Reader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import org.rapla.components.util.xml.RaplaContentHandler; import org.rapla.components.util.xml.RaplaErrorHandler; import org.rapla.components.util.xml.RaplaSAXHandler; import org.rapla.components.util.xml.XMLReaderAdapter; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; import org.xml.sax.ContentHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** Reads the data in xml format from an InputSource into the LocalCache and converts it to a newer version if necessary. */ public final class RaplaInput { private Logger logger; private URL fileSource; private Reader reader; private boolean wasConverted; public RaplaInput(Logger logger) { this.logger = logger; } protected Logger getLogger() { return logger; } /** returns if the data was converted during read.*/ public boolean wasConverted() { return wasConverted; } public void read(URL file, RaplaSAXHandler handler, boolean validate) throws RaplaException,IOException { getLogger().debug("Parsing " + file.toString()); fileSource = file; reader = null; parseData( handler , validate); } private InputSource getNewSource() { if ( fileSource != null ) { return new InputSource( fileSource.toString() ); } else if ( reader != null ) { return new InputSource( reader ); } else { throw new IllegalStateException("fileSource or reader can't be null"); } } private void parseData( RaplaSAXHandler reader,boolean validate) throws RaplaException ,IOException { ContentHandler contentHandler = new RaplaContentHandler( reader); try { InputSource source = getNewSource(); if (validate) { validate( source, "org/rapla/storage/xml/rapla.rng"); } XMLReader parser = XMLReaderAdapter.createXMLReader(false); RaplaErrorHandler errorHandler = new RaplaErrorHandler(logger); parser.setContentHandler(contentHandler); parser.setErrorHandler(errorHandler); parser.parse(source); } catch (SAXException ex) { Throwable cause = ex.getCause(); while (cause != null && cause.getCause() != null) { cause = cause.getCause(); } if (ex instanceof SAXParseException) { throw new RaplaException("Line: " + ((SAXParseException)ex).getLineNumber() + " Column: "+ ((SAXParseException)ex).getColumnNumber() + " " + ((cause != null) ? cause.getMessage() : ex.getMessage()) ,(cause != null) ? cause : ex ); } if (cause == null) { throw new RaplaException( ex); } if (cause instanceof RaplaException) throw (RaplaException) cause; else throw new RaplaException( cause); } /* End of Exception Handling */ } /** uses the jing validator to validate a document against an relaxng schema. * This method uses reflection API, to avoid compile-time dependencies on * the jing.jar * @param in * @param schema * @throws RaplaException */ private void validate(InputSource in, String schema) throws RaplaException { try { ErrorHandler errorHandler = new RaplaErrorHandler(getLogger()); /* // short version * propMapBuilder = new com.thaiopensource.util.PropertyMapBuilder(); * propMapBuilder.put(com.thaiopensource.validate.ValidateProperty.ERROR_HANDLER, errorHandler); * Object propMap = propMapBuilder.toPropertyMap(); * Object o =new com.thaiopensource.validate.ValidationDriver(propMap); * o.loadSchema(schema); * o.validate(in); */ // full reflection syntax Class<?> validatorC = Class.forName("com.thaiopensource.validate.ValidationDriver"); Class<?> propIdC = Class.forName("com.thaiopensource.util.PropertyId"); Class<?> validatepropC = Class.forName("com.thaiopensource.validate.ValidateProperty"); Object errorHandlerId = validatepropC.getDeclaredField("ERROR_HANDLER").get( null ); Class<?> propMapC = Class.forName("com.thaiopensource.util.PropertyMap"); Class<?> propMapBuilderC = Class.forName("com.thaiopensource.util.PropertyMapBuilder"); Object propMapBuilder = propMapBuilderC.newInstance(); Method put = propMapBuilderC.getMethod("put", new Class[] {propIdC, Object.class} ); put.invoke( propMapBuilder, new Object[] {errorHandlerId, errorHandler}); Method topropMap = propMapBuilderC.getMethod("toPropertyMap", new Class[] {} ); Object propMap = topropMap.invoke( propMapBuilder, new Object[] {}); Constructor<?> validatorConst = validatorC.getConstructor( new Class[] { propMapC }); Object validator = validatorConst.newInstance( new Object[] {propMap}); Method loadSchema = validatorC.getMethod( "loadSchema", new Class[] {InputSource.class}); Method validate = validatorC.getMethod("validate", new Class[] {InputSource.class}); InputSource schemaSource = new InputSource( getResource( schema ).toString() ); loadSchema.invoke( validator, new Object[] {schemaSource} ); validate.invoke( validator, new Object[] {in}); } catch (ClassNotFoundException ex) { throw new RaplaException( ex.getMessage() + ". Latest jing.jar is missing on the classpath. Please download from http://www.thaiopensource.com/relaxng/jing.html"); } catch (InvocationTargetException e) { throw new RaplaException("Can't validate data due to the following error: " + e.getTargetException().getMessage(), e.getTargetException()); } catch (Exception ex) { throw new RaplaException("Error invoking JING", ex); } } private URL getResource(String name) throws RaplaException { URL url = getClass().getClassLoader().getResource( name ); if ( url == null ) throw new RaplaException("Resource " + name + " not found"); return url; } }
04900db4-rob
src/org/rapla/storage/dbfile/RaplaInput.java
Java
gpl3
7,784
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbfile; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.concurrent.locks.Lock; import org.rapla.ConnectInfo; import org.rapla.components.util.IOUtil; import org.rapla.components.util.xml.RaplaContentHandler; import org.rapla.components.util.xml.RaplaErrorHandler; import org.rapla.components.util.xml.RaplaSAXHandler; import org.rapla.components.util.xml.XMLReaderAdapter; 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.facade.RaplaComponent; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaException; import org.rapla.framework.StartupEnvironment; import org.rapla.framework.TypedComponentRole; import org.rapla.framework.internal.ContextTools; import org.rapla.framework.logger.Logger; import org.rapla.storage.LocalCache; import org.rapla.storage.UpdateEvent; import org.rapla.storage.UpdateResult; import org.rapla.storage.impl.AbstractCachableOperator; import org.rapla.storage.impl.EntityStore; import org.rapla.storage.impl.server.LocalAbstractCachableOperator; import org.rapla.storage.xml.IOContext; import org.rapla.storage.xml.RaplaMainReader; import org.rapla.storage.xml.RaplaMainWriter; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** Use this Operator to keep the data stored in an XML-File. * <p>Sample configuration: <pre> &lt;file-storage id="file"> &lt;file>data.xml&lt;/file> &lt;encoding>utf-8&lt;/encoding> &lt;validate>no&lt;/validate> &lt;/facade> </pre> * <ul> * <li>The file entry contains the path of the data file. * If the path is not an absolute path it will be resolved * relative to the location of the configuration file * </li> * <li>The encoding entry specifies the encoding of the xml-file. * Currently only UTF-8 is tested. * </li> * <li>The validate entry specifies if the xml-file should be checked * against a schema-file that is located under org/rapla/storage/xml/rapla.rng * (Default is no) * </li> * </ul> * </p> * <p>Note: The xmloperator doesn't check passwords.</p> @see AbstractCachableOperator @see org.rapla.storage.StorageOperator */ final public class FileOperator extends LocalAbstractCachableOperator { private File storageFile; private URL loadingURL; private final String encoding; protected boolean isConnected = false; final boolean includeIds ; public FileOperator( RaplaContext context,Logger logger, Configuration config ) throws RaplaException { super( context, logger ); StartupEnvironment env = context.lookup( StartupEnvironment.class ); URL contextRootURL = env.getContextRootURL(); String datasourceName = config.getChild("datasource").getValue(null); if ( datasourceName != null) { String filePath; try { filePath = ContextTools.resolveContext(datasourceName, context ); } catch (RaplaContextException ex) { filePath = "${context-root}/data.xml"; String message = "JNDI config raplafile is not found using '" + filePath + "' :"+ ex.getMessage() ; getLogger().warn(message); } String resolvedPath = ContextTools.resolveContext(filePath, context); try { storageFile = new File( resolvedPath); loadingURL = storageFile.getCanonicalFile().toURI().toURL(); } catch (Exception e) { throw new RaplaException("Error parsing file '" + resolvedPath + "' " + e.getMessage()); } } else { String fileName = config.getChild( "file" ).getValue( "data.xml" ); try { File file = new File( fileName ); if ( file.isAbsolute() ) { storageFile = file; loadingURL = storageFile.getCanonicalFile().toURI().toURL(); } else { int startupEnv = env.getStartupMode(); if ( startupEnv == StartupEnvironment.WEBSTART || startupEnv == StartupEnvironment.APPLET ) { loadingURL = new URL( contextRootURL, fileName ); } else { File contextRootFile = IOUtil.getFileFrom( contextRootURL ); storageFile = new File( contextRootFile, fileName ); loadingURL = storageFile.getCanonicalFile().toURI().toURL(); } } getLogger().info("Data:" + loadingURL); } catch ( MalformedURLException ex ) { throw new RaplaException( fileName + " is not an valid path " ); } catch ( IOException ex ) { throw new RaplaException( "Can't read " + storageFile + " " + ex.getMessage() ); } } encoding = config.getChild( "encoding" ).getValue( "utf-8" ); boolean validate = config.getChild( "validate" ).getValueAsBoolean( false ); if ( validate ) { getLogger().error("Validation currently not supported"); } includeIds = config.getChild( "includeIds" ).getValueAsBoolean( false ); } public String getURL() { return loadingURL.toExternalForm(); } public boolean supportsActiveMonitoring() { return false; } /** Sets the isConnected-flag and calls loadData.*/ final public User connect(ConnectInfo connectInfo) throws RaplaException { if ( isConnected ) return null; getLogger().info("Connecting: " + getURL()); loadData(); initIndizes(); isConnected = true; getLogger().debug("Connected"); return null; } final public boolean isConnected() { return isConnected; } final public void disconnect() throws RaplaException { boolean wasConnected = isConnected(); if ( wasConnected) { getLogger().info("Disconnecting: " + getURL()); cache.clearAll(); isConnected = false; fireStorageDisconnected(""); getLogger().debug("Disconnected"); } } final public void refresh() throws RaplaException { getLogger().warn( "Incremental refreshs are not supported" ); } final protected void loadData() throws RaplaException { try { cache.clearAll(); addInternalTypes(cache); if ( getLogger().isDebugEnabled() ) getLogger().debug( "Reading data from file:" + loadingURL ); EntityStore entityStore = new EntityStore( cache, cache.getSuperCategory() ); RaplaContext inputContext = new IOContext().createInputContext( context, entityStore, this ); RaplaMainReader contentHandler = new RaplaMainReader( inputContext ); parseData( contentHandler ); Collection<Entity> list = entityStore.getList(); cache.putAll( list ); Preferences preferences = cache.getPreferencesForUserId( null); if ( preferences != null) { TypedComponentRole<RaplaConfiguration> oldEntry = new TypedComponentRole<RaplaConfiguration>("org.rapla.plugin.export2ical"); if (preferences.getEntry(oldEntry, null) != null) { preferences.putEntry( oldEntry, null); } RaplaConfiguration entry = preferences.getEntry(RaplaComponent.PLUGIN_CONFIG, null); if ( entry != null) { DefaultConfiguration pluginConfig = (DefaultConfiguration)entry.find("class", "org.rapla.export2ical.Export2iCalPlugin"); entry.removeChild( pluginConfig); } } resolveInitial( list, this); cache.getSuperCategory().setReadOnly(); for (User user:cache.getUsers()) { String id = user.getId(); String password = entityStore.getPassword( id ); //System.out.println("Storing password in cache" + password); cache.putPassword( id, password ); } // contextualize all Entities if ( getLogger().isDebugEnabled() ) getLogger().debug( "Entities contextualized" ); } catch ( FileNotFoundException ex ) { createDefaultSystem(cache); } catch ( IOException ex ) { getLogger().warn( "Loading error: " + loadingURL); throw new RaplaException( "Can't load file at " + loadingURL + ": " + ex.getMessage() ); } catch ( RaplaException ex ) { throw ex; } catch ( Exception ex ) { throw new RaplaException( ex ); } } private void parseData( RaplaSAXHandler reader) throws RaplaException,IOException { ContentHandler contentHandler = new RaplaContentHandler( reader); try { InputSource source = new InputSource( loadingURL.toString() ); XMLReader parser = XMLReaderAdapter.createXMLReader(false); RaplaErrorHandler errorHandler = new RaplaErrorHandler(getLogger().getChildLogger( "reading" )); parser.setContentHandler(contentHandler); parser.setErrorHandler(errorHandler); parser.parse(source); } catch (SAXException ex) { Throwable cause = ex.getCause(); while (cause != null && cause.getCause() != null) { cause = cause.getCause(); } if (ex instanceof SAXParseException) { throw new RaplaException("Line: " + ((SAXParseException)ex).getLineNumber() + " Column: "+ ((SAXParseException)ex).getColumnNumber() + " " + ((cause != null) ? cause.getMessage() : ex.getMessage()) ,(cause != null) ? cause : ex ); } if (cause == null) { throw new RaplaException( ex); } if (cause instanceof RaplaException) throw (RaplaException) cause; else throw new RaplaException( cause); } /* End of Exception Handling */ } public void dispatch( final UpdateEvent evt ) throws RaplaException { final UpdateResult result; final Lock writeLock = writeLock(); try { preprocessEventStorage(evt); // call of update must be first to update the cache. // then saveData() saves all the data in the cache result = update( evt); saveData(cache, includeIds); } finally { unlock( writeLock ); } fireStorageUpdated( result ); } synchronized final public void saveData(LocalCache cache) throws RaplaException { saveData( cache, true); } synchronized final private void saveData(LocalCache cache, boolean includeIds) throws RaplaException { try { if ( storageFile == null ) { return; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); writeData( buffer,cache, includeIds ); byte[] data = buffer.toByteArray(); buffer.close(); File parentFile = storageFile.getParentFile(); if (!parentFile.exists()) { getLogger().info("Creating directory " + parentFile.toString()); parentFile.mkdirs(); } //String test = new String( data); moveFile( storageFile, storageFile.getPath() + ".bak" ); OutputStream out = new FileOutputStream( storageFile ); out.write( data ); out.close(); } catch ( IOException e ) { throw new RaplaException( e.getMessage() ); } } private void writeData( OutputStream out, LocalCache cache, boolean includeIds ) throws IOException, RaplaException { RaplaContext outputContext = new IOContext().createOutputContext( context, cache.getSuperCategoryProvider(), includeIds ); RaplaMainWriter writer = new RaplaMainWriter( outputContext, cache ); writer.setEncoding( encoding ); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out,encoding)); writer.setWriter(w); writer.printContent(); w.flush(); } private void moveFile( File file, String newPath ) { File backupFile = new File( newPath ); backupFile.delete(); file.renameTo( backupFile ); } public String toString() { return "FileOpertator for " + getURL(); } }
04900db4-rob
src/org/rapla/storage/dbfile/FileOperator.java
Java
gpl3
14,599
/* Javadoc style sheet */ /* Overall document style */ body { background-color:#ffffff; color:#353833; font-family:Arial, Helvetica, sans-serif; font-size:76%; margin:0; } a:link, a:visited { text-decoration:none; color:#4c6b87; } a:hover, a:focus { text-decoration:none; color:#bb7a2a; } a:active { text-decoration:none; color:#4c6b87; } a[name] { color:#353833; } a[name]:hover { text-decoration:none; color:#353833; } pre { font-size:1.3em; } h1 { font-size:1.8em; } h2 { font-size:1.5em; } h3 { font-size:1.4em; } h4 { font-size:1.3em; } h5 { font-size:1.2em; } h6 { font-size:1.1em; } ul { list-style-type:disc; } code, tt { font-size:1.2em; } dt code { font-size:1.2em; } table tr td dt code { font-size:1.2em; vertical-align:top; } sup { font-size:.6em; } /* Document title and Copyright styles */ .clear { clear:both; height:0px; overflow:hidden; } .aboutLanguage { float:right; padding:0px 21px; font-size:.8em; z-index:200; margin-top:-7px; } .legalCopy { margin-left:.5em; } .bar a, .bar a:link, .bar a:visited, .bar a:active { color:#FFFFFF; text-decoration:none; } .bar a:hover, .bar a:focus { color:#bb7a2a; } .tab { background-color:#0066FF; background-image:url(resources/titlebar.gif); background-position:left top; background-repeat:no-repeat; color:#ffffff; padding:8px; width:5em; font-weight:bold; } /* Navigation bar styles */ .bar { background-image:url(resources/background.gif); background-repeat:repeat-x; color:#FFFFFF; padding:.8em .5em .4em .8em; height:auto;/*height:1.8em;*/ font-size:1em; margin:0; } .topNav { background-image:url(resources/background.gif); background-repeat:repeat-x; color:#FFFFFF; float:left; padding:0; width:100%; clear:right; height:2.8em; padding-top:10px; overflow:hidden; } .bottomNav { margin-top:10px; background-image:url(resources/background.gif); background-repeat:repeat-x; color:#FFFFFF; float:left; padding:0; width:100%; clear:right; height:2.8em; padding-top:10px; overflow:hidden; } .subNav { background-color:#dee3e9; border-bottom:1px solid #9eadc0; float:left; width:100%; overflow:hidden; } .subNav div { clear:left; float:left; padding:0 0 5px 6px; } ul.navList, ul.subNavList { float:left; margin:0 25px 0 0; padding:0; } ul.navList li{ list-style:none; float:left; padding:3px 6px; } ul.subNavList li{ list-style:none; float:left; font-size:90%; } .topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited { color:#FFFFFF; text-decoration:none; } .topNav a:hover, .bottomNav a:hover { text-decoration:none; color:#bb7a2a; } .navBarCell1Rev { background-image:url(resources/tab.gif); background-color:#a88834; color:#FFFFFF; margin: auto 5px; border:1px solid #c9aa44; } /* Page header and footer styles */ .header, .footer { clear:both; margin:0 20px; padding:5px 0 0 0; } .indexHeader { margin:10px; position:relative; } .indexHeader h1 { font-size:1.3em; } .title { color:#2c4557; margin:10px 0; } .subTitle { margin:5px 0 0 0; } .header ul { margin:0 0 25px 0; padding:0; } .footer ul { margin:20px 0 5px 0; } .header ul li, .footer ul li { list-style:none; font-size:1.2em; } /* Heading styles */ div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4 { background-color:#dee3e9; border-top:1px solid #9eadc0; border-bottom:1px solid #9eadc0; margin:0 0 6px -8px; padding:2px 5px; } ul.blockList ul.blockList ul.blockList li.blockList h3 { background-color:#dee3e9; border-top:1px solid #9eadc0; border-bottom:1px solid #9eadc0; margin:0 0 6px -8px; padding:2px 5px; } ul.blockList ul.blockList li.blockList h3 { padding:0; margin:15px 0; } ul.blockList li.blockList h2 { padding:0px 0 20px 0; } /* Page layout container styles */ .contentContainer, .sourceContainer, .classUseContainer, .serializedFormContainer, .constantValuesContainer { clear:both; padding:10px 20px; position:relative; } .indexContainer { margin:10px; position:relative; font-size:1.0em; } .indexContainer h2 { font-size:1.1em; padding:0 0 3px 0; } .indexContainer ul { margin:0; padding:0; } .indexContainer ul li { list-style:none; } .contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt { font-size:1.1em; font-weight:bold; margin:10px 0 0 0; color:#4E4E4E; } .contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd { margin:10px 0 10px 20px; } .serializedFormContainer dl.nameValue dt { margin-left:1px; font-size:1.1em; display:inline; font-weight:bold; } .serializedFormContainer dl.nameValue dd { margin:0 0 0 1px; font-size:1.1em; display:inline; } /* List styles */ ul.horizontal li { display:inline; font-size:0.9em; } ul.inheritance { margin:0; padding:0; } ul.inheritance li { display:inline; list-style:none; } ul.inheritance li ul.inheritance { margin-left:15px; padding-left:15px; padding-top:1px; } ul.blockList, ul.blockListLast { margin:10px 0 10px 0; padding:0; } ul.blockList li.blockList, ul.blockListLast li.blockList { list-style:none; margin-bottom:25px; } ul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList { padding:0px 20px 5px 10px; border:1px solid #9eadc0; background-color:#f9f9f9; } ul.blockList ul.blockList ul.blockList li.blockList, ul.blockList ul.blockList ul.blockListLast li.blockList { padding:0 0 5px 8px; background-color:#ffffff; border:1px solid #9eadc0; border-top:none; } ul.blockList ul.blockList ul.blockList ul.blockList li.blockList { margin-left:0; padding-left:0; padding-bottom:15px; border:none; border-bottom:1px solid #9eadc0; } ul.blockList ul.blockList ul.blockList ul.blockList li.blockListLast { list-style:none; border-bottom:none; padding-bottom:0; } table tr td dl, table tr td dl dt, table tr td dl dd { margin-top:0; margin-bottom:1px; } /* Table styles */ .contentContainer table, .classUseContainer table, .constantValuesContainer table { border-bottom:1px solid #9eadc0; width:100%; } .contentContainer ul li table, .classUseContainer ul li table, .constantValuesContainer ul li table { width:100%; } .contentContainer .description table, .contentContainer .details table { border-bottom:none; } .contentContainer ul li table th.colOne, .contentContainer ul li table th.colFirst, .contentContainer ul li table th.colLast, .classUseContainer ul li table th, .constantValuesContainer ul li table th, .contentContainer ul li table td.colOne, .contentContainer ul li table td.colFirst, .contentContainer ul li table td.colLast, .classUseContainer ul li table td, .constantValuesContainer ul li table td{ vertical-align:top; padding-right:20px; } .contentContainer ul li table th.colLast, .classUseContainer ul li table th.colLast,.constantValuesContainer ul li table th.colLast, .contentContainer ul li table td.colLast, .classUseContainer ul li table td.colLast,.constantValuesContainer ul li table td.colLast, .contentContainer ul li table th.colOne, .classUseContainer ul li table th.colOne, .contentContainer ul li table td.colOne, .classUseContainer ul li table td.colOne { padding-right:3px; } .overviewSummary caption, .packageSummary caption, .contentContainer ul.blockList li.blockList caption, .summary caption, .classUseContainer caption, .constantValuesContainer caption { position:relative; text-align:left; background-repeat:no-repeat; color:#FFFFFF; font-weight:bold; clear:none; overflow:hidden; padding:0px; margin:0px; } caption a:link, caption a:hover, caption a:active, caption a:visited { color:#FFFFFF; } .overviewSummary caption span, .packageSummary caption span, .contentContainer ul.blockList li.blockList caption span, .summary caption span, .classUseContainer caption span, .constantValuesContainer caption span { white-space:nowrap; padding-top:8px; padding-left:8px; display:block; float:left; background-image:url(resources/titlebar.gif); height:18px; } .overviewSummary .tabEnd, .packageSummary .tabEnd, .contentContainer ul.blockList li.blockList .tabEnd, .summary .tabEnd, .classUseContainer .tabEnd, .constantValuesContainer .tabEnd { width:10px; background-image:url(resources/titlebar_end.gif); background-repeat:no-repeat; background-position:top right; position:relative; float:left; } ul.blockList ul.blockList li.blockList table { margin:0 0 12px 0px; width:100%; } .tableSubHeadingColor { background-color: #EEEEFF; } .altColor { background-color:#eeeeef; } .rowColor { background-color:#ffffff; } .overviewSummary td, .packageSummary td, .contentContainer ul.blockList li.blockList td, .summary td, .classUseContainer td, .constantValuesContainer td { text-align:left; padding:3px 3px 3px 7px; } th.colFirst, th.colLast, th.colOne, .constantValuesContainer th { background:#dee3e9; border-top:1px solid #9eadc0; border-bottom:1px solid #9eadc0; text-align:left; padding:3px 3px 3px 7px; } td.colOne a:link, td.colOne a:active, td.colOne a:visited, td.colOne a:hover, td.colFirst a:link, td.colFirst a:active, td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link, td.colLast a:active, td.colLast a:visited, td.colLast a:hover, .constantValuesContainer td a:link, .constantValuesContainer td a:active, .constantValuesContainer td a:visited, .constantValuesContainer td a:hover { font-weight:bold; } td.colFirst, th.colFirst { border-left:1px solid #9eadc0; white-space:nowrap; } td.colLast, th.colLast { border-right:1px solid #9eadc0; } td.colOne, th.colOne { border-right:1px solid #9eadc0; border-left:1px solid #9eadc0; } table.overviewSummary { padding:0px; margin-left:0px; } table.overviewSummary td.colFirst, table.overviewSummary th.colFirst, table.overviewSummary td.colOne, table.overviewSummary th.colOne { width:25%; vertical-align:middle; } table.packageSummary td.colFirst, table.overviewSummary th.colFirst { width:25%; vertical-align:middle; } /* Content styles */ .description pre { margin-top:0; } .deprecatedContent { margin:0; padding:10px 0; } .docSummary { padding:0; } /* Formatting effect styles */ .sourceLineNo { color:green; padding:0 30px 0 0; } h1.hidden { visibility:hidden; overflow:hidden; font-size:.9em; } .block { display:block; margin:3px 0 0 0; } .strong { font-weight:bold; }
04900db4-rob
javadoc/stylesheet.css
CSS
gpl3
11,613
/* Use this file to customize the Rapla HTML Pages to your style */ body { font:12px/18px "Lucida Grande","Lucida Sans Unicode",Arial,Verdana,sans-serif; color: #333333; } /* Button Appearance */ .button { border:none; cursor:pointer; display:inline-block; overflow:visible; padding:0; margin:0; height:29px; background:url("images/button.gif") right top; } .button a, .button input { font-size: 13px; font-weight: bold; font-family: Arial,Helvetica,Helvetica Neue,Verdana,sans-serif; text-decoration:none; color: #FFFFFF !important; cursor:pointer; outline:none; overflow:visible; white-space:nowrap; border:none; display:inline-block; padding: 0 18px; margin:0 !important; line-height:29px; height:29px; width:auto; background:url("images/button.gif") no-repeat left top; } /* Browser fixes */ .button input::-moz-focus-inner { padding: 0; border: none; } .menuEntry { padding-top:5px; padding-bottom:5px; } /* You can also customize the calendar .month_table { background-color: #FFFFAA; } */
04900db4-rob
war/default.css
CSS
gpl3
1,048
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> <meta http-equiv="refresh" content="0;URL=rapla"> </head> <body> </body> </html>
04900db4-rob
war/redirect.html
HTML
gpl3
191
#calendar * { font-family: Helvetica,Arial,Verdana,sans-serif; } a, a:visited{ color: black; text-decoration: none; } a:hover{ color: black; background-color: #FFFF88; } #calendar a span.tooltip { display: none; } #calendar a span td { padding: 0px; font-size: small; color: black; } #calendar a td { padding: 0px; font-size: small; color: black; } #legend { align: center; border-width: 0px; } #legend a span { display: none; } #legend a span td { padding: 0px; font-size: small; color: black; } #calendar { width: 100%; } /** calendar tooltip */ #calendar a:hover span.tooltip { display: block; bottom: 0.5em; right: 0.5em; padding: .5em; z-index: 1; font-size: small; color: black; background-color: #FFFF88; /* Doesn't work in IE */ position: fixed; width: 500px; border: 2px solid #000000; } /* woraround for IE */ #calendar a:hover span.tooltip { // position: absolute; } /** legend tooltip */ #legend a:hover span { display: block; bottom: 0.5em; right: 0.5em; padding: .5em; z-index: 1; font-size: small; color: black; background-color: #FFFF88; /* Doesn't work in IE position: fixed; width: auto; */ position: absolute; width: 500px; border: 2px solid #000000; } .title { text-align:center; } .datechooser { text-align:center; } .week_table { width: 100%; empty-cells: show; border-spacing:0px; border-bottom-width:3px; border-bottom-style:solid; border-right-width:1px; border-right-style:solid; padding:0px; border-color:black; /* workaround for IE */ // border-collapse:collapse; background-color: #FFFFFF; } .week_emptycell_black { font-size:9px; margin: 0px; border-top-style:solid; border-top-width:1px; border-left-width:0px; border-right-width:0px; padding-left: 0px; padding-right: 0px; } .week_separatorcell_black { font-size:9px; border-top-width:1px; border-top-style:solid; border-left-width:0px; border-right-width:1px; border-right-style:solid; padding-left: 1px; border-right-color: #CCCCCC; } .week_smallseparatorcell_black { font-size:9px; border-left-width:0px; border-right-width:0px; border-top-width:1px; border-top-style:solid; padding-left: 1px; padding-right: 1px; margin-left: 0px; margin-right: 0px; } .week_emptycell { font-size:9px; margin: 0px; border-color:#CCCCCC; border-top-style:solid; border-top-width:1px; border-left-width:0px; border-right-width:0px; padding-left: 0px; padding-right: 0px; } .week_emptynolinecell { margin: 0px; border-width:0px; } .week_separatorcell { font-size:9px; border-top-width:1px; border-color:#CCCCCC; border-top-style:solid; border-left-width:0px; border-right-width:1px; border-right-style:solid; padding-left: 1px; } .week_separatornolinecell { margin: 0px; border-width:0px; border-color:#CCCCCC; border-right-width:1px; border-right-style:solid; padding-left: 1px; } .week_smallseparatorcell { font-size:9px; border-color:#CCCCCC; border-left-width:0px; border-right-width:0px; border-top-width:1px; border-top-style:solid; padding-left: 1px; padding-right: 1px; margin-left: 0px; margin-right: 0px; } .week_smallseparatornolinecell { margin: 0px; border-width:0px; } .week_header { background-color: #DDDDDD; text-align: left; padding-left: 5px; padding-right: 5px; border-right-width:1px; border-right-style:solid; border-left-width:1px; border-left-style:solid; border-top-width:1px; border-top-style:solid; border-bottom-width:1px; border-bottom-style:solid; } .week_number { font-size: 0.9em; padding-left: 10px; padding-right: 10px; text-align: center; white-space: nowrap; border-left-width: 0px; border-top-width: 0px; border-right-width: 1px; border-bottom-width: 1px; border-style: solid; } .week_times { background-color: #DDDDDD; text-align:right; padding-right: 7px; vertical-align: top; border-left-width:1px; border-right-width:1px; border-top-width:1px; border-left-style:solid; border-right-style:solid; border-top-style:solid; width:10%; } .week_cell { margin: 0px; border-color:#CCCCCC; border-top-style:solid; border-top-width:1px; padding: 0px; padding-bottom: 1px; } .week_block { margin: 0px; padding-left: 2px; padding-right: 2px; padding-top: 0px; border-left-width:1px; border-right-width:1px; border-bottom-width:1px; border-top-width:1px; border-left-style:solid; border-right-style:solid; border-bottom-style:solid; border-top-style:solid; border-radius:5px; font-size: 9pt; min-height:100%; height:100%; cursor: pointer; -moz-box-shadow: 0px 1px 4px rgba(0,0,0,.3); -webkit-box-shadow: 0px 1px 4px rgba(0,0,0,.3); box-shadow: 0px 1px 4px rgba(0,0,0,.3); text-shadow: none; text-decoration: none; } .month_table { width: 100%; background-color: #FFFFFF; empty-cells: show; border-spacing:0px; /* workaround for IE */ // border-collapse:collapse; border: 1px; border-left: 1px solid; } .month_header { background-color: #DDDDDD; text-align: center; border-top-width:1px; border-left-width:0px; border-right-width:1px; border-bottom-width:1px; border-style:solid; } .month_cell { border-width:0px; border-left-width:0px; border-right-width:1px; border-bottom-width:1px; border-style:solid; padding:0px; } .month_block { font-size: 8pt; /* border:1px; */ border-bottom-color: black; border-bottom-style: solid; border-bottom-width: 1px; border-right-color: black; border-right-style: solid; border-right-width: 1px; line-height: 115%; border-radius:4px; } .person { font-family: Verdana; font-weight: bold; } .resource { font-size: 10pt; } .link { text-decoration: underline; } .eventtable { width:100%; } @page { size: auto; } @media print { .datechooser { display: none; } }
04900db4-rob
war/calendar.css
CSS
gpl3
6,232
package org.rapla; import org.rapla.plugin.mail.server.MailInterface; public class MockMailer implements MailInterface { String senderMail; String recipient; String subject; String mailBody; int callCount = 0; public MockMailer() { // Test for breakpoint mailBody = null; } public void sendMail( String senderMail, String recipient, String subject, String mailBody ) { this.senderMail = senderMail; this.recipient = recipient; this.subject = subject; this.mailBody = mailBody; callCount ++; } public int getCallCount() { return callCount; } public String getSenderMail() { return senderMail; } public String getSubject() { return subject; } public String getRecipient() { return recipient; } public String getMailBody() { return mailBody; } }
04900db4-rob
test-src/org/rapla/MockMailer.java
Java
gpl3
933
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.entities.domain.Allocatable; public class RaplaDemoTest extends RaplaTestCase { public RaplaDemoTest(String name) { super(name); } public static Test suite() { return new TestSuite(RaplaDemoTest.class); } public void testAccess() throws Exception { Allocatable[] resources = getFacade().getAllocatables(); assertTrue(resources.length > 0); } }
04900db4-rob
test-src/org/rapla/RaplaDemoTest.java
Java
gpl3
1,447
/*--------------------------------------------------------------------------* | 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.gui.internal.edit.reservation; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.client.ClientService; import org.rapla.entities.domain.Reservation; import org.rapla.gui.ReservationController; import org.rapla.gui.ReservationEdit; import org.rapla.gui.tests.GUITestCase; public final class ReservationEditTest extends GUITestCase{ ClientService clientService; Reservation[] reservations; ReservationController c; ReservationEdit window; ReservationEditImpl internalWindow; public ReservationEditTest(String name) { super(name); } public static Test suite() { return new TestSuite(ReservationEditTest.class); } public void setUp() throws Exception{ super.setUp(); clientService = getClientService(); reservations = clientService.getFacade().getReservationsForAllocatable(null,null,null,null); c = clientService.getContext().lookup(ReservationController.class); window = c.edit(reservations[0]); internalWindow = (ReservationEditImpl) window; } public void testAppointmentEdit() throws Exception { AppointmentListEdit appointmentEdit = internalWindow.appointmentEdit; // Deletes the second appointment int listSize = appointmentEdit.getListEdit().getList().getModel().getSize(); // Wait for the swing thread to paint otherwise we get a small paint exception in the console window due to concurrency issues int paintDelay = 10; Thread.sleep( paintDelay); appointmentEdit.getListEdit().select(1); Thread.sleep( paintDelay); appointmentEdit.getListEdit().removeButton.doClick(); Thread.sleep( paintDelay); // Check if its removed frmom the list int listSizeAfter = appointmentEdit.getListEdit().getList().getModel().getSize(); assertEquals( listSize-1, listSizeAfter); internalWindow.commandHistory.undo(); Thread.sleep( paintDelay); listSizeAfter = appointmentEdit.getListEdit().getList().getModel().getSize(); assertEquals(listSize, listSizeAfter); internalWindow.commandHistory.redo(); Thread.sleep( paintDelay); listSizeAfter = appointmentEdit.getListEdit().getList().getModel().getSize(); assertEquals(listSize-1, listSizeAfter); appointmentEdit.getListEdit().createNewButton.doClick(); Thread.sleep( paintDelay); appointmentEdit.getListEdit().createNewButton.doClick(); Thread.sleep( paintDelay); listSizeAfter = appointmentEdit.getListEdit().getList().getModel().getSize(); assertEquals(listSize+1, listSizeAfter); appointmentEdit.getListEdit().select(1); Thread.sleep( paintDelay); appointmentEdit.getListEdit().removeButton.doClick(); Thread.sleep( paintDelay); appointmentEdit.getListEdit().select(1); Thread.sleep( paintDelay); appointmentEdit.getListEdit().removeButton.doClick(); Thread.sleep( paintDelay); appointmentEdit.getListEdit().createNewButton.doClick(); Thread.sleep( paintDelay); listSizeAfter = appointmentEdit.getListEdit().getList().getModel().getSize(); assertEquals(listSize, listSizeAfter); internalWindow.commandHistory.undo(); Thread.sleep( paintDelay); internalWindow.commandHistory.undo(); Thread.sleep( paintDelay); listSizeAfter = appointmentEdit.getListEdit().getList().getModel().getSize(); assertEquals(listSize, listSizeAfter); } public void testAllocatable() throws Exception{ AllocatableSelection allocatableEdit = internalWindow.allocatableEdit; int firstState = getAllocatableSize(allocatableEdit); // deleting allocatables allocatableEdit.selectedTable.selectAll(); allocatableEdit.btnRemove.doClick(); int secondState = getAllocatableSize(allocatableEdit); assertFalse(firstState == secondState); internalWindow.commandHistory.undo(); int thirdState = getAllocatableSize(allocatableEdit); assertTrue(firstState == thirdState); //adding all allocatables allocatableEdit.completeTable.selectAll(); allocatableEdit.btnAdd.doClick(); int fourthState = getAllocatableSize(allocatableEdit); assertFalse (firstState == fourthState); internalWindow.commandHistory.undo(); int fifthState = getAllocatableSize(allocatableEdit); assertTrue (firstState == fifthState); internalWindow.commandHistory.redo(); int sixthState = getAllocatableSize(allocatableEdit); assertTrue (fourthState == sixthState); } public void testRepeatingEdit() throws Exception{ AppointmentListEdit appointmentEdit = internalWindow.appointmentEdit; //ReservationInfoEdit repeatingAndAttributeEdit = internalWindow.reservationInfo; appointmentEdit.getListEdit().select(0); String firstSelected = getSelectedRadioButton(appointmentEdit.getAppointmentController()); appointmentEdit.getAppointmentController().yearlyRepeating.doClick(); String secondSelected = getSelectedRadioButton(appointmentEdit.getAppointmentController()); assertFalse(firstSelected.equals(secondSelected)); internalWindow.commandHistory.undo(); assertEquals(firstSelected, getSelectedRadioButton(appointmentEdit.getAppointmentController())); internalWindow.commandHistory.redo(); assertEquals("yearly", getSelectedRadioButton(appointmentEdit.getAppointmentController())); appointmentEdit.getAppointmentController().noRepeating.doClick(); appointmentEdit.getAppointmentController().monthlyRepeating.doClick(); appointmentEdit.getAppointmentController().dailyRepeating.doClick(); internalWindow.commandHistory.undo(); assertEquals("monthly", getSelectedRadioButton(appointmentEdit.getAppointmentController())); appointmentEdit.getAppointmentController().yearlyRepeating.doClick(); appointmentEdit.getAppointmentController().weeklyRepeating.doClick(); appointmentEdit.getAppointmentController().noRepeating.doClick(); internalWindow.commandHistory.undo(); internalWindow.commandHistory.undo(); internalWindow.commandHistory.redo(); assertEquals("weekly", getSelectedRadioButton(appointmentEdit.getAppointmentController())); } private int getAllocatableSize(AllocatableSelection allocatableEdit) { return allocatableEdit.mutableReservation.getAllocatables().length; } public String getSelectedRadioButton(AppointmentController editor){ if(editor.dailyRepeating.isSelected()) return "daily"; if(editor.weeklyRepeating.isSelected()) return "weekly"; if(editor.monthlyRepeating.isSelected()) return "monthly"; if(editor.yearlyRepeating.isSelected()) return "yearly"; if(editor.noRepeating.isSelected()) return "single"; return "false"; } public static void main(String[] args) { new ReservationEditTest(ReservationEditTest.class.getName() ).interactiveTest("testMain"); } }
04900db4-rob
test-src/org/rapla/gui/internal/edit/reservation/ReservationEditTest.java
Java
gpl3
8,324
/*--------------------------------------------------------------------------* | 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.gui.toolkit.tests; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.gui.tests.GUITestCase; import org.rapla.gui.toolkit.ErrorDialog; public class ErrorDialogTest extends GUITestCase { public ErrorDialogTest(String name) { super(name); } public static Test suite() { return new TestSuite(ErrorDialogTest.class); } public void testError() throws Exception { ErrorDialog.THROW_ERROR_DIALOG_EXCEPTION = false; ErrorDialog dialog = new ErrorDialog(getContext()); dialog.show("This is a very long sample error-text for our error-message-displaying-test" + " it should be wrapped so that the whole text is diplayed."); } public static void main(String[] args) { new ErrorDialogTest("ErrorDialogTest").interactiveTest("testError"); } }
04900db4-rob
test-src/org/rapla/gui/toolkit/tests/ErrorDialogTest.java
Java
gpl3
1,837
/*--------------------------------------------------------------------------* | 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.gui.tests; import java.util.Date; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.facade.CalendarSelectionModel; import org.rapla.gui.internal.CalendarEditor; public final class CalendarEditorTest extends GUITestCase { public CalendarEditorTest(String name) { super(name); } public static Test suite() { return new TestSuite(CalendarEditorTest.class); } public void testShow() throws Exception { CalendarSelectionModel settings = getFacade().newCalendarModel(getFacade().getUser() ); settings.setSelectedDate(new Date()); CalendarEditor editor = new CalendarEditor(getClientService().getContext(),settings); testComponent(editor.getComponent(),1024,600); editor.start(); //editor.listUI.treeSelection.getTree().setSelectionRow(1); } /* #TODO uncomment me and make me test again * public void testCreateException() throws Exception { CalendarModel settings = new CalendarModelImpl( getClientService().getContext() ); settings.setSelectionType( Reservation.TYPE ); settings.setSelectedDate(new Date()); CalendarEditor editor = new CalendarEditor(getClientService().getContext(),settings); testComponent(editor.getComponent(),1024,600); editor.start(); editor.getComponent().revalidate(); editor.selection.treeSelection.getTree().setSelectionRow(1); Reservation r = (Reservation) editor.selection.treeSelection.getSelectedElement(); //editor.getComponent().revalidate(); //editor.calendarContainer.dateChooser.goNext(); Date date1 = editor.getCalendarView().getStartDate(); Reservation editableRes = (Reservation) getFacade().edit( r ); Appointment app1 = editableRes.getAppointments()[0]; Appointment app2= editableRes.getAppointments()[1]; app1.getRepeating().addException( DateTools.addDays( app1.getStart(), 7 )); editableRes.removeAppointment( app2 ); getFacade().store( editableRes); //We need to wait until the notifaction of the change Thread.sleep(500); assertEquals( date1, editor.getCalendarView().getStartDate()); getLogger().info("WeekViewEditor started"); } */ public static void main(String[] args) { new CalendarEditorTest(CalendarEditorTest.class.getName() ).interactiveTest("testShow"); } }
04900db4-rob
test-src/org/rapla/gui/tests/CalendarEditorTest.java
Java
gpl3
3,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.gui.tests; import java.util.ArrayList; import java.util.Date; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.RaplaTestCase; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.Reservation; import org.rapla.plugin.abstractcalendar.RaplaBuilder; public final class RapaBuilderTest extends RaplaTestCase { public RapaBuilderTest(String name) { super(name); } public static Test suite() { return new TestSuite(RapaBuilderTest.class); } public void testSplitAppointments() throws Exception { Date start = formater().parseDate("2004-01-01",false); Date end = formater().parseDate("2004-01-10",true); // test 2 Blocks List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>(); Reservation reservation = getFacade().newReservation(); Appointment appointment = getFacade().newAppointment( formater().parseDateTime("2004-01-01","18:30:00") ,formater().parseDateTime("2004-01-02","12:00:00") ); reservation.addAppointment( appointment ); appointment.createBlocks(start,end, blocks ); blocks = RaplaBuilder.splitBlocks( blocks ,start ,end ); assertEquals("Blocks are not split in two", 2, blocks.size()); assertEquals( formater().parseDateTime("2004-01-01","23:59:59").getTime()/1000, blocks.get(0).getEnd()/1000); assertEquals( formater().parseDateTime("2004-01-02","00:00:00").getTime(), blocks.get(1).getStart()); assertEquals( formater().parseDateTime("2004-01-02","12:00:00").getTime(), blocks.get(1).getEnd()); // test 3 Blocks blocks.clear(); reservation = getFacade().newReservation(); appointment = getFacade().newAppointment( formater().parseDateTime("2004-01-01","18:30:00") ,formater().parseDateTime("2004-01-04","00:00:00") ); reservation.addAppointment( appointment ); appointment.createBlocks(start,end, blocks ); blocks = RaplaBuilder.splitBlocks( blocks ,start ,end ); assertEquals("Blocks are not split in three", 3, blocks.size()); assertEquals(formater().parseDateTime("2004-01-03","23:59:59").getTime()/1000, blocks.get(2).getEnd()/1000); // test 3 Blocks, but only the first two should show blocks.clear(); reservation = getFacade().newReservation(); appointment = getFacade().newAppointment( formater().parseDateTime("2004-01-01","18:30:00") ,formater().parseDateTime("2004-01-04","00:00:00") ); reservation.addAppointment( appointment ); appointment.createBlocks(start,end, blocks ); blocks = RaplaBuilder.splitBlocks( blocks ,start ,formater().parseDateTime("2004-01-03","00:00:00") ); assertEquals("Blocks are not split in two", 2, blocks.size()); assertEquals(formater().parseDateTime("2004-01-02","23:59:59").getTime()/1000, blocks.get(1).getEnd()/1000); } }
04900db4-rob
test-src/org/rapla/gui/tests/RapaBuilderTest.java
Java
gpl3
4,382
/*--------------------------------------------------------------------------* | 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.gui.tests; import java.util.Collection; import java.util.Collections; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.RaplaTestCase; import org.rapla.client.ClientService; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.ClientFacade; public class DataUpdateTest extends RaplaTestCase { ClientFacade facade; ClientService clientService; Exception error; public DataUpdateTest(String name) { super(name); } public static Test suite() { return new TestSuite(DataUpdateTest.class); } protected void setUp() throws Exception { super.setUp(); clientService = getClientService(); facade = getContext().lookup(ClientFacade.class); } protected void tearDown() throws Exception { super.tearDown(); } public void testReload() throws Exception{ error = null; User user = facade.getUsers()[0]; refreshDelayed(); // So we have to wait for the listener-thread Thread.sleep(1500); if (error != null) throw error; assertTrue( "User-list varied during refresh! ", facade.getUsers()[0].equals(user) ); } boolean fail; public void testCalenderModel() throws Exception{ DynamicType dynamicType = facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE)[0]; { DynamicType mutableType = facade.edit(dynamicType); Attribute newAttribute = facade.newAttribute(AttributeType.STRING); newAttribute.setKey("newkey"); mutableType.addAttribute( newAttribute); facade.store( mutableType ); } Allocatable newResource = facade.newResource(); newResource.setClassification( dynamicType.newClassification()); newResource.getClassification().setValue("name", "testdelete"); newResource.getClassification().setValue("newkey", "filter"); facade.store( newResource ); final CalendarSelectionModel model = clientService.getContext().lookup( CalendarSelectionModel.class); ClassificationFilter filter = dynamicType.newClassificationFilter(); filter.addIsRule("newkey", "filter"); model.setAllocatableFilter( new ClassificationFilter[] {filter}); model.setSelectedObjects( Collections.singletonList( newResource)); assertFalse(model.isDefaultResourceTypes()); assertTrue(filter.matches(newResource.getClassification())); { ClassificationFilter[] allocatableFilter = model.getAllocatableFilter(); assertEquals(1, allocatableFilter.length); assertEquals(1,allocatableFilter[0].ruleSize()); } { DynamicType mutableType = facade.edit(dynamicType); mutableType.removeAttribute( mutableType.getAttribute( "newkey")); facade.storeAndRemove( new Entity[] {mutableType}, new Entity[]{ newResource}); } assertFalse(model.isDefaultResourceTypes()); Collection<RaplaObject> selectedObjects = model.getSelectedObjects( ); int size = selectedObjects.size(); assertEquals(0,size); ClassificationFilter[] allocatableFilter = model.getAllocatableFilter(); assertEquals(1,allocatableFilter.length); ClassificationFilter filter1 = allocatableFilter[0]; assertEquals(0,filter1.ruleSize()); } private void refreshDelayed() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { try { facade.refresh(); } catch (Exception ex) { error = ex; } } }); } }
04900db4-rob
test-src/org/rapla/gui/tests/DataUpdateTest.java
Java
gpl3
5,064
/*--------------------------------------------------------------------------* | 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.gui.tests; import java.awt.BorderLayout; import java.util.concurrent.Semaphore; import javax.swing.JComponent; import org.rapla.RaplaTestCase; import org.rapla.framework.RaplaException; import org.rapla.gui.toolkit.ErrorDialog; import org.rapla.gui.toolkit.FrameController; import org.rapla.gui.toolkit.FrameControllerList; import org.rapla.gui.toolkit.FrameControllerListener; import org.rapla.gui.toolkit.RaplaFrame; public abstract class GUITestCase extends RaplaTestCase { public GUITestCase(String name) { super(name); } protected <T> T getService(Class<T> role) throws RaplaException { return getClientService().getContext().lookup( role); } public void interactiveTest(String methodName) { try { setUp(); ErrorDialog.THROW_ERROR_DIALOG_EXCEPTION = false; try { this.getClass().getMethod(methodName, new Class[] {}).invoke(this,new Object[] {}); waitUntilLastFrameClosed( getClientService().getContext().lookup(FrameControllerList.class) ); System.exit(0); } catch (Exception ex) { getLogger().error(ex.getMessage(), ex); System.exit(1); } finally { tearDown(); } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } System.exit(0); } /** Waits until the last window is closed. Every window should register and unregister on the FrameControllerList. @see org.rapla.gui.toolkit.RaplaFrame */ public static void waitUntilLastFrameClosed(FrameControllerList list) throws InterruptedException { MyFrameControllerListener listener = new MyFrameControllerListener(); list.addFrameControllerListener(listener); listener.waitUntilClosed(); } static class MyFrameControllerListener implements FrameControllerListener { Semaphore mutex; MyFrameControllerListener() { mutex = new Semaphore(1); } public void waitUntilClosed() throws InterruptedException { mutex.acquire(); // we wait for the mutex to be released mutex.acquire(); mutex.release(); } public void frameClosed(FrameController frame) { } public void listEmpty() { mutex.release(); } } /** create a frame of size x,y and place the panel inside the Frame. Use this method for testing new GUI-Components. */ public void testComponent(JComponent component,int x,int y) throws Exception{ RaplaFrame frame = new RaplaFrame(getClientService().getContext()); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(component, BorderLayout.CENTER); frame.setSize(x,y); frame.setVisible(true); } }
04900db4-rob
test-src/org/rapla/gui/tests/GUITestCase.java
Java
gpl3
3,913
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; import java.util.Date; import org.rapla.components.util.DateTools; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.entities.dynamictype.internal.AttributeImpl; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.ClientFacade; import org.rapla.framework.RaplaContext; import org.rapla.gui.internal.edit.ClassifiableFilterEdit; public class DynamicTypeTest extends RaplaTestCase { public DynamicTypeTest(String name) { super(name); } public void testAttributeChangeSimple() throws Exception { ClientFacade facade = getFacade(); String key = "booleantest"; { DynamicType eventType = facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)[0]; DynamicType type = facade.edit( eventType ); Attribute att = facade.newAttribute(AttributeType.BOOLEAN); att.getName().setName("en", "test"); att.setKey(key); type.addAttribute( att); facade.store( type); { eventType = facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)[0]; AttributeImpl attributeImpl = (AttributeImpl) eventType.getAttribute(key); assertNotNull( attributeImpl); } } } public void testAttributeChange() throws Exception { ClientFacade facade = getFacade(); Reservation event = facade.newReservation(); event.getClassification().setValue("name", "test"); Appointment app = facade.newAppointment( new Date() , DateTools.addDay(new Date())); event.addAppointment( app ); DynamicType eventType = event.getClassification().getType(); facade.store( event); String key = "booleantest"; { DynamicType type = facade.edit( eventType ); Attribute att = facade.newAttribute(AttributeType.BOOLEAN); att.getName().setName("en", "test"); att.setKey(key); type.addAttribute( att); facade.store( type); } { Reservation modified = facade.edit( event ); modified.getClassification().setValue(key, Boolean.TRUE); facade.store( modified); } { CalendarSelectionModel model = getClientService().getContext().lookup(CalendarSelectionModel.class); ClassificationFilter firstFilter = eventType.newClassificationFilter(); assertNotNull( firstFilter); firstFilter.addRule(key, new Object[][] {{"=",Boolean.TRUE}}); model.setReservationFilter( new ClassificationFilter[] { firstFilter}); model.save("test"); Thread.sleep(100); } { DynamicType type = facade.edit( eventType ); Attribute att = type.getAttribute(key); att.setType(AttributeType.CATEGORY); facade.store( type); } { Thread.sleep(100); CalendarSelectionModel model = getClientService().getContext().lookup(CalendarSelectionModel.class); model.getReservations(); } // List<String> errorMessages = RaplaTestLogManager.getErrorMessages(); // assertTrue(errorMessages.toString(),errorMessages.size() == 0); } public void testAttributeRemove() throws Exception { ClientFacade facade = getFacade(); Allocatable alloc = facade.getAllocatables()[0]; DynamicType allocType = alloc.getClassification().getType(); String key = "stringtest"; { DynamicType type = facade.edit( allocType ); Attribute att = facade.newAttribute(AttributeType.STRING); att.getName().setName("en", "test"); att.setKey(key); type.addAttribute( att); facade.store( type); } { Allocatable modified = facade.edit( alloc ); modified.getClassification().setValue(key, "t"); facade.store( modified); } { CalendarSelectionModel model = getClientService().getContext().lookup(CalendarSelectionModel.class); ClassificationFilter firstFilter = allocType.newClassificationFilter(); assertNotNull( firstFilter); firstFilter.addRule(key, new Object[][] {{"=","t"}}); model.setReservationFilter( new ClassificationFilter[] { firstFilter}); model.save("test"); } { DynamicType type = facade.edit( allocType ); Attribute att = type.getAttribute(key); type.removeAttribute( att); facade.store( type); } { CalendarSelectionModel model = getClientService().getContext().lookup(CalendarSelectionModel.class); model.getReservations(); Thread.sleep(100); RaplaContext context = getClientService().getContext(); boolean isResourceOnly = true; ClassifiableFilterEdit ui = new ClassifiableFilterEdit( context, isResourceOnly); ui.setFilter( model); } // List<String> errorMessages = RaplaTestLogManager.getErrorMessages(); //assertTrue(errorMessages.toString(),errorMessages.size() == 0); } }
04900db4-rob
test-src/org/rapla/DynamicTypeTest.java
Java
gpl3
6,178
package org.rapla; import java.util.Date; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.facade.ClientFacade; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.RaplaContext; import org.rapla.framework.TypedComponentRole; import org.rapla.framework.logger.ConsoleLogger; import org.rapla.storage.dbrm.RemoteOperator; import org.rapla.storage.dbrm.RemoteServer; import org.rapla.storage.dbrm.RemoteStorage; public class CommunicatorTest extends ServletTestBase { public CommunicatorTest( String name ) { super( name ); } public void testLargeform() throws Exception { ClientFacade facade = getContainer().lookup(ClientFacade.class, "remote-facade"); facade.login("homer","duffs".toCharArray()); Allocatable alloc = facade.newResource(); StringBuffer buf = new StringBuffer(); int stringsize = 100000; for (int i=0;i< stringsize;i++) { buf.append( "xxxxxxxxxx"); } String verylongname = buf.toString(); alloc.getClassification().setValue("name", verylongname); facade.store( alloc); } public void testClient() throws Exception { ClientFacade facade = getContainer().lookup(ClientFacade.class, "remote-facade"); boolean success = facade.login("admin","test".toCharArray()); assertFalse( "Login should fail",success ); facade.login("homer","duffs".toCharArray()); try { Preferences preferences = facade.edit( facade.getSystemPreferences()); TypedComponentRole<String> TEST_ENTRY = new TypedComponentRole<String>("test-entry"); preferences.putEntry(TEST_ENTRY, "test-value"); facade.store( preferences); preferences = facade.edit( facade.getSystemPreferences()); preferences.putEntry(TEST_ENTRY, "test-value"); facade.store( preferences); Allocatable[] allocatables = facade.getAllocatables(); assertTrue( allocatables.length > 0); Reservation[] events = facade.getReservations( new Allocatable[] {allocatables[0]}, null,null); assertTrue( events.length > 0); Reservation r = events[0]; Reservation editable = facade.edit( r); facade.store( editable ); Reservation newEvent = facade.newReservation(); Appointment newApp = facade.newAppointment( new Date(), new Date()); newEvent.addAppointment( newApp ); newEvent.getClassification().setValue("name","Test Reservation"); newEvent.addAllocatable( allocatables[0]); facade.store( newEvent ); facade.remove( newEvent); } finally { facade.logout(); } } public void testUmlaute() throws Exception { ClientFacade facade = getContainer().lookup(ClientFacade.class , "remote-facade"); facade.login("homer","duffs".toCharArray()); Allocatable alloc = facade.newResource(); String typeName = alloc.getClassification().getType().getKey(); // AE = \u00C4 // OE = \u00D6 // UE = \u00DC // ae = \u00E4 // oe = \u00F6 // ue = \u00FC // ss = \u00DF String nameWithUmlaute = "\u00C4\u00D6\u00DC\u00E4\u00F6\u00FC\u00DF"; alloc.getClassification().setValue("name", nameWithUmlaute); int allocSizeBefore = facade.getAllocatables().length; facade.store( alloc); facade.logout(); facade.login("homer","duffs".toCharArray()); DynamicType type = facade.getDynamicType( typeName); ClassificationFilter filter = type.newClassificationFilter(); filter.addEqualsRule("name", nameWithUmlaute); Allocatable[] allAllocs = facade.getAllocatables(); assertEquals( allocSizeBefore + 1, allAllocs.length); Allocatable[] allocs = facade.getAllocatables( new ClassificationFilter[] {filter}); assertEquals( 1, allocs.length); } public void testManyClients() throws Exception { RaplaContext context = getContext(); int clientNum = 50; RemoteOperator [] opts = new RemoteOperator[ clientNum]; DefaultConfiguration remoteConfig = new DefaultConfiguration("element"); DefaultConfiguration serverParam = new DefaultConfiguration("server"); serverParam.setValue("http://localhost:8052/"); remoteConfig.addChild( serverParam ); for ( int i=0;i<clientNum;i++) { RaplaMainContainer container = (RaplaMainContainer) getContainer(); RemoteServer remoteServer = container.getRemoteMethod( context, RemoteServer.class); RemoteStorage remoteStorage = container.getRemoteMethod(context, RemoteStorage.class); RemoteOperator opt = new RemoteOperator(context,new ConsoleLogger(),remoteConfig, remoteServer, remoteStorage ); opt.connect(new ConnectInfo("homer","duffs".toCharArray())); opts[i] = opt; System.out.println("Client " + i + " successfully subscribed"); } testClient(); for ( int i=0;i<clientNum;i++) { RemoteOperator opt = opts[i]; opt.disconnect(); } } }
04900db4-rob
test-src/org/rapla/CommunicatorTest.java
Java
gpl3
5,628
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; import java.io.File; import java.io.IOException; import java.net.URL; import junit.framework.TestCase; import org.rapla.client.ClientService; import org.rapla.client.ClientServiceContainer; import org.rapla.components.util.IOUtil; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.facade.ClientFacade; import org.rapla.framework.Container; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.framework.logger.ConsoleLogger; import org.rapla.framework.logger.Logger; import org.rapla.gui.toolkit.ErrorDialog; public abstract class RaplaTestCase extends TestCase { protected Container raplaContainer; Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_WARN).getChildLogger("test"); public static String TEST_SRC_FOLDER_NAME="test-src"; public static String TEST_FOLDER_NAME="temp/test"; protected RaplaStartupEnvironment env = new RaplaStartupEnvironment(); public RaplaTestCase(String name) { super(name); try { new File("temp").mkdir(); File testFolder =new File(TEST_FOLDER_NAME); System.setProperty("jetty.home",testFolder.getPath()); testFolder.mkdir(); IOUtil.copy( TEST_SRC_FOLDER_NAME +"/test.xconf", TEST_FOLDER_NAME + "/test.xconf" ); //IOUtil.copy( "test-src/test.xlog", TEST_FOLDER_NAME + "/test.xlog" ); } catch (IOException ex) { throw new RuntimeException("Can't initialize config-files: " + ex.getMessage()); } try { Class<?> forName = RaplaTestCase.class.getClassLoader().loadClass("org.slf4j.bridge.SLF4JBridgeHandler"); forName.getMethod("removeHandlersForRootLogger", new Class[] {}).invoke(null, new Object[] {}); forName.getMethod("install", new Class[] {}).invoke(null, new Object[] {}); } catch (Exception ex) { getLogger().warn("Can't install logging bridge " + ex.getMessage()); // Todo bootstrap log } } public void copyDataFile(String testFile) throws IOException { try { IOUtil.copy( testFile, TEST_FOLDER_NAME + "/test.xml" ); } catch (IOException ex) { throw new IOException("Failed to copy TestFile '" + testFile + "': " + ex.getMessage()); } } protected <T> T getService(Class<T> role) throws RaplaException { return getContext().lookup( role); } protected RaplaContext getContext() { return raplaContainer.getContext(); } protected SerializableDateTimeFormat formater() { return new SerializableDateTimeFormat(); } protected Logger getLogger() { return logger; } protected void setUp(String testFile) throws Exception { ErrorDialog.THROW_ERROR_DIALOG_EXCEPTION = true; URL configURL = new URL("file:./" + TEST_FOLDER_NAME + "/test.xconf"); env.setConfigURL( configURL); copyDataFile("test-src/" + testFile); raplaContainer = new RaplaMainContainer( env ); assertNotNull("Container not initialized.",raplaContainer); ClientFacade facade = getFacade(); facade.login("homer", "duffs".toCharArray()); } protected void setUp() throws Exception { setUp("testdefault.xml"); } protected ClientService getClientService() throws RaplaException { ClientServiceContainer clientContainer = getContext().lookup(ClientServiceContainer.class); if ( ! clientContainer.isRunning()) { try { clientContainer.start( new ConnectInfo("homer", "duffs".toCharArray())); } catch (Exception e) { throw new RaplaException( e.getMessage(), e); } } return clientContainer.getContext().lookup( ClientService.class); } protected ClientFacade getFacade() throws RaplaException { return getContext().lookup(ClientFacade.class); } protected RaplaLocale getRaplaLocale() throws RaplaException { return getContext().lookup(RaplaLocale.class); } protected void tearDown() throws Exception { if (raplaContainer != null) raplaContainer.dispose(); } }
04900db4-rob
test-src/org/rapla/RaplaTestCase.java
Java
gpl3
5,286
package org.rapla.plugin.eventtimecalculator; import junit.framework.TestCase; public class EventTimeModelTest extends TestCase { EventTimeModel model = new EventTimeModel(); { model.setDurationOfBreak(15); model.setTimeUnit( 45 ); model.setTimeTillBreak( 90 ); } public void testModel() { // Brutto: 90min => 2 x 45 = 2 TimeUnits (Pause 0) assertEquals(90, model.calcDuration( 90 )); assertEquals(90, model.calcDuration( 91 )); assertEquals(90, model.calcDuration( 104 )); // Brutto: 105min => 2 TimeUnits (Pause 15) assertEquals(90, model.calcDuration( 105 )); assertEquals(91, model.calcDuration( 106 )); // Brutto: 120min => 2 TimeUnits + 15 min (Pause 15min) assertEquals(105, model.calcDuration( 120 )); // Brutto: 150 min => 3 TimeUnits (Pause 15min) assertEquals(135, model.calcDuration( 150 )); // Brutto: 195 min => 4 TimeUnits (Pause 15min) assertEquals(180, model.calcDuration( 195 )); // Brutto: 210min (3h 30min) => 4 TimeUnits (Pause 30min) assertEquals(180, model.calcDuration( 210 )); // Brutto: 220min (3h 40min) => 4 TimeUnit + 10min (Pause 30min) assertEquals(190, model.calcDuration( 220 )); } }
04900db4-rob
test-src/org/rapla/plugin/eventtimecalculator/EventTimeModelTest.java
Java
gpl3
1,200
package org.rapla.plugin.tests; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.TimeZone; import org.rapla.RaplaTestCase; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaDefaultContext; import org.rapla.framework.RaplaLocale; import org.rapla.plugin.ical.server.RaplaICalImport; import org.rapla.server.TimeZoneConverter; import org.rapla.server.internal.TimeZoneConverterImpl; public class ICalImportTest extends RaplaTestCase{ public ICalImportTest(String name) { super(name); } public void testICalImport1() throws Exception{ RaplaContext parentContext = getContext(); RaplaDefaultContext context = new RaplaDefaultContext(parentContext); context.put( TimeZoneConverter.class, new TimeZoneConverterImpl()); TimeZone timezone = TimeZone.getTimeZone("GMT+1"); RaplaICalImport importer = new RaplaICalImport(context, timezone); boolean isUrl = true; String content = "https://www.google.com/calendar/ical/1s28a6qtt9q4faf7l9op7ank4c%40group.calendar.google.com/public/basic.ics"; Allocatable newResource = getFacade().newResource(); newResource.getClassification().setValue("name", "icaltest"); getFacade().store( newResource); List<Allocatable> allocatables = Collections.singletonList( newResource); User user = getFacade().getUser("homer"); String eventTypeKey = getFacade().getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)[0].getKey(); importer.importCalendar(content, isUrl, allocatables, user, eventTypeKey, "name"); } public void testICalImport2() throws Exception{ RaplaContext parentContext = getContext(); RaplaDefaultContext context = new RaplaDefaultContext(parentContext); context.put( TimeZoneConverter.class, new TimeZoneConverterImpl()); TimeZone timezone = TimeZone.getTimeZone("GMT+1"); RaplaICalImport importer = new RaplaICalImport(context, timezone); boolean isUrl = false; String packageName = getClass().getPackage().getName().replaceAll("\\.", "/"); String pathname = TEST_SRC_FOLDER_NAME + "/" + packageName + "/test.ics"; BufferedReader reader = new BufferedReader(new FileReader( new File(pathname))); StringBuilder fileContent = new StringBuilder(); while ( true) { String line = reader.readLine(); if ( line == null) { break; } fileContent.append( line ); fileContent.append( "\n"); } reader.close(); String content = fileContent.toString(); Allocatable newResource = getFacade().newResource(); newResource.getClassification().setValue("name", "icaltest"); getFacade().store( newResource); List<Allocatable> allocatables = Collections.singletonList( newResource); User user = getFacade().getUser("homer"); String eventTypeKey = getFacade().getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)[0].getKey(); importer.importCalendar(content, isUrl, allocatables, user, eventTypeKey, "name"); Reservation[] reservations; { Date start = null; Date end = null; reservations = getFacade().getReservations( allocatables.toArray( Allocatable.ALLOCATABLE_ARRAY), start, end); } assertEquals( 1, reservations.length); Reservation event = reservations[0]; Appointment[] appointments = event.getAppointments(); assertEquals( 1, appointments.length); Appointment appointment = appointments[0]; Date start= appointment.getStart(); RaplaLocale raplaLocale = getRaplaLocale(); // We expect a one our shift in time because we set GMT+1 in timezone settings and the timezone of the ical file is GMT+0 Date time = raplaLocale.toTime(11+1, 30, 0); Date date = raplaLocale.toRaplaDate(2012, 11, 6); assertEquals( raplaLocale.toDate(date, time), start); } }
04900db4-rob
test-src/org/rapla/plugin/tests/ICalImportTest.java
Java
gpl3
4,446
/*--------------------------------------------------------------------------* | 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.plugin.tests; import java.util.Locale; import org.rapla.MockMailer; import org.rapla.ServletTestBase; import org.rapla.facade.ClientFacade; import org.rapla.plugin.mail.MailToUserInterface; import org.rapla.plugin.mail.server.MailInterface; import org.rapla.plugin.mail.server.RaplaMailToUserOnLocalhost; import org.rapla.server.ServerService; import org.rapla.server.ServerServiceContainer; /** listens for allocation changes */ public class MailPluginTest extends ServletTestBase { ServerService raplaServer; ClientFacade facade1; Locale locale; public MailPluginTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); // start the server ServerServiceContainer container = getContainer().lookup(ServerServiceContainer.class,getStorageName()); raplaServer = container.getContext().lookup( ServerService.class); // start the client service facade1 = getContainer().lookup(ClientFacade.class ,"remote-facade"); facade1.login("homer","duffs".toCharArray()); locale = Locale.getDefault(); } protected String getStorageName() { return "storage-file"; } protected void tearDown() throws Exception { facade1.logout(); super.tearDown(); } public void test() throws Exception { MailToUserInterface mail = new RaplaMailToUserOnLocalhost(raplaServer.getContext()); mail.sendMail( "homer","Subject", "MyBody"); MockMailer mailMock = (MockMailer) raplaServer.getContext().lookup( MailInterface.class); Thread.sleep( 1000); assertNotNull( mailMock.getMailBody() ); } }
04900db4-rob
test-src/org/rapla/plugin/tests/MailPluginTest.java
Java
gpl3
2,681
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.tests; import java.util.Arrays; import java.util.Collections; import java.util.Locale; import org.rapla.RaplaTestCase; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Period; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.ClientFacade; import org.rapla.plugin.periodcopy.CopyPluginMenu; /** listens for allocation changes */ public class CopyPeriodPluginTest extends RaplaTestCase { ClientFacade facade; Locale locale; public CopyPeriodPluginTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); facade = raplaContainer.lookup(ClientFacade.class , "local-facade"); facade.login("homer","duffs".toCharArray()); locale = Locale.getDefault(); } private Reservation findReservationWithName(Reservation[] reservations, String name) { for (int i=0;i<reservations.length;i++) { if ( reservations[i].getName( locale).equals( name )) { return reservations[i]; } } return null; } @SuppressWarnings("null") public void test() throws Exception { CalendarSelectionModel model = facade.newCalendarModel( facade.getUser()); ClassificationFilter filter = facade.getDynamicType("room").newClassificationFilter(); filter.addEqualsRule("name","erwin"); Allocatable allocatable = facade.getAllocatables( new ClassificationFilter[] { filter})[0]; model.setSelectedObjects( Collections.singletonList(allocatable )); Period[] periods = facade.getPeriods(); Period sourcePeriod = null; Period destPeriod = null; for ( int i=0;i<periods.length;i++) { if ( periods[i].getName().equals("SS 2002")) { sourcePeriod = periods[i]; } if ( periods[i].getName().equals("SS 2001")) { destPeriod = periods[i]; } } assertNotNull( "Period not found ", sourcePeriod ); assertNotNull( "Period not found ", destPeriod ); CopyPluginMenu init = new CopyPluginMenu( getClientService().getContext() ); Reservation[] original = model.getReservations( sourcePeriod.getStart(), sourcePeriod.getEnd()); assertNotNull(findReservationWithName(original, "power planting")); init.copy( Arrays.asList(original), destPeriod.getStart(),destPeriod.getEnd(), false); Reservation[] copy = model.getReservations( destPeriod.getStart(), destPeriod.getEnd()); assertNotNull(findReservationWithName(copy,"power planting")); } }
04900db4-rob
test-src/org/rapla/plugin/tests/CopyPeriodPluginTest.java
Java
gpl3
3,710
/*--------------------------------------------------------------------------* | 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.plugin.tests; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.rapla.MockMailer; import org.rapla.ServletTestBase; import org.rapla.components.util.DateTools; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.RaplaMap; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.facade.ClientFacade; import org.rapla.framework.RaplaException; import org.rapla.plugin.mail.server.MailInterface; import org.rapla.plugin.notification.NotificationPlugin; import org.rapla.server.ServerService; import org.rapla.server.ServerServiceContainer; /** listens for allocation changes */ public class NotificationPluginTest extends ServletTestBase { ServerService raplaServer; ClientFacade facade1; Locale locale; public NotificationPluginTest( String name ) { super( name ); } protected void setUp() throws Exception { super.setUp(); // start the server ServerServiceContainer raplaServerContainer = getContainer().lookup( ServerServiceContainer.class, getStorageName() ); raplaServer = raplaServerContainer.getContext().lookup( ServerService.class ); // start the client service facade1 = getContainer().lookup( ClientFacade.class , "remote-facade" ); facade1.login( "homer", "duffs".toCharArray() ); locale = Locale.getDefault(); } protected void tearDown() throws Exception { facade1.logout(); super.tearDown(); } protected String getStorageName() { return "storage-file"; } private void add( Allocatable allocatable, Preferences preferences ) throws RaplaException { Preferences copy = facade1.edit( preferences ); RaplaMap<Allocatable> raplaEntityList = copy.getEntry( NotificationPlugin.ALLOCATIONLISTENERS_CONFIG ); List<Allocatable> list; if ( raplaEntityList != null ) { list = new ArrayList<Allocatable>( raplaEntityList.values() ); } else { list = new ArrayList<Allocatable>(); } list.add( allocatable ); //getLogger().info( "Adding notificationEntry " + allocatable ); RaplaMap<Allocatable> newRaplaMap = facade1.newRaplaMap( list ); copy.putEntry( NotificationPlugin.ALLOCATIONLISTENERS_CONFIG, newRaplaMap ); copy.putEntry( NotificationPlugin.NOTIFY_IF_OWNER_CONFIG, true ); facade1.store( copy ); } public void testAdd() throws Exception { Allocatable allocatable = facade1.getAllocatables()[0]; Allocatable allocatable2 = facade1.getAllocatables()[1]; add( allocatable, facade1.getPreferences() ); User user2 = facade1.getUser("monty"); add( allocatable2, facade1.getPreferences(user2) ); Reservation r = facade1.newReservation(); String reservationName = "New Reservation"; r.getClassification().setValue( "name", reservationName ); Appointment appointment = facade1.newAppointment( new Date(), new Date( new Date().getTime() + DateTools.MILLISECONDS_PER_HOUR ) ); r.addAppointment( appointment ); r.addAllocatable( allocatable ); r.addAllocatable( allocatable2 ); System.out.println( r.getLastChanged() ); facade1.store( r ); System.out.println( r.getLastChanged() ); MockMailer mailMock = (MockMailer) raplaServer.getContext().lookup( MailInterface.class ); for ( int i=0;i<1000;i++ ) { if (mailMock.getMailBody()!= null) { break; } Thread.sleep( 100 ); } assertTrue( mailMock.getMailBody().indexOf( reservationName ) >= 0 ); assertEquals( 2, mailMock.getCallCount() ); reservationName = "Another name"; r=facade1.edit( r); r.getClassification().setValue( "name", reservationName ); r.getAppointments()[0].move( new Date( new Date().getTime() + DateTools.MILLISECONDS_PER_HOUR ) ); facade1.store( r ); System.out.println( r.getLastChanged() ); Thread.sleep( 1000 ); assertEquals( 4, mailMock.getCallCount() ); assertNotNull( mailMock.getMailBody() ); assertTrue( mailMock.getMailBody().indexOf( reservationName ) >= 0 ); } public void testRemove() throws Exception { Allocatable allocatable = facade1.getAllocatables()[0]; add( allocatable, facade1.getPreferences() ); Reservation r = facade1.newReservation(); String reservationName = "New Reservation"; r.getClassification().setValue( "name", reservationName ); Appointment appointment = facade1.newAppointment( new Date(), new Date( new Date().getTime() + DateTools.MILLISECONDS_PER_HOUR ) ); r.addAppointment( appointment ); r.addAllocatable( allocatable ); facade1.store( r ); facade1.remove( r ); MockMailer mailMock = (MockMailer) raplaServer.getContext().lookup( MailInterface.class ); for ( int i=0;i<1000;i++ ) { if (mailMock.getMailBody()!= null) { break; } Thread.sleep( 100 ); } assertEquals( 2, mailMock.getCallCount() ); String body = mailMock.getMailBody(); assertTrue( "Body doesnt contain delete text\n" + body, body.indexOf( "gel\u00f6scht" ) >= 0 ); } }
04900db4-rob
test-src/org/rapla/plugin/tests/NotificationPluginTest.java
Java
gpl3
6,640
package org.rapla; import org.rapla.rest.jsonpatch.mergepatch.server.JsonMergePatch; import org.rapla.rest.jsonpatch.mergepatch.server.JsonPatchException; import junit.framework.TestCase; import com.google.gson.JsonElement; import com.google.gson.JsonParser; public class JSONPatchTest extends TestCase { public void test() throws JsonPatchException { JsonParser parser = new JsonParser(); String jsonOrig = new String("{'classification': {'type' : 'MyResourceTypeKey', 'data': {'name' : ['New ResourceName'] } } }"); String newName = "Room A1234"; String jsonPatch = new String("{'classification': { 'data': {'name' : ['"+newName+"'] } } }"); JsonElement patchElement = parser.parse(jsonPatch); JsonElement orig = parser.parse(jsonOrig); final JsonMergePatch patch = JsonMergePatch.fromJson(patchElement); final JsonElement patched = patch.apply(orig); System.out.println("Original " +orig.toString()); System.out.println("Patch " +patchElement.toString()); System.out.println("Patched " +patched.toString()); String jsonExpected = new String("{'classification': {'type' : 'MyResourceTypeKey', 'data': {'name' : ['"+ newName +"'] } } }"); JsonElement expected = parser.parse(jsonExpected); assertEquals( expected.toString(), patched.toString()); } }
04900db4-rob
test-src/org/rapla/JSONPatchTest.java
Java
gpl3
1,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.facade.tests; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Locale; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.RaplaTestCase; import org.rapla.components.util.DateTools; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.entities.DependencyException; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.ReadOnlyException; import org.rapla.entities.User; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.RaplaMap; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.ClientFacade; import org.rapla.facade.Conflict; import org.rapla.facade.ModificationModule; import org.rapla.facade.QueryModule; import org.rapla.facade.UserModule; import org.rapla.facade.internal.CalendarModelImpl; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.framework.TypedComponentRole; import org.rapla.plugin.weekview.WeekViewFactory; public class ClientFacadeTest extends RaplaTestCase { ClientFacade facade; Locale locale; public ClientFacadeTest(String name) { super(name); } public static Test suite() { return new TestSuite(ClientFacadeTest.class); } protected void setUp() throws Exception { super.setUp(); facade = getContext().lookup(ClientFacade.class ); facade.login("homer","duffs".toCharArray()); locale = Locale.getDefault(); } protected void tearDown() throws Exception { facade.logout(); super.tearDown(); } private Reservation findReservation(QueryModule queryMod,String name) throws RaplaException { Reservation[] reservations = queryMod.getReservationsForAllocatable(null,null,null,null); for (int i=0;i<reservations.length;i++) { if (reservations[i].getName(locale).equals(name)) return reservations[i]; } return null; } public void testConflicts() throws Exception { Conflict[] conflicts= facade.getConflicts( ); Reservation[] all = facade.getReservationsForAllocatable(null, null, null, null); facade.removeObjects( all ); Reservation orig = facade.newReservation(); orig.getClassification().setValue("name","new"); Date start = DateTools.fillDate( new Date()); Date end = getRaplaLocale().toDate( start, getRaplaLocale().toTime( 12,0,0)); orig.addAppointment( facade.newAppointment( start, end)); orig.addAllocatable( facade.getAllocatables()[0]); Reservation clone = facade.clone( orig ); facade.store( orig ); facade.store( clone ); Conflict[] conflictsAfter = facade.getConflicts( ); assertEquals( 1, conflictsAfter.length - conflicts.length ); HashSet<Conflict> set = new HashSet<Conflict>( Arrays.asList( conflictsAfter )); assertTrue ( set.containsAll( new HashSet<Conflict>( Arrays.asList( conflicts )))); } // Make some Changes to the Reservation in another client private void changeInSecondFacade(String name) throws Exception { ClientFacade facade2 = raplaContainer.lookup(ClientFacade.class ,"local-facade2"); facade2.login("homer","duffs".toCharArray()); UserModule userMod2 = facade2; QueryModule queryMod2 = facade2; ModificationModule modificationMod2 = facade2; boolean bLogin = userMod2.login("homer","duffs".toCharArray()); assertTrue(bLogin); Reservation reservation = findReservation(queryMod2,name); Reservation mutableReseravation = modificationMod2.edit(reservation); Appointment appointment = mutableReseravation.getAppointments()[0]; RaplaLocale loc = getRaplaLocale(); Calendar cal = loc.createCalendar(); cal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY); Date startTime = loc.toTime( 17,0,0); Date startTime1 = loc.toDate(cal.getTime(), startTime); Date endTime = loc.toTime( 19,0,0); Date endTime1 = loc.toDate(cal.getTime(), endTime); appointment.move(startTime1,endTime1); modificationMod2.store( mutableReseravation ); //userMod2.logout(); } public void testClone() throws Exception { ClassificationFilter filter = facade.getDynamicType("event").newClassificationFilter(); filter.addEqualsRule("name","power planting"); Reservation orig = facade.getReservationsForAllocatable(null, null, null, new ClassificationFilter[] { filter})[0]; Reservation clone = facade.clone( orig ); Appointment a = clone.getAppointments()[0]; Date newStart = new SerializableDateTimeFormat().parseDateTime("2005-10-10","10:20:00"); Date newEnd = new SerializableDateTimeFormat().parseDateTime("2005-10-12", null); a.move( newStart ); a.getRepeating().setEnd( newEnd ); facade.store( clone ); Reservation[] allPowerPlantings = facade.getReservationsForAllocatable(null, null, null, new ClassificationFilter[] { filter}); assertEquals( 2, allPowerPlantings.length); Reservation[] onlyClones = facade.getReservationsForAllocatable(null, newStart, null, new ClassificationFilter[] { filter}); assertEquals( 1, onlyClones.length); } public void testRefresh() throws Exception { changeInSecondFacade("bowling"); facade.refresh(); Reservation resAfter = findReservation(facade,"bowling"); Appointment appointment = resAfter.getAppointments()[0]; Calendar cal = Calendar.getInstance(DateTools.getTimeZone()); cal.setTime(appointment.getStart()); assertEquals(17, cal.get(Calendar.HOUR_OF_DAY) ); assertEquals(Calendar.MONDAY, cal.get(Calendar.DAY_OF_WEEK) ); cal.setTime(appointment.getEnd()); assertEquals(19, cal.get(Calendar.HOUR_OF_DAY)); assertEquals( Calendar.MONDAY, cal.get(Calendar.DAY_OF_WEEK)); } public void testExampleEdit() throws Exception { String allocatableId; String eventId; { Allocatable nonPersistantAllocatable = getFacade().newResource(); nonPersistantAllocatable.getClassification().setValue("name", "Bla"); Reservation nonPeristantEvent = getFacade().newReservation(); nonPeristantEvent.getClassification().setValue("name","dummy-event"); assertEquals( "event", nonPeristantEvent.getClassification().getType().getKey()); nonPeristantEvent.addAllocatable( nonPersistantAllocatable ); nonPeristantEvent.addAppointment( getFacade().newAppointment( new Date(), new Date())); getFacade().storeObjects( new Entity[] { nonPersistantAllocatable, nonPeristantEvent} ); allocatableId = nonPersistantAllocatable.getId(); eventId = nonPeristantEvent.getId(); } Allocatable allocatable = facade.edit(facade.getOperator().resolve(allocatableId, Allocatable.class) ); // Store the allocatable it a second time to test if it is still modifiable after storing allocatable.getClassification().setValue("name", "Blubs"); getFacade().store( allocatable ); // query the allocatable from the store ClassificationFilter filter = getFacade().getDynamicType("room").newClassificationFilter(); filter.addEqualsRule("name","Blubs"); Allocatable persistantAllocatable = getFacade().getAllocatables( new ClassificationFilter[] { filter} )[0]; // query the event from the store ClassificationFilter eventFilter = getFacade().getDynamicType("event").newClassificationFilter(); eventFilter.addEqualsRule("name","dummy-event"); Reservation persistantEvent = getFacade().getReservationsForAllocatable( null, null, null,new ClassificationFilter[] { eventFilter} )[0]; // Another way to get the persistant event would have been //Reservation persistantEvent = getFacade().getPersistant( nonPeristantEvent ); // test if the ids of editable Versions are equal to the persistant ones assertEquals( persistantAllocatable, allocatable); Reservation event = facade.getOperator().resolve( eventId, Reservation.class); assertEquals( persistantEvent, event); assertEquals( persistantEvent.getAllocatables()[0], event.getAllocatables()[0]); // // Check if the modifiable/original versions are different to the persistant versions // assertTrue( persistantAllocatable != allocatable ); // assertTrue( persistantEvent != event ); // assertTrue( persistantEvent.getAllocatables()[0] != event.getAllocatables()[0]); // Test the read only constraints try { persistantAllocatable.getClassification().setValue("name","asdflkj"); fail("ReadOnlyException should have been thrown"); } catch (ReadOnlyException ex) { } try { persistantEvent.getClassification().setValue("name","dummy-event"); fail("ReadOnlyException should have been thrown"); } catch (ReadOnlyException ex) { } try { persistantEvent.removeAllocatable( allocatable); fail("ReadOnlyException should have been thrown"); } catch (ReadOnlyException ex) { } // now we get a second edit copy of the event Reservation nonPersistantEventVersion2 = getFacade().edit( persistantEvent); assertTrue( nonPersistantEventVersion2 != event ); // Both allocatables are persitant, so they have the same reference assertTrue( persistantEvent.getAllocatables()[0] == nonPersistantEventVersion2.getAllocatables()[0]); } public void testLogin() throws Exception { ClientFacade facade2 = raplaContainer.lookup(ClientFacade.class , "local-facade2"); assertEquals(false, facade2.login("non_existant_user","".toCharArray())); assertEquals(false, facade2.login("non_existant_user","fake".toCharArray())); assertTrue(facade2.login("homer","duffs".toCharArray())); assertEquals("homer",facade2.getUser().getUsername()); facade.logout(); } public void testSavePreferences() throws Exception { ClientFacade facade2 = raplaContainer.lookup(ClientFacade.class , "local-facade2"); assertTrue(facade2.login("monty","burns".toCharArray())); Preferences prefs = facade.edit( facade.getPreferences() ); facade2.store( prefs ); facade2.logout(); } public void testNewUser() throws RaplaException { User newUser = facade.newUser(); newUser.setUsername("newUser"); try { facade.getPreferences(newUser); fail( "getPreferences should throw an Exception for non existant user"); } catch (EntityNotFoundException ex ){ } facade.store( newUser ); Preferences prefs = facade.edit( facade.getPreferences(newUser) ); facade.store( prefs ); } public void testPreferenceDependencies() throws RaplaException { Allocatable allocatable = facade.newResource(); facade.store( allocatable); CalendarSelectionModel calendar = facade.newCalendarModel(facade.getUser() ); calendar.setSelectedObjects( Collections.singleton( allocatable)); calendar.setViewId( WeekViewFactory.WEEK_VIEW); CalendarModelConfiguration config = ((CalendarModelImpl)calendar).createConfiguration(); RaplaMap<CalendarModelConfiguration> calendarList = facade.newRaplaMap( Collections.singleton( config )); Preferences preferences = facade.getPreferences(); Preferences editPref = facade.edit( preferences ); TypedComponentRole<RaplaMap<CalendarModelConfiguration>> TEST_ENTRY = new TypedComponentRole<RaplaMap<CalendarModelConfiguration>>("TEST"); editPref.putEntry(TEST_ENTRY, calendarList ); facade.store( editPref ); try { facade.remove( allocatable ); fail("DependencyException should have thrown"); } catch (DependencyException ex) { } calendarList = facade.newRaplaMap( new ArrayList<CalendarModelConfiguration> ()); editPref = facade.edit( preferences ); editPref.putEntry( TEST_ENTRY, calendarList ); facade.store( editPref ); facade.remove( allocatable ); } public void testResourcesNotEmpty() throws RaplaException { Allocatable[] resources = facade.getAllocatables(null); assertTrue(resources.length > 0); } void printConflicts(Conflict[] c) { System.out.println(c.length + " Conflicts:"); for (int i=0;i<c.length;i++) { printConflict(c[i]); } } void printConflict(Conflict c) { System.out.println("Conflict: " + c.getAppointment1() + " with " + c.getAppointment2()); System.out.println(" " + c.getAllocatable().getName(locale)) ; System.out.println(" " + c.getAppointment1() + " overlapps " + c.getAppointment2()); } }
04900db4-rob
test-src/org/rapla/facade/tests/ClientFacadeTest.java
Java
gpl3
14,555
package org.rapla; import java.io.File; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URL; import junit.framework.TestCase; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.webapp.WebAppContext; import org.rapla.components.util.IOUtil; import org.rapla.framework.Container; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.server.MainServlet; @SuppressWarnings("restriction") public abstract class ServletTestBase extends TestCase { MainServlet mainServlet; Server jettyServer; public static String TEST_SRC_FOLDER_NAME="test-src"; public static String WAR_SRC_FOLDER_NAME="war"; final public static String WEBAPP_FOLDER_NAME = RaplaTestCase.TEST_FOLDER_NAME + "/webapp"; final public static String WEBAPP_INF_FOLDER_NAME = WEBAPP_FOLDER_NAME + "/WEB-INF"; public ServletTestBase( String name ) { super( name ); new File("temp").mkdir(); File testFolder =new File(RaplaTestCase.TEST_FOLDER_NAME); testFolder.mkdir(); } protected void setUp() throws Exception { File webappFolder = new File(WEBAPP_FOLDER_NAME); IOUtil.deleteAll( webappFolder ); new File(WEBAPP_INF_FOLDER_NAME).mkdirs(); IOUtil.copy( TEST_SRC_FOLDER_NAME + "/test.xconf", WEBAPP_INF_FOLDER_NAME + "/raplaserver.xconf" ); //IOUtil.copy( "test-src/test.xlog", WEBAPP_INF_FOLDER_NAME + "/raplaserver.xlog" ); IOUtil.copy( TEST_SRC_FOLDER_NAME + "/testdefault.xml", WEBAPP_INF_FOLDER_NAME + "/test.xml" ); IOUtil.copy( WAR_SRC_FOLDER_NAME + "/WEB-INF/web.xml", WEBAPP_INF_FOLDER_NAME + "/web.xml" ); jettyServer =new Server(8052); WebAppContext context = new WebAppContext( jettyServer,"rapla","/" ); context.setResourceBase( webappFolder.getAbsolutePath() ); context.setMaxFormContentSize(64000000); MainServlet.serverContainerHint=getStorageName(); // context.addServlet( new ServletHolder(mainServlet), "/*" ); jettyServer.start(); Handler[] childHandlers = context.getChildHandlersByClass(ServletHandler.class); ServletHolder servlet = ((ServletHandler)childHandlers[0]).getServlet("RaplaServer"); mainServlet = (MainServlet) servlet.getServlet(); URL server = new URL("http://127.0.0.1:8052/rapla/ping"); HttpURLConnection connection = (HttpURLConnection)server.openConnection(); int timeout = 10000; int interval = 200; for ( int i=0;i<timeout / interval;i++) { try { connection.connect(); } catch (ConnectException ex) { Thread.sleep(interval); } } } protected RaplaContext getContext() { return mainServlet.getContext(); } protected Container getContainer() { return mainServlet.getContainer(); } protected <T> T getService(Class<T> role) throws RaplaException { return getContext().lookup( role); } protected RaplaLocale getRaplaLocale() throws Exception { return getContext().lookup(RaplaLocale.class); } protected void tearDown() throws Exception { jettyServer.stop(); super.tearDown(); } protected String getStorageName() { return "storage-file"; } }
04900db4-rob
test-src/org/rapla/ServletTestBase.java
Java
gpl3
3,646
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Locale; import org.rapla.components.util.DateTools; import org.rapla.entities.Category; import org.rapla.entities.DependencyException; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.User; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Permission; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.ConstraintIds; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.ClientFacade; import org.rapla.facade.internal.CalendarModelImpl; import org.rapla.framework.Container; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; import org.rapla.plugin.weekview.WeekViewFactory; import org.rapla.server.ServerService; import org.rapla.server.ServerServiceContainer; import org.rapla.storage.StorageOperator; public class ServerTest extends ServletTestBase { ServerService raplaServer; protected ClientFacade facade1; protected ClientFacade facade2; Locale locale; public ServerTest(String name) { super(name); } static public void main(String[] args) { String method = "testLoad"; ServerTest test = new ServerTest(method); try { test.run(); } catch (Throwable ex) { ex.printStackTrace(); } } protected void setUp() throws Exception { initTestData(); super.setUp(); // start the server Container container = getContainer(); ServerServiceContainer raplaServerContainer = container.lookup( ServerServiceContainer.class, getStorageName()); raplaServer = raplaServerContainer.getContext().lookup( ServerService.class); // start the client service facade1 = container.lookup(ClientFacade.class, "remote-facade"); facade1.login("homer", "duffs".toCharArray()); facade2 = container.lookup(ClientFacade.class, "remote-facade-2"); facade2.login("homer", "duffs".toCharArray()); locale = Locale.getDefault(); } protected void initTestData() throws Exception { } protected String getStorageName() { return "storage-file"; } protected void tearDown() throws Exception { facade1.logout(); facade2.logout(); super.tearDown(); } public void testLoad() throws Exception { facade1.getAllocatables(); } public void testChangeReservation() throws Exception { Reservation r1 = facade1.newReservation(); String typeKey = r1.getClassification().getType().getKey(); r1.getClassification().setValue("name", "test-reservation"); r1.addAppointment(facade1.newAppointment(facade1.today(), new Date())); facade1.store(r1); // Wait for the update facade2.refresh(); Reservation r2 = findReservation(facade2, typeKey, "test-reservation"); assertEquals(1, r2.getAppointments().length); assertEquals(0, r2.getAllocatables().length); // Modify Reservation in first facade Reservation r1clone = facade1.edit(r2); r1clone.addAllocatable(facade1.getAllocatables()[0]); facade1.store(r1clone); // Wait for the update facade2.refresh(); // test for modify in second facade Reservation persistant = facade1.getPersistant(r2); assertEquals(1, persistant.getAllocatables().length); facade2.logout(); } public void testChangeDynamicType() throws Exception { { Allocatable allocatable = facade1.getAllocatables()[0]; assertEquals(3, allocatable.getClassification().getAttributes().length); } DynamicType type = facade1.getDynamicType("room"); Attribute newAttribute; { newAttribute = facade1.newAttribute(AttributeType.CATEGORY); DynamicType typeEdit1 = facade1.edit(type); newAttribute.setConstraint(ConstraintIds.KEY_ROOT_CATEGORY, facade1.getUserGroupsCategory()); newAttribute.setKey("test"); newAttribute.getName().setName("en", "test"); typeEdit1.addAttribute(newAttribute); facade1.store(typeEdit1); } { Allocatable newResource = facade1.newResource(); newResource.setClassification(type.newClassification()); newResource.getClassification().setValue("name", "test-resource"); newResource.getClassification().setValue("test", facade1.getUserGroupsCategory().getCategories()[0]); facade1.store(newResource); } { facade2.refresh(); // Dyn DynamicType typeInSecondFacade = facade2.getDynamicType("room"); Attribute att = typeInSecondFacade.getAttribute("test"); assertEquals("test", att.getKey()); assertEquals(AttributeType.CATEGORY, att.getType()); assertEquals(facade2.getUserGroupsCategory(), att.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY)); ClassificationFilter filter = typeInSecondFacade.newClassificationFilter(); filter.addEqualsRule("name", "test-resource"); Allocatable newResource = facade2.getAllocatables(filter.toArray())[0]; Classification classification = newResource.getClassification(); Category userGroup = (Category) classification.getValue("test"); assertEquals("Category attribute value is not stored", facade2 .getUserGroupsCategory().getCategories()[0].getKey(), userGroup.getKey()); facade2.logout(); } { Allocatable allocatable = facade1.getAllocatables()[0]; assertEquals(4, allocatable.getClassification().getAttributes().length); } DynamicType typeEdit2 = facade1.edit(type); Attribute attributeLater = typeEdit2.getAttribute("test"); assertTrue("Attributes identy changed after storing ", attributeLater.equals(newAttribute)); typeEdit2.removeAttribute(attributeLater); facade1.store(typeEdit2); { Allocatable allocatable = facade1.getAllocatables()[0]; assertEquals(facade1.getAllocatables().length, 5); assertEquals(3, allocatable.getClassification().getAttributes().length); } User user = facade1.newUser(); user.setUsername("test-user"); facade1.store(user); removeAnAttribute(); // Wait for the update { ClientFacade facade2 = getContainer().lookup(ClientFacade.class, "remote-facade-2"); facade2.login("homer", "duffs".toCharArray()); facade2.getUser("test-user"); facade2.logout(); } } public void removeAnAttribute() throws Exception { DynamicType typeEdit3 = facade1.edit(facade1.getDynamicType("room")); typeEdit3.removeAttribute(typeEdit3.getAttribute("belongsto")); Allocatable allocatable = facade1.getAllocatables()[0]; assertEquals("erwin", allocatable.getName(locale)); Allocatable allocatableClone = facade1.edit(allocatable); assertEquals(3, allocatable.getClassification().getAttributes().length); facade1.storeObjects(new Entity[] { allocatableClone, typeEdit3 }); assertEquals(5, facade1.getAllocatables().length); assertEquals(2, allocatable.getClassification().getAttributes().length); ClientFacade facade2 = getContainer().lookup(ClientFacade.class, "remote-facade-2"); facade2.login("homer", "duffs".toCharArray()); // we check if the store affectes the second client. assertEquals(5, facade2.getAllocatables().length); ClassificationFilter filter = facade2.getDynamicType("room") .newClassificationFilter(); filter.addIsRule("name", "erwin"); { Allocatable rAfter = facade2.getAllocatables(filter.toArray())[0]; assertEquals(2, rAfter.getClassification().getAttributes().length); } // facade2.getUser("test-user"); // Wait for the update facade2.refresh(); facade2.logout(); } private Reservation findReservation(ClientFacade facade, String typeKey,String name) throws RaplaException { DynamicType reservationType = facade.getDynamicType(typeKey); ClassificationFilter filter = reservationType.newClassificationFilter(); filter.addRule("name", new Object[][] { { "contains", name } }); Reservation[] reservations = facade.getReservationsForAllocatable(null, null, null, new ClassificationFilter[] { filter }); if (reservations.length > 0) return reservations[0]; else return null; } public void testChangeDynamicType2() throws Exception { { DynamicType type = facade1.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE)[0]; DynamicType typeEdit3 = facade1.edit(type); typeEdit3.removeAttribute(typeEdit3.getAttribute("belongsto")); Allocatable[] allocatables = facade1.getAllocatables(); Allocatable resource1 = allocatables[0]; assertEquals("erwin", resource1.getName(locale)); facade1.store(typeEdit3); } { Allocatable[] allocatables = facade1.getAllocatables(); Allocatable resource1 = allocatables[0]; assertEquals("erwin", resource1.getName(locale)); assertEquals(2, resource1.getClassification().getAttributes().length); } } public void testRemoveCategory() throws Exception { Category superCategoryClone = facade1.edit(facade1.getSuperCategory()); Category department = superCategoryClone.getCategory("department"); Category powerplant = department.getCategory("springfield-powerplant"); powerplant.getParent().removeCategory(powerplant); try { facade1.store(superCategoryClone); fail("Dependency Exception should have been thrown"); } catch (DependencyException ex) { } } public void testChangeLogin() throws RaplaException { ClientFacade facade2 = getContainer().lookup(ClientFacade.class,"remote-facade-2"); facade2.login("monty", "burns".toCharArray()); // boolean canChangePassword = facade2.canChangePassword(); User user = facade2.getUser(); facade2.changePassword(user, "burns".toCharArray(), "newPassword".toCharArray()); facade2.logout(); } public void testRemoveCategoryBug5() throws Exception { DynamicType type = facade1 .newDynamicType(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE); String testTypeName = "TestType"; type.getName().setName("en", testTypeName); Attribute att = facade1.newAttribute(AttributeType.CATEGORY); att.setKey("testdep"); { Category superCategoryClone = facade1.getSuperCategory(); Category department = superCategoryClone.getCategory("department"); att.setConstraint(ConstraintIds.KEY_ROOT_CATEGORY, department); } type.addAttribute(att); facade1.store(type); Category superCategoryClone = facade1.edit(facade1.getSuperCategory()); Category department = superCategoryClone.getCategory("department"); superCategoryClone.removeCategory(department); try { facade1.store(superCategoryClone); fail("Dependency Exception should have been thrown"); } catch (DependencyException ex) { Collection<String> dependencies = ex.getDependencies(); assertTrue("Dependencies doesnt contain " + testTypeName, contains(dependencies, testTypeName)); } } private boolean contains(Collection<String> dependencies, String testTypeName) { for (String dep : dependencies) { if (dep.contains(testTypeName)) { return true; } } return false; } public void testStoreFilter() throws Exception { // select from event where name contains 'planting' or name contains // 'test'; DynamicType dynamicType = facade1.getDynamicType("room"); ClassificationFilter classificationFilter = dynamicType .newClassificationFilter(); Category channel6 = facade1.getSuperCategory() .getCategory("department").getCategory("channel-6"); Category testdepartment = facade1.getSuperCategory() .getCategory("department").getCategory("testdepartment"); classificationFilter.setRule(0, dynamicType.getAttribute("belongsto"), new Object[][] { { "is", channel6 }, { "is", testdepartment } }); boolean thrown = false; ClassificationFilter[] filter = new ClassificationFilter[] { classificationFilter }; User user1 = facade1.getUser(); CalendarSelectionModel calendar = facade1.newCalendarModel(user1); calendar.setViewId(WeekViewFactory.WEEK_VIEW); calendar.setAllocatableFilter(filter); calendar.setSelectedObjects(Collections.emptyList()); calendar.setSelectedDate(facade1.today()); CalendarModelConfiguration conf = ((CalendarModelImpl) calendar) .createConfiguration(); Preferences prefs = facade1.edit(facade1.getPreferences()); TypedComponentRole<CalendarModelConfiguration> TEST_CONF = new TypedComponentRole<CalendarModelConfiguration>( "org.rapla.TestEntry"); prefs.putEntry(TEST_CONF, conf); facade1.store(prefs); ClientFacade facade = raplaServer.getFacade(); User user = facade.getUser("homer"); Preferences storedPrefs = facade.getPreferences(user); assertNotNull(storedPrefs); CalendarModelConfiguration storedConf = storedPrefs.getEntry(TEST_CONF); assertNotNull(storedConf); ClassificationFilter[] storedFilter = storedConf.getFilter(); assertEquals(1, storedFilter.length); ClassificationFilter storedClassFilter = storedFilter[0]; assertEquals(1, storedClassFilter.ruleSize()); try { Category parent = facade1.edit(testdepartment.getParent()); parent.removeCategory(testdepartment); facade1.store(parent); } catch (DependencyException ex) { assertTrue(contains(ex.getDependencies(), prefs.getName(locale))); thrown = true; } assertTrue("Dependency Exception should have been thrown!", thrown); } public void testReservationInTheFutureStoredInCalendar() throws Exception { Date futureDate = new Date(facade1.today().getTime() + DateTools.MILLISECONDS_PER_WEEK * 10); Reservation r = facade1.newReservation(); r.addAppointment(facade1.newAppointment(futureDate, futureDate)); r.getClassification().setValue("name", "Test"); facade1.store(r); CalendarSelectionModel calendar = facade1.newCalendarModel(facade1 .getUser()); calendar.setViewId(WeekViewFactory.WEEK_VIEW); calendar.setSelectedObjects(Collections.singletonList(r)); calendar.setSelectedDate(facade1.today()); calendar.setTitle("test"); CalendarModelConfiguration conf = ((CalendarModelImpl) calendar) .createConfiguration(); Preferences prefs = facade1.edit(facade1.getPreferences()); TypedComponentRole<CalendarModelConfiguration> TEST_ENTRY = new TypedComponentRole<CalendarModelConfiguration>( "org.rapla.test"); prefs.putEntry(TEST_ENTRY, conf); try { facade1.store(prefs); fail("Should throw an exception in the current version, because we can't store references to reservations"); } catch (RaplaException ex) { } } public void testReservationWithExceptionDoesntShow() throws Exception { { facade1.removeObjects(facade1.getReservationsForAllocatable(null, null, null, null)); } Date start = new Date(); Date end = new Date(start.getTime() + DateTools.MILLISECONDS_PER_HOUR * 2); { Reservation r = facade1.newReservation(); r.getClassification().setValue("name", "test-reservation"); Appointment a = facade1.newAppointment(start, end); a.setRepeatingEnabled(true); a.getRepeating().setType(Repeating.WEEKLY); a.getRepeating().setInterval(2); a.getRepeating().setNumber(10); r.addAllocatable(facade1.getAllocatables()[0]); r.addAppointment(a); a.getRepeating().addException(start); a.getRepeating() .addException( new Date(start.getTime() + DateTools.MILLISECONDS_PER_WEEK)); facade1.store(r); facade1.logout(); } { ClientFacade facade2 = getContainer().lookup(ClientFacade.class, "remote-facade-2"); facade2.login("homer", "duffs".toCharArray()); Reservation[] res = facade2.getReservationsForAllocatable(null, start, new Date(start.getTime() + 8 * DateTools.MILLISECONDS_PER_WEEK), null); assertEquals(1, res.length); Thread.sleep(100); facade2.logout(); } } public void testChangeGroup() throws Exception { User user = facade1.edit(facade1.getUser("monty")); Category[] groups = user.getGroups(); assertTrue("No groups found!", groups.length > 0); Category myGroup = facade1.getUserGroupsCategory().getCategory( "my-group"); assertTrue(Arrays.asList(groups).contains(myGroup)); user.removeGroup(myGroup); ClientFacade facade2 = getContainer().lookup(ClientFacade.class, "remote-facade-2"); facade2.login("homer", "duffs".toCharArray()); Allocatable testResource = facade2.edit(facade2.getAllocatables()[0]); assertTrue(testResource.canAllocate(facade2.getUser("monty"), null, null, null)); testResource.removePermission(testResource.getPermissions()[0]); Permission newPermission = testResource.newPermission(); newPermission.setGroup(facade1.getUserGroupsCategory().getCategory( "my-group")); newPermission.setAccessLevel(Permission.READ); testResource.addPermission(newPermission); assertFalse(testResource.canAllocate(facade2.getUser("monty"), null, null, null)); assertTrue(testResource.canRead(facade2.getUser("monty"))); facade1.store(user); facade2.refresh(); assertFalse(testResource.canAllocate(facade2.getUser("monty"), null, null, null)); } public void testRemoveAppointment() throws Exception { Allocatable[] allocatables = facade1.getAllocatables(); Date start = getRaplaLocale().toRaplaDate(2005, 11, 10); Date end = getRaplaLocale().toRaplaDate(2005, 11, 15); Reservation r = facade1.newReservation(); r.getClassification().setValue("name", "newReservation"); r.addAppointment(facade1.newAppointment(start, end)); r.addAllocatable(allocatables[0]); ClassificationFilter f = r.getClassification().getType().newClassificationFilter(); f.addEqualsRule("name", "newReservation"); facade1.store(r); r = facade1.getPersistant(r); facade1.remove(r); Reservation[] allRes = facade1.getReservationsForAllocatable(null, null, null, new ClassificationFilter[] { f }); assertEquals(0, allRes.length); } public void testRestrictionsBug7() throws Exception { Reservation r = facade1.newReservation(); r.getClassification().setValue("name", "newReservation"); Appointment app1; { Date start = getRaplaLocale().toRaplaDate(2005, 11, 10); Date end = getRaplaLocale().toRaplaDate(2005, 10, 15); app1 = facade1.newAppointment(start, end); r.addAppointment(app1); } Appointment app2; { Date start = getRaplaLocale().toRaplaDate(2008, 11, 10); Date end = getRaplaLocale().toRaplaDate(2008, 11, 15); app2 = facade1.newAppointment(start, end); r.addAppointment(app2); } Allocatable allocatable = facade1.getAllocatables()[0]; r.addAllocatable(allocatable); r.setRestriction(allocatable, new Appointment[] { app1, app2 }); facade1.store(r); facade1.logout(); facade1.login("homer", "duffs".toCharArray()); ClassificationFilter f = r.getClassification().getType() .newClassificationFilter(); f.addEqualsRule("name", "newReservation"); Reservation[] allRes = facade1.getReservationsForAllocatable(null, null, null, new ClassificationFilter[] { f }); Reservation test = allRes[0]; allocatable = facade1.getAllocatables()[0]; Appointment[] restrictions = test.getRestriction(allocatable); assertEquals("Restrictions needs to be saved!", 2, restrictions.length); } public void testMultilineTextField() throws Exception { String reservationName = "bowling"; { ClientFacade facade = this.raplaServer.getFacade(); String description = getDescriptionOfReservation(facade, reservationName); assertTrue(description.contains("\n")); } { ClientFacade facade = facade1; String description = getDescriptionOfReservation(facade, reservationName); assertTrue(description.contains("\n")); } } public void testTaskType() throws Exception { // first test creation on server { ClientFacade facade = this.raplaServer.getFacade(); DynamicType dynamicType = facade.getDynamicType(StorageOperator.SYNCHRONIZATIONTASK_TYPE); Classification classification = dynamicType.newClassification(); Allocatable task = facade.newAllocatable(classification, null); facade.store( task); } // then test availability on client try { ClientFacade facade = facade1; @SuppressWarnings("unused") DynamicType dynamicType = facade.getDynamicType(StorageOperator.SYNCHRONIZATIONTASK_TYPE); fail("Entity not found should have been thrown, because type is only accesible on the server side"); } catch (EntityNotFoundException ex) { } } public String getDescriptionOfReservation(ClientFacade facade, String reservationName) throws RaplaException { User user = null; Date start = null; Date end = null; ClassificationFilter filter = facade.getDynamicType("event").newClassificationFilter(); filter.addEqualsRule("name", reservationName); Reservation[] reservations = facade.getReservations(user, start, end, filter.toArray()); Reservation bowling = reservations[0]; Classification classification = bowling.getClassification(); Object descriptionValue = classification.getValue("description"); String description = descriptionValue.toString(); return description; } }
04900db4-rob
test-src/org/rapla/ServerTest.java
Java
gpl3
22,265
package org.rapla.rest.client; import java.net.URL; import junit.framework.TestCase; import org.rapla.ServletTestBase; public class RestAPITest extends ServletTestBase { public RestAPITest(String name) { super(name); } public void testRestApi() throws Exception { RestAPIExample example = new RestAPIExample() { protected void assertTrue( boolean condition) { TestCase.assertTrue(condition); } protected void assertEquals( Object o1, Object o2) { TestCase.assertEquals(o1, o2); } }; URL baseUrl = new URL("http://localhost:8052/rapla/"); example.testRestApi(baseUrl,"homer","duffs"); } }
04900db4-rob
test-src/org/rapla/rest/client/RestAPITest.java
Java
gpl3
784
package org.rapla.rest.client; import java.net.URL; import java.net.URLEncoder; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import org.rapla.rest.client.HTTPJsonConnector; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; public class RestAPIExample { protected void assertTrue( boolean condition) { if (!condition) { throw new IllegalStateException("Assertion failed"); } } protected void assertEquals( Object o1, Object o2) { if ( !o1.equals( o2)) { throw new IllegalStateException("Assertion failed. Expected " + o1 + " but was " + o2); } } public void testRestApi(URL baseUrl, String username,String password) throws Exception { HTTPJsonConnector connector = new HTTPJsonConnector(); // first we login using the auth method String authenticationToken = null; { URL methodURL =new URL(baseUrl,"auth"); JsonObject callObj = new JsonObject(); callObj.addProperty("username", username); callObj.addProperty("password", password); String emptyAuthenticationToken = null; JsonObject resultBody = connector.sendPost(methodURL, callObj, emptyAuthenticationToken); assertNoError(resultBody); JsonObject resultObject = resultBody.get("result").getAsJsonObject(); authenticationToken = resultObject.get("accessToken").getAsString(); String validity = resultObject.get("validUntil").getAsString(); System.out.println("token valid until " + validity); } // we get all the different resource,person and event types String resourceType = null; @SuppressWarnings("unused") String personType =null; String eventType =null; { URL methodURL =new URL(baseUrl,"dynamictypes?classificationType=resource"); JsonObject resultBody = connector.sendGet( methodURL, authenticationToken); assertNoError(resultBody); JsonArray resultList = resultBody.get("result").getAsJsonArray(); assertTrue( resultList.size() > 0); for (JsonElement obj:resultList) { JsonObject casted = (JsonObject) obj; resourceType =casted.get("key").getAsString(); } } { URL methodURL =new URL(baseUrl,"dynamictypes?classificationType=person"); JsonObject resultBody = connector.sendGet( methodURL, authenticationToken); assertNoError(resultBody); JsonArray resultList = resultBody.get("result").getAsJsonArray(); assertTrue( resultList.size() > 0); for (JsonElement obj:resultList) { JsonObject casted = (JsonObject) obj; personType =casted.get("key").getAsString(); } } { URL methodURL =new URL(baseUrl,"dynamictypes?classificationType=reservation"); JsonObject resultBody = connector.sendGet( methodURL, authenticationToken); assertNoError(resultBody); JsonArray resultList = resultBody.get("result").getAsJsonArray(); assertTrue( resultList.size() > 0); for (JsonElement obj:resultList) { JsonObject casted = (JsonObject) obj; eventType =casted.get("key").getAsString(); } } // we create a new resource String resourceId = null; String resourceName; { resourceName = "Test Room"; String objectName = resourceName; String dynamicType = resourceType; JsonObject eventObject = new JsonObject(); Map<String,String> keyValue = new LinkedHashMap<String,String>(); keyValue.put( "name", objectName); JsonObject classificationObj = new JsonObject(); classificationObj.add("type", new JsonPrimitive(dynamicType)); patchClassification(keyValue, classificationObj); eventObject.add("classification", classificationObj); { URL methodURL =new URL(baseUrl,"resources"); JsonObject resultBody = connector.sendPost( methodURL, eventObject, authenticationToken); // we test if the new resource has the name and extract the id for later testing printAttributesAndAssertName(resultBody, objectName); resourceId = resultBody.get("result").getAsJsonObject().get("id").getAsString(); } // now we test again if the new resource is created by using the get method { URL methodURL =new URL(baseUrl,"resources/"+resourceId); JsonObject resultBody = connector.sendGet( methodURL, authenticationToken); printAttributesAndAssertName(resultBody, objectName); } } // we use a get list on the resources { String attributeFilter = URLEncoder.encode("{'name' :'"+ resourceName +"'}","UTF-8"); String resourceTypes =URLEncoder.encode("['"+ resourceType +"']","UTF-8"); URL methodURL =new URL(baseUrl,"resources?resourceTypes="+ resourceTypes+ "&attributeFilter="+attributeFilter) ; JsonObject resultBody = connector.sendGet( methodURL, authenticationToken); assertNoError(resultBody); JsonArray resultList = resultBody.get("result").getAsJsonArray(); assertTrue( resultList.size() > 0); for (JsonElement obj:resultList) { JsonObject casted = (JsonObject) obj; String id = casted.get("id").getAsString(); JsonObject classification = casted.get("classification").getAsJsonObject().get("data").getAsJsonObject(); String name = classification.get("name").getAsJsonArray().get(0).getAsString(); System.out.println("[" +id + "]" + name); } } // we create a new event for the resource String eventId = null; String eventName = null; { eventName ="event name"; String objectName = eventName; String dynamicType =eventType; JsonObject eventObject = new JsonObject(); Map<String,String> keyValue = new LinkedHashMap<String,String>(); keyValue.put( "name", objectName); JsonObject classificationObj = new JsonObject(); classificationObj.add("type", new JsonPrimitive(dynamicType)); patchClassification(keyValue, classificationObj); eventObject.add("classification", classificationObj); // add appointments { // IS0 8061 format is required. Always add the dates in UTC Timezone // Rapla doesn't support multiple timezone. All internal dates are stored in UTC // So store 10:00 local time as 10:00Z JsonObject appointmentObj = createAppointment("2015-01-01T10:00Z","2015-01-01T12:00Z"); JsonArray appoinmentArray = new JsonArray(); appoinmentArray.add( appointmentObj); eventObject.add("appointments", appoinmentArray); } // add resources { JsonArray resourceArray = new JsonArray(); resourceArray.add( new JsonPrimitive(resourceId)); JsonObject linkMap = new JsonObject(); linkMap.add("resources", resourceArray); eventObject.add("links", linkMap); } { URL methodURL =new URL(baseUrl,"events"); JsonObject resultBody = connector.sendPost( methodURL, eventObject, authenticationToken); // we test if the new event has the name and extract the id for later testing printAttributesAndAssertName(resultBody, objectName); eventId = resultBody.get("result").getAsJsonObject().get("id").getAsString(); } // now we test again if the new event is created by using the get method { URL methodURL =new URL(baseUrl,"events/"+eventId); JsonObject resultBody = connector.sendGet( methodURL, authenticationToken); printAttributesAndAssertName(resultBody, objectName); } } // now we query a list of events { // we can use startDate without time String start= URLEncoder.encode("2000-01-01","UTF-8"); // or with time information. String end= URLEncoder.encode("2020-01-01T10:00Z","UTF-8"); String resources = URLEncoder.encode("['"+ resourceId +"']","UTF-8"); String eventTypes = URLEncoder.encode("['"+ eventType +"']","UTF-8"); String attributeFilter = URLEncoder.encode("{'name' :'"+ eventName +"'}","UTF-8"); URL methodURL =new URL(baseUrl,"events?start="+start + "&end="+end + "&resources="+resources +"&eventTypes=" + eventTypes +"&attributeFilter="+attributeFilter) ; JsonObject resultBody = connector.sendGet( methodURL, authenticationToken); assertNoError(resultBody); JsonArray resultList = resultBody.get("result").getAsJsonArray(); assertTrue( resultList.size() > 0); for (JsonElement obj:resultList) { JsonObject casted = (JsonObject) obj; String id = casted.get("id").getAsString(); JsonObject classification = casted.get("classification").getAsJsonObject().get("data").getAsJsonObject(); String name = classification.get("name").getAsJsonArray().get(0).getAsString(); System.out.println("[" +id + "]" + name); } } // we test a patch { String newReservationName ="changed event name"; Map<String,String> keyValue = new LinkedHashMap<String,String>(); keyValue.put( "name", newReservationName); JsonObject patchObject = new JsonObject(); JsonObject classificationObj = new JsonObject(); patchClassification(keyValue, classificationObj); patchObject.add("classification", classificationObj); // you can also use the string syntax and parse to get the patch object //String patchString ="{'classification': { 'data': {'"+ key + "' : ['"+value+"'] } } }"; //JsonObject callObj = new JsonParser().parse(patchString).getAsJsonObject(); URL methodURL =new URL(baseUrl, "events/"+eventId); { JsonObject resultBody = connector.sendPatch( methodURL, patchObject, authenticationToken); // we test if the new event is in the patched result printAttributesAndAssertName(resultBody, newReservationName); } // now we test again if the new event has the new name by using the get method { JsonObject resultBody = connector.sendGet( methodURL, authenticationToken); printAttributesAndAssertName(resultBody, newReservationName); } } } private JsonObject createAppointment(String start, String end) { JsonObject app = new JsonObject(); app.add("start", new JsonPrimitive(start)); app.add("end", new JsonPrimitive(end)); return app; } public void patchClassification(Map<String, String> keyValue, JsonObject classificationObj) { JsonObject data = new JsonObject(); classificationObj.add("data", data); for (Map.Entry<String, String> entry:keyValue.entrySet()) { JsonArray jsonArray = new JsonArray(); jsonArray.add( new JsonPrimitive(entry.getValue())); data.add(entry.getKey(), jsonArray); } } private void printAttributesAndAssertName(JsonObject resultBody, String objectName) { assertNoError(resultBody); JsonObject event = resultBody.get("result").getAsJsonObject(); JsonObject classification = event.get("classification").getAsJsonObject().get("data").getAsJsonObject(); System.out.println("Attributes for object id"); for (Entry<String, JsonElement> entry:classification.entrySet()) { String key =entry.getKey(); JsonArray value= entry.getValue().getAsJsonArray(); System.out.println(" " + key + "=" + value.toString()); if ( key.equals("name")) { assertEquals(objectName, value.get(0).getAsString()); } } } public void assertNoError(JsonObject resultBody) { JsonElement error = resultBody.get("error"); if (error!= null) { System.err.println(error); assertTrue( error == null ); } } public static void main(String[] args) { try { // The base url points to the rapla servlet not the webcontext. // If your rapla context is not running under root webappcontext you need to add the context path. // Example if you deploy the rapla.war in tomcat the default would be // http://host:8051/rapla/rapla/ URL baseUrl = new URL("http://localhost:8051/rapla/"); String username = "admin"; String password = ""; new RestAPIExample().testRestApi(baseUrl, username, password); } catch (Exception e) { e.printStackTrace(); } } }
04900db4-rob
test-src/org/rapla/rest/client/RestAPIExample.java
Java
gpl3
13,951
/*--------------------------------------------------------------------------* | 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.xmlbundle.tests; import java.util.Locale; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.components.xmlbundle.LocaleSelector; import org.rapla.components.xmlbundle.impl.I18nBundleImpl; import org.rapla.components.xmlbundle.impl.LocaleSelectorImpl; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.RaplaDefaultContext; import org.rapla.framework.logger.ConsoleLogger; import org.rapla.framework.logger.Logger; public class I18nBundleImplTest extends AbstractI18nTest { I18nBundleImpl i18n; boolean useFile; LocaleSelector localeSelector; Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_WARN); public I18nBundleImplTest(String name) { this(name, true); } public I18nBundleImplTest(String name,boolean useFile) { super(name); this.useFile = useFile; } protected void setUp() throws Exception { DefaultConfiguration config = new DefaultConfiguration("i18n"); if (this.useFile) { DefaultConfiguration child = new DefaultConfiguration("file"); child.setValue("src/org/rapla/RaplaResources.xml"); config.addChild(child); } else { config.setAttribute("id","org.rapla.RaplaResources"); } i18n = create(config); } private I18nBundleImpl create(Configuration config) throws Exception { I18nBundleImpl i18n; RaplaDefaultContext context = new RaplaDefaultContext(); localeSelector = new LocaleSelectorImpl(); context.put(LocaleSelector.class,localeSelector); i18n = new I18nBundleImpl(context,config,new ConsoleLogger()); return i18n; } protected void tearDown() { i18n.dispose(); } public I18nBundle getI18n() { return i18n; } public static Test suite() { TestSuite suite = new TestSuite(); // The first four test only succeed if the Resource Bundles are build. suite.addTest(new I18nBundleImplTest("testLocaleChanged",false)); suite.addTest(new I18nBundleImplTest("testGetIcon",false)); suite.addTest(new I18nBundleImplTest("testGetString",false)); suite.addTest(new I18nBundleImplTest("testLocale",false)); /* */ suite.addTest(new I18nBundleImplTest("testInvalidConfig",true)); suite.addTest(new I18nBundleImplTest("testLocaleChanged",true)); suite.addTest(new I18nBundleImplTest("testGetIcon",true)); suite.addTest(new I18nBundleImplTest("testGetString",true)); suite.addTest(new I18nBundleImplTest("testLocale",true)); return suite; } public void testLocaleChanged() { localeSelector.setLocale(new Locale("de","DE")); assertEquals(getI18n().getString("cancel"),"Abbrechen"); localeSelector.setLocale(new Locale("en","DE")); assertEquals(getI18n().getString("cancel"),"Cancel"); } public void testInvalidConfig() throws Exception { if (!this.useFile) return; DefaultConfiguration config = new DefaultConfiguration("i18n"); try { create(config); assertTrue("id is missing should be reported", true); } catch (Exception ex) { } config.setAttribute("id","org.rapla.RaplaResources"); DefaultConfiguration child = new DefaultConfiguration("file"); child.setValue("./src/org/rapla/RaplaResou"); config.addChild( child ); try { create(config); assertTrue("file ./src/org/rapla/RaplaResou should fail", true); } catch (Exception ex) { } } }
04900db4-rob
test-src/org/rapla/components/xmlbundle/tests/I18nBundleImplTest.java
Java
gpl3
4,729
/*--------------------------------------------------------------------------* | 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.xmlbundle.tests; import java.util.MissingResourceException; import javax.swing.Icon; import junit.framework.TestCase; import org.rapla.components.xmlbundle.I18nBundle; public abstract class AbstractI18nTest extends TestCase { abstract public I18nBundle getI18n(); public AbstractI18nTest(String name) { super(name); } public void testGetIcon() { Icon icon = getI18n().getIcon("icon.question"); assertNotNull("returned icon is null",icon); boolean failed = false; try { icon = getI18n().getIcon("this_icon_request_should_fail"); } catch (MissingResourceException ex) { failed = true; } assertTrue( "Request for 'this_icon_request_should_fail' should throw MissingResourceException" ,failed ); } public void testGetString() { String string = getI18n().getString("cancel"); if (getI18n().getLocale().getLanguage().equals("de")) assertEquals(string,"Abbrechen"); if (getI18n().getLocale().getLanguage().equals("en")) assertEquals(string,"cancel"); boolean failed = false; try { string = getI18n().getString("this_string_request_should_fail."); } catch (MissingResourceException ex) { failed = true; } assertTrue( "Request for 'this_string_request_should_fail should throw MissingResourceException" ,failed ); } public void testLocale() { assertNotNull(getI18n().getLocale()); assertNotNull(getI18n().getLang()); } public void testXHTML() { assertTrue( "<br/> should be replaced with <br>" ,getI18n().getString("error.invalid_key").indexOf("<br>")>=0 ); } }
04900db4-rob
test-src/org/rapla/components/xmlbundle/tests/AbstractI18nTest.java
Java
gpl3
2,712
package org.rapla.components.mail; import junit.framework.TestCase; import org.rapla.framework.RaplaException; import org.rapla.plugin.mail.server.MailapiClient; public class MailTest extends TestCase { public void testMailSend() throws RaplaException { MailapiClient client = new MailapiClient(); client.setSmtpHost("localhost"); client.setPort( 5023); MockMailServer mailServer = new MockMailServer(); mailServer.setPort( 5023); mailServer.startMailer( true); String sender = "sender@raplatestserver.univers"; String recipient = "reciever@raplatestserver.univers"; client.sendMail(sender,recipient,"HALLO", "Test body"); assertEquals( sender.trim().toLowerCase(), mailServer.getSenderMail().trim().toLowerCase()); assertEquals( recipient.trim().toLowerCase(), mailServer.getRecipient().trim().toLowerCase()); } }
04900db4-rob
test-src/org/rapla/components/mail/MailTest.java
Java
gpl3
941
package org.rapla.components.mail; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; public class MockMailServer { String senderMail; String recipient; int port = 25; public int getPort() { return port; } public void setPort( int port ) { this.port = port; } public static void main(String[] args) { new MockMailServer().startMailer(false); } public void startMailer(boolean deamon) { Thread serverThread = new Thread() { public void run() { ServerSocket socket = null; try { socket = new ServerSocket(port); System.out.println("MockMail server started and listening on port " + port); Socket smtpSocket = socket.accept(); smtpSocket.setKeepAlive(true); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(smtpSocket.getOutputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(smtpSocket.getInputStream())); writer.write("220\n"); writer.flush(); String helloString = reader.readLine(); System.out.println( helloString ); writer.write("250\n"); writer.flush(); String readLine = reader.readLine(); senderMail = readLine.substring("MAIL FROM:".length()); senderMail = senderMail.replaceAll("<","").replaceAll(">", ""); System.out.println( senderMail ); writer.write("250\n"); writer.flush(); String readLine2 = reader.readLine(); recipient = readLine2.substring("RCPT TO:".length()); recipient = recipient.replaceAll("<","").replaceAll(">", ""); System.out.println( recipient ); writer.write("250\n"); writer.flush(); String dataHeader = reader.readLine(); System.out.println( dataHeader ); writer.write("354\n"); writer.flush(); String line; do { line = reader.readLine(); System.out.println( line ); } while ( line.length() == 1 && line.charAt( 0) == 46); reader.readLine(); writer.write("250\n"); writer.flush(); String quit = reader.readLine(); System.out.println( quit ); writer.write("221\n"); writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if ( socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }; serverThread.setDaemon( deamon); serverThread.start(); } public String getRecipient() { return recipient; } public String getSenderMail() { return senderMail; } }
04900db4-rob
test-src/org/rapla/components/mail/MockMailServer.java
Java
gpl3
3,879
/*--------------------------------------------------------------------------* | 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.calendar; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.WindowEvent; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JTextField; /** Test class for RaplaCalendar and RaplaTime */ public final class RaplaCalendarExample { /** TextField for displaying the selected date, time*/ private JTextField textField = new JTextField( 20 ); private JTabbedPane tabbedPane = new JTabbedPane(); /** Listener for all {@link DateChangeEvent}s. */ DateChangeListener listener; JFrame frame; /** Stores all the raplaCalendar objects */ ArrayList<RaplaCalendar> raplaCalendars = new ArrayList<RaplaCalendar>(); /** Stores all the raplaTimes objects */ ArrayList<RaplaTime> raplaTimes = new ArrayList<RaplaTime>(); public RaplaCalendarExample() { frame = new JFrame( "Calendar test" ) { private static final long serialVersionUID = 1L; protected void processWindowEvent( WindowEvent e ) { if ( e.getID() == WindowEvent.WINDOW_CLOSING ) { dispose(); System.exit( 0 ); } else { super.processWindowEvent( e ); } } }; frame.setSize( 550, 450 ); JPanel testContainer = new JPanel(); testContainer.setLayout( new BorderLayout() ); frame.getContentPane().add( testContainer ); testContainer.add( tabbedPane, BorderLayout.CENTER ); testContainer.add( textField, BorderLayout.SOUTH ); listener = new DateChangeListener() { boolean listenerEnabled = true; public void dateChanged( DateChangeEvent evt ) { // find matching RaplaTime and RaplaCalendar int index = raplaCalendars.indexOf( evt.getSource() ); if ( index < 0 ) index = raplaTimes.indexOf( evt.getSource() ); Date date = ( raplaCalendars.get( index ) ).getDate(); Date time = ( raplaTimes.get( index ) ).getTime(); TimeZone timeZone = ( raplaCalendars.get( index ) ).getTimeZone(); Date dateTime = toDateTime( date, time, timeZone ); DateFormat format = DateFormat.getDateTimeInstance(); format.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); textField.setText( "GMT Time: " + format.format( dateTime ) ); // Update the other calendars // Disable listeners during update of all raplacalendars and raplatimes if ( !listenerEnabled ) return; listenerEnabled = false; try { for ( int i = 0; i < raplaCalendars.size(); i++ ) { if ( i == index ) continue; ( raplaCalendars.get( i ) ).setDate( dateTime ); ( raplaTimes.get( i ) ).setTime( dateTime ); } } finally { listenerEnabled = true; } } }; addDefault(); addDESmall(); addUSMedium(); addRULarge(); } /** Uses the first date parameter for year, month, date information and the second for hour, minutes, second, millisecond information.*/ private Date toDateTime( Date date, Date time, TimeZone timeZone ) { Calendar cal1 = Calendar.getInstance( timeZone ); Calendar cal2 = Calendar.getInstance( timeZone ); cal1.setTime( date ); cal2.setTime( time ); cal1.set( Calendar.HOUR_OF_DAY, cal2.get( Calendar.HOUR_OF_DAY ) ); cal1.set( Calendar.MINUTE, cal2.get( Calendar.MINUTE ) ); cal1.set( Calendar.SECOND, cal2.get( Calendar.SECOND ) ); cal1.set( Calendar.MILLISECOND, cal2.get( Calendar.MILLISECOND ) ); return cal1.getTime(); } public void start() { frame.setVisible( true ); } public void addDefault() { RaplaCalendar testCalendar = new RaplaCalendar(); RaplaTime timeField = new RaplaTime(); RaplaNumber numberField = new RaplaNumber( new Long( 0 ), new Long( 0 ), new Long( 60 ), false ); testCalendar.addDateChangeListener( listener ); timeField.addDateChangeListener( listener ); JPanel testPanel = new JPanel(); testPanel.setLayout( new FlowLayout() ); testPanel.add( testCalendar ); testPanel.add( timeField ); testPanel.add( numberField ); tabbedPane.addTab( "default '" + TimeZone.getDefault().getDisplayName() + "'", testPanel ); raplaTimes.add( timeField ); raplaCalendars.add( testCalendar ); } public void addDESmall() { Locale locale = Locale.GERMANY; TimeZone timeZone = TimeZone.getTimeZone( "Europe/Berlin" ); RaplaCalendar testCalendar = new RaplaCalendar( locale, timeZone ); RaplaTime timeField = new RaplaTime( locale, timeZone ); RaplaNumber numberField = new RaplaNumber( new Long( 0 ), new Long( 0 ), new Long( 60 ), false ); Font font = new Font( "SansSerif", Font.PLAIN, 9 ); testCalendar.setFont( font ); // We want to highlight the 3. of october "Tag der deutschen Einheit". testCalendar.setDateRenderer( new WeekendHighlightRenderer() { public RenderingInfo getRenderingInfo( int dayOfWeek, int day, int month, int year ) { if ( day == 3 && month == Calendar.OCTOBER ) return new RenderingInfo(Color.green, null,"Tag der deutschen Einheit") ; return super.getRenderingInfo( dayOfWeek, day, month, year ); } } ); testCalendar.addDateChangeListener( listener ); timeField.setFont( font ); timeField.addDateChangeListener( listener ); numberField.setFont( font ); JPanel testPanel = new JPanel(); testPanel.setLayout( new FlowLayout() ); testPanel.add( testCalendar ); testPanel.add( timeField ); testPanel.add( numberField ); tabbedPane.addTab( "DE 'Europe/Berlin'", testPanel ); raplaTimes.add( timeField ); raplaCalendars.add( testCalendar ); } public void addUSMedium() { Locale locale = Locale.US; TimeZone timeZone = TimeZone.getTimeZone( "GMT+8" ); RaplaCalendar testCalendar = new RaplaCalendar( locale, timeZone ); RaplaTime timeField = new RaplaTime( locale, timeZone ); RaplaNumber numberField = new RaplaNumber( new Long( 0 ), new Long( 0 ), new Long( 60 ), false ); Font font = new Font( "Serif", Font.PLAIN, 18 ); testCalendar.setFont( font ); // We want to highlight the 4. of july "Independence Day". testCalendar.setDateRenderer( new WeekendHighlightRenderer() { public RenderingInfo getRenderingInfo( int dayOfWeek, int day, int month, int year ) { if ( day == 4 && month == Calendar.JULY ) return new RenderingInfo(Color.red, null,"Independence Day") ; return super.getRenderingInfo( dayOfWeek, day, month, year ); } } ); testCalendar.addDateChangeListener( listener ); numberField.setFont( font ); timeField.setFont( font ); timeField.addDateChangeListener( listener ); JPanel testPanel = new JPanel(); testPanel.setLayout( new FlowLayout() ); testPanel.add( testCalendar ); testPanel.add( timeField ); testPanel.add( numberField ); tabbedPane.addTab( "US 'GMT+8'", testPanel ); raplaTimes.add( timeField ); raplaCalendars.add( testCalendar ); } public void addRULarge() { Locale locale = new Locale( "ru", "RU" ); TimeZone timeZone = TimeZone.getTimeZone( "GMT-6" ); RaplaCalendar testCalendar = new RaplaCalendar( locale, timeZone, false ); RaplaTime timeField = new RaplaTime( locale, timeZone ); Font font = new Font( "Arial", Font.BOLD, 26 ); testCalendar.setFont( font ); // Only highlight sunday. WeekendHighlightRenderer renderer = new WeekendHighlightRenderer(); renderer.setHighlight( Calendar.SATURDAY, false ); testCalendar.setDateRenderer( renderer ); testCalendar.addDateChangeListener( listener ); timeField.setFont( font ); timeField.addDateChangeListener( listener ); JPanel testPanel = new JPanel(); testPanel.setLayout( new FlowLayout() ); testPanel.add( testCalendar.getPopupComponent() ); testPanel.add( timeField ); tabbedPane.addTab( "RU 'GMT-6'", testPanel ); raplaTimes.add( timeField ); raplaCalendars.add( testCalendar ); } public static void main( String[] args ) { try { System.out.println( "Testing RaplaCalendar" ); RaplaCalendarExample example = new RaplaCalendarExample(); example.start(); } catch ( Exception e ) { e.printStackTrace(); System.exit( 1 ); } } }
04900db4-rob
test-src/org/rapla/components/calendar/RaplaCalendarExample.java
Java
gpl3
10,690
package org.rapla.components.calendar; import java.awt.BorderLayout; import java.awt.event.WindowEvent; import java.util.Locale; import javax.swing.JFrame; import javax.swing.JPanel; public class TimeFieldChinaExample { JFrame frame; public TimeFieldChinaExample() { frame = new JFrame( "Calendar test" ) { private static final long serialVersionUID = 1L; protected void processWindowEvent( WindowEvent e ) { if ( e.getID() == WindowEvent.WINDOW_CLOSING ) { dispose(); System.exit( 0 ); } else { super.processWindowEvent( e ); } } }; frame.setSize( 150, 80 ); JPanel testContainer = new JPanel(); testContainer.setLayout( new BorderLayout() ); frame.getContentPane().add( testContainer ); RaplaTime timeField = new RaplaTime(); testContainer.add( timeField, BorderLayout.CENTER ); } public void start() { frame.setVisible( true ); } public static void main( String[] args ) { try { Locale locale = Locale.CHINA ; Locale.setDefault( locale ); System.out.println( "Testing TimeField in locale " + locale ); TimeFieldChinaExample example = new TimeFieldChinaExample(); example.start(); } catch ( Exception e ) { e.printStackTrace(); System.exit( 1 ); } } }
04900db4-rob
test-src/org/rapla/components/calendar/TimeFieldChinaExample.java
Java
gpl3
1,655
package org.rapla.components.iolayer; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.io.FileOutputStream; import java.io.IOException; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTable.PrintMode; import javax.swing.table.DefaultTableModel; import org.rapla.RaplaTestCase; public class ITextPrinterTest extends RaplaTestCase { public ITextPrinterTest(String name) { super(name); } public void test() throws Exception { // Table Tester JTable table = new JTable(); int size = 50; DefaultTableModel model = new DefaultTableModel(size+1,1); table.setModel( model ); for ( int i = 0;i<size;i++) { table.getModel().setValueAt("Test " + i, i, 0); } JFrame test = new JFrame(); test.add( new JScrollPane(table)); test.setSize(400, 300); test.setVisible(true); Printable printable = table.getPrintable(PrintMode.NORMAL, null, null); FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream(TEST_FOLDER_NAME +"/my_jtable_fonts.pdf"); PageFormat format = new PageFormat(); ITextPrinter.createPdf( printable, fileOutputStream, format); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } test.setVisible( false); } }
04900db4-rob
test-src/org/rapla/components/iolayer/ITextPrinterTest.java
Java
gpl3
1,540
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to 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.calendarview; import java.util.Calendar; import java.util.Locale; import junit.framework.TestCase; public class WeekdayMapperTest extends TestCase { String[] weekdayNames; int[] weekday2index; int[] index2weekday; public WeekdayMapperTest(String methodName) { super( methodName ); } public void testLocaleGermany() { WeekdayMapper mapper = new WeekdayMapper(Locale.GERMANY); assertEquals(6,mapper.indexForDay(Calendar.SUNDAY)); assertEquals(0,mapper.indexForDay(Calendar.MONDAY)); assertEquals(Calendar.SUNDAY,mapper.dayForIndex(6)); assertEquals(Calendar.MONDAY,mapper.dayForIndex(0)); assertEquals("Montag", mapper.getName(Calendar.MONDAY)); } public void testLocaleUS() { WeekdayMapper mapper = new WeekdayMapper(Locale.US); assertEquals(0,mapper.indexForDay(Calendar.SUNDAY)); assertEquals(1,mapper.indexForDay(Calendar.MONDAY)); assertEquals(Calendar.MONDAY,mapper.dayForIndex(1)); assertEquals("Monday", mapper.getName(Calendar.MONDAY)); } }
04900db4-rob
test-src/org/rapla/components/calendarview/WeekdayMapperTest.java
Java
gpl3
2,067
/*--------------------------------------------------------------------------* | 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.calendarview; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Point; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.rapla.components.calendarview.swing.SwingBlock; import org.rapla.components.calendarview.swing.SwingMonthView; import org.rapla.components.calendarview.swing.SwingWeekView; import org.rapla.components.calendarview.swing.ViewListener; /** Test class for RaplaCalendar and RaplaTime */ public final class RaplaCalendarViewExample { private JTabbedPane tabbedPane = new JTabbedPane(); JFrame frame; private List<MyAppointment> appointments = new ArrayList<MyAppointment>(); public RaplaCalendarViewExample() { frame = new JFrame("Calendar test") { private static final long serialVersionUID = 1L; protected void processWindowEvent(WindowEvent e) { if (e.getID() == WindowEvent.WINDOW_CLOSING) { dispose(); System.exit(0); } else { super.processWindowEvent(e); } } }; frame.setSize(700,550); JPanel testContainer = new JPanel(); testContainer.setLayout(new BorderLayout()); frame.getContentPane().add(testContainer); testContainer.add(tabbedPane,BorderLayout.CENTER); initAppointments(); addWeekview(); addDayview(); addMonthview(); } void initAppointments( ) { Calendar cal = Calendar.getInstance(); // the first appointment cal.setTime( new Date()); cal.set( Calendar.HOUR_OF_DAY, 12); cal.set( Calendar.MINUTE, 0); cal.set( Calendar.DAY_OF_WEEK, Calendar.MONDAY); Date start = cal.getTime(); cal.set( Calendar.HOUR_OF_DAY, 14); Date end = cal.getTime(); appointments.add( new MyAppointment( start, end, "TEST" )); // the second appointment cal.set( Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY); cal.set( Calendar.HOUR_OF_DAY, 13); Date start2 = cal.getTime(); cal.set( Calendar.HOUR_OF_DAY, 15); Date end2 = cal.getTime(); appointments.add( new MyAppointment( start2, end2, "TEST2" )); } public void addWeekview() { final SwingWeekView wv = new SwingWeekView(); tabbedPane.addTab("Weekview", wv.getComponent()); Date today = new Date(); // set to German locale wv.setLocale( Locale.GERMANY); // we exclude Saturday and Sunday List<Integer> excludeDays = new ArrayList<Integer>(); excludeDays.add( new Integer(1)); excludeDays.add( new Integer(7)); wv.setExcludeDays( excludeDays ); // Worktime is from 9 to 17 wv.setWorktime( 9, 17); // 1 row for 15 minutes wv.setRowsPerHour( 4 ); // Set the size of a row to 15 pixel wv.setRowSize( 15 ); // set weekview date to Today wv.setToDate( today ); // create blocks for today wv.addBuilder( new MyBuilder( appointments ) ); wv.rebuild(); // Now we scroll to the first workhour wv.scrollToStart(); wv.addCalendarViewListener( new MyCalendarListener(wv) ); tabbedPane.addChangeListener( new ChangeListener() { public void stateChanged(ChangeEvent arg0) { wv.rebuild(); } }); } public void addDayview() { final SwingWeekView dv = new SwingWeekView(); tabbedPane.addTab("Dayview", dv.getComponent()); // set to German locale dv.setLocale( Locale.GERMANY); dv.setSlotSize( 300 ); // we exclude everyday except the monday of the current week Set<Integer> excludeDays = new HashSet<Integer>(); Calendar cal = Calendar.getInstance(); cal.setTime ( new Date()); cal.set( Calendar.DAY_OF_WEEK, Calendar.MONDAY); Date mondayOfWeek = cal.getTime(); for (int i=0;i<8;i++) { if ( i != cal.get( Calendar.DAY_OF_WEEK)) { excludeDays.add( new Integer(i)); } } dv.setExcludeDays( excludeDays ); // Worktime is from 9 to 17 dv.setWorktime( 9, 17); // 1 row for 15 minutes dv.setRowsPerHour( 4 ); // Set the size of a row to 15 pixel dv.setRowSize( 15 ); // set weekview date to monday dv.setToDate( mondayOfWeek ) ; // create blocks for today dv.addBuilder( new MyBuilder( appointments ) ); dv.rebuild(); // Now we scroll to the first workhour dv.scrollToStart(); dv.addCalendarViewListener( new MyCalendarListener(dv) ); tabbedPane.addChangeListener( new ChangeListener() { public void stateChanged(ChangeEvent arg0) { dv.rebuild(); } }); } public void addMonthview() { final SwingMonthView mv = new SwingMonthView(); tabbedPane.addTab("Monthview", mv.getComponent()); Date today = new Date(); // set to German locale mv.setLocale( Locale.GERMANY); // we exclude Saturday and Sunday List<Integer> excludeDays = new ArrayList<Integer>(); excludeDays.add( new Integer(1)); excludeDays.add( new Integer(7)); mv.setExcludeDays( excludeDays ); // set weekview date to Today mv.setToDate( today ); // create blocks for today mv.addBuilder( new MyBuilder( appointments ) ); mv.rebuild(); mv.addCalendarViewListener( new MyMonthCalendarListener(mv) ); tabbedPane.addChangeListener( new ChangeListener() { public void stateChanged(ChangeEvent arg0) { mv.rebuild(); } }); } public class MyAppointment { Date start; Date end; String label; public MyAppointment(Date start, Date end, String label) { this.start = start; this.end = end; this.label = label; } public void move(Date newStart) { long diff = end.getTime() - start.getTime(); start = new Date(newStart.getTime()); end = new Date( newStart.getTime() + diff); } public void resize(Date newStart, Date newEnd) { if ( newStart != null ) { this.start = newStart; } if ( newEnd != null ) { this.end = newEnd; } } public Date getStart() { return start; } public Date getEnd() { return end; } public String getLabel() { return label; } } static class MyBuilder implements Builder { final AbstractGroupStrategy strategy; List<Block> blocks; List<MyAppointment> appointments; boolean enable = true; MyBuilder(List<MyAppointment> appointments) { this.appointments = appointments; strategy = new BestFitStrategy(); strategy.setResolveConflictsEnabled( true ); } public void prepareBuild(Date startDate, Date endDate) { blocks = new ArrayList<Block>(); for ( Iterator<MyAppointment> it = appointments.iterator(); it.hasNext(); ) { MyAppointment appointment = it.next(); if ( !appointment.getStart().before( startDate) && !appointment.getEnd().after( endDate )) { blocks.add( new MyBlock( appointment )); } } } public int getMaxMinutes() { return 24*60; } public int getMinMinutes() { return 0; } public void build(CalendarView cv) { strategy.build( cv, blocks); } public void setEnabled(boolean enable) { this.enable = enable; } public boolean isEnabled() { return enable; } } static class MyBlock implements SwingBlock { JLabel myBlockComponent; MyAppointment appointment; public MyBlock(MyAppointment appointment) { this.appointment = appointment; myBlockComponent = new JLabel(); myBlockComponent.setText( appointment.getLabel() ); myBlockComponent.setBorder( BorderFactory.createLineBorder( Color.BLACK)); myBlockComponent.setBackground( Color.LIGHT_GRAY); myBlockComponent.setOpaque( true ); } public Date getStart() { return appointment.getStart(); } public Date getEnd() { return appointment.getEnd(); } public MyAppointment getAppointment() { return appointment; } public Component getView() { return myBlockComponent; } public void paintDragging(Graphics g, int width, int height) { // If you comment out the following line, dragging displays correctly in month view myBlockComponent.setSize( width, height -1); myBlockComponent.paint( g ); } public boolean isMovable() { return true; } public boolean isStartResizable() { return false; } public boolean isEndResizable() { return true; } public String getName() { return appointment.getLabel(); } } static class MyCalendarListener implements ViewListener { CalendarView view; public MyCalendarListener(CalendarView view) { this.view = view; } public void selectionPopup(Component slotComponent, Point p, Date start, Date end, int slotNr) { System.out.println("Selection Popup in slot " + slotNr); } public void selectionChanged(Date start, Date end) { System.out.println("Selection change " + start + " - " + end ); } public void blockPopup(Block block, Point p) { System.out.println("Block right click "); } public void blockEdit(Block block, Point p) { System.out.println("Block double click"); } public void moved(Block block, Point p, Date newStart, int slotNr) { MyAppointment appointment = ((MyBlock) block).getAppointment(); appointment.move( newStart); System.out.println("Block moved"); view.rebuild(); } public void resized(Block block, Point p, Date newStart, Date newEnd, int slotNr) { MyAppointment appointment = ((MyBlock) block).getAppointment(); appointment.resize( newStart, newEnd); System.out.println("Block resized"); view.rebuild(); } } static class MyMonthCalendarListener extends MyCalendarListener { public MyMonthCalendarListener(CalendarView view) { super(view); } @Override public void moved(Block block, Point p, Date newStart, int slotNr) { MyAppointment appointment = ((MyBlock) block).getAppointment(); Calendar cal = Calendar.getInstance(); cal.setTime( appointment.getStart() ); int hour = cal.get( Calendar.HOUR_OF_DAY); int minute = cal.get( Calendar.MINUTE); cal.setTime( newStart ); cal.set( Calendar.HOUR_OF_DAY, hour); cal.set( Calendar.MINUTE, minute); appointment.move( cal.getTime()); System.out.println("Block moved to " + cal.getTime()); view.rebuild(); } } public static void main(String[] args) { try { System.out.println("Testing RaplaCalendarView"); RaplaCalendarViewExample example = new RaplaCalendarViewExample(); example.frame.setVisible( true); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
04900db4-rob
test-src/org/rapla/components/calendarview/RaplaCalendarViewExample.java
Java
gpl3
13,752
/*--------------------------------------------------------------------------* | 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.util.ArrayList; import java.util.Iterator; import java.util.List; import junit.framework.TestCase; import org.rapla.components.util.iterator.FilterIterator; public class FilterIteratorTest extends TestCase { public FilterIteratorTest(String name) { super(name); } public void testIterator() { List<Integer> list = new ArrayList<Integer>(); for (int i=0;i<6;i++) { list.add( new Integer(i)); } Iterator<Integer> it = new FilterIterator<Integer>(list) { protected boolean isInIterator( Object obj ) { return ((Integer) obj).intValue() % 2 ==0; } }; for (int i=0;i<6;i++) { if ( i % 2 == 0) assertEquals( new Integer(i), it.next()); } assertTrue( it.hasNext() == false); } }
04900db4-rob
test-src/org/rapla/components/util/FilterIteratorTest.java
Java
gpl3
1,847
package org.rapla.components.util; import java.util.Date; import junit.framework.TestCase; import org.rapla.components.util.DateTools.DateWithoutTimezone; import org.rapla.entities.tests.Day; public class DateToolsTest extends TestCase { public DateToolsTest(String name) { super( name); } public void testCutDate1() { Day day = new Day(2000,1,1); Date gmtDate = day.toGMTDate(); Date gmtDateOneHour = new Date(gmtDate.getTime() + DateTools.MILLISECONDS_PER_HOUR); assertEquals(DateTools.cutDate( gmtDateOneHour), gmtDate); } public void testJulianDayConverter() { Day day = new Day(2013,2,28); long raplaDate = DateTools.toDate(day.getYear(), day.getMonth(), day.getDate()); Date gmtDate = day.toGMTDate(); assertEquals(gmtDate, new Date(raplaDate)); DateWithoutTimezone date = DateTools.toDate(raplaDate); assertEquals( day.getYear(), date.year); assertEquals( day.getMonth(), date.month ); assertEquals( day.getDate(), date.day ); } public void testCutDate2() { Day day = new Day(1,1,1); Date gmtDate = day.toGMTDate(); Date gmtDateOneHour = new Date(gmtDate.getTime() + DateTools.MILLISECONDS_PER_HOUR); assertEquals(DateTools.cutDate( gmtDateOneHour), gmtDate); } }
04900db4-rob
test-src/org/rapla/components/util/DateToolsTest.java
Java
gpl3
1,374
package org.rapla.components.util; import junit.framework.TestCase; public class ToolsTest extends TestCase { public ToolsTest(String name) { super( name); } // public void testReplace() { // String newString = Tools.replaceAll("Helllo Worlld llll","ll","l" ); // assertEquals( "Hello World ll", newString); // } public void testSplit() { String[] result = Tools.split("a;b2;c",';'); assertEquals( "a", result[0]); assertEquals( "b2", result[1]); assertEquals( "c", result[2]); } }
04900db4-rob
test-src/org/rapla/components/util/ToolsTest.java
Java
gpl3
562
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; public class SunBugsTest extends TestCase { public SunBugsTest(String name) { super(name); } public void testCalendarBug1_4_2() { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"), Locale.US ); cal.set(Calendar.HOUR_OF_DAY,12); // This call causes the invalid result in the second get cal.getTime(); cal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY); //Exposes Bug in jdk1.4.2beta assertEquals("Bug exposed in jdk 1.4.2 beta",Calendar.MONDAY,cal.get(Calendar.DAY_OF_WEEK)); } /** this is not bug, but a undocumented feature. The exception should be thrown * in calendar.roll(Calendar.MONTH, 1) public void testCalendarBug1_5_0() { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"), Locale.GERMANY); calendar.setLenient( false ); calendar.setTime( new Date()); // calculate the number of days of the current month calendar.set(Calendar.MONTH,2); calendar.roll(Calendar.MONTH,+1); calendar.set(Calendar.DATE,1); calendar.roll(Calendar.DAY_OF_YEAR,-1); // this throws an InvalidArgumentException under 1.5.0 beta calendar.get(Calendar.DATE); } */ }
04900db4-rob
test-src/org/rapla/SunBugsTest.java
Java
gpl3
2,362
package org.rapla.server; import java.util.Date; import java.util.Locale; import org.rapla.ServletTestBase; import org.rapla.components.util.DateTools; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.facade.ClientFacade; import org.rapla.storage.RaplaSecurityException; public class SecurityManagerTest extends ServletTestBase { protected ClientFacade facade1; Locale locale; public SecurityManagerTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); // start the server getContainer().lookup(ServerServiceContainer.class, getStorageName()); // start the client service facade1 = getContainer().lookup(ClientFacade.class , "remote-facade"); locale = Locale.getDefault(); } protected String getStorageName() { return "storage-file"; } public void testConflictForbidden() throws Exception { // We test conflict prevention for an appointment that is in the future Date start = new Date(facade1.today().getTime() + DateTools.MILLISECONDS_PER_DAY + 10 * DateTools.MILLISECONDS_PER_HOUR); Date end = new Date( start.getTime() + 2 * DateTools.MILLISECONDS_PER_HOUR); facade1.login("homer", "duffs".toCharArray()); DynamicType roomType = facade1.getDynamicType("room"); ClassificationFilter filter = roomType.newClassificationFilter(); filter.addEqualsRule("name", "erwin"); Allocatable resource = facade1.getAllocatables( filter.toArray())[0]; Appointment app1; { app1 = facade1.newAppointment( start, end ) ; // First we create a reservation for the resource Reservation event = facade1.newReservation(); event.getClassification().setValue("name", "taken"); event.addAppointment( app1 ); event.addAllocatable( resource ); facade1.store( event ); } facade1.logout(); // Now we login as a non admin user, who isnt allowed to create conflicts on the resource erwin facade1.login("monty", "burns".toCharArray()); { Reservation event = facade1.newReservation(); // A new event with the same time for the same resource should fail. event.getClassification().setValue("name", "conflicting event"); Appointment app = facade1.newAppointment( start, end ) ; event.addAppointment( app); event.addAllocatable( resource ); try { facade1.store( event ); fail("Security Exception expected"); } catch ( Exception ex) { Throwable ex1 = ex; boolean secExceptionFound = false; while ( ex1 != null) { if ( ex1 instanceof RaplaSecurityException) { secExceptionFound = true; } ex1 = ex1.getCause(); } if ( !secExceptionFound) { ex.printStackTrace(); fail("Exception expected but was not security exception"); } } // moving the start of the second appointment to the end of the first one should work app.move( end ); facade1.store( event ); } { // We have to reget the event DynamicType eventType = facade1.getDynamicType("event"); ClassificationFilter eventFilter = eventType.newClassificationFilter(); eventFilter.addEqualsRule("name", "conflicting event"); Reservation event = facade1.getReservationsForAllocatable( null, null, null, eventFilter.toArray())[0]; // But moving back the appointment to today should fail event = facade1.edit( event ); Date startPlus1 = new Date( start.getTime() + DateTools.MILLISECONDS_PER_HOUR) ; event.getAppointments()[0].move( startPlus1,end); try { facade1.store( event ); fail("Security Exception expected"); } catch ( Exception ex) { Throwable ex1 = ex; boolean secExceptionFound = false; while ( ex1 != null) { if ( ex1 instanceof RaplaSecurityException) { secExceptionFound = true; } ex1 = ex1.getCause(); } if ( !secExceptionFound) { ex.printStackTrace(); fail("Exception expected but was not security exception"); } } facade1.logout(); Thread.sleep(100); } } }
04900db4-rob
test-src/org/rapla/server/SecurityManagerTest.java
Java
gpl3
4,205
package org.rapla.server; import org.rapla.RaplaTestCase; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.User; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; import org.rapla.server.RaplaKeyStorage.LoginInfo; import org.rapla.server.internal.RaplaKeyStorageImpl; public class RaplaKeyStorageTest extends RaplaTestCase { public RaplaKeyStorageTest(String name) { super(name); } public void testKeyStore() throws RaplaException { RaplaKeyStorageImpl storage = new RaplaKeyStorageImpl(getContext()); User user = getFacade().newUser(); user.setUsername("testuser"); getFacade().store( user); TypedComponentRole<String> tagName = new TypedComponentRole<String>("org.rapla.server.secret.test"); String login ="username"; String secret = "secret"; storage.storeLoginInfo(user, tagName, login, secret); { LoginInfo secrets = storage.getSecrets(user, tagName); assertEquals( login,secrets.login); assertEquals( secret,secrets.secret); } getFacade().remove( user); try { storage.getSecrets(user, tagName); fail("Should throw Entity not found exception"); } catch ( EntityNotFoundException ex) { } } }
04900db4-rob
test-src/org/rapla/server/RaplaKeyStorageTest.java
Java
gpl3
1,239
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; import java.util.Date; import java.util.Locale; import org.rapla.components.util.DateTools; import org.rapla.entities.Category; import org.rapla.entities.User; 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.dynamictype.ClassificationFilter; import org.rapla.facade.ClientFacade; import org.rapla.server.ServerServiceContainer; import org.rapla.storage.RaplaSecurityException; public class PermissionTest extends ServletTestBase { ClientFacade adminFacade; ClientFacade testFacade; Locale locale; public PermissionTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); // start the server getContainer().lookup(ServerServiceContainer.class, "storage-file"); // start the client service adminFacade = getContainer().lookup(ClientFacade.class , "remote-facade"); adminFacade.login("homer","duffs".toCharArray()); locale = Locale.getDefault(); try { Category userGroupsCategory = adminFacade.getUserGroupsCategory(); Category groups = adminFacade.edit( userGroupsCategory ); Category testGroup = adminFacade.newCategory(); testGroup.setKey("test-group"); groups.addCategory( testGroup ); adminFacade.store( groups ); { Category testGroup2 = adminFacade.getUserGroupsCategory().getCategory("test-group"); assertNotNull( testGroup2); } User user = adminFacade.newUser(); user.setUsername("test"); user.addGroup( testGroup ); adminFacade.store( user ); adminFacade.changePassword( user, new char[]{}, new char[] {}); } catch (Exception ex) { adminFacade.logout(); super.tearDown(); throw ex; } // Wait for update; testFacade = getContainer().lookup(ClientFacade.class , "remote-facade-2"); boolean canLogin = testFacade.login("test","".toCharArray()); assertTrue( "Can't login", canLogin ); } protected void tearDown() throws Exception { adminFacade.logout(); testFacade.logout(); super.tearDown(); } public void testReadPermissions() throws Exception { // first create a new resource and set the permissions Allocatable allocatable = adminFacade.newResource(); allocatable.getClassification().setValue("name","test-allocatable"); //remove default permission. allocatable.removePermission( allocatable.getPermissions()[0] ); Permission permission = allocatable.newPermission(); Category testGroup = adminFacade.getUserGroupsCategory().getCategory("test-group"); assertNotNull( testGroup); permission.setGroup ( testGroup ); permission.setAccessLevel( Permission.READ ); allocatable.addPermission( permission ); adminFacade.store( allocatable ); // Wait for update testFacade.refresh(); // test the permissions in the second facade. clientReadPermissions(); } public void testAllocatePermissions() throws Exception { // first create a new resource and set the permissions Allocatable allocatable = adminFacade.newResource(); allocatable.getClassification().setValue("name","test-allocatable"); //remove default permission. allocatable.removePermission( allocatable.getPermissions()[0] ); Permission permission = allocatable.newPermission(); Category testGroup = adminFacade.getUserGroupsCategory().getCategory("test-group"); permission.setGroup ( testGroup ); permission.setAccessLevel( Permission.ALLOCATE ); allocatable.addPermission( permission ); adminFacade.store( allocatable ); // Wait for update testFacade.refresh(); // test the permissions in the second facade. clientAllocatePermissions(); // Uncovers bug 1237332, ClassificationFilter filter = testFacade.getDynamicType("event").newClassificationFilter(); filter.addEqualsRule("name","R1"); Reservation evt = testFacade.getReservationsForAllocatable( null, null, null, new ClassificationFilter[] {filter} )[0]; evt = testFacade.edit( evt ); evt.removeAllocatable( allocatable ); testFacade.store( evt ); allocatable = adminFacade.edit( allocatable ); allocatable.getPermissions()[0].setAccessLevel( Permission.READ); adminFacade.store( allocatable ); testFacade.refresh(); evt = testFacade.edit( evt ); evt.addAllocatable( allocatable ); try { testFacade.store( evt ); fail("RaplaSecurityException expected!"); } catch (RaplaSecurityException ex) { // System.err.println ( ex.getMessage()); } Allocatable allocatable2 = adminFacade.newResource(); allocatable2.getClassification().setValue("name","test-allocatable2"); permission = allocatable.newPermission(); permission.setUser( testFacade.getUser()); permission.setAccessLevel( Permission.ADMIN); allocatable2.addPermission( permission ); adminFacade.store( allocatable2 ); testFacade.refresh(); evt.addAllocatable( allocatable2 ); try { testFacade.store( evt ); fail("RaplaSecurityException expected!"); } catch (RaplaSecurityException ex) { } Thread.sleep( 100); } private Allocatable getTestResource() throws Exception { Allocatable[] all = testFacade.getAllocatables(); for ( int i=0;i< all.length; i++ ){ if ( all[i].getName( locale ).equals("test-allocatable") ) { return all [i]; } } return null; } private void clientReadPermissions() throws Exception { User user = testFacade.getUser(); Allocatable a = getTestResource(); assertNotNull( a ); assertTrue( a.canRead( user ) ); assertTrue( !a.canModify( user ) ); assertTrue( !a.canCreateConflicts( user ) ); assertTrue( !a.canAllocate( user, null, null, testFacade.today())); } private void clientAllocatePermissions() throws Exception { Allocatable allocatable = getTestResource(); User user = testFacade.getUser(); assertNotNull( allocatable ); assertTrue( allocatable.canRead( user ) ); Date start1 = DateTools.addDay(testFacade.today()); Date end1 = new Date(start1.getTime() + DateTools.MILLISECONDS_PER_HOUR * 2); Date start2 = new Date(start1.getTime() + DateTools.MILLISECONDS_PER_HOUR * 1); Date end2 = new Date(start1.getTime() + DateTools.MILLISECONDS_PER_HOUR * 3); assertTrue( allocatable.canAllocate( user, null, null, testFacade.today() ) ); Reservation r1 = testFacade.newReservation(); r1.getClassification().setValue("name","R1"); Appointment a1 = testFacade.newAppointment( start1, end1 ); r1.addAppointment( a1 ); r1.addAllocatable( allocatable ); testFacade.store( r1 ); Reservation r2 = testFacade.newReservation(); r2.getClassification().setValue("name","R2"); Appointment a2 = testFacade.newAppointment( start2, end2 ); r2.addAppointment( a2 ); r2.addAllocatable( allocatable ); try { testFacade.store( r2 ); fail("RaplaSecurityException expected! Conflicts should be created"); } catch (RaplaSecurityException ex) { // System.err.println ( ex.getMessage()); } } }
04900db4-rob
test-src/org/rapla/PermissionTest.java
Java
gpl3
8,776
package org.rapla; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import ch.qos.logback.core.ConsoleAppender; @SuppressWarnings("restriction") public class RaplaTestLogManager { // TODO Make me test again List<String> messages = new ArrayList<String>(); static ThreadLocal<RaplaTestLogManager> localManager = new ThreadLocal<RaplaTestLogManager>(); public RaplaTestLogManager() { localManager.set( this); clearMessages(); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); List<Logger> loggerList = lc.getLoggerList(); Appender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>() { @Override protected void writeOut(ILoggingEvent event) throws IOException { super.writeOut(event); } @Override protected void append(ILoggingEvent eventObject) { super.append(eventObject); } }; for ( Logger logger:loggerList) { // System.out.println(logger.toString()); logger.addAppender( appender); } appender.setContext( lc); appender.start(); } public void clearMessages() { messages.clear(); } static public List<String> getErrorMessages() { return localManager.get().messages; } }
04900db4-rob
test-src/org/rapla/RaplaTestLogManager.java
Java
gpl3
1,541
/*--------------------------------------------------------------------------* | 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.tests; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.RaplaTestCase; import org.rapla.entities.Category; import org.rapla.entities.DependencyException; import org.rapla.entities.internal.CategoryImpl; import org.rapla.facade.ClientFacade; import org.rapla.facade.ModificationModule; import org.rapla.facade.QueryModule; import org.rapla.facade.UpdateModule; import org.rapla.framework.RaplaException; public class CategoryTest extends RaplaTestCase { CategoryImpl areas; ModificationModule modificationMod; QueryModule queryMod; UpdateModule updateMod; public CategoryTest(String name) { super(name); } public static Test suite() { return new TestSuite(CategoryTest.class); } protected void setUp() throws Exception { super.setUp(); ClientFacade facade = getFacade(); queryMod = facade; modificationMod = facade; updateMod = facade; areas = (CategoryImpl) modificationMod.newCategory(); areas.setKey("areas"); areas.getName().setName("en","areas"); Category area51 = modificationMod.newCategory(); area51.setKey("51"); area51.getName().setName("en","area 51"); Category buildingA = modificationMod.newCategory(); buildingA.setKey("A"); buildingA.getName().setName("en","building A"); Category floor1 = modificationMod.newCategory(); floor1.setKey("1"); floor1.getName().setName("en","floor 1"); buildingA.addCategory(floor1); area51.addCategory(buildingA); areas.addCategory(area51); } public void testStore2() throws Exception { Category superCategory = modificationMod.edit(queryMod.getSuperCategory()); superCategory.addCategory(areas); modificationMod.store(superCategory); assertTrue(areas.getId() != null); Category editObject = modificationMod.edit(superCategory); modificationMod.store(editObject); assertTrue("reference to subcategory has changed" ,areas == (CategoryImpl) superCategory.getCategory("areas") ); } public void testStore() throws Exception { Category superCategory =modificationMod.edit(queryMod.getSuperCategory()); superCategory.addCategory(areas); modificationMod.store(superCategory); assertTrue(areas.getId() != null); updateMod.refresh(); Category[] categories = queryMod.getSuperCategory().getCategories(); for (int i=0;i<categories.length;i++) if (categories[i].equals(areas)) return; assertTrue("category not stored!",false); } public void testStore3() throws Exception { Category superCategory = queryMod.getSuperCategory(); Category department = modificationMod.edit( superCategory.getCategory("department") ); Category school = department.getCategory("elementary-springfield"); try { department.removeCategory( school); modificationMod.store( department ); fail("No dependency exception thrown"); } catch (DependencyException ex) { } school = modificationMod.edit( superCategory.getCategory("department").getCategory("channel-6") ); modificationMod.store( school ); } public void testEditDeleted() throws Exception { Category superCategory = queryMod.getSuperCategory(); Category department = modificationMod.edit( superCategory.getCategory("department") ); Category subDepartment = department.getCategory("testdepartment"); department.removeCategory( subDepartment); modificationMod.store( department ); try { Category subDepartmentEdit = modificationMod.edit( subDepartment ); modificationMod.store( subDepartmentEdit ); fail( "store should throw an exception, when trying to edit a removed entity "); } catch ( RaplaException ex) { } } public void testGetParent() { Category area51 = areas.getCategory("51"); Category buildingA = area51.getCategory("A"); Category floor1 = buildingA.getCategories()[0]; assertEquals(areas, area51.getParent()); assertEquals(area51, buildingA.getParent()); assertEquals(buildingA, floor1.getParent()); } @SuppressWarnings("null") public void testPath() throws Exception { String path = "category[key='51']/category[key='A']/category[key='1']"; Category sub =areas.getCategoryFromPath(path); assertTrue(sub != null); assertTrue(sub.getName().getName("en").equals("floor 1")); String path2 = areas.getPathForCategory(sub); // System.out.println(path2); assertEquals(path, path2); } public void testAncestorOf() throws Exception { String path = "category[key='51']/category[key='A']/category[key='1']"; Category sub =areas.getCategoryFromPath(path); assertTrue(areas.isAncestorOf(sub)); assertTrue(!sub.isAncestorOf(areas)); } }
04900db4-rob
test-src/org/rapla/entities/tests/CategoryTest.java
Java
gpl3
6,136
/*--------------------------------------------------------------------------* | 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.tests; import java.util.Collections; import java.util.Iterator; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.RaplaTestCase; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.ClassificationFilterRule; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.ClientFacade; import org.rapla.facade.ModificationModule; import org.rapla.facade.QueryModule; import org.rapla.facade.UpdateModule; import org.rapla.facade.internal.CalendarModelImpl; import org.rapla.framework.TypedComponentRole; import org.rapla.plugin.weekview.WeekViewFactory; public class ClassificationFilterTest extends RaplaTestCase { ModificationModule modificationMod; QueryModule queryMod; UpdateModule updateMod; public ClassificationFilterTest(String name) { super(name); } public static Test suite() { return new TestSuite(ClassificationFilterTest.class); } public void setUp() throws Exception { super.setUp(); ClientFacade facade = getFacade(); queryMod = facade; modificationMod = facade; updateMod = facade; } public void testStore() throws Exception { // select from event where (name contains 'planting' or name contains 'owl') or (description contains 'friends'); DynamicType dynamicType = queryMod.getDynamicType("event"); ClassificationFilter classificationFilter = dynamicType.newClassificationFilter(); classificationFilter.setRule(0 ,dynamicType.getAttribute("name") ,new Object[][] { {"contains","planting"} ,{"contains","owl"} } ); classificationFilter.setRule(1 ,dynamicType.getAttribute("description") ,new Object[][] { {"contains","friends"} } ); /* modificationMod.newRaplaCalendarModel( ) ReservationFilter filter = modificationMod.newReservationFilter(, null, ReservationFilter.PARTICULAR_PERIOD, queryMod.getPeriods()[1], null, null ); // filter.setPeriod(); //assertEquals("bowling",queryMod.getReservations(filter)[0].getClassification().getValue("name")); assertTrue(((EntityReferencer)filter).isRefering((RefEntity)dynamicType)); */ ClassificationFilter[] filter = new ClassificationFilter[] {classificationFilter}; CalendarSelectionModel calendar = modificationMod.newCalendarModel(getFacade().getUser() ); calendar.setViewId( WeekViewFactory.WEEK_VIEW); calendar.setSelectedObjects( Collections.emptyList()); calendar.setSelectedDate( queryMod.today()); calendar.setReservationFilter( filter); CalendarModelConfiguration conf = ((CalendarModelImpl)calendar).createConfiguration(); Preferences prefs = modificationMod.edit( queryMod.getPreferences()); TypedComponentRole<CalendarModelConfiguration> testConf = new TypedComponentRole<CalendarModelConfiguration>("org.rapla.TestConf"); prefs.putEntry( testConf, conf); modificationMod.store( prefs ); DynamicType newDynamicType = modificationMod.edit( dynamicType ); newDynamicType.removeAttribute(newDynamicType.getAttribute("description")); modificationMod.store( newDynamicType ); CalendarModelConfiguration configuration = queryMod.getPreferences().getEntry(testConf); filter = configuration.getFilter(); Iterator<? extends ClassificationFilterRule> it = filter[0].ruleIterator(); it.next(); assertTrue("second rule should be removed." , !it.hasNext()); } public void testFilter() throws Exception { // Test if the new date attribute is used correctly in filters { DynamicType dynamicType = queryMod.getDynamicType("room"); DynamicType modifiableType = modificationMod.edit(dynamicType); Attribute attribute = modificationMod.newAttribute( AttributeType.DATE); attribute.setKey( "date"); modifiableType.addAttribute(attribute); modificationMod.store( modifiableType); } DynamicType dynamicType = queryMod.getDynamicType("room"); //Issue 235 in rapla: Null date check in filter not working anymore ClassificationFilter classificationFilter = dynamicType.newClassificationFilter(); Allocatable[] allocatablesWithoutFilter = queryMod.getAllocatables( classificationFilter.toArray()); assertTrue( allocatablesWithoutFilter.length > 0); classificationFilter.setRule(0 ,dynamicType.getAttribute("date") ,new Object[][] { {"=",null} } ); Allocatable[] allocatables = queryMod.getAllocatables( classificationFilter.toArray()); assertTrue( allocatables.length > 0); } }
04900db4-rob
test-src/org/rapla/entities/tests/ClassificationFilterTest.java
Java
gpl3
6,643
/*--------------------------------------------------------------------------* | 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.tests; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.RaplaTestCase; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.entities.internal.CategoryImpl; import org.rapla.facade.ClientFacade; import org.rapla.facade.ModificationModule; import org.rapla.facade.QueryModule; import org.rapla.facade.UpdateModule; import org.rapla.framework.Configuration; import org.rapla.framework.TypedComponentRole; public class PreferencesTest extends RaplaTestCase { CategoryImpl areas; ModificationModule modificationMod; QueryModule queryMod; UpdateModule updateMod; public PreferencesTest(String name) { super(name); } public static Test suite() { return new TestSuite(PreferencesTest.class); } protected void setUp() throws Exception { super.setUp(); ClientFacade facade = getFacade(); queryMod = facade; modificationMod = facade; updateMod = facade; } public void testLoad() throws Exception { Preferences preferences = queryMod.getPreferences(); TypedComponentRole<RaplaConfiguration> SESSION_TEST = new TypedComponentRole<RaplaConfiguration>("org.rapla.SessionTest"); Configuration config = preferences.getEntry(SESSION_TEST); assertEquals("testvalue",config.getAttribute("test")); } public void testStore() throws Exception { Preferences preferences = queryMod.getPreferences(); Preferences clone = modificationMod.edit(preferences); //Allocatable allocatable = queryMod.getAllocatables()[0]; //Configuration config = queryMod.createReference((RaplaType)allocatable); //clone.putEntry("org.rapla.gui.weekview", config); modificationMod.store(clone); //assertEquals(allocatable, queryMod.resolve(config)); updateMod.refresh(); } }
04900db4-rob
test-src/org/rapla/entities/tests/PreferencesTest.java
Java
gpl3
2,921
/*--------------------------------------------------------------------------* | 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.tests; import java.util.Calendar; import java.util.Date; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.RaplaTestCase; import org.rapla.components.util.DateTools; import org.rapla.entities.Entity; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.facade.ClientFacade; import org.rapla.facade.ModificationModule; import org.rapla.facade.QueryModule; import org.rapla.framework.RaplaException; public class ReservationTest extends RaplaTestCase { Reservation reserv1; Reservation reserv2; Allocatable allocatable1; Allocatable allocatable2; Calendar cal; ModificationModule modificationMod; QueryModule queryMod; public ReservationTest(String name) { super(name); } public static Test suite() { return new TestSuite(ReservationTest.class); } public void setUp() throws Exception { super.setUp(); ClientFacade facade = getFacade(); queryMod = facade; modificationMod = facade; cal = Calendar.getInstance(DateTools.getTimeZone()); reserv1 = modificationMod.newReservation(); reserv1.getClassification().setValue("name","Test Reservation 1"); reserv2 = modificationMod.newReservation(); reserv2.getClassification().setValue("name","Test Reservation 2"); allocatable1 = modificationMod.newResource(); allocatable1.getClassification().setValue("name","Test Resource 1"); allocatable2 = modificationMod.newResource(); allocatable2.getClassification().setValue("name","Test Resource 2"); cal.set(Calendar.DAY_OF_WEEK,Calendar.TUESDAY); cal.set(Calendar.HOUR_OF_DAY,13); cal.set(Calendar.MINUTE,0); Date startDate = cal.getTime(); cal.set(Calendar.HOUR_OF_DAY,16); Date endDate = cal.getTime(); Appointment appointment = modificationMod.newAppointment(startDate, endDate); reserv1.addAppointment(appointment); reserv1.addAllocatable(allocatable1); } public void testHasAllocated() { assertTrue(reserv1.hasAllocated(allocatable1)); assertTrue( ! reserv1.hasAllocated(allocatable2)); } public void testEqual() { assertTrue( ! reserv1.equals (reserv2)); assertTrue(reserv1.equals (reserv1)); } public void testEdit() throws RaplaException { // store the reservation to create the id's modificationMod.storeObjects(new Entity[] {allocatable1,allocatable2, reserv1}); String eventId; { Reservation persistantReservation = modificationMod.getPersistant( reserv1); eventId = persistantReservation.getId(); @SuppressWarnings("unused") Appointment oldAppointment= persistantReservation.getAppointments()[0]; // Clone the reservation Reservation clone = modificationMod.edit(persistantReservation); assertTrue(persistantReservation.equals(clone)); assertTrue(clone.hasAllocated(allocatable1)); // Modify the cloned appointment Appointment clonedAppointment= clone.getAppointments()[0]; cal = Calendar.getInstance(DateTools.getTimeZone()); cal.setTime(clonedAppointment.getStart()); cal.set(Calendar.HOUR_OF_DAY,12); clonedAppointment.move(cal.getTime()); // Add a new appointment cal.setTime(clonedAppointment.getStart()); cal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY); cal.set(Calendar.HOUR_OF_DAY,15); Date startDate2 = cal.getTime(); cal.set(Calendar.HOUR_OF_DAY,17); Date endDate2 = cal.getTime(); Appointment newAppointment = modificationMod.newAppointment(startDate2, endDate2); clone.addAppointment(newAppointment); // store clone modificationMod.storeObjects(new Entity[] {clone}); } Reservation persistantReservation = getFacade().getOperator().resolve(eventId, Reservation.class); assertTrue(persistantReservation.hasAllocated(allocatable1)); // Check if oldAppointment has been modified Appointment[] appointments = persistantReservation.getAppointments(); cal.setTime(appointments[0].getStart()); assertTrue(cal.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY); assertTrue(cal.get(Calendar.HOUR_OF_DAY) == 12); // Check if newAppointment has been added assertTrue(appointments.length == 2); cal.setTime(appointments[1].getEnd()); assertEquals(17,cal.get(Calendar.HOUR_OF_DAY)); assertEquals(Calendar.MONDAY,cal.get(Calendar.DAY_OF_WEEK)); cal.setTime(appointments[1].getStart()); assertEquals(15,cal.get(Calendar.HOUR_OF_DAY)); assertEquals(Calendar.MONDAY,cal.get(Calendar.DAY_OF_WEEK)); } }
04900db4-rob
test-src/org/rapla/entities/tests/ReservationTest.java
Java
gpl3
5,877
/*--------------------------------------------------------------------------* | 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.tests; import java.util.Locale; import org.rapla.ServletTestBase; import org.rapla.entities.Category; import org.rapla.entities.User; import org.rapla.facade.ClientFacade; import org.rapla.framework.RaplaException; import org.rapla.server.ServerServiceContainer; public class UserTest extends ServletTestBase { ClientFacade adminFacade; ClientFacade testFacade; Locale locale; public UserTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); // start the server getContainer().lookup(ServerServiceContainer.class, "storage-file"); // start the client service adminFacade = getContainer().lookup(ClientFacade.class , "remote-facade"); adminFacade.login("homer","duffs".toCharArray()); locale = Locale.getDefault(); try { Category groups = adminFacade.edit( adminFacade.getUserGroupsCategory() ); Category testGroup = adminFacade.newCategory(); testGroup.setKey("test-group"); groups.addCategory( testGroup ); adminFacade.store( groups ); } catch (RaplaException ex) { adminFacade.logout(); super.tearDown(); throw ex; } testFacade = getContainer().lookup(ClientFacade.class , "remote-facade-2"); boolean canLogin = testFacade.login("homer","duffs".toCharArray()); assertTrue( "Can't login", canLogin ); } protected void tearDown() throws Exception { adminFacade.logout(); testFacade.logout(); super.tearDown(); } public void testCreateAndRemoveUser() throws Exception { User user = adminFacade.newUser(); user.setUsername("test"); user.setName("Test User"); adminFacade.store( user ); testFacade.refresh(); User newUser = testFacade.getUser("test"); testFacade.remove( newUser ); // first create a new resource and set the permissions } }
04900db4-rob
test-src/org/rapla/entities/tests/UserTest.java
Java
gpl3
3,021
/*--------------------------------------------------------------------------* | 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.tests; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.rapla.RaplaTestCase; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.ConstraintIds; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.facade.ClientFacade; import org.rapla.facade.ModificationModule; import org.rapla.facade.QueryModule; import org.rapla.framework.RaplaException; public class ClassificationTest extends RaplaTestCase { Reservation reserv1; Reservation reserv2; Allocatable allocatable1; Allocatable allocatable2; Calendar cal; ModificationModule modificationMod; QueryModule queryMod; public ClassificationTest(String name) { super(name); } public void setUp() throws Exception { super.setUp(); ClientFacade facade = getFacade(); queryMod = facade; modificationMod = facade; } public void testChangeType() throws RaplaException { Category c1 = modificationMod.newCategory(); c1.setKey("c1"); Category c1a = modificationMod.newCategory(); c1a.setKey("c1a"); c1.addCategory( c1a ); Category c1b = modificationMod.newCategory(); c1a.setKey("c1b"); c1.addCategory( c1b ); Category c2 = modificationMod.newCategory(); c2.setKey("c2"); Category c2a = modificationMod.newCategory(); c2a.setKey("c2a"); c2.addCategory( c2a ); Category rootC = modificationMod.edit( queryMod.getSuperCategory() ); rootC.addCategory( c1 ); rootC.addCategory( c2 ); DynamicType type = modificationMod.newDynamicType(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE); type.setKey("test-type"); Attribute a1 = modificationMod.newAttribute(AttributeType.CATEGORY); a1.setKey("test-attribute"); a1.setConstraint( ConstraintIds.KEY_ROOT_CATEGORY, c1 ); a1.setConstraint( ConstraintIds.KEY_MULTI_SELECT, true); type.addAttribute( a1 ); try { modificationMod.store( type ); fail("Should throw an EntityNotFoundException"); } catch (EntityNotFoundException ex) { } modificationMod.storeObjects( new Entity[] { rootC, type } ); type = modificationMod.getPersistant( type ); Classification classification = type.newClassification(); classification.setValue("name", "test-resource"); List<?> asList = Arrays.asList(new Category[] {c1a, c1b}); classification.setValues(classification.getAttribute("test-attribute"), asList); Allocatable resource = modificationMod.newAllocatable(classification); modificationMod.storeObjects( new Entity[] { resource } ); { Allocatable persistantResource = modificationMod.getPersistant(resource); Collection<Object> values = persistantResource.getClassification().getValues( classification.getAttribute("test-attribute")); assertEquals( 2, values.size()); Iterator<Object> iterator = values.iterator(); assertEquals( c1a,iterator.next()); assertEquals( c1b,iterator.next()); } type = queryMod.getDynamicType("test-type"); type = modificationMod.edit( type ); a1 = type.getAttribute("test-attribute"); a1.setConstraint( ConstraintIds.KEY_ROOT_CATEGORY, c2 ); modificationMod.store( type ); { Allocatable persistantResource = modificationMod.getPersistant(resource); Classification classification2 = persistantResource.getClassification(); Collection<Object> values = classification2.getValues( classification.getAttribute("test-attribute")); assertEquals(0, values.size()); Object value = classification2.getValue("test-attribute"); assertNull( value); } } }
04900db4-rob
test-src/org/rapla/entities/tests/ClassificationTest.java
Java
gpl3
5,155
/*--------------------------------------------------------------------------* | 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.entities.tests; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** For storing time-information (without dates). This is only used in the test-cases. */ public final class Time implements Comparable<Time> { public final static int MILLISECONDS_PER_SECOND = 1000; public final static int MILLISECONDS_PER_MINUTE = 60 * 1000; public final static int MILLISECONDS_PER_HOUR = 60 * 60 * 1000 ; public final static int MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000 ; int millis = 0; public Time(int millis) { this.millis = millis; } public Time(Calendar cal) { this.millis = calculateMillis(cal.get(Calendar.HOUR_OF_DAY) ,cal.get(Calendar.MINUTE) ,cal.get(Calendar.SECOND) ,cal.get(Calendar.MILLISECOND)); } public Time(int hour,int minute) { int second = 0; int millis = 0; this.millis = calculateMillis(hour,minute,second,millis); } public static Calendar time2calendar(long time,TimeZone zone) { Calendar c = Calendar.getInstance(zone); c.setTime(new Date(time)); return c; } public static int date2daytime(Date d,TimeZone zone) { Calendar c = Calendar.getInstance(zone); c.setTime(d); return calendar2daytime(c); } //* @return Time in milliseconds public static int calendar2daytime(Calendar cal) { return Time.calculateMillis(cal.get(Calendar.HOUR_OF_DAY) ,cal.get(Calendar.MINUTE) ,cal.get(Calendar.SECOND) ,cal.get(Calendar.MILLISECOND)); } private static int calculateMillis(int hour,int minute,int second,int millis) { return ((hour * 60 + minute) * 60 + second) * 1000 + millis; } public int getHour() { return millis / MILLISECONDS_PER_HOUR; } public int getMillis() { return millis; } public int getMinute() { return (millis % MILLISECONDS_PER_HOUR) / MILLISECONDS_PER_MINUTE; } public int getSecond() { return (millis % MILLISECONDS_PER_MINUTE) / MILLISECONDS_PER_SECOND; } public int getMillisecond() { return (millis % MILLISECONDS_PER_SECOND); } public String toString() { return getHour() + ":" + getMinute(); } public Date toDate(TimeZone zone) { Calendar cal = Calendar.getInstance(zone); cal.setTime(new Date(0)); cal.set(Calendar.HOUR_OF_DAY,getHour()); cal.set(Calendar.MINUTE,getMinute()); cal.set(Calendar.SECOND,getSecond()); return cal.getTime(); } public int compareTo(Time time2) { if (getMillis() < time2.getMillis()) return -1; if (getMillis() > time2.getMillis()) return 1; return 0; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + millis; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Time other = (Time) obj; if (millis != other.millis) return false; return true; } }
04900db4-rob
test-src/org/rapla/entities/tests/Time.java
Java
gpl3
4,471
/*--------------------------------------------------------------------------* | 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.tests; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.RaplaTestCase; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.facade.ClientFacade; import org.rapla.facade.ModificationModule; import org.rapla.facade.QueryModule; import org.rapla.facade.UpdateModule; public class AttributeTest extends RaplaTestCase { ModificationModule modificationMod; QueryModule queryMod; UpdateModule updateMod; DynamicType type; public AttributeTest(String name) { super(name); } public static Test suite() { return new TestSuite(AttributeTest.class); } protected void setUp() throws Exception { super.setUp(); ClientFacade facade= getFacade(); queryMod = facade; modificationMod = facade; updateMod = facade; } public void testAnnotations() throws Exception { type = modificationMod.newDynamicType(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE); type.setKey("test-type"); Attribute a1 = modificationMod.newAttribute(AttributeType.STRING); a1.setKey("test-attribute"); a1.setAnnotation("expected-rows", "5"); type.addAttribute( a1 ); modificationMod.store( type ); DynamicType type2 = queryMod.getDynamicType("test-type"); Attribute a2 = type2.getAttribute("test-attribute"); assertEquals(a1, a2); assertEquals( "default-annotation", a2.getAnnotation("not-defined-ann","default-annotation" )); assertEquals( "expected-rows", a2.getAnnotationKeys()[0]); assertEquals( "5", a2.getAnnotation("expected-rows")); } }
04900db4-rob
test-src/org/rapla/entities/tests/AttributeTest.java
Java
gpl3
2,835
/*--------------------------------------------------------------------------* | 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.tests; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class TimeTest extends TestCase { public TimeTest(String name) { super(name); } public static Test suite() { return new TestSuite(TimeTest.class); } protected void setUp() { } public void testTime() { Time time = new Time(0,1); assertTrue(time.getMillis() == Time.MILLISECONDS_PER_MINUTE); Time time1 = new Time( 2 * Time.MILLISECONDS_PER_HOUR + 15 * Time.MILLISECONDS_PER_MINUTE); assertTrue(time1.getHour() == 2); assertTrue(time1.getMinute() == 15); Time time2 = new Time(23,15); Time time3 = new Time(2,15); assertTrue(time1.compareTo(time2) == -1); assertTrue(time2.compareTo(time1) == 1); assertTrue(time1.compareTo(time3) == 0); } }
04900db4-rob
test-src/org/rapla/entities/tests/TimeTest.java
Java
gpl3
1,850
package org.rapla.entities.tests; import java.util.UUID; import org.rapla.RaplaTestCase; public class IDGeneratorTest extends RaplaTestCase { public IDGeneratorTest(String name) { super(name); } public void test() { UUID randomUUID = UUID.randomUUID(); String string = randomUUID.toString(); System.out.println( "[" + string.length() +"] "+ string ); } }
04900db4-rob
test-src/org/rapla/entities/tests/IDGeneratorTest.java
Java
gpl3
381
/*--------------------------------------------------------------------------* | 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.tests; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** For storing date-information (without daytime). This is only used in the test-cases. */ public final class Day implements Comparable<Day> { int date = 0; int month = 0; int year = 0; public Day(int year,int month,int date) { this.year = year; this.month = month; this.date = date; } public int getDate() { return date; } public int getMonth() { return month; } public int getYear() { return year; } public String toString() { return getYear() + "-" + getMonth() + "-" + getDate(); } public Date toDate(TimeZone zone) { Calendar cal = Calendar.getInstance(zone); cal.setTime(new Date(0)); cal.set(Calendar.YEAR,getYear()); cal.set(Calendar.MONTH,getMonth() - 1); cal.set(Calendar.DATE,getDate()); cal.set(Calendar.HOUR_OF_DAY,0); cal.set(Calendar.MINUTE,0); cal.set(Calendar.SECOND,0); cal.set(Calendar.MILLISECOND,0); return cal.getTime(); } public Date toGMTDate() { TimeZone zone = TimeZone.getTimeZone("GMT+0"); Calendar cal = Calendar.getInstance(zone); cal.setTime(new Date(0)); cal.set(Calendar.YEAR,getYear()); cal.set(Calendar.MONTH,getMonth() - 1); cal.set(Calendar.DATE,getDate()); cal.set(Calendar.HOUR_OF_DAY,0); cal.set(Calendar.MINUTE,0); cal.set(Calendar.SECOND,0); cal.set(Calendar.MILLISECOND,0); return cal.getTime(); } public int compareTo(Day day) { if (getYear() < day.getYear()) return -1; if (getYear() > day.getYear()) return 1; if (getMonth() < day.getMonth()) return -1; if (getMonth() > day.getMonth()) return 1; if (getDate() < day.getDate()) return -1; if (getDate() > day.getDate()) return 1; return 0; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + date; result = prime * result + month; result = prime * result + year; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Day other = (Day) obj; if (date != other.date) return false; if (month != other.month) return false; if (year != other.year) return false; return true; } }
04900db4-rob
test-src/org/rapla/entities/tests/Day.java
Java
gpl3
3,755
/*--------------------------------------------------------------------------* | 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.tests; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.rapla.components.util.DateTools; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.AppointmentStartComparator; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.RepeatingType; import org.rapla.entities.domain.internal.AppointmentImpl; public class AppointmentTest extends TestCase { TimeZone zone = DateTools.getTimeZone(); //this is GMT Locale locale = Locale.getDefault(); public AppointmentTest(String name) { super(name); } public static Test suite() { return new TestSuite(AppointmentTest.class); } public void setUp() throws Exception { } Appointment createAppointment(Day day,Time start,Time end) { Calendar cal = Calendar.getInstance(zone,locale); cal.set(Calendar.YEAR,day.getYear()); cal.set(Calendar.MONTH,day.getMonth() - 1); cal.set(Calendar.DATE,day.getDate()); cal.set(Calendar.HOUR_OF_DAY,start.getHour()); cal.set(Calendar.MINUTE,start.getMinute()); cal.set(Calendar.SECOND,0); cal.set(Calendar.MILLISECOND,0); Date startTime = cal.getTime(); cal.set(Calendar.HOUR_OF_DAY,end.getHour()); cal.set(Calendar.MINUTE,end.getMinute()); Date endTime = cal.getTime(); return new AppointmentImpl(startTime,endTime); } public void testOverlapAndCompareTo() { Appointment a1 = createAppointment(new Day(2002,5,25),new Time(12,15),new Time(14,15)); Appointment a2 = createAppointment(new Day(2002,5,26),new Time(13,0),new Time(15,0)); Appointment a3 = createAppointment(new Day(2002,5,25),new Time(13,0),new Time(15,0)); Comparator<Appointment> comp = new AppointmentStartComparator(); // First the single Appointments assertTrue(comp.compare(a1,a2) == -1); assertTrue(comp.compare(a2,a1) == 1); assertTrue(comp.compare(a1,a3) == -1); assertTrue(comp.compare(a3,a1) == 1); assertTrue(a1.overlaps(a3)); assertTrue(a3.overlaps(a1)); assertTrue(!a2.overlaps(a3)); assertTrue(!a3.overlaps(a2)); assertTrue(!a1.overlaps(a2)); assertTrue(!a2.overlaps(a1)); // Now we test repeatings a1.setRepeatingEnabled(true); a2.setRepeatingEnabled(true); a3.setRepeatingEnabled(true); // Weekly repeating until 2002-6-2 Repeating repeating1 = a1.getRepeating(); repeating1.setEnd(new Day(2002,6,2).toDate(zone)); // daily repeating 8x Repeating repeating2 = a2.getRepeating(); repeating2.setType(Repeating.DAILY); repeating2.setNumber(8); // weekly repeating 1x Repeating repeating3 = a3.getRepeating(); repeating3.setNumber(1); assertTrue(a1.overlaps( new Day(2002,5,26).toDate(zone) ,new Day(2002,6,2).toDate(zone) ) ); assertTrue(a1.overlaps(a2)); assertTrue("overlap is not symetric",a2.overlaps(a1)); assertTrue(a1.overlaps(a3)); assertTrue("overlap is not symetric",a3.overlaps(a1)); assertTrue(!a2.overlaps(a3)); assertTrue("overlap is not symetric",!a3.overlaps(a2)); // No appointment in first week of repeating repeating1.addException(new Day(2002,5,25).toDate(zone)); assertTrue("appointments should not overlap, because of exception", !a1.overlaps(a3)); assertTrue("overlap is not symetric",!a3.overlaps(a1)); } public void testOverlap1() { Appointment a1 = createAppointment(new Day(2002,4,15),new Time(10,0),new Time(12,0)); Appointment a2 = createAppointment(new Day(2002,4,15),new Time(9,0),new Time(11,0)); a1.setRepeatingEnabled(true); Repeating repeating1 = a1.getRepeating(); repeating1.setEnd(new Day(2002,7,11).toDate(zone)); a2.setRepeatingEnabled(true); Repeating repeating2 = a2.getRepeating(); repeating2.setType(Repeating.DAILY); repeating2.setNumber(5); assertTrue(a1.overlaps(a2)); assertTrue("overlap is not symetric",a2.overlaps(a1)); } public void testOverlap2() { Appointment a1 = createAppointment(new Day(2002,4,12),new Time(12,0),new Time(14,0)); a1.setRepeatingEnabled(true); Repeating repeating1 = a1.getRepeating(); repeating1.setEnd(new Day(2002,7,11).toDate(zone)); assertTrue(a1.overlaps(new Day(2002,4,15).toDate(zone) , new Day(2002,4,22).toDate(zone))); } public void testOverlap3() { final Appointment a1,a2; { final Appointment a = createAppointment(new Day(2012,3,9),new Time(9,0),new Time(11,0)); a.setRepeatingEnabled(true); Repeating repeating = a.getRepeating(); repeating.setEnd(new Day(2012,4,15).toDate(zone)); repeating.addException(new Day(2012,4,6).toDate(zone)); a1 = a; } { final Appointment a = createAppointment(new Day(2012,3,2),new Time(9,0),new Time(11,0)); a.setRepeatingEnabled(true); Repeating repeating = a.getRepeating(); repeating.setEnd(new Day(2012,4,1).toDate(zone)); repeating.addException(new Day(2012,3,16).toDate(zone)); a2 = a; } boolean overlap1 = a1.overlaps(a2); boolean overlap2 = a2.overlaps(a1); assertTrue(overlap1); assertTrue(overlap2); } public void testBlocks() { Appointment a1 = createAppointment(new Day(2002,4,12),new Time(12,0),new Time(14,0)); a1.setRepeatingEnabled(true); Repeating repeating1 = a1.getRepeating(); repeating1.setEnd(new Day(2002,2,11).toDate(zone)); List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>(); a1.createBlocks( new Day(2002,4,5).toDate(zone) , new Day(2002,5,5).toDate(zone) , blocks ); assertEquals( "Repeating end is in the past: createBlocks should only return one block", 1, blocks.size() ); } public void testMatchNeverEnding() { Appointment a1 = createAppointment(new Day(2002,5,25),new Time(11,15),new Time(13,15)); Appointment a2 = createAppointment(new Day(2002,5,25),new Time(11,15),new Time(13,15)); a1.setRepeatingEnabled(true); Repeating repeating1 = a1.getRepeating(); repeating1.setType(Repeating.WEEKLY); a2.setRepeatingEnabled(true); Repeating repeating2 = a2.getRepeating(); repeating2.setType(Repeating.WEEKLY); repeating1.addException(new Day(2002,4,10).toDate( zone )); assertTrue( !a1.matches( a2 ) ); assertTrue( !a2.matches( a1 ) ); } public void testMonthly() { Appointment a1 = createAppointment(new Day(2006,8,17),new Time(10,30),new Time(12,0)); Date start = a1.getStart(); a1.setRepeatingEnabled(true); Repeating repeating1 = a1.getRepeating(); repeating1.setType( RepeatingType.MONTHLY); repeating1.setNumber( 4); List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>(); a1.createBlocks( new Day(2006,8,17).toGMTDate(), new Day( 2007, 3, 30).toGMTDate(), blocks); assertEquals( 4, blocks.size()); Collections.sort(blocks); assertEquals( start, new Date(blocks.get( 0).getStart())); Calendar cal = createGMTCalendar(); cal.setTime( start ); int weekday = cal.get( Calendar.DAY_OF_WEEK); int dayofweekinmonth = cal.get( Calendar.DAY_OF_WEEK_IN_MONTH); assertEquals( Calendar.THURSDAY,weekday ); assertEquals( 3, dayofweekinmonth ); assertEquals( Calendar.AUGUST, cal.get( Calendar.MONTH)); // we expect the second wednesday in april cal.add( Calendar.MONTH, 1 ); cal.set( Calendar.DAY_OF_WEEK , weekday ); cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth); start = cal.getTime(); assertEquals( start, new Date(blocks.get( 1).getStart())); cal.add( Calendar.MONTH, 1 ); cal.set( Calendar.DAY_OF_WEEK , weekday ); cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth); assertEquals(10, cal.get( Calendar.HOUR_OF_DAY)); start = cal.getTime(); assertEquals( start, new Date(blocks.get( 2).getStart())); cal.add( Calendar.MONTH, 1 ); cal.set( Calendar.DAY_OF_WEEK , weekday ); cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth); start = cal.getTime(); assertEquals( start, new Date(blocks.get( 3).getStart())); assertEquals( start, repeating1.getEnd() ); assertEquals( start, a1.getMaxEnd() ); blocks.clear(); a1.createBlocks( new Day(2006,1,1).toGMTDate(), new Day( 2007, 10, 20).toGMTDate(), blocks); assertEquals( 4, blocks.size()); blocks.clear(); a1.createBlocks( new Day(2006,10,19).toGMTDate(), new Day( 2006, 10, 20).toGMTDate(), blocks); assertEquals( 1, blocks.size()); } public void testMonthly5ft() { Appointment a1 = createAppointment(new Day(2006,8,31),new Time(10,30),new Time(12,0)); Date start = a1.getStart(); a1.setRepeatingEnabled(true); Repeating repeating1 = a1.getRepeating(); repeating1.setType( RepeatingType.MONTHLY); repeating1.setNumber( 4); List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>(); a1.createBlocks( new Day(2006,8,1).toGMTDate(), new Day( 2008, 8, 1).toGMTDate(), blocks); assertEquals( 4, blocks.size()); Collections.sort( blocks); assertEquals( start, new Date(blocks.get(0).getStart())); Calendar cal = createGMTCalendar(); cal.setTime( start ); int weekday = cal.get( Calendar.DAY_OF_WEEK); int dayofweekinmonth = cal.get( Calendar.DAY_OF_WEEK_IN_MONTH); assertEquals( Calendar.THURSDAY,weekday ); assertEquals( 5, dayofweekinmonth ); assertEquals( Calendar.AUGUST, cal.get( Calendar.MONTH)); cal.set( Calendar.MONTH, Calendar.NOVEMBER ); cal.set( Calendar.DAY_OF_WEEK , weekday ); cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth); start = cal.getTime(); assertEquals( start, new Date(blocks.get(1).getStart())); cal.add( Calendar.YEAR,1); cal.set( Calendar.MONTH, Calendar.MARCH ); cal.set( Calendar.DAY_OF_WEEK , weekday ); cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth); assertEquals(10, cal.get( Calendar.HOUR_OF_DAY)); start = cal.getTime(); assertEquals( start, new Date(blocks.get(2).getStart())); cal.set( Calendar.MONTH, Calendar.MAY ); cal.set( Calendar.DAY_OF_WEEK , weekday ); cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth); start = cal.getTime(); assertEquals( start, new Date(blocks.get(3).getStart())); assertEquals( start, repeating1.getEnd() ); assertEquals( start, a1.getMaxEnd() ); blocks.clear(); a1.createBlocks( new Day(2006,1,1).toGMTDate(), new Day( 2007, 10, 20).toGMTDate(), blocks); assertEquals( 4, blocks.size()); blocks.clear(); a1.createBlocks( new Day(2006,10,19).toGMTDate(), new Day( 2006, 11, 31).toGMTDate(), blocks); assertEquals( 1, blocks.size()); } public void testMonthlyNeverending() { Appointment a1 = createAppointment(new Day(2006,8,31),new Time(10,30),new Time(12,0)); Date start = a1.getStart(); a1.setRepeatingEnabled(true); Repeating repeating1 = a1.getRepeating(); repeating1.setType( RepeatingType.MONTHLY); repeating1.setEnd( null ); List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>(); a1.createBlocks( new Day(2006,8,1).toGMTDate(), new Day( 2008, 8, 1).toGMTDate(), blocks); assertEquals( 9, blocks.size()); assertEquals( start, new Date(blocks.get(0).getStart())); Calendar cal = createGMTCalendar(); cal.setTime( start ); int weekday = cal.get( Calendar.DAY_OF_WEEK); int dayofweekinmonth = cal.get( Calendar.DAY_OF_WEEK_IN_MONTH); assertEquals( Calendar.THURSDAY,weekday ); assertEquals( 5, dayofweekinmonth ); assertEquals( Calendar.AUGUST, cal.get( Calendar.MONTH)); cal.set( Calendar.MONTH, Calendar.NOVEMBER ); cal.set( Calendar.DAY_OF_WEEK , weekday ); cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth); start = cal.getTime(); assertEquals( start, new Date(blocks.get(1).getStart())); cal.add( Calendar.YEAR,1); cal.set( Calendar.MONTH, Calendar.MARCH ); cal.set( Calendar.DAY_OF_WEEK , weekday ); cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth); assertEquals(10, cal.get( Calendar.HOUR_OF_DAY)); start = cal.getTime(); assertEquals( start, new Date(blocks.get(2).getStart())); cal.set( Calendar.MONTH, Calendar.MAY ); cal.set( Calendar.DAY_OF_WEEK , weekday ); cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth); start = cal.getTime(); assertEquals( start, new Date(blocks.get(3).getStart())); blocks.clear(); a1.createBlocks( new Day(2006,1,1).toGMTDate(), new Day( 2007, 10, 20).toGMTDate(), blocks); assertEquals( 5, blocks.size()); } public void testYearly29February() { Appointment a1 = createAppointment(new Day(2004,2,29),new Time(10,30),new Time(12,0)); Date start = a1.getStart(); a1.setRepeatingEnabled(true); Repeating repeating1 = a1.getRepeating(); repeating1.setType( RepeatingType.YEARLY); repeating1.setNumber( 4); List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>(); a1.createBlocks( new Day(2004,1,1).toGMTDate(), new Day( 2020, 1, 1).toGMTDate(), blocks); assertEquals( 4, blocks.size()); assertEquals( start, new Date(blocks.get(0).getStart())); Calendar cal = createGMTCalendar(); cal.setTime( start ); int weekday = cal.get( Calendar.DAY_OF_WEEK); int dayofweekinmonth = cal.get( Calendar.DAY_OF_WEEK_IN_MONTH); assertEquals( Calendar.SUNDAY,weekday ); assertEquals( 5, dayofweekinmonth ); assertEquals( Calendar.FEBRUARY, cal.get( Calendar.MONTH)); cal.add( Calendar.YEAR,4); cal.set( Calendar.MONTH, Calendar.FEBRUARY ); cal.set( Calendar.DAY_OF_MONTH , 29 ); start = cal.getTime(); assertEquals( start, new Date(blocks.get(1).getStart())); cal.add( Calendar.YEAR,4); cal.set( Calendar.MONTH, Calendar.FEBRUARY ); cal.set( Calendar.DAY_OF_MONTH , 29 ); assertEquals(10, cal.get( Calendar.HOUR_OF_DAY)); start = cal.getTime(); assertEquals( start, new Date(blocks.get(2).getStart())); cal.add( Calendar.YEAR,4); cal.set( Calendar.MONTH, Calendar.FEBRUARY ); cal.set( Calendar.DAY_OF_MONTH , 29 ); start = cal.getTime(); assertEquals( start, new Date(blocks.get(3).getStart())); assertEquals( start, repeating1.getEnd() ); assertEquals( start, a1.getMaxEnd() ); blocks.clear(); a1.createBlocks( new Day(2006,1,1).toGMTDate(), new Day( 2012, 10, 20).toGMTDate(), blocks); assertEquals( 2, blocks.size()); blocks.clear(); a1.createBlocks( new Day(2008,1,1).toGMTDate(), new Day( 2008, 11, 31).toGMTDate(), blocks); assertEquals( 1, blocks.size()); } public void testYearly() { Appointment a1 = createAppointment(new Day(2006,8,17),new Time(10,30),new Time(12,0)); Date start = a1.getStart(); a1.setRepeatingEnabled(true); Repeating repeating1 = a1.getRepeating(); repeating1.setType( RepeatingType.YEARLY ); repeating1.setNumber( 4); Calendar cal = createGMTCalendar(); cal.setTime( start ); int dayInMonth = cal.get( Calendar.DAY_OF_MONTH); int month = cal.get( Calendar.MONTH); List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>(); a1.createBlocks( new Day(2006,8,17).toGMTDate(), new Day( 2010, 3, 30).toGMTDate(), blocks); assertEquals( 4, blocks.size()); assertEquals( start, new Date(blocks.get(0).getStart())); cal.add( Calendar.YEAR, 1 ); start = cal.getTime(); assertEquals( start, new Date(blocks.get(1).getStart())); cal.add( Calendar.YEAR, 1 ); start = cal.getTime(); assertEquals( start, new Date(blocks.get(2).getStart())); cal.add( Calendar.YEAR, 1 ); start = cal.getTime(); assertEquals( dayInMonth,cal.get(Calendar.DAY_OF_MONTH)); assertEquals( month,cal.get(Calendar.MONTH)); assertEquals( start, new Date(blocks.get(3).getStart())); assertEquals( start, repeating1.getEnd() ); assertEquals( start, a1.getMaxEnd() ); } private Calendar createGMTCalendar() { return Calendar.getInstance( DateTools.getTimeZone()); } public void testMonthlySetEnd() { Appointment a1 = createAppointment(new Day(2006,8,17),new Time(10,30),new Time(12,0)); Date start = a1.getStart(); a1.setRepeatingEnabled(true); Repeating repeating1 = a1.getRepeating(); repeating1.setType( RepeatingType.MONTHLY); repeating1.setEnd( new Day(2006,12,1).toGMTDate()); List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>(); { Date s = new Day(2006,8,17).toGMTDate(); Date e = new Day( 2007, 3, 30).toGMTDate(); a1.createBlocks( s,e , blocks); } assertEquals( 4, blocks.size()); assertEquals( start, new Date(blocks.get(0).getStart())); Calendar cal = createGMTCalendar(); cal.setTime( start ); int weekday = cal.get( Calendar.DAY_OF_WEEK); int dayofweekinmonth = cal.get( Calendar.DAY_OF_WEEK_IN_MONTH); assertEquals( Calendar.THURSDAY,weekday ); assertEquals( 3, dayofweekinmonth ); assertEquals( Calendar.AUGUST, cal.get( Calendar.MONTH)); cal.add( Calendar.MONTH, 1 ); cal.set( Calendar.DAY_OF_WEEK , weekday ); cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth); start = cal.getTime(); assertEquals( start, new Date(blocks.get(1).getStart())); cal.add( Calendar.MONTH, 1 ); cal.set( Calendar.DAY_OF_WEEK , weekday ); cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth); assertEquals(10, cal.get( Calendar.HOUR_OF_DAY)); start = cal.getTime(); assertEquals( start, new Date(blocks.get(2).getStart())); cal.add( Calendar.MONTH, 1 ); cal.set( Calendar.DAY_OF_WEEK , weekday ); cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth); start = cal.getTime(); assertEquals( start, new Date(blocks.get(3).getStart())); assertEquals( new Day(2006,12,1).toGMTDate(), repeating1.getEnd() ); assertEquals( new Day(2006,12,1).toGMTDate(), a1.getMaxEnd() ); blocks.clear(); a1.createBlocks( new Day(2006,1,1).toGMTDate(), new Day( 2007, 10, 20).toGMTDate(), blocks); assertEquals( 4, blocks.size()); blocks.clear(); a1.createBlocks( new Day(2006,10,19).toGMTDate(), new Day( 2006, 10, 20).toGMTDate(), blocks); assertEquals( 1, blocks.size()); } }
04900db4-rob
test-src/org/rapla/entities/tests/AppointmentTest.java
Java
gpl3
21,261
package org.rapla; import java.util.Date; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaException; public class HugeDataFileTest extends RaplaTestCase { public HugeDataFileTest( String name ) { super( name ); } public void testHuge() throws RaplaException, Exception { getFacade().login("homer","duffs".toCharArray()); int RESERVATION_COUNT =15000; Reservation[] events = new Reservation[RESERVATION_COUNT]; for ( int i=0;i<RESERVATION_COUNT;i++) { Reservation event = getFacade().newReservation(); Appointment app1 = getFacade().newAppointment( new Date(), new Date()); Appointment app2 = getFacade().newAppointment( new Date(), new Date()); event.addAppointment( app1); event.addAppointment( app2); event.getClassification().setValue("name", "Test-Event " + i); events[i] = event; } getLogger().info("Starting store"); getFacade().storeObjects( events ); getFacade().logout(); getLogger().info("Stored"); getFacade().login("homer","duffs".toCharArray()); } public static void main(String[] args) { HugeDataFileTest test = new HugeDataFileTest( HugeDataFileTest.class.getName()); try { test.setUp(); test.testHuge(); test.tearDown(); } catch (Exception e) { e.printStackTrace(); } } }
04900db4-rob
test-src/org/rapla/HugeDataFileTest.java
Java
gpl3
1,622
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.tests; import java.util.Date; import org.rapla.RaplaTestCase; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.facade.ClientFacade; import org.rapla.framework.RaplaException; import org.rapla.storage.CachableStorageOperator; public abstract class AbstractOperatorTest extends RaplaTestCase { protected CachableStorageOperator operator; protected ClientFacade facade; public AbstractOperatorTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); operator = raplaContainer.lookup(CachableStorageOperator.class , getStorageName()); facade = raplaContainer.lookup(ClientFacade.class, getFacadeName()); } abstract protected String getStorageName(); abstract protected String getFacadeName(); public void testReservationStore() throws RaplaException { // abspeichern facade.login("homer", "duffs".toCharArray() ); { Reservation r = facade.newReservation(); r.getClassification().setValue("name","test"); Appointment app = facade.newAppointment( new Date(), new Date()); Appointment app2 = facade.newAppointment( new Date(), new Date()); Allocatable resource = facade.newResource(); r.addAppointment( app); r.addAppointment( app2); r.addAllocatable(resource ); r.setRestriction( resource, new Appointment[] {app}); app.setRepeatingEnabled( true ); app.getRepeating().setType(Repeating.DAILY); app.getRepeating().setNumber( 10); app.getRepeating().addException( new Date()); facade.storeObjects( new Entity[] { r, resource }); } operator.disconnect(); operator.connect(); facade.login("homer", "duffs".toCharArray() ); // einlesen { String defaultReservation = "event"; ClassificationFilter filter = facade.getDynamicType( defaultReservation ).newClassificationFilter(); filter.addRule("name",new Object[][] { {"contains","test"}}); Reservation reservation = facade.getReservationsForAllocatable( null, null, null, new ClassificationFilter[] {filter} )[0]; Appointment[] apps = reservation.getAppointments(); Allocatable resource = reservation.getAllocatables()[0]; assertEquals( 2, apps.length); assertEquals( 1, reservation.getAppointmentsFor( resource ).length); Appointment app = reservation.getAppointmentsFor( resource )[0]; assertEquals( 1, app.getRepeating().getExceptions().length); assertEquals( Repeating.DAILY, app.getRepeating().getType()); assertEquals( 10, app.getRepeating().getNumber()); } } public void testUserStore() throws RaplaException { facade.login("homer", "duffs".toCharArray() ); { User u = facade.newUser(); u.setUsername("kohlhaas"); u.setAdmin( false); u.addGroup( facade.getUserGroupsCategory().getCategory("my-group")); facade.store( u ); } operator.disconnect(); operator.connect(); facade.login("homer", "duffs".toCharArray() ); { User u = facade.getUser("kohlhaas"); Category[] groups = u.getGroups(); assertEquals( groups.length, 2 ); assertEquals( facade.getUserGroupsCategory().getCategory("my-group"), groups[1]); assertFalse( u.isAdmin() ); } } public void testCategoryAnnotation() throws RaplaException { String sampleDoc = "This is the category for user-groups"; String sampleAnnotationValue = "documentation"; facade.login("homer", "duffs".toCharArray() ); { Category userGroups = facade.edit( facade.getUserGroupsCategory()); userGroups.setAnnotation( sampleAnnotationValue, sampleDoc ); facade.store( userGroups ); } operator.disconnect(); operator.connect(); facade.login("homer", "duffs".toCharArray() ); { Category userGroups = facade.getUserGroupsCategory(); assertEquals( sampleDoc, userGroups.getAnnotation( sampleAnnotationValue )); } } public void testAttributeStore() throws RaplaException { facade.login("homer", "duffs".toCharArray() ); // abspeichern { DynamicType type = facade.edit( facade.getDynamicType("event")); Attribute att = facade.newAttribute( AttributeType.STRING ); att.setKey("test-att"); type.addAttribute( att ); Reservation r = facade.newReservation(); try { r.setClassification( type.newClassification() ); fail("Should have thrown an IllegalStateException"); } catch (IllegalStateException ex) { } facade.store( type ); r.setClassification( facade.getPersistant(type).newClassification() ); r.getClassification().setValue("name","test"); r.getClassification().setValue("test-att","test-att-value"); Appointment app = facade.newAppointment( new Date(), new Date()); Appointment app2 = facade.newAppointment( new Date(), new Date()); Allocatable resource = facade.newResource(); r.addAppointment( app); r.addAppointment( app2); r.addAllocatable(resource ); r.setRestriction( resource, new Appointment[] {app}); app.setRepeatingEnabled( true ); app.getRepeating().setType(Repeating.DAILY); app.getRepeating().setNumber( 10); app.getRepeating().addException( new Date()); facade.storeObjects( new Entity[] { r, resource }); operator.disconnect(); } // einlesen { operator.connect(); facade.login("homer", "duffs".toCharArray() ); String defaultReservation = "event"; ClassificationFilter filter = facade.getDynamicType( defaultReservation ).newClassificationFilter(); filter.addRule("name",new Object[][] { {"contains","test"}}); Reservation reservation = facade.getReservationsForAllocatable( null, null, null, new ClassificationFilter[] {filter} )[0]; Appointment[] apps = reservation.getAppointments(); Allocatable resource = reservation.getAllocatables()[0]; assertEquals( "test-att-value", reservation.getClassification().getValue("test-att")); assertEquals( 2, apps.length); assertEquals( 1, reservation.getAppointmentsFor( resource ).length); Appointment app = reservation.getAppointmentsFor( resource )[0]; assertEquals( 1, app.getRepeating().getExceptions().length); assertEquals( Repeating.DAILY, app.getRepeating().getType()); assertEquals( 10, app.getRepeating().getNumber()); } } }
04900db4-rob
test-src/org/rapla/storage/tests/AbstractOperatorTest.java
Java
gpl3
8,276
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.tests; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.Locale; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.RaplaTestCase; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Period; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.entities.dynamictype.internal.AttributeImpl; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.facade.ClientFacade; import org.rapla.framework.RaplaException; import org.rapla.storage.CachableStorageOperator; import org.rapla.storage.CachableStorageOperatorCommand; import org.rapla.storage.LocalCache; public class LocalCacheTest extends RaplaTestCase { Locale locale; public LocalCacheTest(String name) { super(name); } public static Test suite() { return new TestSuite(LocalCacheTest.class); } protected void setUp() throws Exception { super.setUp(); } public DynamicTypeImpl createDynamicType() throws Exception { AttributeImpl attribute = new AttributeImpl(AttributeType.STRING); attribute.setKey("name"); attribute.setId(getId(Attribute.TYPE,1)); DynamicTypeImpl dynamicType = new DynamicTypeImpl(); dynamicType.setKey("defaultResource"); dynamicType.setId(getId(DynamicType.TYPE,1)); dynamicType.addAttribute(attribute); dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}"); return dynamicType; } public AllocatableImpl createResource(LocalCache cache,int intId,DynamicType type,String name) { Date today = new Date(); AllocatableImpl resource = new AllocatableImpl(today, today); resource.setId(getId(Allocatable.TYPE,intId)); resource.setResolver( cache); Classification classification = type.newClassification(); classification.setValue("name",name); resource.setClassification(classification); return resource; } private String getId(RaplaType type, int intId) { return type.getLocalName() + "_" + intId; } public void testAllocatable() throws Exception { LocalCache cache = new LocalCache(); DynamicTypeImpl type = createDynamicType(); type.setResolver( cache); type.setReadOnly( ); cache.put( type ); AllocatableImpl resource1 = createResource(cache,1,type,"Adrian"); cache.put(resource1); AllocatableImpl resource2 = createResource(cache,2,type,"Beta"); cache.put(resource2); AllocatableImpl resource3 = createResource(cache,3,type,"Ceta"); cache.put(resource3); resource1.getClassification().setValue("name","Zeta"); cache.put(resource1); Allocatable[] resources = cache.getAllocatables().toArray(Allocatable.ALLOCATABLE_ARRAY); assertEquals(3, resources.length); assertTrue(resources[1].getName(locale).equals("Beta")); } public void test2() throws Exception { final CachableStorageOperator storage = raplaContainer.lookup(CachableStorageOperator.class , "raplafile"); storage.connect(); final Period[] periods = getFacade().getPeriods(); storage.runWithReadLock(new CachableStorageOperatorCommand() { @Override public void execute(LocalCache cache) throws RaplaException { { ClassificationFilter[] filters = null; Map<String, String> annotationQuery = null; { final Period period = periods[2]; Collection<Reservation> reservations = storage.getReservations(null,null,period.getStart(),period.getEnd(),filters,annotationQuery); assertEquals(0,reservations.size()); } { final Period period = periods[1]; Collection<Reservation> reservations = storage.getReservations(null,null,period.getStart(),period.getEnd(), filters,annotationQuery); assertEquals(2, reservations.size()); } { User user = cache.getUser("homer"); Collection<Reservation> reservations = storage.getReservations(user,null,null,null, filters,annotationQuery); assertEquals(3, reservations.size()); } { User user = cache.getUser("homer"); final Period period = periods[1]; Collection<Reservation> reservations = storage.getReservations(user,null,period.getStart(),period.getEnd(),filters, annotationQuery); assertEquals(2, reservations.size()); } } { Iterator<Allocatable> it = cache.getAllocatables().iterator(); assertEquals("erwin",it.next().getName(locale)); assertEquals("Room A66",it.next().getName(locale)); } } }); } public void testConflicts() throws Exception { ClientFacade facade = getFacade(); Reservation reservation = facade.newReservation(); //start is 13/4 original end = 28/4 Date startDate = getRaplaLocale().toRaplaDate(2013, 4, 13); Date endDate = getRaplaLocale().toRaplaDate(2013, 4, 28); Appointment appointment = facade.newAppointment(startDate, endDate); reservation.addAppointment(appointment); reservation.getClassification().setValue("name", "test"); facade.store( reservation); Reservation modifiableReservation = facade.edit(reservation); Date splitTime = getRaplaLocale().toRaplaDate(2013, 4, 20); Appointment modifiableAppointment = modifiableReservation.findAppointment( appointment); // left part //leftpart.move(13/4, 20/4) modifiableAppointment.move(appointment.getStart(), splitTime); facade.store( modifiableReservation); CachableStorageOperator storage = raplaContainer.lookup(CachableStorageOperator.class, "raplafile"); User user = null; Collection<Allocatable> allocatables = null; Map<String, String> annotationQuery = null; ClassificationFilter[] filters = null; Collection<Reservation> reservations = storage.getReservations(user, allocatables, startDate, endDate, filters,annotationQuery); assertEquals( 1, reservations.size()); } }
04900db4-rob
test-src/org/rapla/storage/tests/LocalCacheTest.java
Java
gpl3
7,958
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbsql.tests; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.ServerTest; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeAnnotations; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.ConstraintIds; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.facade.ClientFacade; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.storage.CachableStorageOperator; import org.rapla.storage.ImportExportManager; import org.rapla.storage.dbsql.DBOperator; public class SQLOperatorRemoteTest extends ServerTest { public SQLOperatorRemoteTest(String name) { super(name); } protected String getStorageName() { return "storage-sql"; } public static Test suite() throws Exception { TestSuite suite = new TestSuite("SQLOperatorRemoteTest"); suite.addTest( new SQLOperatorRemoteTest("testExport")); suite.addTest( new SQLOperatorRemoteTest("testNewAttribute")); suite.addTest( new SQLOperatorRemoteTest("testAttributeChange")); suite.addTest( new SQLOperatorRemoteTest("testChangeDynamicType")); suite.addTest( new SQLOperatorRemoteTest("testChangeGroup")); suite.addTest( new SQLOperatorRemoteTest("testCreateResourceAndRemoveAttribute")); return suite; } public void testExport() throws Exception { RaplaContext context = getContext(); ImportExportManager conv = context.lookup(ImportExportManager.class); conv.doExport(); { CachableStorageOperator operator = getContainer().lookup(CachableStorageOperator.class, "rapladb"); operator.connect(); operator.getVisibleEntities( null ); Thread.sleep( 1000 ); } // // { // CachableStorageOperator operator = context.lookup(CachableStorageOperator.class ,"file"); // // operator.connect(); // operator.getVisibleEntities( null ); // Thread.sleep( 1000 ); // } } /** exposes a bug in the 0.12.1 Version of Rapla */ public void testAttributeChange() throws Exception { ClientFacade facade = getContainer().lookup(ClientFacade.class ,"sql-facade"); facade.login("admin","".toCharArray()); // change Type changeEventType( facade ); facade.logout(); // We need to disconnect the operator CachableStorageOperator operator = getContainer().lookup(CachableStorageOperator.class ,"rapladb"); operator.disconnect(); operator.connect(); testTypeIds(); // The error shows when connect again operator.connect(); changeEventType( facade ); testTypeIds(); } @Override protected void initTestData() throws Exception { super.initTestData(); } private void changeEventType( ClientFacade facade ) throws RaplaException { DynamicType eventType = facade.edit( facade.getDynamicType("event") ); Attribute attribute = eventType.getAttribute("description"); attribute.setType( AttributeType.CATEGORY ); attribute.setConstraint( ConstraintIds.KEY_ROOT_CATEGORY, facade.getSuperCategory().getCategory("department") ); facade.store( eventType ); } private void testTypeIds() throws RaplaException, SQLException { CachableStorageOperator operator = getContainer().lookup(CachableStorageOperator.class, "rapladb"); Connection connection = ((DBOperator)operator).createConnection(); String sql ="SELECT * from DYNAMIC_TYPE"; try { Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery(sql); while ( !set.isLast()) { set.next(); //int idString = set.getInt("id"); //String key = set.getString("type_key"); //System.out.println( "id " + idString + " key " + key); } } catch (SQLException ex) { throw new RaplaException( ex); } finally { connection.close(); } } public void testNewAttribute() throws Exception { ClientFacade facade = getContainer().lookup(ClientFacade.class,"sql-facade"); facade.login("homer","duffs".toCharArray()); // change Type DynamicType roomType = facade.edit( facade.getDynamicType("room") ); Attribute attribute = facade.newAttribute( AttributeType.STRING ); attribute.setKey("color"); attribute.setAnnotation( AttributeAnnotations.KEY_EDIT_VIEW, AttributeAnnotations.VALUE_EDIT_VIEW_NO_VIEW); roomType.addAttribute( attribute ); facade.store( roomType ); roomType = facade.getPersistant( roomType ); Allocatable[] allocatables = facade.getAllocatables( new ClassificationFilter[] {roomType.newClassificationFilter() }); Allocatable allocatable = facade.edit( allocatables[0]); allocatable.getClassification().setValue("color", "665532"); String name = (String) allocatable.getClassification().getValue("name"); facade.store( allocatable ); facade.logout(); // We need to disconnect the operator CachableStorageOperator operator = getContainer().lookup(CachableStorageOperator.class ,"rapladb"); operator.disconnect(); // The error shows when connect again operator.connect(); facade.login("homer","duffs".toCharArray()); allocatables = facade.getAllocatables( new ClassificationFilter[] {roomType.newClassificationFilter() }); allocatable = facade.edit( allocatables[0]); assertEquals( name, allocatable.getClassification().getValue("name") ); } public void testCreateResourceAndRemoveAttribute() throws RaplaException { Allocatable newResource = facade1.newResource(); newResource.setClassification( facade1.getDynamicType("room").newClassification()); newResource.getClassification().setValue("name", "test-resource"); //If commented in it works //newResource.getClassification().setValue("belongsto", facade1.getSuperCategory().getCategory("department").getCategories()[0]); facade1.store(newResource); DynamicType typeEdit3 = facade1.edit(facade1.getDynamicType("room")); typeEdit3.removeAttribute( typeEdit3.getAttribute("belongsto")); facade1.store(typeEdit3); } public void tearDown() throws Exception { // nochmal ueberpruefen ob die Daten auch wirklich eingelesen werden koennen. This could not be the case CachableStorageOperator operator = getContainer().lookup(CachableStorageOperator.class ,"rapladb"); operator.disconnect(); Thread.sleep( 200 ); operator.connect(); operator.getVisibleEntities( null ); operator.disconnect(); Thread.sleep( 100 ); super.tearDown(); Thread.sleep(500); } }
04900db4-rob
test-src/org/rapla/storage/dbsql/tests/SQLOperatorRemoteTest.java
Java
gpl3
8,294
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbsql.tests; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Collections; import java.util.Date; import java.util.Set; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.components.util.DateTools; import org.rapla.entities.Category; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Period; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.framework.RaplaException; import org.rapla.storage.dbsql.DBOperator; import org.rapla.storage.tests.AbstractOperatorTest; public class SQLOperatorTest extends AbstractOperatorTest { public SQLOperatorTest(String name) { super(name); } public void setUp() throws Exception { super.setUp(); operator.connect(); ((DBOperator) operator).removeAll(); operator.disconnect(); operator.connect(); } public static Test suite() { return new TestSuite(SQLOperatorTest.class); } /** exposes a bug in 1.1 * @throws RaplaException */ public void testPeriodInfitiveEnd() throws RaplaException { facade.login("homer", "duffs".toCharArray() ); Reservation event = facade.newReservation(); Appointment appointment = facade.newAppointment( new Date(), new Date()); event.getClassification().setValue("name","test"); appointment.setRepeatingEnabled( true ); appointment.getRepeating().setEnd( null ); event.addAppointment( appointment ); facade.store(event); operator.refresh(); Set<Reservation> singleton = Collections.singleton( event ); Reservation event1 = (Reservation) operator.getPersistant( singleton).get( event); Repeating repeating = event1.getAppointments()[0].getRepeating(); assertNotNull( repeating ); assertNull( repeating.getEnd()); assertEquals( -1, repeating.getNumber()); } public void testPeriodStorage() throws RaplaException { facade.login("homer", "duffs".toCharArray() ); Date start = DateTools.cutDate( new Date()); Date end = new Date( start.getTime() + DateTools.MILLISECONDS_PER_WEEK); Allocatable period = facade.newPeriod(); Classification c = period.getClassification(); String name = "TEST PERIOD2"; c.setValue("name", name); c.setValue("start", start ); c.setValue("end", end ); facade.store( period); operator.refresh(); //Allocatable period1 = (Allocatable) operator.getPersistant( Collections.singleton( period )).get( period); Period[] periods = facade.getPeriods(); for ( Period period1:periods) { if ( period1.getName( null).equals(name)) { assertEquals( start,period1.getStart()); assertEquals( end, period1.getEnd()); } } } public void testCategoryChange() throws RaplaException { facade.login("homer", "duffs".toCharArray() ); { Category category1 = facade.newCategory(); Category category2 = facade.newCategory(); category1.setKey("users1"); category2.setKey("users2"); Category groups = facade.edit(facade.getUserGroupsCategory()); groups.addCategory( category1 ); groups.addCategory( category2 ); facade.store( groups); Category[] categories = facade.getUserGroupsCategory().getCategories(); assertEquals("users1",categories[3].getKey()); assertEquals("users2",categories[4].getKey()); operator.disconnect(); operator.connect(); facade.refresh(); } { Category[] categories = facade.getUserGroupsCategory().getCategories(); assertEquals("users1",categories[3].getKey()); assertEquals("users2",categories[4].getKey()); } } public void testDynamicTypeChange() throws Exception { facade.login("homer", "duffs".toCharArray() ); DynamicType type = facade.edit(facade.getDynamicType("event")); String id = type.getId(); Attribute att = facade.newAttribute( AttributeType.STRING); att.setKey("test-att"); type.addAttribute( att ); facade.store( type); facade.logout(); printTypeIds(); operator.disconnect(); facade.login("homer", "duffs".toCharArray() ); DynamicType typeAfterEdit = facade.getDynamicType("event"); String idAfterEdit = typeAfterEdit.getId(); assertEquals( id, idAfterEdit); } private void printTypeIds() throws RaplaException, SQLException { Connection connection = ((DBOperator)operator).createConnection(); String sql ="SELECT * from DYNAMIC_TYPE"; try { Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery(sql); while ( !set.isLast()) { set.next(); String idString = set.getString("ID"); String key = set.getString("TYPE_KEY"); System.out.println( "id " + idString + " key " + key); } } catch (SQLException ex) { throw new RaplaException( ex); } finally { connection.close(); } } protected String getStorageName() { return "rapladb"; } protected String getFacadeName() { return "sql-facade"; } }
04900db4-rob
test-src/org/rapla/storage/dbsql/tests/SQLOperatorTest.java
Java
gpl3
6,953
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbfile.tests; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Set; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.RaplaTestCase; import org.rapla.entities.Entity; import org.rapla.framework.RaplaException; import org.rapla.storage.CachableStorageOperator; public class FileOperatorDiffTest extends RaplaTestCase { CachableStorageOperator operator; public FileOperatorDiffTest(String name) { super(name); } public boolean differ(String file1, String file2) throws IOException { BufferedReader in1 = null; BufferedReader in2 = null; boolean bDiffer = false; try { in1 = new BufferedReader(new FileReader(file1)); in2 = new BufferedReader(new FileReader(file2)); int line=0; while (true) { String b1 = in1.readLine(); String b2 = in2.readLine(); if ( b1 == null || b2 == null) { if (b1 != b2) { System.out.println("Different sizes"); bDiffer = true; } break; } line ++; if (!b1.equals(b2)) { System.out.println("Different contents in line " + line ); System.out.println("File1: '" +b1 + "'"); System.out.println("File2: '" +b2 + "'"); bDiffer = true; break; } } return bDiffer; } finally { if (in1 != null) in1.close(); if (in2 != null) in2.close(); } } public static Test suite() { return new TestSuite(FileOperatorDiffTest.class); } public void setUp() throws Exception { super.setUp(); operator = raplaContainer.lookup(CachableStorageOperator.class,"raplafile"); } public void testSave() throws RaplaException,IOException { String testFile = "test-src/testdefault.xml"; assertTrue(differ(TEST_FOLDER_NAME + "/test.xml",testFile) == false); operator.connect(); Entity obj = operator.getUsers().iterator().next(); Set<Entity>singleton = Collections.singleton(obj); Collection<Entity> r = operator.editObjects(singleton, null); Entity clone = r.iterator().next(); Collection<Entity> storeList = new ArrayList<Entity>(1); storeList.add( clone); Collection<Entity> removeList = Collections.emptyList(); operator.storeAndRemove(storeList, removeList, null); assertTrue("stored version differs from orginal " + testFile , differ(TEST_FOLDER_NAME + "/test.xml",testFile) == false ); } }
04900db4-rob
test-src/org/rapla/storage/dbfile/tests/FileOperatorDiffTest.java
Java
gpl3
3,955
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbfile.tests; import org.rapla.ServerTest; import org.rapla.storage.CachableStorageOperator; public class FileOperatorRemoteTest extends ServerTest { CachableStorageOperator operator; public FileOperatorRemoteTest(String name) { super(name); } protected String getStorageName() { return "storage-file"; } }
04900db4-rob
test-src/org/rapla/storage/dbfile/tests/FileOperatorRemoteTest.java
Java
gpl3
1,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.storage.dbfile.tests; import junit.framework.Test; import junit.framework.TestSuite; import org.rapla.storage.tests.AbstractOperatorTest; public class FileOperatorTest extends AbstractOperatorTest { public FileOperatorTest(String name) { super(name); } public static Test suite() { return new TestSuite(FileOperatorTest.class); } protected String getStorageName() { return "raplafile"; } protected String getFacadeName() { return "local-facade"; } }
04900db4-rob
test-src/org/rapla/storage/dbfile/tests/FileOperatorTest.java
Java
gpl3
1,492
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; import java.util.Calendar; import java.util.Locale; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.RaplaLocale; import org.rapla.framework.internal.RaplaLocaleImpl; import org.rapla.framework.logger.ConsoleLogger; public class RaplaLocaleTest extends TestCase { DefaultConfiguration config; public RaplaLocaleTest(String name) { super(name); } public static Test suite() { return new TestSuite(RaplaLocaleTest.class); } private DefaultConfiguration createConfig(String defaultLanguage,String countryString) { DefaultConfiguration config = new DefaultConfiguration("locale"); DefaultConfiguration country = new DefaultConfiguration("country"); country.setValue(countryString); config.addChild(country); DefaultConfiguration languages = new DefaultConfiguration("languages"); config.addChild(languages); languages.setAttribute("default",defaultLanguage); DefaultConfiguration language1 = new DefaultConfiguration("language"); language1.setValue("de"); DefaultConfiguration language2 = new DefaultConfiguration("language"); language2.setValue("en"); languages.addChild(language1); languages.addChild(language2); return config; } public void testDateFormat3() throws Exception { RaplaLocale raplaLocale = new RaplaLocaleImpl(createConfig("de","DE"), new ConsoleLogger()); String s = raplaLocale.formatDate(new SerializableDateTimeFormat().parseDate("2001-01-12",false)); assertEquals( "12.01.01", s); } public void testTimeFormat4() { RaplaLocale raplaLocale= new RaplaLocaleImpl(createConfig("en","US"), new ConsoleLogger()); Calendar cal = Calendar.getInstance(raplaLocale.getTimeZone() ,Locale.US); cal.set(Calendar.HOUR_OF_DAY,21); cal.set(Calendar.MINUTE,0); String s = raplaLocale.formatTime(cal.getTime()); assertEquals("9:00 PM", s); } }
04900db4-rob
test-src/org/rapla/RaplaLocaleTest.java
Java
gpl3
3,057
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; import junit.framework.TestCase; import org.rapla.components.util.Tools; public class ToolsTest extends TestCase { public ToolsTest(String name) { super(name); } public void testEqualsOrBothNull() { Integer a = new Integer( 1 ); Integer b = new Integer( 1 ); Integer c = new Integer( 2 ); assertTrue ( a != b ); assertEquals ( a, b ); assertTrue( Tools.equalsOrBothNull( null, null ) ); assertTrue( !Tools.equalsOrBothNull( a, null ) ); assertTrue( !Tools.equalsOrBothNull( null, b ) ); assertTrue( Tools.equalsOrBothNull( a, b ) ); assertTrue( !Tools.equalsOrBothNull( b, c ) ); } }
04900db4-rob
test-src/org/rapla/ToolsTest.java
Java
gpl3
1,649
#!/bin/sh # # Script for starting @doc.name@ version @doc.version@ under Unix # Set either JAVA_HOME to point at your Java Development Kit installation. # or PATH to point at the java command # resolve links - $0 may be a softlink PRG="$0" while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '.*/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`/"$link" fi done PRGDIR=`dirname "$PRG"` if [ -z "$JAVA_HOME" ] ; then JAVA=`which java` if [ -z "$JAVA" ] ; then echo "Cannot find JAVA. You must set JAVA_HOME to point at your Java Development Kit installation." exit 1 fi JAVA_BINDIR=`dirname $JAVA` JAVA_HOME=$JAVA_BINDIR/.. echo "Guessing JAVA_HOME:" $JAVA_HOME fi if [ -z "$JAVA_OPTIONS" ] ; then JAVA_OPTIONS="-Xmx128M" echo "Guessing JAVA_OPTIONS:" $JAVA_HOME fi echo "PROGDIR" $PRGDIR cd $PRGDIR $JAVA_HOME/bin/java $JAVA_OPTIONS -cp raplabootstrap.jar org.rapla.bootstrap.RaplaJettyLoader $1 $2 $3 $4
04900db4-rob
templates/scripts/rapla_sh
Shell
gpl3
1,008
#!/bin/sh # # Script for starting @doc.name@ version @doc.version@ with jetty webserver under Unix # Set either JAVA_HOME to point at your Java Development Kit installation. # or PATH to point at the java command usage() { echo "Usage: $0 {run|start|stop|restart|supervise} " echo "run : starts rapla-server and wait for Control-c " echo "start : starts rapla-server in the background (use only when run works)" echo "stop : stops rapla-server in the background " echo "restart : calls stop then start " echo "import : imports the data from xml-file into the database " echo "export : exports the data from the database into the xml-file" exit 1 } ################################################## # Find directory function ################################################## findDirectory() { OP=$1 shift for L in $* ; do [ $OP $L ] || continue echo $L break done } # ----- Verify and Set Required Environment Variables ------------------------- PRG=$0 ACTION=$1 while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '.*/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`/"$link" fi done PRGDIR=`dirname "$PRG"` if [ -z "$JAVA_HOME" ] ; then JAVA=`which java` if [ -z "$JAVA" ] ; then echo "Cannot find JAVA. You must set JAVA_HOME to point at your Java Development Kit installation." exit 1 fi JAVA_BINDIR=`dirname $JAVA` JAVA_HOME=$JAVA_BINDIR/.. echo "Guessing JAVA_HOME:" $JAVA_HOME fi if [ -z "$JAVA_OPTIONS" ] ; then JAVA_OPTIONS="-Xmx512M" echo "Guessing JAVA_OPTIONS:" $JAVA_OPTIONS fi JAVA="$JAVA_HOME/bin/java" echo "PROGDIR" $PRGDIR cd $PRGDIR RUN_CMD="$JAVA $JAVA_OPTIONS -cp raplabootstrap.jar -Djava.awt.headless=true org.rapla.bootstrap.RaplaServerLoader" ##################################################### # Find a location for the pid file ##################################################### if [ -z "$JETTY_RUN" ] then JETTY_RUN=`findDirectory -w /var/run /usr/var/run .` fi ##################################################### # Find a PID for the pid file ##################################################### if [ -z "$JETTY_PID" ] then JETTY_PID="$JETTY_RUN/raplajetty.pid" fi ##################################################### # Find a location for the jetty console ##################################################### if [ -z "$JETTY_CONSOLE" ] then if [ -w /dev/console ] then JETTY_CONSOLE=/dev/console else JETTY_CONSOLE=/dev/tty fi fi # ----- Do the action ---------------------------------------------------------- ################################################## # Do the action ################################################## case "$ACTION" in import) $PRGDIR/rapla.sh import ;; export) $PRGDIR/rapla.sh export ;; start) if [ -f $JETTY_PID ] then echo "WARNING $JETTY_PID found. Jetty is probably running!!" fi echo "Running Rapla in Jetty: " $RUN_CMD exec $RUN_CMD >>$JETTY_CONSOLE 2>&1 1>/dev/null & echo $! > $JETTY_PID echo "Jetty running pid="`cat $JETTY_PID` ;; stop) PID=`cat $JETTY_PID 2>/dev/null` echo "Shutting down Jetty: $PID" kill $PID 2>/dev/null sleep 2 kill -9 $PID 2>/dev/null rm -f $JETTY_PID echo "STOPPED `date`" >>$JETTY_CONSOLE ;; restart) $0 stop $* sleep 5 $0 start $* ;; supervise) # # Under control of daemontools supervise monitor which # handles restarts and shutdowns via the svc program. # exec $RUN_CMD ;; run) echo "Running Rapla in Jetty: " $RUN_CMD exec $RUN_CMD ;; *) usage ;; esac exit 0
04900db4-rob
templates/scripts/raplaserver_sh
Shell
gpl3
3,894
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client; /** * Indicates the remote JSON server is not available. * <p> * Usually supplied to {@link org.rapla.rest.gwtjsonrpc.common.AsyncCallback#onFailure(Throwable)} when the * remote host isn't answering, such as if the HTTP server is restarting and has * temporarily stopped accepting new connections. */ @SuppressWarnings("serial") public class ServerUnavailableException extends Exception { public static final String MESSAGE = "Server Unavailable"; public ServerUnavailableException() { super(MESSAGE); } }
04900db4-rob
gwt-src/org/rapla/rest/gwtjsonrpc/client/ServerUnavailableException.java
Java
gpl3
1,153
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client; import org.rapla.rest.gwtjsonrpc.common.AsyncCallback; import org.rapla.rest.gwtjsonrpc.common.VoidResult; import com.google.gwt.core.client.GWT; /** Simple callback to ignore a return value. */ public class VoidCallback implements AsyncCallback<VoidResult> { public static final VoidCallback INSTANCE = new VoidCallback(); protected VoidCallback() { } @Override public void onSuccess(final VoidResult result) { } @Override public void onFailure(final Throwable caught) { GWT.log("Error in VoidCallback", caught); } }
04900db4-rob
gwt-src/org/rapla/rest/gwtjsonrpc/client/VoidCallback.java
Java
gpl3
1,173
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.event; import com.google.gwt.event.shared.EventHandler; /** Handler to receive notifications on RPC beginning. */ public interface RpcStartHandler extends EventHandler { /** Invoked when an RPC call starts. */ public void onRpcStart(RpcStartEvent event); }
04900db4-rob
gwt-src/org/rapla/rest/gwtjsonrpc/client/event/RpcStartHandler.java
Java
gpl3
889
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.event; import org.rapla.rest.gwtjsonrpc.client.JsonUtil; import org.rapla.rest.gwtjsonrpc.client.impl.JsonCall; /** Event received by {@link RpcCompleteHandler} */ public class RpcCompleteEvent extends BaseRpcEvent<RpcCompleteHandler> { private static Type<RpcCompleteHandler> TYPE = null; private static RpcCompleteEvent INSTANCE = null; /** * Fires a RpcCompleteEvent. * <p> * For internal use only. * * @param eventData */ @SuppressWarnings("rawtypes") public static void fire(Object eventData) { assert eventData instanceof JsonCall : "For internal use only"; if (TYPE != null) { // If we have a TYPE, we have an INSTANCE. INSTANCE.call = (JsonCall) eventData; JsonUtil.fireEvent(INSTANCE); } } /** * Gets the type associated with this event. * * @return returns the event type */ public static Type<RpcCompleteHandler> getType() { if (TYPE == null) { TYPE = new Type<RpcCompleteHandler>(); INSTANCE = new RpcCompleteEvent(); } return TYPE; } private RpcCompleteEvent() { // Do nothing } @Override public Type<RpcCompleteHandler> getAssociatedType() { return TYPE; } @Override protected void dispatch(final RpcCompleteHandler handler) { handler.onRpcComplete(this); } @Override protected void kill() { super.kill(); call = null; } }
04900db4-rob
gwt-src/org/rapla/rest/gwtjsonrpc/client/event/RpcCompleteEvent.java
Java
gpl3
2,011
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.event; import org.rapla.rest.gwtjsonrpc.client.impl.JsonCall; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.user.client.rpc.ServiceDefTarget; /** Common event for {@link RpcStartEvent}, {@link RpcCompleteEvent}. */ public abstract class BaseRpcEvent<T extends EventHandler> extends GwtEvent<T> { JsonCall<?> call; /** @return the service instance the remote call occurred on. */ public Object getService() { assertLive(); return call.getProxy(); } /** @return the service instance the remote call occurred on. */ public ServiceDefTarget getServiceDefTarget() { assertLive(); return call.getProxy(); } /** @return the method name being invoked on the service. */ public String getMethodName() { assertLive(); return call.getMethodName(); } }
04900db4-rob
gwt-src/org/rapla/rest/gwtjsonrpc/client/event/BaseRpcEvent.java
Java
gpl3
1,487
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.event; import org.rapla.rest.gwtjsonrpc.client.JsonUtil; import org.rapla.rest.gwtjsonrpc.client.impl.JsonCall; /** Event received by {@link RpcStartHandler} */ public class RpcStartEvent extends BaseRpcEvent<RpcStartHandler> { private static Type<RpcStartHandler> TYPE; private static RpcStartEvent INSTANCE; /** * Fires a RpcStartEvent. * <p> * For internal use only. * * @param eventData */ @SuppressWarnings("rawtypes") public static void fire(Object eventData) { assert eventData instanceof JsonCall : "For internal use only"; if (TYPE != null) { // If we have a TYPE, we have an INSTANCE. INSTANCE.call = (JsonCall) eventData; JsonUtil.fireEvent(INSTANCE); } } /** * Gets the type associated with this event. * * @return returns the event type */ public static Type<RpcStartHandler> getType() { if (TYPE == null) { TYPE = new Type<RpcStartHandler>(); INSTANCE = new RpcStartEvent(); } return TYPE; } private RpcStartEvent() { // Do nothing } @Override public Type<RpcStartHandler> getAssociatedType() { return TYPE; } @Override protected void dispatch(final RpcStartHandler handler) { handler.onRpcStart(this); } @Override protected void kill() { super.kill(); call = null; } }
04900db4-rob
gwt-src/org/rapla/rest/gwtjsonrpc/client/event/RpcStartEvent.java
Java
gpl3
1,958
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.event; import com.google.gwt.event.shared.EventHandler; /** Handler to receive notifications on RPC has finished. */ public interface RpcCompleteHandler extends EventHandler { /** Invoked when an RPC call completes. */ public void onRpcComplete(RpcCompleteEvent event); }
04900db4-rob
gwt-src/org/rapla/rest/gwtjsonrpc/client/event/RpcCompleteHandler.java
Java
gpl3
904
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl; import org.rapla.rest.gwtjsonrpc.client.ServerUnavailableException; import org.rapla.rest.gwtjsonrpc.client.event.RpcCompleteEvent; import org.rapla.rest.gwtjsonrpc.client.event.RpcStartEvent; import org.rapla.rest.gwtjsonrpc.common.AsyncCallback; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; public abstract class JsonCall<T> implements RequestCallback { protected static final JavaScriptObject jsonParser; static { jsonParser = selectJsonParser(); } /** * Select the most efficient available JSON parser. * * If we have a native JSON parser, present in modern browsers (FF 3.5 and * IE8, at time of writing), it is returned. If no native parser is found, a * parser function using <code>eval</code> is returned. * * This is done dynamically, not with a GWT user.agent check, because FF3.5 * does not have a specific user.agent associated with it. Introducing a new * property for the presence of an ES3.1 parser is not worth it, since the * check is only done once anyway, and will result in significantly longer * compile times. * * As GWT will undoubtedly introduce support for the native JSON parser in the * {@link com.google.gwt.json.client.JSONParser JSONParser} class, this code * should be reevaluated to possibly use the GWT parser reference. * * @return a javascript function with the fastest available JSON parser * @see "http://wiki.ecmascript.org/doku.php?id=es3.1:json_support" */ private static native JavaScriptObject selectJsonParser() /*-{ if ($wnd.JSON && typeof $wnd.JSON.parse === 'function') return $wnd.JSON.parse; else return function(expr) { return eval('(' + expr + ')'); }; }-*/; protected final AbstractJsonProxy proxy; protected final String methodName; protected final String requestParams; protected final ResultDeserializer<T> resultDeserializer; protected int attempts; protected AsyncCallback<T> callback; private String token; protected JsonCall(final AbstractJsonProxy abstractJsonProxy, final String methodName, final String requestParams, final ResultDeserializer<T> resultDeserializer) { this.proxy = abstractJsonProxy; this.methodName = methodName; this.requestParams = requestParams; this.resultDeserializer = resultDeserializer; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public AbstractJsonProxy getProxy() { return proxy; } public String getMethodName() { return methodName; } protected abstract void send(); public void send(AsyncCallback<T> callback) { this.callback = callback; send(); } protected void send(RequestBuilder rb) { try { if ( token != null) { rb.setHeader("Authorization", "Bearer " + token); } attempts++; rb.send(); } catch (RequestException e) { callback.onFailure(e); return; } if (attempts == 1) { RpcStartEvent.fire(this); } } @Override public void onError(final Request request, final Throwable exception) { RpcCompleteEvent.fire(this); if (exception.getClass() == RuntimeException.class && exception.getMessage().contains("XmlHttpRequest.status")) { // GWT's XMLHTTPRequest class gives us RuntimeException when the // status code is unreadable from the browser. This occurs when // the connection has failed, e.g. the host is down. // callback.onFailure(new ServerUnavailableException()); } else { callback.onFailure(exception); } } }
04900db4-rob
gwt-src/org/rapla/rest/gwtjsonrpc/client/impl/JsonCall.java
Java
gpl3
4,484