code
stringlengths
3
1.18M
language
stringclasses
1 value
package org.rapla.storage.dbrm; import org.rapla.rest.gwtjsonrpc.common.FutureResult; public class RemoteConnectionInfo { String accessToken; FutureResult<String> reAuthenticateCommand; String serverURL; StatusUpdater statusUpdater; public void setStatusUpdater(StatusUpdater statusUpdater) { this.statusUpdater = statusUpdater; } public StatusUpdater getStatusUpdater() { return statusUpdater; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public void setServerURL(String serverURL) { this.serverURL = serverURL; } public String get() { return serverURL; } public void setReAuthenticateCommand(FutureResult<String> reAuthenticateCommand) { this.reAuthenticateCommand = reAuthenticateCommand; } public String getRefreshToken() throws Exception { return reAuthenticateCommand.get(); } public FutureResult<String> getReAuthenticateCommand() { return reAuthenticateCommand; } public String getAccessToken() { return accessToken; } public String getServerURL() { return serverURL; } }
Java
package org.rapla.storage.dbrm; import org.rapla.framework.RaplaContextException; public interface RemoteMethodStub { <T> T getWebserviceLocalStub(Class<T> role) throws RaplaContextException; }
Java
package org.rapla.storage.dbrm; public interface StatusUpdater { enum Status { READY, BUSY } void setStatus( Status status); }
Java
package org.rapla.storage.dbrm; import org.rapla.framework.RaplaException; public class WrongRaplaVersionException extends RaplaException { private static final long serialVersionUID = 1L; public WrongRaplaVersionException(String text) { super(text); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.dbrm; import org.rapla.framework.RaplaContextException; /** provides a mechanism to invoke a remote service on the server. * The server must provide a RemoteService for the specified serviceName. * The RemoteOperator provides the Service RemoteServiceCaller * @request the webservices in the constructor instead. see RemoteOperator for an example*/ public interface RemoteServiceCaller { <T> T getRemoteMethod(Class<T> a ) throws RaplaContextException; }
Java
package org.rapla.storage.dbrm; import java.io.FileNotFoundException; import java.lang.reflect.Method; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.rapla.entities.DependencyException; import org.rapla.entities.EntityNotFoundException; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaSynchronizationException; import org.rapla.rest.client.HTTPJsonConnector; import org.rapla.rest.gwtjsonrpc.common.FutureResult; import org.rapla.rest.gwtjsonrpc.common.JSONParserWrapper; import org.rapla.rest.gwtjsonrpc.common.ResultImpl; import org.rapla.rest.gwtjsonrpc.common.ResultType; import org.rapla.storage.RaplaNewVersionException; import org.rapla.storage.RaplaSecurityException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class RaplaHTTPConnector extends HTTPJsonConnector { //private String clientVersion; public RaplaHTTPConnector() { // clientVersion = i18n.getString("rapla.version"); } private JsonArray serializeArguments(Class<?>[] parameterTypes, Object[] args) { final GsonBuilder gb = JSONParserWrapper.defaultGsonBuilder().disableHtmlEscaping(); JsonArray params = new JsonArray(); Gson serializer = gb.disableHtmlEscaping().create(); for ( int i=0;i< parameterTypes.length;i++) { Class<?> type = parameterTypes[i]; Object arg = args[i]; JsonElement jsonTree = serializer.toJsonTree(arg, type); params.add( jsonTree); } return params; } private Gson createJsonMapper() { Gson gson = JSONParserWrapper.defaultGsonBuilder().disableHtmlEscaping().create(); return gson; } private Object deserializeReturnValue(Class<?> returnType, JsonElement element) { Gson gson = createJsonMapper(); Object result = gson.fromJson(element, returnType); return result; } private List deserializeReturnList(Class<?> returnType, JsonArray list) { Gson gson = createJsonMapper(); List<Object> result = new ArrayList<Object>(); for (JsonElement element:list ) { Object obj = gson.fromJson(element, returnType); result.add( obj); } return result; } private Set deserializeReturnSet(Class<?> returnType, JsonArray list) { Gson gson = createJsonMapper(); Set<Object> result = new LinkedHashSet<Object>(); for (JsonElement element:list ) { Object obj = gson.fromJson(element, returnType); result.add( obj); } return result; } private Map deserializeReturnMap(Class<?> returnType, JsonObject map) { Gson gson = createJsonMapper(); Map<String,Object> result = new LinkedHashMap<String,Object>(); for (Entry<String, JsonElement> entry:map.entrySet() ) { String key = entry.getKey(); JsonElement element = entry.getValue(); Object obj = gson.fromJson(element, returnType); result.put(key,obj); } return result; } private RaplaException deserializeExceptionObject(JsonObject result) { JsonObject errorElement = result.getAsJsonObject("error"); JsonObject data = errorElement.getAsJsonObject("data"); JsonElement message = errorElement.get("message"); @SuppressWarnings("unused") JsonElement code = errorElement.get("code"); if ( data != null) { JsonArray paramObj = (JsonArray) data.get("params"); JsonElement jsonElement = data.get("exception"); JsonElement stacktrace = data.get("stacktrace"); if ( jsonElement != null) { String classname = jsonElement.getAsString(); List<String> params = new ArrayList<String>(); if ( paramObj != null) { for ( JsonElement param:paramObj) { params.add(param.toString()); } } RaplaException ex = deserializeException(classname, message.toString(), params); try { if ( stacktrace != null) { List<StackTraceElement> trace = new ArrayList<StackTraceElement>(); for (JsonElement element:stacktrace.getAsJsonArray()) { StackTraceElement ste = createJsonMapper().fromJson( element, StackTraceElement.class); trace.add( ste); } ex.setStackTrace( trace.toArray( new StackTraceElement[] {})); } } catch (Exception ex3) { // Can't get stacktrace } return ex; } } return new RaplaException( message.toString()); } private JsonObject sendCall_(String requestMethod, URL methodURL, JsonElement jsonObject, String authenticationToken) throws Exception { try { return sendCall(requestMethod, methodURL, jsonObject, authenticationToken); } catch (SocketException ex) { throw new RaplaConnectException( ex); } catch (UnknownHostException ex) { throw new RaplaConnectException( ex); } catch (FileNotFoundException ex) { throw new RaplaConnectException( ex); } } public FutureResult call(Class<?> service, String methodName, Object[] args,final RemoteConnectionInfo serverInfo) throws Exception { String serviceUrl =service.getName(); Method method = findMethod(service, methodName); String serverURL = serverInfo.getServerURL(); if ( !serverURL.endsWith("/")) { serverURL+="/"; } URL baseUrl = new URL(serverURL); URL methodURL = new URL(baseUrl,"rapla/json/" + serviceUrl ); boolean loginCmd = methodURL.getPath().endsWith("login") || methodName.contains("login"); JsonObject element = serializeCall(method, args); FutureResult<String> authExpiredCommand = serverInfo.getReAuthenticateCommand(); String accessToken = loginCmd ? null: serverInfo.getAccessToken(); JsonObject resultMessage = sendCall_("POST",methodURL, element, accessToken); JsonElement errorElement = resultMessage.get("error"); if ( errorElement != null) { RaplaException ex = deserializeExceptionObject(resultMessage); // if authorization expired String message = ex.getMessage(); boolean b = message != null && message.indexOf( RemoteStorage.USER_WAS_NOT_AUTHENTIFIED)>=0 && !loginCmd; if ( !b || authExpiredCommand == null ) { throw ex; } // try to get a new one String newAuthCode; try { newAuthCode = authExpiredCommand.get(); } catch (RaplaException e) { throw e; } catch (Exception e) { throw new RaplaException(e.getMessage(), e); } // try the same call again with the new result, this time with no auth code failed fallback resultMessage = sendCall_( "POST", methodURL, element, newAuthCode); } JsonElement resultElement = resultMessage.get("result"); Class resultType; Object resultObject; ResultType resultTypeAnnotation = method.getAnnotation(ResultType.class); if ( resultTypeAnnotation != null) { resultType = resultTypeAnnotation.value(); Class container = resultTypeAnnotation.container(); if ( List.class.equals(container) ) { if ( !resultElement.isJsonArray()) { throw new RaplaException("Array expected as json result in " + service + "." + methodName); } resultObject = deserializeReturnList(resultType, resultElement.getAsJsonArray()); } else if ( Set.class.equals(container) ) { if ( !resultElement.isJsonArray()) { throw new RaplaException("Array expected as json result in " + service + "." + methodName); } resultObject = deserializeReturnSet(resultType, resultElement.getAsJsonArray()); } else if ( Map.class.equals( container) ) { if ( !resultElement.isJsonObject()) { throw new RaplaException("JsonObject expected as json result in " + service + "." + methodName); } resultObject = deserializeReturnMap(resultType, resultElement.getAsJsonObject()); } else if ( Object.class.equals( container) ) { resultObject = deserializeReturnValue(resultType, resultElement); } else { throw new RaplaException("Array expected as json result in " + service + "." + methodName); } } else { resultType = method.getReturnType(); resultObject = deserializeReturnValue(resultType, resultElement); } @SuppressWarnings("unchecked") ResultImpl result = new ResultImpl(resultObject); return result; } public Method findMethod(Class<?> service, String methodName) throws RaplaException { Method method = null; for (Method m:service.getMethods()) { if ( m.getName().equals( methodName)) { method = m; } } if ( method == null) { throw new RaplaException("Method "+ methodName + " not found in " + service.getClass() ); } return method; } public JsonObject serializeCall(Method method, Object[] args) { Class<?>[] parameterTypes = method.getParameterTypes(); JsonElement params = serializeArguments(parameterTypes, args); JsonObject element = new JsonObject(); element.addProperty("jsonrpc", "2.0"); element.addProperty("method", method.getName()); element.add("params",params); element.addProperty("id", "1"); return element; } public RaplaException deserializeException(String classname, String message, List<String> params) { String error = ""; if ( message != null) { error+=message; } if ( classname != null) { if ( classname.equals( WrongRaplaVersionException.class.getName())) { return new WrongRaplaVersionException( message); } else if ( classname.equals(RaplaNewVersionException.class.getName())) { return new RaplaNewVersionException( message); } else if ( classname.equals( RaplaSecurityException.class.getName())) { return new RaplaSecurityException( message); } else if ( classname.equals( RaplaSynchronizationException.class.getName())) { return new RaplaSynchronizationException( message); } else if ( classname.equals( RaplaConnectException.class.getName())) { return new RaplaConnectException( message); } else if ( classname.equals( EntityNotFoundException.class.getName())) { // if ( param != null) // { // String id = (String)convertFromString( String.class, param); // return new EntityNotFoundException( message, id); // } return new EntityNotFoundException( message); } else if ( classname.equals( DependencyException.class.getName())) { if ( params != null) { return new DependencyException( message,params); } //Collection<String> depList = Collections.emptyList(); return new DependencyException( message, new String[] {}); } else { error = classname + " " + error; } } return new RaplaException( error); } // private void addParams(Appendable writer, Map<String,String> args ) throws IOException // { // writer.append( "v="+URLEncoder.encode(clientVersion,"utf-8")); // for (Iterator<String> it = args.keySet().iterator();it.hasNext();) // { // writer.append( "&"); // String key = it.next(); // String value= args.get( key); // { // String pair = key; // writer.append( pair); // if ( value != null) // { // writer.append("="+ URLEncoder.encode(value,"utf-8")); // } // } // // } // } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.rapla.components.util.Assert; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.internal.UserImpl; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.ParentEntity; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.framework.Provider; public class LocalCache implements EntityResolver { Map<String,String> passwords = new HashMap<String,String>(); Map<String,Entity> entities; Map<String,DynamicTypeImpl> dynamicTypes; Map<String,UserImpl> users; Map<String,AllocatableImpl> resources; Map<String,ReservationImpl> reservations; private String clientUserId; public LocalCache() { entities = new HashMap<String,Entity>(); // top-level-entities reservations = new LinkedHashMap<String,ReservationImpl>(); users = new LinkedHashMap<String,UserImpl>(); resources = new LinkedHashMap<String,AllocatableImpl>(); dynamicTypes = new LinkedHashMap<String,DynamicTypeImpl>(); initSuperCategory(); } public String getClientUserId() { return clientUserId; } /** use this to prohibit reservations and preferences (except from system and current user) to be stored in the cache*/ public void setClientUserId(String clientUserId) { this.clientUserId = clientUserId; } /** @return true if the entity has been removed and false if the entity was not found*/ public boolean remove(Entity entity) { RaplaType raplaType = entity.getRaplaType(); boolean bResult = true; String entityId = entity.getId(); bResult = entities.remove(entityId) != null; Map<String,? extends Entity> entitySet = getMap(raplaType); if (entitySet != null) { if (entityId == null) return false; entitySet.remove( entityId ); } if ( entity instanceof ParentEntity) { Collection<Entity> subEntities = ((ParentEntity) entity).getSubEntities(); for (Entity child:subEntities) { remove( child); } } return bResult; } @SuppressWarnings("unchecked") private Map<String,Entity> getMap(RaplaType type) { if ( type == Reservation.TYPE) { return (Map)reservations; } if ( type == Allocatable.TYPE) { return (Map)resources; } if ( type == DynamicType.TYPE) { return (Map)dynamicTypes; } if ( type == User.TYPE) { return (Map)users; } return null; } public void put(Entity entity) { Assert.notNull(entity); RaplaType raplaType = entity.getRaplaType(); String id = entity.getId(); if (id == null) throw new IllegalStateException("ID can't be null"); String clientUserId = getClientUserId(); if ( clientUserId != null ) { if (raplaType == Reservation.TYPE || raplaType == Appointment.TYPE ) { throw new IllegalArgumentException("Can't store reservations or appointments in client cache"); } if (raplaType == Preferences.TYPE ) { String owner = ((PreferencesImpl)entity).getId("owner"); if ( owner != null && !owner.equals( clientUserId)) { throw new IllegalArgumentException("Can't store non system preferences for other users in client cache"); } } } // first remove the old children from the map Entity oldEntity = entities.get( entity); if (oldEntity != null && oldEntity instanceof ParentEntity) { Collection<Entity> subEntities = ((ParentEntity) oldEntity).getSubEntities(); for (Entity child:subEntities) { remove( child); } } entities.put(id,entity); Map<String,Entity> entitySet = getMap(raplaType); if (entitySet != null) { entitySet.put( entity.getId() ,entity); } else { //throw new RuntimeException("UNKNOWN TYPE. Can't store object in cache: " + entity.getRaplaType()); } // then put the new children if ( entity instanceof ParentEntity) { Collection<Entity> subEntities = ((ParentEntity) entity).getSubEntities(); for (Entity child:subEntities) { put( child); } } } public Entity get(Comparable id) { if (id == null) throw new RuntimeException("id is null"); return entities.get(id); } // @SuppressWarnings("unchecked") // private <T extends Entity> Collection<T> getCollection(RaplaType type) { // Map<String,? extends Entity> entities = entityMap.get(type); // // if (entities != null) { // return (Collection<T>) entities.values(); // } else { // throw new RuntimeException("UNKNOWN TYPE. Can't get collection: " // + type); // } // } // // @SuppressWarnings("unchecked") // private <T extends RaplaObject> Collection<T> getCollection(Class<T> clazz) { // RaplaType type = RaplaType.get(clazz); // Collection<T> collection = (Collection<T>) getCollection(type); // return new LinkedHashSet(collection); // } public void clearAll() { passwords.clear(); reservations.clear(); users.clear(); resources.clear(); dynamicTypes.clear(); entities.clear(); initSuperCategory(); } private void initSuperCategory() { CategoryImpl superCategory = new CategoryImpl(null, null); superCategory.setId(Category.SUPER_CATEGORY_ID); superCategory.setKey("supercategory"); superCategory.getName().setName("en", "Root"); entities.put (Category.SUPER_CATEGORY_ID, superCategory); Category[] childs = superCategory.getCategories(); for (int i=0;i<childs.length;i++) { superCategory.removeCategory( childs[i] ); } } public CategoryImpl getSuperCategory() { return (CategoryImpl) get(Category.SUPER_CATEGORY_ID); } public UserImpl getUser(String username) { for (UserImpl user:users.values()) { if (user.getUsername().equals(username)) return user; } for (UserImpl user:users.values()) { if (user.getUsername().equalsIgnoreCase(username)) return user; } return null; } public PreferencesImpl getPreferencesForUserId(String userId) { String preferenceId = PreferencesImpl.getPreferenceIdFromUser(userId); PreferencesImpl pref = (PreferencesImpl) tryResolve( preferenceId, Preferences.class); return pref; } public DynamicType getDynamicType(String elementKey) { for (DynamicType dt:dynamicTypes.values()) { if (dt.getKey().equals(elementKey)) return dt; } return null; } public List<Entity> getVisibleEntities(final User user) { List<Entity> result = new ArrayList<Entity>(); result.add( getSuperCategory()); result.addAll(getDynamicTypes()); result.addAll(getUsers()); for (Allocatable alloc: getAllocatables()) { if (user.isAdmin() || alloc.canReadOnlyInformation( user)) { result.add( alloc); } } // add system preferences { PreferencesImpl preferences = getPreferencesForUserId( null ); if ( preferences != null) { result.add( preferences); } } // add user preferences { String userId = user.getId(); Assert.notNull( userId); PreferencesImpl preferences = getPreferencesForUserId( userId ); if ( preferences != null) { result.add( preferences); } } return result; } // Implementation of EntityResolver @Override public Entity resolve(String id) throws EntityNotFoundException { return resolve(id, null); } public <T extends Entity> T resolve(String id,Class<T> entityClass) throws EntityNotFoundException { T entity = tryResolve(id, entityClass); SimpleEntity.checkResolveResult(id, entityClass, entity); return entity; } @Override public Entity tryResolve(String id) { return tryResolve(id, null); } @Override public <T extends Entity> T tryResolve(String id,Class<T> entityClass) { if (id == null) throw new RuntimeException("id is null"); Entity entity = entities.get(id); @SuppressWarnings("unchecked") T casted = (T) entity; return casted; } public String getPassword(String userId) { return passwords.get(userId); } public void putPassword(String userId, String password) { passwords.put(userId,password); } public void putAll( Collection<? extends Entity> list ) { for ( Entity entity: list) { put( entity); } } public Provider<Category> getSuperCategoryProvider() { return new Provider<Category>() { public Category get() { return getSuperCategory(); } }; } @SuppressWarnings("unchecked") public Collection<User> getUsers() { return (Collection)users.values(); } @SuppressWarnings("unchecked") public Collection<Allocatable> getAllocatables() { return (Collection)resources.values(); } @SuppressWarnings("unchecked") public Collection<Reservation> getReservations() { return (Collection)reservations.values(); } @SuppressWarnings("unchecked") public Collection<DynamicType> getDynamicTypes() { return (Collection)dynamicTypes.values(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import org.rapla.entities.Category; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.RaplaObject; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Permission; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.entities.internal.CategoryImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class AllocatableWriter extends ClassifiableWriter { public AllocatableWriter(RaplaContext sm) throws RaplaException { super(sm); } public void printAllocatable(Allocatable allocatable) throws IOException,RaplaException { String tagName; DynamicType type = allocatable.getClassification().getType(); String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); if ( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON.equals(annotation)) { tagName = "rapla:person"; } else if( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE.equals(annotation)) { tagName = "rapla:resource"; } else if( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE.equals(annotation)) { tagName = "rapla:extension"; } else { throw new RaplaException("No or unknown classification type '" + annotation + "' set for " + allocatable.toString() + " ignoring "); } openTag(tagName); printId(allocatable); printOwner(allocatable); printTimestamp(allocatable ); closeTag(); printAnnotations( allocatable); printClassification(allocatable.getClassification()); Permission[] permissions = allocatable.getPermissions(); for ( int i = 0; i < permissions.length; i++ ){ printPermission(permissions[i]); } closeElement(tagName); } public void writeObject(RaplaObject object) throws IOException, RaplaException { printAllocatable( (Allocatable) object); } protected void printPermission(Permission p) throws IOException,RaplaException { openTag("rapla:permission"); if ( p.getUser() != null ) { att("user", getId( p.getUser() )); } else if ( p.getGroup() != null ) { att( "group", getGroupPath( p.getGroup() ) ); } if ( p.getMinAdvance() != null ) { att ( "min-advance", p.getMinAdvance().toString() ); } if ( p.getMaxAdvance() != null ) { att ( "max-advance", p.getMaxAdvance().toString() ); } if ( p.getStart() != null ) { att ( "start-date", dateTimeFormat.formatDate( p.getStart() ) ); } if ( p.getEnd() != null ) { att ( "end-date", dateTimeFormat.formatDate( p.getEnd() ) ); } if ( p.getAccessLevel() != Permission.ALLOCATE_CONFLICTS ) { att("access", Permission.ACCESS_LEVEL_NAMEMAP.get( p.getAccessLevel() ) ); } closeElementTag(); } private String getGroupPath( Category category) throws EntityNotFoundException { Category rootCategory = getSuperCategory().getCategory(Permission.GROUP_CATEGORY_KEY); return ((CategoryImpl) rootCategory ).getPathForCategory(category); } }
Java
package org.rapla.storage.xml; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import org.rapla.entities.Category; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Period; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.DynamicType; public class RaplaEntityComparator implements Comparator<RaplaObject> { Map<RaplaType,Integer> ordering = new HashMap<RaplaType,Integer>(); public RaplaEntityComparator() { int i=0; ordering.put( Category.TYPE,new Integer(i++)); ordering.put( DynamicType.TYPE, new Integer(i++)); ordering.put( User.TYPE,new Integer(i++)); ordering.put( Allocatable.TYPE, new Integer(i++)); ordering.put( Preferences.TYPE,new Integer(i++) ); ordering.put( Period.TYPE, new Integer(i++) ); ordering.put( Reservation.TYPE,new Integer(i++)); } public int compare( RaplaObject o1, RaplaObject o2) { RaplaObject r1 = o1; RaplaObject r2 = o2; RaplaType t1 = r1.getRaplaType(); RaplaType t2 = r2.getRaplaType(); Integer ord1 = ordering.get( t1); Integer ord2 = ordering.get( t2); if ( o1 == o2) { return 0; } if ( ord1 != null && ord2 != null) { if (ord1.intValue()>ord2.intValue()) { return 1; } if (ord1.intValue()<ord2.intValue()) { return -1; } } if ( ord1 != null && ord2 == null) { return -1; } if ( ord2 != null && ord1 == null) { return 1; } if ( o1.hashCode() > o2.hashCode()) { return 1; } else { return -1; } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.LinkedHashMap; import org.rapla.entities.RaplaObject; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.framework.Configuration; import org.rapla.framework.ConfigurationException; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class RaplaConfigurationWriter extends RaplaXMLWriter { public RaplaConfigurationWriter(RaplaContext sm) throws RaplaException { super(sm); } public void writeObject(RaplaObject type) throws IOException, RaplaException { RaplaConfiguration raplaConfig = (RaplaConfiguration) type ; openElement("rapla:" + RaplaConfiguration.TYPE.getLocalName()); try { printConfiguration(raplaConfig ); } catch (ConfigurationException ex) { throw new RaplaException( ex ); } closeElement("rapla:" + RaplaConfiguration.TYPE.getLocalName()); } /** * Serialize each Configuration element. This method is called recursively. * Original code for this method is taken from the org.apache.framework.configuration.DefaultConfigurationSerializer class * @throws ConfigurationException if an error occurs * @throws IOException if an error occurs */ private void printConfiguration(final Configuration element ) throws ConfigurationException, RaplaException, IOException { LinkedHashMap<String, String> attr = new LinkedHashMap<String, String>(); String[] attrNames = element.getAttributeNames(); if( null != attrNames ) { for( int i = 0; i < attrNames.length; i++ ) { String key = attrNames[ i ]; String value = element.getAttribute( attrNames[ i ], "" ); attr.put( key, value); } } String qName = element.getName(); openTag(qName); att(attr); Configuration[] children = element.getChildren(); if (children.length > 0) { closeTag(); for( int i = 0; i < children.length; i++ ) { printConfiguration( children[ i ] ); } closeElement(qName); } else { String value = element.getValue( null ); if (null == value) { closeElementTag(); } else { closeTagOnLine(); print(value); closeElementOnLine(qName); println(); } } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.RaplaObject; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.framework.Configuration; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.internal.SAXConfigurationHandler; public class RaplaConfigurationReader extends RaplaXMLReader { boolean delegating = false; public RaplaConfigurationReader(RaplaContext context) throws RaplaException { super(context); } SAXConfigurationHandler configurationHandler = new SAXConfigurationHandler(); @Override public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts) throws RaplaSAXParseException { if ( RAPLA_NS.equals(namespaceURI) && localName.equals("config")) return; delegating = true; configurationHandler.startElement(namespaceURI,localName, atts); } @Override public void processEnd(String namespaceURI,String localName) throws RaplaSAXParseException { if ( RAPLA_NS.equals(namespaceURI) && localName.equals("config")) { return; } configurationHandler.endElement(namespaceURI, localName); delegating = false; } @Override public void processCharacters(char[] ch,int start,int length) { if ( delegating ){ configurationHandler.characters(ch,start,length); } } public RaplaObject getType() { return new RaplaConfiguration(getConfiguration()); } private Configuration getConfiguration() { Configuration conf = configurationHandler.getConfiguration(); return conf; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.Date; import java.util.Map; import org.rapla.components.util.ParseDateException; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.Ownable; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Permission; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.AttributeImpl; import org.rapla.entities.internal.CategoryImpl; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.framework.logger.Logger; import org.rapla.storage.IdCreator; import org.rapla.storage.impl.EntityStore; public class RaplaXMLReader extends DelegationHandler implements Namespaces { EntityStore store; Logger logger; IdCreator idTable; RaplaContext context; Map<String,RaplaType> localnameMap; Map<RaplaType,RaplaXMLReader> readerMap; SerializableDateTimeFormat dateTimeFormat; I18nBundle i18n; Date now; public static class TimestampDates { public Date createTime; public Date changeTime; } public RaplaXMLReader( RaplaContext context ) throws RaplaException { logger = context.lookup( Logger.class ); this.context = context; this.i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES); this.store = context.lookup( EntityStore.class); this.idTable = context.lookup( IdCreator.class ); RaplaLocale raplaLocale = context.lookup( RaplaLocale.class ); dateTimeFormat = raplaLocale.getSerializableFormat(); this.localnameMap = context.lookup( PreferenceReader.LOCALNAMEMAPENTRY ); this.readerMap = context.lookup( PreferenceReader.READERMAP ); now = new Date(); } public TimestampDates readTimestamps(RaplaSAXAttributes atts) throws RaplaSAXParseException { String createdAt = atts.getValue( "", "created-at"); String lastChanged = atts.getValue( "", "last-changed"); Date createTime = null; Date changeTime = createTime; if (createdAt != null) { createTime = parseTimestamp( createdAt); } else { createTime = now; } if (lastChanged != null) { changeTime = parseTimestamp( lastChanged); } else { changeTime = createTime; } if ( changeTime.after( now) ) { getLogger().warn("Last changed is in the future " +lastChanged + ". Taking current time as new timestamp."); changeTime = now; } if ( createTime.after( now) ) { getLogger().warn("Create time is in the future " +createTime + ". Taking current time as new timestamp."); createTime = now; } TimestampDates result = new TimestampDates(); result.createTime = createTime; result.changeTime = changeTime; return result; } public RaplaType getTypeForLocalName( String localName ) throws RaplaSAXParseException { RaplaType type = localnameMap.get( localName ); if (type == null) throw createSAXParseException( "No type declared for localname " + localName ); return type; } /** * @param raplaType * @throws RaplaSAXParseException */ protected RaplaXMLReader getChildHandlerForType( RaplaType raplaType ) throws RaplaSAXParseException { RaplaXMLReader childReader = readerMap.get( raplaType ); if (childReader == null) { throw createSAXParseException( "No Reader declared for type " + raplaType ); } addChildHandler( childReader ); return childReader; } protected Logger getLogger() { return logger; } public I18nBundle getI18n() { return i18n; } public Long parseLong( String text ) throws RaplaSAXParseException { try { return new Long( text ); } catch (NumberFormatException ex) { throw createSAXParseException( "No valid number format: " + text ); } } public Boolean parseBoolean( String text ) { return new Boolean( text ); } public Date parseDate( String date, boolean fillDate ) throws RaplaSAXParseException { try { return dateTimeFormat.parseDate( date, fillDate ); } catch (ParseDateException ex) { throw createSAXParseException( ex.getMessage() ); } } public Date parseDateTime( String date, String time ) throws RaplaSAXParseException { try { return dateTimeFormat.parseDateTime( date, time ); } catch (ParseDateException ex) { throw createSAXParseException( ex.getMessage() ); } } public Date parseTimestamp( String timestamp ) throws RaplaSAXParseException { try { return dateTimeFormat.parseTimestamp(timestamp); } catch (ParseDateException ex) { throw createSAXParseException( ex.getMessage() ); } } protected String getString( RaplaSAXAttributes atts, String key, String defaultString ) { String str = atts.getValue( "", key ); return (str != null) ? str : defaultString; } protected String getString( RaplaSAXAttributes atts, String key ) throws RaplaSAXParseException { String str = atts.getValue( "", key ); if (str == null) throw createSAXParseException( "Attribute " + key + " not found!" ); return str; } /** return the new id */ protected String setId( Entity entity, RaplaSAXAttributes atts ) throws RaplaSAXParseException { String idString = atts.getValue( "id" ); String id = getId( entity.getRaplaType(), idString ); ((SimpleEntity)entity).setId( id ); return id; } /** return the new id */ protected Object setNewId( Entity entity ) throws RaplaSAXParseException { try { String id = idTable.createId( entity.getRaplaType() ); ((SimpleEntity)entity).setId( id ); return id; } catch (RaplaException ex) { throw createSAXParseException( ex.getMessage() ); } } protected <T extends SimpleEntity&Ownable> void setOwner( T ownable, RaplaSAXAttributes atts ) throws RaplaSAXParseException { String ownerString = atts.getValue( "owner" ); if (ownerString != null) { ownable.putId("owner", getId( User.TYPE, ownerString ) ); } // No else case as no owner should still be possible and there should be no default owner } protected void setLastChangedBy(SimpleEntity entity, RaplaSAXAttributes atts) { String lastChangedBy = atts.getValue( "last-changed-by"); if ( lastChangedBy != null) { try { User user = resolve(User.TYPE,lastChangedBy ); entity.setLastChangedBy( user ); } catch (RaplaSAXParseException ex) { getLogger().warn("Can't find user " + lastChangedBy + " in entity " + entity.getId()); } } } @SuppressWarnings("deprecation") protected String getId( RaplaType type, String str ) throws RaplaSAXParseException { try { final String id; if ( str.equals(Category.SUPER_CATEGORY_ID)) { id = Category.SUPER_CATEGORY_ID; } else if (org.rapla.storage.OldIdMapping.isTextId(type, str)) { id = idTable.createId(type, str); } else { id = str; } return id; } catch (RaplaException ex) { ex.printStackTrace(); throw createSAXParseException( ex.getMessage() ); } } void throwEntityNotFound( String type, Integer id ) throws RaplaSAXParseException { throw createSAXParseException( type + " with id '" + id + "' not found." ); } public RaplaObject getType() throws RaplaSAXParseException { throw createSAXParseException( "Method getType() not implemented by subclass " + this.getClass().getName() ); } protected CategoryImpl getSuperCategory() { return store.getSuperCategory(); } public DynamicType getDynamicType( String keyref ) { return store.getDynamicType( keyref); } protected <T extends Entity> T resolve( RaplaType<T> type, String str ) throws RaplaSAXParseException { try { String id = getId( type, str ); Class<T> typeClass = type.getTypeClass(); T resolved = store.resolve( id, typeClass ); return resolved; } catch (EntityNotFoundException ex) { throw createSAXParseException(ex.getMessage() , ex); } } protected Object parseAttributeValue( Attribute attribute, String text ) throws RaplaSAXParseException { try { AttributeType type = attribute.getType(); if ( type == AttributeType.CATEGORY ) { text = getId(Category.TYPE, text); } else if ( type == AttributeType.ALLOCATABLE ) { text = getId(Allocatable.TYPE, text); } return AttributeImpl.parseAttributeValue( attribute, text); } catch (RaplaException ex) { throw createSAXParseException( ex.getMessage() ); } } public void add(Entity entity) throws RaplaSAXParseException{ if ( entity instanceof Classifiable) { if ((( Classifiable) entity).getClassification() == null) { throw createSAXParseException("Classification can't be null"); } } store.put(entity); } protected Category getCategoryFromPath( String path ) throws RaplaSAXParseException { try { return getSuperCategory().getCategoryFromPath( path ); } catch (Exception ex) { throw createSAXParseException( ex.getMessage() ); } } protected Category getGroup(String groupKey) throws RaplaSAXParseException{ CategoryImpl groupCategory = (CategoryImpl) getSuperCategory().getCategory( Permission.GROUP_CATEGORY_KEY ); if (groupCategory == null) { throw createSAXParseException( Permission.GROUP_CATEGORY_KEY + " category not found" ); } try { return groupCategory.getCategoryFromPath( groupKey ); } catch (Exception ex) { throw createSAXParseException( ex.getMessage(),ex ); } } protected void putPassword( String userid, String password ) { store.putPassword( userid, password); } protected void setCurrentTranslations(MultiLanguageName name) { String lang = i18n.getLang(); boolean contains = name.getAvailableLanguages().contains( lang); if (!contains) { try { String translation = i18n.getString( name.getName("en")); name.setName( lang, translation); } catch (Exception ex) { } } } static public String wrapRaplaDataTag(String xml) { StringBuilder dataElement = new StringBuilder(); dataElement.append("<rapla:data "); for (int i=0;i<RaplaXMLWriter.NAMESPACE_ARRAY.length;i++) { String prefix = RaplaXMLWriter.NAMESPACE_ARRAY[i][1]; String uri = RaplaXMLWriter.NAMESPACE_ARRAY[i][0]; if ( prefix == null) { dataElement.append("xmlns="); } else { dataElement.append("xmlns:" + prefix + "="); } dataElement.append("\""); dataElement.append( uri ); dataElement.append("\" "); } dataElement.append(">"); dataElement.append( xml ); dataElement.append( "</rapla:data>"); String xmlWithNamespaces = dataElement.toString(); return xmlWithNamespaces; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import org.rapla.components.util.Assert; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.Annotatable; import org.rapla.entities.Category; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.AttributeImpl; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class DynamicTypeReader extends RaplaXMLReader { DynamicTypeImpl dynamicType; MultiLanguageName currentName = null; String currentLang = null; String constraintKey = null; AttributeImpl attribute = null; String annotationKey = null; boolean isAttributeActive = false; boolean isDynamictypeActive = false; HashMap<String,String> typeAnnotations = new LinkedHashMap<String,String>(); HashMap<String,String> attributeAnnotations = new LinkedHashMap<String,String>(); private HashMap<String, Map<Attribute,String>> unresolvedDynamicTypeConstraints = new HashMap<String, Map<Attribute,String>>(); public DynamicTypeReader( RaplaContext context ) throws RaplaException { super( context ); unresolvedDynamicTypeConstraints.clear(); } @Override public void processElement( String namespaceURI, String localName, RaplaSAXAttributes atts ) throws RaplaSAXParseException { if (localName.equals( "element" )) { String qname = getString( atts, "name" ); String name = qname.substring( qname.indexOf( ":" ) + 1 ); Assert.notNull( name ); //System.out.println("NAME: " + qname + " Level " + level + " Entry " + entryLevel); if (!isDynamictypeActive) { isDynamictypeActive = true; typeAnnotations.clear(); TimestampDates ts = readTimestamps( atts); dynamicType = new DynamicTypeImpl(ts.createTime, ts.changeTime); if (atts.getValue( "id" )!=null) { setId( dynamicType, atts ); } else { setNewId( dynamicType ); } currentName = dynamicType.getName(); dynamicType.setKey( name ); // because the dynamic types refered in the constraints could be loaded after their first reference we resolve all prior unresolved constraint bindings to that type when the type is loaded Map<Attribute,String> constraintMap = unresolvedDynamicTypeConstraints.get( name ); if ( constraintMap != null) { for (Map.Entry<Attribute,String> entry: constraintMap.entrySet()) { Attribute att = entry.getKey(); String constraintKey = entry.getValue(); // now set the unresolved constraint, we need to ignore readonly check, because the type may be already closed ((AttributeImpl)att).setContraintWithoutWritableCheck(constraintKey, dynamicType); } } unresolvedDynamicTypeConstraints.remove( name); } else { isAttributeActive = true; attribute = new AttributeImpl(); currentName = attribute.getName(); attribute.setKey( name ); Assert.notNull( name, "key attribute cannot be null" ); if (atts.getValue("id") != null) { setId( attribute, atts ); } else { setNewId( attribute ); } attributeAnnotations.clear(); } } if (localName.equals( "constraint" ) && namespaceURI.equals( RAPLA_NS )) { constraintKey = atts.getValue( "name" ); startContent(); } if (localName.equals( "default" )) { startContent(); } // if no attribute type is set if (localName.equals( "data" ) && namespaceURI.equals( RELAXNG_NS ) && attribute.getType().equals( AttributeImpl.DEFAULT_TYPE )) { String typeName = atts.getValue( "type" ); if (typeName == null) throw createSAXParseException( "element relax:data is requiered!" ); AttributeType type = AttributeType.findForString( typeName ); if (type == null) { getLogger().error( "AttributeType '" + typeName + "' not found. Using string."); type = AttributeType.STRING; } attribute.setType( type ); } if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS )) { annotationKey = atts.getValue( "key" ); Assert.notNull( annotationKey, "key attribute cannot be null" ); startContent(); } if (localName.equals( "name" ) && namespaceURI.equals( ANNOTATION_NS )) { startContent(); currentLang = atts.getValue( "lang" ); Assert.notNull( currentLang ); } } private void addAnnotations( Annotatable annotatable, Map<String,String> annotations ) { for (Iterator<Map.Entry<String,String>> it = annotations.entrySet().iterator(); it.hasNext();) { Map.Entry<String,String> entry = it.next(); String key = entry.getKey(); String annotation = entry.getValue(); try { annotatable.setAnnotation( key, annotation ); } catch (IllegalAnnotationException e) { getLogger().error("Can't parse annotation " + e.getMessage(), e); //throw createSAXParseException( e.getMessage() ); } } } @Override public void processEnd( String namespaceURI, String localName ) throws RaplaSAXParseException { if (localName.equals( "element" )) { if (!isAttributeActive) { addAnnotations( dynamicType, typeAnnotations ); setCurrentTranslations(dynamicType.getName()); dynamicType.setResolver( store); add( dynamicType ); // We ensure the dynamic type is not modified anymore dynamicType.setReadOnly( ); isDynamictypeActive = false; } else { addAnnotations( attribute, attributeAnnotations ); //System.out.println("Adding attribute " + attribute + " to " + dynamicType); setCurrentTranslations(attribute.getName()); dynamicType.addAttribute( attribute ); add( attribute ); isAttributeActive = false; } } else if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS )) { String annotationValue = readContent().trim(); if (isAttributeActive) { attributeAnnotations.put( annotationKey, annotationValue ); } else { typeAnnotations.put( annotationKey, annotationValue ); } } else if (localName.equals( "optional" ) && namespaceURI.equals( RELAXNG_NS )) { attribute.setOptional( true ); } else if (localName.equals( "name" ) && namespaceURI.equals( ANNOTATION_NS )) { Assert.notNull( currentName ); currentName.setName( currentLang, readContent() ); } else if (localName.equals( "constraint" ) && namespaceURI.equals( RAPLA_NS )) { String content = readContent().trim(); Object constraint = null; if (attribute.getConstraintClass( constraintKey ) == Category.class) { @SuppressWarnings("deprecation") boolean idContent = org.rapla.storage.OldIdMapping.isTextId(Category.TYPE, content ); if (idContent) { String id = getId( Category.TYPE, content ); constraint = store.tryResolve( id, Category.class ); if ( constraint == null) { getLogger().error("Can't resolve root category for " + dynamicType.getKey() + "." + attribute.getKey() + " id is " + id + " (" + content + ")"); } } else { constraint = getCategoryFromPath( content ); } } else if (attribute.getConstraintClass( constraintKey ) == DynamicType.class) { @SuppressWarnings("deprecation") boolean idContent = org.rapla.storage.OldIdMapping.isTextId( DynamicType.TYPE, content ); if (idContent) { constraint = content.trim(); } else { String elementKey = content; // check if the dynamic type refers to itself if (elementKey.equals( dynamicType.getKey())) { constraint = dynamicType; } else { // this only works if the dynamic type is already loaded constraint = getDynamicType(elementKey); // so we cache the contraint attributes in a map to be filled when the types are loaded if (constraint == null) { Map<Attribute,String> collection = unresolvedDynamicTypeConstraints.get( elementKey); if ( collection == null) { collection = new HashMap<Attribute,String>(); unresolvedDynamicTypeConstraints.put( elementKey, collection); } collection.put( attribute, constraintKey); } } } } else if (attribute.getConstraintClass( constraintKey ) == Integer.class) { constraint = parseLong( content ); } else if (attribute.getConstraintClass( constraintKey ) == Boolean.class) { constraint = parseBoolean( content ); } else { constraint = content; } attribute.setConstraint( constraintKey, constraint ); } if (localName.equals( "default" ) && namespaceURI.equals( RAPLA_NS )) { String content = readContent().trim(); final Object defaultValue; final AttributeType type = attribute.getType(); if (type == AttributeType.CATEGORY) { @SuppressWarnings("deprecation") boolean idContent = org.rapla.storage.OldIdMapping.isTextId(Category.TYPE, content ); if (idContent) { defaultValue = resolve( Category.TYPE, content ); } else { defaultValue = getCategoryFromPath( content ); } } else { Object value; try { value = parseAttributeValue(attribute, content); } catch (RaplaException e) { value = null; } defaultValue = value; } attribute.setDefaultValue(defaultValue ); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.Collection; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; class ClassifiableWriter extends RaplaXMLWriter { public ClassifiableWriter(RaplaContext sm) throws RaplaException { super(sm); } protected void printClassification(Classification classification) throws IOException,RaplaException { if (classification == null) return; DynamicType dynamicType = classification.getType(); boolean internal = ((DynamicTypeImpl)dynamicType).isInternal(); String namespacePrefix = internal ? "ext:" : "dynatt:"; String elementKey = dynamicType.getKey(); if ( internal ) { if (!elementKey.startsWith("rapla:")) { throw new RaplaException("keys for internal type must start with rapla:"); } elementKey = elementKey.substring("rapla:".length() ); } else { if (elementKey.startsWith("rapla:")) { throw new RaplaException("keys for non internal type can't start with rapla:"); } } String elementName = namespacePrefix + elementKey; Attribute[] attributes = classification.getAttributes(); if ( attributes.length == 0) { openTag(elementName); } else { openElement(elementName); } for (int i=0;i<attributes.length;i++) { Attribute attribute = attributes[i]; Collection<?> values = classification.getValues(attribute); for ( Object value:values) { String attributeName = namespacePrefix + attribute.getKey(); openElementOnLine(attributeName); printAttributeValue(attribute, value); closeElementOnLine(attributeName); println(); } } if ( attributes.length == 0) { closeElementTag(); } else { closeElement(elementName); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.Iterator; import java.util.Map; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.configuration.RaplaMap; import org.rapla.entities.configuration.internal.RaplaMapImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class RaplaMapWriter extends RaplaXMLWriter { public RaplaMapWriter(RaplaContext sm) throws RaplaException { super(sm); } public void writeObject(RaplaObject type) throws IOException, RaplaException { writeMap_((RaplaMapImpl) type ); } private void writeMap_(RaplaMapImpl map ) throws IOException, RaplaException { openElement("rapla:" + RaplaMap.TYPE.getLocalName()); for (Iterator<String> it = map.keySet().iterator();it.hasNext();) { Object key = it.next(); Object obj = map.get( key); printEntityReference( key, obj); } closeElement("rapla:" + RaplaMap.TYPE.getLocalName()); } public void writeMap(Map<String,String> map ) throws IOException { openElement("rapla:" + RaplaMap.TYPE.getLocalName()); for (Map.Entry<String,String> entry:map.entrySet()) { String key = entry.getKey(); String obj = entry.getValue(); openTag("rapla:mapentry"); att("key", key.toString()); if ( obj instanceof String) { String value = (String) obj; att("value", value); closeElementTag(); } } closeElement("rapla:" + RaplaMap.TYPE.getLocalName()); } private void printEntityReference(Object key,Object obj) throws RaplaException, IOException { if (obj == null) { getLogger().warn( "Map contains empty value under key " + key ); return; } int start = getIndentLevel(); openTag("rapla:mapentry"); att("key", key.toString()); if ( obj instanceof String) { String value = (String) obj; att("value", value); closeElementTag(); return; } closeTag(); if ( obj instanceof Entity ) { printReference( (Entity) obj); } else { RaplaObject raplaObj = (RaplaObject) obj; getWriterFor( raplaObj.getRaplaType()).writeObject( raplaObj ); } setIndentLevel( start+1 ); closeElement("rapla:mapentry"); setIndentLevel( start ); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import org.rapla.entities.Category; import org.rapla.entities.RaplaObject; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class CategoryWriter extends RaplaXMLWriter { public CategoryWriter(RaplaContext sm) throws RaplaException { super(sm); } public void printRaplaType(RaplaObject type) throws RaplaException, IOException { printCategory( (Category) type); } public void printCategory(Category category) throws IOException,RaplaException { printCategory( category, true); } public void printCategory(Category category,boolean printSubcategories) throws IOException,RaplaException { openTag("rapla:category"); printTimestamp( category); if (isPrintId()) { printId(category); Category parent = category.getParent(); if ( parent != null) { att("parentid", getId( parent)); } } att("key",category.getKey()); closeTag(); printTranslation(category.getName()); printAnnotations( category, false); if ( printSubcategories ) { Category[] categories = category.getCategories(); for (int i=0;i<categories.length;i++) printCategory(categories[i]); } closeElement("rapla:category"); } public void writeObject(RaplaObject persistant) throws RaplaException, IOException { printCategory( (Category) persistant, false); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import org.rapla.components.util.Assert; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.Annotatable; import org.rapla.entities.Category; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.User; import org.rapla.entities.domain.Permission; import org.rapla.entities.domain.ResourceAnnotations; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.domain.internal.PermissionImpl; import org.rapla.entities.storage.internal.ReferenceHandler; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class AllocatableReader extends RaplaXMLReader { private DynAttReader dynAttHandler; private AllocatableImpl allocatable; private String annotationKey; private Annotatable currentAnnotatable; public AllocatableReader( RaplaContext context ) throws RaplaException { super( context ); dynAttHandler = new DynAttReader( context ); addChildHandler( dynAttHandler ); } @Override public void processElement( String namespaceURI, String localName, RaplaSAXAttributes atts ) throws RaplaSAXParseException { if (namespaceURI.equals( DYNATT_NS ) || namespaceURI.equals( EXTENSION_NS )) { if ( localName.equals("rapla:crypto")) { return; } dynAttHandler.setClassifiable( allocatable ); delegateElement( dynAttHandler, namespaceURI, localName, atts ); return; } if (!namespaceURI.equals( RAPLA_NS )) return; if (localName.equals( "permission" )) { PermissionImpl permission = new PermissionImpl(); permission.setResolver( store ); // process user String userString = atts.getValue( "user" ); ReferenceHandler referenceHandler = permission.getReferenceHandler(); if (userString != null) { referenceHandler.putId("user", getId(User.TYPE,userString)); } // process group String groupId = atts.getValue( "groupidref" ); if (groupId != null) { referenceHandler.putId("group", getId(Category.TYPE,groupId)); } else { String groupName = atts.getValue( "group" ); if (groupName != null) { Category group= getGroup( groupName); permission.setGroup( group); } } String startDate = getString( atts, "start-date", null ); if (startDate != null) { permission.setStart( parseDate( startDate, false ) ); } String endDate = getString( atts, "end-date", null ); if (endDate != null) { permission.setEnd( parseDate( endDate, false ) ); } String minAdvance = getString( atts, "min-advance", null ); if (minAdvance != null) { permission.setMinAdvance( parseLong( minAdvance ).intValue() ); } String maxAdvance = getString( atts, "max-advance", null ); if (maxAdvance != null) { permission.setMaxAdvance( parseLong( maxAdvance ).intValue() ); } String accessLevel = getString( atts, "access", Permission.ACCESS_LEVEL_NAMEMAP.get( Permission.ALLOCATE_CONFLICTS ) ); Integer matchingLevel = Permission.ACCESS_LEVEL_NAMEMAP.findAccessLevel( accessLevel ); if (matchingLevel == null) { throw createSAXParseException( "Unknown access level '" + accessLevel + "'" ); } permission.setAccessLevel( matchingLevel ); allocatable.addPermission( permission ); } else if (localName.equals( "annotation" ) ) { annotationKey = atts.getValue( "key" ); Assert.notNull( annotationKey, "key attribute cannot be null" ); startContent(); } else { TimestampDates ts = readTimestamps( atts); allocatable = new AllocatableImpl(ts.createTime, ts.changeTime); allocatable.setResolver( store ); currentAnnotatable = allocatable; setId( allocatable, atts ); // support old holdback conflicts behaviour { String holdBackString = getString( atts, "holdbackconflicts", "false" ); if ( Boolean.valueOf( holdBackString ) ) { try { allocatable.setAnnotation(ResourceAnnotations.KEY_CONFLICT_CREATION, ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE); } catch (IllegalAnnotationException e) { throw createSAXParseException(e.getMessage(),e); } } } setLastChangedBy(allocatable, atts); setOwner(allocatable, atts); } } @Override public void processEnd( String namespaceURI, String localName ) throws RaplaSAXParseException { if (!namespaceURI.equals( RAPLA_NS )) return; if (localName.equals( "resource" ) || localName.equals( "person" ) ) { if (allocatable.getPermissions().length == 0) allocatable.addPermission( new PermissionImpl() ); add( allocatable ); } else if (localName.equals( "extension" ) ) { if ( allocatable.getClassification() != null) { add( allocatable ); } } else if (localName.equals( "annotation" ) ) { try { String annotationValue = readContent().trim(); currentAnnotatable.setAnnotation( annotationKey, annotationValue ); } catch (IllegalAnnotationException ex) { } } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.Map; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; public class PreferenceReader extends RaplaXMLReader { public static final TypedComponentRole<Map<String,RaplaType>> LOCALNAMEMAPENTRY = new TypedComponentRole<Map<String,RaplaType>>("org.rapla.storage.xml.localnameMap"); public static final TypedComponentRole<Map<RaplaType,RaplaXMLReader>> READERMAP = new TypedComponentRole<Map<RaplaType,RaplaXMLReader>>("org.rapla.storage.xml.readerMap"); PreferencesImpl preferences; String configRole; User owner; RaplaXMLReader childReader; String stringValue = null; public PreferenceReader(RaplaContext sm) throws RaplaException { super(sm); } public void setUser( User owner) { this.owner = owner; } @Override public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts) throws RaplaSAXParseException { if ( RAPLA_NS.equals(namespaceURI) && localName.equals("data")) { return; } if (localName.equals("preferences")) { TimestampDates ts = readTimestamps(atts); preferences = new PreferencesImpl(ts.createTime, ts.changeTime); preferences.setResolver( store); if ( owner == null ) { preferences.setId( Preferences.SYSTEM_PREFERENCES_ID); } else { preferences.setOwner( owner ); preferences.setId( Preferences.ID_PREFIX + owner.getId()); } return; } if (localName.equals("entry")) { configRole = getString(atts,"key"); stringValue = getString(atts,"value", null); // ignore old entry if ( stringValue != null) { preferences.putEntryPrivate( configRole,stringValue ); } return; } RaplaType raplaTypeName = getTypeForLocalName(localName ); childReader = getChildHandlerForType( raplaTypeName ); delegateElement(childReader,namespaceURI,localName,atts); } public Preferences getPreferences() { return preferences; } public RaplaObject getChildType() throws RaplaSAXParseException { return childReader.getType(); } @Override public void processEnd(String namespaceURI,String localName) throws RaplaSAXParseException { if (!namespaceURI.equals(RAPLA_NS)) return; if (localName.equals("preferences")) { add(preferences); } if (localName.equals("entry") && stringValue == null) { RaplaObject type = childReader.getType(); preferences.putEntryPrivate(configRole, type); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.configuration.RaplaMap; import org.rapla.entities.configuration.internal.RaplaMapImpl; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class RaplaMapReader extends RaplaXMLReader { String key; RaplaMapImpl entityMap; RaplaXMLReader childReader; public RaplaMapReader(RaplaContext sm) throws RaplaException { super(sm); } @Override public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts) throws RaplaSAXParseException { if ( !RAPLA_NS.equals(namespaceURI)) return; if (localName.equals(RaplaMap.TYPE.getLocalName())) { entityMap = new RaplaMapImpl(); return; } if (localName.equals("mapentry")) { key= getString(atts, "key"); String value = getString( atts, "value", null); if ( value != null) { try { entityMap.putPrivate( key, value ); } catch (ClassCastException ex) { getLogger().error("Mixed maps are currently not supported.", ex); } } return; } String refid = getString( atts, "idref", null); String keyref = getString( atts, "keyref", null); RaplaType raplaType = getTypeForLocalName( localName ); if ( refid != null) { childReader = null; // We ignore the old references from 1.7 if ( entityMap.isTypeSupportedAsLink(raplaType)) { return; } String id = getId( raplaType, refid); entityMap.putIdPrivate( key, id, raplaType); } else if ( keyref != null) { childReader = null; DynamicType type = getDynamicType( keyref ); if ( type != null) { String id = ((Entity) type).getId(); entityMap.putIdPrivate( key, id, DynamicType.TYPE); } } else { childReader = getChildHandlerForType( raplaType ); delegateElement( childReader, namespaceURI, localName, atts); } } @Override public void processEnd(String namespaceURI,String localName) throws RaplaSAXParseException { if ( !RAPLA_NS.equals(namespaceURI) ) return; if ( childReader != null ) { RaplaObject type = childReader.getType(); try { entityMap.putPrivate( key, type); } catch (ClassCastException ex) { getLogger().error("Mixed maps are currently not supported.", ex); } } childReader = null; } public RaplaMap getEntityMap() { return entityMap; } public RaplaObject getType() { //reservation.getReferenceHandler().put() return getEntityMap(); } }
Java
/*--------------------------------------------------------------------------* | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.rapla.components.util.Assert; import org.rapla.components.util.TimeInterval; import org.rapla.entities.Category; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.storage.LocalCache; /** Stores the data from the local cache in XML-format to a print-writer.*/ public class RaplaMainWriter extends RaplaXMLWriter { protected final static String OUTPUT_FILE_VERSION="1.1"; String encoding = "utf-8"; protected LocalCache cache; public RaplaMainWriter(RaplaContext context, LocalCache cache) throws RaplaException { super(context); this.cache = cache; Assert.notNull(cache); } public void setWriter( Appendable writer ) { super.setWriter( writer ); for ( RaplaXMLWriter xmlWriter: writerMap.values()) { xmlWriter.setWriter( writer ); } } public void setEncoding(String encoding) { this.encoding = encoding; } public void printContent() throws IOException,RaplaException { printHeader( 0, null, false ); printCategories(); println(); printDynamicTypes(); println(); ((PreferenceWriter)getWriterFor(Preferences.TYPE)).printPreferences( cache.getPreferencesForUserId( null )); println(); printUsers(); println(); printAllocatables(); println(); printReservations(); println(); closeElement("rapla:data"); } public void printDynamicTypes() throws IOException,RaplaException { openElement("relax:grammar"); DynamicTypeWriter dynamicTypeWriter = (DynamicTypeWriter)getWriterFor(DynamicType.TYPE); for( DynamicType type:cache.getDynamicTypes()) { if ((( DynamicTypeImpl) type).isInternal()) { continue; } dynamicTypeWriter.printDynamicType(type); println(); } printStartPattern(); closeElement("relax:grammar"); } private void printStartPattern() throws IOException { openElement("relax:start"); openElement("relax:choice"); for( DynamicType type:cache.getDynamicTypes()) { if ((( DynamicTypeImpl) type).isInternal()) { continue; } openTag("relax:ref"); att("name",type.getKey()); closeElementTag(); } closeElement("relax:choice"); closeElement("relax:start"); } public void printCategories() throws IOException,RaplaException { openElement("rapla:categories"); CategoryWriter categoryWriter = (CategoryWriter)getWriterFor(Category.TYPE); Category[] categories = cache.getSuperCategory().getCategories(); for (int i=0;i<categories.length;i++) { categoryWriter.printCategory(categories[i]); } closeElement("rapla:categories"); } public void printUsers() throws IOException,RaplaException { openElement("rapla:users"); UserWriter userWriter = (UserWriter)getWriterFor(User.TYPE); println("<!-- Users of the system -->"); for (User user:cache.getUsers()) { String userId = user.getId(); PreferencesImpl preferences = cache.getPreferencesForUserId( userId); String password = cache.getPassword(userId); userWriter.printUser( user, password, preferences); } closeElement("rapla:users"); } public void printAllocatables() throws IOException,RaplaException { openElement("rapla:resources"); println("<!-- resources -->"); // Print all resources that are not persons AllocatableWriter allocatableWriter = (AllocatableWriter)getWriterFor(Allocatable.TYPE); Collection<Allocatable> allAllocatables = cache.getAllocatables(); Map<String,List<Allocatable>> map = new LinkedHashMap<String,List<Allocatable>>(); for (DynamicType type:cache.getDynamicTypes()) { map.put( type.getId(), new ArrayList<Allocatable>()); } for (Allocatable allocatable:allAllocatables) { Classification classification = allocatable.getClassification(); String id = classification.getType().getId(); List<Allocatable> list = map.get( id); list.add( allocatable); } // Print all Persons for ( String id : map.keySet()) { List<Allocatable> list = map.get( id); for (Allocatable allocatable:list) { allocatableWriter.printAllocatable(allocatable); } } println(); closeElement("rapla:resources"); } void printReservations() throws IOException, RaplaException { openElement("rapla:reservations"); ReservationWriter reservationWriter = (ReservationWriter)getWriterFor(Reservation.TYPE); for (Reservation reservation: cache.getReservations()) { reservationWriter.printReservation( reservation ); } closeElement("rapla:reservations"); } private void printHeader(long repositoryVersion, TimeInterval invalidateInterval, boolean resourcesRefresh) throws IOException { println("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?><!--*- coding: " + encoding + " -*-->"); openTag("rapla:data"); for (int i=0;i<NAMESPACE_ARRAY.length;i++) { String prefix = NAMESPACE_ARRAY[i][1]; String uri = NAMESPACE_ARRAY[i][0]; if ( prefix == null) { att("xmlns", uri); } else { att("xmlns:" + prefix, uri); } println(); } att("version", RaplaMainWriter.OUTPUT_FILE_VERSION); if ( repositoryVersion > 0) { att("repositoryVersion", String.valueOf(repositoryVersion)); } if ( resourcesRefresh) { att("resourcesRefresh", "true"); } if ( invalidateInterval != null) { Date startDate = invalidateInterval.getStart(); Date endDate = invalidateInterval.getEnd(); String start; if ( startDate == null) { startDate = new Date(0); } start = dateTimeFormat.formatDate( startDate); att("startDate", start); if ( endDate != null) { String end = dateTimeFormat.formatDate( endDate); att("endDate", end); } } closeTag(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.Date; import org.rapla.entities.RaplaObject; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class ReservationWriter extends ClassifiableWriter { public ReservationWriter(RaplaContext sm) throws RaplaException { super(sm); } protected void printReservation(Reservation r) throws IOException,RaplaException { openTag("rapla:reservation"); printId(r); printOwner(r); printTimestamp(r); closeTag(); printAnnotations( r, false); // System.out.println(((Entity)r).getId() + " Name: " + r.getName() +" User: " + r.getUser()); printClassification(r.getClassification()); { Appointment[] appointments = r.getAppointments(); for (int i = 0; i< appointments.length; i ++) { printAppointment(appointments[i], true); } } Allocatable[] allocatables = r.getAllocatables(); // Print allocatables that dont have a restriction for (int i=0; i< allocatables.length; i ++) { Allocatable allocatable = allocatables[i]; if (r.getRestriction( allocatable ).length > 0 ) { continue; } openTag("rapla:allocate"); printIdRef( allocatable ); closeElementTag(); } closeElement("rapla:reservation"); } public void writeObject( RaplaObject object ) throws IOException, RaplaException { printReservation( (Reservation) object); } public void printAppointment(Appointment appointment, boolean includeAllocations) throws IOException { openTag("rapla:appointment"); // always print the id //if (isPrintId()) { printId( appointment ); //} att("start-date",dateTimeFormat.formatDate( appointment.getStart())); if (appointment.isWholeDaysSet()) { boolean bCut = appointment.getEnd().after(appointment.getStart()); att("end-date",dateTimeFormat.formatDate(appointment.getEnd(),bCut)); } else { att("start-time",dateTimeFormat.formatTime( appointment.getStart())); att("end-date",dateTimeFormat.formatDate( appointment.getEnd())); att("end-time",dateTimeFormat.formatTime( appointment.getEnd())); } Reservation reservation = appointment.getReservation(); Allocatable[] allocatables; if ( reservation != null) { allocatables = reservation.getRestrictedAllocatables(appointment); } else { allocatables = Allocatable.ALLOCATABLE_ARRAY; } if (appointment.getRepeating() == null && allocatables.length == 0) { closeElementTag(); } else { closeTag(); if (appointment.getRepeating() != null) { printRepeating(appointment.getRepeating()); } if ( includeAllocations) { for (int i=0; i< allocatables.length; i ++) { Allocatable allocatable = allocatables[i]; openTag("rapla:allocate"); printIdRef( allocatable ); closeElementTag(); } } closeElement("rapla:appointment"); } } private void printRepeating(Repeating r) throws IOException { openTag("rapla:repeating"); if (r.getInterval()!=1) att("interval",String.valueOf(r.getInterval())); att("type",r.getType().toString()); if (r.isFixedNumber()) { att("number",String.valueOf(r.getNumber())); } else { if (r.getEnd() != null) att("end-date" ,dateTimeFormat.formatDate(r.getEnd(),true)); } Date[] exceptions = r.getExceptions(); if (exceptions.length==0) { closeElementTag(); return; } closeTag(); for (int i=0;i<exceptions.length;i++) { openElement("rapla:exception"); openTag("rapla:date"); att("date",dateTimeFormat.formatDate( exceptions[i])); closeElementTag(); closeElement("rapla:exception"); } closeElement("rapla:repeating"); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import org.rapla.entities.Category; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.RaplaObject; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.domain.Permission; import org.rapla.entities.internal.CategoryImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class UserWriter extends RaplaXMLWriter { public UserWriter(RaplaContext sm) throws RaplaException { super(sm); } public void printUser(User user, String password, Preferences preferences) throws IOException,RaplaException { openTag("rapla:user"); printId(user); printTimestamp( user); att("username",user.getUsername()); if ( password != null ) { att("password",password); } att("name",user.getName()); att("email",user.getEmail()); // Allocatable person = user.getPerson(); // if ( person != null) // { // att("person", person.getId()); // } att("isAdmin",String.valueOf(user.isAdmin())); closeTag(); Category[] groups = user.getGroups(); for ( int i = 0; i < groups.length; i++ ) { Category group = groups[i]; String groupPath = getGroupPath( group ); try { openTag("rapla:group"); att( "key", groupPath ); closeElementTag(); } catch (Exception ex) { getLogger().error(ex.getMessage(), ex); } } if ( preferences != null) { PreferenceWriter preferenceWriter = (PreferenceWriter) getWriterFor(Preferences.TYPE); preferenceWriter.setIndentLevel( getIndentLevel() ); preferenceWriter.printPreferences(preferences); } closeElement("rapla:user"); } public void writeObject(RaplaObject object) throws IOException, RaplaException { printUser( (User) object,null,null); } private String getGroupPath( Category category) throws EntityNotFoundException { Category rootCategory = getSuperCategory().getCategory(Permission.GROUP_CATEGORY_KEY); return ((CategoryImpl) rootCategory ).getPathForCategory(category); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.rapla.components.util.DateTools; import org.rapla.components.util.TimeInterval; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.Category; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Period; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.facade.Conflict; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class RaplaMainReader extends RaplaXMLReader { private Map<String,RaplaXMLReader> localnameTable = new HashMap<String,RaplaXMLReader>(); public final static String INPUT_FILE_VERSION = RaplaMainWriter.OUTPUT_FILE_VERSION; private TimeInterval invalidateInterval = null; private boolean resourcesRefresh = false; public RaplaMainReader( RaplaContext context ) throws RaplaException { super( context ); // Setup the delegation classes localnameTable.put( "grammar", readerMap.get( DynamicType.TYPE ) ); localnameTable.put( "element", readerMap.get( DynamicType.TYPE ) ); localnameTable.put( "user", readerMap.get( User.TYPE ) ); localnameTable.put( "category", readerMap.get( Category.TYPE ) ); localnameTable.put( "preferences", readerMap.get( Preferences.TYPE ) ); localnameTable.put( "resource", readerMap.get( Allocatable.TYPE ) ); localnameTable.put( "person", readerMap.get( Allocatable.TYPE ) ); localnameTable.put( "extension", readerMap.get( Allocatable.TYPE ) ); localnameTable.put( "period", readerMap.get( Period.TYPE ) ); localnameTable.put( "reservation", readerMap.get( Reservation.TYPE ) ); localnameTable.put( "conflict", readerMap.get( Conflict.TYPE ) ); localnameTable.put( "remove", readerMap.get( "remove") ); localnameTable.put( "store", readerMap.get( "store") ); localnameTable.put( "reference", readerMap.get( "reference") ); addChildHandler( readerMap.values() ); } private void addChildHandler( Collection<? extends DelegationHandler> collection ) { Iterator<? extends DelegationHandler> it = collection.iterator(); while (it.hasNext()) addChildHandler( it.next() ); } /** checks the version of the input-file. throws WrongVersionException if the file-version is not supported by the reader. */ private void processHead( String uri, String name, RaplaSAXAttributes atts ) throws RaplaSAXParseException { try { String version = null; getLogger().debug( "Getting version." ); if (name.equals( "data" ) && uri.equals( RAPLA_NS )) { version = atts.getValue( "version" ); if (version == null) throw createSAXParseException( "Could not get Version" ); } String start = atts.getValue( "startDate"); String end = atts.getValue( "endDate"); if ( start != null || end != null) { Date startDate = start!= null ? parseDate(start, false) : null; Date endDate = end!= null ? parseDate(end, true) : null; if ( startDate != null && startDate.getTime() < DateTools.MILLISECONDS_PER_DAY) { startDate = null; } invalidateInterval = new TimeInterval(startDate, endDate); } String resourcesRefresh = atts.getValue( "resourcesRefresh"); if ( resourcesRefresh != null) { this.resourcesRefresh = Boolean.parseBoolean( resourcesRefresh); } if (name.equals( "DATA" )) { version = atts.getValue( "version" ); if (version == null) { version = "0.1"; } } if (version == null) throw createSAXParseException( "Invalid Format. Could not read data." ); if (!version.equals( INPUT_FILE_VERSION )) { double versionNr; try { versionNr = new Double(version).doubleValue(); } catch (NumberFormatException ex) { throw new RaplaException("Invalid version tag (double-value expected)!"); } // get the version number of the data-schema if (versionNr > new Double(RaplaMainReader.INPUT_FILE_VERSION).doubleValue()) throw new RaplaException("This version of Rapla cannot read files with a version-number" + " greater than " + RaplaMainReader.INPUT_FILE_VERSION + ", try out the latest version."); getLogger().warn( "Older version detected. " ); } getLogger().debug( "Found compatible version-number." ); // We've got the right version. We can proceed. } catch (Exception ex) { throw createSAXParseException(ex.getMessage(),ex); } } @Override public void processElement( String namespaceURI, String localName, RaplaSAXAttributes atts ) throws RaplaSAXParseException { if (level == 1) { processHead( namespaceURI, localName, atts ); return; } if ( !namespaceURI.equals(RAPLA_NS) && !namespaceURI.equals(RELAXNG_NS)) { // Ignore unknown namespace return; } // lookup delegation-handler for the localName DelegationHandler handler = localnameTable.get( localName ); // Ignore unknown elements if (handler != null) { delegateElement( handler, namespaceURI, localName, atts ); } } public TimeInterval getInvalidateInterval() { return invalidateInterval; } public boolean isResourcesRefresh() { return resourcesRefresh; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.Stack; import org.rapla.components.util.Assert; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.Annotatable; import org.rapla.entities.Category; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.internal.CategoryImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class CategoryReader extends RaplaXMLReader { MultiLanguageName currentName = null; Annotatable currentAnnotatable = null; String currentLang = null; Stack<CategoryImpl> categoryStack = new Stack<CategoryImpl>(); CategoryImpl superCategory; String annotationKey = null; CategoryImpl lastProcessedCategory = null; boolean readOnlyThisCategory; public CategoryReader( RaplaContext context ) throws RaplaException { super( context ); superCategory = getSuperCategory(); currentName = superCategory.getName(); } public void setReadOnlyThisCategory( boolean enable ) { readOnlyThisCategory = enable; } @Override public void processElement( String namespaceURI, String localName, RaplaSAXAttributes atts ) throws RaplaSAXParseException { if (localName.equals( "category" ) && namespaceURI.equals( RAPLA_NS )) { String key = atts.getValue( "key" ); Assert.notNull( key ); TimestampDates ts = readTimestamps( atts); CategoryImpl category = new CategoryImpl(ts.createTime, ts.changeTime ); category.setKey( key ); currentName = category.getName(); currentAnnotatable = category; if (atts.getValue( "id" )!=null) { setId( category, atts ); } else { setNewId( category ); } if (!readOnlyThisCategory) { if ( !categoryStack.empty() ) { Category parent = categoryStack.peek(); parent.addCategory( category); } else { String parentId = atts.getValue( "parentid"); if ( parentId!= null) { if (parentId.equals(Category.SUPER_CATEGORY_ID)) { if ( !superCategory.isReadOnly()) { superCategory.addCategory( category); } category.putEntity("parent", superCategory); } else { String parentIdN = getId( Category.TYPE, parentId); category.putId("parent", parentIdN); } } else { if (atts.getValue( "id" )==null) { superCategory.addCategory( category); } else { // It is the super categorycategory.getReferenceHandler().put("parent", superCategory); } } } } categoryStack.push( category ); /* Category test = category; String output = ""; while (test != null) { output = "/" + test.getKey() + output; test = test.getParent(); } // System.out.println("Storing category " + output ); */ } if (localName.equals( "name" ) && namespaceURI.equals( ANNOTATION_NS )) { startContent(); currentLang = atts.getValue( "lang" ); Assert.notNull( currentLang ); } if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS )) { annotationKey = atts.getValue( "key" ); Assert.notNull( annotationKey, "key attribute cannot be null" ); startContent(); } } @Override public void processEnd( String namespaceURI, String localName ) throws RaplaSAXParseException { if (localName.equals( "category" )) { // Test Namespace uris here for possible xerces bug if (namespaceURI.equals( "" )) { throw createSAXParseException( " category namespace empty. Possible Xerces Bug. Download a newer version of xerces." ); } CategoryImpl category = categoryStack.pop(); setCurrentTranslations( category.getName()); if (!readOnlyThisCategory) { add( category ); } lastProcessedCategory = category; } else if (localName.equals( "name" ) && namespaceURI.equals( ANNOTATION_NS )) { String translation = readContent(); currentName.setName( currentLang, translation ); } else if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS )) { try { String annotationValue = readContent().trim(); currentAnnotatable.setAnnotation( annotationKey, annotationValue ); } catch (IllegalAnnotationException ex) { } } } public CategoryImpl getCurrentCategory() { return lastProcessedCategory; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.Date; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.domain.Permission; import org.rapla.entities.domain.internal.AllocatableImpl; import org.rapla.entities.dynamictype.Classification; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.storage.StorageOperator; public class PeriodReader extends DynAttReader { public PeriodReader(RaplaContext context) throws RaplaException { super(context); } static int idCount = 0 ; @Override public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts) throws RaplaSAXParseException { if (namespaceURI.equals(RAPLA_NS) && localName.equals("period")) { AllocatableImpl period = new AllocatableImpl(new Date(), new Date()); Classification classification = store.getDynamicType(StorageOperator.PERIOD_TYPE).newClassification(); classification.setValue("name", getString(atts,"name")); classification.setValue("start",parseDate(getString(atts,"start"),false)); classification.setValue("end",parseDate(getString(atts,"end"),true)); period.setClassification( classification); Permission newPermission = period.newPermission(); newPermission.setAccessLevel( Permission.READ); period.addPermission( newPermission); String id = atts.getValue("id"); if ( id != null) { period.setId(id); } else { period.setId("period_"+idCount); idCount++; } add(period); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.Date; import org.rapla.entities.Category; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.RaplaObject; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.internal.CategoryImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; /** Stores the data from the local cache in XML-format to a print-writer.*/ public class DynamicTypeWriter extends RaplaXMLWriter { public DynamicTypeWriter(RaplaContext sm) throws RaplaException { super(sm); } public void printDynamicType(DynamicType type) throws IOException,RaplaException { openTag("relax:define"); att("name",type.getKey()); closeTag(); openTag("relax:element"); att("name","dynatt:" + type.getKey()); if (isPrintId()) { att("id",getId(type)); } printTimestamp( type ); closeTag(); printTranslation(type.getName()); printAnnotations(type); Attribute att[] = type.getAttributes(); for (int i = 0; i< att.length; i ++) { printAttribute(att[i]); } closeElement("relax:element"); closeElement("relax:define"); } public void writeObject(RaplaObject type) throws IOException, RaplaException { printDynamicType( (DynamicType) type ); } private String getCategoryPath( Category category) throws EntityNotFoundException { Category rootCategory = getSuperCategory(); if ( category != null && rootCategory.equals( category) ) { return ""; } return ((CategoryImpl) rootCategory ).getPathForCategory(category); } protected void printAttribute(Attribute attribute) throws IOException,RaplaException { if (attribute.isOptional()) openElement("relax:optional"); openTag("relax:element"); att("name",attribute.getKey()); // if (isPrintId()) // att("id",getId(attribute)); AttributeType type = attribute.getType(); closeTag(); printTranslation( attribute.getName() ); printAnnotations( attribute ); String[] constraintKeys = attribute.getConstraintKeys(); openTag("relax:data"); att("type", type.toString()); closeElementTag(); for (int i = 0; i<constraintKeys.length; i++ ) { String key = constraintKeys[i]; Object constraint = attribute.getConstraint( key ); // constraint not set if (constraint == null) continue; openTag("rapla:constraint"); att("name", key ); closeTagOnLine(); if ( constraint instanceof Category) { Category category = (Category) constraint; print( getCategoryPath( category ) ); } else if ( constraint instanceof DynamicType) { DynamicType dynamicType = (DynamicType) constraint; print( dynamicType.getKey() ); } else if ( constraint instanceof Date) { final String formatDate = dateTimeFormat.formatDate( (Date) constraint); print( formatDate); } else { print( constraint.toString()); } closeElementOnLine("rapla:constraint"); println(); } Object defaultValue = attribute.defaultValue(); if ( defaultValue != null) { openTag("rapla:default"); closeTagOnLine(); if ( defaultValue instanceof Category) { Category category = (Category) defaultValue; print( getCategoryPath( category ) ); } else if ( defaultValue instanceof Date) { final String formatDate = dateTimeFormat.formatDate( (Date) defaultValue); print( formatDate); } else { print( defaultValue.toString()); } closeElementOnLine("rapla:default"); println(); } closeElement("relax:element"); if (attribute.isOptional()) closeElement("relax:optional"); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.components.util.xml.XMLWriter; import org.rapla.entities.Annotatable; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.Ownable; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.Timestamp; import org.rapla.entities.User; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.ConstraintIds; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.internal.CategoryImpl; import org.rapla.framework.Provider; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; /** Stores the data from the local cache in XML-format to a print-writer.*/ abstract public class RaplaXMLWriter extends XMLWriter implements Namespaces { //protected NamespaceSupport namespaceSupport = new NamespaceSupport(); private boolean isPrintId; private Map<String,RaplaType> localnameMap; Logger logger; Map<RaplaType,RaplaXMLWriter> writerMap; protected RaplaContext context; protected SerializableDateTimeFormat dateTimeFormat = SerializableDateTimeFormat.INSTANCE; Provider<Category> superCategory; public RaplaXMLWriter( RaplaContext context) throws RaplaException { this.context = context; enableLogging( context.lookup( Logger.class)); this.writerMap =context.lookup( PreferenceWriter.WRITERMAP ); this.localnameMap = context.lookup(PreferenceReader.LOCALNAMEMAPENTRY); this.isPrintId = context.has(IOContext.PRINTID); this.superCategory = context.lookup( IOContext.SUPERCATEGORY); // namespaceSupport.pushContext(); // for (int i=0;i<NAMESPACE_ARRAY.length;i++) { // String prefix = NAMESPACE_ARRAY[i][1]; // String uri = NAMESPACE_ARRAY[i][0]; // if ( prefix != null) { // namespaceSupport.declarePrefix(prefix, uri); // } // } } public Category getSuperCategory() { return superCategory.get(); } public void enableLogging(Logger logger) { this.logger = logger; } protected Logger getLogger() { return logger; } protected void printTimestamp(Timestamp stamp) throws IOException { final Date createTime = stamp.getCreateTime(); final Date lastChangeTime = stamp.getLastChanged(); if ( createTime != null) { att("created-at", SerializableDateTimeFormat.INSTANCE.formatTimestamp( createTime)); } if ( lastChangeTime != null) { att("last-changed", SerializableDateTimeFormat.INSTANCE.formatTimestamp( lastChangeTime)); } User user = stamp.getLastChangedBy(); if ( user != null) { att("last-changed-by", getId(user)); } } protected void printTranslation(MultiLanguageName name) throws IOException { Iterator<String> it= name.getAvailableLanguages().iterator(); while (it.hasNext()) { String lang = it.next(); String value = name.getName(lang); openTag("doc:name"); att("lang",lang); closeTagOnLine(); printEncode(value); closeElementOnLine("doc:name"); println(); } } protected void printAnnotations(Annotatable annotatable, boolean includeTags) throws IOException{ String[] keys = annotatable.getAnnotationKeys(); if ( keys.length == 0 ) return; if ( includeTags) { openElement("doc:annotations"); } for (String key:keys) { String value = annotatable.getAnnotation(key); openTag("rapla:annotation"); att("key", key); closeTagOnLine(); printEncode(value); closeElementOnLine("rapla:annotation"); println(); } if ( includeTags) { closeElement("doc:annotations"); } } protected void printAnnotations(Annotatable annotatable) throws IOException{ printAnnotations(annotatable, true); } protected void printAttributeValue(Attribute attribute, Object value) throws IOException,RaplaException { if ( value == null) { return; } AttributeType type = attribute.getType(); if (type.equals(AttributeType.ALLOCATABLE)) { print(getId((Entity)value)); } else if (type.equals(AttributeType.CATEGORY)) { CategoryImpl rootCategory = (CategoryImpl) attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY); if ( !(value instanceof Category)) { throw new RaplaException("Wrong attribute value Category expected but was " + value.getClass()); } Category categoryValue = (Category)value; if (rootCategory == null) { getLogger().error("root category missing for attriubte " + attribute); } else { String keyPathString = getKeyPath(rootCategory, categoryValue); print( keyPathString); } } else if (type.equals(AttributeType.DATE) ) { final Date date; if ( value instanceof Date) date = (Date)value; else date = null; printEncode( dateTimeFormat.formatDate( date ) ); } else { printEncode( value.toString() ); } } private String getKeyPath(CategoryImpl rootCategory, Category categoryValue) throws EntityNotFoundException { List<String> pathForCategory = rootCategory.getPathForCategory(categoryValue, true ); String keyPathString = CategoryImpl.getKeyPathString(pathForCategory); return keyPathString; } protected void printOwner(Ownable obj) throws IOException { User user = obj.getOwner(); if (user == null) return; att("owner", getId(user)); } protected void printReference(Entity entity) throws IOException, EntityNotFoundException { String localName = entity.getRaplaType().getLocalName(); openTag("rapla:" + localName); if ( entity.getRaplaType() == DynamicType.TYPE ) { att("keyref", ((DynamicType)entity).getKey()); } else if ( entity.getRaplaType() == Category.TYPE && !isPrintId()) { String path = getKeyPath( (CategoryImpl)getSuperCategory(), (Category) entity); att("keyref", path); } else { att("idref",getId( entity)); } closeElementTag(); } protected String getId(Entity entity) { Comparable id2 = entity.getId(); return id2.toString(); } protected RaplaXMLWriter getWriterFor(RaplaType raplaType) throws RaplaException { RaplaXMLWriter writer = writerMap.get(raplaType); if ( writer == null) { throw new RaplaException("No writer for type " + raplaType); } writer.setIndentLevel( getIndentLevel()); writer.setWriter( getWriter()); return writer; } protected void printId(Entity entity) throws IOException { att("id", getId( entity )); } protected void printIdRef(Entity entity) throws IOException { att("idref", getId( entity ) ); } /** Returns if the ids should be saved, even when keys are * available. */ public boolean isPrintId() { return isPrintId; } /** * @throws IOException */ public void writeObject(@SuppressWarnings("unused") RaplaObject object) throws IOException, RaplaException { throw new RaplaException("Method not implemented by subclass " + this.getClass().getName()); } public String getLocalNameForType(RaplaType raplaType) throws RaplaException{ for (Iterator<Map.Entry<String,RaplaType>> it = localnameMap.entrySet().iterator();it.hasNext();) { Map.Entry<String,RaplaType> entry =it.next(); if (entry.getValue().equals( raplaType)) { return entry.getKey(); } } throw new RaplaException("No writer declared for Type " + raplaType ); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.io.IOException; import java.util.Collection; import java.util.Map; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.RaplaMap; import org.rapla.entities.configuration.internal.CalendarModelConfigurationImpl; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class RaplaCalendarSettingsWriter extends ClassificationFilterWriter { /** * @param sm * @throws RaplaException */ public RaplaCalendarSettingsWriter(RaplaContext sm) throws RaplaException { super(sm); } public void writeObject(RaplaObject type) throws IOException, RaplaException { CalendarModelConfigurationImpl calendar = (CalendarModelConfigurationImpl) type ; openTag("rapla:" + CalendarModelConfiguration.TYPE.getLocalName()); att("title", calendar.getTitle()); att("view", calendar.getView()); Map<String,String> extensionMap = calendar.getOptionMap(); final String saveDate = extensionMap != null ? extensionMap.get( CalendarModel.SAVE_SELECTED_DATE) : "false" ; boolean saveDateActive = saveDate != null && saveDate.equals("true"); if ( calendar.getSelectedDate() != null && saveDateActive) { att("date", dateTimeFormat.formatDate( calendar.getSelectedDate())); } if ( calendar.getStartDate() != null && saveDateActive) { att("startdate", dateTimeFormat.formatDate( calendar.getStartDate())); } if ( calendar.getEndDate() != null && saveDateActive) { att("enddate", dateTimeFormat.formatDate( calendar.getEndDate())); } if ( calendar.isResourceRootSelected()) { att("rootSelected","true"); } closeTag(); Collection<Entity> selectedObjects = calendar.getSelected(); if (selectedObjects != null && selectedObjects.size() > 0) { openElement("selected"); for ( Entity entity:selectedObjects) { printReference( entity); } closeElement("selected"); } if (extensionMap != null && extensionMap.size() > 0) { openElement("options"); RaplaMapWriter writer = (RaplaMapWriter)getWriterFor( RaplaMap.TYPE); writer.writeMap( extensionMap); closeElement("options"); } ClassificationFilter[] filter =calendar.getFilter() ; if ( filter.length> 0) { openElement("filter"); for (ClassificationFilter f:filter) { final DynamicType dynamicType = f.getType(); final String annotation = dynamicType.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE); boolean eventType = annotation != null && annotation.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION); if (( eventType && !calendar.isDefaultEventTypes()) || (!eventType && !calendar.isDefaultResourceTypes()) ) { printClassificationFilter( f ); } } closeElement("filter"); } closeElement("rapla:" + CalendarModelConfiguration.TYPE.getLocalName()); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import java.util.Date; import org.rapla.components.util.Assert; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.Annotatable; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.RepeatingType; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class ReservationReader extends RaplaXMLReader { ReservationImpl reservation; private String allocatableId = null; private AppointmentImpl appointment = null; private Repeating repeating = null; private DynAttReader dynAttHandler; private String annotationKey; private Annotatable currentAnnotatable; public ReservationReader( RaplaContext context) throws RaplaException { super( context); dynAttHandler = new DynAttReader( context); addChildHandler(dynAttHandler); } @Override public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts) throws RaplaSAXParseException { if (namespaceURI.equals( DYNATT_NS ) || namespaceURI.equals( EXTENSION_NS )) { dynAttHandler.setClassifiable(reservation); delegateElement(dynAttHandler,namespaceURI,localName,atts); return; } if (!namespaceURI.equals(RAPLA_NS)) return; if ( localName.equals( "reservation" ) ) { TimestampDates ts = readTimestamps( atts); reservation = new ReservationImpl( ts.createTime, ts.changeTime ); reservation.setResolver( store ); currentAnnotatable = reservation; setId(reservation, atts); setLastChangedBy( reservation, atts); setOwner(reservation, atts); } if (localName.equals("appointment")) { String id = atts.getValue("id"); String startDate=atts.getValue("start-date"); String endDate= atts.getValue("end-date"); if (endDate == null) endDate = startDate; String startTime = atts.getValue("start-time"); String endTime = atts.getValue("end-time"); Date start; Date end; if (startTime != null && endTime != null) { start = parseDateTime(startDate,startTime); end = parseDateTime(endDate,endTime); } else { start = parseDate(startDate,false); end = parseDate(endDate,true); } appointment= new AppointmentImpl(start,end); appointment.setWholeDays(startTime== null && endTime==null); if (id!=null) { setId(appointment, atts); } else { setNewId(appointment); } addAppointment(appointment); } if (localName.equals("repeating")) { String type =atts.getValue("type"); String interval =atts.getValue("interval"); String enddate =atts.getValue("end-date"); String number =atts.getValue("number"); appointment.setRepeatingEnabled(true); repeating = appointment.getRepeating(); repeating.setType( RepeatingType.findForString( type)); if (interval != null) { repeating.setInterval(Integer.valueOf(interval).intValue()); } if (enddate != null) { repeating.setEnd(parseDate(enddate,true)); } else if (number != null) { repeating.setNumber(Integer.valueOf(number).intValue()); } else { repeating.setEnd(null); } /* if (getLogger().enabled(6)) getLogger().log(6, "Repeating " + repeating.toString() ); */ } if (localName.equals("allocate")) { String id = getString( atts, "idref" ); allocatableId = getId( Allocatable.TYPE, id); reservation.addId("resources", allocatableId ); if ( appointment != null ) { reservation.addRestrictionForId( allocatableId, appointment.getId()); } } if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS )) { annotationKey = atts.getValue( "key" ); Assert.notNull( annotationKey, "key attribute cannot be null" ); startContent(); } if (localName.equals("exception")) { } if (localName.equals("date")) { String dateString =atts.getValue("date"); if (dateString != null && repeating != null) repeating.addException(parseDate(dateString,false)); } } protected void addAppointment(Appointment appointment) { reservation.addAppointment(appointment); } @Override public void processEnd(String namespaceURI,String localName) throws RaplaSAXParseException { if (!namespaceURI.equals(RAPLA_NS)) return; if (localName.equals("appointment") && appointment != null ) { add(appointment); appointment = null; } if (localName.equals("reservation")) { add(reservation); } if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS )) { try { String annotationValue = readContent().trim(); currentAnnotatable.setAnnotation( annotationKey, annotationValue ); } catch (IllegalAnnotationException ex) { } } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.storage.xml; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.entities.Category; import org.rapla.entities.internal.UserImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class UserReader extends RaplaXMLReader { UserImpl user; PreferenceReader preferenceHandler; public UserReader( RaplaContext context ) throws RaplaException { super( context ); preferenceHandler = new PreferenceReader( context ); addChildHandler( preferenceHandler ); } @Override public void processElement( String namespaceURI, String localName, RaplaSAXAttributes atts ) throws RaplaSAXParseException { if (!namespaceURI.equals( RAPLA_NS )) return; if (localName.equals( "user" )) { TimestampDates ts = readTimestamps( atts); user = new UserImpl(ts.createTime, ts.changeTime); String id = setId( user, atts ); // String idString = getString(atts, "person",null); // if ( idString != null) // { // String personId = getId(Allocatable.TYPE,idString); // user.putId("person",personId); // } user.setUsername( getString( atts, "username", "" ) ); user.setName( getString( atts, "name", "" ) ); user.setEmail( getString( atts, "email", "" ) ); user.setAdmin( getString( atts, "isAdmin", "false" ).equals( "true" ) ); String password = getString( atts, "password", null ); preferenceHandler.setUser( user ); if ( password != null) { putPassword( id, password ); } } if (localName.equals( "group" )) { String groupId = atts.getValue( "idref" ); if (groupId !=null) { String newGroupId = getId(Category.TYPE, groupId); user.addId("groups",newGroupId); } else { String groupKey = getString( atts, "key" ); Category group = getGroup( groupKey); if (group != null) { user.addGroup( group ); } } } if (localName.equals( "preferences" )) { delegateElement( preferenceHandler, namespaceURI, localName, atts ); } } @Override public void processEnd( String namespaceURI, String localName ) throws RaplaSAXParseException { if (!namespaceURI.equals( RAPLA_NS )) return; if (localName.equals( "user" )) { preferenceHandler.setUser( null ); add( user ); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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"} }; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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"); } }
Java
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; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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 ); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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); } } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, of which license fullfill the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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; } }
Java
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")); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, of which license fullfill the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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; }
Java
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); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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(); } }
Java
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; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; 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); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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"); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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"); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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"); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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; } } }); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; 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); } }
Java
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(); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; 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(); } }
Java
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 )); } }
Java
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); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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() ); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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")); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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 ); } }
Java
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()); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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()); } }
Java
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"; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; 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; } }
Java
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"); } }
Java
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(); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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) { } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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 ); } }
Java
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()); } }
Java
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; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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 ); } } }
Java
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 ); } } }
Java
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); } }
Java
/*--------------------------------------------------------------------------* | 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)); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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); } }
Java
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); } }
Java
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]); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; 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); } */ }
Java
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); } } }
Java
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) { } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; 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()); } } }
Java
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; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.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)); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.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); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.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(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.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)); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.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 } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.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); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.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; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.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")); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.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); } }
Java