code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
// Copyright 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.client.event;
import org.rapla.rest.gwtjsonrpc.client.JsonUtil;
import org.rapla.rest.gwtjsonrpc.client.impl.JsonCall;
/** Event received by {@link RpcStartHandler} */
public class RpcStartEvent extends BaseRpcEvent<RpcStartHandler> {
private static Type<RpcStartHandler> TYPE;
private static RpcStartEvent INSTANCE;
/**
* Fires a RpcStartEvent.
* <p>
* For internal use only.
*
* @param eventData
*/
@SuppressWarnings("rawtypes")
public static void fire(Object eventData) {
assert eventData instanceof JsonCall : "For internal use only";
if (TYPE != null) { // If we have a TYPE, we have an INSTANCE.
INSTANCE.call = (JsonCall) eventData;
JsonUtil.fireEvent(INSTANCE);
}
}
/**
* Gets the type associated with this event.
*
* @return returns the event type
*/
public static Type<RpcStartHandler> getType() {
if (TYPE == null) {
TYPE = new Type<RpcStartHandler>();
INSTANCE = new RpcStartEvent();
}
return TYPE;
}
private RpcStartEvent() {
// Do nothing
}
@Override
public Type<RpcStartHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(final RpcStartHandler handler) {
handler.onRpcStart(this);
}
@Override
protected void kill() {
super.kill();
call = null;
}
}
| Java |
// Copyright 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.client.event;
import com.google.gwt.event.shared.EventHandler;
/** Handler to receive notifications on RPC has finished. */
public interface RpcCompleteHandler extends EventHandler {
/** Invoked when an RPC call completes. */
public void onRpcComplete(RpcCompleteEvent event);
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.rebind;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.TypeOracle;
/**
* Generates proxy implementations of RemoteJsonService.
*/
public class RemoteJsonServiceProxyGenerator extends Generator {
@Override
public String generate(final TreeLogger logger, final GeneratorContext ctx,
final String requestedClass) throws UnableToCompleteException {
final TypeOracle typeOracle = ctx.getTypeOracle();
assert (typeOracle != null);
final JClassType remoteService = typeOracle.findType(requestedClass);
if (remoteService == null) {
logger.log(TreeLogger.ERROR, "Unable to find metadata for type '"
+ requestedClass + "'", null);
throw new UnableToCompleteException();
}
// WebService annotation = remoteService.getAnnotation( javax.jws.WebService.class);
// if (annotation == null)
// {
// return null;
// }
if (remoteService.isInterface() == null) {
logger.log(TreeLogger.ERROR, remoteService.getQualifiedSourceName()
+ " is not an interface", null);
throw new UnableToCompleteException();
}
ProxyCreator proxyCreator = new ProxyCreator(remoteService);
TreeLogger proxyLogger =
logger.branch(TreeLogger.DEBUG,
"Generating client proxy for remote service interface '"
+ remoteService.getQualifiedSourceName() + "'", null);
return proxyCreator.create(proxyLogger, ctx);
}
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.rebind;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.rapla.rest.gwtjsonrpc.client.impl.JsonSerializer;
import org.rapla.rest.gwtjsonrpc.client.impl.ser.EnumSerializer;
import org.rapla.rest.gwtjsonrpc.client.impl.ser.JavaLangString_JsonSerializer;
import org.rapla.rest.gwtjsonrpc.client.impl.ser.JavaUtilDate_JsonSerializer;
import org.rapla.rest.gwtjsonrpc.client.impl.ser.ListSerializer;
import org.rapla.rest.gwtjsonrpc.client.impl.ser.ObjectArraySerializer;
import org.rapla.rest.gwtjsonrpc.client.impl.ser.ObjectMapSerializer;
import org.rapla.rest.gwtjsonrpc.client.impl.ser.ObjectSerializer;
import org.rapla.rest.gwtjsonrpc.client.impl.ser.PrimitiveArraySerializer;
import org.rapla.rest.gwtjsonrpc.client.impl.ser.SetSerializer;
import org.rapla.rest.gwtjsonrpc.client.impl.ser.StringMapSerializer;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JField;
import com.google.gwt.core.ext.typeinfo.JPackage;
import com.google.gwt.core.ext.typeinfo.JPrimitiveType;
import com.google.gwt.core.ext.typeinfo.JType;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;
class SerializerCreator {
private static final String SER_SUFFIX = "_JsonSerializer";
private static final Comparator<JField> FIELD_COMP =
new Comparator<JField>() {
@Override
public int compare(final JField o1, final JField o2) {
return o1.getName().compareTo(o2.getName());
}
};
private static final HashMap<String, String> defaultSerializers;
private static final HashMap<String, String> parameterizedSerializers;
static {
defaultSerializers = new HashMap<String, String>();
parameterizedSerializers = new HashMap<String, String>();
defaultSerializers.put(java.lang.String.class.getCanonicalName(),
JavaLangString_JsonSerializer.class.getCanonicalName());
defaultSerializers.put(java.util.Date.class.getCanonicalName(),
JavaUtilDate_JsonSerializer.class.getCanonicalName());
// defaultSerializers.put(java.sql.Date.class.getCanonicalName(),
// JavaSqlDate_JsonSerializer.class.getCanonicalName());
// defaultSerializers.put(java.sql.Timestamp.class.getCanonicalName(),
// JavaSqlTimestamp_JsonSerializer.class.getCanonicalName());
parameterizedSerializers.put(java.util.List.class.getCanonicalName(),
ListSerializer.class.getCanonicalName());
parameterizedSerializers.put(java.util.Map.class.getCanonicalName(),
ObjectMapSerializer.class.getCanonicalName());
parameterizedSerializers.put(java.util.Set.class.getCanonicalName(),
SetSerializer.class.getCanonicalName());
}
private final HashMap<String, String> generatedSerializers;
private final GeneratorContext context;
private JClassType targetType;
SerializerCreator(final GeneratorContext c) {
context = c;
generatedSerializers = new HashMap<String, String>();
}
String create(final JClassType targetType, final TreeLogger logger)
throws UnableToCompleteException {
if (targetType.isParameterized() != null || targetType.isArray() != null) {
ensureSerializersForTypeParameters(logger, targetType);
}
String sClassName = serializerFor(targetType);
if (sClassName != null) {
return sClassName;
}
checkCanSerialize(logger, targetType, true);
recursivelyCreateSerializers(logger, targetType);
this.targetType = targetType;
final SourceWriter srcWriter = getSourceWriter(logger, context);
final String sn = getSerializerQualifiedName(targetType);
if (!generatedSerializers.containsKey(targetType.getQualifiedSourceName())) {
generatedSerializers.put(targetType.getQualifiedSourceName(), sn);
}
if (srcWriter == null) {
return sn;
}
if (!targetType.isAbstract()) {
generateSingleton(srcWriter);
}
if (targetType.isEnum() != null) {
generateEnumFromJson(srcWriter);
} else {
generateInstanceMembers(srcWriter);
generatePrintJson(srcWriter);
generateFromJson(srcWriter);
generateGetSets(srcWriter);
}
srcWriter.commit(logger);
return sn;
}
private void recursivelyCreateSerializers(final TreeLogger logger,
final JType targetType) throws UnableToCompleteException {
if (targetType.isPrimitive() != null || isBoxedPrimitive(targetType)) {
return;
}
final JClassType targetClass = targetType.isClass();
if (needsSuperSerializer(targetClass)) {
create(targetClass.getSuperclass(), logger);
}
for (final JField f : sortFields(targetClass)) {
ensureSerializer(logger, f.getType());
}
}
Set<JClassType> createdType = new HashSet<JClassType>();
private void ensureSerializer(final TreeLogger logger, final JType type)
throws UnableToCompleteException {
if (ensureSerializersForTypeParameters(logger, type)) {
return;
}
final String qsn = type.getQualifiedSourceName();
if (defaultSerializers.containsKey(qsn)
|| parameterizedSerializers.containsKey(qsn)) {
return;
}
JClassType type2 = (JClassType) type;
if ( createdType.contains( type2))
{
return;
}
createdType.add( type2 );
create(type2, logger);
}
private boolean ensureSerializersForTypeParameters(final TreeLogger logger,
final JType type) throws UnableToCompleteException {
if (isJsonPrimitive(type) || isBoxedPrimitive(type)) {
return true;
}
if (type.isArray() != null) {
ensureSerializer(logger, type.isArray().getComponentType());
return true;
}
if (type.isParameterized() != null) {
for (final JClassType t : type.isParameterized().getTypeArgs()) {
ensureSerializer(logger, t);
}
}
return false;
}
void checkCanSerialize(final TreeLogger logger, final JType type)
throws UnableToCompleteException {
checkCanSerialize(logger, type, false);
}
Set<JClassType> checkedType = new HashSet<JClassType>();
void checkCanSerialize(final TreeLogger logger, final JType type,
boolean allowAbstractType) throws UnableToCompleteException {
if (type.isPrimitive() == JPrimitiveType.LONG) {
logger.log(TreeLogger.ERROR,
"Type 'long' not supported in JSON encoding", null);
throw new UnableToCompleteException();
}
// if (type.isPrimitive() == JPrimitiveType.VOID) {
// logger.log(TreeLogger.ERROR,
// "Type 'void' not supported in JSON encoding", null);
// throw new UnableToCompleteException();
// }
final String qsn = type.getQualifiedSourceName();
if (type.isEnum() != null) {
return;
}
if (isJsonPrimitive(type) || isBoxedPrimitive(type)) {
return;
}
if (type.isArray() != null) {
final JType leafType = type.isArray().getLeafType();
if (leafType.isPrimitive() != null || isBoxedPrimitive(leafType)) {
if (type.isArray().getRank() != 1) {
logger.log(TreeLogger.ERROR, "gwtjsonrpc does not support "
+ "(de)serializing of multi-dimensional arrays of primitves");
// To work around this, we would need to generate serializers for
// them, this can be considered a todo
throw new UnableToCompleteException();
} else
// Rank 1 arrays work fine.
return;
}
checkCanSerialize(logger, type.isArray().getComponentType());
return;
}
if (defaultSerializers.containsKey(qsn)) {
return;
}
if (type.isParameterized() != null) {
final JClassType[] typeArgs = type.isParameterized().getTypeArgs();
for (final JClassType t : typeArgs) {
checkCanSerialize(logger, t);
}
if (parameterizedSerializers.containsKey(qsn)) {
return;
}
} else if (parameterizedSerializers.containsKey(qsn)) {
logger.log(TreeLogger.ERROR,
"Type " + qsn + " requires type paramter(s)", null);
throw new UnableToCompleteException();
}
if (qsn.startsWith("java.") || qsn.startsWith("javax.")) {
logger.log(TreeLogger.ERROR, "Standard type " + qsn
+ " not supported in JSON encoding", null);
throw new UnableToCompleteException();
}
if (type.isInterface() != null ) {
logger.log(TreeLogger.ERROR, "Interface " + qsn
+ " not supported in JSON encoding", null);
throw new UnableToCompleteException();
}
final JClassType ct = (JClassType) type;
if ( checkedType.contains( ct))
{
return;
}
checkedType.add( ct );
if (ct.isAbstract() && !allowAbstractType) {
logger.log(TreeLogger.ERROR, "Abstract type " + qsn
+ " not supported here", null);
throw new UnableToCompleteException();
}
for (final JField f : sortFields(ct)) {
final TreeLogger branch =
logger.branch(TreeLogger.DEBUG, "In type " + qsn + ", field "
+ f.getName());
checkCanSerialize(branch, f.getType());
}
}
String serializerFor(final JType t) {
if (t.isArray() != null) {
final JType componentType = t.isArray().getComponentType();
if (componentType.isPrimitive() != null
|| isBoxedPrimitive(componentType))
return PrimitiveArraySerializer.class.getCanonicalName();
else
return ObjectArraySerializer.class.getCanonicalName() + "<"
+ componentType.getQualifiedSourceName() + ">";
}
if (isStringMap(t)) {
return StringMapSerializer.class.getName();
}
final String qsn = t.getQualifiedSourceName();
if (defaultSerializers.containsKey(qsn)) {
return defaultSerializers.get(qsn);
}
if (parameterizedSerializers.containsKey(qsn)) {
return parameterizedSerializers.get(qsn);
}
return generatedSerializers.get(qsn);
}
private boolean isStringMap(final JType t) {
return t.isParameterized() != null
&& t.getErasedType().isClassOrInterface() != null
&& t.isParameterized().getTypeArgs().length > 0
&& t.isParameterized().getTypeArgs()[0].getQualifiedSourceName()
.equals(String.class.getName())
&& t.getErasedType().isClassOrInterface().isAssignableTo(
context.getTypeOracle().findType(Map.class.getName()));
}
private void generateSingleton(final SourceWriter w) {
w.print("public static final ");
w.print(getSerializerSimpleName());
w.print(" INSTANCE = new ");
w.print(getSerializerSimpleName());
w.println("();");
w.println();
}
private void generateInstanceMembers(final SourceWriter w) {
for (final JField f : sortFields(targetType)) {
final JType ft = f.getType();
if (needsTypeParameter(ft)) {
final String serType = serializerFor(ft);
w.print("private final ");
w.print(serType);
w.print(" ");
w.print("ser_" + f.getName());
w.print(" = ");
generateSerializerReference(ft, w);
w.println(";");
}
}
w.println();
}
void generateSerializerReference(final JType type, final SourceWriter w) {
String serializerFor = serializerFor(type);
if (type.isArray() != null) {
final JType componentType = type.isArray().getComponentType();
if (componentType.isPrimitive() != null
|| isBoxedPrimitive(componentType)) {
w.print(PrimitiveArraySerializer.class.getCanonicalName());
w.print(".INSTANCE");
} else {
w.print("new " + serializerFor + "(");
generateSerializerReference(componentType, w);
w.print(")");
}
} else if (needsTypeParameter(type)) {
w.print("new " + serializerFor + "(");
final JClassType[] typeArgs = type.isParameterized().getTypeArgs();
int n = 0;
if (isStringMap(type)) {
n++;
}
boolean first = true;
for (; n < typeArgs.length; n++) {
if (first) {
first = false;
} else {
w.print(", ");
}
generateSerializerReference(typeArgs[n], w);
}
w.print(")");
} else {
w.print(serializerFor + ".INSTANCE");
}
}
private void generateGetSets(final SourceWriter w) {
for (final JField f : sortFields(targetType)) {
if (f.isPrivate()) {
w.print("private static final native ");
w.print(f.getType().getQualifiedSourceName());
w.print(" objectGet_" + f.getName());
w.print("(");
w.print(targetType.getQualifiedSourceName() + " instance");
w.print(")");
w.println("/*-{ ");
w.indent();
w.print("return instance.@");
w.print(targetType.getQualifiedSourceName());
w.print("::");
w.print(f.getName());
w.println(";");
w.outdent();
w.println("}-*/;");
w.print("private static final native void ");
w.print(" objectSet_" + f.getName());
w.print("(");
w.print(targetType.getQualifiedSourceName() + " instance, ");
w.print(f.getType().getQualifiedSourceName() + " value");
w.print(")");
w.println("/*-{ ");
w.indent();
w.print("instance.@");
w.print(targetType.getQualifiedSourceName());
w.print("::");
w.print(f.getName());
w.println(" = value;");
w.outdent();
w.println("}-*/;");
}
if (f.getType() == JPrimitiveType.CHAR || isBoxedCharacter(f.getType())) {
w.print("private static final native String");
w.print(" jsonGet0_" + f.getName());
w.print("(final JavaScriptObject instance)");
w.println("/*-{ ");
w.indent();
w.print("return instance.");
w.print(f.getName());
w.println(";");
w.outdent();
w.println("}-*/;");
w.print("private static final ");
w.print(f.getType() == JPrimitiveType.CHAR ? "char" : "Character");
w.print(" jsonGet_" + f.getName());
w.print("(JavaScriptObject instance)");
w.println(" {");
w.indent();
w.print("return ");
w.print(JsonSerializer.class.getName());
w.print(".toChar(");
w.print("jsonGet0_" + f.getName());
w.print("(instance)");
w.println(");");
w.outdent();
w.println("}");
} else {
w.print("private static final native ");
if (f.getType().isArray() != null) {
w.print("JavaScriptObject");
} else if (isJsonPrimitive(f.getType())) {
w.print(f.getType().getQualifiedSourceName());
} else if (isBoxedPrimitive(f.getType())) {
w.print(boxedTypeToPrimitiveTypeName(f.getType()));
} else {
w.print("Object");
}
w.print(" jsonGet_" + f.getName());
w.print("(JavaScriptObject instance)");
w.println("/*-{ ");
w.indent();
w.print("return instance.");
w.print(f.getName());
w.println(";");
w.outdent();
w.println("}-*/;");
}
w.println();
}
}
private void generateEnumFromJson(final SourceWriter w) {
w.print("public ");
w.print(targetType.getQualifiedSourceName());
w.println(" fromJson(Object in) {");
w.indent();
w.print("return in != null");
w.print(" ? " + targetType.getQualifiedSourceName()
+ ".valueOf((String)in)");
w.print(" : null");
w.println(";");
w.outdent();
w.println("}");
w.println();
}
private void generatePrintJson(final SourceWriter w) {
final JField[] fieldList = sortFields(targetType);
w.print("protected int printJsonImpl(int fieldCount, StringBuilder sb, ");
w.println("Object instance) {");
w.indent();
w.print("final ");
w.print(targetType.getQualifiedSourceName());
w.print(" src = (");
w.print(targetType.getQualifiedSourceName());
w.println(")instance;");
if (needsSuperSerializer(targetType)) {
w.print("fieldCount = super.printJsonImpl(fieldCount, sb, (");
w.print(targetType.getSuperclass().getQualifiedSourceName());
w.println(")src);");
}
final String docomma = "if (fieldCount++ > 0) sb.append(\",\");";
for (final JField f : fieldList) {
final String doget;
if (f.isPrivate()) {
doget = "objectGet_" + f.getName() + "(src)";
} else {
doget = "src." + f.getName();
}
final String doname = "sb.append(\"\\\"" + f.getName() + "\\\":\");";
if (f.getType() == JPrimitiveType.CHAR || isBoxedCharacter(f.getType())) {
w.println(docomma);
w.println(doname);
w.println("sb.append(\"\\\"\");");
w.println("sb.append(" + JsonSerializer.class.getSimpleName()
+ ".escapeChar(" + doget + "));");
w.println("sb.append(\"\\\"\");");
} else if (isJsonString(f.getType())) {
w.println("if (" + doget + " != null) {");
w.indent();
w.println(docomma);
w.println(doname);
w.println("sb.append(" + JsonSerializer.class.getSimpleName()
+ ".escapeString(" + doget + "));");
w.outdent();
w.println("}");
w.println();
} else if (isJsonPrimitive(f.getType()) || isBoxedPrimitive(f.getType())) {
w.println(docomma);
w.println(doname);
w.println("sb.append(" + doget + ");");
w.println();
} else {
w.println("if (" + doget + " != null) {");
w.indent();
w.println(docomma);
w.println(doname);
if (needsTypeParameter(f.getType())) {
w.print("ser_" + f.getName());
} else {
w.print(serializerFor(f.getType()) + ".INSTANCE");
}
w.println(".printJson(sb, " + doget + ");");
w.outdent();
w.println("}");
w.println();
}
}
w.println("return fieldCount;");
w.outdent();
w.println("}");
w.println();
}
private void generateFromJson(final SourceWriter w) {
w.print("public ");
w.print(targetType.getQualifiedSourceName());
w.println(" fromJson(Object in) {");
w.indent();
if (targetType.isAbstract()) {
w.println("throw new UnsupportedOperationException();");
} else {
w.println("if (in == null) return null;");
w.println("final JavaScriptObject jso = (JavaScriptObject)in;");
w.print("final ");
w.print(targetType.getQualifiedSourceName());
w.print(" dst = new ");
w.println(targetType.getQualifiedSourceName() + "();");
w.println("fromJsonImpl(jso, dst);");
w.println("return dst;");
}
w.outdent();
w.println("}");
w.println();
w.print("protected void fromJsonImpl(JavaScriptObject jso,");
w.print(targetType.getQualifiedSourceName());
w.println(" dst) {");
w.indent();
if (needsSuperSerializer(targetType)) {
w.print("super.fromJsonImpl(jso, (");
w.print(targetType.getSuperclass().getQualifiedSourceName());
w.println(")dst);");
}
for (final JField f : sortFields(targetType)) {
final String doget = "jsonGet_" + f.getName() + "(jso)";
final String doset0, doset1;
if (f.isPrivate()) {
doset0 = "objectSet_" + f.getName() + "(dst, ";
doset1 = ")";
} else {
doset0 = "dst." + f.getName() + " = ";
doset1 = "";
}
JType type = f.getType();
if (type.isArray() != null) {
final JType ct = type.isArray().getComponentType();
w.println("if (" + doget + " != null) {");
w.indent();
w.print("final ");
w.print(ct.getQualifiedSourceName());
w.print("[] tmp = new ");
w.print(ct.getQualifiedSourceName());
w.print("[");
w.print(ObjectArraySerializer.class.getName());
w.print(".size(" + doget + ")");
w.println("];");
w.println("ser_" + f.getName() + ".fromJson(" + doget + ", tmp);");
w.print(doset0);
w.print("tmp");
w.print(doset1);
w.println(";");
w.outdent();
w.println("}");
} else if (isJsonPrimitive(type)) {
w.print(doset0);
w.print(doget);
w.print(doset1);
w.println(";");
} else if (isBoxedPrimitive(type)) {
w.print(doset0);
w.print("new " + type.getQualifiedSourceName() + "(");
w.print(doget);
w.print(")");
w.print(doset1);
w.println(";");
} else {
w.print(doset0);
if (needsTypeParameter(type)) {
w.print("ser_" + f.getName());
} else {
String serializerFor = serializerFor(type);
w.print(serializerFor + ".INSTANCE");
}
w.print(".fromJson(" + doget + ")");
w.print(doset1);
w.println(";");
}
}
w.outdent();
w.println("}");
w.println();
}
static boolean isJsonPrimitive(final JType t) {
return t.isPrimitive() != null || isJsonString(t);
}
static boolean isBoxedPrimitive(final JType t) {
final String qsn = t.getQualifiedSourceName();
return qsn.equals(Boolean.class.getCanonicalName())
|| qsn.equals(Byte.class.getCanonicalName()) || isBoxedCharacter(t)
|| qsn.equals(Double.class.getCanonicalName())
|| qsn.equals(Float.class.getCanonicalName())
|| qsn.equals(Integer.class.getCanonicalName())
|| qsn.equals(Short.class.getCanonicalName());
}
static boolean isBoxedCharacter(JType t) {
return t.getQualifiedSourceName()
.equals(Character.class.getCanonicalName());
}
private String boxedTypeToPrimitiveTypeName(JType t) {
final String qsn = t.getQualifiedSourceName();
if (qsn.equals(Boolean.class.getCanonicalName())) return "boolean";
if (qsn.equals(Byte.class.getCanonicalName())) return "byte";
if (qsn.equals(Character.class.getCanonicalName()))
return "java.lang.String";
if (qsn.equals(Double.class.getCanonicalName())) return "double";
if (qsn.equals(Float.class.getCanonicalName())) return "float";
if (qsn.equals(Integer.class.getCanonicalName())) return "int";
if (qsn.equals(Short.class.getCanonicalName())) return "short";
throw new IllegalArgumentException(t + " is not a boxed type");
}
static boolean isJsonString(final JType t) {
return t.getQualifiedSourceName().equals(String.class.getCanonicalName());
}
private SourceWriter getSourceWriter(final TreeLogger logger,
final GeneratorContext ctx) {
final JPackage targetPkg = targetType.getPackage();
final String pkgName = targetPkg == null ? "" : targetPkg.getName();
final PrintWriter pw;
final ClassSourceFileComposerFactory cf;
pw = ctx.tryCreate(logger, pkgName, getSerializerSimpleName());
if (pw == null) {
return null;
}
cf = new ClassSourceFileComposerFactory(pkgName, getSerializerSimpleName());
cf.addImport(JavaScriptObject.class.getCanonicalName());
cf.addImport(JsonSerializer.class.getCanonicalName());
if (targetType.isEnum() != null) {
cf.addImport(EnumSerializer.class.getCanonicalName());
cf.setSuperclass(EnumSerializer.class.getSimpleName() + "<"
+ targetType.getQualifiedSourceName() + ">");
} else if (needsSuperSerializer(targetType)) {
cf.setSuperclass(getSerializerQualifiedName(targetType.getSuperclass()));
} else {
cf.addImport(ObjectSerializer.class.getCanonicalName());
cf.setSuperclass(ObjectSerializer.class.getSimpleName() + "<"
+ targetType.getQualifiedSourceName() + ">");
}
return cf.createSourceWriter(ctx, pw);
}
private static boolean needsSuperSerializer(JClassType type) {
type = type.getSuperclass();
while (!Object.class.getName().equals(type.getQualifiedSourceName())) {
if (sortFields(type).length > 0) {
return true;
}
type = type.getSuperclass();
}
return false;
}
private String getSerializerQualifiedName(final JClassType targetType) {
final String[] name;
name = ProxyCreator.synthesizeTopLevelClassName(targetType, SER_SUFFIX);
return name[0].length() == 0 ? name[1] : name[0] + "." + name[1];
}
private String getSerializerSimpleName() {
return ProxyCreator.synthesizeTopLevelClassName(targetType, SER_SUFFIX)[1];
}
static boolean needsTypeParameter(final JType ft) {
return ft.isArray() != null
|| (ft.isParameterized() != null && parameterizedSerializers
.containsKey(ft.getQualifiedSourceName()));
}
private static JField[] sortFields(final JClassType targetType) {
final ArrayList<JField> r = new ArrayList<JField>();
for (final JField f : targetType.getFields()) {
if (!f.isStatic() && !f.isTransient() && !f.isFinal()) {
r.add(f);
}
}
Collections.sort(r, FIELD_COMP);
return r.toArray(new JField[r.size()]);
}
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.rebind;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import org.rapla.rest.gwtjsonrpc.client.CallbackHandle;
import org.rapla.rest.gwtjsonrpc.client.impl.AbstractJsonProxy;
import org.rapla.rest.gwtjsonrpc.client.impl.FutureResultImpl;
import org.rapla.rest.gwtjsonrpc.client.impl.JsonSerializer;
import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer;
import org.rapla.rest.gwtjsonrpc.client.impl.v2_0.JsonCall20HttpGet;
import org.rapla.rest.gwtjsonrpc.client.impl.v2_0.JsonCall20HttpPost;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.rest.gwtjsonrpc.common.RpcImpl;
import org.rapla.rest.gwtjsonrpc.common.RpcImpl.Transport;
import org.rapla.rest.gwtjsonrpc.common.RpcImpl.Version;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.TreeLogger.Type;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JArrayType;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.core.ext.typeinfo.JPackage;
import com.google.gwt.core.ext.typeinfo.JParameter;
import com.google.gwt.core.ext.typeinfo.JParameterizedType;
import com.google.gwt.core.ext.typeinfo.JPrimitiveType;
import com.google.gwt.core.ext.typeinfo.JType;
import com.google.gwt.dev.generator.NameFactory;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;
class ProxyCreator {
private static final String PROXY_SUFFIX = "_JsonProxy";
private JClassType svcInf;
//private JClassType asyncCallbackClass;
//private JClassType futureResultInterface;
String futureResultClassName;
//private JClassType futureResultClass;
private SerializerCreator serializerCreator;
private ResultDeserializerCreator deserializerCreator;
private int instanceField;
ProxyCreator(final JClassType remoteService) {
svcInf = remoteService;
}
String create(final TreeLogger logger, final GeneratorContext context)
throws UnableToCompleteException {
serializerCreator = new SerializerCreator(context);
deserializerCreator = new ResultDeserializerCreator(context, serializerCreator);
futureResultClassName = FutureResultImpl.class.getName();
//final TypeOracle typeOracle = context.getTypeOracle();
//try {
//asyncCallbackClass = typeOracle.getType(AsyncCallback.class.getName());
//String futureResultInterfaceName = FutureResult.class.getName();
//futureResultInterface = typeOracle.getType(futureResultInterfaceName);
// futureResultClass = typeOracle.getType(futureResultClassName);
// } catch (NotFoundException e) {
// logger.log(TreeLogger.ERROR, null, e);
// throw new UnableToCompleteException();
// }
checkMethods(logger, context);
final SourceWriter srcWriter = getSourceWriter(logger, context);
if (srcWriter == null) {
return getProxyQualifiedName();
}
generateProxyConstructor(logger, srcWriter);
generateProxyCallCreator(logger, srcWriter);
generateProxyMethods(logger, srcWriter);
srcWriter.commit(logger);
return getProxyQualifiedName();
}
private void checkMethods(final TreeLogger logger,
@SuppressWarnings("unused") final GeneratorContext context) throws UnableToCompleteException {
final Set<String> declaredNames = new HashSet<String>();
final JMethod[] methodList = svcInf.getOverridableMethods();
for (final JMethod m : methodList) {
if (!declaredNames.add(m.getName())) {
invalid(logger, "Overloading method " + m.getName() + " not supported");
}
final JParameter[] params = m.getParameters();
// if (m.getReturnType() != JPrimitiveType.VOID && !returnsCallbackHandle(m)) {
// invalid(logger, "Method " + m.getName() + " must return void or "
// + CallbackHandle.class);
// }
//
// if (params.length == 0) {
// invalid(logger, "Method " + m.getName() + " requires "
// + AsyncCallback.class.getName() + " as last parameter");
// }
//
// final JParameter callback = params[params.length - 1];
// if (!callback.getType().getErasedType().getQualifiedSourceName().equals(
// asyncCallbackClass.getQualifiedSourceName())) {
// invalid(logger, "Method " + m.getName() + " requires "
// + AsyncCallback.class.getName() + " as last parameter");
// }
// if (callback.getType().isParameterized() == null) {
// invalid(logger, "Callback " + callback.getName()
// + " must have a type parameter");
// }
final JType callback = m.getReturnType();
// if (!callback.getErasedType().getQualifiedSourceName().equals(
// futureResultInterface.getQualifiedSourceName())) {
// invalid(logger, "Method " + m.getName() + " requires "
// + FutureResult.class.getName() + " as return type");
// }
// if (callback.isParameterized() == null) {
// invalid(logger, "FutureResult must have a type parameter");
// }
final JClassType resultType =callback.isParameterized().getTypeArgs()[0];
//final JType resultType =callback;
// if (returnsCallbackHandle(m)) {
// if (params.length != 1) {
// invalid(logger, "Method " + m.getName()
// + " must not accept parameters");
// }
//
// final JClassType rt = m.getReturnType().isClass();
// if (rt.isParameterized() == null) {
// invalid(logger, "CallbackHandle return value of " + m.getName()
// + " must have a type parameter");
// }
// if (!resultType.getQualifiedSourceName().equals(
// rt.isParameterized().getTypeArgs()[0].getQualifiedSourceName())) {
// invalid(logger, "CallbackHandle return value of " + m.getName()
// + " must match type with AsyncCallback parameter");
// }
// }
// if (m.getAnnotation(HostPageCache.class) != null) {
// if (m.getReturnType() != JPrimitiveType.VOID) {
// invalid(logger, "Method " + m.getName()
// + " must return void if using " + HostPageCache.class.getName());
// }
// if (params.length != 1) {
// invalid(logger, "Method " + m.getName()
// + " must not accept parameters");
// }
// }
for (int i = 0; i < params.length /*- 1*/; i++) {
final JParameter p = params[i];
final TreeLogger branch =
logger.branch(TreeLogger.DEBUG, m.getName() + ", parameter "
+ p.getName());
serializerCreator.checkCanSerialize(branch, p.getType());
if (p.getType().isPrimitive() == null
&& !SerializerCreator.isBoxedPrimitive(p.getType())) {
serializerCreator.create((JClassType) p.getType(), branch);
}
}
{
JClassType p = resultType;
final TreeLogger branch =
logger.branch(TreeLogger.DEBUG, m.getName() + ", result "
+ p.getName());
if (p.isPrimitive() == null
&& !SerializerCreator.isBoxedPrimitive(p)) {
serializerCreator.create((JClassType) p, branch);
}
}
final TreeLogger branch =
logger.branch(TreeLogger.DEBUG, m.getName() + ", result "
+ resultType.getQualifiedSourceName());
if ( resultType.getQualifiedSourceName().startsWith(FutureResult.class.getName()))
{
JParameterizedType parameterized = resultType.isParameterized();
JClassType jClassType = parameterized.getTypeArgs()[0];
serializerCreator.checkCanSerialize(branch, jClassType);
}
else
{
serializerCreator.checkCanSerialize(branch, resultType);
}
if (resultType.isArray() != null) {
// Arrays need a special deserializer
deserializerCreator.create(branch, resultType.isArray());
} else if (resultType.isPrimitive() == null
&& !SerializerCreator.isBoxedPrimitive(resultType))
// Non primitives get deserialized by their normal serializer
serializerCreator.create((JClassType)resultType, branch);
// (Boxed)Primitives are left, they are handled specially
}
}
private boolean returnsCallbackHandle(final JMethod m) {
return m.getReturnType().getErasedType().getQualifiedSourceName().equals(
CallbackHandle.class.getName());
}
private void invalid(final TreeLogger logger, final String what)
throws UnableToCompleteException {
logger.log(TreeLogger.ERROR, what, null);
throw new UnableToCompleteException();
}
private SourceWriter getSourceWriter(final TreeLogger logger,
final GeneratorContext ctx) {
final JPackage servicePkg = svcInf.getPackage();
final String pkgName = servicePkg == null ? "" : servicePkg.getName();
final PrintWriter pw;
final ClassSourceFileComposerFactory cf;
pw = ctx.tryCreate(logger, pkgName, getProxySimpleName());
if (pw == null) {
return null;
}
cf = new ClassSourceFileComposerFactory(pkgName, getProxySimpleName());
cf.addImport(AbstractJsonProxy.class.getCanonicalName());
cf.addImport(JsonSerializer.class.getCanonicalName());
cf.addImport(JavaScriptObject.class.getCanonicalName());
cf.addImport(ResultDeserializer.class.getCanonicalName());
cf.addImport(FutureResultImpl.class.getCanonicalName());
cf.addImport(GWT.class.getCanonicalName());
cf.setSuperclass(AbstractJsonProxy.class.getSimpleName());
cf.addImplementedInterface(svcInf.getErasedType().getQualifiedSourceName());
return cf.createSourceWriter(ctx, pw);
}
private void generateProxyConstructor(@SuppressWarnings("unused") final TreeLogger logger,
final SourceWriter w) {
final RemoteServiceRelativePath relPath =
svcInf.getAnnotation(RemoteServiceRelativePath.class);
if (relPath != null) {
w.println();
w.println("public " + getProxySimpleName() + "() {");
w.indent();
w.println("setServiceEntryPoint(GWT.getModuleBaseURL() + \""
+ relPath.value() + "\");");
w.outdent();
w.println("}");
}
}
private void generateProxyCallCreator(final TreeLogger logger,
final SourceWriter w) throws UnableToCompleteException {
String callName = getJsonCallClassName(logger);
w.println();
w.println("@Override");
w.print("protected <T> ");
w.print(callName);
w.print("<T> newJsonCall(final AbstractJsonProxy proxy, ");
w.print("final String methodName, final String reqData, ");
w.println("final ResultDeserializer<T> ser) {");
w.indent();
w.print("return new ");
w.print(callName);
w.println("<T>(proxy, methodName, reqData, ser);");
w.outdent();
w.println("}");
}
private String getJsonCallClassName(final TreeLogger logger)
throws UnableToCompleteException {
RpcImpl impl = svcInf.getAnnotation(RpcImpl.class);
if (impl == null) {
return JsonCall20HttpPost.class.getCanonicalName();
} else if (impl.version() == Version.V2_0
&& impl.transport() == Transport.HTTP_POST) {
return JsonCall20HttpPost.class.getCanonicalName();
} else if (impl.version() == Version.V2_0
&& impl.transport() == Transport.HTTP_GET) {
return JsonCall20HttpGet.class.getCanonicalName();
}
logger.log(Type.ERROR, "Unsupported JSON-RPC version and transport "
+ "combination: Supported are 1.1 over HTTP POST and "
+ "2.0 over HTTP POST and GET");
throw new UnableToCompleteException();
}
private void generateProxyMethods(final TreeLogger logger,
final SourceWriter srcWriter) {
final JMethod[] methodList = svcInf.getOverridableMethods();
for (final JMethod m : methodList) {
generateProxyMethod(logger, m, srcWriter);
}
}
private void generateProxyMethod(@SuppressWarnings("unused") final TreeLogger logger,
final JMethod method, final SourceWriter w) {
final JParameter[] params = method.getParameters();
final JType callback = method.getReturnType();// params[params.length - 1];
JType resultType = callback;
// final JClassType resultType =
// callback.isParameterized().getTypeArgs()[0];
final String[] serializerFields = new String[params.length];
String resultField = "";
w.println();
for (int i = 0; i < params.length /*- 1*/; i++) {
final JType pType = params[i].getType();
if (SerializerCreator.needsTypeParameter(pType)) {
serializerFields[i] = "serializer_" + instanceField++;
w.print("private static final ");
if (pType.isArray() != null)
w.print(serializerCreator.serializerFor(pType));
else
w.print(JsonSerializer.class.getName());
w.print(" ");
w.print(serializerFields[i]);
w.print(" = ");
serializerCreator.generateSerializerReference(pType, w);
w.println(";");
}
}
JClassType parameterizedResult = null;
if (resultType.isParameterized() != null) {
resultField = "serializer_" + instanceField++;
w.print("private static final ");
w.print(ResultDeserializer.class.getName());
w.print(" ");
w.print(resultField);
w.print(" = ");
parameterizedResult = resultType.isParameterized().getTypeArgs()[0];
serializerCreator.generateSerializerReference(parameterizedResult, w);
w.println(";");
}
w.print("public ");
w.print(method.getReturnType().getQualifiedSourceName());
w.print(" ");
w.print(method.getName());
w.print("(");
boolean needsComma = false;
final NameFactory nameFactory = new NameFactory();
for (int i = 0; i < params.length; i++) {
final JParameter param = params[i];
if (needsComma) {
w.print(", ");
} else {
needsComma = true;
}
final JType paramType = param.getType().getErasedType();
w.print(paramType.getQualifiedSourceName());
w.print(" ");
nameFactory.addName(param.getName());
w.print(param.getName());
}
w.println(") {");
w.indent();
if (returnsCallbackHandle(method)) {
w.print("return new ");
w.print(CallbackHandle.class.getName());
w.print("(");
if (SerializerCreator.needsTypeParameter(resultType)) {
w.print(resultField);
} else {
deserializerCreator.generateDeserializerReference(resultType, w);
}
w.print(", " + "null" // callback.getName()
);
w.println(");");
w.outdent();
w.println("}");
return;
}
// final HostPageCache hpc = method.getAnnotation(HostPageCache.class);
// if (hpc != null) {
// final String objName = nameFactory.createName("cached");
// w.print("final JavaScriptObject " + objName + " = ");
// w.print(AbstractJsonProxy.class.getName());
// w.print(".");
// w.print(hpc.once() ? "hostPageCacheGetOnce" : "hostPageCacheGetMany");
// w.println("(\"" + hpc.name() + "\");");
// w.println("if (" + objName + " != null) {");
// w.indent();
// w.print(JsonUtil.class.getName());
// w.print(".invoke(");
// if (SerializerCreator.needsTypeParameter(resultType)) {
// w.print(resultField);
// } else {
// deserializerCreator.generateDeserializerReference(resultType, w);
// }
// // w.print(", " + callback.getName());
// w.print(", " + "null");
// w.print(", " + objName);
// w.println(");");
// w.println("return;");
// w.outdent();
// w.println("}");
// }
final String reqDataStr;
if (params.length == 1) {
reqDataStr = "\"[]\"";
} else {
final String reqData = nameFactory.createName("reqData");
w.println("final StringBuilder " + reqData + " = new StringBuilder();");
needsComma = false;
w.println(reqData + ".append('[');");
for (int i = 0; i < params.length; i++) {
if (needsComma) {
w.println(reqData + ".append(\",\");");
} else {
needsComma = true;
}
final JType pType = params[i].getType();
final String pName = params[i].getName();
if (pType == JPrimitiveType.CHAR
|| SerializerCreator.isBoxedCharacter(pType)) {
w.println(reqData + ".append(\"\\\"\");");
w.println(reqData + ".append(" + JsonSerializer.class.getSimpleName()
+ ".escapeChar(" + pName + "));");
w.println(reqData + ".append(\"\\\"\");");
} else if ((SerializerCreator.isJsonPrimitive(pType) || SerializerCreator
.isBoxedPrimitive(pType))
&& !SerializerCreator.isJsonString(pType)) {
w.println(reqData + ".append(" + pName + ");");
} else {
w.println("if (" + pName + " != null) {");
w.indent();
if (SerializerCreator.needsTypeParameter(pType)) {
w.print(serializerFields[i]);
} else {
serializerCreator.generateSerializerReference(pType, w);
}
w.println(".printJson(" + reqData + ", " + pName + ");");
w.outdent();
w.println("} else {");
w.indent();
w.println(reqData + ".append(" + JsonSerializer.class.getName()
+ ".JS_NULL);");
w.outdent();
w.println("}");
}
}
w.println(reqData + ".append(']');");
reqDataStr = reqData + ".toString()";
}
String resultClass = futureResultClassName;
if (parameterizedResult != null)
{
resultClass+="<" + parameterizedResult.getQualifiedSourceName()+ ">";
}
w.println( resultClass + " result = new " + resultClass + "();");
w.print("doInvoke(");
w.print("\"" + method.getName() + "\"");
w.print(", " + reqDataStr);
w.print(", ");
if (resultType.isParameterized() != null) {
w.print(resultField);
} else {
deserializerCreator.generateDeserializerReference(resultType, w);
}
//w.print(", " + callback.getName());
w.print(", result");
w.println(");");
w.println("return result;");
w.outdent();
w.println("}");
}
private String getProxyQualifiedName() {
final String[] name = synthesizeTopLevelClassName(svcInf, PROXY_SUFFIX);
return name[0].length() == 0 ? name[1] : name[0] + "." + name[1];
}
private String getProxySimpleName() {
return synthesizeTopLevelClassName(svcInf, PROXY_SUFFIX)[1];
}
static String[] synthesizeTopLevelClassName(JClassType type, String suffix) {
// Gets the basic name of the type. If it's a nested type, the type name
// will contains dots.
//
String className;
String packageName;
JType leafType = type.getLeafType();
if (leafType.isPrimitive() != null) {
className = leafType.getSimpleSourceName();
packageName = "";
} else {
JClassType classOrInterface = leafType.isClassOrInterface();
assert (classOrInterface != null);
className = classOrInterface.getName();
packageName = classOrInterface.getPackage().getName();
}
JParameterizedType isGeneric = type.isParameterized();
if (isGeneric != null) {
for (JClassType param : isGeneric.getTypeArgs()) {
className += "_";
className += param.getQualifiedSourceName().replace('.', '_');
}
}
JArrayType isArray = type.isArray();
if (isArray != null) {
className += "_Array_Rank_" + isArray.getRank();
}
// Add the meaningful suffix.
//
className += suffix;
// Make it a top-level name.
//
className = className.replace('.', '_');
return new String[] {packageName, className};
}
}
| Java |
// Copyright 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.rebind;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.typeinfo.JArrayType;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JType;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import org.rapla.rest.gwtjsonrpc.client.impl.ArrayResultDeserializer;
import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer;
import org.rapla.rest.gwtjsonrpc.client.impl.ser.PrimitiveArrayResultDeserializers;
import org.rapla.rest.gwtjsonrpc.client.impl.ser.PrimitiveResultDeserializers;
/**
* Creator of ResultDeserializers. Actually, only object arrays have created
* deserializers:
* <ul>
* <li>Boxed primitives are handled by {@link PrimitiveResultDeserializers}
* <li>Normal objects have their (generated) serializers extending
* {@link com.google.gwtjsonrpc.client.ObjectSerializer}, that handle result
* deserialisation as well.
* <li>Arrays of (boxed) primitives are handled by
* {@link PrimitiveArrayResultDeserializers}.
* <li>And object arrays get a generated deserializer extending
* {@link ArrayResultDeserializer}
* </ul>
* All object arrays that have a JSONSerializer for the array component can be
* generated, but they will need to live in the same package as the serializer.
* To do this, if the serializer lives in the
* <code>com.google.gwtjsonrpc.client</code> package (where custom object
* serializers live), the ResultDeserializer for it's array will be placed in
* this package as well. Else it will be placed with the serializer in the
* package the object lives.
*/
class ResultDeserializerCreator {
private static final String DSER_SUFFIX = "_ResultDeserializer";
private GeneratorContext context;
private HashMap<String, String> generatedDeserializers;
private SerializerCreator serializerCreator;
private JArrayType targetType;
private JType componentType;
ResultDeserializerCreator(GeneratorContext c, SerializerCreator sc) {
context = c;
generatedDeserializers = new HashMap<String, String>();
serializerCreator = sc;
}
void create(TreeLogger logger, JArrayType targetType) {
this.targetType = targetType;
this.componentType = targetType.getComponentType();
if (componentType.isPrimitive() != null
|| SerializerCreator.isBoxedPrimitive(componentType)) {
logger.log(TreeLogger.DEBUG,
"No need to create array deserializer for primitive array "
+ targetType);
return;
}
if (deserializerFor(targetType) != null) {
return;
}
logger.log(TreeLogger.DEBUG, "Creating result deserializer for "
+ targetType.getSimpleSourceName());
final SourceWriter srcWriter = getSourceWriter(logger, context);
if (srcWriter == null) {
return;
}
final String dsn = getDeserializerQualifiedName(targetType);
generatedDeserializers.put(targetType.getQualifiedSourceName(), dsn);
generateSingleton(srcWriter);
generateInstanceMembers(srcWriter);
generateFromResult(srcWriter);
srcWriter.commit(logger);
}
private void generateSingleton(final SourceWriter w) {
w.print("public static final ");
w.print(getDeserializerSimpleName(targetType));
w.print(" INSTANCE = new ");
w.print(getDeserializerSimpleName(targetType));
w.println("();");
w.println();
}
private void generateInstanceMembers(SourceWriter w) {
w.print("private final ");
w.print(serializerCreator.serializerFor(targetType));
w.print(" ");
w.print("serializer");
w.print(" = ");
serializerCreator.generateSerializerReference(targetType, w);
w.println(";");
w.println();
}
private void generateFromResult(SourceWriter w) {
final String ctn = componentType.getQualifiedSourceName();
w.println("@Override");
w.print("public " + ctn + "[] ");
w.println("fromResult(JavaScriptObject responseObject) {");
w.indent();
w.print("final " + ctn + "[] tmp = new " + ctn);
w.println("[getResultSize(responseObject)];");
w.println("serializer.fromJson(getResult(responseObject), tmp);");
w.println("return tmp;");
w.outdent();
w.println("}");
}
private String getDeserializerQualifiedName(JArrayType targetType) {
final String pkgName = getDeserializerPackageName(targetType);
final String className = getDeserializerSimpleName(targetType);
return pkgName.length() == 0 ? className : pkgName + "." + className;
}
private String getDeserializerPackageName(JArrayType targetType) {
// Place array deserializer in same package as the component deserializer
final String compSerializer =
serializerCreator.serializerFor(targetType.getComponentType());
final int end = compSerializer.lastIndexOf('.');
return end >= 0 ? compSerializer.substring(0, end) : "";
}
private static String getDeserializerSimpleName(JClassType targetType) {
return ProxyCreator.synthesizeTopLevelClassName(targetType, DSER_SUFFIX)[1];
}
private SourceWriter getSourceWriter(TreeLogger logger,
GeneratorContext context) {
String pkgName = getDeserializerPackageName(targetType);
final String simpleName = getDeserializerSimpleName(targetType);
final PrintWriter pw;
final ClassSourceFileComposerFactory cf;
pw = context.tryCreate(logger, pkgName, simpleName);
if (pw == null) {
return null;
}
cf = new ClassSourceFileComposerFactory(pkgName, simpleName);
cf.addImport(JavaScriptObject.class.getCanonicalName());
cf.addImport(ResultDeserializer.class.getCanonicalName());
cf.setSuperclass(ArrayResultDeserializer.class.getCanonicalName());
cf.addImplementedInterface(ResultDeserializer.class.getCanonicalName()
+ "<" + targetType.getQualifiedSourceName() + ">");
return cf.createSourceWriter(context, pw);
}
private String deserializerFor(JArrayType targetType) {
final JType componentType = targetType.getComponentType();
// Custom primitive deserializers
if (SerializerCreator.isBoxedPrimitive(componentType))
return PrimitiveArrayResultDeserializers.class.getCanonicalName() + "."
+ componentType.getSimpleSourceName().toUpperCase() + "_INSTANCE";
final String name =
generatedDeserializers.get(targetType.getQualifiedSourceName());
return name == null ? null : name + ".INSTANCE";
}
public void generateDeserializerReference(JType targetType, SourceWriter w) {
if (SerializerCreator.isBoxedPrimitive(targetType)) {
w.print(PrimitiveResultDeserializers.class.getCanonicalName());
w.print(".");
w.print(targetType.getSimpleSourceName().toUpperCase());
w.print("_INSTANCE");
} else if (targetType.isArray() != null) {
w.print(deserializerFor(targetType.isArray()));
} else {
serializerCreator.generateSerializerReference(targetType, w);
}
}
}
| 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.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 |
/*--------------------------------------------------------------------------*
| 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) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbfile.tests;
import org.rapla.ServerTest;
import org.rapla.storage.CachableStorageOperator;
public class FileOperatorRemoteTest extends ServerTest {
CachableStorageOperator operator;
public FileOperatorRemoteTest(String name) {
super(name);
}
protected String getStorageName() {
return "storage-file";
}
}
| 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.tests;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.rapla.storage.tests.AbstractOperatorTest;
public class FileOperatorTest extends AbstractOperatorTest {
public FileOperatorTest(String name) {
super(name);
}
public static Test suite() {
return new TestSuite(FileOperatorTest.class);
}
protected String getStorageName() {
return "raplafile";
}
protected String getFacadeName() {
return "local-facade";
}
}
| 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.tests;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.rapla.RaplaTestCase;
import org.rapla.entities.Entity;
import org.rapla.framework.RaplaException;
import org.rapla.storage.CachableStorageOperator;
public class FileOperatorDiffTest extends RaplaTestCase {
CachableStorageOperator operator;
public FileOperatorDiffTest(String name) {
super(name);
}
public boolean differ(String file1, String file2) throws IOException {
BufferedReader in1 = null;
BufferedReader in2 = null;
boolean bDiffer = false;
try {
in1 = new BufferedReader(new FileReader(file1));
in2 = new BufferedReader(new FileReader(file2));
int line=0;
while (true) {
String b1 = in1.readLine();
String b2 = in2.readLine();
if ( b1 == null || b2 == null)
{
if (b1 != b2)
{
System.out.println("Different sizes");
bDiffer = true;
}
break;
}
line ++;
if (!b1.equals(b2)) {
System.out.println("Different contents in line " + line );
System.out.println("File1: '" +b1 + "'");
System.out.println("File2: '" +b2 + "'");
bDiffer = true;
break;
}
}
return bDiffer;
}
finally {
if (in1 != null)
in1.close();
if (in2 != null)
in2.close();
}
}
public static Test suite() {
return new TestSuite(FileOperatorDiffTest.class);
}
public void setUp() throws Exception {
super.setUp();
operator = raplaContainer.lookup(CachableStorageOperator.class,"raplafile");
}
public void testSave() throws RaplaException,IOException {
String testFile = "test-src/testdefault.xml";
assertTrue(differ(TEST_FOLDER_NAME + "/test.xml",testFile) == false);
operator.connect();
Entity obj = operator.getUsers().iterator().next();
Set<Entity>singleton = Collections.singleton(obj);
Collection<Entity> r = operator.editObjects(singleton, null);
Entity clone = r.iterator().next();
Collection<Entity> storeList = new ArrayList<Entity>(1);
storeList.add( clone);
Collection<Entity> removeList = Collections.emptyList();
operator.storeAndRemove(storeList, removeList, null);
assertTrue("stored version differs from orginal " + testFile
, differ(TEST_FOLDER_NAME + "/test.xml",testFile) == false );
}
}
| 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.tests;
import java.util.Date;
import org.rapla.RaplaTestCase;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.facade.ClientFacade;
import org.rapla.framework.RaplaException;
import org.rapla.storage.CachableStorageOperator;
public abstract class AbstractOperatorTest extends RaplaTestCase {
protected CachableStorageOperator operator;
protected ClientFacade facade;
public AbstractOperatorTest(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
operator = raplaContainer.lookup(CachableStorageOperator.class , getStorageName());
facade = raplaContainer.lookup(ClientFacade.class, getFacadeName());
}
abstract protected String getStorageName();
abstract protected String getFacadeName();
public void testReservationStore() throws RaplaException {
// abspeichern
facade.login("homer", "duffs".toCharArray() );
{
Reservation r = facade.newReservation();
r.getClassification().setValue("name","test");
Appointment app = facade.newAppointment( new Date(), new Date());
Appointment app2 = facade.newAppointment( new Date(), new Date());
Allocatable resource = facade.newResource();
r.addAppointment( app);
r.addAppointment( app2);
r.addAllocatable(resource );
r.setRestriction( resource, new Appointment[] {app});
app.setRepeatingEnabled( true );
app.getRepeating().setType(Repeating.DAILY);
app.getRepeating().setNumber( 10);
app.getRepeating().addException( new Date());
facade.storeObjects( new Entity[] { r, resource });
}
operator.disconnect();
operator.connect();
facade.login("homer", "duffs".toCharArray() );
// einlesen
{
String defaultReservation = "event";
ClassificationFilter filter = facade.getDynamicType( defaultReservation ).newClassificationFilter();
filter.addRule("name",new Object[][] { {"contains","test"}});
Reservation reservation = facade.getReservationsForAllocatable( null, null, null, new ClassificationFilter[] {filter} )[0];
Appointment[] apps = reservation.getAppointments();
Allocatable resource = reservation.getAllocatables()[0];
assertEquals( 2, apps.length);
assertEquals( 1, reservation.getAppointmentsFor( resource ).length);
Appointment app = reservation.getAppointmentsFor( resource )[0];
assertEquals( 1, app.getRepeating().getExceptions().length);
assertEquals( Repeating.DAILY, app.getRepeating().getType());
assertEquals( 10, app.getRepeating().getNumber());
}
}
public void testUserStore() throws RaplaException {
facade.login("homer", "duffs".toCharArray() );
{
User u = facade.newUser();
u.setUsername("kohlhaas");
u.setAdmin( false);
u.addGroup( facade.getUserGroupsCategory().getCategory("my-group"));
facade.store( u );
}
operator.disconnect();
operator.connect();
facade.login("homer", "duffs".toCharArray() );
{
User u = facade.getUser("kohlhaas");
Category[] groups = u.getGroups();
assertEquals( groups.length, 2 );
assertEquals( facade.getUserGroupsCategory().getCategory("my-group"), groups[1]);
assertFalse( u.isAdmin() );
}
}
public void testCategoryAnnotation() throws RaplaException {
String sampleDoc = "This is the category for user-groups";
String sampleAnnotationValue = "documentation";
facade.login("homer", "duffs".toCharArray() );
{
Category userGroups = facade.edit( facade.getUserGroupsCategory());
userGroups.setAnnotation( sampleAnnotationValue, sampleDoc );
facade.store( userGroups );
}
operator.disconnect();
operator.connect();
facade.login("homer", "duffs".toCharArray() );
{
Category userGroups = facade.getUserGroupsCategory();
assertEquals( sampleDoc, userGroups.getAnnotation( sampleAnnotationValue ));
}
}
public void testAttributeStore() throws RaplaException {
facade.login("homer", "duffs".toCharArray() );
// abspeichern
{
DynamicType type = facade.edit( facade.getDynamicType("event"));
Attribute att = facade.newAttribute( AttributeType.STRING );
att.setKey("test-att");
type.addAttribute( att );
Reservation r = facade.newReservation();
try {
r.setClassification( type.newClassification() );
fail("Should have thrown an IllegalStateException");
} catch (IllegalStateException ex) {
}
facade.store( type );
r.setClassification( facade.getPersistant(type).newClassification() );
r.getClassification().setValue("name","test");
r.getClassification().setValue("test-att","test-att-value");
Appointment app = facade.newAppointment( new Date(), new Date());
Appointment app2 = facade.newAppointment( new Date(), new Date());
Allocatable resource = facade.newResource();
r.addAppointment( app);
r.addAppointment( app2);
r.addAllocatable(resource );
r.setRestriction( resource, new Appointment[] {app});
app.setRepeatingEnabled( true );
app.getRepeating().setType(Repeating.DAILY);
app.getRepeating().setNumber( 10);
app.getRepeating().addException( new Date());
facade.storeObjects( new Entity[] { r, resource });
operator.disconnect();
}
// einlesen
{
operator.connect();
facade.login("homer", "duffs".toCharArray() );
String defaultReservation = "event";
ClassificationFilter filter = facade.getDynamicType( defaultReservation ).newClassificationFilter();
filter.addRule("name",new Object[][] { {"contains","test"}});
Reservation reservation = facade.getReservationsForAllocatable( null, null, null, new ClassificationFilter[] {filter} )[0];
Appointment[] apps = reservation.getAppointments();
Allocatable resource = reservation.getAllocatables()[0];
assertEquals( "test-att-value", reservation.getClassification().getValue("test-att"));
assertEquals( 2, apps.length);
assertEquals( 1, reservation.getAppointmentsFor( resource ).length);
Appointment app = reservation.getAppointmentsFor( resource )[0];
assertEquals( 1, app.getRepeating().getExceptions().length);
assertEquals( Repeating.DAILY, app.getRepeating().getType());
assertEquals( 10, app.getRepeating().getNumber());
}
}
}
| 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.tests;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.rapla.RaplaTestCase;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.entities.dynamictype.internal.DynamicTypeImpl;
import org.rapla.facade.ClientFacade;
import org.rapla.framework.RaplaException;
import org.rapla.storage.CachableStorageOperator;
import org.rapla.storage.CachableStorageOperatorCommand;
import org.rapla.storage.LocalCache;
public class LocalCacheTest extends RaplaTestCase {
Locale locale;
public LocalCacheTest(String name) {
super(name);
}
public static Test suite() {
return new TestSuite(LocalCacheTest.class);
}
protected void setUp() throws Exception {
super.setUp();
}
public DynamicTypeImpl createDynamicType() throws Exception {
AttributeImpl attribute = new AttributeImpl(AttributeType.STRING);
attribute.setKey("name");
attribute.setId(getId(Attribute.TYPE,1));
DynamicTypeImpl dynamicType = new DynamicTypeImpl();
dynamicType.setKey("defaultResource");
dynamicType.setId(getId(DynamicType.TYPE,1));
dynamicType.addAttribute(attribute);
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}");
return dynamicType;
}
public AllocatableImpl createResource(LocalCache cache,int intId,DynamicType type,String name) {
Date today = new Date();
AllocatableImpl resource = new AllocatableImpl(today, today);
resource.setId(getId(Allocatable.TYPE,intId));
resource.setResolver( cache);
Classification classification = type.newClassification();
classification.setValue("name",name);
resource.setClassification(classification);
return resource;
}
private String getId(RaplaType type, int intId) {
return type.getLocalName() + "_" + intId;
}
public void testAllocatable() throws Exception {
LocalCache cache = new LocalCache();
DynamicTypeImpl type = createDynamicType();
type.setResolver( cache);
type.setReadOnly( );
cache.put( type );
AllocatableImpl resource1 = createResource(cache,1,type,"Adrian");
cache.put(resource1);
AllocatableImpl resource2 = createResource(cache,2,type,"Beta");
cache.put(resource2);
AllocatableImpl resource3 = createResource(cache,3,type,"Ceta");
cache.put(resource3);
resource1.getClassification().setValue("name","Zeta");
cache.put(resource1);
Allocatable[] resources = cache.getAllocatables().toArray(Allocatable.ALLOCATABLE_ARRAY);
assertEquals(3, resources.length);
assertTrue(resources[1].getName(locale).equals("Beta"));
}
public void test2() throws Exception {
final CachableStorageOperator storage = raplaContainer.lookup(CachableStorageOperator.class , "raplafile");
storage.connect();
final Period[] periods = getFacade().getPeriods();
storage.runWithReadLock(new CachableStorageOperatorCommand() {
@Override
public void execute(LocalCache cache) throws RaplaException {
{
ClassificationFilter[] filters = null;
Map<String, String> annotationQuery = null;
{
final Period period = periods[2];
Collection<Reservation> reservations = storage.getReservations(null,null,period.getStart(),period.getEnd(),filters,annotationQuery);
assertEquals(0,reservations.size());
}
{
final Period period = periods[1];
Collection<Reservation> reservations = storage.getReservations(null,null,period.getStart(),period.getEnd(), filters,annotationQuery);
assertEquals(2, reservations.size());
}
{
User user = cache.getUser("homer");
Collection<Reservation> reservations = storage.getReservations(user,null,null,null, filters,annotationQuery);
assertEquals(3, reservations.size());
}
{
User user = cache.getUser("homer");
final Period period = periods[1];
Collection<Reservation> reservations = storage.getReservations(user,null,period.getStart(),period.getEnd(),filters, annotationQuery);
assertEquals(2, reservations.size());
}
}
{
Iterator<Allocatable> it = cache.getAllocatables().iterator();
assertEquals("erwin",it.next().getName(locale));
assertEquals("Room A66",it.next().getName(locale));
}
}
});
}
public void testConflicts() throws Exception {
ClientFacade facade = getFacade();
Reservation reservation = facade.newReservation();
//start is 13/4 original end = 28/4
Date startDate = getRaplaLocale().toRaplaDate(2013, 4, 13);
Date endDate = getRaplaLocale().toRaplaDate(2013, 4, 28);
Appointment appointment = facade.newAppointment(startDate, endDate);
reservation.addAppointment(appointment);
reservation.getClassification().setValue("name", "test");
facade.store( reservation);
Reservation modifiableReservation = facade.edit(reservation);
Date splitTime = getRaplaLocale().toRaplaDate(2013, 4, 20);
Appointment modifiableAppointment = modifiableReservation.findAppointment( appointment);
// left part
//leftpart.move(13/4, 20/4)
modifiableAppointment.move(appointment.getStart(), splitTime);
facade.store( modifiableReservation);
CachableStorageOperator storage = raplaContainer.lookup(CachableStorageOperator.class, "raplafile");
User user = null;
Collection<Allocatable> allocatables = null;
Map<String, String> annotationQuery = null;
ClassificationFilter[] filters = null;
Collection<Reservation> reservations = storage.getReservations(user, allocatables, startDate, endDate, filters,annotationQuery);
assertEquals( 1, reservations.size());
}
}
| 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.tests;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.rapla.ServerTest;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeAnnotations;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.ConstraintIds;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.facade.ClientFacade;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.storage.CachableStorageOperator;
import org.rapla.storage.ImportExportManager;
import org.rapla.storage.dbsql.DBOperator;
public class SQLOperatorRemoteTest extends ServerTest {
public SQLOperatorRemoteTest(String name) {
super(name);
}
protected String getStorageName() {
return "storage-sql";
}
public static Test suite() throws Exception {
TestSuite suite = new TestSuite("SQLOperatorRemoteTest");
suite.addTest( new SQLOperatorRemoteTest("testExport"));
suite.addTest( new SQLOperatorRemoteTest("testNewAttribute"));
suite.addTest( new SQLOperatorRemoteTest("testAttributeChange"));
suite.addTest( new SQLOperatorRemoteTest("testChangeDynamicType"));
suite.addTest( new SQLOperatorRemoteTest("testChangeGroup"));
suite.addTest( new SQLOperatorRemoteTest("testCreateResourceAndRemoveAttribute"));
return suite;
}
public void testExport() throws Exception {
RaplaContext context = getContext();
ImportExportManager conv = context.lookup(ImportExportManager.class);
conv.doExport();
{
CachableStorageOperator operator = getContainer().lookup(CachableStorageOperator.class, "rapladb");
operator.connect();
operator.getVisibleEntities( null );
Thread.sleep( 1000 );
}
//
// {
// CachableStorageOperator operator = context.lookup(CachableStorageOperator.class ,"file");
//
// operator.connect();
// operator.getVisibleEntities( null );
// Thread.sleep( 1000 );
// }
}
/** exposes a bug in the 0.12.1 Version of Rapla */
public void testAttributeChange() throws Exception {
ClientFacade facade = getContainer().lookup(ClientFacade.class ,"sql-facade");
facade.login("admin","".toCharArray());
// change Type
changeEventType( facade );
facade.logout();
// We need to disconnect the operator
CachableStorageOperator operator = getContainer().lookup(CachableStorageOperator.class ,"rapladb");
operator.disconnect();
operator.connect();
testTypeIds();
// The error shows when connect again
operator.connect();
changeEventType( facade );
testTypeIds();
}
@Override
protected void initTestData() throws Exception {
super.initTestData();
}
private void changeEventType( ClientFacade facade ) throws RaplaException
{
DynamicType eventType = facade.edit( facade.getDynamicType("event") );
Attribute attribute = eventType.getAttribute("description");
attribute.setType( AttributeType.CATEGORY );
attribute.setConstraint( ConstraintIds.KEY_ROOT_CATEGORY, facade.getSuperCategory().getCategory("department") );
facade.store( eventType );
}
private void testTypeIds() throws RaplaException, SQLException
{
CachableStorageOperator operator = getContainer().lookup(CachableStorageOperator.class, "rapladb");
Connection connection = ((DBOperator)operator).createConnection();
String sql ="SELECT * from DYNAMIC_TYPE";
try
{
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(sql);
while ( !set.isLast())
{
set.next();
//int idString = set.getInt("id");
//String key = set.getString("type_key");
//System.out.println( "id " + idString + " key " + key);
}
}
catch (SQLException ex)
{
throw new RaplaException( ex);
}
finally
{
connection.close();
}
}
public void testNewAttribute() throws Exception {
ClientFacade facade = getContainer().lookup(ClientFacade.class,"sql-facade");
facade.login("homer","duffs".toCharArray());
// change Type
DynamicType roomType = facade.edit( facade.getDynamicType("room") );
Attribute attribute = facade.newAttribute( AttributeType.STRING );
attribute.setKey("color");
attribute.setAnnotation( AttributeAnnotations.KEY_EDIT_VIEW, AttributeAnnotations.VALUE_EDIT_VIEW_NO_VIEW);
roomType.addAttribute( attribute );
facade.store( roomType );
roomType = facade.getPersistant( roomType );
Allocatable[] allocatables = facade.getAllocatables( new ClassificationFilter[] {roomType.newClassificationFilter() });
Allocatable allocatable = facade.edit( allocatables[0]);
allocatable.getClassification().setValue("color", "665532");
String name = (String) allocatable.getClassification().getValue("name");
facade.store( allocatable );
facade.logout();
// We need to disconnect the operator
CachableStorageOperator operator = getContainer().lookup(CachableStorageOperator.class ,"rapladb");
operator.disconnect();
// The error shows when connect again
operator.connect();
facade.login("homer","duffs".toCharArray());
allocatables = facade.getAllocatables( new ClassificationFilter[] {roomType.newClassificationFilter() });
allocatable = facade.edit( allocatables[0]);
assertEquals( name, allocatable.getClassification().getValue("name") );
}
public void testCreateResourceAndRemoveAttribute() throws RaplaException
{
Allocatable newResource = facade1.newResource();
newResource.setClassification( facade1.getDynamicType("room").newClassification());
newResource.getClassification().setValue("name", "test-resource");
//If commented in it works
//newResource.getClassification().setValue("belongsto", facade1.getSuperCategory().getCategory("department").getCategories()[0]);
facade1.store(newResource);
DynamicType typeEdit3 = facade1.edit(facade1.getDynamicType("room"));
typeEdit3.removeAttribute( typeEdit3.getAttribute("belongsto"));
facade1.store(typeEdit3);
}
public void tearDown() throws Exception {
// nochmal ueberpruefen ob die Daten auch wirklich eingelesen werden koennen. This could not be the case
CachableStorageOperator operator = getContainer().lookup(CachableStorageOperator.class ,"rapladb");
operator.disconnect();
Thread.sleep( 200 );
operator.connect();
operator.getVisibleEntities( null );
operator.disconnect();
Thread.sleep( 100 );
super.tearDown();
Thread.sleep(500);
}
}
| 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.tests;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.Date;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.rapla.components.util.DateTools;
import org.rapla.entities.Category;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaException;
import org.rapla.storage.dbsql.DBOperator;
import org.rapla.storage.tests.AbstractOperatorTest;
public class SQLOperatorTest extends AbstractOperatorTest {
public SQLOperatorTest(String name) {
super(name);
}
public void setUp() throws Exception {
super.setUp();
operator.connect();
((DBOperator) operator).removeAll();
operator.disconnect();
operator.connect();
}
public static Test suite() {
return new TestSuite(SQLOperatorTest.class);
}
/** exposes a bug in 1.1
* @throws RaplaException */
public void testPeriodInfitiveEnd() throws RaplaException {
facade.login("homer", "duffs".toCharArray() );
Reservation event = facade.newReservation();
Appointment appointment = facade.newAppointment( new Date(), new Date());
event.getClassification().setValue("name","test");
appointment.setRepeatingEnabled( true );
appointment.getRepeating().setEnd( null );
event.addAppointment( appointment );
facade.store(event);
operator.refresh();
Set<Reservation> singleton = Collections.singleton( event );
Reservation event1 = (Reservation) operator.getPersistant( singleton).get( event);
Repeating repeating = event1.getAppointments()[0].getRepeating();
assertNotNull( repeating );
assertNull( repeating.getEnd());
assertEquals( -1, repeating.getNumber());
}
public void testPeriodStorage() throws RaplaException {
facade.login("homer", "duffs".toCharArray() );
Date start = DateTools.cutDate( new Date());
Date end = new Date( start.getTime() + DateTools.MILLISECONDS_PER_WEEK);
Allocatable period = facade.newPeriod();
Classification c = period.getClassification();
String name = "TEST PERIOD2";
c.setValue("name", name);
c.setValue("start", start );
c.setValue("end", end );
facade.store( period);
operator.refresh();
//Allocatable period1 = (Allocatable) operator.getPersistant( Collections.singleton( period )).get( period);
Period[] periods = facade.getPeriods();
for ( Period period1:periods)
{
if ( period1.getName( null).equals(name))
{
assertEquals( start,period1.getStart());
assertEquals( end, period1.getEnd());
}
}
}
public void testCategoryChange() throws RaplaException {
facade.login("homer", "duffs".toCharArray() );
{
Category category1 = facade.newCategory();
Category category2 = facade.newCategory();
category1.setKey("users1");
category2.setKey("users2");
Category groups = facade.edit(facade.getUserGroupsCategory());
groups.addCategory( category1 );
groups.addCategory( category2 );
facade.store( groups);
Category[] categories = facade.getUserGroupsCategory().getCategories();
assertEquals("users1",categories[3].getKey());
assertEquals("users2",categories[4].getKey());
operator.disconnect();
operator.connect();
facade.refresh();
}
{
Category[] categories = facade.getUserGroupsCategory().getCategories();
assertEquals("users1",categories[3].getKey());
assertEquals("users2",categories[4].getKey());
}
}
public void testDynamicTypeChange() throws Exception
{
facade.login("homer", "duffs".toCharArray() );
DynamicType type = facade.edit(facade.getDynamicType("event"));
String id = type.getId();
Attribute att = facade.newAttribute( AttributeType.STRING);
att.setKey("test-att");
type.addAttribute( att );
facade.store( type);
facade.logout();
printTypeIds();
operator.disconnect();
facade.login("homer", "duffs".toCharArray() );
DynamicType typeAfterEdit = facade.getDynamicType("event");
String idAfterEdit = typeAfterEdit.getId();
assertEquals( id, idAfterEdit);
}
private void printTypeIds() throws RaplaException, SQLException
{
Connection connection = ((DBOperator)operator).createConnection();
String sql ="SELECT * from DYNAMIC_TYPE";
try
{
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(sql);
while ( !set.isLast())
{
set.next();
String idString = set.getString("ID");
String key = set.getString("TYPE_KEY");
System.out.println( "id " + idString + " key " + key);
}
}
catch (SQLException ex)
{
throw new RaplaException( ex);
}
finally
{
connection.close();
}
}
protected String getStorageName() {
return "rapladb";
}
protected String getFacadeName() {
return "sql-facade";
}
}
| 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 junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.internal.RaplaLocaleImpl;
import org.rapla.framework.logger.ConsoleLogger;
public class RaplaLocaleTest extends TestCase {
DefaultConfiguration config;
public RaplaLocaleTest(String name) {
super(name);
}
public static Test suite() {
return new TestSuite(RaplaLocaleTest.class);
}
private DefaultConfiguration createConfig(String defaultLanguage,String countryString) {
DefaultConfiguration config = new DefaultConfiguration("locale");
DefaultConfiguration country = new DefaultConfiguration("country");
country.setValue(countryString);
config.addChild(country);
DefaultConfiguration languages = new DefaultConfiguration("languages");
config.addChild(languages);
languages.setAttribute("default",defaultLanguage);
DefaultConfiguration language1 = new DefaultConfiguration("language");
language1.setValue("de");
DefaultConfiguration language2 = new DefaultConfiguration("language");
language2.setValue("en");
languages.addChild(language1);
languages.addChild(language2);
return config;
}
public void testDateFormat3() throws Exception
{
RaplaLocale raplaLocale = new RaplaLocaleImpl(createConfig("de","DE"), new ConsoleLogger());
String s = raplaLocale.formatDate(new SerializableDateTimeFormat().parseDate("2001-01-12",false));
assertEquals( "12.01.01", s);
}
public void testTimeFormat4()
{
RaplaLocale raplaLocale= new RaplaLocaleImpl(createConfig("en","US"), new ConsoleLogger());
Calendar cal = Calendar.getInstance(raplaLocale.getTimeZone()
,Locale.US);
cal.set(Calendar.HOUR_OF_DAY,21);
cal.set(Calendar.MINUTE,0);
String s = raplaLocale.formatTime(cal.getTime());
assertEquals("9:00 PM", s);
}
}
| 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 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 |
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 |
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 |
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 |
/*--------------------------------------------------------------------------*
| 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 |
/*--------------------------------------------------------------------------*
| 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 |
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 |
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.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 |
/*--------------------------------------------------------------------------*
| 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 |
/*--------------------------------------------------------------------------*
| 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) 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) 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) 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;
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 |
/*--------------------------------------------------------------------------*
| 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.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 |
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 |
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.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.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 |
/*--------------------------------------------------------------------------*
| 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.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 |
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 |
/*--------------------------------------------------------------------------*
| 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;
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 |
package org.rapla;
import java.util.Date;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.framework.RaplaException;
public class HugeDataFileTest extends RaplaTestCase
{
public HugeDataFileTest( String name )
{
super( name );
}
public void testHuge() throws RaplaException, Exception
{
getFacade().login("homer","duffs".toCharArray());
int RESERVATION_COUNT =15000;
Reservation[] events = new Reservation[RESERVATION_COUNT];
for ( int i=0;i<RESERVATION_COUNT;i++)
{
Reservation event = getFacade().newReservation();
Appointment app1 = getFacade().newAppointment( new Date(), new Date());
Appointment app2 = getFacade().newAppointment( new Date(), new Date());
event.addAppointment( app1);
event.addAppointment( app2);
event.getClassification().setValue("name", "Test-Event " + i);
events[i] = event;
}
getLogger().info("Starting store");
getFacade().storeObjects( events );
getFacade().logout();
getLogger().info("Stored");
getFacade().login("homer","duffs".toCharArray());
}
public static void main(String[] args)
{
HugeDataFileTest test = new HugeDataFileTest( HugeDataFileTest.class.getName());
try
{
test.setUp();
test.testHuge();
test.tearDown();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
| 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.TestCase;
import org.rapla.components.util.Tools;
public class ToolsTest extends TestCase {
public ToolsTest(String name) {
super(name);
}
public void testEqualsOrBothNull() {
Integer a = new Integer( 1 );
Integer b = new Integer( 1 );
Integer c = new Integer( 2 );
assertTrue ( a != b );
assertEquals ( a, b );
assertTrue( Tools.equalsOrBothNull( null, null ) );
assertTrue( !Tools.equalsOrBothNull( a, null ) );
assertTrue( !Tools.equalsOrBothNull( null, b ) );
assertTrue( Tools.equalsOrBothNull( a, b ) );
assertTrue( !Tools.equalsOrBothNull( b, c ) );
}
}
| Java |
package org.rapla.entities.tests;
import java.util.UUID;
import org.rapla.RaplaTestCase;
public class IDGeneratorTest extends RaplaTestCase {
public IDGeneratorTest(String name) {
super(name);
}
public void test()
{
UUID randomUUID = UUID.randomUUID();
String string = randomUUID.toString();
System.out.println( "[" + string.length() +"] "+ string );
}
}
| 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 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) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.entities.tests;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/**
For storing date-information (without daytime).
This is only used in the test-cases.
*/
public final class Day implements Comparable<Day>
{
int date = 0;
int month = 0;
int year = 0;
public Day(int year,int month,int date) {
this.year = year;
this.month = month;
this.date = date;
}
public int getDate() {
return date;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
public String toString() {
return getYear() + "-" + getMonth() + "-" + getDate();
}
public Date toDate(TimeZone zone) {
Calendar cal = Calendar.getInstance(zone);
cal.setTime(new Date(0));
cal.set(Calendar.YEAR,getYear());
cal.set(Calendar.MONTH,getMonth() - 1);
cal.set(Calendar.DATE,getDate());
cal.set(Calendar.HOUR_OF_DAY,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
return cal.getTime();
}
public Date toGMTDate() {
TimeZone zone = TimeZone.getTimeZone("GMT+0");
Calendar cal = Calendar.getInstance(zone);
cal.setTime(new Date(0));
cal.set(Calendar.YEAR,getYear());
cal.set(Calendar.MONTH,getMonth() - 1);
cal.set(Calendar.DATE,getDate());
cal.set(Calendar.HOUR_OF_DAY,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
return cal.getTime();
}
public int compareTo(Day day) {
if (getYear() < day.getYear())
return -1;
if (getYear() > day.getYear())
return 1;
if (getMonth() < day.getMonth())
return -1;
if (getMonth() > day.getMonth())
return 1;
if (getDate() < day.getDate())
return -1;
if (getDate() > day.getDate())
return 1;
return 0;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + date;
result = prime * result + month;
result = prime * result + year;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Day other = (Day) obj;
if (date != other.date)
return false;
if (month != other.month)
return false;
if (year != other.year)
return false;
return true;
}
}
| 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.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 |
/*--------------------------------------------------------------------------*
| 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 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) 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.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.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.rapla.components.util.DateTools;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.AppointmentStartComparator;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.RepeatingType;
import org.rapla.entities.domain.internal.AppointmentImpl;
public class AppointmentTest extends TestCase {
TimeZone zone = DateTools.getTimeZone(); //this is GMT
Locale locale = Locale.getDefault();
public AppointmentTest(String name) {
super(name);
}
public static Test suite() {
return new TestSuite(AppointmentTest.class);
}
public void setUp() throws Exception {
}
Appointment createAppointment(Day day,Time start,Time end) {
Calendar cal = Calendar.getInstance(zone,locale);
cal.set(Calendar.YEAR,day.getYear());
cal.set(Calendar.MONTH,day.getMonth() - 1);
cal.set(Calendar.DATE,day.getDate());
cal.set(Calendar.HOUR_OF_DAY,start.getHour());
cal.set(Calendar.MINUTE,start.getMinute());
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
Date startTime = cal.getTime();
cal.set(Calendar.HOUR_OF_DAY,end.getHour());
cal.set(Calendar.MINUTE,end.getMinute());
Date endTime = cal.getTime();
return new AppointmentImpl(startTime,endTime);
}
public void testOverlapAndCompareTo() {
Appointment a1 = createAppointment(new Day(2002,5,25),new Time(12,15),new Time(14,15));
Appointment a2 = createAppointment(new Day(2002,5,26),new Time(13,0),new Time(15,0));
Appointment a3 = createAppointment(new Day(2002,5,25),new Time(13,0),new Time(15,0));
Comparator<Appointment> comp = new AppointmentStartComparator();
// First the single Appointments
assertTrue(comp.compare(a1,a2) == -1);
assertTrue(comp.compare(a2,a1) == 1);
assertTrue(comp.compare(a1,a3) == -1);
assertTrue(comp.compare(a3,a1) == 1);
assertTrue(a1.overlaps(a3));
assertTrue(a3.overlaps(a1));
assertTrue(!a2.overlaps(a3));
assertTrue(!a3.overlaps(a2));
assertTrue(!a1.overlaps(a2));
assertTrue(!a2.overlaps(a1));
// Now we test repeatings
a1.setRepeatingEnabled(true);
a2.setRepeatingEnabled(true);
a3.setRepeatingEnabled(true);
// Weekly repeating until 2002-6-2
Repeating repeating1 = a1.getRepeating();
repeating1.setEnd(new Day(2002,6,2).toDate(zone));
// daily repeating 8x
Repeating repeating2 = a2.getRepeating();
repeating2.setType(Repeating.DAILY);
repeating2.setNumber(8);
// weekly repeating 1x
Repeating repeating3 = a3.getRepeating();
repeating3.setNumber(1);
assertTrue(a1.overlaps(
new Day(2002,5,26).toDate(zone)
,new Day(2002,6,2).toDate(zone)
)
);
assertTrue(a1.overlaps(a2));
assertTrue("overlap is not symetric",a2.overlaps(a1));
assertTrue(a1.overlaps(a3));
assertTrue("overlap is not symetric",a3.overlaps(a1));
assertTrue(!a2.overlaps(a3));
assertTrue("overlap is not symetric",!a3.overlaps(a2));
// No appointment in first week of repeating
repeating1.addException(new Day(2002,5,25).toDate(zone));
assertTrue("appointments should not overlap, because of exception", !a1.overlaps(a3));
assertTrue("overlap is not symetric",!a3.overlaps(a1));
}
public void testOverlap1() {
Appointment a1 = createAppointment(new Day(2002,4,15),new Time(10,0),new Time(12,0));
Appointment a2 = createAppointment(new Day(2002,4,15),new Time(9,0),new Time(11,0));
a1.setRepeatingEnabled(true);
Repeating repeating1 = a1.getRepeating();
repeating1.setEnd(new Day(2002,7,11).toDate(zone));
a2.setRepeatingEnabled(true);
Repeating repeating2 = a2.getRepeating();
repeating2.setType(Repeating.DAILY);
repeating2.setNumber(5);
assertTrue(a1.overlaps(a2));
assertTrue("overlap is not symetric",a2.overlaps(a1));
}
public void testOverlap2() {
Appointment a1 = createAppointment(new Day(2002,4,12),new Time(12,0),new Time(14,0));
a1.setRepeatingEnabled(true);
Repeating repeating1 = a1.getRepeating();
repeating1.setEnd(new Day(2002,7,11).toDate(zone));
assertTrue(a1.overlaps(new Day(2002,4,15).toDate(zone)
, new Day(2002,4,22).toDate(zone)));
}
public void testOverlap3() {
final Appointment a1,a2;
{
final Appointment a = createAppointment(new Day(2012,3,9),new Time(9,0),new Time(11,0));
a.setRepeatingEnabled(true);
Repeating repeating = a.getRepeating();
repeating.setEnd(new Day(2012,4,15).toDate(zone));
repeating.addException(new Day(2012,4,6).toDate(zone));
a1 = a;
}
{
final Appointment a = createAppointment(new Day(2012,3,2),new Time(9,0),new Time(11,0));
a.setRepeatingEnabled(true);
Repeating repeating = a.getRepeating();
repeating.setEnd(new Day(2012,4,1).toDate(zone));
repeating.addException(new Day(2012,3,16).toDate(zone));
a2 = a;
}
boolean overlap1 = a1.overlaps(a2);
boolean overlap2 = a2.overlaps(a1);
assertTrue(overlap1);
assertTrue(overlap2);
}
public void testBlocks() {
Appointment a1 = createAppointment(new Day(2002,4,12),new Time(12,0),new Time(14,0));
a1.setRepeatingEnabled(true);
Repeating repeating1 = a1.getRepeating();
repeating1.setEnd(new Day(2002,2,11).toDate(zone));
List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
a1.createBlocks( new Day(2002,4,5).toDate(zone)
, new Day(2002,5,5).toDate(zone)
, blocks );
assertEquals( "Repeating end is in the past: createBlocks should only return one block", 1, blocks.size() );
}
public void testMatchNeverEnding() {
Appointment a1 = createAppointment(new Day(2002,5,25),new Time(11,15),new Time(13,15));
Appointment a2 = createAppointment(new Day(2002,5,25),new Time(11,15),new Time(13,15));
a1.setRepeatingEnabled(true);
Repeating repeating1 = a1.getRepeating();
repeating1.setType(Repeating.WEEKLY);
a2.setRepeatingEnabled(true);
Repeating repeating2 = a2.getRepeating();
repeating2.setType(Repeating.WEEKLY);
repeating1.addException(new Day(2002,4,10).toDate( zone ));
assertTrue( !a1.matches( a2 ) );
assertTrue( !a2.matches( a1 ) );
}
public void testMonthly()
{
Appointment a1 = createAppointment(new Day(2006,8,17),new Time(10,30),new Time(12,0));
Date start = a1.getStart();
a1.setRepeatingEnabled(true);
Repeating repeating1 = a1.getRepeating();
repeating1.setType( RepeatingType.MONTHLY);
repeating1.setNumber( 4);
List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
a1.createBlocks( new Day(2006,8,17).toGMTDate(), new Day( 2007, 3, 30).toGMTDate(), blocks);
assertEquals( 4, blocks.size());
Collections.sort(blocks);
assertEquals( start, new Date(blocks.get( 0).getStart()));
Calendar cal = createGMTCalendar();
cal.setTime( start );
int weekday = cal.get( Calendar.DAY_OF_WEEK);
int dayofweekinmonth = cal.get( Calendar.DAY_OF_WEEK_IN_MONTH);
assertEquals( Calendar.THURSDAY,weekday );
assertEquals( 3, dayofweekinmonth );
assertEquals( Calendar.AUGUST, cal.get( Calendar.MONTH));
// we expect the second wednesday in april
cal.add( Calendar.MONTH, 1 );
cal.set( Calendar.DAY_OF_WEEK , weekday );
cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth);
start = cal.getTime();
assertEquals( start, new Date(blocks.get( 1).getStart()));
cal.add( Calendar.MONTH, 1 );
cal.set( Calendar.DAY_OF_WEEK , weekday );
cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth);
assertEquals(10, cal.get( Calendar.HOUR_OF_DAY));
start = cal.getTime();
assertEquals( start, new Date(blocks.get( 2).getStart()));
cal.add( Calendar.MONTH, 1 );
cal.set( Calendar.DAY_OF_WEEK , weekday );
cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth);
start = cal.getTime();
assertEquals( start, new Date(blocks.get( 3).getStart()));
assertEquals( start, repeating1.getEnd() );
assertEquals( start, a1.getMaxEnd() );
blocks.clear();
a1.createBlocks( new Day(2006,1,1).toGMTDate(), new Day( 2007, 10, 20).toGMTDate(), blocks);
assertEquals( 4, blocks.size());
blocks.clear();
a1.createBlocks( new Day(2006,10,19).toGMTDate(), new Day( 2006, 10, 20).toGMTDate(), blocks);
assertEquals( 1, blocks.size());
}
public void testMonthly5ft()
{
Appointment a1 = createAppointment(new Day(2006,8,31),new Time(10,30),new Time(12,0));
Date start = a1.getStart();
a1.setRepeatingEnabled(true);
Repeating repeating1 = a1.getRepeating();
repeating1.setType( RepeatingType.MONTHLY);
repeating1.setNumber( 4);
List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
a1.createBlocks( new Day(2006,8,1).toGMTDate(), new Day( 2008, 8, 1).toGMTDate(), blocks);
assertEquals( 4, blocks.size());
Collections.sort( blocks);
assertEquals( start, new Date(blocks.get(0).getStart()));
Calendar cal = createGMTCalendar();
cal.setTime( start );
int weekday = cal.get( Calendar.DAY_OF_WEEK);
int dayofweekinmonth = cal.get( Calendar.DAY_OF_WEEK_IN_MONTH);
assertEquals( Calendar.THURSDAY,weekday );
assertEquals( 5, dayofweekinmonth );
assertEquals( Calendar.AUGUST, cal.get( Calendar.MONTH));
cal.set( Calendar.MONTH, Calendar.NOVEMBER );
cal.set( Calendar.DAY_OF_WEEK , weekday );
cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth);
start = cal.getTime();
assertEquals( start, new Date(blocks.get(1).getStart()));
cal.add( Calendar.YEAR,1);
cal.set( Calendar.MONTH, Calendar.MARCH );
cal.set( Calendar.DAY_OF_WEEK , weekday );
cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth);
assertEquals(10, cal.get( Calendar.HOUR_OF_DAY));
start = cal.getTime();
assertEquals( start, new Date(blocks.get(2).getStart()));
cal.set( Calendar.MONTH, Calendar.MAY );
cal.set( Calendar.DAY_OF_WEEK , weekday );
cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth);
start = cal.getTime();
assertEquals( start, new Date(blocks.get(3).getStart()));
assertEquals( start, repeating1.getEnd() );
assertEquals( start, a1.getMaxEnd() );
blocks.clear();
a1.createBlocks( new Day(2006,1,1).toGMTDate(), new Day( 2007, 10, 20).toGMTDate(), blocks);
assertEquals( 4, blocks.size());
blocks.clear();
a1.createBlocks( new Day(2006,10,19).toGMTDate(), new Day( 2006, 11, 31).toGMTDate(), blocks);
assertEquals( 1, blocks.size());
}
public void testMonthlyNeverending()
{
Appointment a1 = createAppointment(new Day(2006,8,31),new Time(10,30),new Time(12,0));
Date start = a1.getStart();
a1.setRepeatingEnabled(true);
Repeating repeating1 = a1.getRepeating();
repeating1.setType( RepeatingType.MONTHLY);
repeating1.setEnd( null );
List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
a1.createBlocks( new Day(2006,8,1).toGMTDate(), new Day( 2008, 8, 1).toGMTDate(), blocks);
assertEquals( 9, blocks.size());
assertEquals( start, new Date(blocks.get(0).getStart()));
Calendar cal = createGMTCalendar();
cal.setTime( start );
int weekday = cal.get( Calendar.DAY_OF_WEEK);
int dayofweekinmonth = cal.get( Calendar.DAY_OF_WEEK_IN_MONTH);
assertEquals( Calendar.THURSDAY,weekday );
assertEquals( 5, dayofweekinmonth );
assertEquals( Calendar.AUGUST, cal.get( Calendar.MONTH));
cal.set( Calendar.MONTH, Calendar.NOVEMBER );
cal.set( Calendar.DAY_OF_WEEK , weekday );
cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth);
start = cal.getTime();
assertEquals( start, new Date(blocks.get(1).getStart()));
cal.add( Calendar.YEAR,1);
cal.set( Calendar.MONTH, Calendar.MARCH );
cal.set( Calendar.DAY_OF_WEEK , weekday );
cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth);
assertEquals(10, cal.get( Calendar.HOUR_OF_DAY));
start = cal.getTime();
assertEquals( start, new Date(blocks.get(2).getStart()));
cal.set( Calendar.MONTH, Calendar.MAY );
cal.set( Calendar.DAY_OF_WEEK , weekday );
cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth);
start = cal.getTime();
assertEquals( start, new Date(blocks.get(3).getStart()));
blocks.clear();
a1.createBlocks( new Day(2006,1,1).toGMTDate(), new Day( 2007, 10, 20).toGMTDate(), blocks);
assertEquals( 5, blocks.size());
}
public void testYearly29February()
{
Appointment a1 = createAppointment(new Day(2004,2,29),new Time(10,30),new Time(12,0));
Date start = a1.getStart();
a1.setRepeatingEnabled(true);
Repeating repeating1 = a1.getRepeating();
repeating1.setType( RepeatingType.YEARLY);
repeating1.setNumber( 4);
List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
a1.createBlocks( new Day(2004,1,1).toGMTDate(), new Day( 2020, 1, 1).toGMTDate(), blocks);
assertEquals( 4, blocks.size());
assertEquals( start, new Date(blocks.get(0).getStart()));
Calendar cal = createGMTCalendar();
cal.setTime( start );
int weekday = cal.get( Calendar.DAY_OF_WEEK);
int dayofweekinmonth = cal.get( Calendar.DAY_OF_WEEK_IN_MONTH);
assertEquals( Calendar.SUNDAY,weekday );
assertEquals( 5, dayofweekinmonth );
assertEquals( Calendar.FEBRUARY, cal.get( Calendar.MONTH));
cal.add( Calendar.YEAR,4);
cal.set( Calendar.MONTH, Calendar.FEBRUARY );
cal.set( Calendar.DAY_OF_MONTH , 29 );
start = cal.getTime();
assertEquals( start, new Date(blocks.get(1).getStart()));
cal.add( Calendar.YEAR,4);
cal.set( Calendar.MONTH, Calendar.FEBRUARY );
cal.set( Calendar.DAY_OF_MONTH , 29 );
assertEquals(10, cal.get( Calendar.HOUR_OF_DAY));
start = cal.getTime();
assertEquals( start, new Date(blocks.get(2).getStart()));
cal.add( Calendar.YEAR,4);
cal.set( Calendar.MONTH, Calendar.FEBRUARY );
cal.set( Calendar.DAY_OF_MONTH , 29 );
start = cal.getTime();
assertEquals( start, new Date(blocks.get(3).getStart()));
assertEquals( start, repeating1.getEnd() );
assertEquals( start, a1.getMaxEnd() );
blocks.clear();
a1.createBlocks( new Day(2006,1,1).toGMTDate(), new Day( 2012, 10, 20).toGMTDate(), blocks);
assertEquals( 2, blocks.size());
blocks.clear();
a1.createBlocks( new Day(2008,1,1).toGMTDate(), new Day( 2008, 11, 31).toGMTDate(), blocks);
assertEquals( 1, blocks.size());
}
public void testYearly()
{
Appointment a1 = createAppointment(new Day(2006,8,17),new Time(10,30),new Time(12,0));
Date start = a1.getStart();
a1.setRepeatingEnabled(true);
Repeating repeating1 = a1.getRepeating();
repeating1.setType( RepeatingType.YEARLY );
repeating1.setNumber( 4);
Calendar cal = createGMTCalendar();
cal.setTime( start );
int dayInMonth = cal.get( Calendar.DAY_OF_MONTH);
int month = cal.get( Calendar.MONTH);
List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
a1.createBlocks( new Day(2006,8,17).toGMTDate(), new Day( 2010, 3, 30).toGMTDate(), blocks);
assertEquals( 4, blocks.size());
assertEquals( start, new Date(blocks.get(0).getStart()));
cal.add( Calendar.YEAR, 1 );
start = cal.getTime();
assertEquals( start, new Date(blocks.get(1).getStart()));
cal.add( Calendar.YEAR, 1 );
start = cal.getTime();
assertEquals( start, new Date(blocks.get(2).getStart()));
cal.add( Calendar.YEAR, 1 );
start = cal.getTime();
assertEquals( dayInMonth,cal.get(Calendar.DAY_OF_MONTH));
assertEquals( month,cal.get(Calendar.MONTH));
assertEquals( start, new Date(blocks.get(3).getStart()));
assertEquals( start, repeating1.getEnd() );
assertEquals( start, a1.getMaxEnd() );
}
private Calendar createGMTCalendar() {
return Calendar.getInstance( DateTools.getTimeZone());
}
public void testMonthlySetEnd()
{
Appointment a1 = createAppointment(new Day(2006,8,17),new Time(10,30),new Time(12,0));
Date start = a1.getStart();
a1.setRepeatingEnabled(true);
Repeating repeating1 = a1.getRepeating();
repeating1.setType( RepeatingType.MONTHLY);
repeating1.setEnd( new Day(2006,12,1).toGMTDate());
List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
{
Date s = new Day(2006,8,17).toGMTDate();
Date e = new Day( 2007, 3, 30).toGMTDate();
a1.createBlocks( s,e , blocks);
}
assertEquals( 4, blocks.size());
assertEquals( start, new Date(blocks.get(0).getStart()));
Calendar cal = createGMTCalendar();
cal.setTime( start );
int weekday = cal.get( Calendar.DAY_OF_WEEK);
int dayofweekinmonth = cal.get( Calendar.DAY_OF_WEEK_IN_MONTH);
assertEquals( Calendar.THURSDAY,weekday );
assertEquals( 3, dayofweekinmonth );
assertEquals( Calendar.AUGUST, cal.get( Calendar.MONTH));
cal.add( Calendar.MONTH, 1 );
cal.set( Calendar.DAY_OF_WEEK , weekday );
cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth);
start = cal.getTime();
assertEquals( start, new Date(blocks.get(1).getStart()));
cal.add( Calendar.MONTH, 1 );
cal.set( Calendar.DAY_OF_WEEK , weekday );
cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth);
assertEquals(10, cal.get( Calendar.HOUR_OF_DAY));
start = cal.getTime();
assertEquals( start, new Date(blocks.get(2).getStart()));
cal.add( Calendar.MONTH, 1 );
cal.set( Calendar.DAY_OF_WEEK , weekday );
cal.set( Calendar.DAY_OF_WEEK_IN_MONTH, dayofweekinmonth);
start = cal.getTime();
assertEquals( start, new Date(blocks.get(3).getStart()));
assertEquals( new Day(2006,12,1).toGMTDate(), repeating1.getEnd() );
assertEquals( new Day(2006,12,1).toGMTDate(), a1.getMaxEnd() );
blocks.clear();
a1.createBlocks( new Day(2006,1,1).toGMTDate(), new Day( 2007, 10, 20).toGMTDate(), blocks);
assertEquals( 4, blocks.size());
blocks.clear();
a1.createBlocks( new Day(2006,10,19).toGMTDate(), new Day( 2006, 10, 20).toGMTDate(), blocks);
assertEquals( 1, blocks.size());
}
}
| 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.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 |
/*
Copyright 2012 Mattias Jiderhamn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package se.jiderhamn.classloader.leak.prevention;
import java.beans.PropertyEditorManager;
import java.lang.management.ManagementFactory;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Authenticator;
import java.net.URL;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
/** Changed by Christopher Kohlhaas
* Modified from the original uncommented the following line
* //java.awt.Toolkit.getDefaultToolkit(); // Will start a Thread
* //javax.imageio.ImageIO.getCacheDirectory(); // Will call sun.awt.AppContext.getAppContext()
* and added the JettyRemover
*/
/**
* This class helps prevent classloader leaks.
* <h1>Basic setup</h1>
* <p>Activate protection by adding this class as a context listener
* in your <code>web.xml</code>, like this:</p>
* <pre>
* <listener>
* <listener-class>se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor</listener-class>
* </listener>
* </pre>
*
* You should usually declare this <code>listener</code> before any other listeners, to make it "outermost".
*
* <h1>Configuration</h1>
* The context listener has a number of settings that can be configured with context parameters in <code>web.xml</code>,
* i.e.:
*
* <pre>
* <context-param>
* <param-name>ClassLoaderLeakPreventor.stopThreads</param-name>
* <param-value>false</param-value>
* </context-param>
* </pre>
*
* The available settings are
* <table border="1">
* <tr>
* <th>Parameter name</th>
* <th>Default value</th>
* <th>Description</th>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.stopThreads</code></td>
* <td><code>true</code></td>
* <td>Should threads tied to the web app classloader be forced to stop at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.stopTimerThreads</code></td>
* <td><code>true</code></td>
* <td>Should Timer threads tied to the web app classloader be forced to stop at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.executeShutdownHooks</td>
* <td><code>true</code></td>
* <td>Should shutdown hooks registered from the application be executed at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.threadWaitMs</td>
* <td><code>5000</code> (5 seconds)</td>
* <td>No of milliseconds to wait for threads to finish execution, before stopping them.</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.shutdownHookWaitMs</code></td>
* <td><code>10000</code> (10 seconds)</td>
* <td>
* No of milliseconds to wait for shutdown hooks to finish execution, before stopping them.
* If set to -1 there will be no waiting at all, but Thread is allowed to run until finished.
* </td>
* </tr>
* </table>
*
*
* <h1>License</h1>
* <p>This code is licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2</a> license,
* which allows you to include modified versions of the code in your distributed software, without having to release
* your source code.</p>
*
* <h1>More info</h1>
* <p>For more info, see
* <a href="http://java.jiderhamn.se/2012/03/04/classloader-leaks-vi-this-means-war-leak-prevention-library/">here</a>.
* </p>
*
* <h1>Design goals</h1>
* <p>If you want to help improve this component, you should be aware of the design goals</p>
* <p>
* Primary design goal: Zero dependencies. The component should build and run using nothing but the JDK and the
* Servlet API. Specifically we should <b>not</b> depend on any logging framework, since they are part of the problem.
* We also don't want to use any utility libraries, in order not to impose any further dependencies into any project
* that just wants to get rid of classloader leaks.
* Access to anything outside of the standard JDK (in order to prevent a known leak) should be managed
* with reflection.
* </p>
* <p>
* Secondary design goal: Keep the runtime component in a single <code>.java</code> file. It should be possible to
* just add this one <code>.java</code> file into your own source tree.
* </p>
*
* @author Mattias Jiderhamn, 2012-2013
*/
public class ClassLoaderLeakPreventor implements javax.servlet.ServletContextListener {
/** Default no of milliseconds to wait for threads to finish execution */
public static final int THREAD_WAIT_MS_DEFAULT = 5 * 1000; // 5 seconds
/** Default no of milliseconds to wait for shutdown hook to finish execution */
public static final int SHUTDOWN_HOOK_WAIT_MS_DEFAULT = 10 * 1000; // 10 seconds
public static final String JURT_ASYNCHRONOUS_FINALIZER = "com.sun.star.lib.util.AsynchronousFinalizer";
///////////
// Settings
/** Should threads tied to the web app classloader be forced to stop at application shutdown? */
protected boolean stopThreads = true;
/** Should Timer threads tied to the web app classloader be forced to stop at application shutdown? */
protected boolean stopTimerThreads = true;
/** Should shutdown hooks registered from the application be executed at application shutdown? */
protected boolean executeShutdownHooks = true;
/**
* No of milliseconds to wait for threads to finish execution, before stopping them.
*/
protected int threadWaitMs = SHUTDOWN_HOOK_WAIT_MS_DEFAULT;
/**
* No of milliseconds to wait for shutdown hooks to finish execution, before stopping them.
* If set to -1 there will be no waiting at all, but Thread is allowed to run until finished.
*/
protected int shutdownHookWaitMs = SHUTDOWN_HOOK_WAIT_MS_DEFAULT;
/** Is it possible, that we are running under JBoss? */
private boolean mayBeJBoss = false;
protected final Field java_lang_Thread_threadLocals;
protected final Field java_lang_Thread_inheritableThreadLocals;
protected final Field java_lang_ThreadLocal$ThreadLocalMap_table;
protected Field java_lang_ThreadLocal$ThreadLocalMap$Entry_value;
public ClassLoaderLeakPreventor() {
// Initialize some reflection variables
java_lang_Thread_threadLocals = findField(Thread.class, "threadLocals");
java_lang_Thread_inheritableThreadLocals = findField(Thread.class, "inheritableThreadLocals");
java_lang_ThreadLocal$ThreadLocalMap_table = findFieldOfClass("java.lang.ThreadLocal$ThreadLocalMap", "table");
if(java_lang_Thread_threadLocals == null)
error("java.lang.Thread.threadLocals not found; something is seriously wrong!");
if(java_lang_Thread_inheritableThreadLocals == null)
error("java.lang.Thread.inheritableThreadLocals not found; something is seriously wrong!");
if(java_lang_ThreadLocal$ThreadLocalMap_table == null)
error("java.lang.ThreadLocal$ThreadLocalMap.table not found; something is seriously wrong!");
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Implement javax.servlet.ServletContextListener
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void contextInitialized(ServletContextEvent servletContextEvent) {
final ServletContext servletContext = servletContextEvent.getServletContext();
stopThreads = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopThreads"));
stopTimerThreads = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopTimerThreads"));
executeShutdownHooks = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.executeShutdownHooks"));
threadWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.threadWaitMs", THREAD_WAIT_MS_DEFAULT);
shutdownHookWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.shutdownHookWaitMs", SHUTDOWN_HOOK_WAIT_MS_DEFAULT);
info("Settings for " + this.getClass().getName() + " (CL: 0x" +
Integer.toHexString(System.identityHashCode(getWebApplicationClassLoader())) + "):");
info(" stopThreads = " + stopThreads);
info(" stopTimerThreads = " + stopTimerThreads);
info(" executeShutdownHooks = " + executeShutdownHooks);
info(" threadWaitMs = " + threadWaitMs + " ms");
info(" shutdownHookWaitMs = " + shutdownHookWaitMs + " ms");
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
try {
// If package org.jboss is found, we may be running under JBoss
mayBeJBoss = (contextClassLoader.getResource("org/jboss") != null);
}
catch(Exception ex) {
// Do nothing
}
info("Initializing context by loading some known offenders with system classloader");
// This part is heavily inspired by Tomcats JreMemoryLeakPreventionListener
// See http://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java?view=markup
try {
// Switch to system classloader in before we load/call some JRE stuff that will cause
// the current classloader to be available for garbage collection
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
// Christopher: Uncommented as it will not work on some containers as google app engine
//java.awt.Toolkit.getDefaultToolkit(); // Will start a Thread
java.security.Security.getProviders();
java.sql.DriverManager.getDrivers(); // Load initial drivers using system classloader
// Christopher: Uncommented as it will not work on some containers as google app engine
//javax.imageio.ImageIO.getCacheDirectory(); // Will call sun.awt.AppContext.getAppContext()
try {
Class.forName("javax.security.auth.Policy")
.getMethod("getPolicy")
.invoke(null);
}
catch (IllegalAccessException iaex) {
error(iaex);
}
catch (InvocationTargetException itex) {
error(itex);
}
catch (NoSuchMethodException nsmex) {
error(nsmex);
}
catch (ClassNotFoundException e) {
// Ignore silently - class is deprecated
}
try {
javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
}
catch (Exception ex) { // Example: ParserConfigurationException
error(ex);
}
try {
Class.forName("javax.xml.bind.DatatypeConverterImpl"); // Since JDK 1.6. May throw java.lang.Error
}
catch (ClassNotFoundException e) {
// Do nothing
}
try {
Class.forName("javax.security.auth.login.Configuration", true, ClassLoader.getSystemClassLoader());
}
catch (ClassNotFoundException e) {
// Do nothing
}
// This probably does not affect classloaders, but prevents some problems with .jar files
try {
// URL needs to be well-formed, but does not need to exist
new URL("jar:file://dummy.jar!/").openConnection().setDefaultUseCaches(false);
}
catch (Exception ex) {
error(ex);
}
/////////////////////////////////////////////////////
// Load Sun specific classes that may cause leaks
final boolean isSunJRE = System.getProperty("java.vendor").startsWith("Sun");
try {
Class.forName("com.sun.jndi.ldap.LdapPoolManager");
}
catch(ClassNotFoundException cnfex) {
if(isSunJRE)
error(cnfex);
}
try {
Class.forName("sun.java2d.Disposer"); // Will start a Thread
}
catch (ClassNotFoundException cnfex) {
if(isSunJRE && ! mayBeJBoss) // JBoss blocks this package/class, so don't warn
error(cnfex);
}
try {
Class<?> gcClass = Class.forName("sun.misc.GC");
final Method requestLatency = gcClass.getDeclaredMethod("requestLatency", long.class);
requestLatency.invoke(null, 3600000L);
}
catch (ClassNotFoundException cnfex) {
if(isSunJRE)
error(cnfex);
}
catch (NoSuchMethodException nsmex) {
error(nsmex);
}
catch (IllegalAccessException iaex) {
error(iaex);
}
catch (InvocationTargetException itex) {
error(itex);
}
// Cause oracle.jdbc.driver.OracleTimeoutPollingThread to be started with contextClassLoader = system classloader
try {
Class.forName("oracle.jdbc.driver.OracleTimeoutThreadPerVM");
} catch (ClassNotFoundException e) {
// Ignore silently - class not present
}
}
catch (Throwable ex)
{
error( ex);
}
finally {
// Reset original classloader
Thread.currentThread().setContextClassLoader(contextClassLoader);
}
}
@SuppressWarnings("unchecked")
public void contextDestroyed(ServletContextEvent servletContextEvent) {
final boolean jvmIsShuttingDown = isJvmShuttingDown();
if(jvmIsShuttingDown) {
info("JVM is shutting down - skip cleanup");
return; // Don't do anything more
}
info(getClass().getName() + " shutting down context by removing known leaks (CL: 0x" +
Integer.toHexString(System.identityHashCode(getWebApplicationClassLoader())) + ")");
//////////////////
// Fix known leaks
//////////////////
java.beans.Introspector.flushCaches(); // Clear cache of strong references
// Apache Commons Pool can leave unfinished threads. Anything specific we can do?
clearBeanELResolverCache();
fixBeanValidationApiLeak();
fixJsfLeak();
fixGeoToolsLeak();
// Can we do anything about Google Guice ?
// Can we do anything about Groovy http://jira.codehaus.org/browse/GROOVY-4154 ?
clearIntrospectionUtilsCache();
// Can we do anything about Logback http://jira.qos.ch/browse/LBCORE-205 ?
// Force the execution of the cleanup code for JURT; see https://issues.apache.org/ooo/show_bug.cgi?id=122517
forceStartOpenOfficeJurtCleanup();
////////////////////
// Fix generic leaks
// Deregister JDBC drivers contained in web application
deregisterJdbcDrivers();
// Unregister MBeans loaded by the web application class loader
unregisterMBeans();
// Deregister shutdown hooks - execute them immediately
deregisterShutdownHooks();
deregisterPropertyEditors();
deregisterSecurityProviders();
clearDefaultAuthenticator();
deregisterRmiTargets();
clearThreadLocalsOfAllThreads();
stopThreads();
destroyThreadGroups();
unsetCachedKeepAliveTimer();
try {
try { // First try Java 1.6 method
final Method clearCache16 = ResourceBundle.class.getMethod("clearCache", ClassLoader.class);
debug("Since Java 1.6+ is used, we can call " + clearCache16);
clearCache16.invoke(null, getWebApplicationClassLoader());
}
catch (NoSuchMethodException e) {
// Not Java 1.6+, we have to clear manually
final Map<?,?> cacheList = getStaticFieldValue(ResourceBundle.class, "cacheList"); // Java 5: SoftCache extends AbstractMap
final Iterator<?> iter = cacheList.keySet().iterator();
Field loaderRefField = null;
while(iter.hasNext()) {
Object key = iter.next(); // CacheKey
if(loaderRefField == null) { // First time
loaderRefField = key.getClass().getDeclaredField("loaderRef");
loaderRefField.setAccessible(true);
}
WeakReference<ClassLoader> loaderRef = (WeakReference<ClassLoader>) loaderRefField.get(key); // LoaderReference extends WeakReference
ClassLoader classLoader = loaderRef.get();
if(isWebAppClassLoaderOrChild(classLoader)) {
info("Removing ResourceBundle from cache: " + key);
iter.remove();
}
}
}
}
catch(Exception ex) {
error(ex);
}
// (CacheKey of java.util.ResourceBundle.NONEXISTENT_BUNDLE will point to first referring classloader...)
// Release this classloader from Apache Commons Logging (ACL) by calling
// LogFactory.release(getCurrentClassLoader());
// Use reflection in case ACL is not present.
// Do this last, in case other shutdown procedures want to log something.
final Class logFactory = findClass("org.apache.commons.logging.LogFactory");
if(logFactory != null) { // Apache Commons Logging present
info("Releasing web app classloader from Apache Commons Logging");
try {
logFactory.getMethod("release", java.lang.ClassLoader.class)
.invoke(null, getWebApplicationClassLoader());
}
catch (Exception ex) {
error(ex);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Fix generic leaks
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Deregister JDBC drivers loaded by web app classloader */
public void deregisterJdbcDrivers() {
final List<Driver> driversToDeregister = new ArrayList<Driver>();
final Enumeration<Driver> allDrivers = DriverManager.getDrivers();
while(allDrivers.hasMoreElements()) {
final Driver driver = allDrivers.nextElement();
if(isLoadedInWebApplication(driver)) // Should be true for all returned by DriverManager.getDrivers()
driversToDeregister.add(driver);
}
for(Driver driver : driversToDeregister) {
try {
warn("JDBC driver loaded by web app deregistered: " + driver.getClass());
DriverManager.deregisterDriver(driver);
}
catch (SQLException e) {
error(e);
}
}
}
/** Unregister MBeans loaded by the web application class loader */
protected void unregisterMBeans() {
try {
JettyJMXRemover jettyJMXRemover = null;
// If you enable jmx support in jetty 8 or 9 some mbeans (e.g. for the servletholder or sessionmanager) are instanciated in the web application thread
// and a reference to the WebappClassloader is stored in a private ObjectMBean._loader which is unfortunatly not the classloader that loaded the class.
// So for unregisterMBeans to work even for the jetty mbeans we need to access the MBeanContainer class of the jetty container.
try {
jettyJMXRemover = new JettyJMXRemover(getWebApplicationClassLoader());
} catch (Exception ex) {
error( ex);
}
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
final Set<ObjectName> allMBeanNames = mBeanServer.queryNames(new ObjectName("*:*"), null);
for(ObjectName objectName : allMBeanNames) {
try {
if ( jettyJMXRemover != null && jettyJMXRemover.unregisterJettyJMXBean(objectName))
{
continue;
}
final ClassLoader mBeanClassLoader = mBeanServer.getClassLoaderFor(objectName);
if(isWebAppClassLoaderOrChild(mBeanClassLoader)) { // MBean loaded in web application
warn("MBean '" + objectName + "' was loaded in web application; unregistering");
mBeanServer.unregisterMBean(objectName);
}
}
catch(Exception e) { // MBeanRegistrationException / InstanceNotFoundException
error(e);
}
}
}
catch (Exception e) { // MalformedObjectNameException
error(e);
}
}
/**
* removes the ObjectMBean beans created by the jetty MBeanContainer for each webapp context such as
* Mbeans for SessionHandler,ServletHandler and ServletMappings
*/
private class JettyJMXRemover
{
Object[] objectsWrappedWithMBean;
Object beanContainer;
private Method findBeanM;
private Method removeBeanM;
@SuppressWarnings("unchecked")
public JettyJMXRemover(ClassLoader classLoader) throws Exception
{
try
{
// If package org.eclipse.jetty is found, we may be running under jetty
if (classLoader.getResource("org/eclipse/jetty") == null)
{
return;
}
}
catch(Exception ex) {
return;
}
// Jetty not started with jmx or webappcontext so an unregister of webappcontext JMX beans is not neccessary.
try {
Class.forName("org.eclipse.jetty.jmx.MBeanContainer", false, classLoader.getParent());
Class.forName("org.eclipse.jetty.webapp.WebAppContext", false, classLoader.getParent());
}
catch (Exception e1) {
return;
}
// first we need to access the necessary classes via reflection (are all loaded, because webapplication is already initialized)
final Class WebAppClassLoaderC = Class.forName("org.eclipse.jetty.webapp.WebAppClassLoader");
final Class WebAppContextC = Class.forName("org.eclipse.jetty.webapp.WebAppContext");
final Class ServerC = Class.forName("org.eclipse.jetty.server.Server");
final Class SessionHandlerC = Class.forName("org.eclipse.jetty.server.session.SessionHandler");
final Class MBeanContainerC = Class.forName("org.eclipse.jetty.jmx.MBeanContainer");
final Class SessionManagerC = Class.forName("org.eclipse.jetty.server.SessionManager");
final Class ServletHandlerC = Class.forName("org.eclipse.jetty.servlet.ServletHandler");
// first we need access to the MBeanContainer to access the beans
//WebAppContext webappContext = (WebAppContext)servletContext;
final Object webappContext = WebAppClassLoaderC.getMethod("getContext").invoke(classLoader);
if (webappContext == null)
{
return;
}
//Server server = (Server)webappContext.getServer();
final Object server = WebAppContextC.getMethod("getServer").invoke(webappContext);
if ( server == null)
{
return;
}
//MBeanContainer beanContainer = (MBeanContainer)server.getBean( MBeanContainer.class);
beanContainer = ServerC.getMethod("getBean", Class.class).invoke( server, MBeanContainerC);
findBeanM = MBeanContainerC.getMethod("findBean", ObjectName.class);
removeBeanM = MBeanContainerC.getMethod("removeBean", Object.class);
// now we store all objects that belong to the webapplication and that will be wrapped by mbeans in a list
if ( beanContainer !=null )
{
List list = new ArrayList();
//SessionHandler sessionHandler =webappContext.getSessionHandler();
final Object sessionHandler = WebAppContextC.getMethod("getSessionHandler").invoke( webappContext);
if (sessionHandler != null)
{
list.add( sessionHandler);
//SessionManager sessionManager = sessionHandler.getSessionManager();
final Object sessionManager = SessionHandlerC.getMethod("getSessionManager").invoke( sessionHandler);
if ( sessionManager != null)
{
list.add( sessionManager);
//SessionIdManager sessionIdManager = sessionManager.getSessionIdManager();
final Object sessionIdManager = SessionManagerC.getMethod("getSessionIdManager").invoke( sessionManager);
if (sessionIdManager != null)
{
list.add( sessionIdManager);
}
}
}
//SecurityHandler securityHandler = webappContext.getSecurityHandler();
final Object securityHandler = WebAppContextC.getMethod("getSecurityHandler").invoke( webappContext);
if ( securityHandler != null )
{
list.add( securityHandler);
}
//ServletHandler servletHandler = webappContext.getServletHandler();
final Object servletHandler = WebAppContextC.getMethod("getServletHandler").invoke( webappContext);
if ( servletHandler != null)
{
list.add( servletHandler );
//Object[] servletMappings = servletHandler.getServletMappings();
final Object[] servletMappings = (Object[]) ServletHandlerC.getMethod("getServletMappings").invoke( servletHandler);
list.addAll( Arrays.asList(servletMappings ));
//Object[] servlets = servletHandler.getServlets();
final Object[] servlets = (Object[]) ServletHandlerC.getMethod("getServlets").invoke( servletHandler);
list.addAll( Arrays.asList(servlets ));
}
this.objectsWrappedWithMBean = list.toArray();
}
}
boolean unregisterJettyJMXBean(ObjectName objectName)
{
if ( objectsWrappedWithMBean == null || objectName.getDomain() == null || !objectName.getDomain().contains("org.eclipse.jetty"))
{
return false;
}
else
{
try
{
Object obj = findBeanM.invoke(beanContainer, objectName);
// look if obj is in the suspect list
for ( Object o: objectsWrappedWithMBean)
{
if ( o == obj)
{
warn("MBean '" + objectName + "' is a suspect in causing memory leaks; unregistering");
// and remove it via the MBeanContainer
removeBeanM.invoke(beanContainer, obj);
return true;
}
}
}
catch (Exception ex) {
error( ex);
}
return false;
}
}
}
/** Find and deregister shutdown hooks. Will by default execute the hooks after removing them. */
protected void deregisterShutdownHooks() {
// We will not remove known shutdown hooks, since loading the owning class of the hook,
// may register the hook if previously unregistered
@SuppressWarnings("unchecked")
Map<Thread, Thread> shutdownHooks = (Map<Thread, Thread>) getStaticFieldValue("java.lang.ApplicationShutdownHooks", "hooks");
if(shutdownHooks != null) { // Could be null during JVM shutdown, which we already avoid, but be extra precautious
// Iterate copy to avoid ConcurrentModificationException
for(Thread shutdownHook : new ArrayList<Thread>(shutdownHooks.keySet())) {
if(isThreadInWebApplication(shutdownHook)) { // Planned to run in web app
removeShutdownHook(shutdownHook);
}
}
}
}
/** Deregister shutdown hook and execute it immediately */
@SuppressWarnings("deprecation")
protected void removeShutdownHook(Thread shutdownHook) {
final String displayString = "'" + shutdownHook + "' of type " + shutdownHook.getClass().getName();
error("Removing shutdown hook: " + displayString);
Runtime.getRuntime().removeShutdownHook(shutdownHook);
if(executeShutdownHooks) { // Shutdown hooks should be executed
info("Executing shutdown hook now: " + displayString);
// Make sure it's from this web app instance
shutdownHook.start(); // Run cleanup immediately
if(shutdownHookWaitMs > 0) { // Wait for shutdown hook to finish
try {
shutdownHook.join(shutdownHookWaitMs); // Wait for thread to run
}
catch (InterruptedException e) {
// Do nothing
}
if(shutdownHook.isAlive()) {
warn(shutdownHook + "still running after " + shutdownHookWaitMs + " ms - Stopping!");
shutdownHook.stop();
}
}
}
}
/** Deregister custom property editors */
protected void deregisterPropertyEditors() {
final Field registryField = findField(PropertyEditorManager.class, "registry");
if(registryField == null) {
info("Internal registry of " + PropertyEditorManager.class.getName() + " not found");
}
else {
try {
synchronized (PropertyEditorManager.class) {
@SuppressWarnings("unchecked")
final Map<Class<?>, Class<?>> registry = (Map<Class<?>, Class<?>>) registryField.get(null);
if(registry != null) { // Initialized
final Set<Class> toRemove = new HashSet<Class>();
for(Map.Entry<Class<?>, Class<?>> entry : registry.entrySet()) {
if(isLoadedByWebApplication(entry.getKey()) ||
isLoadedByWebApplication(entry.getValue())) { // More likely
toRemove.add(entry.getKey());
}
}
for(Class clazz : toRemove) {
warn("Property editor for type " + clazz + " = " + registry.get(clazz) + " needs to be deregistered");
PropertyEditorManager.registerEditor(clazz, null); // Deregister
}
}
}
}
catch (Exception e) { // Such as IllegalAccessException
error(e);
}
}
}
/** Deregister custom security providers */
protected void deregisterSecurityProviders() {
final Set<String> providersToRemove = new HashSet<String>();
for(java.security.Provider provider : java.security.Security.getProviders()) {
if(isLoadedInWebApplication(provider)) {
providersToRemove.add(provider.getName());
}
}
if(! providersToRemove.isEmpty()) {
warn("Removing security providers loaded in web app: " + providersToRemove);
for(String providerName : providersToRemove) {
java.security.Security.removeProvider(providerName);
}
}
}
/** Clear the default java.net.Authenticator (in case current one is loaded in web app) */
protected void clearDefaultAuthenticator() {
final Authenticator defaultAuthenticator = getStaticFieldValue(Authenticator.class, "theAuthenticator");
if(defaultAuthenticator == null || // Can both mean not set, or error retrieving, so unset anyway to be safe
isLoadedInWebApplication(defaultAuthenticator)) {
Authenticator.setDefault(null);
}
}
/** This method is heavily inspired by org.apache.catalina.loader.WebappClassLoader.clearReferencesRmiTargets() */
protected void deregisterRmiTargets() {
try {
final Class objectTableClass = findClass("sun.rmi.transport.ObjectTable");
if(objectTableClass != null) {
clearRmiTargetsMap((Map<?, ?>) getStaticFieldValue(objectTableClass, "objTable"));
clearRmiTargetsMap((Map<?, ?>) getStaticFieldValue(objectTableClass, "implTable"));
}
}
catch (Exception ex) {
error(ex);
}
}
/** Iterate RMI Targets Map and remove entries loaded by web app classloader */
protected void clearRmiTargetsMap(Map<?, ?> rmiTargetsMap) {
try {
final Field cclField = findFieldOfClass("sun.rmi.transport.Target", "ccl");
debug("Looping " + rmiTargetsMap.size() + " RMI Targets to find leaks");
for(Iterator<?> iter = rmiTargetsMap.values().iterator(); iter.hasNext(); ) {
Object target = iter.next(); // sun.rmi.transport.Target
ClassLoader ccl = (ClassLoader) cclField.get(target);
if(isWebAppClassLoaderOrChild(ccl)) {
warn("Removing RMI Target: " + target);
iter.remove();
}
}
}
catch (Exception ex) {
error(ex);
}
}
protected void clearThreadLocalsOfAllThreads() {
final ThreadLocalProcessor clearingThreadLocalProcessor = new ClearingThreadLocalProcessor();
for(Thread thread : getAllThreads()) {
forEachThreadLocalInThread(thread, clearingThreadLocalProcessor);
}
}
/**
* Partially inspired by org.apache.catalina.loader.WebappClassLoader.clearReferencesThreads()
*/
@SuppressWarnings("deprecation")
protected void stopThreads() {
final Class<?> workerClass = findClass("java.util.concurrent.ThreadPoolExecutor$Worker");
final Field oracleTarget = findField(Thread.class, "target"); // Sun/Oracle JRE
final Field ibmRunnable = findField(Thread.class, "runnable"); // IBM JRE
for(Thread thread : getAllThreads()) {
final Runnable runnable = (oracleTarget != null) ?
(Runnable) getFieldValue(oracleTarget, thread) : // Sun/Oracle JRE
(Runnable) getFieldValue(ibmRunnable, thread); // IBM JRE
if(thread != Thread.currentThread() && // Ignore current thread
(isThreadInWebApplication(thread) || isLoadedInWebApplication(runnable))) {
if (thread.getClass().getName().startsWith(JURT_ASYNCHRONOUS_FINALIZER)) {
// Note, the thread group of this thread may be "system" if it is triggered by the Garbage Collector
// however if triggered by us in forceStartOpenOfficeJurtCleanup() it may depend on the application server
if(stopThreads) {
info("Found JURT thread " + thread.getName() + "; starting " + JURTKiller.class.getSimpleName());
new JURTKiller(thread).start();
}
else
warn("JURT thread " + thread.getName() + " is still running in web app");
}
else if(thread.getThreadGroup() != null &&
("system".equals(thread.getThreadGroup().getName()) || // System thread
"RMI Runtime".equals(thread.getThreadGroup().getName()))) { // RMI thread (honestly, just copied from Tomcat)
if("Keep-Alive-Timer".equals(thread.getName())) {
thread.setContextClassLoader(getWebApplicationClassLoader().getParent());
debug("Changed contextClassLoader of HTTP keep alive thread");
}
}
else if(thread.isAlive()) { // Non-system, running in web app
if("java.util.TimerThread".equals(thread.getClass().getName())) {
if(stopTimerThreads) {
warn("Stopping Timer thread running in classloader.");
stopTimerThread(thread);
}
else {
info("Timer thread is running in classloader, but will not be stopped");
}
}
else {
// If threads is running an java.util.concurrent.ThreadPoolExecutor.Worker try shutting down the executor
if(workerClass != null && workerClass.isInstance(runnable)) {
if(stopThreads) {
warn("Shutting down " + ThreadPoolExecutor.class.getName() + " running within the classloader.");
try {
// java.util.concurrent.ThreadPoolExecutor, introduced in Java 1.5
final Field workerExecutor = findField(workerClass, "this$0");
final ThreadPoolExecutor executor = getFieldValue(workerExecutor, runnable);
executor.shutdownNow();
}
catch (Exception ex) {
error(ex);
}
}
else
info(ThreadPoolExecutor.class.getName() + " running within the classloader will not be shut down.");
}
final String displayString = "'" + thread + "' of type " + thread.getClass().getName();
if(stopThreads) {
final String waitString = (threadWaitMs > 0) ? "after " + threadWaitMs + " ms " : "";
warn("Stopping Thread " + displayString + " running in web app " + waitString);
if(threadWaitMs > 0) {
try {
thread.join(threadWaitMs); // Wait for thread to run
}
catch (InterruptedException e) {
// Do nothing
}
}
// Normally threads should not be stopped (method is deprecated), since it may cause an inconsistent state.
// In this case however, the alternative is a classloader leak, which may or may not be considered worse.
if(thread.isAlive())
thread.stop();
}
else {
warn("Thread " + displayString + " is still running in web app");
}
}
}
}
}
}
protected void stopTimerThread(Thread thread) {
// Seems it is not possible to access Timer of TimerThread, so we need to mimic Timer.cancel()
/**
try {
Timer timer = (Timer) findField(thread.getClass(), "this$0").get(thread); // This does not work!
warn("Cancelling Timer " + timer + " / TimeThread '" + thread + "'");
timer.cancel();
}
catch (IllegalAccessException iaex) {
error(iaex);
}
*/
try {
final Field newTasksMayBeScheduled = findField(thread.getClass(), "newTasksMayBeScheduled");
final Object queue = findField(thread.getClass(), "queue").get(thread); // java.lang.TaskQueue
final Method clear = queue.getClass().getDeclaredMethod("clear");
clear.setAccessible(true);
// Do what java.util.Timer.cancel() does
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (queue) {
newTasksMayBeScheduled.set(thread, false);
clear.invoke(queue);
queue.notify(); // "In case queue was already empty."
}
// We shouldn't need to join() here, thread will finish soon enough
}
catch (Exception ex) {
error(ex);
}
}
/** Destroy any ThreadGroups that are loaded by the application classloader */
public void destroyThreadGroups() {
try {
ThreadGroup systemThreadGroup = Thread.currentThread().getThreadGroup();
while(systemThreadGroup.getParent() != null) {
systemThreadGroup = systemThreadGroup.getParent();
}
// systemThreadGroup should now be the topmost ThreadGroup, "system"
int enumeratedGroups;
ThreadGroup[] allThreadGroups;
int noOfGroups = systemThreadGroup.activeGroupCount(); // Estimate no of groups
do {
noOfGroups += 10; // Make room for 10 extra
allThreadGroups = new ThreadGroup[noOfGroups];
enumeratedGroups = systemThreadGroup.enumerate(allThreadGroups);
} while(enumeratedGroups >= noOfGroups); // If there was not room for all groups, try again
for(ThreadGroup threadGroup : allThreadGroups) {
if(isLoadedInWebApplication(threadGroup) && ! threadGroup.isDestroyed()) {
warn("ThreadGroup '" + threadGroup + "' was loaded inside application, needs to be destroyed");
int noOfThreads = threadGroup.activeCount();
if(noOfThreads > 0) {
warn("There seems to be " + noOfThreads + " running in ThreadGroup '" + threadGroup + "'; interrupting");
try {
threadGroup.interrupt();
}
catch (Exception e) {
error(e);
}
}
try {
threadGroup.destroy();
info("ThreadGroup '" + threadGroup + "' successfully destroyed");
}
catch (Exception e) {
error(e);
}
}
}
}
catch (Exception ex) {
error(ex);
}
}
/**
* Since Keep-Alive-Timer thread may have terminated, but still be referenced, we need to make sure it does not
* reference this classloader.
*/
protected void unsetCachedKeepAliveTimer() {
Object keepAliveCache = getStaticFieldValue("sun.net.www.http.HttpClient", "kac", true);
if(keepAliveCache != null) {
final Thread keepAliveTimer = getFieldValue(keepAliveCache, "keepAliveTimer");
if(keepAliveTimer != null) {
if(isWebAppClassLoaderOrChild(keepAliveTimer.getContextClassLoader())) {
keepAliveTimer.setContextClassLoader(getWebApplicationClassLoader().getParent());
error("ContextClassLoader of sun.net.www.http.HttpClient cached Keep-Alive-Timer set to parent instead");
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Fix specific leaks
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Clean the cache of BeanELResolver */
protected void clearBeanELResolverCache() {
final Class beanElResolverClass = findClass("javax.el.BeanELResolver");
if(beanElResolverClass != null) {
boolean cleared = false;
try {
@SuppressWarnings("unchecked")
final Method purgeBeanClasses = beanElResolverClass.getDeclaredMethod("purgeBeanClasses", ClassLoader.class);
purgeBeanClasses.setAccessible(true);
purgeBeanClasses.invoke(beanElResolverClass.newInstance(), getWebApplicationClassLoader());
cleared = true;
}
catch (NoSuchMethodException e) {
// Version of javax.el probably > 2.2; no real need to clear
}
catch (Exception e) {
error(e);
}
if(! cleared) {
// Fallback, if purgeBeanClasses() could not be called
final Field propertiesField = findField(beanElResolverClass, "properties");
if(propertiesField != null) {
try {
final Map properties = (Map) propertiesField.get(null);
properties.clear();
}
catch (Exception e) {
error(e);
}
}
}
}
}
public void fixBeanValidationApiLeak() {
Class offendingClass = findClass("javax.validation.Validation$DefaultValidationProviderResolver");
if(offendingClass != null) { // Class is present on class path
Field offendingField = findField(offendingClass, "providersPerClassloader");
if(offendingField != null) {
final Object providersPerClassloader = getStaticFieldValue(offendingField);
if(providersPerClassloader instanceof Map) { // Map<ClassLoader, List<ValidationProvider<?>>> in offending code
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (providersPerClassloader) {
// Fix the leak!
((Map)providersPerClassloader).remove(getWebApplicationClassLoader());
}
}
}
}
}
/**
* Workaround for leak caused by Mojarra JSF implementation if included in the container.
* See <a href="http://java.net/jira/browse/JAVASERVERFACES-2746">JAVASERVERFACES-2746</a>
*/
protected void fixJsfLeak() {
/*
Note that since a WeakHashMap is used, it is not the map key that is the problem. However the value is a
Map with java.beans.PropertyDescriptor as value, and java.beans.PropertyDescriptor has a Hashtable in which
a class is put with "type" as key. This class may have been loaded by the web application.
One example case is the class org.primefaces.component.menubutton.MenuButton that points to a Map with a key
"model" whose PropertyDescriptor.table has key "type" with the class org.primefaces.model.MenuModel as its value.
For performance reasons however, we'll only look at the top level key and remove any that has been loaded by the
web application.
*/
Object o = getStaticFieldValue("javax.faces.component.UIComponentBase", "descriptors");
if(o instanceof WeakHashMap) {
WeakHashMap descriptors = (WeakHashMap) o;
final Set<Class> toRemove = new HashSet<Class>();
for(Object key : descriptors.keySet()) {
if(key instanceof Class && isLoadedByWebApplication((Class)key)) {
// For performance reasons, remove all classes loaded in web application
toRemove.add((Class) key);
// This would be more correct, but presumably slower
/*
Map<String, PropertyDescriptor> m = (Map<String, PropertyDescriptor>) descriptors.get(key);
for(Map.Entry<String,PropertyDescriptor> entry : m.entrySet()) {
Object type = entry.getValue().getValue("type"); // Key constant javax.el.ELResolver.TYPE
if(type instanceof Class && isLoadedByWebApplication((Class)type)) {
toRemove.add((Class) key);
}
}
*/
}
}
if(! toRemove.isEmpty()) {
info("Removing " + toRemove.size() + " classes from Mojarra descriptors cache");
for(Class clazz : toRemove) {
descriptors.remove(clazz);
}
}
}
}
/** Shutdown GeoTools cleaner thread as of http://jira.codehaus.org/browse/GEOT-2742 */
@SuppressWarnings("unchecked")
protected void fixGeoToolsLeak() {
final Class weakCollectionCleanerClass = findClass("org.geotools.util.WeakCollectionCleaner");
if(weakCollectionCleanerClass != null) {
try {
weakCollectionCleanerClass.getMethod("exit").invoke(null);
}
catch (Exception ex) {
error(ex);
}
}
}
/** Clear IntrospectionUtils caches of Tomcat and Apache Commons Modeler */
@SuppressWarnings("unchecked")
protected void clearIntrospectionUtilsCache() {
// Tomcat
final Class tomcatIntrospectionUtils = findClass("org.apache.tomcat.util.IntrospectionUtils");
if(tomcatIntrospectionUtils != null) {
try {
tomcatIntrospectionUtils.getMethod("clear").invoke(null);
}
catch (Exception ex) {
if(! mayBeJBoss) // JBoss includes this class, but no cache and no clear() method
error(ex);
}
}
// Apache Commons Modeler
final Class modelIntrospectionUtils = findClass("org.apache.commons.modeler.util.IntrospectionUtils");
if(modelIntrospectionUtils != null && ! isWebAppClassLoaderOrChild(modelIntrospectionUtils.getClassLoader())) { // Loaded outside web app
try {
modelIntrospectionUtils.getMethod("clear").invoke(null);
}
catch (Exception ex) {
warn("org.apache.commons.modeler.util.IntrospectionUtils needs to be cleared but there was an error, " +
"consider upgrading Apache Commons Modeler");
error(ex);
}
}
}
/**
* The bug detailed at https://issues.apache.org/ooo/show_bug.cgi?id=122517 is quite tricky. This is a try to
* avoid the issues by force starting the threads and it's job queue.
*/
protected void forceStartOpenOfficeJurtCleanup() {
if(stopThreads) {
if(isLoadedByWebApplication(findClass(JURT_ASYNCHRONOUS_FINALIZER))) {
/*
The com.sun.star.lib.util.AsynchronousFinalizer class was found and loaded, which means that in case the
static block that starts the daemon thread had not been started yet, it has been started now.
Now let's force Garbage Collection, with the hopes of having the finalize()ers that put Jobs on the
AsynchronousFinalizer queue be executed. Then just leave it, and handle the rest in {@link #stopThreads}.
*/
info("OpenOffice JURT AsynchronousFinalizer thread started - forcing garbage collection to invoke finalizers");
gc();
}
}
else {
// Check for class existence without loading class and thus executing static block
if(getWebApplicationClassLoader().getResource("com/sun/star/lib/util/AsynchronousFinalizer.class") != null) {
warn("OpenOffice JURT AsynchronousFinalizer thread will not be stopped if started, as stopThreads is false");
/*
By forcing Garbage Collection, we'll hopefully start the thread now, in case it would have been started by
GC later, so that at least it will appear in the logs.
*/
gc();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Utility methods
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected ClassLoader getWebApplicationClassLoader() {
//return ClassLoaderLeakPreventor.class.getClassLoader();
// Alternative
return Thread.currentThread().getContextClassLoader();
}
/** Test if provided object is loaded with web application classloader */
protected boolean isLoadedInWebApplication(Object o) {
return (o instanceof Class) && isLoadedByWebApplication((Class)o) || // Object is a java.lang.Class instance
o != null && isLoadedByWebApplication(o.getClass());
}
/** Test if provided class is loaded with web application classloader */
protected boolean isLoadedByWebApplication(Class clazz) {
return clazz != null && isWebAppClassLoaderOrChild(clazz.getClassLoader());
}
/** Test if provided ClassLoader is the classloader of the web application, or a child thereof */
protected boolean isWebAppClassLoaderOrChild(ClassLoader cl) {
final ClassLoader webAppCL = getWebApplicationClassLoader();
// final ClassLoader webAppCL = Thread.currentThread().getContextClassLoader();
while(cl != null) {
if(cl == webAppCL)
return true;
cl = cl.getParent();
}
return false;
}
protected boolean isThreadInWebApplication(Thread thread) {
return isLoadedInWebApplication(thread) || // Custom Thread class in web app
isWebAppClassLoaderOrChild(thread.getContextClassLoader()); // Running in web application
}
@SuppressWarnings("unchecked")
protected <E> E getStaticFieldValue(Class clazz, String fieldName) {
Field staticField = findField(clazz, fieldName);
return (staticField != null) ? (E) getStaticFieldValue(staticField) : null;
}
@SuppressWarnings("unchecked")
protected <E> E getStaticFieldValue(String className, String fieldName) {
return (E) getStaticFieldValue(className, fieldName, false);
}
@SuppressWarnings("unchecked")
protected <E> E getStaticFieldValue(String className, String fieldName, boolean trySystemCL) {
Field staticField = findFieldOfClass(className, fieldName, trySystemCL);
return (staticField != null) ? (E) getStaticFieldValue(staticField) : null;
}
protected Field findFieldOfClass(String className, String fieldName) {
return findFieldOfClass(className, fieldName, false);
}
protected Field findFieldOfClass(String className, String fieldName, boolean trySystemCL) {
Class clazz = findClass(className, trySystemCL);
if(clazz != null) {
return findField(clazz, fieldName);
}
else
return null;
}
protected Class findClass(String className) {
return findClass(className, false);
}
protected Class findClass(String className, boolean trySystemCL) {
try {
return Class.forName(className);
}
// catch (NoClassDefFoundError e) {
// // Silently ignore
// return null;
// }
catch (ClassNotFoundException e) {
if (trySystemCL) {
try {
return Class.forName(className, true, ClassLoader.getSystemClassLoader());
} catch (ClassNotFoundException e1) {
// Silently ignore
return null;
}
}
// Silently ignore
return null;
}
catch (Exception ex) { // Example SecurityException
warn(ex);
return null;
}
}
protected Field findField(Class clazz, String fieldName) {
if(clazz == null)
return null;
try {
final Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true); // (Field is probably private)
return field;
}
catch (NoSuchFieldException ex) {
// Silently ignore
return null;
}
catch (Exception ex) { // Example SecurityException
warn(ex);
return null;
}
}
@SuppressWarnings("unchecked")
protected <T> T getStaticFieldValue(Field field) {
try {
return (T) field.get(null);
}
catch (Exception ex) {
warn(ex);
// Silently ignore
return null;
}
}
protected <T> T getFieldValue(Object obj, String fieldName) {
final Field field = findField(obj.getClass(), fieldName);
@SuppressWarnings("unchecked")
T fieldValue = (T) getFieldValue(field, obj);
return fieldValue;
}
protected <T> T getFieldValue(Field field, Object obj) {
try {
@SuppressWarnings("unchecked")
T fieldValue = (T) field.get(obj);
return fieldValue;
}
catch (Exception ex) {
warn(ex);
// Silently ignore
return null;
}
}
/** Is the JVM currently shutting down? */
protected boolean isJvmShuttingDown() {
try {
final Thread dummy = new Thread(); // Will never be started
Runtime.getRuntime().removeShutdownHook(dummy);
return false;
}
catch (IllegalStateException isex) {
return true; // Shutting down
}
catch (Throwable t) { // Any other Exception, assume we are not shutting down
return false;
}
}
/** Get a Collection with all Threads.
* This method is heavily inspired by org.apache.catalina.loader.WebappClassLoader.getThreads() */
protected Collection<Thread> getAllThreads() {
// This is some orders of magnitude slower...
// return Thread.getAllStackTraces().keySet();
// Find root ThreadGroup
ThreadGroup tg = Thread.currentThread().getThreadGroup();
while(tg.getParent() != null)
tg = tg.getParent();
// Note that ThreadGroup.enumerate() silently ignores all threads that does not fit into array
int guessThreadCount = tg.activeCount() + 50;
Thread[] threads = new Thread[guessThreadCount];
int actualThreadCount = tg.enumerate(threads);
while(actualThreadCount == guessThreadCount) { // Map was filled, there may be more
guessThreadCount *= 2;
threads = new Thread[guessThreadCount];
actualThreadCount = tg.enumerate(threads);
}
// Filter out nulls
final List<Thread> output = new ArrayList<Thread>();
for(Thread t : threads) {
if(t != null) {
output.add(t);
}
}
return output;
}
/**
* Loop ThreadLocals and inheritable ThreadLocals in current Thread
* and for each found, invoke the callback interface
*/
protected void forEachThreadLocalInCurrentThread(ThreadLocalProcessor threadLocalProcessor) {
final Thread thread = Thread.currentThread();
forEachThreadLocalInThread(thread, threadLocalProcessor);
}
protected void forEachThreadLocalInThread(Thread thread, ThreadLocalProcessor threadLocalProcessor) {
try {
if(java_lang_Thread_threadLocals != null) {
processThreadLocalMap(thread, threadLocalProcessor, java_lang_Thread_threadLocals.get(thread));
}
if(java_lang_Thread_inheritableThreadLocals != null) {
processThreadLocalMap(thread, threadLocalProcessor, java_lang_Thread_inheritableThreadLocals.get(thread));
}
}
catch (/*IllegalAccess*/Exception ex) {
error(ex);
}
}
protected void processThreadLocalMap(Thread thread, ThreadLocalProcessor threadLocalProcessor, Object threadLocalMap) throws IllegalAccessException {
if(threadLocalMap != null && java_lang_ThreadLocal$ThreadLocalMap_table != null) {
final Object[] threadLocalMapTable = (Object[]) java_lang_ThreadLocal$ThreadLocalMap_table.get(threadLocalMap); // java.lang.ThreadLocal.ThreadLocalMap.Entry[]
for(Object entry : threadLocalMapTable) {
if(entry != null) {
// Key is kept in WeakReference
Reference reference = (Reference) entry;
final ThreadLocal<?> threadLocal = (ThreadLocal<?>) reference.get();
if(java_lang_ThreadLocal$ThreadLocalMap$Entry_value == null) {
java_lang_ThreadLocal$ThreadLocalMap$Entry_value = findField(entry.getClass(), "value");
}
final Object value = java_lang_ThreadLocal$ThreadLocalMap$Entry_value.get(entry);
threadLocalProcessor.process(thread, reference, threadLocal, value);
}
}
}
}
protected interface ThreadLocalProcessor {
void process(Thread thread, Reference entry, ThreadLocal<?> threadLocal, Object value);
}
/** ThreadLocalProcessor that detects and warns about potential leaks */
protected class WarningThreadLocalProcessor implements ThreadLocalProcessor {
public final void process(Thread thread, Reference entry, ThreadLocal<?> threadLocal, Object value) {
final boolean customThreadLocal = isLoadedInWebApplication(threadLocal); // This is not an actual problem
final boolean valueLoadedInWebApp = isLoadedInWebApplication(value);
if(customThreadLocal || valueLoadedInWebApp ||
(value instanceof ClassLoader && isWebAppClassLoaderOrChild((ClassLoader) value))) { // The value is classloader (child) itself
// This ThreadLocal is either itself loaded by the web app classloader, or it's value is
// Let's do something about it
StringBuilder message = new StringBuilder();
if(threadLocal != null) {
if(customThreadLocal) {
message.append("Custom ");
}
message.append("ThreadLocal of type ").append(threadLocal.getClass().getName()).append(": ").append(threadLocal);
}
else {
message.append("Unknown ThreadLocal");
}
message.append(" with value ").append(value);
if(value != null) {
message.append(" of type ").append(value.getClass().getName());
if(valueLoadedInWebApp)
message.append(" that is loaded by web app");
}
warn(message.toString());
processFurther(thread, entry, threadLocal, value); // Allow subclasses to perform further processing
}
}
/**
* After having detected potential ThreadLocal leak and warned about it, this method is called.
* Subclasses may override this method to perform further processing, such as clean up.
* @param thread
* @param entry
* @param threadLocal
* @param value
*/
protected void processFurther(Thread thread, Reference entry, ThreadLocal<?> threadLocal, Object value) {
// To be overridden in subclass
}
}
/** ThreadLocalProcessor that not only detects and warns about potential leaks, but also tries to clear them */
protected class ClearingThreadLocalProcessor extends WarningThreadLocalProcessor {
public void processFurther(Thread thread, Reference entry, ThreadLocal<?> threadLocal, Object value) {
if(threadLocal != null && thread == Thread.currentThread()) { // If running for current thread and we have the ThreadLocal ...
// ... remove properly
info(" Will be remove()d");
threadLocal.remove();
}
else { // We cannot remove entry properly, so just make it stale
info(" Will be made stale for later expunging");
entry.clear(); // Clear the key
if(java_lang_ThreadLocal$ThreadLocalMap$Entry_value == null) {
java_lang_ThreadLocal$ThreadLocalMap$Entry_value = findField(entry.getClass(), "value");
}
try {
java_lang_ThreadLocal$ThreadLocalMap$Entry_value.set(entry, null); // Clear value to avoid circular references
}
catch (IllegalAccessException iaex) {
error(iaex);
}
}
}
}
/** Parse init parameter for integer value, returning default if not found or invalid */
protected static int getIntInitParameter(ServletContext servletContext, String parameterName, int defaultValue) {
final String parameterString = servletContext.getInitParameter(parameterName);
if(parameterString != null && parameterString.trim().length() > 0) {
try {
return Integer.parseInt(parameterString);
}
catch (NumberFormatException e) {
// Do nothing, return default value
}
}
return defaultValue;
}
/**
* Unlike <code>{@link System#gc()}</code> this method guarantees that garbage collection has been performed before
* returning.
*/
protected static void gc() {
Object obj = new Object();
WeakReference ref = new WeakReference<Object>(obj);
//noinspection UnusedAssignment
obj = null;
while(ref.get() != null) {
System.gc();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Log methods
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* Since logging frameworks are part of the problem, we don't want to depend on any of them here.
* Feel free however to subclass or fork and use a log framework, in case you think you know what you're doing.
*/
protected String getLogPrefix() {
return ClassLoaderLeakPreventor.class.getSimpleName() + ": ";
}
protected void debug(String s) {
System.out.println(getLogPrefix() + s);
}
protected void info(String s) {
System.out.println(getLogPrefix() + s);
}
protected void warn(String s) {
System.err.println(getLogPrefix() + s);
}
protected void warn(Throwable t) {
t.printStackTrace(System.err);
}
protected void error(String s) {
System.err.println(getLogPrefix() + s);
}
protected void error(Throwable t) {
t.printStackTrace(System.err);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Inner class with the sole task of killing JURT finalizer thread after it is done processing jobs.
* We need to postpone the stopping of this thread, since more Jobs may in theory be add()ed when this web application
* instance is closing down and being garbage collected.
* See https://issues.apache.org/ooo/show_bug.cgi?id=122517
*/
protected class JURTKiller extends Thread {
private final Thread jurtThread;
private final List jurtQueue;
public JURTKiller(Thread jurtThread) {
super("JURTKiller");
this.jurtThread = jurtThread;
jurtQueue = getStaticFieldValue(JURT_ASYNCHRONOUS_FINALIZER, "queue");
}
@Override
public void run() {
if(jurtQueue == null || jurtThread == null) {
error(getName() + ": No queue or thread!?");
return;
}
if(! jurtThread.isAlive()) {
warn(getName() + ": " + jurtThread.getName() + " is already dead?");
}
boolean queueIsEmpty = false;
while(! queueIsEmpty) {
try {
debug(getName() + " goes to sleep for " + THREAD_WAIT_MS_DEFAULT + " ms");
Thread.sleep(THREAD_WAIT_MS_DEFAULT);
}
catch (InterruptedException e) {
// Do nothing
}
if(State.RUNNABLE != jurtThread.getState()) { // Unless thread is currently executing a Job
debug(getName() + " about to force Garbage Collection");
gc(); // Force garbage collection, which may put new items on queue
synchronized (jurtQueue) {
queueIsEmpty = jurtQueue.isEmpty();
debug(getName() + ": JURT queue is empty? " + queueIsEmpty);
}
}
else
debug(getName() + ": JURT thread " + jurtThread.getName() + " is executing Job");
}
info(getName() + " about to kill " + jurtThread);
if(jurtThread.isAlive())
stop( jurtThread);
}
@SuppressWarnings("deprecation")
private void stop(Thread thread) {
thread.stop();
}
}
} | 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.Iterator;
import java.util.List;
import org.rapla.components.util.DateTools;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentFormater;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Repeating;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
/** default implementation of appointment formater */
public class AppointmentFormaterImpl
implements
AppointmentFormater
{
I18nBundle i18n;
RaplaLocale loc;
public AppointmentFormaterImpl(RaplaContext context) throws RaplaException
{
i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
loc = context.lookup(RaplaLocale.class);
}
protected RaplaLocale getRaplaLocale() {
return loc;
}
protected I18nBundle getI18n() {
return i18n;
}
protected String getString(String key) {
return i18n.getString(key);
}
public String getShortSummary(Appointment appointment) {
String time = loc.formatTime(appointment.getStart());
Repeating repeating = appointment.getRepeating();
final boolean wholeDaysSet = appointment.isWholeDaysSet();
final String timeString = wholeDaysSet ? "" :" " + time;
String weekday = loc.getWeekday(appointment.getStart());
if (repeating != null) {
if (repeating.isWeekly()) {
return weekday + timeString;
}
if (repeating.isDaily())
return getString("daily") + " " + time;
if (repeating.isMonthly())
return getWeekdayOfMonth( appointment.getStart() ) + weekday + timeString;
if (repeating.isYearly())
return getDayOfMonth( appointment.getStart() ) + loc.getMonth(appointment.getStart()) +" " + timeString;
}
String date = loc.formatDate(appointment.getStart());
return weekday + " " +date + " " + timeString;
}
public String getVeryShortSummary(Appointment appointment) {
Repeating repeating = appointment.getRepeating();
if (repeating != null) {
if (repeating.isWeekly())
return getRaplaLocale().getWeekday(appointment.getStart());
if (repeating.isDaily()) {
String time = getRaplaLocale().formatTime(appointment.getStart());
return time;
}
if (repeating.isMonthly())
{
return getRaplaLocale().getWeekday(appointment.getStart());
}
}
String date = getRaplaLocale().formatDateShort(appointment.getStart());
return date;
}
public String getSummary( Appointment a ) {
StringBuffer buf = new StringBuffer();
Repeating repeating = a.getRepeating();
final boolean wholeDaysSet = a.isWholeDaysSet();
Date start = a.getStart();
Date end = a.getEnd();
if ( repeating == null )
{
buf.append( loc.getWeekday( start ) );
buf.append( ' ' );
buf.append( loc.formatDate( start ) );
if (!wholeDaysSet && !( end.equals( DateTools.cutDate(end)) && start.equals(DateTools.cutDate( start))))
{
buf.append( ' ' );
buf.append( loc.formatTime( start ) );
if ( isSameDay( start, end ) || (end.equals( DateTools.cutDate(end)) && isSameDay( DateTools.fillDate( start), end)) )
{
buf.append( '-' );
}
else
{
buf.append( " - " );
buf.append( loc.getWeekday( end ) );
buf.append( ' ' );
buf.append( loc.formatDate( end ) );
buf.append( ' ' );
}
buf.append( loc.formatTime( end ) );
}
else if ( end.getTime() - start.getTime() > DateTools.MILLISECONDS_PER_DAY)
{
buf.append( " - " );
buf.append( loc.getWeekday( DateTools.addDays(end,-1 )) );
buf.append( ' ' );
buf.append( loc.formatDate( DateTools.addDays(end,-1 )) );
}
}
else if ( repeating.isWeekly() || repeating.isMonthly() || repeating.isYearly())
{
if( repeating.isMonthly())
{
buf.append( getWeekdayOfMonth( start ));
}
if (repeating.isYearly())
{
buf.append( getDayOfMonth( start ) );
buf.append( loc.getMonth( start ) );
}
else
{
buf.append( loc.getWeekday( start ) );
}
if (wholeDaysSet)
{
if ( end.getTime() - start.getTime() > DateTools.MILLISECONDS_PER_DAY)
{
if ( end.getTime() - start.getTime() <= DateTools.MILLISECONDS_PER_DAY * 6 )
{
buf.append( " - " );
buf.append( loc.getWeekday( end ) );
}
else
{
buf.append( ' ' );
buf.append( loc.formatDate( start ) );
buf.append( " - " );
buf.append( loc.getWeekday( end ) );
buf.append( ' ' );
buf.append( loc.formatDate( end ) );
}
}
}
else
{
buf.append( ' ' );
if ( isSameDay( start, end ) )
{
buf.append( loc.formatTime( start ) );
buf.append( '-' );
buf.append( loc.formatTime( end ) );
}
else if ( end.getTime() - start.getTime() <= DateTools.MILLISECONDS_PER_DAY * 6 )
{
buf.append( loc.formatTime( start ) );
buf.append( " - " );
buf.append( loc.getWeekday( end ) );
buf.append( ' ' );
buf.append( loc.formatTime( end ) );
}
else
{
buf.append( loc.formatDate( start ) );
buf.append( ' ' );
buf.append( loc.formatTime( start ) );
buf.append( " - " );
buf.append( loc.getWeekday( end ) );
buf.append( ' ' );
buf.append( loc.formatDate( end ) );
buf.append( ' ' );
buf.append( loc.formatTime( end ) );
}
}
if ( repeating.isWeekly())
{
buf.append( ' ' );
buf.append( getInterval( repeating ) );
}
if ( repeating.isMonthly())
{
buf.append(" " + getString("monthly"));
}
if ( repeating.isYearly())
{
buf.append(" " + getString("yearly"));
}
}
else if ( repeating.isDaily() )
{
long days =(end.getTime() - start.getTime()) / (DateTools.MILLISECONDS_PER_HOUR * 24 );
if ( !a.isWholeDaysSet())
{
buf.append( loc.formatTime( start ) );
if ( days <1)
{
buf.append( '-' );
buf.append( loc.formatTime( end ) );
}
buf.append( ' ' );
}
buf.append( getInterval( repeating ) );
}
return buf.toString();
}
private String getWeekdayOfMonth( Date date )
{
StringBuffer b = new StringBuffer();
int numb = DateTools.getDayOfWeekInMonth( date );
b.append( String.valueOf(numb));
b.append( '.');
b.append( ' ');
return b.toString();
}
private String getDayOfMonth( Date date )
{
StringBuffer b = new StringBuffer();
int numb = DateTools.getDayOfMonth( date );
b.append( String.valueOf(numb));
b.append( '.');
b.append( ' ');
return b.toString();
}
private boolean isSameDay( Date d1, Date d2 ) {
return DateTools.isSameDay(d1, d2);
}
public String getExceptionSummary( Repeating r ) {
StringBuffer buf = new StringBuffer();
buf.append(getString("appointment.exceptions"));
buf.append(": ");
Date[] exc = r.getExceptions();
for ( int i=0;i<exc.length;i++) {
if (i>0)
buf.append(", ");
buf.append( getRaplaLocale().formatDate( exc[i] ) );
}
return buf.toString();
}
private String getInterval( Repeating r ) {
StringBuffer buf = new StringBuffer();
if ( r.getInterval() == 1 ) {
buf.append( getString( r.getType().toString() ) );
} else {
String fString ="weekly";
if ( r.isWeekly() ) {
fString = getString( "weeks" );
}
if ( r.isDaily() ) {
fString = getString( "days" );
}
buf.append( getI18n().format( "interval.format", "" + r.getInterval(), fString ) );
}
return buf.toString();
}
private boolean isPeriodicaly(Period period, Repeating r) {
Appointment a = r.getAppointment();
if (r.getEnd().after( period.getEnd() ) )
return false;
if ( r.isWeekly() )
{
return
( DateTools.cutDate(a.getStart().getTime()) - period.getStart().getTime() )
<= DateTools.MILLISECONDS_PER_DAY * 6
&&
( DateTools.cutDate(period.getEnd().getTime()) - r.getEnd().getTime() )
<= DateTools.MILLISECONDS_PER_DAY * 6
;
}
else if ( r.isDaily() )
{
return
isSameDay( a.getStart(), period.getStart() )
&&
isSameDay( r.getEnd(), period.getEnd() )
;
}
return false;
}
public String getSummary( Repeating r , List<Period> periods) {
if ( r.getEnd() != null && !r.isFixedNumber() )
{
Iterator<Period> it = periods.iterator();
while ( it.hasNext() ) {
Period period = it.next();
if ( isPeriodicaly(period, r))
return getI18n().format("in_period.format"
,period.getName(loc.getLocale())
);
}
}
return getSummary(r);
}
public String getSummary( Repeating r ) {
Appointment a = r.getAppointment();
StringBuffer buf = new StringBuffer();
String startDate = loc.formatDate( a.getStart() );
buf.append( getI18n().format("format.repeat_from", startDate) );
buf.append( ' ' );
// print end date, when end is given
if ( r.getEnd() != null) {
String endDate = loc.formatDate( DateTools.subDay(r.getEnd()) );
buf.append( getI18n().format("format.repeat_until", endDate) );
buf.append( ' ' );
}
// print number of repeating if number is gt 0 and fixed times
if ( r.getNumber()>=0 && r.isFixedNumber() ) {
buf.append( getI18n().format("format.repeat_n_times", String.valueOf(r.getNumber())) );
buf.append( ' ' );
}
// print never ending if end is null
if (r.getEnd() == null ){
buf.append( getString("repeating.forever") );
buf.append( ' ' );
}
return buf.toString();
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import org.rapla.ConnectInfo;
import org.rapla.entities.User;
import org.rapla.framework.RaplaException;
/** Encapsulates the methods responsible for authentification.
*/
public interface UserModule {
/** The login method establishes the connection and loads data.
* @return false on an invalid login.
* @throws RaplaException if the connection can't be established.
*/
boolean login(String username,char[] password) throws RaplaException;
boolean login(ConnectInfo connectInfo) throws RaplaException;
/** logout of the current user */
void logout() throws RaplaException;
/** returns if a session is active. True between a successful login and logout. */
boolean isSessionActive();
/** throws an Exception if no user has loged in.
@return the user that has loged in. */
User getUser() throws RaplaException;
void changePassword(User user,char[] oldPassword,char[] newPassword) throws RaplaException;
boolean canChangePassword();
/** changes the name for the logged in user. If a person is connected then all three fields are used. Otherwise only lastname is used*/
void changeName(String title, String firstname, String surname) throws RaplaException;
void confirmEmail(String newEmail) throws RaplaException;
/** changes the name for the user that is logged in. */
void changeEmail(String newEmail) 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.facade;
import java.util.Set;
/** This class contains the configuration options for the calendar views
like Worktimes and dates configuration is done in the calendar option menu.
Hours belonging to the worktime get a different color in the
weekview. This is also the minimum interval that will be used for
printing.<br>
Excluded Days are only visible, when there is an appointment to
display.<br>
*/
public interface CalendarOptions {
/** return the worktimeStart in hours
* @deprecated use {@link #getWorktimeStartMinutes()} instead*/
@Deprecated
int getWorktimeStart();
int getRowsPerHour();
/** return the worktimeEnd in hours
* @deprecated use {@link #getWorktimeEndMinutes()} instead*/
@Deprecated
int getWorktimeEnd();
Set<Integer> getExcludeDays();
int getDaysInWeekview();
int getFirstDayOfWeek();
boolean isExceptionsVisible();
boolean isCompactColumns();
boolean isResourceColoring();
boolean isEventColoring();
int getMinBlockWidth();
int getWorktimeStartMinutes();
int getWorktimeEndMinutes();
boolean isNonFilteredEventsVisible();
boolean isWorktimeOvernight();
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import org.rapla.storage.StorageOperator;
/** A collection of all module-interfaces
*/
public interface ClientFacade
extends
UserModule
,ModificationModule
,QueryModule
,UpdateModule
{
StorageOperator getOperator();
}
| 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.facade;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.components.xmlbundle.CompoundI18n;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.Annotatable;
import org.rapla.entities.Category;
import org.rapla.entities.Named;
import org.rapla.entities.Ownable;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.configuration.internal.PreferencesImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentFormater;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.RaplaObjectAnnotations;
import org.rapla.entities.domain.ReservationStartComparator;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.Classifiable;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ConstraintIds;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.facade.internal.CalendarOptionsImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.RaplaSynchronizationException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.framework.logger.ConsoleLogger;
import org.rapla.framework.logger.Logger;
/**
Base class for most components. Eases
access to frequently used services, e.g. {@link I18nBundle}.
*/
public class RaplaComponent
{
public static final TypedComponentRole<I18nBundle> RAPLA_RESOURCES = new TypedComponentRole<I18nBundle>("org.rapla.RaplaResources");
public static final TypedComponentRole<RaplaConfiguration> PLUGIN_CONFIG= new TypedComponentRole<RaplaConfiguration>("org.rapla.plugin");
private final ClientServiceManager serviceManager;
private TypedComponentRole<I18nBundle> childBundleName;
private Logger logger;
private RaplaContext context;
public RaplaComponent(RaplaContext context) {
try {
logger = context.lookup(Logger.class );
} catch (RaplaContextException e) {
logger = new ConsoleLogger();
}
this.context = context;
this.serviceManager = new ClientServiceManager();
}
protected void setLogger(Logger logger)
{
this.logger = logger;
}
final public TypedComponentRole<I18nBundle> getChildBundleName() {
return childBundleName;
}
final public void setChildBundleName(TypedComponentRole<I18nBundle> childBundleName) {
this.childBundleName = childBundleName;
}
final protected Container getContainer() throws RaplaContextException {
return getContext().lookup(Container.class);
}
/** returns if the session user is admin */
final public boolean isAdmin() {
try {
return getUser().isAdmin();
} catch (RaplaException ex) {
}
return false;
}
/** returns if the session user is a registerer */
final public boolean isRegisterer() {
if (isAdmin())
{
return true;
}
try {
Category registererGroup = getQuery().getUserGroupsCategory().getCategory(Permission.GROUP_REGISTERER_KEY);
return getUser().belongsTo(registererGroup);
} catch (RaplaException ex) {
}
return false;
}
final public boolean isModifyPreferencesAllowed() {
if (isAdmin())
{
return true;
}
try {
Category modifyPreferences = getQuery().getUserGroupsCategory().getCategory(Permission.GROUP_MODIFY_PREFERENCES_KEY);
if ( modifyPreferences == null ) {
return true;
}
return getUser().belongsTo(modifyPreferences);
} catch (RaplaException ex) {
}
return false;
}
/** returns if the user has allocation rights for one or more resource */
final public boolean canUserAllocateSomething(User user) throws RaplaException {
Allocatable[] allocatables =getQuery().getAllocatables();
if ( user.isAdmin() )
return true;
if (!canCreateReservation(user))
{
return false;
}
for ( int i=0;i<allocatables.length;i++) {
Permission[] permissions = allocatables[i].getPermissions();
for ( int j=0;j<permissions.length;j++) {
Permission p = permissions[j];
if (!p.affectsUser( user ))
{
continue;
}
if ( p.getAccessLevel() > Permission.READ)
{
return true;
}
}
}
return false;
}
final public boolean canCreateReservation(User user) {
boolean result = getQuery().canCreateReservations(user);
return result;
}
final public boolean canCreateReservation() {
try {
User user = getUser();
return canCreateReservation( user);
} catch (RaplaException ex) {
return false;
}
}
protected boolean canAllocate()
{
CalendarSelectionModel model = getService( CalendarSelectionModel.class);
//Date start, Date end,
Collection<Allocatable> allocatables = getService(CalendarSelectionModel.class).getMarkedAllocatables();
boolean canAllocate = true;
Date start = getStartDate( model);
Date end = getEndDate( model, start);
for (Allocatable allo:allocatables)
{
if (!canAllocate( start, end, allo))
{
canAllocate = false;
}
}
return canAllocate;
}
protected Date getStartDate(CalendarModel model) {
Collection<TimeInterval> markedIntervals = model.getMarkedIntervals();
Date startDate = null;
if ( markedIntervals.size() > 0)
{
TimeInterval first = markedIntervals.iterator().next();
startDate = first.getStart();
}
if ( startDate != null)
{
return startDate;
}
Date selectedDate = model.getSelectedDate();
if ( selectedDate == null)
{
selectedDate = getQuery().today();
}
Date time = new Date (DateTools.MILLISECONDS_PER_MINUTE * getCalendarOptions().getWorktimeStartMinutes());
startDate = getRaplaLocale().toDate(selectedDate,time);
return startDate;
}
protected Date getEndDate( CalendarModel model,Date startDate) {
Collection<TimeInterval> markedIntervals = model.getMarkedIntervals();
Date endDate = null;
if ( markedIntervals.size() > 0)
{
TimeInterval first = markedIntervals.iterator().next();
endDate = first.getEnd();
}
if ( endDate != null)
{
return endDate;
}
return new Date(startDate.getTime() + DateTools.MILLISECONDS_PER_HOUR);
}
protected boolean canAllocate(Date start, Date end, Allocatable allocatables) {
if ( allocatables == null) {
return true;
}
try {
User user = getUser();
Date today = getQuery().today();
return allocatables.canAllocate( user, start, end, today );
} catch (RaplaException ex) {
return false;
}
}
/** returns if the current user is allowed to modify the object. */
final public boolean canModify(Object object) {
try {
User user = getUser();
return canModify(object, user);
} catch (RaplaException ex) {
return false;
}
}
static public boolean canModify(Object object, User user) {
if (object == null || !(object instanceof RaplaObject))
{
return false;
}
if ( user == null)
{
return false;
}
if (user.isAdmin())
return true;
if (object instanceof Ownable) {
Ownable ownable = (Ownable) object;
User owner = ownable.getOwner();
if ( owner != null && user.equals(owner))
{
return true;
}
if (object instanceof Allocatable) {
Allocatable allocatable = (Allocatable) object;
if (allocatable.canModify( user ))
{
return true;
}
if ( owner == null)
{
Category[] groups = user.getGroups();
for ( Category group: groups)
{
if (group.getKey().equals(Permission.GROUP_REGISTERER_KEY))
{
return true;
}
}
}
}
}
if (checkClassifiableModifyPermissions(object, user))
{
return true;
}
return false;
}
public boolean canRead(Appointment appointment,User user)
{
Reservation reservation = appointment.getReservation();
boolean canReadReservationsFromOthers = getQuery().canReadReservationsFromOthers( user);
boolean result = canRead(reservation, user, canReadReservationsFromOthers);
return result;
}
static public boolean canRead(Reservation reservation,User user, boolean canReadReservationsFromOthers)
{
if ( user == null)
{
return true;
}
if ( canModify(reservation, user))
{
return true;
}
if ( !canReadReservationsFromOthers)
{
return false;
}
if (checkClassifiablerReadPermissions(reservation, user))
{
return true;
}
return false;
}
static public boolean canRead(Allocatable allocatable, User user) {
if ( canModify(allocatable, user))
{
return true;
}
if (checkClassifiablerReadPermissions(allocatable, user))
{
return true;
}
return false;
}
/** We check if an attribute with the permission_modify exists and look if the permission is set either globally (if boolean type is used) or for a specific user group (if category type is used)*/
public static boolean checkClassifiableModifyPermissions(Object object,
User user) {
return checkClassifiablePermissions(object, user, ReservationImpl.PERMISSION_MODIFY, false);
}
public static boolean checkClassifiablerReadPermissions(
Object object, User user) {
return checkClassifiablePermissions(object, user, ReservationImpl.PERMISSION_READ, true);
}
static Category dummyCategory = new CategoryImpl(new Date(), new Date());
// The dummy category is used if no permission attribute is found. Use permissionNotFoundReturns to set whether this means permssion granted or not
private static boolean checkClassifiablePermissions(Object object, User user, String permissionKey, boolean permssionNotFoundReturnsYesCategory) {
Collection<Category> cat = getPermissionGroups(object, dummyCategory,permissionKey, permssionNotFoundReturnsYesCategory);
if ( cat == null)
{
return false;
}
if ( cat.size() == 1 && cat.iterator().next() == dummyCategory)
{
return true;
}
for (Category c: cat)
{
if (user.belongsTo( c) )
{
return true;
}
}
return false;
}
/** returns the group that is has the requested permission on the object
**/
public static Collection<Category> getPermissionGroups(Object object, Category yesCategory, String permissionKey, boolean permssionNotFoundReturnsYesCategory)
{
if (object instanceof Classifiable ) {
final Classifiable classifiable = (Classifiable) object;
Classification classification = classifiable.getClassification();
if ( classification != null)
{
final DynamicType type = classification.getType();
final Attribute attribute = type.getAttribute(permissionKey);
if ( attribute != null)
{
return getPermissionGroups(classification, yesCategory, attribute);
}
else
{
if ( permssionNotFoundReturnsYesCategory && yesCategory != null)
{
return Collections.singleton(yesCategory);
}
else
{
return null;
}
}
}
}
return null;
}
private static Collection<Category> getPermissionGroups(Classification classification,
Category yesCategory, final Attribute attribute) {
final AttributeType type2 = attribute.getType();
if (type2 == AttributeType.BOOLEAN)
{
final Object value = classification.getValue( attribute);
if (Boolean.TRUE.equals(value))
{
return Collections.singleton(yesCategory);
}
else
{
return null;
}
}
if ( type2 == AttributeType.CATEGORY)
{
Collection<?> values = classification.getValues( attribute);
@SuppressWarnings("unchecked")
Collection<Category> cat = (Collection<Category>) values;
if ( cat == null || cat.size() == 0)
{
Category rootCat = (Category)attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY);
if ( rootCat.getCategories().length == 0)
{
cat = Collections.singleton(rootCat);
}
}
return cat;
}
return null;
}
public CalendarOptions getCalendarOptions() {
User user;
try
{
user = getUser();
}
catch (RaplaException ex) {
// Use system settings if an error occurs
user = null;
}
return getCalendarOptions( user);
}
protected CalendarOptions getCalendarOptions(User user) {
RaplaConfiguration conf = null;
try {
if ( user != null)
{
conf = getQuery().getPreferences( user ).getEntry(CalendarOptionsImpl.CALENDAR_OPTIONS);
}
if ( conf == null)
{
conf = getQuery().getPreferences( null ).getEntry(CalendarOptionsImpl.CALENDAR_OPTIONS);
}
if ( conf != null)
{
return new CalendarOptionsImpl( conf );
}
} catch (RaplaException ex) {
}
return getService( CalendarOptions.class);
}
protected User getUser() throws RaplaException {
return getUserModule().getUser();
}
protected Logger getLogger() {
return logger;
}
/** lookup the service in the serviceManager under the specified key:
serviceManager.lookup(role).
@throws IllegalStateException if GUIComponent wasn't serviced. No service method called
@throws UnsupportedOperationException if service not available.
*/
protected <T> T getService(Class<T> role) {
try {
return context.lookup( role);
} catch (RaplaContextException e) {
throw serviceExcption(role, e);
}
}
protected UnsupportedOperationException serviceExcption(Object role, RaplaContextException e) {
return new UnsupportedOperationException("Service not supported in this context: " + role, e);
}
protected <T> T getService(TypedComponentRole<T> role) {
try {
return context.lookup(role);
} catch (RaplaContextException e) {
throw serviceExcption(role, e);
}
}
protected RaplaContext getContext() {
return context;
}
/** lookup RaplaLocale from the context */
protected RaplaLocale getRaplaLocale() {
if (serviceManager.raplaLocale == null)
serviceManager.raplaLocale = getService(RaplaLocale.class);
return serviceManager.raplaLocale;
}
protected Locale getLocale() {
return getRaplaLocale().getLocale();
}
protected I18nBundle childBundle;
/** lookup I18nBundle from the serviceManager */
protected I18nBundle getI18n() {
TypedComponentRole<I18nBundle> childBundleName = getChildBundleName();
if ( childBundleName != null) {
if ( childBundle == null) {
I18nBundle pluginI18n = getService(childBundleName );
childBundle = new CompoundI18n(pluginI18n,getI18nDefault());
}
return childBundle;
}
return getI18nDefault();
}
private I18nBundle getI18nDefault() {
if (serviceManager.i18n == null)
serviceManager.i18n = getService(RaplaComponent.RAPLA_RESOURCES);
return serviceManager.i18n;
}
/** lookup AppointmentFormater from the serviceManager */
protected AppointmentFormater getAppointmentFormater() {
if (serviceManager.appointmentFormater == null)
serviceManager.appointmentFormater = getService(AppointmentFormater.class);
return serviceManager.appointmentFormater;
}
/** lookup PeriodModel from the serviceManager */
protected PeriodModel getPeriodModel() {
try {
return getQuery().getPeriodModel();
} catch (RaplaException ex) {
throw new UnsupportedOperationException("Service not supported in this context: " );
}
}
/** lookup QueryModule from the serviceManager */
protected QueryModule getQuery() {
return getClientFacade();
}
final protected ClientFacade getClientFacade() {
if (serviceManager.facade == null)
serviceManager.facade = getService( ClientFacade.class );
return serviceManager.facade;
}
/** lookup ModificationModule from the serviceManager */
protected ModificationModule getModification() {
return getClientFacade();
}
/** lookup UpdateModule from the serviceManager */
protected UpdateModule getUpdateModule() {
return getClientFacade();
}
/** lookup UserModule from the serviceManager */
protected UserModule getUserModule() {
return getClientFacade();
}
/** returns a translation for the object name into the selected language. If
a translation into the selected language is not possible an english translation will be tried next.
If theres no translation for the default language, the first available translation will be used. */
public String getName(Object object) {
if (object == null)
return "";
if (object instanceof Named) {
String name = ((Named) object).getName(getI18n().getLocale());
return (name != null) ? name : "";
}
return object.toString();
}
/** calls getI18n().getString(key) */
final public String getString(String key) {
return getI18n().getString(key);
}
/** calls "<html>" + getI18n().getString(key) + "</html>"*/
final public String getStringAsHTML(String key) {
return "<html>" + getI18n().getString(key) + "</html>";
}
private static class ClientServiceManager {
I18nBundle i18n;
ClientFacade facade;
RaplaLocale raplaLocale;
AppointmentFormater appointmentFormater;
}
final public Preferences newEditablePreferences() throws RaplaException {
Preferences preferences = getQuery().getPreferences();
ModificationModule modification = getModification();
return modification.edit(preferences);
}
/** @deprecated demand webservice in constructor instead*/
@Deprecated
final public <T> T getWebservice(Class<T> a) throws RaplaException
{
org.rapla.storage.dbrm.RemoteServiceCaller remote = getService( org.rapla.storage.dbrm.RemoteServiceCaller.class);
return remote.getRemoteMethod(a);
}
@Deprecated
public Configuration getPluginConfig(String pluginClassName) throws RaplaException
{
Preferences systemPreferences = getQuery().getSystemPreferences();
return ((PreferencesImpl)systemPreferences).getOldPluginConfig(pluginClassName);
}
public static boolean isTemplate(RaplaObject<?> obj)
{
if ( obj instanceof Appointment)
{
obj = ((Appointment) obj).getReservation();
}
if ( obj instanceof Annotatable)
{
String template = ((Annotatable)obj).getAnnotation( RaplaObjectAnnotations.KEY_TEMPLATE);
return template != null;
}
return false;
}
protected List<Reservation> copy(Collection<Reservation> toCopy, Date beginn) throws RaplaException
{
List<Reservation> sortedReservations = new ArrayList<Reservation>( toCopy);
Collections.sort( sortedReservations, new ReservationStartComparator(getLocale()));
List<Reservation> copies = new ArrayList<Reservation>();
Date firstStart = null;
for (Reservation reservation: sortedReservations) {
if ( firstStart == null )
{
firstStart = ReservationStartComparator.getStart( reservation);
}
Reservation copy = copy(reservation, beginn, firstStart);
copies.add( copy);
}
return copies;
}
public Reservation copyAppointment(Reservation reservation, Date beginn) throws RaplaException
{
Date firstStart = ReservationStartComparator.getStart( reservation);
Reservation copy = copy(reservation, beginn, firstStart);
return copy;
}
private Reservation copy(Reservation reservation, Date destStart,Date firstStart) throws RaplaException {
Reservation r = getModification().clone( reservation);
Appointment[] appointments = r.getAppointments();
for ( Appointment app :appointments) {
Repeating repeating = app.getRepeating();
Date oldStart = app.getStart();
// we need to calculate an offset so that the reservations will place themself relativ to the first reservation in the list
long offset = DateTools.countDays( firstStart, oldStart) * DateTools.MILLISECONDS_PER_DAY;
Date newStart ;
Date destWithOffset = new Date(destStart.getTime() + offset );
newStart = getRaplaLocale().toDate( destWithOffset , oldStart );
app.move( newStart) ;
if (repeating != null)
{
Date[] exceptions = repeating.getExceptions();
repeating.clearExceptions();
for (Date exc: exceptions)
{
long days = DateTools.countDays(oldStart, exc);
Date newDate = DateTools.addDays(newStart, days);
repeating.addException( newDate);
}
if ( !repeating.isFixedNumber())
{
Date oldEnd = repeating.getEnd();
if ( oldEnd != null)
{
// If we don't have and endig destination, just make the repeating to the original length
long days = DateTools.countDays(oldStart, oldEnd);
Date end = DateTools.addDays(newStart, days);
repeating.setEnd( end);
}
}
}
}
return r;
}
public static void unlock(Lock lock)
{
if ( lock != null)
{
lock.unlock();
}
}
public static Lock lock(Lock lock, int seconds) throws RaplaException {
try
{
if ( lock.tryLock())
{
return lock;
}
if (lock.tryLock(seconds, TimeUnit.SECONDS))
{
return lock;
}
else
{
throw new RaplaSynchronizationException("Someone is currently writing. Please try again! Can't acquire lock " + lock );
}
}
catch (InterruptedException ex)
{
throw new RaplaSynchronizationException( ex);
}
}
}
| Java |
package org.rapla.facade;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
public interface CalendarModel extends Cloneable, ClassifiableFilter
{
public static final String SHOW_NAVIGATION_ENTRY = "org.rapla.plugin.abstractcalendar.show_navigation";
public static final String ONLY_ALLOCATION_INFO = "org.rapla.plugin.abstractcalendar.only_allocation_info";
public static final String SAVE_SELECTED_DATE = "org.rapla.plugin.abstractcalendar.save_selected_date";
public static final String ONLY_MY_EVENTS = "only_own_reservations";
public static final TypedComponentRole<Boolean> ONLY_MY_EVENTS_DEFAULT = new TypedComponentRole<Boolean>("org.rapla.plugin.abstractcalendar.only_own_reservations");
String getNonEmptyTitle();
User getUser();
Date getSelectedDate();
void setSelectedDate( Date date );
Date getStartDate();
void setStartDate( Date date );
Date getEndDate();
void setEndDate( Date date );
Collection<RaplaObject> getSelectedObjects();
/** Calendar View Plugins can use the calendar options to store their requiered optional parameters for a calendar view */
String getOption(String name);
Collection<RaplaObject> getSelectedObjectsAndChildren() throws RaplaException;
/** Convenience method to extract the allocatables from the selectedObjects and their children
* @see #getSelectedObjectsAndChildren */
Allocatable[] getSelectedAllocatables() throws RaplaException;
Reservation[] getReservations( Date startDate, Date endDate ) throws RaplaException;
Reservation[] getReservations() throws RaplaException;
CalendarModel clone();
List<AppointmentBlock> getBlocks() throws RaplaException;
DynamicType guessNewEventType() throws RaplaException;
/** returns the marked time intervals in the calendar. */
Collection<TimeInterval> getMarkedIntervals();
Collection<Allocatable> getMarkedAllocatables();
} | 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;
import java.util.Set;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaType;
/** Encapsulate the changes that are made in the backend-store.*/
public interface ModificationEvent
{
/** returns if the objects has changed.*/
boolean hasChanged(Entity object);
/** returns if the objects was removed.*/
boolean isRemoved(Entity object);
/** returns if the objects has changed or was removed.*/
boolean isModified(Entity object);
/** returns if any object of the specified type has changed or was removed.*/
boolean isModified(RaplaType raplaType);
/** returns all removed objects .*/
Set<Entity> getRemoved();
/** returns all changed object .*/
Set<Entity> getChanged();
Set<Entity> getAddObjects();
TimeInterval getInvalidateInterval();
boolean isModified();
}
| 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;
import java.util.EventListener;
import org.rapla.framework.RaplaException;
/** Classes implementing this interface will be notified when changes to
* reservations or resources occurred. The listener can be registered by calling
* <code>addModificationListener</code> of the <code>UpdateModule</code> <br>
* Don't forget to remove the listener by calling <code>removeModificationLister</code>
* when no longer needed.
* @author Christopher Kohlhaas
* @see UpdateModule
* @see ModificationEvent
*/
public interface ModificationListener extends EventListener {
/** this notifies all listeners that data in the rapla-backend has changed.
* The {@link ModificationEvent} describes these changes.
*/
void dataChanged(ModificationEvent evt) throws RaplaException;
}
| Java |
package org.rapla.facade;
import java.util.Collection;
import java.util.Date;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.framework.RaplaException;
public interface CalendarSelectionModel extends CalendarModel{
String getTitle();
void setTitle(String title);
void setViewId(String viewId);
String getViewId();
void setSelectedObjects(Collection<? extends Object> selectedObjects);
void setOption( String name, String string );
void selectUser( User user );
/** If show only own reservations is selected. Thats if the current user is selected with select User*/
boolean isOnlyCurrentUserSelected();
void setReservationFilter(ClassificationFilter[] array);
void setAllocatableFilter(ClassificationFilter[] filters);
public void resetExports();
public void save(final String filename) throws RaplaException;
public void load(final String filename) throws RaplaException, EntityNotFoundException, CalendarNotFoundExeption;
CalendarSelectionModel clone();
void setMarkedIntervals(Collection<TimeInterval> timeIntervals);
/** calls setMarkedIntervals with a single interval from start to end*/
void markInterval(Date start, Date end);
void setMarkedAllocatables(Collection<Allocatable> allocatable);
/** CalendarModels do not update automatically but need to be notified on changes from the outside*/
void dataChanged(ModificationEvent evt) 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.facade;
import java.util.HashMap;
import java.util.Map;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
public class AllocationChangeEvent
{
static Map<String,Type> TYPES = new HashMap<String,Type>();
public static class Type
{
private String type;
Type( String type )
{
TYPES.put( type, this );
this.type = type;
}
public String toString()
{
return type;
}
}
Type m_type;
public static Type CHANGE = new Type( "change" );
public static Type ADD = new Type( "add" );
public static Type REMOVE = new Type( "remove" );
User m_user;
Reservation m_newReservation;
Allocatable m_allocatable;
Appointment m_newAppointment;
Appointment m_oldAppointment;
public AllocationChangeEvent( Type type, User user, Reservation newReservation, Allocatable allocatable,
Appointment appointment )
{
m_user = user;
m_type = type;
m_allocatable = allocatable;
if ( type.equals( REMOVE ) )
m_oldAppointment = appointment;
m_newAppointment = appointment;
m_newReservation = newReservation;
}
public AllocationChangeEvent( User user, Reservation newReservation, Allocatable allocatable,
Appointment newAppointment, Appointment oldApp )
{
this( CHANGE, user, newReservation, allocatable, newAppointment );
m_oldAppointment = oldApp;
}
/** either Type.CHANGE,Type.REMOVE or Type.ADD */
public Type getType()
{
return m_type;
}
/** returns the user-object, of the user that made the change.
* <strong>Warning can be null</strong>
*/
public User getUser()
{
return m_user;
}
public Allocatable getAllocatable()
{
return m_allocatable;
}
public Appointment getNewAppointment()
{
return m_newAppointment;
}
public Reservation getNewReservation()
{
return m_newReservation;
}
/** only available if type is "change" */
public Appointment getOldAppointment()
{
return m_oldAppointment;
}
}
| 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;
import org.rapla.framework.RaplaException;
/** Classes implementing this interface will be notified when an update error
* occurred. The listener can be registered by calling
* <code>addUpdateErrorListener</code> of the <code>UpdateModule</code> <br>
* Don't forget to remove the listener by calling <code>removeUpdateErrorLister</code>
* when no longer need.
* @author Christopher Kohlhaas
* @see UpdateModule
*/
public interface UpdateErrorListener {
/** this notifies all listeners that the update of the data has
caused an error. A normal source for UpdateErrors is a broken
connection to the server.
*/
void updateError(RaplaException ex);
void disconnected(String message);
}
| Java |
package org.rapla.facade;
import org.rapla.framework.RaplaException;
public class CalendarNotFoundExeption extends RaplaException {
public CalendarNotFoundExeption(String text) {
super(text);
}
private static final long serialVersionUID = 1L;
}
| 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;
import java.util.EventListener;
/** After a store all registered ChangeListeners get notified by calling
* the trigger method. A list with all changes is passed.
* At the moment only AllocationChangeEvents are triggered.
* By this you can get notified, when any Reservation changes.
* The difference between the UpdateEvent and a ChangeEvent is,
* that the UpdateEvent contains the new Versions of all updated enties,
* while a ChangeEvent contains Information about a single change.
* That change can be calculated as with the AllocationChangeEvent, which
* represents a single allocation change for one allocatable object
* ,including information about the old allocation and the new one.
* @see AllocationChangeEvent
*/
public interface AllocationChangeListener extends EventListener
{
void changed(AllocationChangeEvent[] changeEvents);
}
| 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;
import java.util.Date;
import java.util.List;
import org.rapla.entities.domain.Period;
/** ListModel that contains all periods. Updates the list automatically if a period is added, changed or deleted.
* */
public interface PeriodModel
{
/** returns the first matching period or null if no period matches.*/
public Period getPeriodFor(Date date);
public Period getNearestPeriodForDate(Date date);
public Period getNearestPeriodForStartDate(Date date);
public Period getNearestPeriodForStartDate(Date date, Date endDate);
public Period getNearestPeriodForEndDate(Date date);
/** return all matching periods.*/
public List<Period> getPeriodsFor(Date date);
public int getSize();
public Period[] getAllPeriods();
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
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.Appointment;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaException;
/** Methods for quering the various entities of the backend
*/
public interface QueryModule
{
/** returns all DynamicTypes matching the specified classification
possible keys are reservation, person and resource.
@see org.rapla.entities.dynamictype.DynamicTypeAnnotations
*/
DynamicType[] getDynamicTypes(String classificationType) throws RaplaException;
/** returns the DynamicType with the passed elementKey */
DynamicType getDynamicType(String elementKey) throws RaplaException;
/** returns The root category. */
Category getSuperCategory();
/** returns The category that contains all the user-groups of rapla */
Category getUserGroupsCategory() throws RaplaException;
/** returns all users */
User[] getUsers() throws RaplaException;
/** returns the user with the specified username */
User getUser(String username) throws RaplaException;
/** returns all allocatables that match the passed ClassificationFilter. If null all readable allocatables are returned*/
Allocatable[] getAllocatables(ClassificationFilter[] filters) throws RaplaException;
/** returns all readable allocatables, same as getAllocatables(null)*/
Allocatable[] getAllocatables() throws RaplaException;
/** returns the reservations of the specified user in the specified interval
@param user A user-object or null for all users
@param start only reservations beginning after the start-date will be returned (can be null).
@param end only reservations beginning before the end-date will be returned (can be null).
@param filters you can specify classificationfilters or null for all reservations .
*/
Reservation[] getReservations(User user,Date start,Date end,ClassificationFilter[] filters) throws RaplaException;
/**returns all reservations that have allocated at least one Resource or Person that is part of the allocatables array.
@param allocatables only reservations that allocate at least on element of this array will be returned.
@param start only reservations beginning after the start-date will be returned (can be null).
@param end only reservations beginning before the end-date will be returned (can be null).
**/
Reservation[] getReservations(Allocatable[] allocatables,Date start,Date end) throws RaplaException;
Reservation[] getReservationsForAllocatable(Allocatable[] allocatables, Date start,Date end,ClassificationFilter[] filters) throws RaplaException;
List<Reservation> getReservations(Collection<Conflict> conflicts) throws RaplaException;
/** returns all available periods */
Period[] getPeriods() throws RaplaException;
/** returns an Interface for accessing the periods
* @throws RaplaException */
PeriodModel getPeriodModel() throws RaplaException;
/** returns the current date in GMT+0 Timezone. If rapla operates
in multi-user mode, the date should be calculated from the
server date.
*/
Date today();
/** returns all allocatables from the set of passed allocatables, that are already allocated by different parallel reservations at the time-slices, that are described by the appointment */
public Map<Allocatable, Collection<Appointment>> getAllocatableBindings(Collection<Allocatable> allocatables,Collection<Appointment> forAppointment) throws RaplaException;
/** returns all allocatables, that are already allocated by different parallel reservations at the time-slices, that are described by the appointment
* @deprecated use {@link #getAllocatableBindings(Collection,Collection)} instead
* */
@Deprecated
Allocatable[] getAllocatableBindings(Appointment appointment) throws RaplaException;
/** returns all existing conflicts with the reservation */
Conflict[] getConflicts(Reservation reservation) throws RaplaException;
/** returns all existing conflicts that are visible for the user
conflicts
*/
Conflict[] getConflicts() throws RaplaException;
/** returns if the user has the permissions to change/create an
allocation on the passed appointment. Changes of an
existing appointment that are in an permisable
timeframe are allowed. Example: The extension of an exisiting appointment,
doesn't affect allocations in the past and should not create a
conflict with the permissions.
*/
//boolean hasPermissionToAllocate( Appointment appointment, Allocatable allocatable );
/** returns the preferences for the passed user, must be admin todo this. creates a new prefence object if not set*/
Preferences getPreferences(User user) throws RaplaException;
/** returns the preferences for the passed user, must be admin todo this.*/
Preferences getPreferences(User user, boolean createIfNotNull) throws RaplaException;
/** returns the preferences for the login user */
Preferences getPreferences() throws RaplaException;
Preferences getSystemPreferences() throws RaplaException;
/** returns if the user is allowed to exchange the allocatables of this reservation. A user can do it if he has
* at least admin privileges for one allocatable. He can only exchange or remove or insert allocatables he has admin privileges on.
* The User cannot change appointments.*/
boolean canExchangeAllocatables(Reservation reservation);
boolean canReadReservationsFromOthers(User user);
boolean canCreateReservations(User user);
boolean canEditTemplats(User user);
public Collection<String> getTemplateNames() throws RaplaException;
public Collection<Reservation> getTemplateReservations(String name) throws RaplaException;
Date getNextAllocatableDate(Collection<Allocatable> asList, Appointment appointment, CalendarOptions options) throws RaplaException;
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
public interface UpdateModule
{
public final static TypedComponentRole<Integer> REFRESH_INTERVAL_ENTRY = new TypedComponentRole<Integer>("org.rapla.refreshInterval");
public final static TypedComponentRole<Integer> ARCHIVE_AGE = new TypedComponentRole<Integer>("org.rapla.archiveAge");
public static final int REFRESH_INTERVAL_DEFAULT = 30000;
/**
* Refreshes the data that is in the cache (or on the client)
and notifies all registered {@link ModificationListener ModificationListeners}
with an update-event.
There are two types of refreshs.
<ul>
<li>Incremental Refresh: Only the changes are propagated</li>
<li>Full Refresh: The complete data is reread. (Currently disabled in Rapla)</li>
</ul>
<p>
Incremental refreshs are the normal case if you have a client server basis.
(In a single user system no refreshs are necessary at all).
The refreshs are triggered in defined intervals if you use the webbased communication
and automaticaly if you use the old communication layer. You can change the refresh interval
via the admin options.
</p>
<p>
Of course you can call a refresh anytime you want to synchronize with the server, e.g. if
you want to ensure you are uptodate before editing. If you are on the server you dont need to refresh.
</p>
<strong>WARNING: When using full refresh on a local file storage
all information will be changed. So use it
only if you modify the data from external.
You better re-get and re-draw all
the information in the Frontend after a full refresh.
</strong>
*/
void refresh() throws RaplaException;
/** returns if the Facade is connected through a server (false if it has a local store)*/
boolean isClientForServer();
/**
* registers a new ModificationListener.
* A ModifictionEvent will be fired to every registered DateChangeListener
* when one or more entities have been added, removed or changed
* @see ModificationListener
* @see ModificationEvent
*/
void addModificationListener(ModificationListener listener);
void removeModificationListener(ModificationListener listener);
void addUpdateErrorListener(UpdateErrorListener listener);
void removeUpdateErrorListener(UpdateErrorListener listener);
void addAllocationChangedListener(AllocationChangeListener triggerListener);
void removeAllocationChangedListener(AllocationChangeListener triggerListener);
}
| 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;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.framework.RaplaException;
public interface ClassifiableFilter
{
ClassificationFilter[] getReservationFilter() throws RaplaException ;
ClassificationFilter[] getAllocatableFilter() throws RaplaException ;
boolean isDefaultEventTypes();
boolean isDefaultResourceTypes();
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.User;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.RepeatingType;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaException;
/** All methods that allow modifing the entity-objects.
*/
public interface ModificationModule {
/** check if the reservation can be saved */
void checkReservation(Reservation reservation) throws RaplaException;
/** creates a new Rapla Map. Keep in mind that only RaplaObjects and Strings are allowed as entries for a RaplaMap!*/
<T> RaplaMap<T> newRaplaMap( Map<String,T> map);
/** creates an ordered RaplaMap with the entries of the collection as values and their position in the collection from 1..n as keys*/
<T> RaplaMap<T> newRaplaMap( Collection<T> col);
CalendarSelectionModel newCalendarModel( User user) throws RaplaException;
/** Creates a new event, Creates a new event from the first dynamic type found, basically a shortcut to newReservation(getDynamicType(VALUE_CLASSIFICATION_TYPE_RESERVATION)[0].newClassification())
* This is a convenience method for testing.
*/
Reservation newReservation() throws RaplaException;
/** Shortcut for newReservation(classification,getUser()*/
Reservation newReservation(Classification classification) throws RaplaException;
/** Creates a new reservation from the classifcation object and with the passed user as its owner
* You can create a new classification from a {@link DynamicType} with newClassification method.
* @see DynamicType#newClassification()
*/
Reservation newReservation(Classification classification,User user) throws RaplaException;
Appointment newAppointment(Date startDate,Date endDate) throws RaplaException;
Appointment newAppointment(Date startDate,Date endDate, User user) throws RaplaException;
/** @deprecated use newAppointment and change the repeating type of the appointment afterwards*/
Appointment newAppointment(Date startDate,Date endDate, RepeatingType repeatingType, int repeatingDuration) throws RaplaException;
/** Creates a new resource from the first dynamic type found, basically a shortcut to newAlloctable(getDynamicType(VALUE_CLASSIFICATION_TYPE_RESOURCE)[0].newClassification()).
* This is a convenience method for testing.
* */
Allocatable newResource() throws RaplaException;
/** Creates a new person resource, Creates a new resource from the first dynamic type found, basically a shortcut to newAlloctable(getDynamicType(VALUE_CLASSIFICATION_TYPE_PERSON)[0].newClassification())
* This is a convenience method for testing.
*/
Allocatable newPerson() throws RaplaException;
/** Creates a new allocatable from the classifcation object and with the passed user as its owner
* You can create a new classification from a {@link DynamicType} with newClassification method.
* @see DynamicType#newClassification()*/
Allocatable newAllocatable( Classification classification, User user) throws RaplaException;
/** Shortcut for newAllocatble(classification,getUser()*/
Allocatable newAllocatable( Classification classification) throws RaplaException;
Allocatable newPeriod() throws RaplaException;
Category newCategory() throws RaplaException;
Attribute newAttribute(AttributeType attributeType) throws RaplaException;
DynamicType newDynamicType(String classificationType) throws RaplaException;
User newUser() throws RaplaException;
/** Clones an entity. The entities will get new identifier and
won't be equal to the original. The resulting object is not persistant and therefore
can be editet.
*/
<T extends Entity> T clone(T obj) throws RaplaException;
/** This call will be delegated to the {@link org.rapla.storage.StorageOperator}. It
* returns an editable working copy of an object. Only objects return by this method and new objects are editable.
* To get the persistant, non-editable version of a working copy use {@link #getPersistant} */
<T extends Entity> T edit(T obj) throws RaplaException;
<T extends Entity> Collection<T> edit(Collection<T> list) throws RaplaException;
/** Returns the persistant version of a working copy.
* Throws an {@link org.rapla.entities.EntityNotFoundException} when the
* object is not found
* @see #edit
* @see #clone
*/
<T extends Entity> T getPersistant(T working) throws RaplaException;
<T extends Entity> Map<T,T> getPersistant(Collection<T> list) throws RaplaException;
/** This call will be delegated to the {@link org.rapla.storage.StorageOperator} */
void storeObjects(Entity<?>[] obj) throws RaplaException;
/** @see #storeObjects(Entity[]) */
void store(Entity<?> obj) throws RaplaException;
/** This call will be delegated to the {@link org.rapla.storage.StorageOperator} */
void removeObjects(Entity<?>[] obj) throws RaplaException;
/** @see #removeObjects(Entity[]) */
void remove(Entity<?> obj) throws RaplaException;
/** stores and removes objects in the one transaction
* @throws RaplaException */
void storeAndRemove( Entity<?>[] storedObjects, Entity<?>[] removedObjects) throws RaplaException;
void setTemplateName(String templateName);
String getTemplateName();
CommandHistory getCommandHistory();
}
| 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;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import org.rapla.entities.Entity;
import org.rapla.entities.Named;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
/**
* A conflict is the allocation of the same resource at the same time by different
* reservations. There's one conflict for each resource and each overlapping of
* two allocations. So if there are 3 reservations that allocate the same 2 resources
* on 2 days of the week, then we got ( 3 * 2 ) * 2 * 2 = 24 conflicts. Thats
* 3 reservations, each conflicting with two other 2 reservations on 2 days with 2 resources.
*
* @version 1.0
* @author Christopher Kohlhaas
*/
public interface Conflict extends Named, Entity<Conflict>
{
static public final RaplaType<Conflict> TYPE = new RaplaType<Conflict>(Conflict.class,"conflict");
/** @return the allocatable, allocated for the same time by two different reservations. */
public Allocatable getAllocatable();
// /** @return the first Reservation, that is involved in the conflict.*/
// public Reservation getReservation1();
/** The appointment of the first reservation, that causes the conflict. */
public String getAppointment1();
// /** @return the second Reservation, that is involved in the conflict.*/
// public Reservation getReservation2();
// /** @return The User, who created the second Reservation.*/
// public User getUser2();
/** The appointment of the second reservation, that causes the conflict. */
public String getAppointment2();
String getReservation1();
String getReservation2();
String getReservation1Name();
String getReservation2Name();
///** Find the first occurance of a conflict in the specified interval or null when not in intervall*/
//public Date getFirstConflictDate(final Date fromDate, final Date toDate);
//public boolean canModify(User user);
public boolean isOwner( User user);
public static final Conflict[] CONFLICT_ARRAY= new Conflict[] {};
public class Util
{
public static Collection<Allocatable> getAllocatables(
Collection<Conflict> conflictsSelected) {
LinkedHashSet<Allocatable> allocatables = new LinkedHashSet<Allocatable>();
for ( Conflict conflict: conflictsSelected)
{
allocatables.add(conflict.getAllocatable());
}
return allocatables;
}
// static public List<Reservation> getReservations(Collection<Conflict> conflicts) {
// Collection<Reservation> reservations = new LinkedHashSet<Reservation>();
// for (Conflict conflict:conflicts)
// {
// reservations.add(conflict.getReservation1());
// reservations.add(conflict.getReservation2());
//
// }
// return new ArrayList<Reservation>( reservations);
// }
//
}
boolean hasAppointment(Appointment appointment);
//boolean endsBefore(Date date);
Date getStartDate();
}
| 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.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.AllocationChangeEvent;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.UpdateResult;
/** Converts updateResults into AllocationChangeEvents */
public class AllocationChangeFinder
{
ArrayList<AllocationChangeEvent> changeList = new ArrayList<AllocationChangeEvent>();
UpdateResult updateResult;
Logger logger;
private AllocationChangeFinder(Logger logger, UpdateResult updateResult) {
this.logger = logger;
if ( updateResult == null)
return;
User user = updateResult.getUser();
for (Iterator<UpdateResult.Add> it = updateResult.getOperations( UpdateResult.Add.class );it.hasNext();) {
UpdateResult.Add addOp = it.next();
added( addOp.getNew(), user );
}
for (Iterator<UpdateResult.Remove> it = updateResult.getOperations( UpdateResult.Remove.class );it.hasNext();) {
UpdateResult.Remove removeOp = it.next();
removed( removeOp.getCurrent(), user );
}
for (Iterator<UpdateResult.Change> it = updateResult.getOperations( UpdateResult.Change.class );it.hasNext();) {
UpdateResult.Change changeOp = it.next();
Entity old = changeOp.getOld();
Entity newObj = changeOp.getNew();
changed(old , newObj, user );
}
}
public Logger getLogger()
{
return logger;
}
static public List<AllocationChangeEvent> getTriggerEvents(UpdateResult result,Logger logger) {
AllocationChangeFinder finder = new AllocationChangeFinder(logger, result);
return finder.changeList;
}
private void added(RaplaObject entity, User user) {
RaplaType raplaType = entity.getRaplaType();
if ( raplaType == Reservation.TYPE ) {
Reservation newRes = (Reservation) entity;
addAppointmentAdd(
user
,newRes
,Arrays.asList(newRes.getAllocatables())
,Arrays.asList(newRes.getAppointments())
);
}
}
private void removed(RaplaObject entity,User user) {
RaplaType raplaType = entity.getRaplaType();
if ( raplaType == Reservation.TYPE ) {
if (getLogger().isDebugEnabled())
getLogger().debug("Reservation removed: " + entity);
Reservation oldRes = (Reservation) entity;
addAppointmentRemove(
user
,oldRes
,oldRes
,Arrays.asList(oldRes.getAllocatables())
,Arrays.asList(oldRes.getAppointments())
);
}
}
private void changed(Entity oldEntity,Entity newEntity, User user) {
RaplaType raplaType = oldEntity.getRaplaType();
if (raplaType == Reservation.TYPE ) {
if (getLogger().isDebugEnabled())
getLogger().debug("Reservation changed: " + oldEntity);
Reservation oldRes = (Reservation) oldEntity;
Reservation newRes = (Reservation) newEntity;
List<Allocatable> alloc1 = Arrays.asList(oldRes.getAllocatables());
List<Allocatable> alloc2 = Arrays.asList(newRes.getAllocatables());
List<Appointment> app1 = Arrays.asList(oldRes.getAppointments());
List<Appointment> app2 = Arrays.asList(newRes.getAppointments());
ArrayList<Allocatable> removeList = new ArrayList<Allocatable>(alloc1);
removeList.removeAll(alloc2);
// add removed allocations to the change list
addAppointmentRemove(user, oldRes,newRes, removeList, app1);
ArrayList<Allocatable> addList = new ArrayList<Allocatable>(alloc2);
addList.removeAll(alloc1);
// add new allocations to the change list
addAppointmentAdd(user, newRes, addList, app2);
ArrayList<Allocatable> changeList = new ArrayList<Allocatable>(alloc2);
changeList.retainAll(alloc1);
addAllocationDiff(user, changeList,oldRes,newRes);
}
if ( Appointment.TYPE == raplaType ) {
if (getLogger().isDebugEnabled())
getLogger().debug("Appointment changed: " + oldEntity + " to " + newEntity);
}
}
/*
private void printList(List list) {
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
*/
/**
* Calculates the allocations that have changed
*/
private void addAllocationDiff(User user,List<Allocatable> allocatableList,Reservation oldRes,Reservation newRes) {
List<Appointment> app1 = Arrays.asList(oldRes.getAppointments());
List<Appointment> app2 = Arrays.asList(newRes.getAppointments());
ArrayList<Appointment> removeList = new ArrayList<Appointment>(app1);
removeList.removeAll(app2);
addAppointmentRemove(user, oldRes,newRes,allocatableList,removeList);
ArrayList<Appointment> addList = new ArrayList<Appointment>(app2);
addList.removeAll(app1);
addAppointmentAdd(user, newRes,allocatableList,addList);
/*
System.out.println("OLD appointments");
printList(app1);
System.out.println("NEW appointments");
printList(app2);
*/
Set<Appointment> newList = new HashSet<Appointment>(app2);
newList.retainAll(app1);
ArrayList<Appointment> oldList = new ArrayList<Appointment>(app1);
oldList.retainAll(app2);
sort(oldList);
for (int i=0;i<oldList.size();i++) {
Appointment oldApp = oldList.get(i);
Appointment newApp = null;
for ( Appointment app:newList)
{
if ( app.equals( oldApp))
{
newApp = app;
}
}
if ( newApp == null)
{
// This should never happen as we call retainAll before
getLogger().error("Not found matching pair for " + oldApp);
continue;
}
for (Allocatable allocatable: allocatableList )
{
boolean oldAllocated = oldRes.hasAllocated(allocatable, oldApp);
boolean newAllocated = newRes.hasAllocated(allocatable, newApp);
if (!oldAllocated && !newAllocated) {
continue;
}
else if (!oldAllocated && newAllocated)
{
changeList.add(new AllocationChangeEvent(AllocationChangeEvent.ADD,user,newRes,allocatable,newApp));
}
else if (oldAllocated && !newAllocated)
{
changeList.add(new AllocationChangeEvent(AllocationChangeEvent.REMOVE,user,newRes,allocatable,newApp));
}
else if (!newApp.matches(oldApp))
{
getLogger().debug("\n" + newApp + " doesn't match \n" + oldApp);
changeList.add(new AllocationChangeEvent(user,newRes,allocatable,newApp,oldApp));
}
}
}
}
@SuppressWarnings("unchecked")
public void sort(ArrayList<Appointment> oldList) {
Collections.sort(oldList);
}
private void addAppointmentAdd(User user,Reservation newRes,List<Allocatable> allocatables,List<Appointment> appointments) {
for (Allocatable allocatable:allocatables)
{
for (Appointment appointment:appointments)
{
if (!newRes.hasAllocated(allocatable,appointment))
continue;
changeList.add(new AllocationChangeEvent(AllocationChangeEvent.ADD,user, newRes,allocatable,appointment));
}
}
}
private void addAppointmentRemove(User user,Reservation oldRes,Reservation newRes,List<Allocatable> allocatables,List<Appointment> appointments) {
for (Allocatable allocatable:allocatables)
{
for (Appointment appointment:appointments)
{
if (!oldRes.hasAllocated(allocatable,appointment))
continue;
changeList.add(new AllocationChangeEvent(AllocationChangeEvent.REMOVE,user, newRes,allocatable,appointment));
}
}
}
}
| 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.facade.internal;
import static org.rapla.entities.configuration.CalendarModelConfiguration.EXPORT_ENTRY;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
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.TimeInterval;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.IllegalAnnotationException;
import org.rapla.entities.Named;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.configuration.CalendarModelConfiguration;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.configuration.internal.CalendarModelConfigurationImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.AppointmentBlockStartComparator;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.entities.dynamictype.internal.ParsedText;
import org.rapla.entities.dynamictype.internal.ParsedText.EvalContext;
import org.rapla.entities.dynamictype.internal.ParsedText.Function;
import org.rapla.entities.dynamictype.internal.ParsedText.ParseContext;
import org.rapla.entities.storage.CannotExistWithoutTypeException;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarNotFoundExeption;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.Conflict;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.storage.UpdateResult;
public class CalendarModelImpl implements CalendarSelectionModel
{
private static final String DEFAULT_VIEW = "week";//WeekViewFactory.WEEK_VIEW;
private static final String ICAL_EXPORT_ENABLED = "org.rapla.plugin.export2ical"+ ".selected";
private static final String HTML_EXPORT_ENABLED = EXPORT_ENTRY + ".selected";
Date startDate;
Date endDate;
Date selectedDate;
List<RaplaObject> selectedObjects = new ArrayList<RaplaObject>();
String title;
ClientFacade m_facade;
String selectedView;
I18nBundle i18n;
RaplaContext context;
RaplaLocale raplaLocale;
User user;
Map<String,String> optionMap = new HashMap<String,String>();
//Map<String,String> viewOptionMap = new HashMap<String,String>();
boolean defaultEventTypes = true;
boolean defaultResourceTypes = true;
Collection<TimeInterval> timeIntervals = Collections.emptyList();
Collection<Allocatable> markedAllocatables = Collections.emptyList();
Map<DynamicType,ClassificationFilter> reservationFilter = new LinkedHashMap<DynamicType, ClassificationFilter>();
Map<DynamicType,ClassificationFilter> allocatableFilter = new LinkedHashMap<DynamicType, ClassificationFilter>();
public static final RaplaConfiguration ALLOCATABLES_ROOT = new RaplaConfiguration("rootnode", "allocatables");
public CalendarModelImpl(RaplaContext context, User user, ClientFacade facade) throws RaplaException {
this.context = context;
this.raplaLocale =context.lookup(RaplaLocale.class);
i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
m_facade = facade;
if ( user == null && m_facade.isSessionActive()) {
user = m_facade.getUser();
}
Date today = m_facade.today();
setSelectedDate( today);
setStartDate( today);
setEndDate( DateTools.addYear(getStartDate()));
DynamicType[] types = m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE);
if ( types.length == 0 ) {
types = m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON);
}
setSelectedObjects( Collections.singletonList( types[0]) );
setViewId( DEFAULT_VIEW);
this.user = user;
if ( user != null && !user.isAdmin()) {
boolean selected = m_facade.getSystemPreferences().getEntryAsBoolean( CalendarModel.ONLY_MY_EVENTS_DEFAULT, true);
optionMap.put( CalendarModel.ONLY_MY_EVENTS, selected ? "true" : "false");
}
optionMap.put( CalendarModel.SAVE_SELECTED_DATE, "false");
resetExports();
}
public void resetExports()
{
setTitle(null);
setOption( CalendarModel.SHOW_NAVIGATION_ENTRY, "true");
setOption(HTML_EXPORT_ENABLED, "false");
setOption(ICAL_EXPORT_ENABLED, "false");
}
public boolean isMatchingSelectionAndFilter( Appointment appointment) throws RaplaException
{
Reservation reservation = appointment.getReservation();
if ( reservation == null)
{
return false;
}
Allocatable[] allocatables = reservation.getAllocatablesFor(appointment);
HashSet<RaplaObject> hashSet = new HashSet<RaplaObject>( Arrays.asList(allocatables));
Collection<RaplaObject> selectedObjectsAndChildren = getSelectedObjectsAndChildren();
hashSet.retainAll( selectedObjectsAndChildren);
boolean matchesAllotables = hashSet.size() != 0;
if ( !matchesAllotables)
{
return false;
}
Classification classification = reservation.getClassification();
if ( isDefaultEventTypes())
{
return true;
}
ClassificationFilter[] reservationFilter = getReservationFilter();
for ( ClassificationFilter filter:reservationFilter)
{
if (filter.matches(classification))
{
return true;
}
}
return false;
}
public boolean setConfiguration(CalendarModelConfiguration config, final Map<String,String> alternativOptions) throws RaplaException {
ArrayList<RaplaObject> selectedObjects = new ArrayList<RaplaObject>();
allocatableFilter.clear();
reservationFilter.clear();
if ( config == null)
{
defaultEventTypes = true;
defaultResourceTypes = true;
DynamicType type =null;
{
DynamicType[] dynamicTypes = m_facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE);
if ( dynamicTypes.length > 0)
{
type = dynamicTypes[0];
}
}
if ( type == null)
{
DynamicType[] dynamicTypes = m_facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON);
if ( dynamicTypes.length > 0)
{
type = dynamicTypes[0];
}
}
if ( type != null)
{
setSelectedObjects( Collections.singletonList(type));
}
return true;
}
else
{
defaultEventTypes = config.isDefaultEventTypes();
defaultResourceTypes = config.isDefaultResourceTypes();
}
boolean couldResolveAllEntities = true;
// get filter
title = config.getTitle();
selectedView = config.getView();
//selectedObjects
optionMap = new TreeMap<String,String>();
// viewOptionMap = new TreeMap<String,String>();
if ( config.getOptionMap() != null)
{
Map<String,String> configOptions = config.getOptionMap();
addOptions(configOptions);
}
if (alternativOptions != null )
{
addOptions(alternativOptions);
}
final String saveDate = optionMap.get( CalendarModel.SAVE_SELECTED_DATE);
if ( config.getSelectedDate() != null && (saveDate == null || saveDate.equals("true"))) {
setSelectedDate( config.getSelectedDate() );
}
else
{
setSelectedDate( m_facade.today());
}
if ( config.getStartDate() != null) {
setStartDate( config.getStartDate() );
}
else
{
setStartDate( m_facade.today());
}
if ( config.getEndDate() != null && (saveDate == null || saveDate.equals("true"))) {
setEndDate( config.getEndDate() );
}
else
{
setEndDate( DateTools.addYear(getStartDate()));
}
selectedObjects.addAll( config.getSelected());
if ( config.isResourceRootSelected())
{
selectedObjects.add( ALLOCATABLES_ROOT);
}
Set<User> selectedUsers = getSelected(User.TYPE);
User currentUser = getUser();
if (currentUser != null && selectedUsers.size() == 1 && selectedUsers.iterator().next().equals( currentUser))
{
if ( getOption( CalendarModel.ONLY_MY_EVENTS) == null)
{
setOption( CalendarModel.ONLY_MY_EVENTS, "true");
selectedObjects.remove( currentUser);
}
}
setSelectedObjects( selectedObjects );
for ( ClassificationFilter f:config.getFilter())
{
final DynamicType type = f.getType();
final String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
boolean eventType = annotation != null &&annotation.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
Map<DynamicType,ClassificationFilter> map = eventType ? reservationFilter : allocatableFilter;
map.put(type, f);
}
return couldResolveAllEntities;
}
protected void addOptions(Map<String,String> configOptions) {
for (Map.Entry<String, String> entry:configOptions.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
optionMap.put( key, value);
}
}
public User getUser() {
return user;
}
public CalendarModelConfigurationImpl createConfiguration() throws RaplaException {
ClassificationFilter[] allocatableFilter = isDefaultResourceTypes() ? null : getAllocatableFilter();
ClassificationFilter[] eventFilter = isDefaultEventTypes() ? null : getReservationFilter();
return createConfiguration(allocatableFilter, eventFilter);
}
CalendarModelConfigurationImpl beforeTemplateConf;
public void dataChanged(ModificationEvent evt) throws RaplaException
{
Collection<RaplaObject> selectedObjects = getSelectedObjects();
if ( evt == null)
{
return;
}
boolean switchTemplate = ((UpdateResult)evt).isSwitchTemplateMode();
if (switchTemplate)
{
boolean changeToTemplate= m_facade.getTemplateName() != null;
if (changeToTemplate)
{
beforeTemplateConf = createConfiguration();
setSelectedObjects(Collections.singleton(ALLOCATABLES_ROOT));
}
else if ( beforeTemplateConf != null)
{
setConfiguration( beforeTemplateConf, null);
beforeTemplateConf = null;
}
}
{
Collection<RaplaObject> newSelection = new ArrayList<RaplaObject>();
boolean changed = false;
for ( RaplaObject obj: selectedObjects)
{
if ( obj instanceof Entity)
{
if (!evt.isRemoved((Entity) obj))
{
newSelection.add( obj);
}
else
{
changed = true;
}
}
}
if ( changed)
{
setSelectedObjects( newSelection);
}
}
{
if (evt.isModified( DynamicType.TYPE) || evt.isModified( Category.TYPE) || evt.isModified( User.TYPE))
{
CalendarModelConfigurationImpl config = (CalendarModelConfigurationImpl)createConfiguration();
updateConfig(evt, config);
if ( beforeTemplateConf != null)
{
updateConfig(evt, beforeTemplateConf);
}
setConfiguration( config, null);
}
}
}
public void updateConfig(ModificationEvent evt, CalendarModelConfigurationImpl config) throws CannotExistWithoutTypeException {
User user2 = getUser();
if ( user2 != null && evt.isModified( user2))
{
Set<User> changed = RaplaType.retainObjects(evt.getChanged(), Collections.singleton(user2));
if ( changed.size() > 0)
{
User newUser = changed.iterator().next();
user = newUser;
}
}
for ( RaplaObject obj:evt.getChanged())
{
if ( obj.getRaplaType() == DynamicType.TYPE)
{
DynamicType type = (DynamicType) obj;
if ( config.needsChange(type))
{
config.commitChange( type);
}
}
}
for ( RaplaObject obj:evt.getRemoved())
{
if ( obj.getRaplaType() == DynamicType.TYPE)
{
DynamicType type = (DynamicType) obj;
config.commitRemove( type);
}
}
}
private CalendarModelConfigurationImpl createConfiguration(ClassificationFilter[] allocatableFilter, ClassificationFilter[] eventFilter) throws RaplaException {
String viewName = selectedView;
Set<Entity> selected = new HashSet<Entity>( );
Collection<RaplaObject> selectedObjects = getSelectedObjects();
for (RaplaObject object:selectedObjects) {
if ( !(object instanceof Conflict) && (object instanceof Entity))
{
// throw new RaplaException("Storing the conflict view is not possible with Rapla.");
selected.add( (Entity) object );
}
}
final Date selectedDate = getSelectedDate();
final Date startDate = getStartDate();
final Date endDate = getEndDate();
boolean resourceRootSelected = selectedObjects.contains( ALLOCATABLES_ROOT);
return newRaplaCalendarModel( selected,resourceRootSelected, allocatableFilter,eventFilter, title, startDate, endDate, selectedDate, viewName, optionMap);
}
public CalendarModelConfigurationImpl newRaplaCalendarModel(Collection<Entity> selected,
boolean resourceRootSelected,
ClassificationFilter[] allocatableFilter,
ClassificationFilter[] eventFilter, String title, Date startDate,
Date endDate, Date selectedDate, String view, Map<String,String> optionMap) throws RaplaException
{
boolean defaultResourceTypes;
boolean defaultEventTypes;
int eventTypes = 0;
int resourceTypes = 0;
defaultResourceTypes = true;
defaultEventTypes = true;
List<ClassificationFilter> filter = new ArrayList<ClassificationFilter>();
if (allocatableFilter != null) {
for (ClassificationFilter entry : allocatableFilter) {
ClassificationFilter clone = entry.clone();
filter.add(clone);
resourceTypes++;
if (entry.ruleSize() > 0) {
defaultResourceTypes = false;
}
}
}
if (eventFilter != null) {
for (ClassificationFilter entry : eventFilter) {
ClassificationFilter clone = entry.clone();
filter.add(clone);
eventTypes++;
if (entry.ruleSize() > 0) {
defaultEventTypes = false;
}
}
}
DynamicType[] allEventTypes;
allEventTypes = m_facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
if (allEventTypes.length > eventTypes && eventFilter != null) {
defaultEventTypes = false;
}
final DynamicType[] allTypes = m_facade.getDynamicTypes(null);
final int allResourceTypes = allTypes.length - allEventTypes.length;
if (allResourceTypes > resourceTypes && allocatableFilter != null) {
defaultResourceTypes = false;
}
final ClassificationFilter[] filterArray = filter.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY);
List<String> selectedIds = new ArrayList<String>();
Collection<RaplaType> idTypeList = new ArrayList<RaplaType>();
for (Entity obj:selected)
{
selectedIds.add( obj.getId());
idTypeList.add( obj.getRaplaType());
}
CalendarModelConfigurationImpl calendarModelConfigurationImpl = new CalendarModelConfigurationImpl(selectedIds, idTypeList,resourceRootSelected,filterArray, defaultResourceTypes, defaultEventTypes, title, startDate, endDate, selectedDate, view, optionMap);
calendarModelConfigurationImpl.setResolver( m_facade.getOperator());
return calendarModelConfigurationImpl;
}
public void setReservationFilter(ClassificationFilter[] array) {
reservationFilter.clear();
if ( array == null)
{
defaultEventTypes = true;
return;
}
try {
defaultEventTypes = createConfiguration(null,array).isDefaultEventTypes();
} catch (RaplaException e) {
// DO Not set the types
}
for (ClassificationFilter entry: array)
{
final DynamicType type = entry.getType();
reservationFilter.put( type, entry);
}
}
public void setAllocatableFilter(ClassificationFilter[] array) {
allocatableFilter.clear();
if ( array == null)
{
defaultResourceTypes = true;
return;
}
try {
defaultResourceTypes = createConfiguration(array,null).isDefaultResourceTypes();
} catch (RaplaException e) {
// DO Not set the types
}
for (ClassificationFilter entry: array)
{
final DynamicType type = entry.getType();
allocatableFilter.put( type, entry);
}
}
@Override
public Date getSelectedDate() {
return selectedDate;
}
@Override
public void setSelectedDate(Date date) {
if ( date == null)
throw new IllegalStateException("Date can't be null");
this.selectedDate = date;
}
@Override
public Date getStartDate() {
return startDate;
}
@Override
public void setStartDate(Date date) {
if ( date == null)
throw new IllegalStateException("Date can't be null");
this.startDate = date;
}
@Override
public Date getEndDate() {
return endDate;
}
@Override
public void setEndDate(Date date) {
if ( date == null)
throw new IllegalStateException("Date can't be null");
this.endDate = date;
}
@Override
public String getTitle()
{
return title;
}
@Override
public void setTitle(String title) {
this.title = title;
}
@Override
public void setViewId(String view) {
this.selectedView = view;
}
@Override
public String getViewId() {
return this.selectedView;
}
class CalendarModelParseContext implements ParseContext
{
public Function resolveVariableFunction(String variableName) throws IllegalAnnotationException {
if ( variableName.equals("allocatables"))
{
List<Function> emptyList = Collections.emptyList();
return new Function(variableName, emptyList)
{
@Override
public Object eval(EvalContext context) {
try {
return Arrays.asList(getSelectedAllocatables());
} catch (RaplaException e) {
return Collections.emptyList();
}
}
};
}
else if ( variableName.equals("timeIntervall"))
{
List<Function> emptyList = Collections.emptyList();
return new Function(variableName, emptyList)
{
@Override
public Object eval(EvalContext context) {
return getTimeIntervall();
}
};
}
else if ( variableName.equals("selectedDate"))
{
List<Function> emptyList = Collections.emptyList();
return new Function(variableName, emptyList)
{
@Override
public Object eval(EvalContext context) {
return getSelectedDate();
}
};
}
return null;
}
}
public TimeInterval getTimeIntervall()
{
return new TimeInterval(getStartDate(), getEndDate());
}
@Override
public String getNonEmptyTitle() {
String title = getTitle();
if (title != null && title.trim().length()>0)
{
ParseContext parseContext = new CalendarModelParseContext();
ParsedText parsedTitle;
try {
parsedTitle = new ParsedText( title);
parsedTitle.init(parseContext);
} catch (IllegalAnnotationException e) {
return e.getMessage();
}
Locale locale = raplaLocale.getLocale();
EvalContext evalContext = new EvalContext( locale);
String result = parsedTitle.formatName( evalContext);
return result;
}
String types = "";
/*
String dateString = getRaplaLocale().formatDate(getSelectedDate());
if ( isListingAllocatables()) {
try {
Collection list = getSelectedObjectsAndChildren();
if (list.size() == 1) {
Object obj = list.iterator().next();
if (!( obj instanceof DynamicType))
{
types = getI18n().format("allocation_view",getName( obj ),dateString);
}
}
} catch (RaplaException ex) {
}
if ( types == null )
types = getI18n().format("allocation_view", getI18n().getString("resources_persons"));
} else if ( isListingReservations()) {
types = getI18n().getString("reservations");
} else {
types = "unknown";
}
*/
return types;
}
public String getName(Object object) {
if (object == null)
return "";
if (object instanceof Named) {
String name = ((Named) object).getName(getI18n().getLocale());
return (name != null) ? name : "";
}
return object.toString();
}
private Collection<Allocatable> getFilteredAllocatables() throws RaplaException {
List<Allocatable> list = new ArrayList<Allocatable>();
for ( Allocatable allocatable :m_facade.getAllocatables())
{
if ( isInFilter( allocatable) && (user == null || allocatable.canRead(user))) {
list.add( allocatable);
}
}
return list;
}
private boolean isInFilter( Allocatable classifiable) {
if (isTemplateModus())
{
return true;
}
final Classification classification = classifiable.getClassification();
final DynamicType type = classification.getType();
final ClassificationFilter classificationFilter = allocatableFilter.get( type);
if ( classificationFilter != null)
{
final boolean matches = classificationFilter.matches(classification);
return matches;
}
else
{
return defaultResourceTypes;
}
}
@Override
public Collection<RaplaObject> getSelectedObjectsAndChildren() throws RaplaException
{
Assert.notNull(selectedObjects);
ArrayList<DynamicType> dynamicTypes = new ArrayList<DynamicType>();
for (Iterator<RaplaObject> it = selectedObjects.iterator();it.hasNext();)
{
Object obj = it.next();
if (obj instanceof DynamicType) {
dynamicTypes.add ((DynamicType)obj);
}
}
HashSet<RaplaObject> result = new HashSet<RaplaObject>();
result.addAll( selectedObjects );
boolean allAllocatablesSelected = selectedObjects.contains( CalendarModelImpl.ALLOCATABLES_ROOT);
Collection<Allocatable> filteredList = getFilteredAllocatables();
for (Iterator<Allocatable> it = filteredList.iterator();it.hasNext();)
{
Allocatable oneSelectedItem = it.next();
if ( selectedObjects.contains(oneSelectedItem)) {
continue;
}
Classification classification = oneSelectedItem.getClassification();
if ( classification == null)
{
continue;
}
if ( allAllocatablesSelected || dynamicTypes.contains(classification.getType()))
{
result.add( oneSelectedItem );
continue;
}
}
return result;
}
@Override
public void setSelectedObjects(Collection<? extends Object> selectedObjects) {
this.selectedObjects = retainRaplaObjects(selectedObjects);
if (markedAllocatables != null && !markedAllocatables.isEmpty())
{
markedAllocatables = new LinkedHashSet<Allocatable>(markedAllocatables);
try {
markedAllocatables.retainAll( Arrays.asList(getSelectedAllocatables()));
} catch (RaplaException e) {
markedAllocatables = Collections.emptyList();
}
}
}
private List<RaplaObject> retainRaplaObjects(Collection<? extends Object> list ){
List<RaplaObject> result = new ArrayList<RaplaObject>();
for ( Iterator<? extends Object> it = list.iterator();it.hasNext();) {
Object obj = it.next();
if ( obj instanceof RaplaObject) {
result.add( (RaplaObject)obj );
}
}
return result;
}
@Override
public Collection<RaplaObject> getSelectedObjects()
{
return selectedObjects;
}
@Override
public ClassificationFilter[] getReservationFilter() throws RaplaException
{
Collection<ClassificationFilter> filter ;
if ( isDefaultEventTypes() || isTemplateModus())
{
filter = new ArrayList<ClassificationFilter>();
for (DynamicType type :m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION))
{
filter.add( type.newClassificationFilter());
}
}
else
{
filter = reservationFilter.values();
}
return filter.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY);
}
protected boolean isTemplateModus() {
return m_facade.getTemplateName() != null;
}
@Override
public ClassificationFilter[] getAllocatableFilter() throws RaplaException {
Collection<ClassificationFilter> filter ;
if ( isDefaultResourceTypes() || isTemplateModus())
{
filter = new ArrayList<ClassificationFilter>();
for (DynamicType type :m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE))
{
filter.add( type.newClassificationFilter());
}
for (DynamicType type :m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON))
{
filter.add( type.newClassificationFilter());
}
}
else
{
filter = allocatableFilter.values();
}
return filter.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY);
}
public CalendarSelectionModel clone() {
CalendarModelImpl clone;
try
{
clone = new CalendarModelImpl(context, user, m_facade);
CalendarModelConfiguration config = createConfiguration();
Map<String, String> alternativOptions = null;
clone.setConfiguration( config, alternativOptions);
}
catch ( RaplaException e )
{
throw new IllegalStateException( e.getMessage() );
}
return clone;
}
@Override
public Reservation[] getReservations() throws RaplaException {
return getReservations( getStartDate(), getEndDate() );
}
@Override
public Reservation[] getReservations(Date startDate, Date endDate) throws RaplaException
{
return getReservationsAsList( startDate, endDate ).toArray( Reservation.RESERVATION_ARRAY);
}
private List<Reservation> getReservationsAsList(Date start, Date end) throws RaplaException
{
Allocatable[] allocatables = getSelectedAllocatables();
if ( isNoAllocatableSelected())
{
allocatables = null;
}
Collection<Conflict> conflicts = getSelectedConflicts();
if ( conflicts.size() > 0)
{
return m_facade.getReservations(conflicts);
}
Reservation[] reservationArray =m_facade.getReservations(allocatables, start, end);
List<Reservation> asList = Arrays.asList( reservationArray );
return restrictReservations(asList);
}
public List<Reservation> restrictReservations(Collection<Reservation> reservationsToRestrict) throws RaplaException {
List<Reservation> reservations = new ArrayList<Reservation>(reservationsToRestrict);
// Don't restrict templates
if ( isTemplateModus())
{
return reservations;
}
ClassificationFilter[] reservationFilter = getReservationFilter();
if ( isDefaultEventTypes())
{
reservationFilter = null;
}
Set<User> users = getUserRestrictions();
for ( Iterator<Reservation> it = reservations.iterator();it.hasNext();)
{
Reservation event = it.next();
if ( !users.isEmpty() && !users.contains( event.getOwner() )) {
it.remove();
}
else if (reservationFilter != null && !ClassificationFilter.Util.matches( reservationFilter,event))
{
it.remove();
}
}
return reservations;
}
private Set<User> getUserRestrictions() {
User currentUser = getUser();
if ( currentUser != null && isOnlyCurrentUserSelected() || !m_facade.canReadReservationsFromOthers( currentUser))
{
return Collections.singleton( currentUser );
}
else if ( currentUser != null && currentUser.isAdmin())
{
return getSelected(User.TYPE);
}
else
{
return Collections.emptySet();
}
}
private boolean isNoAllocatableSelected()
{
for (RaplaObject obj :getSelectedObjects())
{
RaplaType raplaType = obj.getRaplaType();
if ( raplaType == Allocatable.TYPE)
{
return false;
}
else if (raplaType == DynamicType.TYPE)
{
DynamicType type = (DynamicType) obj;
String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
if ( annotation.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON ) || annotation.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE))
{
return false;
}
}
else if ( obj.equals(ALLOCATABLES_ROOT) )
{
return false;
}
}
return true;
}
@Override
public Allocatable[] getSelectedAllocatables() throws RaplaException {
Collection<Allocatable> result = getSelectedAllocatablesAsList();
return result.toArray(Allocatable.ALLOCATABLE_ARRAY);
}
protected Collection<Allocatable> getSelectedAllocatablesAsList()
throws RaplaException {
Collection<Allocatable> result = new HashSet<Allocatable>();
for(RaplaObject object:getSelectedObjectsAndChildren()) {
if ( object.getRaplaType() == Conflict.TYPE ) {
result.add( ((Conflict)object).getAllocatable() );
}
}
// We ignore the allocatable selection if there are conflicts selected
if ( result.isEmpty())
{
for(RaplaObject object:getSelectedObjectsAndChildren()) {
if ( object.getRaplaType() ==Allocatable.TYPE ) {
result.add( (Allocatable)object );
}
}
}
Collection<Allocatable> filteredAllocatables = getFilteredAllocatables();
result.retainAll( filteredAllocatables);
return result;
}
public Collection<Conflict> getSelectedConflicts() {
return getSelected(Conflict.TYPE);
}
public Set<DynamicType> getSelectedTypes(String classificationType) throws RaplaException {
Set<DynamicType> result = new HashSet<DynamicType>();
Iterator<RaplaObject> it = getSelectedObjectsAndChildren().iterator();
while (it.hasNext()) {
RaplaObject object = it.next();
if ( object.getRaplaType() == DynamicType.TYPE ) {
if (classificationType == null || (( DynamicType) object).getAnnotation( DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE).equals( classificationType))
{
result.add((DynamicType) object );
}
}
}
return result;
}
private <T extends RaplaObject<T>> Set<T> getSelected(RaplaType<T> type) {
Set<T> result = new HashSet<T>();
Iterator<RaplaObject> it = getSelectedObjects().iterator();
while (it.hasNext()) {
RaplaObject object = it.next();
if ( object.getRaplaType() == type ) {
@SuppressWarnings("unchecked")
T casted = (T)object;
result.add( casted );
}
}
return result;
}
protected I18nBundle getI18n() {
return i18n;
}
protected RaplaLocale getRaplaLocale() {
return raplaLocale;
}
@Override
public boolean isOnlyCurrentUserSelected() {
String option = getOption(CalendarModel.ONLY_MY_EVENTS );
if ( option != null && option.equalsIgnoreCase("TRUE"))
{
return true;
}
return false;
}
@Override
public void selectUser(User user) {
List<RaplaObject> selectedObjects = new ArrayList<RaplaObject>(getSelectedObjects());
for (Iterator<RaplaObject> it = selectedObjects.iterator();it.hasNext();) {
RaplaObject obj = it.next();
if (obj.getRaplaType() == User.TYPE ) {
it.remove();
}
}
if ( user != null)
{
selectedObjects.add( user );
}
setSelectedObjects(selectedObjects);
}
@Override
public String getOption( String name )
{
return optionMap.get( name );
}
@Override
public void setOption( String name, String string )
{
if ( string == null)
{
optionMap.remove( name);
}
else
{
optionMap.put( name, string);
}
}
@Override
public boolean isDefaultEventTypes()
{
return defaultEventTypes;
}
@Override
public boolean isDefaultResourceTypes()
{
return defaultResourceTypes;
}
@Override
public void save(final String filename) throws RaplaException,
EntityNotFoundException {
Preferences clone = createStorablePreferences(filename);
m_facade.store(clone);
}
public Preferences createStorablePreferences(final String filename) throws RaplaException, EntityNotFoundException {
final CalendarModelConfiguration conf = createConfiguration();
Preferences clone = m_facade.edit(m_facade.getPreferences(user));
if ( filename == null)
{
clone.putEntry( CalendarModelConfiguration.CONFIG_ENTRY, conf);
}
else
{
Map<String,CalendarModelConfiguration> exportMap= clone.getEntry(EXPORT_ENTRY);
Map<String,CalendarModelConfiguration> newMap;
if ( exportMap == null)
newMap = new TreeMap<String,CalendarModelConfiguration>();
else
newMap = new TreeMap<String,CalendarModelConfiguration>( exportMap);
newMap.put(filename, conf);
clone.putEntry( EXPORT_ENTRY, m_facade.newRaplaMap( newMap ));
}
return clone;
}
// Old defaultname behaviour. Duplication of language resource names. But the system has to be replaced anyway in the future, because it doesnt allow for multiple language outputs on the server.
private boolean isOldDefaultNameBehavoir(final String filename)
{
List<String> translations = new ArrayList<String>();
translations.add( getI18n().getString("default") );
translations.add( "default" );
translations.add( "Default" );
translations.add( "Standard" );
translations.add( "Standaard");
// special for polnish
if (filename.startsWith( "Domy") && filename.endsWith("lne"))
{
return true;
}
if (filename.startsWith( "Est") && filename.endsWith("ndar"))
{
return true;
}
return translations.contains(filename);
}
@Override
public void load(final String filename) throws RaplaException, EntityNotFoundException, CalendarNotFoundExeption {
final CalendarModelConfiguration modelConfig;
boolean createIfNotNull =false;
{
final Preferences preferences = m_facade.getPreferences(user, createIfNotNull);
modelConfig = getModelConfig(filename, preferences);
}
if ( modelConfig == null && filename != null )
{
throw new CalendarNotFoundExeption("Calendar with name " + filename + " not found.");
}
else
{
final boolean isDefault = filename == null ;
Map<String,String> alternativeOptions = new HashMap<String,String>();
if (modelConfig != null && modelConfig.getOptionMap() != null)
{
// All old default calendars have no selected date
if (isDefault && (modelConfig.getOptionMap().get( CalendarModel.SAVE_SELECTED_DATE) == null))
{
alternativeOptions.put(CalendarModel.SAVE_SELECTED_DATE , "false");
}
// All old calendars are exported
if ( !isDefault && modelConfig.getOptionMap().get(HTML_EXPORT_ENABLED) == null)
{
alternativeOptions.put(HTML_EXPORT_ENABLED,"true");
}
}
setConfiguration(modelConfig, alternativeOptions);
}
}
public CalendarModelConfiguration getModelConfig(final String filename,final Preferences preferences) {
final CalendarModelConfiguration modelConfig;
if (preferences != null)
{
final boolean isDefault = filename == null ;
if ( isDefault )
{
modelConfig = preferences.getEntry(CalendarModelConfiguration.CONFIG_ENTRY);
}
else if ( filename != null && !isDefault)
{
Map<String,CalendarModelConfiguration> exportMap= preferences.getEntry(EXPORT_ENTRY);
final CalendarModelConfiguration config;
if ( exportMap != null)
{
config = exportMap.get(filename);
}
else
{
config = null;
}
if ( config == null && isOldDefaultNameBehavoir(filename) )
{
modelConfig = preferences.getEntry(CalendarModelConfiguration.CONFIG_ENTRY);
}
else
{
modelConfig = config;
}
}
else
{
modelConfig = null;
}
}
else
{
modelConfig = null;
}
return modelConfig;
}
//Set<Appointment> conflictList = new HashSet<Appointment>();
// if ( selectedConflicts != null)
// {
// for (Conflict conflict: selectedConflicts)
// {
// if ( conflict.getAppointment1().equals( app.getId()))
// {
// conflictList.add(conflict.getAppointment2());
// }
// else if ( conflict.getAppointment2().equals( app.getId()))
// {
// conflictList.add(conflict.getAppointment1());
// }
// }
// }
@Override
public List<AppointmentBlock> getBlocks() throws RaplaException
{
List<AppointmentBlock> appointments = new ArrayList<AppointmentBlock>();
Set<Allocatable> selectedAllocatables = new HashSet<Allocatable>(Arrays.asList(getSelectedAllocatables()));
if ( isNoAllocatableSelected())
{
selectedAllocatables = null;
}
Collection<Conflict> selectedConflicts = getSelectedConflicts();
List<Reservation> reservations = m_facade.getReservations( selectedConflicts);
Map<Appointment,Set<Appointment>> conflictingAppointments = ConflictImpl.getMap(selectedConflicts,reservations);
for ( Reservation event:getReservations())
{
for (Appointment app: event.getAppointments())
{
//
Allocatable[] allocatablesFor = event.getAllocatablesFor(app);
if ( selectedAllocatables == null || containsOne(selectedAllocatables, allocatablesFor))
{
Collection<Appointment> conflictList = conflictingAppointments.get( app );
if ( conflictList == null || conflictList.isEmpty())
{
app.createBlocks(getStartDate(), getEndDate(), appointments);
}
else
{
List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
app.createBlocks(getStartDate(), getEndDate(), blocks);
Iterator<AppointmentBlock> it = blocks.iterator();
while ( it.hasNext())
{
AppointmentBlock block = it.next();
boolean found = false;
for ( Appointment conflictingApp:conflictList)
{
if (conflictingApp.overlaps( block ))
{
found = true;
break;
}
}
if ( !found)
{
it.remove();
}
}
appointments.addAll( blocks);
}
}
}
}
Collections.sort(appointments, new AppointmentBlockStartComparator());
return appointments;
}
private boolean containsOne(Set<Allocatable> allocatableSet,
Allocatable[] listOfAllocatablesToMatch) {
for ( Allocatable alloc: listOfAllocatablesToMatch)
{
if (allocatableSet.contains(alloc))
{
return true;
}
}
return false;
}
@Override
public DynamicType guessNewEventType() throws RaplaException {
Set<DynamicType> selectedTypes = getSelectedTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
DynamicType guessedType;
if (selectedTypes.size()>0)
{
guessedType = selectedTypes.iterator().next();
}
else
{
guessedType = m_facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)[0];
}
ClassificationFilter[] reservationFilter = getReservationFilter();
DynamicType firstType = null;
boolean found = false;
// assure that the guessed type is in the filter selection list
for (ClassificationFilter filter : reservationFilter)
{
DynamicType type = filter.getType();
if ( firstType == null)
{
firstType = type;
}
if ( type.equals( guessedType))
{
found = true;
break;
}
}
if (!found && firstType != null)
{
guessedType = firstType;
}
return guessedType;
}
@Override
public Collection<TimeInterval> getMarkedIntervals()
{
return timeIntervals;
}
@Override
public void setMarkedIntervals(Collection<TimeInterval> timeIntervals)
{
if ( timeIntervals != null)
{
this.timeIntervals = Collections.unmodifiableCollection(timeIntervals);
}
else
{
this.timeIntervals = Collections.emptyList();
}
}
@Override
public void markInterval(Date start, Date end) {
TimeInterval timeInterval = new TimeInterval( start, end);
setMarkedIntervals( Collections.singletonList( timeInterval));
}
@Override
public Collection<Allocatable> getMarkedAllocatables() {
return markedAllocatables;
}
@Override
public void setMarkedAllocatables(Collection<Allocatable> allocatables) {
this.markedAllocatables = allocatables;
}
public Collection<Appointment> getAppointments(TimeInterval interval) throws RaplaException
{
Date startDate = interval.getStart();
Date endDate = interval.getEnd();
List<Reservation> reservations = getReservationsAsList(startDate, endDate);
Collection<Allocatable> allocatables =getSelectedAllocatablesAsList();
List<Appointment> result = RaplaBuilder.getAppointments(reservations, allocatables);
return result;
}
}
| 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.internal;
import java.util.Calendar;
import java.util.LinkedHashSet;
import java.util.Set;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.facade.CalendarOptions;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
/** <strong>WARNING!!</strong> This class should not be public to the outside. Please use the interface */
public class CalendarOptionsImpl implements CalendarOptions {
public final static TypedComponentRole<RaplaConfiguration> CALENDAR_OPTIONS= new TypedComponentRole<RaplaConfiguration>("org.rapla.calendarview");
public final static TypedComponentRole<Boolean> SHOW_CONFLICT_WARNING = new TypedComponentRole<Boolean>("org.rapla.conflict.showWarning");
public static final String WORKTIME = "worktime";
public static final String EXCLUDE_DAYS = "exclude-days";
public static final String WEEKSTART = "exclude-days";
public static final String ROWS_PER_HOUR = "rows-per-hour";
public final static String EXCEPTIONS_VISIBLE="exceptions-visible";
public final static String COMPACT_COLUMNS="compact-columns";
public final static String COLOR_BLOCKS="color";
public final static String COLOR_RESOURCES="resources";
public final static String COLOR_EVENTS="reservations";
public final static String COLOR_EVENTS_AND_RESOURCES="reservations_and_resources";
public final static String COLOR_NONE="disabled";
public final static String DAYS_IN_WEEKVIEW = "days-in-weekview";
public final static String FIRST_DAY_OF_WEEK = "first-day-of-week";
public final static String MIN_BLOCK_WIDTH = "minimum-block-width";
/** The following fields will be replaced in version 1.7 as they don't refer to the calendar but to the creation of appointment. Please don't use*/
public final static String REPEATING="repeating";
public final static String NTIMES="repeating.ntimes";
public final static String CALNAME="calendar-name";
public final static String REPEATINGTYPE="repeatingtype";
public final static String NON_FILTERED_EVENTS= "non-filtered-events";
public final static String NON_FILTERED_EVENTS_TRANSPARENT= "transparent";
public final static String NON_FILTERED_EVENTS_HIDDEN= "not_visible";
int nTimes;
/** Ends here*/
Set<Integer> excludeDays = new LinkedHashSet<Integer>();
int maxtimeMinutes = -1;
int mintimeMinutes = -1;
int rowsPerHour = 4;
boolean exceptionsVisible;
boolean compactColumns = false; // use for strategy.setFixedSlotsEnabled
Configuration config;
String colorField;
boolean nonFilteredEventsVisible = false;
int daysInWeekview;
int firstDayOfWeek;
private int minBlockWidth;
public CalendarOptionsImpl(Configuration config ) throws RaplaException {
this.config = config;
Configuration worktime = config.getChild( WORKTIME );
String worktimesString = worktime.getValue("8-18");
int minusIndex = worktimesString.indexOf("-");
try {
if ( minusIndex >= 0)
{
String firstPart = worktimesString.substring(0,minusIndex);
String secondPart = worktimesString.substring(minusIndex+ 1);
mintimeMinutes = parseMinutes( firstPart );
maxtimeMinutes = parseMinutes( secondPart );
}
else
{
mintimeMinutes = parseMinutes( worktimesString);
}
} catch ( NumberFormatException e ) {
throw new RaplaException( "Invalid time in " + worktime + ". use the following format : 8-18 or 8:30-18:00!");
}
Configuration exclude = config.getChild( EXCLUDE_DAYS );
String excludeString = exclude.getValue("");
if ( excludeString.trim().length() > 0)
{
String[] tokens = excludeString.split(",");
for ( String token:tokens)
{
String normalizedToken = token.toLowerCase().trim();
try {
excludeDays.add( new Integer(normalizedToken) );
} catch ( NumberFormatException e ) {
throw new RaplaException("Invalid day in " + excludeDays + ". only numbers are allowed!");
}
} // end of while ()
}
int firstDayOfWeekDefault = Calendar.getInstance().getFirstDayOfWeek();
firstDayOfWeek = config.getChild(FIRST_DAY_OF_WEEK).getValueAsInteger(firstDayOfWeekDefault);
daysInWeekview = config.getChild(DAYS_IN_WEEKVIEW).getValueAsInteger( 7 );
rowsPerHour = config.getChild( ROWS_PER_HOUR ).getValueAsInteger( 4 );
exceptionsVisible = config.getChild(EXCEPTIONS_VISIBLE).getValueAsBoolean(false);
colorField = config.getChild( COLOR_BLOCKS ).getValue( COLOR_EVENTS_AND_RESOURCES );
minBlockWidth = config.getChild( MIN_BLOCK_WIDTH).getValueAsInteger(0);
nTimes = config.getChild( NTIMES ).getValueAsInteger( 1 );
nonFilteredEventsVisible = config.getChild( NON_FILTERED_EVENTS).getValue(NON_FILTERED_EVENTS_TRANSPARENT).equals( NON_FILTERED_EVENTS_TRANSPARENT);
}
private int parseMinutes(String string) {
String[] split = string.split(":");
int hour = Integer.parseInt(split[0].toLowerCase().trim());
int minute = 0;
if ( split.length > 1)
{
minute = Integer.parseInt(split[1].toLowerCase().trim());
}
int result = Math.max(0,Math.min(24 * 60,hour * 60 + minute));
return result;
}
public Configuration getConfig() {
return config;
}
public int getWorktimeStart() {
return mintimeMinutes / 60;
}
public int getRowsPerHour() {
return rowsPerHour;
}
public int getWorktimeEnd() {
return maxtimeMinutes / 60;
}
public Set<Integer> getExcludeDays() {
return excludeDays;
}
public boolean isNonFilteredEventsVisible()
{
return nonFilteredEventsVisible;
}
public void setNonFilteredEventsVisible(boolean nonFilteredEventsVisible)
{
this.nonFilteredEventsVisible = nonFilteredEventsVisible;
}
public boolean isExceptionsVisible() {
return exceptionsVisible;
}
public boolean isCompactColumns() {
return compactColumns;
}
public boolean isResourceColoring() {
return colorField.equals( COLOR_RESOURCES ) || colorField.equals( COLOR_EVENTS_AND_RESOURCES);
}
public boolean isEventColoring() {
return colorField.equals( COLOR_EVENTS ) || colorField.equals( COLOR_EVENTS_AND_RESOURCES);
}
public int getDaysInWeekview() {
return daysInWeekview;
}
public int getFirstDayOfWeek()
{
return firstDayOfWeek;
}
public int getMinBlockWidth()
{
return minBlockWidth;
}
public boolean isWorktimeOvernight() {
int worktimeS = getWorktimeStartMinutes();
int worktimeE = getWorktimeEndMinutes();
worktimeE = (worktimeE == 0)?24*60:worktimeE;
boolean overnight = worktimeS >= worktimeE|| worktimeE == 24*60;
return overnight;
}
public int getWorktimeStartMinutes() {
return mintimeMinutes;
}
public int getWorktimeEndMinutes() {
return maxtimeMinutes;
}
}
| 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.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.rapla.components.util.Assert;
import org.rapla.entities.Entity;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.internal.PeriodImpl;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.facade.PeriodModel;
import org.rapla.facade.QueryModule;
import org.rapla.framework.RaplaException;
import org.rapla.storage.StorageOperator;
class PeriodModelImpl implements PeriodModel,ModificationListener
{
TreeSet<Period> m_periods = new TreeSet<Period>(new Comparator<Period>() {
public int compare(Period o1, Period o2) {
int compareTo = o1.compareTo(o2);
return -compareTo;
}
}
);
ClientFacade facade;
Period defaultPeriod;
PeriodModelImpl( ClientFacade query ) throws RaplaException {
this.facade = query;
update();
}
public void update() throws RaplaException {
m_periods.clear();
DynamicType type = facade.getDynamicType(StorageOperator.PERIOD_TYPE);
ClassificationFilter[] filters = type.newClassificationFilter().toArray();
Collection<Allocatable> allocatables = facade.getOperator().getAllocatables( filters);
for ( Allocatable alloc:allocatables)
{
Classification classification = alloc.getClassification();
String name = (String)classification.getValue("name");
Date start = (Date) classification.getValue("start");
Date end = (Date) classification.getValue("end");
PeriodImpl period = new PeriodImpl(name,start,end);
m_periods.add(period);
}
}
public void dataChanged(ModificationEvent evt) throws RaplaException
{
if (isPeriodModified(evt))
{
update();
}
}
protected boolean isPeriodModified(ModificationEvent evt) {
for (Entity changed:evt.getChanged())
{
if ( isPeriod( changed))
{
return true;
}
}
for (Entity changed:evt.getRemoved())
{
if ( isPeriod( changed))
{
return true;
}
}
return false;
}
private boolean isPeriod(Entity entity) {
if ( entity.getRaplaType() != Allocatable.TYPE)
{
return false;
}
Allocatable alloc = (Allocatable) entity;
Classification classification = alloc.getClassification();
if ( classification == null)
{
return false;
}
if (!classification.getType().getKey().equals(StorageOperator.PERIOD_TYPE))
{
return false;
}
return true;
}
protected QueryModule getQuery() {
return facade;
}
/** returns the first matching period or null if no period matches.*/
public Period getPeriodFor(Date date) {
if (date == null)
return null;
PeriodImpl comparePeriod = new PeriodImpl("DUMMY",date,date);
Iterator<Period> it = m_periods.tailSet(comparePeriod).iterator();
while (it.hasNext()) {
Period period = it.next();
if (period.contains(date)) {
return period;
}
}
return null;
}
static private long diff(Date d1,Date d2) {
long diff = d1.getTime()-d2.getTime();
if (diff<0)
diff = diff * -1;
return diff;
}
public Period getNearestPeriodForDate(Date date) {
return getNearestPeriodForStartDate( m_periods, date, null);
}
public Period getNearestPeriodForStartDate(Date date) {
return getNearestPeriodForStartDate( date, null);
}
public Period getNearestPeriodForStartDate(Date date, Date endDate) {
return getNearestPeriodForStartDate( getPeriodsFor( date ), date, endDate);
}
public Period getNearestPeriodForEndDate(Date date) {
return getNearestPeriodForEndDate( getPeriodsFor( date ), date);
}
static private Period getNearestPeriodForStartDate(Collection<Period> periodList, Date date, Date endDate) {
Period result = null;
long min_from_start=Long.MAX_VALUE, min_from_end=0;
long from_start, from_end=0;
Iterator<Period> it = periodList.iterator();
while (it.hasNext())
{
Period period = it.next();
if ( period == null)
{ // EXCO: Why this test ?
continue;
}
from_start = diff(period.getStart(),date);
if ( endDate != null )
{
from_end = Math.abs(diff(period.getEnd(), endDate));
}
if ( from_start < min_from_start
|| (from_start == min_from_start && from_end < min_from_end)
)
{
min_from_start = from_start;
min_from_end = from_end;
result = period;
}
}
return result;
}
static private Period getNearestPeriodForEndDate(Collection<Period> periodList, Date date) {
Period result = null;
long min=-1;
Iterator<Period> it = periodList.iterator();
while (it.hasNext()) {
Period period = it.next();
if (min == -1) {
min = diff(period.getEnd(),date);
result = period;
}
if (diff(period.getEnd(),date) < min) {
min = diff(period.getStart(),date);
result = period;
}
}
return result;
}
/** return all matching periods.*/
public List<Period> getPeriodsFor(Date date) {
ArrayList<Period> list = new ArrayList<Period>();
if (date == null)
return list;
PeriodImpl comparePeriod = new PeriodImpl("DUMMY",date,date);
SortedSet<Period> set = m_periods.tailSet(comparePeriod);
Iterator<Period> it = set.iterator();
while (it.hasNext()) {
Period period = it.next();
//System.out.println(m_periods[i].getStart() + " - " + m_periods[i].getEnd());
if (period.contains(date)) {
list.add( period );
}
}
return list;
}
public int getSize() {
Assert.notNull(m_periods,"Componenet not setup!");
return m_periods.size();
}
public Period[] getAllPeriods() {
Period[] sortedPriods = m_periods.toArray( Period.PERIOD_ARRAY);
return sortedPriods;
}
public Object getElementAt(int index) {
Assert.notNull(m_periods,"Componenet not setup!");
Iterator<Period> it = m_periods.iterator();
for (int i=0;it.hasNext();i++) {
Object obj = it.next();
if (i == index)
return obj;
}
return null;
}
}
| 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.facade.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import org.rapla.ConnectInfo;
import org.rapla.components.util.Command;
import org.rapla.components.util.CommandScheduler;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.components.util.undo.CommandHistory;
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.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.entities.configuration.internal.RaplaMapImpl;
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.RepeatingType;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.RaplaObjectAnnotations;
import org.rapla.entities.domain.ResourceAnnotations;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.domain.internal.AppointmentImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.entities.dynamictype.internal.DynamicTypeImpl;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.entities.internal.ModifiableTimestamp;
import org.rapla.entities.internal.UserImpl;
import org.rapla.entities.storage.ParentEntity;
import org.rapla.entities.storage.internal.SimpleEntity;
import org.rapla.facade.AllocationChangeEvent;
import org.rapla.facade.AllocationChangeListener;
import org.rapla.facade.CalendarOptions;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.Conflict;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.facade.PeriodModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.facade.UpdateErrorListener;
import org.rapla.framework.Configuration;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.internal.ContextTools;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.RaplaSecurityException;
import org.rapla.storage.StorageOperator;
import org.rapla.storage.StorageUpdateListener;
import org.rapla.storage.UpdateResult;
/**
* This is the default implementation of the necessary Client-Facade to the
* DB-Subsystem.
* <p>
* Sample configuration 1:
*
* <pre>
* <facade id="facade">
* <store>file</store>
* </facade>
* </pre>
*
* </p>
* <p>
* The store entry contains the id of a storage-component. Storage-Components
* are all components that implement the {@link StorageOperator} interface.
* </p>
*/
public class FacadeImpl implements ClientFacade,StorageUpdateListener {
protected CommandScheduler notifyQueue;
private String workingUserId = null;
private StorageOperator operator;
private Vector<ModificationListener> modificatonListenerList = new Vector<ModificationListener>();
private Vector<AllocationChangeListener> allocationListenerList = new Vector<AllocationChangeListener>();
private Vector<UpdateErrorListener> errorListenerList = new Vector<UpdateErrorListener>();
private I18nBundle i18n;
private PeriodModelImpl periodModel;
// private ConflictFinder conflictFinder;
private Vector<ModificationListener> directListenerList = new Vector<ModificationListener>();
public CommandHistory commandHistory = new CommandHistory();
Locale locale;
RaplaContext context;
Logger logger;
String templateName;
public FacadeImpl(RaplaContext context, Configuration config, Logger logger) throws RaplaException {
this( context, getOperator(context, config, logger), logger);
}
private static StorageOperator getOperator(RaplaContext context, Configuration config, Logger logger)
throws RaplaContextException {
String configEntry = config.getChild("store").getValue("*");
String storeSelector = ContextTools.resolveContext(configEntry, context ).toString();
logger.info("Using rapladatasource " +storeSelector);
try {
Container container = context.lookup(Container.class);
StorageOperator operator = container.lookup(StorageOperator.class, storeSelector);
return operator;
}
catch (RaplaContextException ex) {
throw new RaplaContextException("Store "
+ storeSelector
+ " is not found (or could not be initialized)", ex);
}
}
public static FacadeImpl create(RaplaContext context, StorageOperator operator, Logger logger) throws RaplaException
{
return new FacadeImpl(context, operator, logger);
}
private FacadeImpl(RaplaContext context, StorageOperator operator, Logger logger) throws RaplaException {
this.operator = operator;
this.logger = logger;
i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
locale = context.lookup(RaplaLocale.class).getLocale();
this.context = context;
operator.addStorageUpdateListener(this);
notifyQueue = context.lookup( CommandScheduler.class );
//org.rapla.components.util.CommandQueue.createCommandQueue();
}
public Logger getLogger()
{
return logger;
}
public StorageOperator getOperator() {
return operator;
}
// Implementation of StorageUpdateListener.
/**
* This method is called by the storage-operator, when stored objects have
* changed.
*
* <strong>Caution:</strong> You must not lock the storage operator during
* processing of this call, because it could have been locked by the store
* method, causing deadlocks
*/
public void objectsUpdated(UpdateResult evt) {
if (getLogger().isDebugEnabled())
getLogger().debug("Objects updated");
cacheValidString = null;
cachedReservations = null;
if (workingUserId != null)
{
if ( evt.isModified( User.TYPE))
{
if (operator.tryResolve( workingUserId, User.class) == null)
{
EntityNotFoundException ex = new EntityNotFoundException("User for id " + workingUserId + " not found. Maybe it was removed.");
fireUpdateError(ex);
}
}
}
fireUpdateEvent(evt);
}
public void updateError(RaplaException ex) {
getLogger().error(ex.getMessage(), ex);
fireUpdateError(ex);
}
public void storageDisconnected(String message) {
fireStorageDisconnected(message);
}
/******************************
* Update-module *
******************************/
public boolean isClientForServer() {
return operator.supportsActiveMonitoring();
}
public void refresh() throws RaplaException {
if (operator.supportsActiveMonitoring()) {
operator.refresh();
}
}
void setName(MultiLanguageName name, String to)
{
String currentLang = i18n.getLang();
name.setName("en", to);
try
{
// try to find a translation in the current locale
String translation = i18n.getString( to);
name.setName(currentLang, translation);
}
catch (Exception ex)
{
// go on, if non is found
}
}
public void addModificationListener(ModificationListener listener) {
modificatonListenerList.add(listener);
}
public void addDirectModificationListener(ModificationListener listener)
{
directListenerList.add(listener);
}
public void removeModificationListener(ModificationListener listener) {
directListenerList.remove(listener);
modificatonListenerList.remove(listener);
}
private Collection<ModificationListener> getModificationListeners() {
if (modificatonListenerList.size() == 0)
{
return Collections.emptyList();
}
synchronized (this) {
Collection<ModificationListener> list = new ArrayList<ModificationListener>(3);
if (periodModel != null) {
list.add(periodModel);
}
Iterator<ModificationListener> it = modificatonListenerList.iterator();
while (it.hasNext()) {
ModificationListener listener = it.next();
list.add(listener);
}
return list;
}
}
public void addAllocationChangedListener(AllocationChangeListener listener) {
if ( operator.supportsActiveMonitoring())
{
throw new IllegalStateException("You can't add an allocation listener to a client facade because reservation objects are not updated");
}
allocationListenerList.add(listener);
}
public void removeAllocationChangedListener(AllocationChangeListener listener) {
allocationListenerList.remove(listener);
}
private Collection<AllocationChangeListener> getAllocationChangeListeners() {
if (allocationListenerList.size() == 0)
{
return Collections.emptyList();
}
synchronized (this) {
Collection<AllocationChangeListener> list = new ArrayList<AllocationChangeListener>( 3);
Iterator<AllocationChangeListener> it = allocationListenerList.iterator();
while (it.hasNext()) {
AllocationChangeListener listener = it.next();
list.add(listener);
}
return list;
}
}
public AllocationChangeEvent[] createAllocationChangeEvents(UpdateResult evt) {
Logger logger = getLogger().getChildLogger("trigger.allocation");
List<AllocationChangeEvent> triggerEvents = AllocationChangeFinder.getTriggerEvents(evt, logger);
return triggerEvents.toArray( new AllocationChangeEvent[0]);
}
public void addUpdateErrorListener(UpdateErrorListener listener) {
errorListenerList.add(listener);
}
public void removeUpdateErrorListener(UpdateErrorListener listener) {
errorListenerList.remove(listener);
}
public UpdateErrorListener[] getUpdateErrorListeners() {
return errorListenerList.toArray(new UpdateErrorListener[] {});
}
protected void fireUpdateError(RaplaException ex) {
UpdateErrorListener[] listeners = getUpdateErrorListeners();
for (int i = 0; i < listeners.length; i++) {
listeners[i].updateError(ex);
}
}
protected void fireStorageDisconnected(String message) {
UpdateErrorListener[] listeners = getUpdateErrorListeners();
for (int i = 0; i < listeners.length; i++) {
listeners[i].disconnected(message);
}
}
final class UpdateCommandAllocation implements Runnable, Command {
Collection<AllocationChangeListener> listenerList;
AllocationChangeEvent[] allocationChangeEvents;
public UpdateCommandAllocation(Collection<AllocationChangeListener> allocationChangeListeners, UpdateResult evt) {
this.listenerList= new ArrayList<AllocationChangeListener>(allocationChangeListeners);
if ( allocationChangeListeners.size() > 0)
{
allocationChangeEvents = createAllocationChangeEvents(evt);
}
}
public void execute() {
run();
}
public void run() {
for (AllocationChangeListener listener: listenerList)
{
try {
if (isAborting())
return;
if (getLogger().isDebugEnabled())
getLogger().debug("Notifying " + listener);
if (allocationChangeEvents.length > 0) {
listener.changed(allocationChangeEvents);
}
} catch (Exception ex) {
getLogger().error("update-exception", ex);
}
}
}
}
final class UpdateCommandModification implements Runnable, Command {
Collection<ModificationListener> listenerList;
ModificationEvent modificationEvent;
public UpdateCommandModification(Collection<ModificationListener> modificationListeners, UpdateResult evt) {
this.listenerList = new ArrayList<ModificationListener>(modificationListeners);
this.modificationEvent = evt;
}
public void execute() {
run();
}
public void run() {
for (ModificationListener listener: listenerList) {
try {
if (isAborting())
return;
if (getLogger().isDebugEnabled())
getLogger().debug("Notifying " + listener);
listener.dataChanged(modificationEvent);
} catch (Exception ex) {
getLogger().error("update-exception", ex);
}
}
}
} /**
* fires update event asynchronous.
*/
protected void fireUpdateEvent(UpdateResult evt) {
if (periodModel != null) {
try {
periodModel.update();
} catch (RaplaException e) {
getLogger().error("Can't update Period Model", e);
}
}
{
Collection<ModificationListener> modificationListeners = directListenerList;
if (modificationListeners.size() > 0 ) {
new UpdateCommandModification(modificationListeners,evt).execute();
}
}
{
Collection<ModificationListener> modificationListeners = getModificationListeners();
if (modificationListeners.size() > 0 ) {
notifyQueue.schedule(new UpdateCommandModification(modificationListeners, evt),0);
}
Collection<AllocationChangeListener> allocationChangeListeners = getAllocationChangeListeners();
if (allocationChangeListeners.size() > 0) {
notifyQueue.schedule(new UpdateCommandAllocation(allocationChangeListeners, evt),0);
}
}
}
/******************************
* Query-module *
******************************/
private Collection<Allocatable> getVisibleAllocatables( ClassificationFilter[] filters) throws RaplaException {
User workingUser = getWorkingUser();
Collection<Allocatable> objects = operator.getAllocatables(filters);
Iterator<Allocatable> it = objects.iterator();
while (it.hasNext()) {
Allocatable allocatable = it.next();
if (workingUser == null || workingUser.isAdmin())
continue;
if (!allocatable.canRead(workingUser))
it.remove();
}
return objects;
}
int queryCounter = 0;
private Collection<Reservation> getVisibleReservations(User user, Allocatable[] allocatables, Date start, Date end, ClassificationFilter[] reservationFilters)
throws RaplaException {
if ( templateName != null)
{
Collection<Reservation> reservations = getTemplateReservations( templateName);
return reservations;
}
List<Allocatable> allocList;
if (allocatables != null)
{
if ( allocatables.length == 0 )
{
return Collections.emptyList();
}
allocList = Arrays.asList( allocatables);
}
else
{
allocList = Collections.emptyList();
}
Collection<Reservation> reservations =operator.getReservations(user,allocList, start, end, reservationFilters,null);
// Category can_see = getUserGroupsCategory().getCategory(
// Permission.GROUP_CAN_READ_EVENTS_FROM_OTHERS);
if (getLogger().isDebugEnabled())
{
getLogger().debug((++queryCounter)+". Query reservation called user=" + user + " start=" +start + " end=" + end);
}
return reservations;
}
public Allocatable[] getAllocatables() throws RaplaException {
return getAllocatables(null);
}
public Allocatable[] getAllocatables(ClassificationFilter[] filters) throws RaplaException {
return getVisibleAllocatables(filters).toArray( Allocatable.ALLOCATABLE_ARRAY);
}
public boolean canExchangeAllocatables(Reservation reservation) {
try {
Allocatable[] all = getAllocatables(null);
User user = getUser();
for (int i = 0; i < all.length; i++) {
if (all[i].canModify(user)) {
return true;
}
}
} catch (RaplaException ex) {
}
return false;
}
public Preferences getPreferences() throws RaplaException {
return getPreferences(getUser());
}
public Preferences getSystemPreferences() throws RaplaException
{
return operator.getPreferences(null, true);
}
public Preferences getPreferences(User user) throws RaplaException {
return operator.getPreferences(user, true);
}
public Preferences getPreferences(User user,boolean createIfNotNull) throws RaplaException {
return operator.getPreferences(user, createIfNotNull);
}
public Category getSuperCategory() {
return operator.getSuperCategory();
}
public Category getUserGroupsCategory() throws RaplaException {
Category userGroups = getSuperCategory().getCategory(
Permission.GROUP_CATEGORY_KEY);
if (userGroups == null) {
throw new RaplaException("No category '"+ Permission.GROUP_CATEGORY_KEY + "' available");
}
return userGroups;
}
public Collection<String> getTemplateNames() throws RaplaException
{
return operator.getTemplateNames();
}
public Collection<Reservation> getTemplateReservations(String name) throws RaplaException
{
User user = null;
Collection<Allocatable> allocList = null;
Date start = null;
Date end = null;
Map<String,String> annotationQuery = new LinkedHashMap<String,String>();
annotationQuery.put(RaplaObjectAnnotations.KEY_TEMPLATE, name);
Collection<Reservation> result = operator.getReservations(user,allocList, start, end,null, annotationQuery);
return result;
}
public Reservation[] getReservations(User user, Date start, Date end,ClassificationFilter[] filters) throws RaplaException {
return getVisibleReservations(user, null,start, end, filters).toArray(Reservation.RESERVATION_ARRAY);
}
private String cacheValidString;
private Reservation[] cachedReservations;
public Reservation[] getReservations(Allocatable[] allocatables,Date start, Date end) throws RaplaException {
String cacheKey = createCacheKey( allocatables, start, end);
if ( cacheValidString != null && cacheValidString.equals( cacheKey) && cachedReservations != null)
{
return cachedReservations;
}
Reservation[] reservationsForAllocatable = getReservationsForAllocatable(allocatables, start, end, null);
cachedReservations = reservationsForAllocatable;
cacheValidString = cacheKey;
return reservationsForAllocatable;
}
private String createCacheKey(Allocatable[] allocatables, Date start,
Date end) {
StringBuilder buf = new StringBuilder();
if ( allocatables != null)
{
for ( Allocatable alloc:allocatables)
{
buf.append(alloc.getId());
buf.append(";");
}
}
else
{
buf.append("all_reservations;");
}
if ( start != null)
{
buf.append(start.getTime() + ";");
}
if ( end != null)
{
buf.append(end.getTime() + ";");
}
return buf.toString();
}
public List<Reservation> getReservations(Collection<Conflict> conflicts) throws RaplaException
{
Collection<String> ids = new ArrayList<String>();
for ( Conflict conflict:conflicts)
{
ids.add(conflict.getReservation1());
ids.add(conflict.getReservation2());
}
Collection<Entity> values = operator.getFromId( ids, true).values();
@SuppressWarnings("unchecked")
ArrayList<Reservation> converted = new ArrayList(values);
return converted;
}
public Reservation[] getReservationsForAllocatable(Allocatable[] allocatables, Date start, Date end,ClassificationFilter[] reservationFilters) throws RaplaException {
//System.gc();
Collection<Reservation> reservations = getVisibleReservations(null, allocatables,start, end, reservationFilters);
return reservations.toArray(Reservation.RESERVATION_ARRAY);
}
public Period[] getPeriods() throws RaplaException {
Period[] result = getPeriodModel().getAllPeriods();
return result;
}
public PeriodModel getPeriodModel() throws RaplaException {
if (periodModel == null) {
periodModel = new PeriodModelImpl(this);
}
return periodModel;
}
public DynamicType[] getDynamicTypes(String classificationType)
throws RaplaException {
ArrayList<DynamicType> result = new ArrayList<DynamicType>();
Collection<DynamicType> collection = operator.getDynamicTypes();
for (DynamicType type: collection) {
String classificationTypeAnno = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
// ignore internal types for backward compatibility
if ((( DynamicTypeImpl)type).isInternal())
{
continue;
}
if ( classificationType == null || classificationType.equals(classificationTypeAnno)) {
result.add(type);
}
}
return result.toArray(DynamicType.DYNAMICTYPE_ARRAY);
}
public DynamicType getDynamicType(String elementKey) throws RaplaException {
DynamicType dynamicType = operator.getDynamicType(elementKey);
if ( dynamicType == null)
{
throw new EntityNotFoundException("No dynamictype with elementKey "
+ elementKey);
}
return dynamicType;
}
public User[] getUsers() throws RaplaException {
User[] result = operator.getUsers().toArray(User.USER_ARRAY);
return result;
}
public User getUser(String username) throws RaplaException {
User user = operator.getUser(username);
if (user == null)
throw new EntityNotFoundException("No User with username " + username);
return user;
}
public Conflict[] getConflicts(Reservation reservation) throws RaplaException {
Date today = operator.today();
if ( RaplaComponent.isTemplate( reservation))
{
return Conflict.CONFLICT_ARRAY;
}
Collection<Allocatable> allocatables = Arrays.asList(reservation.getAllocatables());
Collection<Appointment> appointments = Arrays.asList(reservation.getAppointments());
Collection<Reservation> ignoreList = Collections.singleton( reservation );
Map<Allocatable, Map<Appointment, Collection<Appointment>>> allocatableBindings = operator.getAllAllocatableBindings( allocatables, appointments, ignoreList);
ArrayList<Conflict> conflictList = new ArrayList<Conflict>();
for ( Map.Entry<Allocatable, Map<Appointment, Collection<Appointment>>> entry: allocatableBindings.entrySet() )
{
Allocatable allocatable= entry.getKey();
String annotation = allocatable.getAnnotation( ResourceAnnotations.KEY_CONFLICT_CREATION);
boolean holdBackConflicts = annotation != null && annotation.equals( ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE);
if ( holdBackConflicts)
{
continue;
}
Map<Appointment, Collection<Appointment>> appointmentMap = entry.getValue();
for (Map.Entry<Appointment, Collection<Appointment>> appointmentEntry: appointmentMap.entrySet())
{
Appointment appointment = appointmentEntry.getKey();
if ( reservation.hasAllocated( allocatable, appointment))
{
Collection<Appointment> conflictionAppointments = appointmentEntry.getValue();
if ( conflictionAppointments != null)
{
for ( Appointment conflictingAppointment: conflictionAppointments)
{
Appointment appointment1 = appointment;
Appointment appointment2 = conflictingAppointment;
if (ConflictImpl.isConflict(appointment1, appointment2, today))
{
ConflictImpl.addConflicts(conflictList, allocatable,appointment1, appointment2, today);
}
}
}
}
}
}
return conflictList.toArray(Conflict.CONFLICT_ARRAY);
}
public Conflict[] getConflicts() throws RaplaException {
final User user;
User workingUser = getWorkingUser();
if ( workingUser != null && !workingUser.isAdmin())
{
user = workingUser;
}
else
{
user = null;
}
Collection<Conflict> conflicts = operator.getConflicts( user);
if (getLogger().isDebugEnabled())
{
getLogger().debug("getConflits called. Returned " + conflicts.size() + " conflicts.");
}
return conflicts.toArray(new Conflict[] {});
}
public static boolean hasPermissionToAllocate( User user, Appointment appointment,Allocatable allocatable, Reservation original, Date today) {
if ( user.isAdmin()) {
return true;
}
Date start = appointment.getStart();
Date end = appointment.getMaxEnd();
Permission[] permissions = allocatable.getPermissions();
for ( int i = 0; i < permissions.length; i++)
{
Permission p = permissions[i];
int accessLevel = p.getAccessLevel();
if ( (!p.affectsUser( user )) || accessLevel< Permission.READ) {
continue;
}
if ( accessLevel == Permission.ADMIN)
{
// user has the right to allocate
return true;
}
if ( accessLevel >= Permission.ALLOCATE && p.covers( start, end, today ) )
{
return true;
}
if ( original == null )
{
continue;
}
// We must check if the changes of the existing appointment
// are in a permisable timeframe (That should be allowed)
// 1. check if appointment is old,
// 2. check if allocatable was already assigned to the appointment
Appointment originalAppointment = original.findAppointment( appointment );
if ( originalAppointment == null || !original.hasAllocated( allocatable, originalAppointment))
{
continue;
}
// 3. check if the appointment has changed during
// that time
if ( appointment.matches( originalAppointment ) )
{
return true;
}
if ( accessLevel >= Permission.ALLOCATE )
{
Date maxTime = DateTools.max(appointment.getMaxEnd(), originalAppointment.getMaxEnd());
if (maxTime == null)
{
maxTime = DateTools.addYears( today, 4);
}
Date minChange = appointment.getFirstDifference( originalAppointment, maxTime );
Date maxChange = appointment.getLastDifference( originalAppointment, maxTime );
//System.out.println ( "minChange: " + minChange + ", maxChange: " + maxChange );
if ( p.covers( minChange, maxChange, today ) ) {
return true;
}
}
}
return false;
}
public boolean canEditTemplats(User user) {
return hasGroupRights(user, Permission.GROUP_CAN_EDIT_TEMPLATES);
}
public boolean canReadReservationsFromOthers(User user) {
return hasGroupRights(user, Permission.GROUP_CAN_READ_EVENTS_FROM_OTHERS);
}
protected boolean hasGroupRights(User user, String groupKey) {
if (user == null) {
User workingUser;
try {
workingUser = getWorkingUser();
} catch (EntityNotFoundException e) {
return false;
}
return workingUser == null || workingUser.isAdmin();
}
if (user.isAdmin()) {
return true;
}
try {
Category group = getUserGroupsCategory().getCategory( groupKey);
if ( group == null)
{
return true;
}
return user.belongsTo(group);
} catch (Exception ex) {
getLogger().error("Can't get permissions!", ex);
}
return false;
}
public boolean canCreateReservations(User user) {
return hasGroupRights(user, Permission.GROUP_CAN_CREATE_EVENTS);
}
@Deprecated
public Allocatable[] getAllocatableBindings(Appointment forAppointment) throws RaplaException {
List<Allocatable> allocatableList = Arrays.asList(getAllocatables());
List<Allocatable> result = new ArrayList<Allocatable>();
Map<Allocatable, Collection<Appointment>> bindings = getAllocatableBindings( allocatableList, Collections.singletonList(forAppointment));
for (Map.Entry<Allocatable, Collection<Appointment>> entry: bindings.entrySet())
{
Collection<Appointment> appointments = entry.getValue();
if ( appointments.contains( forAppointment))
{
Allocatable alloc = entry.getKey();
result.add( alloc);
}
}
return result.toArray(Allocatable.ALLOCATABLE_ARRAY);
}
public Map<Allocatable,Collection<Appointment>> getAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments) throws RaplaException {
Collection<Reservation> ignoreList = new HashSet<Reservation>();
if ( appointments != null)
{
for (Appointment app: appointments)
{
Reservation r = app.getReservation();
if ( r != null)
{
ignoreList.add( r );
}
}
}
return operator.getFirstAllocatableBindings(allocatables, appointments, ignoreList);
}
public Date getNextAllocatableDate(Collection<Allocatable> allocatables, Appointment appointment, CalendarOptions options) throws RaplaException {
int worktimeStartMinutes = options.getWorktimeStartMinutes();
int worktimeEndMinutes = options.getWorktimeEndMinutes();
Integer[] excludeDays = options.getExcludeDays().toArray( new Integer[] {});
int rowsPerHour = options.getRowsPerHour();
Reservation reservation = appointment.getReservation();
Collection<Reservation> ignoreList;
if (reservation != null)
{
ignoreList = Collections.singleton( reservation);
}
else
{
ignoreList = Collections.emptyList();
}
return operator.getNextAllocatableDate(allocatables, appointment,ignoreList, worktimeStartMinutes, worktimeEndMinutes, excludeDays, rowsPerHour);
}
/******************************
* Login - Module *
******************************/
public User getUser() throws RaplaException {
if (this.workingUserId == null) {
throw new RaplaException("no user loged in");
}
return operator.resolve( workingUserId, User.class);
}
/** unlike getUser this can be null if working user not set*/
private User getWorkingUser() throws EntityNotFoundException {
if ( workingUserId == null)
{
return null;
}
return operator.resolve( workingUserId, User.class);
}
public boolean login(String username, char[] password)
throws RaplaException {
return login( new ConnectInfo(username, password));
}
public boolean login(ConnectInfo connectInfo)
throws RaplaException {
User user = null;
try {
if (!operator.isConnected()) {
user = operator.connect( connectInfo);
}
} catch (RaplaSecurityException ex) {
return false;
} finally {
// Clear password
// for (int i = 0; i < password.length; i++)
// password[i] = 0;
}
if ( user == null)
{
String username = connectInfo.getUsername();
if ( connectInfo.getConnectAs() != null)
{
username = connectInfo.getConnectAs();
}
user = operator.getUser(username);
}
if (user != null) {
this.workingUserId = user.getId();
getLogger().info("Login " + user.getUsername());
return true;
} else {
return false;
}
}
public boolean canChangePassword() {
try {
return operator.canChangePassword();
} catch (RaplaException e) {
return false;
}
}
public boolean isSessionActive() {
return (this.workingUserId != null);
}
private boolean aborting;
public void logout() throws RaplaException {
if (this.workingUserId == null )
return;
getLogger().info("Logout " + workingUserId);
aborting = true;
try
{
// now we can add it again
this.workingUserId = null;
// we need to remove the storage update listener, because the disconnect
// would trigger a restart otherwise
operator.removeStorageUpdateListener(this);
operator.disconnect();
operator.addStorageUpdateListener(this);
}
finally
{
aborting = false;
}
}
private boolean isAborting() {
return aborting || !operator.isConnected();
}
public void changePassword(User user, char[] oldPassword, char[] newPassword) throws RaplaException {
operator.changePassword( user, oldPassword, newPassword);
}
/******************************
* Modification-module *
******************************/
public String getTemplateName()
{
if ( templateName != null)
{
return templateName;
}
return null;
}
public void setTemplateName(String templateName)
{
this.templateName = templateName;
cachedReservations = null;
cacheValidString = null;
User workingUser;
try {
workingUser = getWorkingUser();
} catch (EntityNotFoundException e) {
// system user as change initiator won't hurt
workingUser = null;
getLogger().error(e.getMessage(),e);
}
UpdateResult updateResult = new UpdateResult( workingUser);
updateResult.setSwitchTemplateMode(true);
updateResult.setInvalidateInterval( new TimeInterval(null, null));
fireUpdateEvent( updateResult);
}
@SuppressWarnings("unchecked")
public <T> RaplaMap<T> newRaplaMap(Map<String, T> map) {
return (RaplaMap<T>) new RaplaMapImpl(map);
}
@SuppressWarnings("unchecked")
public <T> RaplaMap<T> newRaplaMap(Collection<T> col) {
return (RaplaMap<T>) new RaplaMapImpl(col);
}
public Appointment newAppointment(Date startDate, Date endDate) throws RaplaException {
User user = getUser();
return newAppointment(startDate, endDate, user);
}
public Reservation newReservation() throws RaplaException
{
Classification classification = getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)[0].newClassification();
return newReservation( classification );
}
public Reservation newReservation(Classification classification) throws RaplaException
{
User user = getUser();
return newReservation( classification,user );
}
public Reservation newReservation(Classification classification,User user) throws RaplaException
{
if (!canCreateReservations( user))
{
throw new RaplaException("User not allowed to create events");
}
Date now = operator.getCurrentTimestamp();
ReservationImpl reservation = new ReservationImpl(now ,now );
if ( templateName != null )
{
reservation.setAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE, templateName);
}
reservation.setClassification(classification);
setNew(reservation, user);
return reservation;
}
public Allocatable newAllocatable( Classification classification) throws RaplaException
{
return newAllocatable(classification, getUser());
}
public Allocatable newAllocatable( Classification classification, User user) throws RaplaException {
Date now = operator.getCurrentTimestamp();
AllocatableImpl allocatable = new AllocatableImpl(now, now);
DynamicTypeImpl type = (DynamicTypeImpl)classification.getType();
if ( type.getElementKey().equals(StorageOperator.PERIOD_TYPE))
{
Permission newPermission =allocatable.newPermission();
newPermission.setAccessLevel( Permission.READ);
allocatable.addPermission(newPermission);
}
if ( !type.isInternal())
{
allocatable.addPermission(allocatable.newPermission());
if (user != null && !user.isAdmin()) {
Permission permission = allocatable.newPermission();
permission.setUser(user);
permission.setAccessLevel(Permission.ADMIN);
allocatable.addPermission(permission);
}
}
allocatable.setClassification(classification);
setNew(allocatable, user);
return allocatable;
}
private Classification newClassification(String classificationType)
throws RaplaException {
DynamicType[] dynamicTypes = getDynamicTypes(classificationType);
DynamicType dynamicType = dynamicTypes[0];
Classification classification = dynamicType.newClassification();
return classification;
}
public Appointment newAppointment(Date startDate, Date endDate, User user) throws RaplaException {
AppointmentImpl appointment = new AppointmentImpl(startDate, endDate);
setNew(appointment, user);
return appointment;
}
public Appointment newAppointment(Date startDate, Date endDate, RepeatingType repeatingType, int repeatingDuration) throws RaplaException {
AppointmentImpl appointment = new AppointmentImpl(startDate, endDate, repeatingType, repeatingDuration);
User user = getUser();
setNew(appointment, user);
return appointment;
}
public Allocatable newResource() throws RaplaException {
User user = getUser();
Classification classification = newClassification(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE);
return newAllocatable(classification, user);
}
public Allocatable newPerson() throws RaplaException {
User user = getUser();
Classification classification = newClassification(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON);
return newAllocatable(classification, user);
}
public Allocatable newPeriod() throws RaplaException {
DynamicType periodType = getDynamicType(StorageOperator.PERIOD_TYPE);
Classification classification = periodType.newClassification();
classification.setValue("name", "");
Date today = today();
classification.setValue("start", DateTools.cutDate(today));
classification.setValue("end", DateTools.addDays(DateTools.fillDate(today),7));
Allocatable period = newAllocatable(classification);
setNew(period);
return period;
}
public Date today() {
return operator.today();
}
public Category newCategory() throws RaplaException {
Date now = operator.getCurrentTimestamp();
CategoryImpl category = new CategoryImpl(now, now);
setNew(category);
return category;
}
private Attribute createStringAttribute(String key, String name) throws RaplaException {
Attribute attribute = newAttribute(AttributeType.STRING);
attribute.setKey(key);
setName(attribute.getName(), name);
return attribute;
}
public DynamicType newDynamicType(String classificationType) throws RaplaException {
Date now = operator.getCurrentTimestamp();
DynamicTypeImpl dynamicType = new DynamicTypeImpl(now,now);
dynamicType.setAnnotation("classification-type", classificationType);
dynamicType.setKey(createDynamicTypeKey(classificationType));
setNew(dynamicType);
if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE)) {
dynamicType.addAttribute(createStringAttribute("name", "name"));
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}");
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS,"automatic");
} else if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)) {
dynamicType.addAttribute(createStringAttribute("name","eventname"));
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}");
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS, null);
} else if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON)) {
dynamicType.addAttribute(createStringAttribute("surname", "surname"));
dynamicType.addAttribute(createStringAttribute("firstname", "firstname"));
dynamicType.addAttribute(createStringAttribute("email", "email"));
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT, "{surname} {firstname}");
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS, null);
}
return dynamicType;
}
public Attribute newAttribute(AttributeType attributeType) throws RaplaException {
AttributeImpl attribute = new AttributeImpl(attributeType);
setNew(attribute);
return attribute;
}
public User newUser() throws RaplaException {
Date now = operator.getCurrentTimestamp();
UserImpl user = new UserImpl( now, now);
setNew(user);
String[] defaultGroups = new String[] {Permission.GROUP_MODIFY_PREFERENCES_KEY,Permission.GROUP_CAN_READ_EVENTS_FROM_OTHERS,Permission.GROUP_CAN_CREATE_EVENTS};
for ( String groupKey: defaultGroups)
{
Category group = getUserGroupsCategory().getCategory( groupKey);
if (group != null)
{
user.addGroup(group);
}
}
return user;
}
public CalendarSelectionModel newCalendarModel(User user) throws RaplaException{
User workingUser = getWorkingUser();
if ( workingUser != null && !workingUser.isAdmin() && !user.equals(workingUser))
{
throw new RaplaException("Can't create a calendar model for a different user.");
}
return new CalendarModelImpl( context, user, this);
}
private String createDynamicTypeKey(String classificationType)
throws RaplaException {
DynamicType[] dts = getDynamicTypes(classificationType);
int max = 1;
for (int i = 0; i < dts.length; i++) {
String key = dts[i].getKey();
int len = classificationType.length();
if (key.indexOf(classificationType) >= 0 && key.length() > len && Character.isDigit(key.charAt(len))) {
try {
int value = Integer.valueOf(key.substring(len)).intValue();
if (value >= max)
max = value + 1;
} catch (NumberFormatException ex) {
}
}
}
return classificationType + (max);
}
private void setNew(Entity entity) throws RaplaException {
setNew(entity, null);
}
private void setNew(Entity entity,User user) throws RaplaException {
setNew(Collections.singleton(entity), entity.getRaplaType(), user);
}
private <T extends Entity> void setNew(Collection<T> entities, RaplaType raplaType,User user)
throws RaplaException {
for ( T entity: entities)
{
if ((entity instanceof ParentEntity) && (((ParentEntity)entity).getSubEntities().iterator().hasNext()) && ! (entity instanceof Reservation) ) {
throw new RaplaException("The current Rapla Version doesnt support cloning entities with sub-entities. (Except reservations)");
}
}
String[] ids = operator.createIdentifier(raplaType, entities.size());
int i = 0;
for ( T uncasted: entities)
{
String id = ids[i++];
SimpleEntity entity = (SimpleEntity) uncasted;
entity.setId(id);
entity.setResolver(operator);
if (getLogger() != null && getLogger().isDebugEnabled()) {
getLogger().debug("new " + entity.getId());
}
if (entity instanceof Reservation) {
if (user == null)
throw new RaplaException("The reservation " + entity + " needs an owner but user specified is null ");
((Ownable) entity).setOwner(user);
}
}
}
public void checkReservation(Reservation reservation) throws RaplaException {
if (reservation.getAppointments().length == 0) {
throw new RaplaException(i18n.getString("error.no_appointment"));
}
Locale locale = i18n.getLocale();
String name = reservation.getName(locale);
if (name.trim().length() == 0) {
throw new RaplaException(i18n.getString("error.no_reservation_name"));
}
}
public <T extends Entity> T edit(T obj) throws RaplaException {
if (obj == null)
throw new NullPointerException("Can't edit null objects");
Set<T> singleton = Collections.singleton( obj);
Collection<T> edit = edit(singleton);
T result = edit.iterator().next();
return result;
}
public <T extends Entity> Collection<T> edit(Collection<T> list) throws RaplaException
{
List<Entity> castedList = new ArrayList<Entity>();
for ( Entity entity:list)
{
castedList.add( entity);
}
User workingUser = getWorkingUser();
Collection<Entity> result = operator.editObjects(castedList, workingUser);
List<T> castedResult = new ArrayList<T>();
for ( Entity entity:result)
{
@SuppressWarnings("unchecked")
T casted = (T) entity;
castedResult.add( casted);
}
return castedResult;
}
@SuppressWarnings("unchecked")
private <T extends Entity> T _clone(T obj) throws RaplaException {
T deepClone = (T) obj.clone();
T clone = deepClone;
RaplaType raplaType = clone.getRaplaType();
if (raplaType == Appointment.TYPE) {
// Hack for 1.6 compiler compatibility
Object temp = clone;
((AppointmentImpl) temp).removeParent();
}
if (raplaType == Category.TYPE) {
// Hack for 1.6 compiler compatibility
Object temp = clone;
((CategoryImpl) temp).removeParent();
}
User workingUser = getWorkingUser();
setNew((Entity) clone, workingUser);
return clone;
}
@SuppressWarnings("unchecked")
public <T extends Entity> T clone(T obj) throws RaplaException {
if (obj == null)
throw new NullPointerException("Can't clone null objects");
User workingUser = getWorkingUser();
T result;
RaplaType<T> raplaType = obj.getRaplaType();
// Hack for 1.6 compiler compatibility
if (((Object)raplaType) == Appointment.TYPE ){
T _clone = _clone(obj);
// Hack for 1.6 compiler compatibility
Object temp = _clone;
((AppointmentImpl) temp).setParent(null);
result = _clone;
// Hack for 1.6 compiler compatibility
} else if (((Object)raplaType) == Reservation.TYPE) {
// Hack for 1.6 compiler compatibility
Object temp = obj;
Reservation clonedReservation = cloneReservation((Reservation) temp);
// Hack for 1.6 compiler compatibility
Reservation r = clonedReservation;
if ( workingUser != null)
{
r.setOwner( workingUser );
}
if ( templateName != null )
{
r.setAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE, templateName);
}
else
{
String originalTemplate = r.getAnnotation( RaplaObjectAnnotations.KEY_TEMPLATE);
if (originalTemplate != null)
{
r.setAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE_COPYOF, originalTemplate);
}
r.setAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE, null);
}
// Hack for 1.6 compiler compatibility
Object r2 = r;
result = (T)r2;
}
else
{
try {
T _clone = _clone(obj);
result = _clone;
} catch (ClassCastException ex) {
throw new RaplaException("This entity can't be cloned ", ex);
} finally {
}
}
if (result instanceof ModifiableTimestamp) {
Date now = operator.getCurrentTimestamp();
((ModifiableTimestamp) result).setLastChanged(now);
if (workingUser != null) {
((ModifiableTimestamp) result).setLastChangedBy(workingUser);
}
}
return result;
}
/** Clones a reservation and sets new ids for all appointments and the reservation itsel
*/
private Reservation cloneReservation(Reservation obj) throws RaplaException {
User workingUser = getWorkingUser();
// first we do a reservation deep clone
Reservation clone = obj.clone();
HashMap<Allocatable, Appointment[]> restrictions = new HashMap<Allocatable, Appointment[]>();
Allocatable[] allocatables = clone.getAllocatables();
for (Allocatable allocatable:allocatables) {
restrictions.put(allocatable, clone.getRestriction(allocatable));
}
// then we set new ids for all appointments
Appointment[] clonedAppointments = clone.getAppointments();
setNew(Arrays.asList(clonedAppointments),Appointment.TYPE, workingUser);
for (Appointment clonedAppointment:clonedAppointments) {
clone.removeAppointment(clonedAppointment);
}
// and now a new id for the reservation
setNew( clone, workingUser);
for (Appointment clonedAppointment:clonedAppointments) {
clone.addAppointment(clonedAppointment);
}
for (Allocatable allocatable:allocatables) {
clone.addAllocatable( allocatable);
Appointment[] appointments = restrictions.get(allocatable);
if (appointments != null) {
clone.setRestriction(allocatable, appointments);
}
}
return clone;
}
public <T extends Entity> T getPersistant(T entity) throws RaplaException {
Set<T> persistantList = Collections.singleton( entity);
Map<T,T> map = getPersistant( persistantList);
T result = map.get( entity);
if ( result == null)
{
throw new EntityNotFoundException( "There is no persistant version of " + entity);
}
return result;
}
public <T extends Entity> Map<T,T> getPersistant(Collection<T> list) throws RaplaException {
Map<Entity,Entity> result = operator.getPersistant(list);
LinkedHashMap<T, T> castedResult = new LinkedHashMap<T, T>();
for ( Map.Entry<Entity,Entity> entry: result.entrySet())
{
@SuppressWarnings("unchecked")
T key = (T) entry.getKey();
@SuppressWarnings("unchecked")
T value = (T) entry.getValue();
castedResult.put( key, value);
}
return castedResult;
}
public void store(Entity<?> obj) throws RaplaException {
if (obj == null)
throw new NullPointerException("Can't store null objects");
storeObjects(new Entity[] { obj });
}
public void remove(Entity<?> obj) throws RaplaException {
if (obj == null)
throw new NullPointerException("Can't remove null objects");
removeObjects(new Entity[] { obj });
}
public void storeObjects(Entity<?>[] obj) throws RaplaException {
storeAndRemove(obj, Entity.ENTITY_ARRAY);
}
public void removeObjects(Entity<?>[] obj) throws RaplaException {
storeAndRemove(Entity.ENTITY_ARRAY, obj);
}
public void storeAndRemove(Entity<?>[] storeObjects, Entity<?>[] removedObjects) throws RaplaException {
if (storeObjects.length == 0 && removedObjects.length == 0)
return;
long time = System.currentTimeMillis();
for (int i = 0; i < storeObjects.length; i++) {
if (storeObjects[i] == null) {
throw new RaplaException("Stored Objects cant be null");
}
if (storeObjects[i].getRaplaType() == Reservation.TYPE) {
checkReservation((Reservation) storeObjects[i]);
}
}
for (int i = 0; i < removedObjects.length; i++) {
if (removedObjects[i] == null) {
throw new RaplaException("Removed Objects cant be null");
}
}
ArrayList<Entity>storeList = new ArrayList<Entity>();
ArrayList<Entity>removeList = new ArrayList<Entity>();
for (Entity toStore : storeObjects) {
storeList.add( toStore);
}
for (Entity<?> toRemove : removedObjects) {
removeList.add( toRemove);
}
User workingUser = getWorkingUser();
operator.storeAndRemove(storeList, removeList, workingUser);
if (getLogger().isDebugEnabled())
getLogger().debug("Storing took " + (System.currentTimeMillis() - time) + " ms.");
}
public CommandHistory getCommandHistory()
{
return commandHistory;
}
public void changeName(String title, String firstname, String surname) throws RaplaException
{
User user = getUser();
getOperator().changeName(user,title,firstname,surname);
}
public void changeEmail(String newEmail) throws RaplaException
{
User user = getUser();
getOperator().changeEmail(user, newEmail);
}
public void confirmEmail(String newEmail) throws RaplaException {
User user = getUser();
getOperator().confirmEmail(user, newEmail);
}
}
| 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.facade.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.rapla.components.util.DateTools;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.entities.storage.EntityResolver;
import org.rapla.entities.storage.internal.SimpleEntity;
import org.rapla.facade.Conflict;
import org.rapla.facade.RaplaComponent;
/**
* A conflict is the allocation of the same resource at the same time by different
* reservations. There's one conflict for each resource and each overlapping of
* two allocations. So if there are 3 reservations that allocate the same 2 resources
* on 2 days of the week, then we got ( 3 * 2 ) * 2 * 2 = 24 conflicts. Thats
* 3 reservations, each conflicting with two other 2 reservations on 2 days with 2 resources.
*
* @author Christopher Kohlhaas
*/
public class ConflictImpl extends SimpleEntity implements Conflict
{
Date startDate;
String reservation1Name;
String reservation2Name;
ConflictImpl() {
}
public ConflictImpl(
Allocatable allocatable,
Appointment app1,
Appointment app2,
Date today
)
{
this(allocatable,app1,app2, today,createId(allocatable.getId(), app1.getId(), app2.getId()));
}
public ConflictImpl(
Allocatable allocatable,
Appointment app1,
Appointment app2,
Date today,
String id
)
{
putEntity("allocatable", allocatable);
startDate = getStartDate_(today, app1, app2);
putEntity("appointment1", app1);
putEntity("appointment2", app2);
Reservation reservation1 = app1.getReservation();
Reservation reservation2 = app2.getReservation();
putEntity("reservation1", reservation1);
putEntity("reservation2", reservation2);
putEntity("owner1", reservation1.getOwner());
putEntity("owner2", reservation2.getOwner());
this.reservation1Name = reservation1.getName(Locale.getDefault());
this.reservation2Name = reservation2.getName(Locale.getDefault());
setResolver( ((AllocatableImpl)allocatable).getResolver());
setId( id);
}
public String getReservation1Name() {
return reservation1Name;
}
public String getReservation2Name() {
return reservation2Name;
}
public Date getStartDate()
{
return startDate;
}
@Override
public Iterable<ReferenceInfo> getReferenceInfo() {
return Collections.emptyList();
}
private Date getStartDate_(Date today,Appointment app1, Appointment app2) {
Date fromDate = today;
Date start1 = app1.getStart();
if ( start1.before( fromDate))
{
fromDate = start1;
}
Date start2 = app2.getStart();
if ( start2.before( fromDate))
{
fromDate = start2;
}
Date toDate = DateTools.addDays( today, 365 * 10);
Date date = getFirstConflictDate(fromDate, toDate, app1, app2);
return date;
}
static public String createId(String allocId, String id1, String id2)
{
StringBuilder buf = new StringBuilder();
//String id1 = getId("appointment1");
//String id2 = getId("appointment2");
if ( id1.equals( id2))
{
throw new IllegalStateException("ids of conflicting appointments are the same " + id1);
}
buf.append(allocId);
buf.append(';');
buf.append(id1.compareTo( id2) > 0 ? id1 : id2);
buf.append(';');
buf.append(id1.compareTo( id2) > 0 ? id2 : id1);
return buf.toString();
}
// public ConflictImpl(String id) throws RaplaException {
// String[] split = id.split(";");
// ReferenceHandler referenceHandler = getReferenceHandler();
// referenceHandler.putId("allocatable", LocalCache.getId(Allocatable.TYPE,split[0]));
// referenceHandler.putId("appointment1", LocalCache.getId(Appointment.TYPE,split[1]));
// referenceHandler.putId("appointment2", LocalCache.getId(Appointment.TYPE,split[2]));
// setId( id);
// }
// public static boolean isConflictId(String id) {
// if ( id == null)
// {
// return false;
// }
// String[] split = id.split(";");
// if ( split.length != 3)
// {
// return false;
// }
// try {
// LocalCache.getId(Allocatable.TYPE,split[0]);
// LocalCache.getId(Appointment.TYPE,split[1]);
// LocalCache.getId(Appointment.TYPE,split[2]);
// } catch (RaplaException e) {
// return false;
// }
// return true;
// }
/** @return the first Reservation, that is involed in the conflict.*/
// public Reservation getReservation1()
// {
// Appointment appointment1 = getAppointment1();
// if ( appointment1 == null)
// {
// throw new IllegalStateException("Appointment 1 is null resolve not called");
// }
// return appointment1.getReservation();
// }
/** The appointment of the first reservation, that causes the conflict. */
public String getAppointment1()
{
return getId("appointment1");
}
public String getReservation1()
{
return getId("reservation1");
}
public String getReservation2()
{
return getId("reservation2");
}
/** @return the allocatable, allocated for the same time by two different reservations. */
public Allocatable getAllocatable()
{
return getEntity("allocatable", Allocatable.class);
}
// /** @return the second Reservation, that is involed in the conflict.*/
// public Reservation getReservation2()
// {
// Appointment appointment2 = getAppointment2();
// if ( appointment2 == null)
// {
// throw new IllegalStateException("Appointment 2 is null resolve not called");
// }
// return appointment2.getReservation();
// }
// /** @return The User, who created the second Reservation.*/
// public User getUser2()
// {
// return getReservation2().getOwner();
// }
/** The appointment of the second reservation, that causes the conflict. */
public String getAppointment2()
{
return getId("appointment2");
}
public static final ConflictImpl[] CONFLICT_ARRAY= new ConflictImpl[] {};
/**
* @see org.rapla.entities.Named#getName(java.util.Locale)
*/
public String getName(Locale locale) {
return getAllocatable().getName( locale );
}
public boolean isOwner( User user)
{
User owner1 = getOwner1();
User owner2 = getOwner2();
if (user != null && !user.equals(owner1) && !user.equals(owner2)) {
return false;
}
return true;
}
// public Date getFirstConflictDate(final Date fromDate, Date toDate) {
// Appointment a1 =getAppointment1();
// Appointment a2 =getAppointment2();
// return getFirstConflictDate(fromDate, toDate, a1, a2);
//}
public User getOwner1() {
return getEntity("owner1", User.class);
}
public User getOwner2() {
return getEntity("owner2", User.class);
}
private boolean contains(String appointmentId) {
if ( appointmentId == null)
return false;
String app1 = getAppointment1();
String app2 = getAppointment2();
if ( app1 != null && app1.equals( appointmentId))
return true;
if ( app2 != null && app2.equals( appointmentId))
return true;
return false;
}
static public boolean equals( ConflictImpl firstConflict,Conflict secondConflict) {
if (secondConflict == null )
return false;
if (!firstConflict.contains( secondConflict.getAppointment1()))
return false;
if (!firstConflict.contains( secondConflict.getAppointment2()))
return false;
Allocatable allocatable = firstConflict.getAllocatable();
if ( allocatable != null && !allocatable.equals( secondConflict.getAllocatable())) {
return false;
}
return true;
}
private static boolean contains(ConflictImpl conflict,
Collection<Conflict> conflictList) {
for ( Conflict conf:conflictList)
{
if ( equals(conflict,conf))
{
return true;
}
}
return false;
}
public RaplaType<Conflict> getRaplaType()
{
return Conflict.TYPE;
}
public String toString()
{
Conflict conflict = this;
StringBuffer buf = new StringBuffer();
buf.append( "Conflict for");
buf.append( conflict.getAllocatable());
buf.append( " " );
buf.append( conflict.getAppointment1());
buf.append( " " );
buf.append( "with");
buf.append( " " );
buf.append( conflict.getAppointment2());
buf.append( " " );
return buf.toString();
}
static public Date getFirstConflictDate(final Date fromDate, Date toDate,
Appointment a1, Appointment a2) {
Date minEnd = a1.getMaxEnd();
if ( a1.getMaxEnd() != null && a2.getMaxEnd() != null && a2.getMaxEnd().before( a1.getMaxEnd())) {
minEnd = a2.getMaxEnd();
}
Date maxStart = a1.getStart();
if ( a2.getStart().after( a1.getStart())) {
maxStart = a2.getStart();
}
if ( fromDate != null && maxStart.before( fromDate))
{
maxStart = fromDate;
}
// look for 10 years in the future (520 weeks)
if ( minEnd == null)
minEnd = new Date(maxStart.getTime() + DateTools.MILLISECONDS_PER_DAY * 365 * 10 );
if ( toDate != null && minEnd.after( toDate))
{
minEnd = toDate;
}
List<AppointmentBlock> listA = new ArrayList<AppointmentBlock>();
a1.createBlocks(maxStart, minEnd, listA );
List<AppointmentBlock> listB = new ArrayList<AppointmentBlock>();
a2.createBlocks( maxStart, minEnd, listB );
for ( int i=0, j=0;i<listA.size() && j<listB.size();) {
long s1 = listA.get( i).getStart();
long s2 = listB.get( j).getStart();
long e1 = listA.get( i).getEnd();
long e2 = listB.get( j).getEnd();
if ( s1< e2 && s2 < e1) {
return new Date( Math.max( s1, s2));
}
if ( s1> s2)
j++;
else
i++;
}
return null;
}
public static void addConflicts(Collection<Conflict> conflictList, Allocatable allocatable,Appointment appointment1, Appointment appointment2,Date today)
{
final ConflictImpl conflict = new ConflictImpl(allocatable,appointment1, appointment2, today);
// Rapla 1.4: Don't add conflicts twice
if (!contains(conflict, conflictList) )
{
conflictList.add(conflict);
}
}
public static boolean endsBefore(Appointment appointment1,Appointment appointment2, Date date) {
Date maxEnd1 = appointment1.getMaxEnd();
Date maxEnd2 = appointment2.getMaxEnd();
if (maxEnd1 != null && maxEnd1.before( date))
{
return true;
}
if (maxEnd2 != null && maxEnd2.before( date))
{
return true;
}
return false;
}
public static boolean isConflict(Appointment appointment1,Appointment appointment2, Date today) {
// Don't add conflicts, when in the past
if (endsBefore(appointment1, appointment2, today))
{
return false;
}
if (appointment1.equals(appointment2))
return false;
if (RaplaComponent.isTemplate( appointment1))
{
return false;
}
if (RaplaComponent.isTemplate( appointment2))
{
return false;
}
boolean conflictTypes = checkForConflictTypes( appointment1, appointment2);
if ( !conflictTypes )
{
return false;
}
Date maxEnd1 = appointment1.getMaxEnd();
Date maxEnd2 = appointment2.getMaxEnd();
Date checkEnd = maxEnd1;
if ( maxEnd2 != null && checkEnd !=null && maxEnd2.before( checkEnd) )
{
checkEnd = maxEnd2;
}
if (checkEnd != null && ConflictImpl.getFirstConflictDate(today, checkEnd, appointment1, appointment2) == null)
{
return false;
}
return true;
}
public static boolean isConflictWithoutCheck(Appointment appointment1,Appointment appointment2, Date today) {
// Don't add conflicts, when in the past
if (appointment1.equals(appointment2))
return false;
boolean conflictTypes = checkForConflictTypes2( appointment1, appointment2);
if ( !conflictTypes )
{
return false;
}
Date maxEnd1 = appointment1.getMaxEnd();
Date maxEnd2 = appointment2.getMaxEnd();
Date checkEnd = maxEnd1;
if ( maxEnd2 != null && checkEnd !=null && maxEnd2.before( checkEnd) )
{
checkEnd = maxEnd2;
}
if (checkEnd != null && ConflictImpl.getFirstConflictDate(today, checkEnd, appointment1, appointment2) == null)
{
return false;
}
return true;
}
@SuppressWarnings("null")
private static boolean checkForConflictTypes(Appointment a1, Appointment a2) {
Reservation r1 = a1.getReservation();
DynamicType type1 = r1 != null ? r1.getClassification().getType() : null;
String annotation1 = getConflictAnnotation( type1);
if ( isNoConflicts( annotation1 ) )
{
return false;
}
Reservation r2 = a2.getReservation();
DynamicType type2 = r2 != null ? r2.getClassification().getType() : null;
String annotation2 = getConflictAnnotation( type2);
if ( isNoConflicts ( annotation2))
{
return false;
}
if ( annotation1 != null )
{
if ( annotation1.equals(DynamicTypeAnnotations.VALUE_CONFLICTS_WITH_OTHER_TYPES))
{
if (type2 != null)
{
if (type1.equals(type2))
{
return false;
}
}
}
}
return true;
}
@SuppressWarnings("null")
private static boolean checkForConflictTypes2(Appointment a1, Appointment a2) {
Reservation r1 = a1.getReservation();
DynamicType type1 = r1 != null ? r1.getClassification().getType() : null;
String annotation1 = getConflictAnnotation( type1);
Reservation r2 = a2.getReservation();
DynamicType type2 = r2 != null ? r2.getClassification().getType() : null;
if ( annotation1 != null )
{
if ( annotation1.equals(DynamicTypeAnnotations.VALUE_CONFLICTS_WITH_OTHER_TYPES))
{
if (type2 != null)
{
if (type1.equals(type2))
{
return false;
}
}
}
}
return true;
}
public static boolean isNoConflicts(String annotation) {
if ( annotation != null && annotation.equals(DynamicTypeAnnotations.VALUE_CONFLICTS_NONE))
{
return true;
}
return false;
}
public static String getConflictAnnotation( DynamicType type) {
if ( type == null)
{
return null;
}
return type.getAnnotation(DynamicTypeAnnotations.KEY_CONFLICTS);
}
public boolean hasAppointment(Appointment appointment)
{
boolean result = getAppointment1().equals( appointment) || getAppointment2().equals( appointment);
return result;
}
@Override
public Conflict clone()
{
ConflictImpl clone = new ConflictImpl();
super.deepClone( clone);
return clone;
}
static public boolean canModify(Conflict conflict,User user, EntityResolver resolver) {
Allocatable allocatable = conflict.getAllocatable();
if (user == null || user.isAdmin())
{
return true;
}
if (allocatable.canRead( user ))
{
Reservation reservation = resolver.tryResolve(conflict.getReservation1(), Reservation.class);
if ( reservation == null )
{
// reservation will be deleted, and conflict also so return
return false;
}
if (RaplaComponent.canModify(reservation, user) )
{
return true;
}
Reservation overlappingReservation = resolver.tryResolve(conflict.getReservation2(), Reservation.class);
if ( overlappingReservation == null )
{
return false;
}
if (RaplaComponent.canModify(overlappingReservation, user))
{
return true;
}
}
return false;
}
public static Map<Appointment, Set<Appointment>> getMap(Collection<Conflict> selectedConflicts,List<Reservation> reservations)
{
Map<Appointment, Set<Appointment>> result = new HashMap<Appointment,Set<Appointment>>();
Map<String, Appointment> map = new HashMap<String,Appointment>();
for ( Reservation reservation:reservations)
{
for (Appointment app:reservation.getAppointments())
{
map.put( app.getId(), app);
}
}
for ( Conflict conflict:selectedConflicts)
{
Appointment app1 = map.get(conflict.getAppointment1());
Appointment app2 = map.get(conflict.getAppointment2());
add(result, app1, app2);
add(result, app2, app1);
}
return result;
}
private static void add(Map<Appointment, Set<Appointment>> result,Appointment app1, Appointment app2) {
Set<Appointment> set = result.get( app1);
if ( set == null)
{
set = new HashSet<Appointment>();
result.put(app1,set);
}
set.add( app2);
}
}
| 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.client;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.rapla.framework.StartupEnvironment;
/** The applet-encapsulation of the Main.class reads the configuration
* from the document-base of the applet and displays
* an applet with a start button.
* @author Christopher Kohlhaas
* @see MainWebstart
*/
final public class MainApplet extends JApplet
{
private static final long serialVersionUID = 1L;
JPanel dlg = new JPanel();
JButton button;
JLabel label;
boolean startable = false;
public MainApplet()
{
JPanel panel1 = new JPanel();
panel1.setBackground( new Color( 255, 255, 204 ) );
GridLayout gridLayout1 = new GridLayout();
gridLayout1.setColumns( 1 );
gridLayout1.setRows( 3 );
gridLayout1.setHgap( 10 );
gridLayout1.setVgap( 10 );
panel1.setLayout( gridLayout1 );
label = new JLabel( "Rapla-Applet loading" );
panel1.add( label );
button = new JButton( "StartRapla" );
button.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
startThread();
}
} );
panel1.add( button );
dlg.setBackground( new Color( 255, 255, 204 ) );
dlg.setBorder( BorderFactory.createMatteBorder( 1, 1, 2, 2, Color.black ) );
dlg.add( panel1 );
}
public void start()
{
getRootPane().putClientProperty( "defeatSystemEventQueueCheck", Boolean.TRUE );
try
{
setContentPane( dlg );
button.setEnabled( startable );
startable = true;
button.setEnabled( startable );
}
catch ( Exception ex )
{
ex.printStackTrace();
}
}
private void updateStartable()
{
javax.swing.SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
button.setEnabled( startable );
}
} );
}
private void startThread()
{
( new Thread()
{
public void run()
{
try
{
startable = false;
updateStartable();
MainWebclient main = new MainWebclient();
URL configURL = new URL( getDocumentBase(), MainWebclient.CLIENT_CONFIG_SERVLET_URL );
main.init( configURL, StartupEnvironment.APPLET );
main.env.setDownloadURL( getDocumentBase() );
System.out.println( "Docbase " + getDocumentBase() );
main.startRapla("client");
}
catch ( Exception ex )
{
ex.printStackTrace();
}
finally
{
startable = true;
updateStartable();
}
}
} ).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.client;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.internal.ConfigTools;
final public class MainWebstart
{
public static void main(String[] args) {
MainWebclient main = new MainWebclient();
try {
main.init( ConfigTools.webstartConfigToURL( MainWebclient.CLIENT_CONFIG_SERVLET_URL),StartupEnvironment.WEBSTART);
main.startRapla("client");
} catch (Throwable ex) {
main.getLogger().error("Couldn't start Rapla",ex);
main.raplaContainer.dispose();
System.out.flush();
try
{
Thread.sleep( 2000 );
}
catch ( InterruptedException e )
{
}
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.client;
import java.net.URL;
import org.rapla.ConnectInfo;
import org.rapla.RaplaMainContainer;
import org.rapla.RaplaStartupEnvironment;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.logger.ConsoleLogger;
import org.rapla.framework.logger.Logger;
public class MainWebclient
{
/** The default config filename for client-mode raplaclient.xconf*/
public final static String CLIENT_CONFIG_SERVLET_URL = "rapla/raplaclient.xconf";
private Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_WARN).getChildLogger("init");
RaplaStartupEnvironment env = new RaplaStartupEnvironment();
Container raplaContainer;
void init(URL configURL,int mode) throws Exception {
env.setStartupMode( mode );
env.setConfigURL( configURL );
env.setBootstrapLogger( getLogger() );
}
void startRapla(final String id) throws Exception {
ConnectInfo connectInfo = null;
startRapla(id, connectInfo);
}
protected void startRapla(final String id, ConnectInfo connectInfo) throws Exception, RaplaContextException {
raplaContainer = new RaplaMainContainer( env);
ClientServiceContainer clientContainer = raplaContainer.lookup(ClientServiceContainer.class, id );
ClientService client = clientContainer.getContext().lookup( ClientService.class);
client.addRaplaClientListener(new RaplaClientListenerAdapter() {
public void clientClosed(ConnectInfo reconnect) {
if ( reconnect != null) {
raplaContainer.dispose();
try {
startRapla(id, reconnect);
} catch (Exception ex) {
getLogger().error("Error restarting client",ex);
exit();
}
} else {
exit();
}
}
public void clientAborted()
{
exit();
}
});
clientContainer.start(connectInfo);
}
public static void main(String[] args) {
MainWebclient main = new MainWebclient();
try {
main.init( new URL("http://localhost:8051/rapla/raplaclient.xconf"),StartupEnvironment.CONSOLE);
main.startRapla("client");
} catch (Throwable ex) {
main.getLogger().error("Couldn't start Rapla",ex);
main.raplaContainer.dispose();
System.out.flush();
try
{
Thread.sleep( 2000 );
}
catch ( InterruptedException e )
{
}
System.exit(1);
}
}
private void exit() {
if ( raplaContainer != null)
{
raplaContainer.dispose();
}
if (env.getStartupMode() != StartupEnvironment.APPLET)
{
System.exit(0);
}
}
Logger getLogger() {
return logger;
}
}
| 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.client;
import org.rapla.ConnectInfo;
public interface RaplaClientListener
{
public void clientStarted();
public void clientClosed(ConnectInfo reconnect);
public void clientAborted();
}
| 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.client;
import org.rapla.ConnectInfo;
public class RaplaClientListenerAdapter implements RaplaClientListener
{
public void clientStarted() {
}
public void clientClosed(ConnectInfo reconnect) {
}
public void clientAborted()
{
}
}
| 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.client;
import java.util.Map;
import org.rapla.entities.User;
import org.rapla.facade.ClientFacade;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.gui.toolkit.RaplaFrame;
import org.rapla.gui.toolkit.RaplaWidget;
/** This service starts and manages the rapla-gui-client.
*/
public interface ClientService
{
public static TypedComponentRole<Map<Object,Object>> SESSION_MAP = new TypedComponentRole<Map<Object,Object>>("org.rapla.SessionMap");
public static TypedComponentRole<RaplaFrame> MAIN_COMPONENT = new TypedComponentRole<RaplaFrame>("org.rapla.MainComponent");
public static TypedComponentRole<RaplaWidget> WELCOME_FIELD = new TypedComponentRole<RaplaWidget>("org.rapla.gui.WelcomeField");
void addRaplaClientListener(RaplaClientListener listener);
void removeRaplaClientListener(RaplaClientListener listener);
ClientFacade getFacade() throws RaplaContextException;
/** setup a component with the services logger,context and servicemanager */
boolean isRunning();
/** the admin can switch to another user!
* @throws RaplaContextException
* @throws RaplaException */
void switchTo(User user) throws RaplaException;
/** returns true if the admin has switched to anoter user!*/
boolean canSwitchBack();
/** restarts the complete Client and displays a new login*/
void restart();
/** returns true if an logout option is available. This is true when the user used an login dialog.*/
boolean isLogoutAvailable();
RaplaContext getContext();
void logout();
}
| Java |
package org.rapla.client;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.framework.TypedComponentRole;
import org.rapla.gui.AppointmentStatusFactory;
import org.rapla.gui.ObjectMenuFactory;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.PluginOptionPanel;
import org.rapla.gui.PublishExtensionFactory;
import org.rapla.gui.ReservationCheck;
import org.rapla.gui.SwingViewFactory;
import org.rapla.gui.toolkit.IdentifiableMenuEntry;
/** Constant Pool of basic extension points of the Rapla client.
* You can add your extension in the provideService Method of your PluginDescriptor
* <pre>
* container.addContainerProvidedComponent( REPLACE_WITH_EXTENSION_POINT_NAME, REPLACE_WITH_CLASS_IMPLEMENTING_EXTENSION, config);
* </pre>
* @see org.rapla.framework.PluginDescriptor
*/
public interface RaplaClientExtensionPoints
{
/** add your own views to Rapla, by providing a org.rapla.gui.ViewFactory
* @see SwingViewFactory
* */
Class<SwingViewFactory> CALENDAR_VIEW_EXTENSION = SwingViewFactory.class;
/** A client extension is started automaticaly when a user has successfully login into the Rapla system. A class added as service doesn't need to implement a specific interface and is instanciated automaticaly after client login. You can add a RaplaContext parameter to your constructor to get access to the services of rapla.
*/
Class<ClientExtension> CLIENT_EXTENSION = ClientExtension.class;
/** You can add a specific configuration panel for your plugin.
* Note if you add a pluginOptionPanel you need to provide the PluginClass as hint.
* Example
* <code>
* container.addContainerProvidedComponent( RaplaExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION, AutoExportPluginOption.class, getClass().getName());
* </code>
* @see org.rapla.entities.configuration.Preferences
* @see OptionPanel
* */
TypedComponentRole<PluginOptionPanel> PLUGIN_OPTION_PANEL_EXTENSION = new TypedComponentRole<PluginOptionPanel>("org.rapla.plugin.Option");
/** You can add additional option panels for editing the user preference.
* @see org.rapla.entities.configuration.Preferences
* @see OptionPanel
* */
TypedComponentRole<OptionPanel> USER_OPTION_PANEL_EXTENSION = new TypedComponentRole<OptionPanel>("org.rapla.UserOptions");
/** You can add additional option panels for the editing the system preferences
* @see org.rapla.entities.configuration.Preferences
* @see OptionPanel
* */
TypedComponentRole<OptionPanel> SYSTEM_OPTION_PANEL_EXTENSION = new TypedComponentRole<OptionPanel>("org.rapla.SystemOptions");
/** add your own wizard menus to create events. Use the CalendarSelectionModel service to get access to the current calendar
* @see CalendarSelectionModel
**/
TypedComponentRole<IdentifiableMenuEntry> RESERVATION_WIZARD_EXTENSION = new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ReservationWizardExtension");
/** you can add an interactive check when the user stores a reservation
*@see ReservationCheck
**/
Class<ReservationCheck> RESERVATION_SAVE_CHECK = ReservationCheck.class;
/** add your own menu entries in the context menu of an object. To do this provide
an ObjectMenuFactory under this entry.
@see ObjectMenuFactory
*/
Class<ObjectMenuFactory> OBJECT_MENU_EXTENSION = ObjectMenuFactory.class;
/** add a footer for summary of appointments in edit window
* provide an AppointmentStatusFactory to add your own footer to the appointment edit
@see AppointmentStatusFactory
* */
Class<AppointmentStatusFactory> APPOINTMENT_STATUS = AppointmentStatusFactory.class;
/** add your own submenus to the admin menu.
*/
TypedComponentRole<IdentifiableMenuEntry> ADMIN_MENU_EXTENSION_POINT = new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.AdminMenuInsert");
/** add your own import-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> IMPORT_MENU_EXTENSION_POINT =new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ImportMenuInsert");
/** add your own export-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> EXPORT_MENU_EXTENSION_POINT =new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ExportMenuInsert");
/** add your own view-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> VIEW_MENU_EXTENSION_POINT =new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ViewMenuInsert");
/** add your own edit-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> EDIT_MENU_EXTENSION_POINT = new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.EditMenuInsert");
/** add your own help-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> HELP_MENU_EXTENSION_POINT = new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ExtraMenuInsert");
/** add your own publish options for the calendars*/
Class<PublishExtensionFactory> PUBLISH_EXTENSION_OPTION = PublishExtensionFactory.class;
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.