code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
package org.rapla.server.internal;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class CryptoHandler extends RaplaComponent {
String syncEncryptionAlg = "AES/ECB/PKCS5Padding";
private Cipher encryptionCipher;
private Cipher decryptionCipher;
private Base64 base64;
private static final String ENCODING = "UTF-8";
public CryptoHandler( RaplaContext context,String pepper) throws RaplaException
{
super( context);
try {
byte[] linebreake = {};
this.base64 = new Base64(64, linebreake, true);
initializeCiphers( pepper);
} catch (Exception e) {
throw new RaplaException( e.getMessage(),e);
}
}
private void initializeCiphers(String pepper) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException {
byte[] key = pepper.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
Key specKey = new SecretKeySpec(key, "AES");
this.encryptionCipher = Cipher.getInstance(syncEncryptionAlg);
this.encryptionCipher.init(Cipher.ENCRYPT_MODE, specKey);
this.decryptionCipher = Cipher.getInstance(syncEncryptionAlg);
this.decryptionCipher.init(Cipher.DECRYPT_MODE, specKey);
}
public String encrypt(String toBeEncrypted) throws RaplaException{
try {
return base64.encodeToString(this.encryptionCipher.doFinal(toBeEncrypted.getBytes(ENCODING)));
} catch (Exception e) {
throw new RaplaException(e.getMessage(), e);
}
}
public String decrypt(String toBeDecryptedBase64) throws RaplaException{
try {
return new String(this.decryptionCipher.doFinal(base64.decode(toBeDecryptedBase64.getBytes(ENCODING))));
} catch (Exception e) {
throw new RaplaException(e.getMessage(), e);
}
}
}
| 04900db4-clienttest | src/org/rapla/server/internal/CryptoHandler.java | Java | gpl3 | 2,334 |
<body>
<p align="center">This document is the description of the classes and interfaces used in rapla.</p>
<p align="center" valign="center"><A HREF="@doc.homepage@"><img src="logo.png"/></A> <B>Version @doc.version@</B></p>
<p>For more information contact the <A HREF="@doc.developer-list-link@">developers mailinglist</A>
or take look at the documentation section on our homepage.
</p>
@see <A HREF="@doc.homepage@">@doc.homepage@</A>
@see <A HREF="@doc.developer-list-link@">mailinglist</A>
</body>
| 04900db4-clienttest | src/org/rapla/overview.html | HTML | gpl3 | 509 |
package org.rapla.rest.client;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
public class HTTPJsonConnector {
public HTTPJsonConnector() {
super();
}
private String readResultToString(InputStream input) throws IOException {
InputStreamReader in = new InputStreamReader( input,"UTF-8");
char[] buf = new char[4096];
StringBuffer buffer = new StringBuffer();
while ( true )
{
int len = in.read(buf);
if ( len == -1)
{
break;
}
buffer.append( buf, 0,len );
}
String result = buffer.toString();
in.close();
return result;
}
public JsonObject sendPost(URL methodURL, JsonElement jsonObject, String authenticationToken) throws IOException,JsonParseException {
return sendCall("POST", methodURL, jsonObject, authenticationToken);
}
public JsonObject sendGet(URL methodURL, String authenticationToken) throws IOException,JsonParseException {
return sendCall("GET", methodURL, null, authenticationToken);
}
public JsonObject sendPut(URL methodURL, JsonElement jsonObject, String authenticationToken) throws IOException,JsonParseException {
return sendCall("PUT", methodURL, jsonObject, authenticationToken);
}
public JsonObject sendPatch(URL methodURL, JsonElement jsonObject, String authenticationToken) throws IOException,JsonParseException {
return sendCall("PATCH", methodURL, jsonObject, authenticationToken);
}
public JsonObject sendDelete(URL methodURL, String authenticationToken) throws IOException,JsonParseException {
return sendCall("DELETE", methodURL, null, authenticationToken);
}
protected JsonObject sendCall(String requestMethod, URL methodURL, JsonElement jsonObject, String authenticationToken) throws IOException,JsonParseException {
HttpURLConnection conn = (HttpURLConnection)methodURL.openConnection();
if ( !requestMethod.equals("POST") && !requestMethod.equals("GET"))
{
conn.setRequestMethod("POST");
// we tunnel all non POST or GET requests to avoid proxy filtering (e.g. URLConnection does not allow PATCH)
conn.setRequestProperty("X-HTTP-Method-Override",requestMethod);
}
else
{
conn.setRequestMethod(requestMethod);
}
conn.setUseCaches( false );
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.setRequestProperty("Content-Type", "application/json" + ";charset=utf-8");
conn.setRequestProperty("Accept", "application/json");
if ( authenticationToken != null)
{
conn.setRequestProperty("Authorization", "Bearer " + authenticationToken);
}
conn.setReadTimeout(20000); //set timeout to 20 seconds
conn.setConnectTimeout(15000); //set connect timeout to 15 seconds
conn.setDoOutput(true);
conn.connect();
if ( requestMethod.equals("PUT") ||requestMethod.equals("POST") ||requestMethod.equals("PATCH"))
{
OutputStream outputStream = null;
Writer wr = null;
try
{
outputStream= conn.getOutputStream();
wr = new OutputStreamWriter(outputStream,"UTF-8");
Gson gson = new GsonBuilder().create();
String body = gson.toJson( jsonObject);
wr.write( body);
wr.flush();
}
finally
{
if ( wr != null)
{
wr.close();
}
if ( outputStream != null)
{
outputStream.close();
}
}
}
else
{
}
JsonObject resultMessage = readResult(conn);
return resultMessage;
}
public JsonObject readResult(HttpURLConnection conn) throws IOException,JsonParseException {
String resultString;
InputStream inputStream = null;
try
{
String encoding = conn.getContentEncoding();
if (encoding != null && encoding.equalsIgnoreCase("gzip"))
{
inputStream = new GZIPInputStream(conn.getInputStream());
}
else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
inputStream = new InflaterInputStream(conn.getInputStream(), new Inflater(true));
}
else {
inputStream = conn.getInputStream();
}
resultString = readResultToString( inputStream);
}
finally
{
if ( inputStream != null)
{
inputStream.close();
}
}
JsonParser jsonParser = new JsonParser();
JsonElement parsed = jsonParser.parse(resultString);
if ( !(parsed instanceof JsonObject))
{
throw new JsonParseException("Invalid json result. JsonObject expected.");
}
JsonObject resultMessage = (JsonObject) parsed;
return resultMessage;
}
} | 04900db4-clienttest | src/org/rapla/rest/client/HTTPJsonConnector.java | Java | gpl3 | 5,691 |
package org.rapla.rest.jsonpatch.mergepatch.server;
public class JsonPatchException extends Exception {
private static final long serialVersionUID = 1L;
public JsonPatchException(String string) {
super(string);
}
}
| 04900db4-clienttest | src/org/rapla/rest/jsonpatch/mergepatch/server/JsonPatchException.java | Java | gpl3 | 224 |
/*
* Copyright (c) 2014, Francis Galiegue (fgaliegue@gmail.com)
*
* This software is dual-licensed under:
*
* - the Lesser General Public License (LGPL) version 3.0 or, at your option, any
* later version;
* - the Apache Software License (ASL) version 2.0.
*
* The text of both licenses is available under the src/resources/ directory of
* this project (under the names LGPL-3.0.txt and ASL-2.0.txt respectively).
*
* Direct link to the sources:
*
* - LGPL 3.0: https://www.gnu.org/licenses/lgpl-3.0.txt
* - ASL 2.0: http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.rapla.rest.jsonpatch.mergepatch.server;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/**
* Merge patch for a JSON Object
*
* <p>This only takes care of the top level, and delegates to other {@link
* JsonMergePatch} instances for deeper levels.</p>
*/
final class ObjectMergePatch
extends JsonMergePatch
{
private final Map<String, JsonElement> fields;
private final Set<String> removals;
ObjectMergePatch(final JsonElement content)
{
super(content);
fields = asMap(content);
removals = new HashSet<String>();
for (final Map.Entry<String, JsonElement> entry: fields.entrySet())
if (entry.getValue() == null)
removals.add(entry.getKey());
fields.keySet().removeAll(removals);
}
@Override
public JsonElement apply(final JsonElement input) throws JsonPatchException
{
if (!input.isJsonObject())
return mapToNode(fields);
final Map<String, JsonElement> map = asMap(input);
// Remove all entries which must be removed
map.keySet().removeAll(removals);
// Now cycle through what is left
String memberName;
JsonElement patchNode;
for (final Map.Entry<String, JsonElement> entry: map.entrySet()) {
memberName = entry.getKey();
patchNode = fields.get(memberName);
// Leave untouched if no mention in the patch
if (patchNode == null)
continue;
// If the patch node is a primitive type, replace in the result.
// Reminder: there cannot be a JSON null anymore
if (patchNode.isJsonPrimitive()) {
entry.setValue(patchNode); // no need for .deepCopy()
continue;
}
final JsonMergePatch patch = JsonMergePatch.fromJson(patchNode);
entry.setValue(patch.apply(entry.getValue()));
}
// Finally, if there are members in the patch not present in the input,
// fill in members
for (final String key: difference(fields.keySet(), map.keySet()))
map.put(key, clearNulls(fields.get(key)));
return mapToNode(map);
}
private Set<String> difference(Set<String> keySet, Set<String> keySet2) {
LinkedHashSet<String> result = new LinkedHashSet<String>();
for ( String key:keySet)
{
if ( !keySet2.contains(key))
{
result.add( key);
}
}
return result;
}
private Map<String, JsonElement> asMap(JsonElement input) {
Map<String,JsonElement> result = new LinkedHashMap<String,JsonElement>();
for ( Entry<String, JsonElement> entry :input.getAsJsonObject().entrySet())
{
JsonElement value = entry.getValue();
String key = entry.getKey();
result.put( key,value);
}
return result;
}
private static JsonElement mapToNode(final Map<String, JsonElement> map)
{
final JsonObject ret = new JsonObject();
for ( String key: map.keySet())
{
JsonElement value = map.get( key);
ret.add(key, value);
}
return ret;
}
}
| 04900db4-clienttest | src/org/rapla/rest/jsonpatch/mergepatch/server/ObjectMergePatch.java | Java | gpl3 | 3,911 |
package org.rapla.rest.jsonpatch.mergepatch.server;
import java.util.Iterator;
import java.util.Map;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public abstract class JsonMergePatch
{
protected final JsonElement origPatch;
/**
* Protected constructor
*
* <p>Only necessary for serialization purposes. The patching process
* itself never requires the full node to operate.</p>
*
* @param node the original patch node
*/
protected JsonMergePatch(final JsonElement node)
{
origPatch = node;
}
public abstract JsonElement apply(final JsonElement input) throws JsonPatchException;
public static JsonMergePatch fromJson(final JsonElement input)
throws JsonPatchException
{
if ( input.isJsonPrimitive())
{
throw new JsonPatchException("Only json containers are supported");
}
return input.isJsonArray() ? new ArrayMergePatch(input)
: new ObjectMergePatch(input);
}
/**
* Clear "null values" from a JSON value
*
* <p>Non container values are unchanged. For arrays, null elements are
* removed. From objects, members whose values are null are removed.</p>
*
* <p>This method is recursive, therefore arrays within objects, or objects
* within arrays, or arrays within arrays etc are also affected.</p>
*
* @param node the original JSON value
* @return a JSON value without null values (see description)
*/
protected static JsonElement clearNulls(final JsonElement node)
{
if (node.isJsonPrimitive())
return node;
return node.isJsonArray() ? clearNullsFromArray((JsonArray)node) : clearNullsFromObject((JsonObject)node);
}
private static JsonElement clearNullsFromArray(final JsonArray node)
{
final JsonArray ret = new JsonArray();
/*
* Cycle through array elements. If the element is a null node itself,
* skip it. Otherwise, add a "cleaned up" element to the result.
*/
for (final JsonElement element: node)
if (!element.isJsonNull())
ret.add(clearNulls(element));
return ret;
}
private static JsonElement clearNullsFromObject(final JsonObject node)
{
final JsonObject ret = new JsonObject();
final Iterator<Map.Entry<String, JsonElement>> iterator
= node.entrySet().iterator();
Map.Entry<String, JsonElement> entry;
JsonElement value;
/*
* When faces with an object, cycle through this object's entries.
*
* If the value of the entry is a JSON null, don't include it in the
* result. If not, include a "cleaned up" value for this key instead of
* the original element.
*/
while (iterator.hasNext()) {
entry = iterator.next();
value = entry.getValue();
if (value != null) {
String key = entry.getKey();
JsonElement clearNulls = clearNulls(value);
ret.add(key, clearNulls);
}
}
return ret;
}
public String toString()
{
return origPatch.toString();
}
} | 04900db4-clienttest | src/org/rapla/rest/jsonpatch/mergepatch/server/JsonMergePatch.java | Java | gpl3 | 2,975 |
package org.rapla.rest.jsonpatch.mergepatch.server;
import com.google.gson.JsonElement;
final class ArrayMergePatch extends JsonMergePatch
{
// Always an array
private final JsonElement content;
ArrayMergePatch(final JsonElement content)
{
super(content);
this.content = clearNulls(content);
}
@Override
public JsonElement apply(final JsonElement input) throws JsonPatchException
{
return content;
}
} | 04900db4-clienttest | src/org/rapla/rest/jsonpatch/mergepatch/server/ArrayMergePatch.java | Java | gpl3 | 435 |
package org.rapla.rest;
public @interface GwtIncompatible {
}
| 04900db4-clienttest | src/org/rapla/rest/GwtIncompatible.java | Java | gpl3 | 64 |
package org.rapla.rest.server;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.jws.WebParam;
import javax.jws.WebService;
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.domain.internal.AppointmentImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.servletpages.RaplaPageGenerator;
import org.rapla.storage.RaplaSecurityException;
@WebService
public class RaplaEventsRestPage extends AbstractRestPage implements RaplaPageGenerator
{
public RaplaEventsRestPage(RaplaContext context) throws RaplaException
{
super(context);
}
private Collection<String> CLASSIFICATION_TYPES = Arrays.asList(new String[] {DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION});
public List<ReservationImpl> list(@WebParam(name="user") User user, @WebParam(name="start")Date start, @WebParam(name="end")Date end, @WebParam(name="resources") List<String> resources, @WebParam(name="eventTypes") List<String> eventTypes,@WebParam(name="attributeFilter") Map<String,String> simpleFilter ) throws RaplaException
{
Collection<Allocatable> allocatables = new ArrayList<Allocatable>();
for (String id :resources)
{
Allocatable allocatable = operator.resolve(id, Allocatable.class);
allocatables.add( allocatable);
}
ClassificationFilter[] filters = getClassificationFilter(simpleFilter, CLASSIFICATION_TYPES, eventTypes);
Map<String, String> annotationQuery = null;
boolean canReadReservationsFromOthers = getQuery().canReadReservationsFromOthers(user);
User owner = null;
Collection<Reservation> reservations = operator.getReservations(owner, allocatables, start, end, filters, annotationQuery);
List<ReservationImpl> result = new ArrayList<ReservationImpl>();
for ( Reservation r:reservations)
{
if ( RaplaComponent.canRead(r, user, canReadReservationsFromOthers))
{
result.add((ReservationImpl) r);
}
}
return result;
}
public ReservationImpl get(@WebParam(name="user") User user, @WebParam(name="id")String id) throws RaplaException
{
ReservationImpl event = (ReservationImpl) operator.resolve(id, Reservation.class);
boolean canReadReservationsFromOthers = getQuery().canReadReservationsFromOthers(user);
if (!RaplaComponent.canRead(event, user, canReadReservationsFromOthers))
{
throw new RaplaSecurityException("User " + user + " can't read event " + event);
}
return event;
}
public ReservationImpl update(@WebParam(name="user") User user, ReservationImpl event) throws RaplaException
{
if (!RaplaComponent.canModify(event, user))
{
throw new RaplaSecurityException("User " + user + " can't modify event " + event);
}
event.setResolver( operator);
getModification().store( event);
ReservationImpl result =(ReservationImpl) getModification().getPersistant( event);
return result;
}
public ReservationImpl create(@WebParam(name="user") User user, ReservationImpl event) throws RaplaException
{
if (!getQuery().canCreateReservations(user))
{
throw new RaplaSecurityException("User " + user + " can't modify event " + event);
}
if (event.getId() != null)
{
throw new RaplaException("Id has to be null for new events");
}
String eventId = operator.createIdentifier(Reservation.TYPE, 1)[0];
event.setId( eventId);
event.setResolver( operator);
event.setCreateDate( operator.getCurrentTimestamp());
Appointment[] appointments = event.getAppointments();
String[] appointmentIds = operator.createIdentifier(Appointment.TYPE, 1);
for ( int i=0;i<appointments.length;i++)
{
AppointmentImpl app = (AppointmentImpl)appointments[i];
String id = appointmentIds[i];
app.setId(id);
}
event.setOwner( user );
getModification().store( event);
ReservationImpl result =(ReservationImpl) getModification().getPersistant( event);
return result;
}
}
| 04900db4-clienttest | src/org/rapla/rest/server/RaplaEventsRestPage.java | Java | gpl3 | 4,791 |
package org.rapla.rest.server;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.entities.User;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.rest.gwtjsonrpc.server.JsonServlet;
import org.rapla.server.ServerServiceContainer;
import org.rapla.servletpages.RaplaPageGenerator;
import org.rapla.storage.RaplaSecurityException;
import org.rapla.storage.StorageOperator;
public class AbstractRestPage extends RaplaComponent implements RaplaPageGenerator {
protected StorageOperator operator;
protected JsonServlet servlet;
protected final ServerServiceContainer serverContainer;
String getMethod = null;
String updatetMethod = null;
String listMethod = null;
String createMethod = null;
public AbstractRestPage(RaplaContext context) throws RaplaException
{
super(context);
operator = context.lookup( ClientFacade.class).getOperator();
serverContainer = context.lookup(ServerServiceContainer.class);
Class class1 = getServiceObject().getClass();
Collection<String> publicMethodNames = getPublicMethods(class1);
servlet = new JsonServlet(getLogger(), class1);
if ( publicMethodNames.contains("get"))
{
getMethod = "get";
}
if ( publicMethodNames.contains("update"))
{
updatetMethod = "update";
}
if ( publicMethodNames.contains("create"))
{
createMethod = "create";
}
if ( publicMethodNames.contains("list"))
{
listMethod = "list";
}
}
@Override
public void generatePage(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
User user;
Object serviceObj = getServiceObject();
try {
user = serverContainer.getUser(request);
if ( user == null)
{
throw new RaplaSecurityException("User not authentified. Pass access token");
}
request.setAttribute("user", user);
String pathInfo = request.getPathInfo();
int appendix = pathInfo.indexOf("/",1);
String method = request.getMethod();
if ( appendix > 0)
{
if ( method.equals("GET") && getMethod != null )
{
String id = pathInfo.substring(appendix+1);
request.setAttribute("id", id);
request.setAttribute("method", getMethod);
}
else if ( method.equals("PATCH") && getMethod != null && updatetMethod != null)
{
String id = pathInfo.substring(appendix+1);
request.setAttribute("id", id);
request.setAttribute("method", getMethod);
request.setAttribute("patchMethod", updatetMethod);
}
else if ( method.equals("PUT") && updatetMethod != null)
{
String id = pathInfo.substring(appendix+1);
request.setAttribute("id", id);
request.setAttribute("method", updatetMethod);
}
else
{
throw new RaplaException(method + " Method not supported in this context");
}
}
else
{
if ( method.equals("GET") && listMethod != null)
{
request.setAttribute("method", listMethod);
}
else if ( method.equals("POST") && createMethod != null)
{
request.setAttribute("method", createMethod);
}
else
{
throw new RaplaException(method + " Method not supported in this context");
}
}
} catch (RaplaException ex) {
servlet.serviceError(request, response, servletContext, ex);
return;
}
servlet.service(request, response, servletContext, serviceObj);
// super.generatePage(servletContext, request, response);
}
protected Collection<String> getPublicMethods(Class class1) {
HashSet<String> result = new HashSet<String>();
for (Method m:class1.getMethods())
{
if ( Modifier.isPublic(m.getModifiers() ))
{
result.add( m.getName());
}
}
return result;
}
public ClassificationFilter[] getClassificationFilter(Map<String, String> simpleFilter, Collection<String> selectedClassificationTypes, Collection<String> typeNames) throws RaplaException {
ClassificationFilter[] filters = null;
if ( simpleFilter != null || typeNames == null)
{
DynamicType[] types = getQuery().getDynamicTypes(null);
List<ClassificationFilter> filterList = new ArrayList<ClassificationFilter>();
for ( DynamicType type:types)
{
String classificationType = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
if ( classificationType == null || !selectedClassificationTypes.contains(classificationType))
{
continue;
}
ClassificationFilter classificationFilter = type.newClassificationFilter();
if ( typeNames != null)
{
if ( !typeNames.contains( type.getKey()))
{
continue;
}
}
if ( simpleFilter != null)
{
for (String key:simpleFilter.keySet())
{
Attribute att = type.getAttribute(key);
if ( att != null)
{
String value = simpleFilter.get(key);
// convert from string to attribute type
Object object = att.convertValue(value);
if ( object != null)
{
classificationFilter.addEqualsRule(att.getKey(), object);
}
filterList.add(classificationFilter);
}
}
}
else
{
filterList.add(classificationFilter);
}
}
filters = filterList.toArray( new ClassificationFilter[] {});
}
return filters;
}
private Object getServiceObject() {
return this;
}
} | 04900db4-clienttest | src/org/rapla/rest/server/AbstractRestPage.java | Java | gpl3 | 7,545 |
package org.rapla.rest.server;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.rest.gwtjsonrpc.common.JSONParserWrapper;
import org.rapla.rest.gwtjsonrpc.server.JsonServlet;
import org.rapla.rest.gwtjsonrpc.server.RPCServletUtils;
import org.rapla.server.ServerServiceContainer;
import org.rapla.servletpages.RaplaPageGenerator;
import org.rapla.storage.RaplaSecurityException;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
public class RaplaAPIPage extends RaplaComponent implements RaplaPageGenerator
{
final ServerServiceContainer serverContainer;
public RaplaAPIPage(RaplaContext context) throws RaplaContextException {
super(context);
serverContainer = context.lookup(ServerServiceContainer.class);
}
Map<String,JsonServlet> servletMap = new HashMap<String, JsonServlet>();
private JsonServlet getJsonServlet(HttpServletRequest request,String serviceAndMethodName) throws RaplaException {
if ( serviceAndMethodName == null || serviceAndMethodName.length() == 0) {
throw new RaplaException("Servicename missing in url");
}
int indexRole = serviceAndMethodName.indexOf( "/" );
String interfaceName;
if ( indexRole > 0 )
{
interfaceName= serviceAndMethodName.substring( 0, indexRole );
if ( serviceAndMethodName.length() >= interfaceName.length())
{
String methodName = serviceAndMethodName.substring( indexRole + 1 );
request.setAttribute(JsonServlet.JSON_METHOD, methodName);
}
}
else
{
interfaceName = serviceAndMethodName;
}
JsonServlet servlet = servletMap.get( interfaceName);
if ( servlet == null)
{
try
{
if (!serverContainer.hasWebservice(interfaceName))
{
throw new RaplaException("Webservice " + interfaceName + " not configured or initialized.");
}
Class<?> interfaceClass = Class.forName(interfaceName, true,RaplaAPIPage.class.getClassLoader());
// Test if service is found
servlet = new JsonServlet(getLogger(), interfaceClass);
}
catch (Exception ex)
{
throw new RaplaException( ex.getMessage(), ex);
}
servletMap.put( interfaceName, servlet);
}
return servlet;
}
public void generatePage(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException
{
String id = request.getParameter("id");
String serviceAndMethodName = getServiceAndMethodName(request);
try
{
JsonServlet servlet;
try
{
servlet = getJsonServlet( request, serviceAndMethodName );
}
catch (RaplaException ex)
{
getLogger().error(ex.getMessage(), ex);
String out = serializeException(id, ex);
RPCServletUtils.writeResponse(servletContext, response, out, false);
return;
}
Class<?> role = servlet.getInterfaceClass();
Object impl;
try
{
impl = serverContainer.createWebservice(role, request);
}
catch (RaplaSecurityException ex)
{
servlet.serviceError(request, response, servletContext, ex);
return;
}
servlet.service(request, response, servletContext, impl);
}
catch ( RaplaSecurityException ex)
{
getLogger().error(ex.getMessage());
}
catch ( RaplaException ex)
{
getLogger().error(ex.getMessage(), ex);
}
}
protected String getServiceAndMethodName(HttpServletRequest request) {
String requestURI =request.getPathInfo();
String path = "/json/";
int rpcIndex=requestURI.indexOf(path) ;
String serviceAndMethodName = requestURI.substring(rpcIndex + path.length()).trim();
return serviceAndMethodName;
}
protected String serializeException(String id, Exception ex)
{
final JsonObject r = new JsonObject();
String versionName = "jsonrpc";
int code = -32603;
r.add(versionName, new JsonPrimitive("2.0"));
if (id != null) {
r.add("id", new JsonPrimitive(id));
}
GsonBuilder gb = JSONParserWrapper.defaultGsonBuilder();
final JsonObject error = JsonServlet.getError(versionName, code, ex, gb);
r.add("error", error);
GsonBuilder builder = JSONParserWrapper.defaultGsonBuilder();
String out = builder.create().toJson( r);
return out;
}
}
| 04900db4-clienttest | src/org/rapla/rest/server/RaplaAPIPage.java | Java | gpl3 | 5,352 |
package org.rapla.rest.server;
import java.util.ArrayList;
import java.util.List;
import javax.jws.WebParam;
import javax.jws.WebService;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.internal.DynamicTypeImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.servletpages.RaplaPageGenerator;
@WebService
public class RaplaDynamicTypesRestPage extends AbstractRestPage implements RaplaPageGenerator
{
public RaplaDynamicTypesRestPage(RaplaContext context) throws RaplaException {
super(context);
}
public List<DynamicTypeImpl> list(@WebParam(name="classificationType") String classificationType ) throws RaplaException
{
DynamicType[] types = getQuery().getDynamicTypes(classificationType);
List<DynamicTypeImpl> result = new ArrayList<DynamicTypeImpl>();
for ( DynamicType r:types)
{
result.add((DynamicTypeImpl) r);
}
return result;
}
}
| 04900db4-clienttest | src/org/rapla/rest/server/RaplaDynamicTypesRestPage.java | Java | gpl3 | 1,040 |
package org.rapla.rest.server;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.jws.WebParam;
import javax.jws.WebService;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.servletpages.RaplaPageGenerator;
import org.rapla.storage.RaplaSecurityException;
@WebService
public class RaplaResourcesRestPage extends AbstractRestPage implements RaplaPageGenerator
{
private Collection<String> CLASSIFICATION_TYPES = Arrays.asList(new String[] {DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE,DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON});
public RaplaResourcesRestPage(RaplaContext context) throws RaplaException
{
super(context);
}
public List<AllocatableImpl> list(@WebParam(name="user") User user,@WebParam(name="resourceTypes") List<String> resourceTypes, @WebParam(name="attributeFilter") Map<String,String> simpleFilter ) throws RaplaException
{
ClassificationFilter[] filters = getClassificationFilter(simpleFilter, CLASSIFICATION_TYPES, resourceTypes);
Collection<Allocatable> resources = operator.getAllocatables(filters);
List<AllocatableImpl> result = new ArrayList<AllocatableImpl>();
for ( Allocatable r:resources)
{
if ( RaplaComponent.canRead(r, user))
{
result.add((AllocatableImpl) r);
}
}
return result;
}
public AllocatableImpl get(@WebParam(name="user") User user, @WebParam(name="id")String id) throws RaplaException
{
AllocatableImpl resource = (AllocatableImpl) operator.resolve(id, Allocatable.class);
if (!RaplaComponent.canRead(resource, user))
{
throw new RaplaSecurityException("User " + user + " can't read " + resource);
}
return resource;
}
public AllocatableImpl update(@WebParam(name="user") User user, AllocatableImpl resource) throws RaplaException
{
if (!RaplaComponent.canModify(resource, user))
{
throw new RaplaSecurityException("User " + user + " can't modify " + resource);
}
resource.setResolver( operator);
getModification().store( resource );
AllocatableImpl result =(AllocatableImpl) getModification().getPersistant( resource);
return result;
}
public AllocatableImpl create(@WebParam(name="user") User user, AllocatableImpl resource) throws RaplaException
{
if (!getQuery().canCreateReservations(user))
{
throw new RaplaSecurityException("User " + user + " can't modify " + resource);
}
if (resource.getId() != null)
{
throw new RaplaException("Id has to be null for new events");
}
String eventId = operator.createIdentifier(Allocatable.TYPE, 1)[0];
resource.setId( eventId);
resource.setResolver( operator);
resource.setCreateDate( operator.getCurrentTimestamp());
resource.setOwner( user );
getModification().store( resource);
AllocatableImpl result =(AllocatableImpl) getModification().getPersistant( resource);
return result;
}
}
| 04900db4-clienttest | src/org/rapla/rest/server/RaplaResourcesRestPage.java | Java | gpl3 | 3,608 |
package org.rapla.rest.server;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.servletpages.RaplaPageGenerator;
import org.rapla.storage.dbrm.RemoteServer;
public class RaplaAuthRestPage extends RaplaAPIPage implements RaplaPageGenerator
{
public RaplaAuthRestPage(RaplaContext context) throws RaplaContextException {
super(context);
}
@Override
protected String getServiceAndMethodName(HttpServletRequest request)
{
return RemoteServer.class.getName() +"/auth";
}
@Override
public void generatePage(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
super.generatePage(servletContext, request, response);
}
}
| 04900db4-clienttest | src/org/rapla/rest/server/RaplaAuthRestPage.java | Java | gpl3 | 1,026 |
// 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.server;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Date;
import javax.crypto.Mac;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
* Utility function to compute and verify XSRF tokens.
* <p>
* {@link JsonServlet} uses this class to verify tokens appearing in the custom
* <code>xsrfKey</code> JSON request property. The tokens protect against
* cross-site request forgery by depending upon the browser's security model.
* The classic browser security model prohibits a script from site A from
* reading any data received from site B. By sending unforgeable tokens from the
* server and asking the client to return them to us, the client script must
* have had read access to the token at some point and is therefore also from
* our server.
*/
public class SignedToken {
private static final int INT_SZ = 4;
private static final String MAC_ALG = "HmacSHA1";
/**
* Generate a random key for use with the XSRF library.
*
* @return a new private key, base 64 encoded.
*/
public static String generateRandomKey() {
final byte[] r = new byte[26];
new SecureRandom().nextBytes(r);
return encodeBase64(r);
}
private final int maxAge;
private final SecretKeySpec key;
private final SecureRandom rng;
private final int tokenLength;
/**
* Create a new utility, using a randomly generated key.
*
* @param age the number of seconds a token may remain valid.
* @throws XsrfException the JVM doesn't support the necessary algorithms.
*/
public SignedToken(final int age) throws XsrfException {
this(age, generateRandomKey());
}
/**
* Create a new utility, using the specific key.
*
* @param age the number of seconds a token may remain valid.
* @param keyBase64 base 64 encoded representation of the key.
* @throws XsrfException the JVM doesn't support the necessary algorithms.
*/
public SignedToken(final int age, final String keyBase64)
throws XsrfException {
maxAge = age > 5 ? age / 5 : age;
key = new SecretKeySpec(decodeBase64(keyBase64), MAC_ALG);
rng = new SecureRandom();
tokenLength = 2 * INT_SZ + newMac().getMacLength();
}
/** @return maximum age of a signed token, in seconds. */
public int getMaxAge() {
return maxAge > 0 ? maxAge * 5 : maxAge;
}
// /**
// * Get the text of a signed token which is stored in a cookie.
// *
// * @param cookieName the name of the cookie to get the text from.
// * @return the signed text; null if the cookie is not set or the cookie's
// * token was forged.
// */
// public String getCookieText(final String cookieName) {
// final String val = ServletCookieAccess.get(cookieName);
// boolean ok;
// try {
// ok = checkToken(val, null) != null;
// } catch (XsrfException e) {
// ok = false;
// }
// return ok ? ServletCookieAccess.getTokenText(cookieName) : null;
// }
/**
* Generate a new signed token.
*
* @param text the text string to sign. Typically this should be some
* user-specific string, to prevent replay attacks. The text must be
* safe to appear in whatever context the token itself will appear, as
* the text is included on the end of the token.
* @return the signed token. The text passed in <code>text</code> will appear
* after the first ',' in the returned token string.
* @throws XsrfException the JVM doesn't support the necessary algorithms.
*/
public String newToken(final String text, Date now) throws XsrfException {
final int q = rng.nextInt();
final byte[] buf = new byte[tokenLength];
encodeInt(buf, 0, q);
encodeInt(buf, INT_SZ, now(now) ^ q);
computeToken(buf, text);
return encodeBase64(buf) + '$' + text;
}
/**
* Validate a returned token.
*
* @param tokenString a token string previously created by this class.
* @param text text that must have been used during {@link #newToken(String)}
* in order for the token to be valid. If null the text will be taken
* from the token string itself.
* @return true if the token is valid; false if the token is null, the empty
* string, has expired, does not match the text supplied, or is a
* forged token.
* @throws XsrfException the JVM doesn't support the necessary algorithms to
* generate a token. XSRF services are simply not available.
*/
public ValidToken checkToken(final String tokenString, final String text,Date now)
throws XsrfException {
if (tokenString == null || tokenString.length() == 0) {
return null;
}
final int s = tokenString.indexOf('$');
if (s <= 0) {
return null;
}
final String recvText = tokenString.substring(s + 1);
final byte[] in;
try {
String substring = tokenString.substring(0, s);
in = decodeBase64(substring);
} catch (RuntimeException e) {
return null;
}
if (in.length != tokenLength) {
return null;
}
final int q = decodeInt(in, 0);
final int c = decodeInt(in, INT_SZ) ^ q;
final int n = now( now);
if (maxAge > 0 && Math.abs(c - n) > maxAge) {
return null;
}
final byte[] gen = new byte[tokenLength];
System.arraycopy(in, 0, gen, 0, 2 * INT_SZ);
computeToken(gen, text != null ? text : recvText);
if (!Arrays.equals(gen, in)) {
return null;
}
return new ValidToken(maxAge > 0 && c + (maxAge >> 1) <= n, recvText);
}
private void computeToken(final byte[] buf, final String text)
throws XsrfException {
final Mac m = newMac();
m.update(buf, 0, 2 * INT_SZ);
m.update(toBytes(text));
try {
m.doFinal(buf, 2 * INT_SZ);
} catch (ShortBufferException e) {
throw new XsrfException("Unexpected token overflow", e);
}
}
private Mac newMac() throws XsrfException {
try {
final Mac m = Mac.getInstance(MAC_ALG);
m.init(key);
return m;
} catch (NoSuchAlgorithmException e) {
throw new XsrfException(MAC_ALG + " not supported", e);
} catch (InvalidKeyException e) {
throw new XsrfException("Invalid private key", e);
}
}
private static int now(Date now) {
return (int) (now.getTime() / 5000L);
}
private static byte[] decodeBase64(final String s) {
return Base64.decodeBase64(toBytes(s));
}
private static String encodeBase64(final byte[] buf) {
return toString(Base64.encodeBase64(buf));
}
private static void encodeInt(final byte[] buf, final int o, int v) {
buf[o + 3] = (byte) v;
v >>>= 8;
buf[o + 2] = (byte) v;
v >>>= 8;
buf[o + 1] = (byte) v;
v >>>= 8;
buf[o] = (byte) v;
}
private static int decodeInt(final byte[] buf, final int o) {
int r = buf[o] << 8;
r |= buf[o + 1] & 0xff;
r <<= 8;
r |= buf[o + 2] & 0xff;
return (r << 8) | (buf[o + 3] & 0xff);
}
private static byte[] toBytes(final String s) {
final byte[] r = new byte[s.length()];
for (int k = r.length - 1; k >= 0; k--) {
r[k] = (byte) s.charAt(k);
}
return r;
}
private static String toString(final byte[] b) {
final StringBuilder r = new StringBuilder(b.length);
for (int i = 0; i < b.length; i++) {
r.append((char) b[i]);
}
return r.toString();
}
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/server/SignedToken.java | Java | gpl3 | 8,137 |
// 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.server;
/** Indicates the requested method is not known. */
@SuppressWarnings("serial")
class NoSuchRemoteMethodException extends RuntimeException {
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/server/NoSuchRemoteMethodException.java | Java | gpl3 | 771 |
// 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.server;
/** A validated token from {@link SignedToken#checkToken(String, String)} */
public class ValidToken {
private final boolean refresh;
private final String data;
public ValidToken(final boolean ref, final String d) {
refresh = ref;
data = d;
}
/** The text protected by the token's encryption key. */
public String getData() {
return data;
}
/** True if the token's life span is almost half-over and should be renewed. */
public boolean needsRefresh() {
return refresh;
}
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/server/ValidToken.java | Java | gpl3 | 1,140 |
// 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.server;
/** Indicates the requested method is not known. */
@SuppressWarnings("serial")
public class XsrfException extends Exception {
public XsrfException(final String message) {
super(message);
}
public XsrfException(final String message, final Throwable why) {
super(message, why);
}
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/server/XsrfException.java | Java | gpl3 | 926 |
// 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.server;
import java.lang.reflect.Type;
import com.google.gson.InstanceCreator;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
final class CallDeserializer implements
JsonDeserializer<ActiveCall>, InstanceCreator<ActiveCall> {
private final ActiveCall req;
private final JsonServlet server;
CallDeserializer(final ActiveCall call, final JsonServlet jsonServlet) {
req = call;
server = jsonServlet;
}
@Override
public ActiveCall createInstance(final Type type) {
return req;
}
@Override
public ActiveCall deserialize(final JsonElement json, final Type typeOfT,
final JsonDeserializationContext context) throws JsonParseException,
NoSuchRemoteMethodException {
if (!json.isJsonObject()) {
throw new JsonParseException("Expected object");
}
final JsonObject in = json.getAsJsonObject();
req.id = in.get("id");
final JsonElement jsonrpc = in.get("jsonrpc");
final JsonElement version = in.get("version");
if (isString(jsonrpc) && version == null) {
final String v = jsonrpc.getAsString();
if ("2.0".equals(v)) {
req.versionName = "jsonrpc";
req.versionValue = jsonrpc;
} else {
throw new JsonParseException("Expected jsonrpc=2.0");
}
} else if (isString(version) && jsonrpc == null) {
final String v = version.getAsString();
if ("1.1".equals(v)) {
req.versionName = "version";
req.versionValue = version;
} else {
throw new JsonParseException("Expected version=1.1");
}
} else {
throw new JsonParseException("Expected version=1.1 or jsonrpc=2.0");
}
final JsonElement method = in.get("method");
if (!isString(method)) {
throw new JsonParseException("Expected method name as string");
}
req.method = server.lookupMethod(method.getAsString());
if (req.method == null) {
throw new NoSuchRemoteMethodException();
}
final Type[] paramTypes = req.method.getParamTypes();
final JsonElement params = in.get("params");
if (params != null) {
if (!params.isJsonArray()) {
throw new JsonParseException("Expected params array");
}
final JsonArray paramsArray = params.getAsJsonArray();
if (paramsArray.size() != paramTypes.length) {
throw new JsonParseException("Expected " + paramTypes.length
+ " parameter values in params array");
}
final Object[] r = new Object[paramTypes.length];
for (int i = 0; i < r.length; i++) {
final JsonElement v = paramsArray.get(i);
if (v != null) {
r[i] = context.deserialize(v, paramTypes[i]);
}
}
req.params = r;
} else {
if (paramTypes.length != 0) {
throw new JsonParseException("Expected params array");
}
req.params = JsonServlet.NO_PARAMS;
}
return req;
}
private static boolean isString(final JsonElement e) {
return e != null && e.isJsonPrimitive()
&& e.getAsJsonPrimitive().isString();
}
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/server/CallDeserializer.java | Java | gpl3 | 3,867 |
// 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.server;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.jws.WebService;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.rapla.components.util.ParseDateException;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.entities.DependencyException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.logger.Logger;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.rest.gwtjsonrpc.common.JSONParserWrapper;
import org.rapla.rest.gwtjsonrpc.common.JsonConstants;
import org.rapla.rest.jsonpatch.mergepatch.server.JsonMergePatch;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
/**
* Forward JSON based RPC requests onto services.
* <b>JSON-RPC 1.1</b><br>
* Calling conventions match the JSON-RPC 1.1 working draft from 7 August 2006
* (<a href="http://json-rpc.org/wd/JSON-RPC-1-1-WD-20060807.html">draft</a>).
* Only positional parameters are supported.
* <p>
* <b>JSON-RPC 2.0</b><br>
* Calling conventions match the JSON-RPC 2.0 specification.
* <p>
* When supported by the browser/client, the "gzip" encoding is used to compress
* the resulting JSON, reducing transfer time for the response data.
*/
public class JsonServlet {
public final static String JSON_METHOD = "method";
static final Object[] NO_PARAMS = {};
Class class1;
private Map<String, MethodHandle> myMethods;
Logger logger;
public JsonServlet(final Logger logger, final Class class1) throws RaplaException {
this.class1 = class1;
this.logger = logger;
myMethods = methods(class1);
if (myMethods.isEmpty()) {
throw new RaplaException("No public service methods declared in " + class1 + " Did you forget the javax.jws.WebService annotation?");
}
}
public Class getInterfaceClass() {
return class1;
}
/** Create a GsonBuilder to parse a request or return a response. */
protected GsonBuilder createGsonBuilder() {
return JSONParserWrapper.defaultGsonBuilder();
}
/**
* Lookup a method implemented by this servlet.
*
* @param methodName
* name of the method.
* @return the method handle; null if the method is not declared.
*/
protected MethodHandle lookupMethod(final String methodName) {
return myMethods.get(methodName);
}
/** @return maximum size of a JSON request, in bytes */
protected int maxRequestSize() {
// Our default limit of 100 MB should be sufficient for nearly any
// application. It takes a long time to format this on the client
// or to upload it.
//
return 100 * 1024 * 1024;
}
public void service(final HttpServletRequest req, final HttpServletResponse resp, ServletContext servletContext, final Object service) throws IOException {
ActiveCall call = new ActiveCall(req, resp);
call.noCache();
// if (!acceptJSON(call)) {
// textError(call, SC_BAD_REQUEST, "Must Accept " +
// JsonConstants.JSON_TYPE);
// return;
// }
boolean isPatch = req.getMethod().equals("PATCH");
doService(service, call);
if ( isPatch && !call.hasFailed())
{
Object result = call.result;
call = new ActiveCall(req, resp);
try
{
final Gson gs = createGsonBuilder().create();
JsonElement unpatchedObject = gs.toJsonTree(result);
String patchBody = readBody(call);
JsonElement patchElement = new JsonParser().parse( patchBody);
final JsonMergePatch patch = JsonMergePatch.fromJson(patchElement);
final JsonElement patchedObject = patch.apply(unpatchedObject);
Object patchMethod = req.getAttribute("patchMethod");
if ( patchMethod == null )
{
throw new RaplaException("request attribute patchMethod or patchParameter is missing.");
}
req.setAttribute("method", patchMethod);
String patchedObjectToString =gs.toJson( patchedObject);
req.setAttribute("postBody", patchedObjectToString);
doService(service, call);
}
catch (Exception ex)
{
call.externalFailure = ex;
}
}
final String out = formatResult(call);
RPCServletUtils.writeResponse(servletContext, call.httpResponse, out, out.length() > 256 && RPCServletUtils.acceptsGzipEncoding(call.httpRequest));
}
public void serviceError(final HttpServletRequest req, final HttpServletResponse resp, ServletContext servletContext, final Throwable ex) throws IOException {
final ActiveCall call = new ActiveCall(req, resp);
call.versionName = "jsonrpc";
call.versionValue = new JsonPrimitive("2.0");
call.noCache();
call.onInternalFailure(ex);
final String out = formatResult(call);
RPCServletUtils.writeResponse(servletContext, call.httpResponse, out, out.length() > 256 && RPCServletUtils.acceptsGzipEncoding(call.httpRequest));
}
// private boolean acceptJSON(final CallType call) {
// final String accepts = call.httpRequest.getHeader("Accept");
// if (accepts == null) {
// // A really odd client, it didn't send us an accept header?
// //
// return false;
// }
//
// if (JsonConstants.JSON_TYPE.equals(accepts)) {
// // Common case, as our JSON client side code sets only this
// //
// return true;
// }
//
// // The browser may take JSON, but also other types. The popular
// // Opera browser will add other accept types to our AJAX requests
// // even though our AJAX handler wouldn't be able to actually use
// // the data. The common case for these is to start with our own
// // type, then others, so we special case it before we go through
// // the expense of splitting the Accepts header up.
// //
// if (accepts.startsWith(JsonConstants.JSON_TYPE + ",")) {
// return true;
// }
// final String[] parts = accepts.split("[ ,;][ ,;]*");
// for (final String p : parts) {
// if (JsonConstants.JSON_TYPE.equals(p)) {
// return true;
// }
// }
//
// // Assume the client is busted and won't take JSON back.
// //
// return false;
// }
private void doService(final Object service, final ActiveCall call) throws IOException {
try {
try {
String httpMethod = call.httpRequest.getMethod();
if ("GET".equals(httpMethod) || "PATCH".equals(httpMethod)) {
parseGetRequest(call);
} else if ("POST".equals(httpMethod)) {
parsePostRequest(call);
} else {
call.httpResponse.setStatus(SC_BAD_REQUEST);
call.onFailure(new Exception("Unsupported HTTP method"));
return;
}
} catch (JsonParseException err) {
if (err.getCause() instanceof NoSuchRemoteMethodException) {
// GSON seems to catch our own exception and wrap it...
//
throw (NoSuchRemoteMethodException) err.getCause();
}
call.httpResponse.setStatus(SC_BAD_REQUEST);
call.onFailure(new Exception("Error parsing request " + err.getMessage(), err));
return;
}
} catch (NoSuchRemoteMethodException err) {
call.httpResponse.setStatus(SC_NOT_FOUND);
call.onFailure(new Exception("No such service method"));
return;
}
if (!call.isComplete()) {
call.method.invoke(service, call.params, call);
}
}
private void parseGetRequest(final ActiveCall call) {
final HttpServletRequest req = call.httpRequest;
if ("2.0".equals(req.getParameter("jsonrpc"))) {
final JsonObject d = new JsonObject();
d.addProperty("jsonrpc", "2.0");
d.addProperty("method", req.getParameter("method"));
d.addProperty("id", req.getParameter("id"));
try {
String parameter = req.getParameter("params");
final byte[] params = parameter.getBytes("ISO-8859-1");
JsonElement parsed;
try {
parsed = new JsonParser().parse(parameter);
} catch (JsonParseException e) {
final String p = new String(Base64.decodeBase64(params), "UTF-8");
parsed = new JsonParser().parse(p);
}
d.add("params", parsed);
} catch (UnsupportedEncodingException e) {
throw new JsonParseException("Cannot parse params", e);
}
try {
final GsonBuilder gb = createGsonBuilder();
gb.registerTypeAdapter(ActiveCall.class, new CallDeserializer(call, this));
gb.create().fromJson(d, ActiveCall.class);
} catch (JsonParseException err) {
call.method = null;
call.params = null;
throw err;
}
} else { /* JSON-RPC 1.1 or GET REST API */
String body = (String)req.getAttribute("postBody");
mapRequestToCall(call, req, body);
}
}
public void mapRequestToCall(final ActiveCall call, final HttpServletRequest req, String body) {
final Gson gs = createGsonBuilder().create();
String methodName = (String) req.getAttribute(JSON_METHOD);
if (methodName != null) {
call.versionName = "jsonrpc";
call.versionValue = new JsonPrimitive("2.0");
} else {
methodName = req.getParameter("method");
call.versionName = "version";
call.versionValue = new JsonPrimitive("1.1");
}
call.method = lookupMethod(methodName);
if (call.method == null) {
throw new NoSuchRemoteMethodException();
}
final Type[] paramTypes = call.method.getParamTypes();
String[] paramNames = call.method.getParamNames();
final Object[] r = new Object[paramTypes.length];
for (int i = 0; i < r.length; i++) {
Type type = paramTypes[i];
String name = paramNames[i];
if (name == null && !call.versionName.equals("jsonrpc")) {
name = "param" + i;
}
{
// First search in the request attributes
Object attribute = req.getAttribute(name);
Object paramValue;
if ( attribute != null)
{
paramValue =attribute;
Class attributeClass = attribute.getClass();
// we try to convert string and jsonelements to the parameter type (if the parameter type is not string or jsonelement)
if ( attributeClass.equals(String.class) && !type.equals(String.class) )
{
JsonParser parser = new JsonParser();
JsonElement parsed = parser.parse((String)attribute);
paramValue = gs.fromJson(parsed, type);
}
else if (JsonElement.class.isAssignableFrom(attributeClass) && !type.equals(JsonElement.class))
{
JsonElement parsed = (JsonElement) attribute;
paramValue = gs.fromJson(parsed, type);
}
else
{
paramValue =attribute;
}
}
// then in request parameters
else
{
String v = null;
v = req.getParameter(name);
// if not found in request use body
if ( v == null && body != null && !body.isEmpty())
{
v = body;
}
if (v == null) {
paramValue = null;
} else if (type == String.class) {
paramValue = v;
} else if (type == Date.class) {
// special case for handling date parameters with the
// ':' char i it
try {
paramValue = SerializableDateTimeFormat.INSTANCE.parseTimestamp(v);
} catch (ParseDateException e) {
throw new JsonSyntaxException(v, e);
}
} else if (type instanceof Class<?> && ((Class<?>) type).isPrimitive()) {
// Primitive type, use the JSON representation of that
// type.
//
paramValue = gs.fromJson(v, type);
} else {
// Assume it is like a java.sql.Timestamp or something
// and treat
// the value as JSON string.
//
JsonParser parser = new JsonParser();
JsonElement parsed = parser.parse(v);
paramValue = gs.fromJson(parsed, type);
}
}
r[i] = paramValue;
}
}
call.params = r;
}
private static boolean isBodyJson(final ActiveCall call) {
String type = call.httpRequest.getContentType();
if (type == null) {
return false;
}
int semi = type.indexOf(';');
if (semi >= 0) {
type = type.substring(0, semi).trim();
}
return JsonConstants.JSON_TYPE.equals(type);
}
private static boolean isBodyUTF8(final ActiveCall call) {
String enc = call.httpRequest.getCharacterEncoding();
if (enc == null) {
enc = "";
}
return enc.toLowerCase().contains(JsonConstants.JSON_ENC.toLowerCase());
}
private String readBody(final ActiveCall call) throws IOException {
if (!isBodyJson(call)) {
throw new JsonParseException("Invalid Request Content-Type");
}
if (!isBodyUTF8(call)) {
throw new JsonParseException("Invalid Request Character-Encoding");
}
final int len = call.httpRequest.getContentLength();
if (len < 0) {
throw new JsonParseException("Invalid Request Content-Length");
}
if (len == 0) {
throw new JsonParseException("Invalid Request POST Body Required");
}
if (len > maxRequestSize()) {
throw new JsonParseException("Invalid Request POST Body Too Large");
}
final InputStream in = call.httpRequest.getInputStream();
if (in == null) {
throw new JsonParseException("Invalid Request POST Body Required");
}
try {
final byte[] body = new byte[len];
int off = 0;
while (off < len) {
final int n = in.read(body, off, len - off);
if (n <= 0) {
throw new JsonParseException("Invalid Request Incomplete Body");
}
off += n;
}
final CharsetDecoder d = Charset.forName(JsonConstants.JSON_ENC).newDecoder();
d.onMalformedInput(CodingErrorAction.REPORT);
d.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
return d.decode(ByteBuffer.wrap(body)).toString();
} catch (CharacterCodingException e) {
throw new JsonParseException("Invalid Request Not UTF-8", e);
}
} finally {
in.close();
}
}
private void parsePostRequest(final ActiveCall call) throws UnsupportedEncodingException, IOException {
try {
HttpServletRequest request = call.httpRequest;
String attribute = (String)request.getAttribute(JSON_METHOD);
String postBody = readBody(call);
final GsonBuilder gb = createGsonBuilder();
if ( attribute != null)
{
mapRequestToCall(call, request, postBody);
}
else
{
gb.registerTypeAdapter(ActiveCall.class, new CallDeserializer(call, this));
Gson mapper = gb.create();
mapper.fromJson(postBody, ActiveCall.class);
}
} catch (JsonParseException err) {
call.method = null;
call.params = null;
throw err;
}
}
private String formatResult(final ActiveCall call) throws UnsupportedEncodingException, IOException {
final GsonBuilder gb = createGsonBuilder();
gb.registerTypeAdapter(call.getClass(), new JsonSerializer<ActiveCall>() {
@Override
public JsonElement serialize(final ActiveCall src, final Type typeOfSrc, final JsonSerializationContext context) {
if (call.externalFailure != null) {
final String msg;
if (call.method != null) {
msg = "Error in " + call.method.getName();
} else {
msg = "Error";
}
logger.error(msg, call.externalFailure);
}
Throwable failure = src.externalFailure != null ? src.externalFailure : src.internalFailure;
Object result = src.result;
if (result instanceof FutureResult) {
try {
result = ((FutureResult) result).get();
} catch (Exception e) {
failure = e;
}
}
final JsonObject r = new JsonObject();
if (src.versionName == null || src.versionValue == null)
{
r.add("jsonrpc", new JsonPrimitive("2.0"));
}
else
{
r.add(src.versionName, src.versionValue);
}
if (src.id != null) {
r.add("id", src.id);
}
if (failure != null) {
final int code = to2_0ErrorCode(src);
final JsonObject error = getError(src.versionName, code, failure, gb);
r.add("error", error);
} else {
r.add("result", context.serialize(result));
}
return r;
}
});
Gson create = gb.create();
final StringWriter o = new StringWriter();
create.toJson(call, o);
o.close();
String string = o.toString();
return string;
}
private int to2_0ErrorCode(final ActiveCall src) {
final Throwable e = src.externalFailure;
final Throwable i = src.internalFailure;
if (e instanceof NoSuchRemoteMethodException || i instanceof NoSuchRemoteMethodException) {
return -32601 /* Method not found. */;
}
if (e instanceof IllegalArgumentException || i instanceof IllegalArgumentException) {
return -32602 /* Invalid paramters. */;
}
if (e instanceof JsonParseException || i instanceof JsonParseException) {
return -32700 /* Parse error. */;
}
return -32603 /* Internal error. */;
}
// private static void textError(final ActiveCall call, final int status,
// final String message) throws IOException {
// final HttpServletResponse r = call.httpResponse;
// r.setStatus(status);
// r.setContentType("text/plain; charset=" + ENC);
//
// final Writer w = new OutputStreamWriter(r.getOutputStream(), ENC);
// try {
// w.write(message);
// } finally {
// w.close();
// }
// }
public static JsonObject getError(String version, int code, Throwable failure, GsonBuilder gb) {
final JsonObject error = new JsonObject();
String message = failure.getMessage();
if (message == null) {
message = failure.toString();
}
Gson gson = gb.create();
if ("jsonrpc".equals(version)) {
error.addProperty("code", code);
error.addProperty("message", message);
JsonObject errorData = new JsonObject();
errorData.addProperty("exception", failure.getClass().getName());
// FIXME Replace with generic solution for exception param
// serialization
if (failure instanceof DependencyException) {
JsonArray params = new JsonArray();
for (String dep : ((DependencyException) failure).getDependencies()) {
params.add(new JsonPrimitive(dep));
}
errorData.add("params", params);
}
JsonArray stackTrace = new JsonArray();
for (StackTraceElement el : failure.getStackTrace()) {
JsonElement jsonRep = gson.toJsonTree(el);
stackTrace.add( jsonRep);
}
errorData.add("stacktrace", stackTrace);
error.add("data", errorData);
} else {
error.addProperty("name", "JSONRPCError");
error.addProperty("code", 999);
error.addProperty("message", message);
}
return error;
}
private static Map<String, MethodHandle> methods(Class class1) {
final Class d = findInterface(class1);
if (d == null) {
return Collections.<String, MethodHandle> emptyMap();
}
final Map<String, MethodHandle> r = new HashMap<String, MethodHandle>();
for (final Method m : d.getMethods()) {
if (!Modifier.isPublic(m.getModifiers())) {
continue;
}
final MethodHandle h = new MethodHandle(m);
r.put(h.getName(), h);
}
return Collections.unmodifiableMap(r);
}
private static Class findInterface(Class<?> c) {
while (c != null) {
if ( c.getAnnotation(WebService.class) != null) {
return c;
}
for (final Class<?> i : c.getInterfaces()) {
final Class r = findInterface(i);
if (r != null) {
return r;
}
}
c = c.getSuperclass();
}
return null;
}
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/server/JsonServlet.java | Java | gpl3 | 24,724 |
// 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.server;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import javax.jws.WebParam;
/**
* Pairing of a specific implementation and method.
*/
public class MethodHandle {
//private final RemoteJsonService imp;
private final Method method;
private final Type[] parameterTypes;
private String[] parameterNames;
/**
* Create a new handle for a specific service implementation and method.
*
* @param imp instance of the service all calls will be made on.
* @param method Java method to invoke on <code>imp</code>. The last parameter
* of the method must accept an {@link org.rapla.rest.gwtjsonrpc.common.AsyncCallback}
* and the method must return void.
*/
MethodHandle( final Method method) {
//this.imp = imp;
this.method = method;
final Type[] args = method.getGenericParameterTypes();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
parameterNames = new String[args.length ];
for (int i=0;i<args.length;i++)
{
Annotation[] annot= parameterAnnotations[i];
String paramterName = null;
for ( Annotation a:annot)
{
Class<? extends Annotation> annotationType = a.annotationType();
if ( annotationType.equals( WebParam.class))
{
paramterName = ((WebParam)a).name();
}
}
if ( paramterName != null)
{
parameterNames[i] = paramterName;
}
}
parameterTypes = new Type[args.length ];
System.arraycopy(args, 0, parameterTypes, 0, parameterTypes.length);
}
/**
* @return unique name of the method within the service.
*/
public String getName() {
return method.getName();
}
/** @return an annotation attached to the method's description. */
public <T extends Annotation> T getAnnotation(final Class<T> t) {
return method.getAnnotation(t);
}
/**
* @return true if this method requires positional arguments.
*/
public Type[] getParamTypes() {
return parameterTypes;
}
public String[] getParamNames()
{
return parameterNames;
}
/**
* Invoke this method with the specified arguments, updating the callback.
*
* @param arguments arguments to the method. May be the empty array if no
* parameters are declared beyond the AsyncCallback, but must not be
* null.
* @param imp the implementing object
* @param callback the callback the implementation will invoke onSuccess or
* onFailure on as it performs its work. Only the last onSuccess or
* onFailure invocation matters.
*/
public void invoke(final Object imp,final Object[] arguments,final ActiveCall callback) {
try {
Object result = method.invoke(imp, arguments);
callback.onSuccess(result);
} catch (InvocationTargetException e) {
final Throwable c = e.getCause();
if (c != null) {
callback.onInternalFailure(c);
} else {
callback.onInternalFailure(e);
}
} catch (IllegalAccessException e) {
callback.onInternalFailure(e);
} catch (RuntimeException e) {
callback.onInternalFailure(e);
} catch (Error e) {
callback.onInternalFailure(e);
}
}
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/server/MethodHandle.java | Java | gpl3 | 3,914 |
// 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.server;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.rest.gwtjsonrpc.common.AsyncCallback;
import com.google.gson.JsonElement;
/** An active RPC call. */
public class ActiveCall implements AsyncCallback<Object> {
protected final HttpServletRequest httpRequest;
protected final HttpServletResponse httpResponse;
JsonElement id;
String versionName;
JsonElement versionValue;
MethodHandle method;
Object[] params;
Object result;
Throwable externalFailure;
Throwable internalFailure;
/**
* Create a new call.
*
* @param req the request.
* @param resp the response.
*/
public ActiveCall(final HttpServletRequest req, final HttpServletResponse resp) {
httpRequest = req;
httpResponse = resp;
}
/**
* @return true if this call has something to send to the client; false if the
* call still needs to be computed further in order to come up with a
* success return value or a failure
*/
public final boolean isComplete() {
return result != null || externalFailure != null || internalFailure != null;
}
@Override
public final void onSuccess(final Object result) {
this.result = result;
this.externalFailure = null;
this.internalFailure = null;
}
@Override
public void onFailure(final Throwable error) {
this.result = null;
this.externalFailure = error;
this.internalFailure = null;
}
public final void onInternalFailure(final Throwable error) {
this.result = null;
this.externalFailure = null;
this.internalFailure = error;
}
/** Mark the response to be uncached by proxies and browsers. */
public void noCache() {
httpResponse.setHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT");
httpResponse.setHeader("Pragma", "no-cache");
httpResponse.setHeader("Cache-Control", "no-cache, must-revalidate");
}
public boolean hasFailed() {
return externalFailure != null || internalFailure != null;
}
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/server/ActiveCall.java | Java | gpl3 | 2,653 |
// 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.server;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** Utility to handle writing JSON-RPC responses, possibly compressed. */
public class RPCServletUtils {
public static boolean acceptsGzipEncoding(HttpServletRequest request) {
String accepts = request.getHeader("Accept-Encoding");
return accepts != null && accepts.indexOf("gzip") != -1;
}
public static void writeResponse(ServletContext ctx, HttpServletResponse res,
String responseContent, boolean encodeWithGzip) throws IOException {
byte[] data = responseContent.getBytes("UTF-8");
if (encodeWithGzip) {
ByteArrayOutputStream buf = new ByteArrayOutputStream(data.length);
GZIPOutputStream gz = new GZIPOutputStream(buf);
try {
gz.write(data);
gz.finish();
gz.flush();
res.setHeader("Content-Encoding", "gzip");
data = buf.toByteArray();
} catch (IOException e) {
ctx.log("Unable to compress response", e);
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
} finally {
gz.close();
}
}
res.setContentLength(data.length);
res.setContentType("application/json; charset=utf-8");
res.setStatus(HttpServletResponse.SC_OK);
res.setHeader("Content-Disposition", "attachment");
res.getOutputStream().write(data);
}
private RPCServletUtils() {
}
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/server/RPCServletUtils.java | Java | gpl3 | 2,195 |
package org.rapla.rest.gwtjsonrpc.common;
@java.lang.annotation.Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(value={java.lang.annotation.ElementType.METHOD})
public @interface ResultType {
Class value();
Class container() default Object.class;
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/common/ResultType.java | Java | gpl3 | 296 |
// 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.common;
/** Mock object for AsyncCallbacks which do not need to return data. */
public class VoidResult {
public static final VoidResult INSTANCE = new VoidResult();
protected VoidResult() {
}
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/common/VoidResult.java | Java | gpl3 | 822 |
package org.rapla.rest.gwtjsonrpc.common;
public class ResultImpl<T> implements FutureResult<T>
{
Exception ex;
T result;
public static VoidResultImpl VOID = new VoidResultImpl();
public static class VoidResultImpl extends ResultImpl<org.rapla.rest.gwtjsonrpc.common.VoidResult>
{
VoidResultImpl() {
}
public VoidResultImpl(Exception ex)
{
super( ex);
}
}
protected ResultImpl()
{
}
public ResultImpl(T result) {
this.result = result;
}
public ResultImpl(Exception ex)
{
this.ex = ex;
}
@Override
public T get() throws Exception {
if ( ex != null)
{
throw ex;
}
return result;
}
@Override
public T get(long wait) throws Exception {
if ( ex != null)
{
throw ex;
}
return result;
}
@Override
public void get(AsyncCallback<T> callback) {
if ( ex != null)
{
callback.onFailure( ex);
}
else
{
callback.onSuccess(result);
}
}
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/common/ResultImpl.java | Java | gpl3 | 920 |
package org.rapla.rest.gwtjsonrpc.common;
public interface FutureResult<T> {
public T get() throws Exception;
public T get(long wait) throws Exception;
public void get(AsyncCallback<T> callback);
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/common/FutureResult.java | Java | gpl3 | 203 |
package org.rapla.rest.gwtjsonrpc.common;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.entities.configuration.internal.RaplaMapImpl;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.InstanceCreator;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.ConstructorConstructor;
import com.google.gson.internal.Excluder;
import com.google.gson.internal.bind.MapTypeAdapterFactory;
import com.google.gson.internal.bind.ReflectiveTypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
public class JSONParserWrapper {
/** Create a default GsonBuilder with some extra types defined. */
public static GsonBuilder defaultGsonBuilder() {
final GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(java.util.Set.class,
new InstanceCreator<java.util.Set<Object>>() {
@Override
public Set<Object> createInstance(final Type arg0) {
return new LinkedHashSet<Object>();
}
});
Map<Type, InstanceCreator<?>> instanceCreators = new LinkedHashMap<Type,InstanceCreator<?>>();
instanceCreators.put(Map.class, new InstanceCreator<Map>() {
public Map createInstance(Type type) {
return new LinkedHashMap();
}
});
ConstructorConstructor constructorConstructor = new ConstructorConstructor(instanceCreators);
FieldNamingStrategy fieldNamingPolicy = FieldNamingPolicy.IDENTITY;
Excluder excluder = Excluder.DEFAULT;
final ReflectiveTypeAdapterFactory reflectiveTypeAdapterFactory = new ReflectiveTypeAdapterFactory(constructorConstructor, fieldNamingPolicy, excluder);
gb.registerTypeAdapterFactory(new MapTypeAdapterFactory(constructorConstructor, false));
gb.registerTypeAdapterFactory(new MyAdaptorFactory(reflectiveTypeAdapterFactory));
gb.registerTypeAdapter(java.util.Date.class, new GmtDateTypeAdapter());
GsonBuilder configured = gb.disableHtmlEscaping().setPrettyPrinting();
return configured;
}
public static class GmtDateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
private GmtDateTypeAdapter() {
}
@Override
public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
String timestamp = SerializableDateTimeFormat.INSTANCE.formatTimestamp(date);
return new JsonPrimitive(timestamp);
}
@Override
public synchronized Date deserialize(JsonElement jsonElement, Type type,JsonDeserializationContext jsonDeserializationContext) {
String asString = jsonElement.getAsString();
try {
Date timestamp = SerializableDateTimeFormat.INSTANCE.parseTimestamp(asString);
return timestamp;
} catch (Exception e) {
throw new JsonSyntaxException(asString, e);
}
}
}
public static class MyAdaptorFactory implements TypeAdapterFactory
{
ReflectiveTypeAdapterFactory reflectiveTypeAdapterFactory;
public MyAdaptorFactory(ReflectiveTypeAdapterFactory reflectiveTypeAdapterFactory) {
this.reflectiveTypeAdapterFactory = reflectiveTypeAdapterFactory;
}
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
Class<? super T> raw = type.getRawType();
if (!RaplaMapImpl.class.isAssignableFrom(raw)) {
return null; // it's a primitive!
}
return reflectiveTypeAdapterFactory.create(gson, type);
}
}
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/common/JSONParserWrapper.java | Java | gpl3 | 4,093 |
// 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.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Specify the json rpc protocol version and transport mechanism to be used for
* a service.
* <p>
* Default is version 1.1 over HTTP POST.
* <p>
* <b>Note: if you use the generated (servlet), only version 1.1 over HTTP POST
* is supported</b>.
*/
@Target(ElementType.TYPE)
public @interface RpcImpl {
/**
* JSON-RPC protocol versions.
*/
public enum Version {
/**
* Version 1.1.
*
* @see <a
* href="http://groups.google.com/group/json-rpc/web/json-rpc-1-1-wd">Spec</a>
*/
V1_1,
/**
* Version 2.0.
*
* @see <a
* href="http://groups.google.com/group/json-rpc/web/json-rpc-1-2-proposal">Spec</a>
*/
V2_0
}
/**
* Supported transport mechanisms.
*/
public enum Transport {
HTTP_POST, HTTP_GET
}
/**
* Specify the JSON-RPC version. Default is version 1.1.
*/
Version version() default Version.V1_1;
/**
* Specify the transport protocol used to make the RPC call. Default is HTTP
* POST.
*/
Transport transport() default Transport.HTTP_POST;
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/common/RpcImpl.java | Java | gpl3 | 1,784 |
// 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.common;
/**
* Marker interface for JSON based RPC. Should be replaced with a marker annotation when generator supports annotations
* <p>
* Application service interfaces should extend this interface:
*
* <pre>
* public interface FooService extends RemoteJsonService ...
* </pre>
* <p>
* and declare each method as returning void and accepting {@link org.rapla.rest.gwtjsonrpc.common.AsyncCallback}
* as the final parameter, with a concrete type specified as the result type:
*
* <pre>
* public interface FooService extends RemoteJsonService {
* public void fooItUp(AsyncCallback<ResultType> callback);
* }
* </pre>
* <p>
* Instances of the interface can be obtained in the client and configured to
* reference a particular JSON server:
*
* <pre>
* FooService mysvc = GWT.create(FooService.class);
* ((ServiceDefTarget) mysvc).setServiceEntryPoint(GWT.getModuleBaseURL()
* + "FooService");
*</pre>
* <p>
* Calling conventions match the JSON-RPC 1.1 working draft from 7 August 2006
* (<a href="http://json-rpc.org/wd/JSON-RPC-1-1-WD-20060807.html">draft</a>).
* Only positional parameters are supported.
* <p>
* JSON service callbacks may also be declared; see
* {@link com.google.gwtjsonrpc.client.CallbackHandle}.
*/
public interface RemoteJsonService {
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/common/RemoteJsonService.java | Java | gpl3 | 1,932 |
// 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.common;
/** Shared constants between client and server implementations. */
public class JsonConstants {
/** Proper Content-Type header value for JSON encoded data. */
public static final String JSON_TYPE = "application/json";
/** Character encoding preferred for JSON text. */
public static final String JSON_ENC = "UTF-8";
/** Request Content-Type header for JSON data. */
public static final String JSON_REQ_CT = JSON_TYPE + "; charset=utf-8";
/** Json-rpc 2.0: Proper Content-Type header value for JSON encoded data. */
public static final String JSONRPC20_TYPE = "application/json-rpc";
/** Json-rpc 2.0: Request Content-Type header for JSON data. */
public static final String JSONRPC20_REQ_CT = JSON_TYPE + "; charset=utf-8";
/** Json-rpc 2.0: Content types that we SHOULD accept as being valid */
public static final String JSONRPC20_ACCEPT_CTS =
JSON_TYPE + ",application/json,application/jsonrequest";
/** Error message when xsrfKey in request is missing or invalid. */
public static final String ERROR_INVALID_XSRF = "Invalid xsrfKey in request";
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/common/JsonConstants.java | Java | gpl3 | 1,719 |
// Copyright 2012 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.common;
/** Invoked with the result (or error) of an RPC. */
public interface AsyncCallback<T> {
/**
* Called when an asynchronous call fails to complete normally.
* {@link com.google.gwt.user.client.rpc.InvocationException}s,
* or checked exceptions thrown by the service method are examples of the type
* of failures that can be passed to this method.
*
* @param caught failure encountered while executing a remote procedure call
*/
void onFailure(Throwable caught);
/**
* Called when an asynchronous call completes successfully.
*
* @param result the return value of the remote produced call
*/
void onSuccess(T result);
}
| 04900db4-clienttest | src/org/rapla/rest/gwtjsonrpc/common/AsyncCallback.java | Java | gpl3 | 1,288 |
package org.rapla.examples;
import java.util.Locale;
import org.rapla.RaplaMainContainer;
import org.rapla.entities.domain.Allocatable;
import org.rapla.facade.ClientFacade;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.logger.ConsoleLogger;
/** Simple demonstration for connecting your app and importing some users. See sources*/
public class RaplaConnectorTest
{
public static void main(String[] args) {
final ConsoleLogger logger = new ConsoleLogger( ConsoleLogger.LEVEL_INFO);
try
{
// Connects to http://localhost:8051/
// and calls rapla/rpc/methodNames for interacting
StartupEnvironment env = new SimpleConnectorStartupEnvironment( "localhost", 8051,"/", false, logger);
RaplaMainContainer container = new RaplaMainContainer( env);
RaplaContext context = container.getContext();
// get an interface to the facade and login
ClientFacade facade = context.lookup(ClientFacade.class);
if ( !facade.login( "admin", "".toCharArray()) ) {
throw new RaplaException("Can't login");
}
// query resouce
Allocatable firstResource = facade.getAllocatables() [0] ;
logger.info( firstResource.getName( Locale.getDefault()));
// cleanup the Container
container.dispose();
}
catch ( Exception e )
{
logger.error("Could not start test ", e );
}
}
}
| 04900db4-clienttest | src/org/rapla/examples/RaplaConnectorTest.java | Java | gpl3 | 1,670 |
package org.rapla.examples;
import java.net.MalformedURLException;
import java.net.URL;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.logger.Logger;
/** Startup environment that creates an Facade Object to communicate with an rapla server instance.
*/
public class SimpleConnectorStartupEnvironment implements StartupEnvironment
{
DefaultConfiguration config;
URL server;
Logger logger;
public SimpleConnectorStartupEnvironment(final String host, final Logger logger) throws MalformedURLException
{
this( host, 8051, "/",false, logger);
}
public SimpleConnectorStartupEnvironment(final String host, final int hostPort, String contextPath,boolean isSecure, final Logger logger) throws MalformedURLException {
this.logger = logger;
config = new DefaultConfiguration("rapla-config");
final DefaultConfiguration facadeConfig = new DefaultConfiguration("facade");
facadeConfig.setAttribute("id","facade");
final DefaultConfiguration remoteConfig = new DefaultConfiguration("remote-storage");
remoteConfig.setAttribute("id","remote");
DefaultConfiguration serverHost =new DefaultConfiguration("server");
serverHost.setValue( "${download-url}" );
remoteConfig.addChild( serverHost );
config.addChild( facadeConfig );
config.addChild( remoteConfig );
String protocoll = "http";
if ( isSecure )
{
protocoll = "https";
}
if ( !contextPath.startsWith("/"))
{
contextPath = "/" + contextPath ;
}
if ( !contextPath.endsWith("/"))
{
contextPath = contextPath + "/";
}
server = new URL(protocoll,host, hostPort, contextPath);
}
public Configuration getStartupConfiguration() throws RaplaException
{
return config;
}
public int getStartupMode()
{
return CONSOLE;
}
public URL getContextRootURL() throws RaplaException
{
return null;
}
public Logger getBootstrapLogger()
{
return logger;
}
public URL getDownloadURL() throws RaplaException
{
return server;
}
public URL getConfigURL() throws RaplaException {
return null;
}
}
| 04900db4-clienttest | src/org/rapla/examples/SimpleConnectorStartupEnvironment.java | Java | gpl3 | 2,457 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.examples;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import org.rapla.RaplaMainContainer;
import org.rapla.components.util.Tools;
import org.rapla.entities.Category;
import org.rapla.entities.User;
import org.rapla.facade.ClientFacade;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.logger.ConsoleLogger;
/**Demonstration for connecting your app and importing some users */
public class RaplaImportUsers {
public static void main(String[] args) {
if ( args.length< 1 ) {
System.out.println("Usage: filename");
System.out.println("Example: users.csv ");
return;
}
final ConsoleLogger logger = new ConsoleLogger( ConsoleLogger.LEVEL_INFO);
try
{
StartupEnvironment env = new SimpleConnectorStartupEnvironment( "localhost", 8051, "/",false, logger);
RaplaMainContainer container = new RaplaMainContainer( env);
importFile( container.getContext(), args[0] );
// cleanup the Container
container.dispose();
}
catch ( Exception e )
{
logger.error("Could not start test ", e );
}
}
private static void importFile(RaplaContext context,String filename) throws Exception {
System.out.println(" Please enter the admin password ");
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String adminPass = stdin.readLine();
// get an interface to the facade and login
ClientFacade facade = context.lookup(ClientFacade.class);
if ( !facade.login("admin", adminPass.toCharArray() ) ) {
throw new RaplaException("Can't login");
}
FileReader reader = new FileReader( filename );
importUsers( facade, reader);
reader.close();
facade.logout();
}
public static void importUsers(ClientFacade facade, Reader reader) throws RaplaException, IOException {
String[][] entries = Tools.csvRead( reader, 5 );
Category rootCategory = facade.getUserGroupsCategory();
for ( int i=0;i<entries.length; i++ ) {
String[] lineEntries = entries[i];
String name = lineEntries[0];
String email = lineEntries[1];
String username = lineEntries[2];
String groupKey = lineEntries[3];
String password = lineEntries[4];
User user = facade.newUser();
user.setUsername( username );
user.setName ( name );
user.setEmail( email );
Category group = findCategory( rootCategory, groupKey );
if (group != null) {
user.addGroup( group );
}
facade.store(user);
facade.changePassword( user, new char[] {} ,password.toCharArray());
System.out.println("Imported user " + user + " with password '" + password + "'");
}
}
static private Category findCategory( Category rootCategory, String groupPath) {
Category group = rootCategory;
String[] groupKeys = Tools.split( groupPath, '/');
for ( int i=0;i<groupKeys.length; i++) {
group = group.getCategory( groupKeys[i] );
}
return group;
}
}
| 04900db4-clienttest | src/org/rapla/examples/RaplaImportUsers.java | Java | gpl3 | 4,453 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.defaultwizard;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
public class DefaultWizardPlugin implements PluginDescriptor<ClientServiceContainer> {
public static final String PLUGIN_CLASS = DefaultWizardPlugin.class.getName();
public static boolean ENABLE_BY_DEFAULT = true;
public void provideServices(ClientServiceContainer container, Configuration config) {
if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( RaplaClientExtensionPoints.RESERVATION_WIZARD_EXTENSION, DefaultWizard.class);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/defaultwizard/DefaultWizardPlugin.java | Java | gpl3 | 1,710 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.defaultwizard;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.swing.MenuElement;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.facade.CalendarModel;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.toolkit.IdentifiableMenuEntry;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaMenuItem;
/** This ReservationWizard displays no wizard and directly opens a ReservationEdit Window
*/
public class DefaultWizard extends RaplaGUIComponent implements IdentifiableMenuEntry, ActionListener
{
Map<Component,DynamicType> typeMap = new HashMap<Component, DynamicType>();
public DefaultWizard(RaplaContext sm){
super(sm);
}
public String getId() {
return "000_defaultWizard";
}
public MenuElement getMenuElement() {
typeMap.clear();
DynamicType[] eventTypes;
try {
eventTypes = getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
} catch (RaplaException e) {
return null;
}
boolean canCreateReservation = canCreateReservation();
MenuElement element;
if ( eventTypes.length == 1)
{
RaplaMenuItem item = new RaplaMenuItem( getId());
item.setEnabled( canAllocate() && canCreateReservation);
item.setText(getString("new_reservation"));
item.setIcon( getIcon("icon.new"));item.addActionListener( this);
typeMap.put( item, eventTypes[0]);
element = item;
}
else
{
RaplaMenu item = new RaplaMenu( getId());
item.setEnabled( canAllocate() && canCreateReservation);
item.setText(getString("new_reservation"));
item.setIcon( getIcon("icon.new"));
for ( DynamicType type:eventTypes)
{
RaplaMenuItem newItem = new RaplaMenuItem(type.getKey());
newItem.setText( type.getName( getLocale()));
item.add( newItem);
newItem.addActionListener( this);
typeMap.put( newItem, type);
}
element = item;
}
return element;
}
public void actionPerformed(ActionEvent e) {
try
{
CalendarModel model = getService(CalendarModel.class);
Object source = e.getSource();
DynamicType type = typeMap.get( source);
if ( type == null)
{
getLogger().warn("Type not found for " + source + " in map " + typeMap);
return;
}
Classification newClassification = type.newClassification();
Reservation r = getModification().newReservation( newClassification );
Appointment appointment = createAppointment(model);
r.addAppointment(appointment);
Collection<Allocatable> markedAllocatables = model.getMarkedAllocatables();
if ( markedAllocatables == null || markedAllocatables.size() == 0)
{
Allocatable[] allocatables = model.getSelectedAllocatables();
if ( allocatables.length == 1)
{
r.addAllocatable( allocatables[0]);
}
}
else
{
for ( Allocatable alloc: markedAllocatables)
{
r.addAllocatable( alloc);
}
}
getReservationController().edit( r );
}
catch (RaplaException ex)
{
showException( ex, getMainComponent());
}
}
protected Appointment createAppointment(CalendarModel model)
throws RaplaException {
Date startDate = getStartDate(model);
Date endDate = getEndDate( model, startDate);
Appointment appointment = getModification().newAppointment(startDate, endDate);
return appointment;
}
// /**
// * @param model
// * @param startDate
// * @return
// */
// 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 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;
// }
}
| 04900db4-clienttest | src/org/rapla/plugin/defaultwizard/DefaultWizard.java | Java | gpl3 | 6,231 |
package org.rapla.plugin.mail;
import javax.jws.WebService;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.RaplaException;
@WebService
public interface MailConfigService
{
boolean isExternalConfigEnabled() throws RaplaException;
void testMail( DefaultConfiguration config,String defaultSender) throws RaplaException;
DefaultConfiguration getConfig() throws RaplaException;
// LoginInfo getLoginInfo() throws RaplaException;
// void setLogin(String username,String password) throws RaplaException;
// public class LoginInfo
// {
// public String username;
// public String password;
// }
}
| 04900db4-clienttest | src/org/rapla/plugin/mail/MailConfigService.java | Java | gpl3 | 632 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.mail.client;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Locale;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import org.rapla.components.calendar.RaplaNumber;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.gui.DefaultPluginOption;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.plugin.mail.MailConfigService;
import org.rapla.plugin.mail.MailPlugin;
public class MailOption extends DefaultPluginOption {
JTextField mailServer;
RaplaNumber smtpPortField ;
JTextField defaultSender;
JTextField username;
JPasswordField password;
RaplaButton send ;
JCheckBox useSsl = new JCheckBox();
private boolean listenersEnabled;
private boolean externalConfigEnabled;
MailConfigService configService;
public MailOption(RaplaContext sm,MailConfigService mailConfigService)
{
super(sm);
this.configService = mailConfigService;
}
protected JPanel createPanel() throws RaplaException {
JPanel panel = super.createPanel();
externalConfigEnabled = configService.isExternalConfigEnabled();
mailServer = new JTextField();
smtpPortField = new RaplaNumber(new Integer(25), new Integer(0),null,false);
defaultSender = new JTextField();
username = new JTextField();
password = new JPasswordField();
send = new RaplaButton();
password.setEchoChar('*');
JPanel content = new JPanel();
addCopyPaste( mailServer);
addCopyPaste( defaultSender);
addCopyPaste(username);
addCopyPaste(password);
double[][] sizes = new double[][] {
{5,TableLayout.PREFERRED, 5,TableLayout.FILL,5}
,{TableLayout.PREFERRED,5,TableLayout.PREFERRED, 5, TableLayout.PREFERRED,5,TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED}
};
TableLayout tableLayout = new TableLayout(sizes);
content.setLayout(tableLayout);
if (externalConfigEnabled)
{
JLabel info = new JLabel("Mail config is provided by servlet container.");
content.add(info, "3,0");
}
else
{
content.add(new JLabel("Mail Server"), "1,0");
content.add( mailServer, "3,0");
content.add(new JLabel("Use SSL*"), "1,2");
content.add(useSsl,"3,2");
content.add(new JLabel("Mail Port"), "1,4");
content.add( smtpPortField, "3,4");
content.add(new JLabel("Username"), "1,6");
content.add( username, "3,6");
content.add(new JLabel("Password"), "1,8");
JPanel passwordPanel = new JPanel();
passwordPanel.setLayout( new BorderLayout());
content.add( passwordPanel, "3,8");
passwordPanel.add( password, BorderLayout.CENTER);
final JCheckBox showPassword = new JCheckBox("show password");
passwordPanel.add( showPassword, BorderLayout.EAST);
showPassword.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean show = showPassword.isSelected();
password.setEchoChar( show ? ((char) 0): '*');
}
});
content.add(new JLabel("Default Sender"), "1,10");
content.add( defaultSender, "3,10");
}
content.add(new JLabel("Test Mail"), "1,12");
content.add( send, "3,12");
String mailid = getUser().getEmail();
if(mailid.length() == 0) {
send.setText("Send to " + getUser()+ " : Provide email in user profile");
send.setEnabled(false);
//java.awt.Font font = send.getFont();
//send.setFont( font.deriveFont( Font.BOLD));
}
else {
send.setText("Send to " + getUser()+ " : " + mailid);
send.setEnabled(true);
//send.setBackground(Color.GREEN);
}
useSsl.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
if ( listenersEnabled)
{
int port = useSsl.isSelected() ? 465 : 25;
smtpPortField.setNumber( new Integer(port));
}
}
});
send.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
DefaultConfiguration newConfig = new DefaultConfiguration( config);
Configuration[] children = newConfig.getChildren();
for (Configuration child:children)
{
newConfig.removeChild(child);
}
String className = getPluginClass().getName();
newConfig.setAttribute( "class", className);
newConfig.setAttribute( "enabled", activate.isSelected());
// if ( !activate.isSelected())
// {
// throw new RaplaException("You need to activate MailPlugin " + getString("restart_options"));
// }
if (!externalConfigEnabled)
{
addChildren( newConfig);
// if ( !newConfig.equals( config))
// {
// getLogger().info("old config" + config );
// getLogger().info("new config" + newConfig);
// throw new RaplaException(getString("restart_options"));
// }
}
else
{
String attribute = config.getAttribute("enabled", null);
if ( attribute == null || !attribute.equalsIgnoreCase("true") )
{
throw new RaplaException(getString("restart_options"));
}
}
//String senderMail = defaultSender.getText();
String recipient = getUser().getEmail();
if ( recipient == null || recipient.trim().length() == 0)
{
throw new RaplaException("You need to set an email address in your user settings.");
}
try
{
send.setBackground(new Color(255,100,100, 255));
configService.testMail( newConfig, defaultSender.getText());
send.setBackground(Color.GREEN);
send.setText("Please check your mailbox.");
}
catch (UnsupportedOperationException ex)
{
JComponent component = getComponent();
showException( new RaplaException(getString("restart_options")), component);
}
}
catch (RaplaException ex )
{
JComponent component = getComponent();
showException( ex, component);
// } catch (ConfigurationException ex) {
// JComponent component = getComponent();
// showException( ex, component);
}
}
});
panel.add( content, BorderLayout.CENTER);
return panel;
}
protected void addChildren( DefaultConfiguration newConfig) {
if ( !externalConfigEnabled)
{
DefaultConfiguration smtpPort = new DefaultConfiguration("smtp-port");
DefaultConfiguration smtpServer = new DefaultConfiguration("smtp-host");
DefaultConfiguration ssl = new DefaultConfiguration("ssl");
smtpPort.setValue(smtpPortField.getNumber().intValue() );
smtpServer.setValue( mailServer.getText());
ssl.setValue( useSsl.isSelected() );
newConfig.addChild( smtpPort );
newConfig.addChild( smtpServer );
newConfig.addChild( ssl );
DefaultConfiguration username = new DefaultConfiguration("username");
DefaultConfiguration password = new DefaultConfiguration("password");
String usernameValue = this.username.getText();
if ( usernameValue != null && usernameValue.trim().length() > 0)
{
username.setValue( usernameValue);
}
newConfig.addChild( username );
String passwordString = new String(this.password.getPassword());
if ( passwordString.trim().length() > 0 )
{
password.setValue( passwordString);
}
newConfig.addChild( password );
}
}
@Override
protected void readConfig( Configuration config) {
try
{
config = configService.getConfig();
}
catch (RaplaException ex)
{
showException(ex, getComponent());
}
listenersEnabled = false;
try
{
useSsl.setSelected( config.getChild("ssl").getValueAsBoolean( false));
mailServer.setText( config.getChild("smtp-host").getValue("localhost"));
smtpPortField.setNumber( new Integer(config.getChild("smtp-port").getValueAsInteger(25)));
username.setText( config.getChild("username").getValue(""));
password.setText( config.getChild("password").getValue(""));
}
finally
{
listenersEnabled = true;
}
}
public void show() throws RaplaException {
super.show();
defaultSender.setText( preferences.getEntryAsString(MailPlugin.DEFAULT_SENDER_ENTRY,"rapla@domainname"));
}
public void commit() throws RaplaException {
writePluginConfig(false);
TypedComponentRole<RaplaConfiguration> configEntry = MailPlugin.MAILSERVER_CONFIG;
RaplaConfiguration newConfig = new RaplaConfiguration("config" );
addChildren( newConfig );
preferences.putEntry( configEntry,newConfig);
preferences.putEntry(MailPlugin.DEFAULT_SENDER_ENTRY, defaultSender.getText() );
}
/**
* @see org.rapla.gui.DefaultPluginOption#getPluginClass()
*/
public Class<? extends PluginDescriptor<?>> getPluginClass() {
return MailPlugin.class;
}
public String getName(Locale locale) {
return "Mail Plugin";
}
}
| 04900db4-clienttest | src/org/rapla/plugin/mail/client/MailOption.java | Java | gpl3 | 10,893 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.mail;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.plugin.mail.client.MailOption;
import org.rapla.plugin.mail.internal.RaplaMailToUserOnServer;
/** Provides the MailToUserInterface and the MailInterface for sending mails.
* The MailInterface can only be used on a machine that can connect to the mailserver.
* While the MailToUserInterface can be called from a client, it redirects the mail request to
* the server, which must be able to connect to the mailserver.
*
* Example 1:
*
* <code>
* MailToUserInterface mail = getContext().loopup( MailToUserInterface.class );
* mail.sendMail( subject, body );
* </code>
*
* @see MailToUserInterface
*/
public class MailPlugin implements PluginDescriptor<ClientServiceContainer>
{
public static final boolean ENABLE_BY_DEFAULT = false;
public static final TypedComponentRole<String> DEFAULT_SENDER_ENTRY = new TypedComponentRole<String>("org.rapla.plugin.mail.DefaultSender");
public static final TypedComponentRole<RaplaConfiguration> MAILSERVER_CONFIG = new TypedComponentRole<RaplaConfiguration>("org.rapla.plugin.mail.server.Config");
public void provideServices(ClientServiceContainer container, Configuration config) throws RaplaContextException {
container.addContainerProvidedComponent( RaplaClientExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION,MailOption.class);
if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( MailToUserInterface.class, RaplaMailToUserOnServer.class);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/mail/MailPlugin.java | Java | gpl3 | 2,856 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.mail;
import org.rapla.framework.RaplaException;
public class MailException extends RaplaException {
private static final long serialVersionUID = 1L;
public MailException(String text,Throwable ex) {
super(text,ex);
}
public MailException(String text) {
super(text);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/mail/MailException.java | Java | gpl3 | 1,291 |
package org.rapla.plugin.mail;
import javax.jws.WebService;
import org.rapla.framework.RaplaException;
@WebService
public interface MailToUserInterface
{
void sendMail(String username,String subject, String body) throws RaplaException;
}
| 04900db4-clienttest | src/org/rapla/plugin/mail/MailToUserInterface.java | Java | gpl3 | 244 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.mail.server;
import org.rapla.RaplaMainContainer;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.internal.PreferencesImpl;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.mail.MailConfigService;
import org.rapla.plugin.mail.MailPlugin;
import org.rapla.server.RaplaKeyStorage;
import org.rapla.server.RemoteMethodFactory;
import org.rapla.server.RemoteSession;
import org.rapla.storage.RaplaSecurityException;
public class RaplaConfigServiceImpl extends RaplaComponent implements RemoteMethodFactory<MailConfigService>
{
RaplaKeyStorage keyStore;
public RaplaConfigServiceImpl( RaplaContext context) throws RaplaContextException {
super( context );
keyStore = context.lookup( RaplaKeyStorage.class);
}
public MailConfigService createService(final RemoteSession remoteSession) {
return new MailConfigService()
{
public boolean isExternalConfigEnabled() throws RaplaException
{
return getContext().has(RaplaMainContainer.ENV_RAPLAMAIL);
}
@SuppressWarnings("deprecation")
@Override
public DefaultConfiguration getConfig() throws RaplaException {
User user = remoteSession.getUser();
if ( !user.isAdmin())
{
throw new RaplaSecurityException("Access only for admin users");
}
Preferences preferences = getQuery().getSystemPreferences();
DefaultConfiguration config = preferences.getEntry( MailPlugin.MAILSERVER_CONFIG);
if ( config == null)
{
config = (DefaultConfiguration) ((PreferencesImpl)preferences).getOldPluginConfig(MailPlugin.class.getName());
}
return config;
}
@Override
public void testMail(DefaultConfiguration config, String defaultSender) throws RaplaException {
User user = remoteSession.getUser();
if ( !user.isAdmin())
{
throw new RaplaSecurityException("Access only for admin users");
}
String subject ="Rapla Test Mail";
String mailBody ="If you receive this mail the rapla mail settings are successfully configured.";
MailInterface test = getService(MailInterface.class);
String recipient = user.getEmail();
if (test instanceof MailapiClient)
{
((MailapiClient)test).sendMail(defaultSender, recipient, subject, mailBody, config);
}
else
{
test.sendMail(defaultSender,recipient, subject, mailBody);
}
}
// @Override
// public LoginInfo getLoginInfo() throws RaplaException {
// User user = remoteSession.getUser();
// if ( user == null || !user.isAdmin())
// {
// throw new RaplaSecurityException("Only admins can get mailserver login info");
// }
// org.rapla.server.RaplaKeyStorage.LoginInfo secrets = keyStore.getSecrets( null, MailPlugin.MAILSERVER_CONFIG);
// LoginInfo result = new LoginInfo();
// if ( secrets != null)
// {
// result.username = secrets.login;
// result.password = secrets.secret;
// }
// return result;
// }
//
// @Override
// public void setLogin(String username, String password) throws RaplaException {
// User user = remoteSession.getUser();
// if ( user == null || !user.isAdmin())
// {
// throw new RaplaSecurityException("Only admins can set mailserver login info");
// }
// if ( username.length() == 0 && password.length() == 0)
// {
// keyStore.removeLoginInfo(null, MailPlugin.MAILSERVER_CONFIG);
// }
// else
// {
// keyStore.storeLoginInfo( null, MailPlugin.MAILSERVER_CONFIG, username, password);
// }
// }
};
}
}
| 04900db4-clienttest | src/org/rapla/plugin/mail/server/RaplaConfigServiceImpl.java | Java | gpl3 | 5,005 |
package org.rapla.plugin.mail.server;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
import org.rapla.RaplaMainContainer;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.facade.ClientFacade;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.mail.MailException;
import org.rapla.plugin.mail.MailPlugin;
public class MailapiClient implements MailInterface
{
String mailhost = "localhost";
int port = 25;
boolean ssl =false;
String username;
String password;
RaplaContext context;
Object lookup;
public MailapiClient( RaplaContext context) throws RaplaException {
this.context = context;
if ( context.has(RaplaMainContainer.ENV_RAPLAMAIL))
{
lookup = context.lookup(RaplaMainContainer.ENV_RAPLAMAIL);
}
}
public MailapiClient()
{
}
public boolean isSsl() {
return ssl;
}
public void setSsl(boolean ssl) {
this.ssl = ssl;
}
public void sendMail( String senderMail, String recipient, String subject, String mailBody ) throws MailException
{
if ( lookup != null)
{
send(senderMail, recipient, subject, mailBody, lookup);
return;
}
else
{
sendMail(senderMail, recipient, subject, mailBody, (Configuration)null);
}
}
public void sendMail( String senderMail, String recipient, String subject, String mailBody, Configuration config ) throws MailException
{
Object session;
if ( config == null && context != null && context.has( ClientFacade.class))
{
Preferences systemPreferences;
try {
systemPreferences = context.lookup(ClientFacade.class).getSystemPreferences();
} catch (RaplaException e) {
throw new MailException( e.getMessage(),e);
}
config = systemPreferences.getEntry(MailPlugin.MAILSERVER_CONFIG, new RaplaConfiguration());
}
if ( config != null)
{
// get the configuration entry text with the default-value "Welcome"
int port = config.getChild("smtp-port").getValueAsInteger(25);
String mailhost = config.getChild("smtp-host").getValue("localhost");
String username= config.getChild("username").getValue("");
String password= config.getChild("password").getValue("");
boolean ssl = config.getChild("ssl").getValueAsBoolean(false);
session = createSessionFromProperties(mailhost,port,ssl, username, password);
}
else
{
session = createSessionFromProperties(mailhost,port,ssl, username, password);
}
send(senderMail, recipient, subject, mailBody, session);
}
private Object createSessionFromProperties(String mailhost, int port, boolean ssl, String username, String password) throws MailException {
Properties props = new Properties();
props.put("mail.smtp.host", mailhost);
props.put("mail.smtp.port", new Integer(port));
boolean usernameSet = username != null && username.trim().length() > 0;
if ( usernameSet)
{
props.put("username", username);
props.put("mail.smtp.auth","true");
}
if ( password != null)
{
if ( usernameSet || password.length() > 0)
{
props.put("password", password);
}
}
if (ssl)
{
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.port", new Integer(port));
}
Object session;
try {
Class<?> MailLibsC = Class.forName("org.rapla.plugin.mail.server.RaplaMailLibs");
session = MailLibsC.getMethod("getSession", Properties.class).invoke( null, props);
} catch (Exception e) {
Throwable cause = e;
if ( e instanceof InvocationTargetException)
{
cause = e.getCause();
}
throw new MailException( cause.getMessage(), cause);
}
return session;
}
private void send(String senderMail, String recipient, String subject,
String mailBody, Object uncastedSession) throws MailException {
ClassLoader classLoader = uncastedSession.getClass().getClassLoader();
try {
sendWithReflection(senderMail, recipient, subject, mailBody, uncastedSession, classLoader);
// try
// {
// Session castedSession = (Session) uncastedSession;
// sendWithoutReflection(senderMail, recipient, subject, mailBody, castedSession);
// }
// catch ( ClassCastException ex)
// {
// sendWithReflection(senderMail, recipient, subject, mailBody, uncastedSession, classLoader);
// return;
// }
} catch (Exception ex) {
String message = ex.getMessage();
throw new MailException( message, ex);
}
}
// private void sendWithoutReflection(String senderMail, String recipient,
// String subject, String mailBody, Session session) throws Exception {
// Message message = new MimeMessage(session);
// if ( senderMail != null && senderMail.trim().length() > 0)
// {
// message.setFrom(new InternetAddress(senderMail));
// }
// RecipientType type = Message.RecipientType.TO;
// Address[] parse = InternetAddress.parse(recipient);
// message.setRecipients(type, parse);
// message.setSubject(subject);
// message.setText(mailBody);
// Transport.send(message);
// }
private void sendWithReflection(String senderMail, String recipient,
String subject, String mailBody, Object session,
ClassLoader classLoader) throws Exception {
Thread currentThread = Thread.currentThread();
ClassLoader original = currentThread.getContextClassLoader();
boolean changedClass =false;
try {
try
{
currentThread.setContextClassLoader( classLoader);
changedClass = true;
}
catch (Throwable ex)
{
}
Class<?> SessionC = classLoader.loadClass("javax.mail.Session");
Class<?> MimeMessageC = classLoader.loadClass("javax.mail.internet.MimeMessage");
Class<?> MessageC = classLoader.loadClass("javax.mail.Message");
Class<?> AddressC = classLoader.loadClass("javax.mail.Address");
Class<?> RecipientTypeC = classLoader.loadClass("javax.mail.Message$RecipientType");
Class<?> InternetAddressC = classLoader.loadClass("javax.mail.internet.InternetAddress");
Class<?> TransportC = classLoader.loadClass("javax.mail.Transport");
//Message message = new MimeMessage(session);
Object message = MimeMessageC.getConstructor( SessionC).newInstance( session);
if ( senderMail != null && senderMail.trim().length() > 0)
{
//message.setFrom(new InternetAddress(senderMail));
Object senderMailAddress = InternetAddressC.getConstructor( String.class).newInstance( senderMail);
MimeMessageC.getMethod("setFrom", AddressC).invoke( message, senderMailAddress);
}
//RecipientType type = Message.RecipientType.TO;
//Address[] parse = InternetAddress.parse(recipient);
//message.setRecipients(type, parse);
Object type = RecipientTypeC.getField("TO").get(null);
Object[] parsedRecipientDummy = (Object[]) Array.newInstance(AddressC, 0);
Object parsedRecipient = InternetAddressC.getMethod("parse", String.class).invoke(null, recipient);
Method method = MessageC.getMethod("setRecipients", RecipientTypeC, parsedRecipientDummy.getClass());
method.invoke( message, type, parsedRecipient);
//message.setSubject(subject);
MimeMessageC.getMethod("setSubject", String.class).invoke( message, subject);
//message.setText(mailBody);
//MimeMessageC.getMethod("setText", String.class).invoke( message, mailBody);
MimeMessageC.getMethod("setContent", Object.class, String.class).invoke( message, mailBody, "text/plain; charset=UTF-8");
//Transport.send(message);
TransportC.getMethod("send", MessageC).invoke( null, message);
} catch (Exception ex) {
Throwable e = ex;
if ( ex instanceof InvocationTargetException){
e = ex.getCause();
}
String message = e.getMessage();
throw new RaplaException( message, e);
}
finally
{
if ( changedClass)
{
currentThread.setContextClassLoader( original);
}
}
}
public String getSmtpHost()
{
return mailhost;
}
public void setSmtpHost( String mailhost )
{
this.mailhost = mailhost;
}
public String getPassword()
{
return password;
}
public void setPassword( String password )
{
this.password = password;
}
public int getPort()
{
return port;
}
public void setPort( int port )
{
this.port = port;
}
public String getUsername()
{
return username;
}
public void setUsername( String username )
{
this.username = username;
}
} | 04900db4-clienttest | src/org/rapla/plugin/mail/server/MailapiClient.java | Java | gpl3 | 9,133 |
package org.rapla.plugin.mail.server;
import org.rapla.plugin.mail.MailException;
public interface MailInterface {
/* Sends the mail.
Callers should check if the parameters are all valid
according to the SMTP RFC at http://www.ietf.org/rfc/rfc821.txt
because the implementing classes may not check for validity
*/
public void sendMail
(
String senderMail
,String recipient
,String subject
,String mailBody
)
throws MailException;
}
| 04900db4-clienttest | src/org/rapla/plugin/mail/server/MailInterface.java | Java | gpl3 | 529 |
package org.rapla.plugin.mail.server;
import java.util.Properties;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
public class RaplaMailLibs
{
static public Object getSession(Properties props) {
javax.mail.Authenticator authenticator = null;
final String username2 = (String) props.get("username");
final String password2 = (String) props.get("password");
if ( props.containsKey("username"))
{
authenticator = new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username2,password2);
}
};
}
Object session = Session.getInstance(props, authenticator);
return session;
}
} | 04900db4-clienttest | src/org/rapla/plugin/mail/server/RaplaMailLibs.java | Java | gpl3 | 748 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.mail.server;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.framework.logger.Logger;
import org.rapla.plugin.mail.MailConfigService;
import org.rapla.plugin.mail.MailPlugin;
import org.rapla.plugin.mail.MailToUserInterface;
import org.rapla.server.ServerServiceContainer;
import org.rapla.server.internal.RemoteStorageImpl;
/** Provides the MailToUserInterface and the MailInterface for sending mails.
* The MailInterface can only be used on a machine that can connect to the mailserver.
* While the MailToUserInterface can be called from a client, it redirects the mail request to
* the server, which must be able to connect to the mailserver.
*
* Example 1:
*
* <code>
* MailToUserInterface mail = getContext().loopup( MailToUserInterface.class );
* mail.sendMail( subject, body );
* </code>
*
* Example 2:
*
* <code>
* MailInterface mail = getContext().loopup( MailInterface.class );
* mail.sendMail( senderMail, recipient, subject, body );
* </code>
* @see MailInterface
* @see MailToUserInterface
*/
public class MailServerPlugin implements PluginDescriptor<ServerServiceContainer>
{
public void provideServices(ServerServiceContainer container, Configuration config) throws RaplaContextException {
container.addRemoteMethodFactory(MailConfigService.class,RaplaConfigServiceImpl.class);
convertSettings(container.getContext(), config);
if ( !config.getAttributeAsBoolean("enabled", false) )
return;
Class<? extends MailInterface> mailClass = null;
String mailClassConfig =config.getChild("mailinterface").getValue( null);
if ( mailClassConfig != null)
{
try {
@SuppressWarnings("unchecked")
Class<? extends MailInterface> forName = (Class<? extends MailInterface>) Class.forName( mailClassConfig);
mailClass = forName;
} catch (Exception e) {
container.getContext().lookup(Logger.class).error( "Error loading mailinterface " +e.getMessage() );
}
}
if ( mailClass == null)
{
mailClass = MailapiClient.class;
}
container.addContainerProvidedComponent( MailInterface.class, mailClass);
// only add mail service on localhost
container.addRemoteMethodFactory(MailToUserInterface.class,RaplaMailToUserOnLocalhost.class);
container.addContainerProvidedComponent( MailToUserInterface.class, RaplaMailToUserOnLocalhost.class);
}
private void convertSettings(RaplaContext context,Configuration config) throws RaplaContextException
{
String className = MailPlugin.class.getName();
TypedComponentRole<RaplaConfiguration> newConfKey = MailPlugin.MAILSERVER_CONFIG;
if ( config.getChildren().length > 0)
{
RemoteStorageImpl.convertToNewPluginConfig(context, className, newConfKey);
}
}
}
| 04900db4-clienttest | src/org/rapla/plugin/mail/server/MailServerPlugin.java | Java | gpl3 | 4,161 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.mail.server;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.mail.MailPlugin;
import org.rapla.plugin.mail.MailToUserInterface;
import org.rapla.server.RemoteMethodFactory;
import org.rapla.server.RemoteSession;
public class RaplaMailToUserOnLocalhost extends RaplaComponent implements MailToUserInterface, RemoteMethodFactory<MailToUserInterface>
{
public RaplaMailToUserOnLocalhost( RaplaContext context) {
super( context );
}
public void sendMail(String userName,String subject, String body) throws RaplaException {
User recipientUser = getQuery().getUser( userName );
// O.K. We need to generate the mail
String recipientEmail = recipientUser.getEmail();
if (recipientEmail == null || recipientEmail.trim().length() == 0) {
getLogger().warn("No email address specified for user "
+ recipientUser.getUsername()
+ " Can't send mail.");
return;
}
final MailInterface mail = getContext().lookup(MailInterface.class);
ClientFacade facade = getContext().lookup(ClientFacade.class);
Preferences prefs = facade.getSystemPreferences();
final String defaultSender = prefs.getEntryAsString( MailPlugin.DEFAULT_SENDER_ENTRY, "");
mail.sendMail( defaultSender, recipientEmail,subject, body);
getLogger().getChildLogger("mail").info("Email send to user " + userName);
}
public MailToUserInterface createService(RemoteSession remoteSession) {
return this;
}
}
| 04900db4-clienttest | src/org/rapla/plugin/mail/server/RaplaMailToUserOnLocalhost.java | Java | gpl3 | 2,863 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.mail.internal;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.mail.MailToUserInterface;
/** RemoteStub */
public class RaplaMailToUserOnServer extends RaplaComponent implements MailToUserInterface
{
MailToUserInterface service;
public RaplaMailToUserOnServer( RaplaContext context, MailToUserInterface service )
{
super( context );
this.service = service;
}
public void sendMail( String username, String subject, String mailBody ) throws RaplaException
{
service.sendMail(username, subject, mailBody);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/mail/internal/RaplaMailToUserOnServer.java | Java | gpl3 | 1,633 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.periodcopy;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.swing.JMenuItem;
import org.rapla.components.util.DateTools;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.ReservationStartComparator;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.edit.SaveUndo;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.IdentifiableMenuEntry;
import org.rapla.gui.toolkit.RaplaMenuItem;
public class CopyPluginMenu extends RaplaGUIComponent implements IdentifiableMenuEntry,ActionListener
{
RaplaMenuItem item;
String id = "copy_events";
final String label ;
public CopyPluginMenu(RaplaContext sm) {
super(sm);
setChildBundleName( PeriodCopyPlugin.RESOURCE_FILE);
//menu.insert( new RaplaSeparator("info_end"));
label =getString(id) ;
item = new RaplaMenuItem(id);
// ResourceBundle bundle = ResourceBundle.getBundle( "org.rapla.plugin.periodcopy.PeriodCopy");
//bundle.getString("copy_events");
item.setText( label );
item.setIcon( getIcon("icon.copy") );
item.addActionListener(this);
}
public String getId() {
return id;
}
public JMenuItem getMenuElement() {
return item;
}
// public void copy(CalendarModel model, Period sourcePeriod, Period destPeriod,boolean includeSingleAppointments) throws RaplaException {
// Reservation[] reservations = model.getReservations( sourcePeriod.getStart(), sourcePeriod.getEnd() );
// copy( reservations, destPeriod.getStart(), destPeriod.getEnd(),includeSingleAppointments);
// }
public void actionPerformed(ActionEvent evt) {
try {
final CopyDialog useCase = new CopyDialog(getContext());
String[] buttons = new String[]{getString("abort"), getString("copy") };
final DialogUI dialog = DialogUI.create( getContext(),getMainComponent(),true, useCase.getComponent(), buttons);
dialog.setTitle( label);
dialog.setSize( 600, 500);
dialog.getButton( 0).setIcon( getIcon("icon.abort"));
dialog.getButton( 1).setIcon( getIcon("icon.copy"));
// ActionListener listener = new ActionListener() {
// public void actionPerformed(ActionEvent arg0) {
// dialog.getButton( 1).setEnabled( useCase.isSourceDifferentFromDest() );
// }
// };
//
dialog.startNoPack();
final boolean includeSingleAppointments = useCase.isSingleAppointments();
if ( dialog.getSelectedIndex() == 1) {
List<Reservation> reservations = useCase.getReservations();
copy( reservations, useCase.getDestStart(), useCase.getDestEnd(), includeSingleAppointments );
}
} catch (Exception ex) {
showException( ex, getMainComponent() );
}
}
public void copy( List<Reservation> reservations , Date destStart, Date destEnd,boolean includeSingleAppointmentsAndExceptions) throws RaplaException {
List<Reservation> newReservations = new ArrayList<Reservation>();
List<Reservation> sortedReservations = new ArrayList<Reservation>( reservations);
Collections.sort( sortedReservations, new ReservationStartComparator(getLocale()));
Date firstStart = null;
for (Reservation reservation: sortedReservations) {
if ( firstStart == null )
{
firstStart = ReservationStartComparator.getStart( reservation);
}
Reservation r = copy(reservation, destStart,
destEnd, includeSingleAppointmentsAndExceptions,
firstStart);
if ( r.getAppointments().length > 0) {
newReservations.add( r );
}
}
Collection<Reservation> originalEntity = null;
SaveUndo<Reservation> cmd = new SaveUndo<Reservation>(getContext(), newReservations, originalEntity);
getModification().getCommandHistory().storeAndExecute( cmd);
}
public Reservation copy(Reservation reservation, Date destStart,
Date destEnd, boolean includeSingleAppointmentsAndExceptions,
Date firstStart) throws RaplaException {
Reservation r = getModification().clone( reservation);
if ( firstStart == null )
{
firstStart = ReservationStartComparator.getStart( reservation);
}
Appointment[] appointments = r.getAppointments();
for ( Appointment app :appointments) {
Repeating repeating = app.getRepeating();
if (( repeating == null && !includeSingleAppointmentsAndExceptions) || (repeating != null && repeating.getEnd() == null)) {
r.removeAppointment( app );
continue;
}
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 );
if ( repeating != null && repeating.getType().equals ( Repeating.DAILY) )
{
newStart = getRaplaLocale().toDate( destWithOffset , oldStart );
}
else
{
newStart = getNewStartWeekly(oldStart, destWithOffset);
}
app.move( newStart) ;
if (repeating != null)
{
Date[] exceptions = repeating.getExceptions();
if ( includeSingleAppointmentsAndExceptions )
{
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 (destEnd != null)
{
repeating.setEnd( destEnd);
}
else
{
// 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);
}
}
}
}
// System.out.println(reservations[i].getName( getRaplaLocale().getLocale()));
}
return r;
}
private Date getNewStartWeekly(Date oldStart, Date destStart) {
Date newStart;
Calendar calendar = getRaplaLocale().createCalendar();
calendar.setTime( oldStart);
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
calendar = getRaplaLocale().createCalendar();
calendar.setTime(destStart);
calendar.set( Calendar.DAY_OF_WEEK, weekday);
if ( calendar.getTime().before( destStart))
{
calendar.add( Calendar.DATE, 7);
}
Date firstOccOfWeekday = calendar.getTime();
newStart = getRaplaLocale().toDate( firstOccOfWeekday, oldStart );
return newStart;
}
}
| 04900db4-clienttest | src/org/rapla/plugin/periodcopy/CopyPluginMenu.java | Java | gpl3 | 8,533 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.periodcopy;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.TypedComponentRole;
public class PeriodCopyPlugin implements PluginDescriptor<ClientServiceContainer>
{
public static final boolean ENABLE_BY_DEFAULT = true;
public static final TypedComponentRole<I18nBundle> RESOURCE_FILE = new TypedComponentRole<I18nBundle>(PeriodCopyPlugin.class.getPackage().getName() + ".PeriodCopy");
public void provideServices(ClientServiceContainer container, Configuration config) {
if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( RESOURCE_FILE, I18nBundleImpl.class,I18nBundleImpl.createConfig( RESOURCE_FILE.getId() ) );
container.addContainerProvidedComponent( RaplaClientExtensionPoints.EDIT_MENU_EXTENSION_POINT, CopyPluginMenu.class);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/periodcopy/PeriodCopyPlugin.java | Java | gpl3 | 2,089 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.periodcopy;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.components.calendar.DateChangeEvent;
import org.rapla.components.calendar.DateChangeListener;
import org.rapla.components.calendar.RaplaCalendar;
import org.rapla.components.layout.TableLayout;
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.domain.internal.PeriodImpl;
import org.rapla.facade.CalendarModel;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.common.NamedListCellRenderer;
import org.rapla.gui.internal.edit.fields.BooleanField;
import org.rapla.gui.toolkit.RaplaWidget;
/** sample UseCase that only displays the text of the configuration and
all reservations of the user.*/
class CopyDialog extends RaplaGUIComponent implements RaplaWidget
{
@SuppressWarnings("unchecked")
JComboBox sourcePeriodChooser = new JComboBox(new String[] {"a", "b"});
@SuppressWarnings("unchecked")
JComboBox destPeriodChooser = new JComboBox(new String[] {"a", "b"});
RaplaLocale locale = getRaplaLocale();
RaplaCalendar destBegin;
RaplaCalendar sourceBegin;
RaplaCalendar sourceEnd;
JPanel panel = new JPanel();
JLabel label = new JLabel();
JList selectedReservations = new JList();
BooleanField singleChooser;
PeriodImpl customPeriod = new PeriodImpl("", null, null);
JPanel customSourcePanel = new JPanel();
JPanel customDestPanel = new JPanel();
@SuppressWarnings("unchecked")
public CopyDialog(RaplaContext sm) throws RaplaException {
super(sm);
locale = getRaplaLocale();
sourceBegin = createRaplaCalendar();
sourceEnd = createRaplaCalendar();
destBegin = createRaplaCalendar();
setChildBundleName( PeriodCopyPlugin.RESOURCE_FILE);
Period[] periods = getQuery().getPeriods();
singleChooser = new BooleanField(sm, "singleChooser");
singleChooser.addChangeListener( new ChangeListener() {
public void stateChanged(ChangeEvent e) {
try {
updateReservations();
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
});
DefaultComboBoxModel sourceModel = new DefaultComboBoxModel( periods );
Date today = getQuery().today();
final PeriodImpl customSource = new PeriodImpl(getString("custom_period"), today, today);
sourceModel.insertElementAt(customSource, 0);
DefaultComboBoxModel destModel = new DefaultComboBoxModel( periods );
final PeriodImpl customDest = new PeriodImpl(getString("custom_period"),today, null);
{
destModel.insertElementAt(customDest, 0);
}
//customEnd.setStart( destDate.getDate());
sourcePeriodChooser.setModel( sourceModel);
destPeriodChooser.setModel( destModel);
label.setText(getString("copy_selected_events_from"));
panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
panel.setLayout(new TableLayout(new double[][]{
{TableLayout.PREFERRED ,5 , TableLayout.FILL }
,{20, 5, TableLayout.PREFERRED ,5 ,TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED,5, TableLayout.PREFERRED,5, TableLayout.PREFERRED }
}
));
selectedReservations.setEnabled( false );
customSourcePanel.add( sourceBegin );
customSourcePanel.add( new JLabel(getString("time_until")) );
customSourcePanel.add( sourceEnd );
customDestPanel.add( destBegin);
panel.add(label, "0,0,2,1");
panel.add( new JLabel(getString("source")),"0,2" );
panel.add( sourcePeriodChooser,"2,2" );
panel.add( customSourcePanel,"2,4" );
panel.add( new JLabel(getString("destination")),"0,6" );
panel.add( destPeriodChooser,"2,6" );
panel.add( customDestPanel,"2,8" );
panel.add( new JLabel(getString("copy_single")),"0,10" );
panel.add( singleChooser.getComponent(),"2,10" );
singleChooser.setValue( Boolean.TRUE);
panel.add( new JLabel(getString("reservations")) , "0,12,l,t");
panel.add( new JScrollPane( selectedReservations ),"2,12" );
updateView();
sourcePeriodChooser.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateView();
if ( sourcePeriodChooser.getSelectedIndex() > 1)
{
Period beginPeriod = (Period)sourcePeriodChooser.getSelectedItem();
sourceBegin.setDate(beginPeriod.getStart());
sourceEnd.setDate(beginPeriod.getEnd());
}
}
});
NamedListCellRenderer aRenderer = new NamedListCellRenderer( getRaplaLocale().getLocale());
sourcePeriodChooser.setRenderer( aRenderer);
destPeriodChooser.setRenderer( aRenderer);
destPeriodChooser.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateView();
if ( destPeriodChooser.getSelectedIndex() > 0)
{
Period endPeriod = (Period)destPeriodChooser.getSelectedItem();
destBegin.setDate(endPeriod.getStart());
}
}
});
DateChangeListener dateChangeListener = new DateChangeListener() {
public void dateChanged(DateChangeEvent evt) {
customSource.setStart( sourceBegin.getDate());
customSource.setEnd( sourceEnd.getDate());
customDest.setStart( destBegin.getDate());
try {
updateReservations();
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
};
sourceBegin.addDateChangeListener(dateChangeListener);
sourceEnd.addDateChangeListener(dateChangeListener);
destBegin.addDateChangeListener(dateChangeListener);
sourcePeriodChooser.setSelectedIndex(0);
destPeriodChooser.setSelectedIndex(0);
updateReservations();
}
public Date getSourceStart()
{
return sourceBegin.getDate();
}
public Date getSourceEnd()
{
return sourceEnd.getDate();
}
public Date getDestStart()
{ return destBegin.getDate();
}
public Date getDestEnd()
{
if ( destPeriodChooser.getSelectedIndex() > 0)
{
Period endPeriod = (Period)destPeriodChooser.getSelectedItem();
return endPeriod.getStart();
}
else
{
return null;
}
}
private boolean isIncluded(Reservation r, boolean includeSingleAppointments)
{
Appointment[] appointments = r.getAppointments();
int count = 0;
for ( int j=0;j<appointments.length;j++) {
Appointment app = appointments[j];
Repeating repeating = app.getRepeating();
if (( repeating == null && !includeSingleAppointments) || (repeating != null && repeating.getEnd() == null)) {
continue;
}
count++;
}
return count > 0;
}
private void updateView() {
boolean customStartEnabled = sourcePeriodChooser.getSelectedIndex() == 0;
sourceBegin.setEnabled( customStartEnabled);
sourceEnd.setEnabled( customStartEnabled);
boolean customDestEnabled = destPeriodChooser.getSelectedIndex() == 0;
destBegin.setEnabled( customDestEnabled);
}
@SuppressWarnings("unchecked")
private void updateReservations() throws RaplaException
{
DefaultListModel listModel = new DefaultListModel();
List<Reservation> reservations = getReservations();
for ( Reservation reservation: reservations) {
listModel.addElement( reservation.getName( getLocale() ) );
}
selectedReservations.setModel( listModel);
}
public JComponent getComponent() {
return panel;
}
public boolean isSingleAppointments() {
Object value = singleChooser.getValue();
return value != null && ((Boolean)value).booleanValue();
}
public List<Reservation> getReservations() throws RaplaException {
final CalendarModel model = getService( CalendarModel.class);
Reservation[] reservations = model.getReservations( getSourceStart(), getSourceEnd() );
List<Reservation> listModel = new ArrayList<Reservation>();
for ( Reservation reservation:reservations) {
boolean includeSingleAppointments = isSingleAppointments();
if (isIncluded(reservation, includeSingleAppointments))
{
listModel.add( reservation );
}
}
return listModel;
}
}
| 04900db4-clienttest | src/org/rapla/plugin/periodcopy/CopyDialog.java | Java | gpl3 | 10,207 |
<body>
This is the base package of the GUI-client. Communication through the backend
is done through the modules of <code>org.rapla.facade</code> package.
The gui-client is normally started through the <code>RaplaClientService</code>.
You can also plug-in your own components into the gui.
</body>
| 04900db4-clienttest | src/org/rapla/plugin/package.html | HTML | gpl3 | 301 |
package org.rapla.plugin.eventtimecalculator.client;
import java.util.Locale;
import javax.swing.JComponent;
import javax.swing.JPanel;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.plugin.eventtimecalculator.EventTimeCalculatorPlugin;
/**
* ****************************************************************************
* This is the admin-option panel.
*
* @author Tobias Bertram
*/
public class EventTimeCalculatorUserOption extends RaplaGUIComponent implements OptionPanel {
EventTimeCalculatorOption optionPanel;
private Preferences preferences;
Configuration config;
JPanel panel;
public EventTimeCalculatorUserOption(RaplaContext sm, Configuration config) {
super(sm);
this.config = config;
optionPanel = new EventTimeCalculatorOption(sm, false);
setChildBundleName(EventTimeCalculatorPlugin.RESOURCE_FILE);
panel = optionPanel.createPanel();
}
@Override
public JComponent getComponent() {
return panel;
}
public void show() throws RaplaException {
Configuration config = preferences.getEntry( EventTimeCalculatorPlugin.USER_CONFIG);
if ( config == null)
{
config = this.config;
}
optionPanel.readConfig( config);
}
public void setPreferences(Preferences preferences) {
this.preferences = preferences;
}
public void commit() {
RaplaConfiguration config = new RaplaConfiguration("eventtime");
optionPanel.addChildren(config);
preferences.putEntry( EventTimeCalculatorPlugin.USER_CONFIG, config);
}
/**
* returns a string with the name of the plugin.
*/
public String getName(Locale locale) {
return getString("EventTimeCalculatorPlugin");
}
}
| 04900db4-clienttest | src/org/rapla/plugin/eventtimecalculator/client/EventTimeCalculatorUserOption.java | Java | gpl3 | 2,118 |
package org.rapla.plugin.eventtimecalculator.client;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.rapla.components.calendar.RaplaNumber;
import org.rapla.components.layout.TableLayout;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.plugin.eventtimecalculator.EventTimeCalculatorPlugin;
/**
* ****************************************************************************
* This is the admin-option panel.
*
* @author Tobias Bertram
*/
public class EventTimeCalculatorOption extends RaplaGUIComponent {
private RaplaNumber intervalNumber;
private RaplaNumber breakNumber;
//private RaplaNumber lunchbreakNumber;
private RaplaNumber timeUnit;
private JTextField timeFormat;
private JCheckBox chkAllowUserPrefs;
boolean adminOptions;
public EventTimeCalculatorOption(RaplaContext sm, boolean adminOptions) {
super(sm);
this.adminOptions = adminOptions;
setChildBundleName(EventTimeCalculatorPlugin.RESOURCE_FILE);
}
/**
* creates the panel shown in the admin option dialog.
*/
protected JPanel createPanel() {
JPanel content = new JPanel();
double[][] sizes = new double[][]{
{5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5},
{TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5
}};
TableLayout tableLayout = new TableLayout(sizes);
content.setLayout(tableLayout);
content.add(new JLabel(getString("time_till_break") + ":"), "1,0");
content.add(new JLabel(getString("break_duration") + ":"), "1,2");
// content.add(new JLabel(i18n.getString("lunch_break_duration") + ":"), "1,4");
content.add(new JLabel(getString("time_unit") + ":"), "1,6");
content.add(new JLabel(getString("time_format") + ":"), "1,8");
intervalNumber = new RaplaNumber(EventTimeCalculatorPlugin.DEFAULT_intervalNumber, 0, null, false);
content.add(intervalNumber, "3,0");
content.add(new JLabel(getString("minutes")), "5,0");
breakNumber = new RaplaNumber(EventTimeCalculatorPlugin.DEFAULT_breakNumber, 0, null, false);
content.add(breakNumber, "3,2");
content.add(new JLabel(getString("minutes")), "5,2");
// lunchbreakNumber = new RaplaNumber(EventTimeCalculatorPlugin.DEFAULT_lunchbreakNumber, new Integer(1), null, false);
// content.add(lunchbreakNumber, "3,4");
// content.add(new JLabel(i18n.getString("minutes")), "5,4");
timeUnit = new RaplaNumber(EventTimeCalculatorPlugin.DEFAULT_timeUnit, 1, null, false);
content.add(timeUnit, "3,6");
content.add(new JLabel(getString("minutes")), "5,6");
timeFormat = new JTextField();
content.add(timeFormat, "3,8");
if ( adminOptions)
{
chkAllowUserPrefs = new JCheckBox();
content.add(chkAllowUserPrefs, "3,10");
content.add(new JLabel(getString("allow_user_prefs")), "1,10");
}
return content;
}
/**
* adds new configuration to the children to overwrite the default configuration.
*/
protected void addChildren(DefaultConfiguration newConfig) {
newConfig.getMutableChild(EventTimeCalculatorPlugin.INTERVAL_NUMBER, true).setValue(intervalNumber.getNumber().intValue());
newConfig.getMutableChild(EventTimeCalculatorPlugin.BREAK_NUMBER, true).setValue(breakNumber.getNumber().intValue());
// newConfig.getMutableChild(EventTimeCalculatorPlugin.LUNCHBREAK_NUMBER, true).setValue(lunchbreakNumber.getNumber().intValue());
newConfig.getMutableChild(EventTimeCalculatorPlugin.TIME_UNIT, true).setValue(timeUnit.getNumber().intValue());
newConfig.getMutableChild(EventTimeCalculatorPlugin.TIME_FORMAT, true).setValue(timeFormat.getText());
if ( adminOptions)
{
newConfig.getMutableChild(EventTimeCalculatorPlugin.USER_PREFS, true).setValue(chkAllowUserPrefs.isSelected());
}
}
/**
* reads children out of the configuration and shows them in the admin option panel.
*/
protected void readConfig(Configuration config) {
int intervalNumberInt = config.getChild(EventTimeCalculatorPlugin.INTERVAL_NUMBER).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_intervalNumber);
intervalNumber.setNumber(intervalNumberInt);
int breakNumberInt = config.getChild(EventTimeCalculatorPlugin.BREAK_NUMBER).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_breakNumber);
breakNumber.setNumber(breakNumberInt);
// int lunchbreakNumberInt = config.getChild(EventTimeCalculatorPlugin.LUNCHBREAK_NUMBER).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_lunchbreakNumber);
// lunchbreakNumber.setNumber(new Integer(lunchbreakNumberInt));
int timeUnitInt = config.getChild(EventTimeCalculatorPlugin.TIME_UNIT).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_timeUnit);
timeUnit.setNumber(timeUnitInt);
String timeFormatString = config.getChild(EventTimeCalculatorPlugin.TIME_FORMAT).getValue(EventTimeCalculatorPlugin.DEFAULT_timeFormat);
timeFormat.setText(timeFormatString);
if ( adminOptions)
{
boolean allowUserPrefs = config.getChild(EventTimeCalculatorPlugin.USER_PREFS).getValueAsBoolean(EventTimeCalculatorPlugin.DEFAULT_userPrefs);
chkAllowUserPrefs.setSelected(allowUserPrefs);
}
}
}
| 04900db4-clienttest | src/org/rapla/plugin/eventtimecalculator/client/EventTimeCalculatorOption.java | Java | gpl3 | 6,071 |
package org.rapla.plugin.eventtimecalculator.client;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.AppointmentStatusFactory;
import org.rapla.gui.ReservationEdit;
import org.rapla.gui.toolkit.RaplaWidget;
public class EventTimeCalculatorStatusFactory implements AppointmentStatusFactory {
public RaplaWidget createStatus(RaplaContext context, ReservationEdit reservationEdit) throws RaplaException {
return new EventTimeCalculatorStatusWidget(context, reservationEdit);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/eventtimecalculator/client/EventTimeCalculatorStatusFactory.java | Java | gpl3 | 561 |
package org.rapla.plugin.eventtimecalculator.client;
import java.awt.BorderLayout;
import java.util.Locale;
import javax.swing.JPanel;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.DefaultPluginOption;
import org.rapla.plugin.eventtimecalculator.EventTimeCalculatorPlugin;
/**
* ****************************************************************************
* This is the admin-option panel.
*
* @author Tobias Bertram
*/
public class EventTimeCalculatorAdminOption extends DefaultPluginOption {
EventTimeCalculatorOption optionPanel;
public EventTimeCalculatorAdminOption(RaplaContext sm) {
super(sm);
setChildBundleName(EventTimeCalculatorPlugin.RESOURCE_FILE);
optionPanel = new EventTimeCalculatorOption(sm, true);
}
/**
* creates the panel shown in the admin option dialog.
*/
protected JPanel createPanel() throws RaplaException {
JPanel panel = super.createPanel();
JPanel content = optionPanel.createPanel();
panel.add(content, BorderLayout.CENTER);
return panel;
}
/**
* adds new configuration to the children to overwrite the default configuration.
*/
protected void addChildren(DefaultConfiguration newConfig) {
optionPanel.addChildren( newConfig);
}
/**
* reads children out of the configuration and shows them in the admin option panel.
*/
protected void readConfig(Configuration config) {
optionPanel.readConfig(config);
}
/**
* returns a string with the name of the class EventTimeCalculatorPlugin.
*/
public Class<? extends PluginDescriptor<?>> getPluginClass() {
return EventTimeCalculatorPlugin.class;
}
/**
* returns a string with the name of the plugin.
*/
public String getName(Locale locale) {
return getString("EventTimeCalculatorPlugin");
}
}
| 04900db4-clienttest | src/org/rapla/plugin/eventtimecalculator/client/EventTimeCalculatorAdminOption.java | Java | gpl3 | 2,154 |
package org.rapla.plugin.eventtimecalculator.client;
import java.awt.Font;
import java.util.Collection;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.AppointmentListener;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.ReservationEdit;
import org.rapla.gui.toolkit.RaplaWidget;
import org.rapla.plugin.eventtimecalculator.EventTimeCalculatorFactory;
import org.rapla.plugin.eventtimecalculator.EventTimeCalculatorPlugin;
import org.rapla.plugin.eventtimecalculator.EventTimeModel;
/**
* @author Tobias Bertram
* Class EventTimeCalculator provides the service to show the actual duration of all appointments of a reservation.
*/
public class EventTimeCalculatorStatusWidget extends RaplaGUIComponent implements RaplaWidget {
JPanel content = new JPanel();
JLabel totalDurationLabel = new JLabel();
JLabel selectedDurationLabel = new JLabel();
I18nBundle i18n;
ReservationEdit reservationEdit;
EventTimeCalculatorFactory factory;
/**
* creates the panel for the GUI in window "reservation".
*/
public EventTimeCalculatorStatusWidget(final RaplaContext context, final ReservationEdit reservationEdit) throws RaplaException {
super(context);
factory = context.lookup(EventTimeCalculatorFactory.class);
//this.config = config;
i18n = context.lookup(EventTimeCalculatorPlugin.RESOURCE_FILE);
setChildBundleName(EventTimeCalculatorPlugin.RESOURCE_FILE);
double[][] sizes = new double[][]{
{5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5},
{TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5}};
TableLayout tableLayout = new TableLayout(sizes);
content.setLayout(tableLayout);
Font font1 = totalDurationLabel.getFont().deriveFont((float) 9.0);
totalDurationLabel.setFont(font1);
selectedDurationLabel.setFont(font1);
content.add(selectedDurationLabel, "1,2");
content.add(totalDurationLabel, "3,2");
this.reservationEdit = reservationEdit;
/**
* updates Panel if an appointment is removed, changed, added.
*/
reservationEdit.addAppointmentListener(new AppointmentListener() {
public void appointmentSelected(Collection<Appointment> appointment) {
updateStatus();
}
public void appointmentRemoved(Collection<Appointment> appointment) {
updateStatus();
}
public void appointmentChanged(Collection<Appointment> appointment) {
updateStatus();
}
public void appointmentAdded(Collection<Appointment> appointment) {
updateStatus();
}
});
updateStatus();
}
/**
* provides the necessary parameters to use the class TimeCalculator.
* also provides some logic needed for the calculation of the actual duration of all appointments in the shown reservation.
*/
private void updateStatus() {
Reservation event = reservationEdit.getReservation();
if (event == null)
{
return;
}
final EventTimeModel eventTimeModel = factory.getEventTimeModel();
boolean totalDurationVisible = eventTimeModel.hasEnd(event.getAppointments());
if (totalDurationVisible) {
long totalDuration = 0;
totalDuration = eventTimeModel.calcDuration(event.getAppointments());
totalDurationLabel.setText(getString("total_duration") + ": " + eventTimeModel.format(totalDuration));
}
final Collection<Appointment> selectedAppointmentsCollection = reservationEdit.getSelectedAppointments();
final Appointment [] selectedAppointments = selectedAppointmentsCollection.toArray(new Appointment[selectedAppointmentsCollection.size()]);
boolean selectedDurationVisible = eventTimeModel.hasEnd(event.getAppointments());
if (selectedDurationVisible) {
long totalDuration = 0;
totalDuration = eventTimeModel.calcDuration(selectedAppointments);
selectedDurationLabel.setText(getString("duration") + ": " + eventTimeModel.format(totalDuration));
}
/*
Appointment[] appointments = event.getAppointments();
boolean noEnd = false;
long totalDuration = 0;
EventTimeModel eventTimeModel = factory.getEventTimeModel();
for (Appointment appointment : appointments) { // goes through all appointments of the reservation
if (appointment.getRepeating() != null && appointment.getRepeating().getEnd() == null) { // appoinment repeats forever?
noEnd = true;
break;
}
List<AppointmentBlock> splits = new ArrayList<AppointmentBlock>(); // split appointment block
appointment.createBlocks(appointment.getStart(),
DateTools.fillDate(appointment.getMaxEnd()), splits);
for (AppointmentBlock block : splits) { // goes through the block
long duration = DateTools.countMinutes(block.getStart(), block.getEnd());
// lunch break flag: here the lunchBreakActivated-Flag should be taken out of the preferences and given to the calculateActualDuration-method
// final long TIME_TILL_BREAK_DURATION = config.getChild(EventTimeCalculatorPlugin.INTERVAL_NUMBER).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_timeUnit);
// final long BREAK_DURATION = config.getChild(EventTimeCalculatorPlugin.BREAK_NUMBER).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_breakNumber);
long actualDuration = eventTimeModel.calcDuration(duration); // EventTimeCalculatorFactory.calculateActualDuration(duration, TIME_TILL_BREAK_DURATION, BREAK_DURATION);
totalDuration += actualDuration;
}
}
*/
// String format = EventTimeCalculatorFactory.format(config, totalDuration);
totalDurationLabel.setVisible(totalDurationVisible);
selectedDurationLabel.setVisible(selectedDurationVisible);
}
/* public String formatDuration(Configuration config, long totalDuration) {
final String format = config.getChild(EventTimeCalculatorPlugin.TIME_FORMAT).getValue(EventTimeCalculatorPlugin.DEFAULT_timeFormat);
final int timeUnit = config.getChild(EventTimeCalculatorPlugin.TIME_UNIT).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_timeUnit);
return MessageFormat.format(format, totalDuration / timeUnit, totalDuration % timeUnit);
}*/
/**
* returns the panel shown in the window "reservation"
*/
public JComponent getComponent() {
return content;
}
}
| 04900db4-clienttest | src/org/rapla/plugin/eventtimecalculator/client/EventTimeCalculatorStatusWidget.java | Java | gpl3 | 7,126 |
package org.rapla.plugin.eventtimecalculator;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.TypedComponentRole;
import org.rapla.plugin.eventtimecalculator.client.EventTimeCalculatorAdminOption;
import org.rapla.plugin.eventtimecalculator.client.EventTimeCalculatorStatusFactory;
import org.rapla.plugin.eventtimecalculator.client.EventTimeCalculatorUserOption;
import org.rapla.plugin.tableview.TableViewExtensionPoints;
public class EventTimeCalculatorPlugin implements PluginDescriptor<ClientServiceContainer> {
public static final TypedComponentRole<I18nBundle> RESOURCE_FILE = new TypedComponentRole<I18nBundle>( EventTimeCalculatorPlugin.class.getPackage().getName() + ".EventTimeCalculatorResources");
public static final String PLUGIN_CLASS = EventTimeCalculatorPlugin.class.getName();
public static final boolean ENABLE_BY_DEFAULT = false;
// public static String PREF_LUNCHBREAK_NUMBER = "eventtimecalculator_lunchbreak_number";
public static final TypedComponentRole<RaplaConfiguration> USER_CONFIG = new TypedComponentRole<RaplaConfiguration>("org.rapla.plugin.eventtimecalculator");
public static final String INTERVAL_NUMBER = "interval_number";
public static final String BREAK_NUMBER = "break_number";
// public static final String LUNCHBREAK_NUMBER = "lunchbreak_number";
public static final String TIME_UNIT = "time_unit";
public static final String TIME_FORMAT = "time_format";
public static final String USER_PREFS = "user_prefs";
public static final int DEFAULT_intervalNumber = 60;
public static final int DEFAULT_timeUnit = 60;
public static final String DEFAULT_timeFormat = "{0},{1}";
public static final int DEFAULT_breakNumber = 0;
public static final boolean DEFAULT_userPrefs = false;
//public static final int DEFAULT_lunchbreakNumber = 30;
/**
* provides the resource file of the plugin.
* uses the extension points to provide the different services of the plugin.
*/
public void provideServices(ClientServiceContainer container, Configuration config) {
container.addContainerProvidedComponent(RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig(RESOURCE_FILE.getId()));
container.addContainerProvidedComponent(RaplaClientExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION, EventTimeCalculatorAdminOption.class);
if (!config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT))
return;
container.addContainerProvidedComponent(EventTimeCalculatorFactory.class,EventTimeCalculatorFactory.class, config);
if ( config.getChild(USER_PREFS).getValueAsBoolean(false))
{
container.addContainerProvidedComponent(RaplaClientExtensionPoints.USER_OPTION_PANEL_EXTENSION, EventTimeCalculatorUserOption.class, config);
}
container.addContainerProvidedComponent(RaplaClientExtensionPoints.APPOINTMENT_STATUS, EventTimeCalculatorStatusFactory.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, DurationColumnAppoimentBlock.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, DurationColumnReservation.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_SUMMARY, DurationCounter.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_SUMMARY, DurationCounter.class);
}
} | 04900db4-clienttest | src/org/rapla/plugin/eventtimecalculator/EventTimeCalculatorPlugin.java | Java | gpl3 | 3,882 |
package org.rapla.plugin.eventtimecalculator;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import org.rapla.components.util.DateTools;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.Reservation;
import org.rapla.framework.Configuration;
/**
* Created with IntelliJ IDEA.
* User: kuestermann
* Date: 10.06.13
* Time: 17:52
* To change this template use File | Settings | File Templates.
*/
public class EventTimeModel {
protected int timeTillBreak;
protected int durationOfBreak;
protected int timeUnit;
protected String timeFormat;
public EventTimeModel()
{
timeUnit = EventTimeCalculatorPlugin.DEFAULT_timeUnit;
timeFormat = EventTimeCalculatorPlugin.DEFAULT_timeFormat;
timeTillBreak = EventTimeCalculatorPlugin.DEFAULT_intervalNumber;
durationOfBreak = EventTimeCalculatorPlugin.DEFAULT_breakNumber;
}
public int getTimeTillBreak() {
return timeTillBreak;
}
public void setTimeTillBreak(int timeTillBreak) {
this.timeTillBreak = timeTillBreak;
}
public int getDurationOfBreak() {
return durationOfBreak;
}
public void setDurationOfBreak(int durationOfBreak) {
this.durationOfBreak = durationOfBreak;
}
public int getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(int timeUnit) {
this.timeUnit = timeUnit;
}
public String getTimeFormat() {
return timeFormat;
}
public void setTimeFormat(String timeFormat) {
this.timeFormat = timeFormat;
}
public EventTimeModel(Configuration configuration) {
timeTillBreak = configuration.getChild(EventTimeCalculatorPlugin.INTERVAL_NUMBER).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_intervalNumber);
durationOfBreak= configuration.getChild(EventTimeCalculatorPlugin.BREAK_NUMBER).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_breakNumber);
timeUnit= configuration.getChild(EventTimeCalculatorPlugin.TIME_UNIT).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_timeUnit);
timeFormat= configuration.getChild(EventTimeCalculatorPlugin.TIME_FORMAT).getValue(EventTimeCalculatorPlugin.DEFAULT_timeFormat);
}
public String format(long duration) {
if (duration < 0 || timeUnit == 0) {
return "";
}
return MessageFormat.format(timeFormat, duration / timeUnit, duration % timeUnit);
}
public long calcDuration(long minutes)
{
int blockTimeIncludingBreak = timeTillBreak + durationOfBreak;
if (timeTillBreak <= 0 || durationOfBreak <= 0 || minutes<=timeTillBreak)
return minutes;
long breaks = (minutes + durationOfBreak -1 ) / blockTimeIncludingBreak;
long fullBreaks = minutes / blockTimeIncludingBreak;
long partBreak;
if ( breaks > fullBreaks)
{
long timeInclFullBreak = timeTillBreak * (fullBreaks + 1) + fullBreaks * durationOfBreak ;
partBreak = minutes - timeInclFullBreak;
}
else
{
partBreak = 0;
}
long actualDuration = minutes - (fullBreaks * durationOfBreak) - partBreak;
return actualDuration;
}
public long calcDuration(Reservation reservation) {
return calcDuration(reservation.getAppointments());
}
public long calcDuration(AppointmentBlock block) {
long duration = DateTools.countMinutes(block.getStart(), block.getEnd());
return calcDuration(duration);
}
public long calcDuration(Appointment[] appointments){
final Collection<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
long totalDuration = 0;
for (Appointment app : appointments) {
Date start = app.getStart();
Date end = app.getMaxEnd();
if (end == null) {
totalDuration = -1;
break;
} else {
app.createBlocks(start, end, blocks);
}
}
for (AppointmentBlock block : blocks) {
long duration = calcDuration(block);
if (totalDuration >= 0) {
totalDuration += duration;
}
}
return totalDuration;
}
public boolean hasEnd(Appointment[] appointments) {
boolean hasEnd = true;
for (Appointment appointment : appointments) { // goes through all appointments of the reservation
if (hasEnd(appointment)) { // appoinment repeats forever?
hasEnd = false;
break;
}
}
return hasEnd;
}
public boolean hasEnd(Appointment appointment) {
return appointment != null && appointment.getRepeating() != null && appointment.getRepeating().getEnd() == null;
}
public boolean hasEnd(Reservation reservation) {
return hasEnd(reservation.getAppointments());
}
}
| 04900db4-clienttest | src/org/rapla/plugin/eventtimecalculator/EventTimeModel.java | Java | gpl3 | 5,010 |
package org.rapla.plugin.eventtimecalculator;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class EventTimeCalculatorFactory extends RaplaComponent
{
boolean isUserPrefAllowed;
Configuration config;
public EventTimeCalculatorFactory(RaplaContext context,Configuration config)
{
super( context);
isUserPrefAllowed = config.getChild(EventTimeCalculatorPlugin.USER_PREFS).getValueAsBoolean(EventTimeCalculatorPlugin.DEFAULT_userPrefs);
this.config = config;
}
public EventTimeModel getEventTimeModel () {
Configuration configuration = config;
if ( isUserPrefAllowed)
{
RaplaConfiguration raplaConfig;
try {
raplaConfig = getQuery().getPreferences().getEntry(EventTimeCalculatorPlugin.USER_CONFIG);
if ( raplaConfig != null)
{
configuration = raplaConfig;
}
} catch (RaplaException e) {
getLogger().warn(e.getMessage());
}
}
EventTimeModel m = new EventTimeModel(configuration);
return m;
}
}
| 04900db4-clienttest | src/org/rapla/plugin/eventtimecalculator/EventTimeCalculatorFactory.java | Java | gpl3 | 1,287 |
package org.rapla.plugin.eventtimecalculator;
import javax.swing.table.TableColumn;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.configuration.Preferences;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
/**
* User: kuestermann
* Date: 22.08.12
* Time: 09:30
*/
public class DurationColumn extends RaplaComponent implements ModificationListener {
public DurationColumn(RaplaContext context)
{
super(context);
getUpdateModule().addModificationListener( this);
}
public void init(TableColumn column) {
column.setMaxWidth(90);
column.setPreferredWidth(90);
}
public String getColumnName() {
I18nBundle i18n = getService(EventTimeCalculatorPlugin.RESOURCE_FILE);
return i18n.getString("duration");
}
public Class<?> getColumnClass() {
return String.class;
}
protected boolean validConf = false;
public void dataChanged(ModificationEvent evt) throws RaplaException {
if ( evt.isModified(Preferences.TYPE))
{
validConf = false;
}
}
}
| 04900db4-clienttest | src/org/rapla/plugin/eventtimecalculator/DurationColumn.java | Java | gpl3 | 1,296 |
package org.rapla.plugin.eventtimecalculator;
import org.rapla.entities.domain.Reservation;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.tableview.ReservationTableColumn;
/**
* User: kuestermann
* Date: 22.08.12
* Time: 09:29
*/
public final class DurationColumnReservation extends DurationColumn implements ReservationTableColumn {
private EventTimeModel eventTimeModel;
EventTimeCalculatorFactory factory;
public DurationColumnReservation(RaplaContext context) throws RaplaException {
super(context);
factory = context.lookup(EventTimeCalculatorFactory.class);
}
public String getValue(Reservation event) {
if ( !validConf )
{
eventTimeModel = factory.getEventTimeModel();
validConf = true;
}
return eventTimeModel.format(eventTimeModel.calcDuration(event));
}
public String getHtmlValue(Reservation object) {
String dateString= getValue(object);
return dateString;
}
}
| 04900db4-clienttest | src/org/rapla/plugin/eventtimecalculator/DurationColumnReservation.java | Java | gpl3 | 1,062 |
package org.rapla.plugin.eventtimecalculator;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.tableview.AppointmentTableColumn;
/**
* User: kuestermann
* Date: 22.08.12
* Time: 09:30
*/
public final class DurationColumnAppoimentBlock extends DurationColumn implements AppointmentTableColumn {
EventTimeCalculatorFactory factory;
private EventTimeModel eventTimeModel;
public DurationColumnAppoimentBlock(RaplaContext context) throws RaplaException {
super(context);
factory = context.lookup(EventTimeCalculatorFactory.class);
}
public String getValue(AppointmentBlock block) {
if ( !validConf )
{
eventTimeModel = factory.getEventTimeModel();
validConf = true;
}
return eventTimeModel.format(eventTimeModel.calcDuration(block));
}
public String getHtmlValue(AppointmentBlock block) {
String dateString = getValue(block);
return dateString;
}
}
| 04900db4-clienttest | src/org/rapla/plugin/eventtimecalculator/DurationColumnAppoimentBlock.java | Java | gpl3 | 1,093 |
package org.rapla.plugin.eventtimecalculator.server;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.plugin.eventtimecalculator.DurationColumnAppoimentBlock;
import org.rapla.plugin.eventtimecalculator.DurationColumnReservation;
import org.rapla.plugin.eventtimecalculator.DurationCounter;
import org.rapla.plugin.eventtimecalculator.EventTimeCalculatorFactory;
import org.rapla.plugin.eventtimecalculator.EventTimeCalculatorPlugin;
import org.rapla.plugin.tableview.TableViewExtensionPoints;
import org.rapla.server.ServerServiceContainer;
public class EventTimeCalculatorServerPlugin implements PluginDescriptor<ServerServiceContainer> {
/**
* provides the resource file of the plugin.
* uses the extension points to provide the different services of the plugin.
*/
public void provideServices(ServerServiceContainer container, Configuration config) {
container.addContainerProvidedComponent(EventTimeCalculatorPlugin.RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig(EventTimeCalculatorPlugin.RESOURCE_FILE.getId()));
if (!config.getAttributeAsBoolean("enabled", EventTimeCalculatorPlugin.ENABLE_BY_DEFAULT))
return;
container.addContainerProvidedComponent(EventTimeCalculatorFactory.class,EventTimeCalculatorFactory.class, config);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, DurationColumnAppoimentBlock.class, config);
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, DurationColumnReservation.class, config);
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_SUMMARY, DurationCounter.class, config);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_SUMMARY, DurationCounter.class, config);
}
} | 04900db4-clienttest | src/org/rapla/plugin/eventtimecalculator/server/EventTimeCalculatorServerPlugin.java | Java | gpl3 | 2,013 |
package org.rapla.plugin.eventtimecalculator;
import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;
import org.rapla.components.tablesorter.TableSorter;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.tableview.internal.AppointmentTableModel;
import org.rapla.plugin.tableview.internal.ReservationTableModel;
import org.rapla.plugin.tableview.internal.SummaryExtension;
/**
* User: kuestermann
* Date: 22.08.12
* Time: 09:29
*/
public final class DurationCounter extends RaplaComponent implements SummaryExtension {
EventTimeCalculatorFactory factory;
public DurationCounter(RaplaContext context) throws RaplaException {
super(context);
factory = context.lookup(EventTimeCalculatorFactory.class);
}
public void init(final JTable table, JPanel summaryRow) {
final JLabel counter = new JLabel();
summaryRow.add( Box.createHorizontalStrut(30));
summaryRow.add( counter);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0)
{
EventTimeModel eventTimeModel = factory.getEventTimeModel();
int[] selectedRows = table.getSelectedRows();
TableModel model = table.getModel();
TableSorter sorterModel = null;
if ( model instanceof TableSorter)
{
sorterModel = ((TableSorter) model);
model = ((TableSorter)model).getTableModel();
}
long totalduration = 0;
for ( int row:selectedRows)
{
if (sorterModel != null)
row = sorterModel.modelIndex(row);
if ( model instanceof AppointmentTableModel)
{
AppointmentBlock block = ((AppointmentTableModel) model).getAppointmentAt(row);
long duration = eventTimeModel.calcDuration(block);
totalduration+= duration;
}
if ( model instanceof ReservationTableModel)
{
Reservation block = ((ReservationTableModel) model).getReservationAt(row);
long duration = eventTimeModel.calcDuration(block);
if ( duration <0)
{
totalduration = -1;
break;
}
totalduration+= duration;
}
}
I18nBundle i18n = getService(EventTimeCalculatorPlugin.RESOURCE_FILE);
String durationString = totalduration < 0 ? i18n.getString("infinite") : eventTimeModel.format(totalduration);
counter.setText( i18n.getString("total_duration") + " " + durationString);
}
});
}
}
| 04900db4-clienttest | src/org/rapla/plugin/eventtimecalculator/DurationCounter.java | Java | gpl3 | 3,507 |
/*--------------------------------------------------------------------------*
| 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.plugin.tempatewizard;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.swing.MenuElement;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.edit.SaveUndo;
import org.rapla.gui.toolkit.IdentifiableMenuEntry;
import org.rapla.gui.toolkit.MenuScroller;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaMenuItem;
/** This ReservationWizard displays no wizard and directly opens a ReservationEdit Window
*/
public class TemplateWizard extends RaplaGUIComponent implements IdentifiableMenuEntry, ActionListener, ModificationListener
{
Map<Component,String> componentMap = new HashMap<Component, String>();
Collection<String> templateNames;
public TemplateWizard(RaplaContext context) throws RaplaException{
super(context);
getUpdateModule().addModificationListener( this);
updateTemplateNames();
}
public String getId() {
return "020_templateWizard";
}
@Override
public void dataChanged(ModificationEvent evt) throws RaplaException {
if ( evt.getInvalidateInterval() != null)
{
updateTemplateNames();
}
}
private Collection<String> updateTemplateNames() throws RaplaException {
return templateNames = getQuery().getTemplateNames();
}
public MenuElement getMenuElement() {
componentMap.clear();
boolean canCreateReservation = canCreateReservation();
MenuElement element;
if (templateNames.size() == 0)
{
return null;
}
if ( templateNames.size() == 1)
{
RaplaMenuItem item = new RaplaMenuItem( getId());
item.setEnabled( canAllocate() && canCreateReservation);
item.setText(getString("new_reservations_from_template"));
item.setIcon( getIcon("icon.new"));
item.addActionListener( this);
String template = templateNames.iterator().next();
componentMap.put( item, template);
element = item;
}
else
{
RaplaMenu item = new RaplaMenu( getId());
item.setEnabled( canAllocate() && canCreateReservation);
item.setText(getString("new_reservations_from_template"));
item.setIcon( getIcon("icon.new"));
Set<String> templateSet = new TreeSet<String>(templateNames);
SortedMap<String, Set<String>> keyGroup = new TreeMap<String, Set<String>>();
if ( templateSet.size() > 10)
{
for ( String string:templateSet)
{
if (string.length() == 0)
{
continue;
}
String firstChar = string.substring( 0,1);
Set<String> group = keyGroup.get( firstChar);
if ( group == null)
{
group = new TreeSet<String>();
keyGroup.put( firstChar, group);
}
group.add(string);
}
SortedMap<String, Set<String>> merged = merge( keyGroup);
for ( String subMenuName: merged.keySet())
{
RaplaMenu subMenu = new RaplaMenu( getId());
item.setIcon( getIcon("icon.new"));
subMenu.setText( subMenuName);
Set<String> set = merged.get( subMenuName);
int maxItems = 20;
if ( set.size() >= maxItems)
{
int millisToScroll = 40;
MenuScroller.setScrollerFor( subMenu, maxItems , millisToScroll);
}
addTemplates(subMenu, set);
item.add( subMenu);
}
}
else
{
addTemplates( item, templateSet);
}
element = item;
}
return element;
}
public void addTemplates(RaplaMenu item,
Set<String> templateSet) {
for ( String templateName:templateSet)
{
RaplaMenuItem newItem = new RaplaMenuItem(templateName);
componentMap.put( newItem, templateName);
newItem.setText( templateName );
item.add( newItem);
newItem.addActionListener( this);
}
}
private SortedMap<String, Set<String>> merge(
SortedMap<String, Set<String>> keyGroup)
{
SortedMap<String,Set<String>> result = new TreeMap<String, Set<String>>();
String beginnChar = null;
String currentChar = null;
Set<String> currentSet = null;
for ( String key: keyGroup.keySet() )
{
Set<String> set = keyGroup.get( key);
if ( currentSet == null)
{
currentSet = new TreeSet<String>();
beginnChar = key;
currentChar = key;
}
if ( !key.equals( currentChar))
{
if ( set.size() + currentSet.size() > 10)
{
String storeKey;
if ( beginnChar != null && !beginnChar.equals(currentChar))
{
storeKey = beginnChar + "-" + currentChar;
}
else
{
storeKey = currentChar;
}
result.put( storeKey, currentSet);
currentSet = new TreeSet<String>();
beginnChar = key;
currentChar = key;
}
else
{
currentChar = key;
}
}
currentSet.addAll( set);
}
String storeKey;
if ( beginnChar != null)
{
if ( !beginnChar.equals(currentChar))
{
storeKey = beginnChar + "-" + currentChar;
}
else
{
storeKey = currentChar;
}
result.put( storeKey, currentSet);
}
return result;
}
public void actionPerformed(ActionEvent e) {
try
{
CalendarModel model = getService(CalendarModel.class);
Date beginn = getStartDate( model);
Object source = e.getSource();
String templateName = componentMap.get( source);
List<Reservation> newReservations;
Collection<Reservation> reservations = getQuery().getTemplateReservations(templateName);
if (reservations.size() > 0)
{
newReservations = copy( reservations, beginn);
Collection<Allocatable> markedAllocatables = model.getMarkedAllocatables();
if (markedAllocatables != null )
{
for (Reservation event: newReservations)
{
if ( event.getAllocatables().length == 0)
{
for ( Allocatable alloc:markedAllocatables)
{
if (!event.hasAllocated(alloc))
{
event.addAllocatable( alloc);
}
}
}
}
}
}
else
{
showException(new EntityNotFoundException("Template " + templateName + " not found"), getMainComponent());
return;
}
if ( newReservations.size() == 1)
{
Reservation next = newReservations.iterator().next();
getReservationController().edit( next);
}
else
{
Collection<Reservation> list = new ArrayList<Reservation>();
for ( Reservation reservation:newReservations)
{
Reservation cast = reservation;
User lastChangedBy = cast.getLastChangedBy();
if ( lastChangedBy != null && !lastChangedBy.equals(getUser()))
{
throw new RaplaException("Reservation " + cast + " has wrong user " + lastChangedBy);
}
list.add( cast);
}
SaveUndo<Reservation> saveUndo = new SaveUndo<Reservation>(getContext(), list, null);
getModification().getCommandHistory().storeAndExecute( saveUndo);
}
}
catch (RaplaException ex)
{
showException( ex, getMainComponent());
}
}
}
| 04900db4-clienttest | src/org/rapla/plugin/tempatewizard/TemplateWizard.java | Java | gpl3 | 8,599 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.tempatewizard;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
public class TempateWizardPlugin implements PluginDescriptor<ClientServiceContainer> {
public static final String PLUGIN_CLASS = TempateWizardPlugin.class.getName();
public static boolean ENABLE_BY_DEFAULT = true;
public void provideServices(ClientServiceContainer container, Configuration config) {
if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( RaplaClientExtensionPoints.RESERVATION_WIZARD_EXTENSION, TemplateWizard.class);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/tempatewizard/TempateWizardPlugin.java | Java | gpl3 | 1,711 |
package org.rapla.plugin.timeslot;
public class Timeslot implements Comparable<Timeslot>
{
String name;
int minuteOfDay;
public Timeslot(String name, int minuteOfDay)
{
this.name = name;
this.minuteOfDay = minuteOfDay;
}
public String getName() {
return name;
}
public int getMinuteOfDay() {
return minuteOfDay;
}
public int compareTo(Timeslot other) {
if ( minuteOfDay == other.minuteOfDay)
{
return name.compareTo( other.name);
}
return minuteOfDay < other.minuteOfDay ? -1 : 1;
}
public String toString()
{
return name + " " + (minuteOfDay / 60) +":" + (minuteOfDay % 60);
}
} | 04900db4-clienttest | src/org/rapla/plugin/timeslot/Timeslot.java | Java | gpl3 | 652 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.timeslot;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
public class TimeslotPlugin implements PluginDescriptor<ClientServiceContainer>
{
public final static boolean ENABLE_BY_DEFAULT = false;
public void provideServices(ClientServiceContainer container, Configuration config) {
container.addContainerProvidedComponent( RaplaClientExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION,TimeslotOption.class);
if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT))
return;
container.addContainerProvidedComponent(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,CompactDayViewFactory.class);
container.addContainerProvidedComponent(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,CompactWeekViewFactory.class);
container.addContainerProvidedComponent(TimeslotProvider.class,TimeslotProvider.class,config );
}
}
| 04900db4-clienttest | src/org/rapla/plugin/timeslot/TimeslotPlugin.java | Java | gpl3 | 1,980 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.timeslot;
import javax.swing.Icon;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.SwingCalendarView;
import org.rapla.gui.SwingViewFactory;
import org.rapla.gui.images.Images;
public class CompactDayViewFactory extends RaplaComponent implements SwingViewFactory
{
public final static String DAY_TIMESLOT = "day_timeslot";
public CompactDayViewFactory( RaplaContext context )
{
super( context );
}
public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException
{
return new SwingCompactDayCalendar( context, model, editable);
}
public String getViewId()
{
return DAY_TIMESLOT;
}
public String getName()
{
return getString(DAY_TIMESLOT);
}
Icon icon;
public Icon getIcon()
{
if ( icon == null) {
icon = Images.getIcon("/org/rapla/plugin/compactweekview/images/week_compact.png");
}
return icon;
}
public String getMenuSortKey() {
return "B2";
}
}
| 04900db4-clienttest | src/org/rapla/plugin/timeslot/CompactDayViewFactory.java | Java | gpl3 | 2,170 |
/*--------------------------------------------------------------------------*
| 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.plugin.timeslot;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.JLabel;
import org.rapla.components.calendarview.Block;
import org.rapla.components.calendarview.GroupStartTimesStrategy;
import org.rapla.components.calendarview.swing.AbstractSwingCalendar;
import org.rapla.components.calendarview.swing.SwingBlock;
import org.rapla.components.calendarview.swing.SwingCompactWeekView;
import org.rapla.components.calendarview.swing.ViewListener;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarOptions;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.abstractcalendar.AbstractRaplaBlock;
import org.rapla.plugin.abstractcalendar.AbstractRaplaSwingCalendar;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.plugin.abstractcalendar.RaplaCalendarViewListener;
public class SwingCompactDayCalendar extends AbstractRaplaSwingCalendar
{
List<Timeslot> timeslots;
public SwingCompactDayCalendar(RaplaContext sm,CalendarModel settings, boolean editable) throws RaplaException {
super( sm, settings, editable);
}
protected AbstractSwingCalendar createView(boolean showScrollPane) throws RaplaException
{
SwingCompactWeekView compactWeekView = new SwingCompactWeekView( showScrollPane ) {
@Override
protected JComponent createColumnHeader(Integer column) {
JLabel component = (JLabel) super.createColumnHeader(column);
if ( column != null)
{
try {
List<Allocatable> sortedAllocatables = getSortedAllocatables();
Allocatable allocatable = sortedAllocatables.get(column);
String name = allocatable.getName( getLocale());
component.setText( name);
} catch (RaplaException e) {
}
}
else
{
String dateText = getRaplaLocale().formatDateShort(getStartDate());
component.setText( dateText);
}
return component;
}
protected int getColumnCount()
{
try {
Allocatable[] selectedAllocatables =model.getSelectedAllocatables();
return selectedAllocatables.length;
} catch (RaplaException e) {
return 0;
}
}
@Override
public TimeInterval normalizeBlockIntervall(SwingBlock block)
{
Date start = block.getStart();
Date end = block.getEnd();
for (Timeslot slot:timeslots)
{
int minuteOfDay = DateTools.getMinuteOfDay( start.getTime());
if ( minuteOfDay >= slot.minuteOfDay)
{
start = new Date(DateTools.cutDate( start).getTime() + slot.minuteOfDay);
break;
}
}
for (Timeslot slot:timeslots)
{
int minuteOfDay = DateTools.getMinuteOfDay( end.getTime());
if ( minuteOfDay < slot.minuteOfDay)
{
end = new Date(DateTools.cutDate( end).getTime() + slot.minuteOfDay);
}
if ( slot.minuteOfDay > minuteOfDay)
{
break;
}
}
return new TimeInterval(start,end);
}
};
compactWeekView.setDaysInView(1);
return compactWeekView;
}
protected ViewListener createListener() throws RaplaException {
return new RaplaCalendarViewListener(getContext(), model, view.getComponent()) {
@Override
protected Collection<Allocatable> getMarkedAllocatables()
{
List<Allocatable> selectedAllocatables = getSortedAllocatables();
int columns = selectedAllocatables.size();
Set<Allocatable> allSelected = new HashSet<Allocatable>();
int slots = columns*timeslots.size();
for ( int i=0;i<slots;i++)
{
if ( ((SwingCompactWeekView)view).isSelected(i))
{
int column = i%columns;
Allocatable allocatable = selectedAllocatables.get( column);
allSelected.add( allocatable);
}
}
if ( selectedAllocatables.size() == 1 ) {
allSelected.add(selectedAllocatables.get(0));
}
return allSelected;
}
@Override
public void selectionChanged(Date start,Date end)
{
TimeInterval inter = getMarkedInterval(start);
super.selectionChanged(inter.getStart(), inter.getEnd());
}
protected TimeInterval getMarkedInterval(Date start) {
List<Allocatable> selectedAllocatables = getSortedAllocatables();
int columns = selectedAllocatables.size();
Date end;
Integer startTime = null;
Integer endTime = null;
int slots = columns*timeslots.size();
for ( int i=0;i<slots;i++)
{
if ( ((SwingCompactWeekView)view).isSelected(i))
{
int index = i/columns;
int time = timeslots.get(index).minuteOfDay;
if ( startTime == null || time < startTime )
{
startTime = time;
}
time = index<timeslots.size()-1 ? timeslots.get(index+1).minuteOfDay : 24* 60;
if ( endTime == null || time >= endTime )
{
endTime = time;
}
}
}
CalendarOptions calendarOptions = getCalendarOptions();
if ( startTime == null)
{
startTime = calendarOptions.getWorktimeStartMinutes();
}
if ( endTime == null)
{
endTime = calendarOptions.getWorktimeEndMinutes() + (calendarOptions.isWorktimeOvernight() ? 24*60:0);
}
Calendar cal = getRaplaLocale().createCalendar();
cal.setTime ( start );
cal.set( Calendar.HOUR_OF_DAY, startTime/60);
cal.set( Calendar.MINUTE, startTime%60);
start = cal.getTime();
cal.set( Calendar.HOUR_OF_DAY, endTime/60);
cal.set( Calendar.MINUTE, endTime%60);
end = cal.getTime();
TimeInterval intervall = new TimeInterval(start,end);
return intervall;
}
@Override
public void moved(Block block, Point p, Date newStart, int slotNr) {
int index= slotNr;//getIndex( selectedAllocatables, block );
if ( index < 0)
{
return;
}
try
{
final List<Allocatable> selectedAllocatables = getSortedAllocatables();
int columns = selectedAllocatables.size();
int column = index%columns;
Allocatable newAlloc = selectedAllocatables.get(column);
AbstractRaplaBlock raplaBlock = (AbstractRaplaBlock)block;
Allocatable oldAlloc = raplaBlock.getGroupAllocatable();
int rowIndex = index/columns;
Timeslot timeslot = timeslots.get(rowIndex);
int time = timeslot.minuteOfDay;
Calendar cal = getRaplaLocale().createCalendar();
int lastMinuteOfDay;
cal.setTime ( block.getStart() );
lastMinuteOfDay = cal.get( Calendar.HOUR_OF_DAY) * 60 + cal.get( Calendar.MINUTE);
boolean sameTimeSlot = true;
if ( lastMinuteOfDay < time)
{
sameTimeSlot = false;
}
if ( rowIndex +1 < timeslots.size())
{
Timeslot nextTimeslot = timeslots.get(rowIndex+1);
if ( lastMinuteOfDay >= nextTimeslot.minuteOfDay )
{
sameTimeSlot = false;
}
}
cal.setTime ( newStart );
if ( sameTimeSlot)
{
time = lastMinuteOfDay;
}
cal.set( Calendar.HOUR_OF_DAY, time /60);
cal.set( Calendar.MINUTE, time %60);
newStart = cal.getTime();
if ( newAlloc != null && oldAlloc != null && !newAlloc.equals(oldAlloc))
{
AppointmentBlock appointmentBlock= raplaBlock.getAppointmentBlock();
getReservationController().exchangeAllocatable(appointmentBlock, oldAlloc,newAlloc, newStart, getMainComponent(),p);
}
else
{
moved( block,p ,newStart);
}
}
catch (RaplaException ex) {
showException(ex, getMainComponent());
}
}
};
}
protected RaplaBuilder createBuilder() throws RaplaException
{
RaplaBuilder builder = super.createBuilder();
timeslots = getService(TimeslotProvider.class).getTimeslots();
List<Integer> startTimes = new ArrayList<Integer>();
for (Timeslot slot:timeslots) {
startTimes.add( slot.getMinuteOfDay());
}
final List<Allocatable> allocatables = getSortedAllocatables();
builder.setSmallBlocks( true );
GroupStartTimesStrategy strategy = new GroupStartTimesStrategy();
strategy.setAllocatables(allocatables);
strategy.setFixedSlotsEnabled( true);
strategy.setResolveConflictsEnabled( false );
strategy.setStartTimes( startTimes );
builder.setBuildStrategy( strategy);
String[] slotNames = new String[ timeslots.size() ];
int maxSlotLength = 5;
for (int i = 0; i <timeslots.size(); i++ ) {
String slotName = timeslots.get( i ).getName();
maxSlotLength = Math.max( maxSlotLength, slotName.length());
slotNames[i] = slotName;
}
((SwingCompactWeekView)view).setLeftColumnSize( 30+ maxSlotLength * 6);
builder.setSplitByAllocatables( false );
((SwingCompactWeekView)view).setSlots( slotNames );
return builder;
}
protected void configureView() throws RaplaException {
view.setToDate(model.getSelectedDate());
// if ( !view.isEditable() ) {
// view.setSlotSize( model.getSize());
// } else {
// view.setSlotSize( 200 );
// }
}
public int getIncrementSize()
{
return Calendar.DATE;
}
}
| 04900db4-clienttest | src/org/rapla/plugin/timeslot/SwingCompactDayCalendar.java | Java | gpl3 | 11,901 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.timeslot.server;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.plugin.timeslot.TimeslotPlugin;
import org.rapla.plugin.timeslot.TimeslotProvider;
import org.rapla.server.RaplaServerExtensionPoints;
import org.rapla.server.ServerServiceContainer;
public class TimeslotServerPlugin implements PluginDescriptor<ServerServiceContainer>
{
public void provideServices(ServerServiceContainer container, Configuration config) {
if ( !config.getAttributeAsBoolean("enabled", TimeslotPlugin.ENABLE_BY_DEFAULT))
return;
container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,CompactHTMLDayViewFactory.class);
container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,CompactHTMLWeekViewFactory.class);
container.addContainerProvidedComponent(TimeslotProvider.class,TimeslotProvider.class,config );
}
}
| 04900db4-clienttest | src/org/rapla/plugin/timeslot/server/TimeslotServerPlugin.java | Java | gpl3 | 1,950 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.timeslot.server;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory;
import org.rapla.servletpages.RaplaPageGenerator;
public class CompactHTMLDayViewFactory extends RaplaComponent implements HTMLViewFactory
{
public final static String DAY_TIMESLOT = "day_timeslot";
public CompactHTMLDayViewFactory( RaplaContext context )
{
super( context );
}
public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model)
{
return new HTMLCompactDayViewPage( context, model);
}
public String getViewId()
{
return DAY_TIMESLOT;
}
public String getName()
{
return getString(DAY_TIMESLOT);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/timeslot/server/CompactHTMLDayViewFactory.java | Java | gpl3 | 1,790 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.timeslot.server;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
import org.rapla.components.calendarview.GroupStartTimesStrategy;
import org.rapla.components.calendarview.html.AbstractHTMLView;
import org.rapla.components.calendarview.html.HTMLCompactWeekView;
import org.rapla.components.util.xml.XMLWriter;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarOptions;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.plugin.abstractcalendar.server.AbstractHTMLCalendarPage;
import org.rapla.plugin.timeslot.Timeslot;
import org.rapla.plugin.timeslot.TimeslotProvider;
public class HTMLCompactViewPage extends AbstractHTMLCalendarPage
{
public HTMLCompactViewPage( RaplaContext context, CalendarModel calendarModel)
{
super( context, calendarModel);
}
protected AbstractHTMLView createCalendarView() {
HTMLCompactWeekView weekView = new HTMLCompactWeekView()
{
@Override
public void rebuild() {
String weeknumberString = MessageFormat.format(getString("calendarweek.abbreviation"), getStartDate());
setWeeknumber(weeknumberString);
super.rebuild();
}
};
weekView.setLeftColumnSize(0.01);
return weekView;
}
@Override
protected void configureView() throws RaplaException {
CalendarOptions opt = getCalendarOptions();
Set<Integer> excludeDays = opt.getExcludeDays();
view.setExcludeDays( excludeDays );
view.setDaysInView( opt.getDaysInWeekview());
int firstDayOfWeek = opt.getFirstDayOfWeek();
view.setFirstWeekday( firstDayOfWeek);
view.setExcludeDays( excludeDays );
}
protected RaplaBuilder createBuilder() throws RaplaException
{
List<Timeslot> timeslots = getService(TimeslotProvider.class).getTimeslots();
List<Integer> startTimes = new ArrayList<Integer>();
for (Timeslot slot:timeslots) {
startTimes.add( slot.getMinuteOfDay());
}
RaplaBuilder builder = super.createBuilder();
builder.setSmallBlocks( true );
GroupStartTimesStrategy strategy = new GroupStartTimesStrategy();
strategy.setFixedSlotsEnabled( true);
strategy.setResolveConflictsEnabled( false );
strategy.setStartTimes( startTimes );
builder.setBuildStrategy( strategy);
builder.setSplitByAllocatables( false );
String[] slotNames = new String[ timeslots.size() ];
for (int i = 0; i <timeslots.size(); i++ ) {
slotNames[i] = XMLWriter.encode( timeslots.get( i ).getName());
}
((HTMLCompactWeekView)view).setSlots( slotNames );
return builder;
}
protected int getIncrementSize() {
return Calendar.WEEK_OF_YEAR;
}
}
| 04900db4-clienttest | src/org/rapla/plugin/timeslot/server/HTMLCompactViewPage.java | Java | gpl3 | 3,925 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.timeslot.server;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.rapla.components.calendarview.GroupStartTimesStrategy;
import org.rapla.components.calendarview.html.AbstractHTMLView;
import org.rapla.components.calendarview.html.HTMLCompactWeekView;
import org.rapla.components.util.xml.XMLWriter;
import org.rapla.entities.domain.Allocatable;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarOptions;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.plugin.abstractcalendar.server.AbstractHTMLCalendarPage;
import org.rapla.plugin.timeslot.Timeslot;
import org.rapla.plugin.timeslot.TimeslotProvider;
public class HTMLCompactDayViewPage extends AbstractHTMLCalendarPage
{
public HTMLCompactDayViewPage( RaplaContext context, CalendarModel calendarModel)
{
super( context, calendarModel);
}
protected AbstractHTMLView createCalendarView() {
HTMLCompactWeekView weekView = new HTMLCompactWeekView()
{
protected List<String> getHeaderNames()
{
List<String> headerNames = new ArrayList<String>();
try
{
List<Allocatable> sortedAllocatables = getSortedAllocatables();
for (Allocatable alloc: sortedAllocatables)
{
headerNames.add( alloc.getName( getLocale()));
}
}
catch (RaplaException ex)
{
}
return headerNames;
}
protected int getColumnCount()
{
try {
Allocatable[] selectedAllocatables =model.getSelectedAllocatables();
return selectedAllocatables.length;
} catch (RaplaException e) {
return 0;
}
}
@Override
public void rebuild() {
setWeeknumber(getRaplaLocale().formatDateShort(getStartDate()));
super.rebuild();
}
};
weekView.setLeftColumnSize(0.01);
return weekView;
}
@Override
protected void configureView() throws RaplaException {
CalendarOptions opt = getCalendarOptions();
int days = 1;
view.setDaysInView( days);
int firstDayOfWeek = opt.getFirstDayOfWeek();
view.setFirstWeekday( firstDayOfWeek);
Set<Integer> excludeDays = new HashSet<Integer>();
view.setExcludeDays( excludeDays );
}
protected RaplaBuilder createBuilder() throws RaplaException
{
List<Timeslot> timeslots = getService(TimeslotProvider.class).getTimeslots();
List<Integer> startTimes = new ArrayList<Integer>();
for (Timeslot slot:timeslots) {
startTimes.add( slot.getMinuteOfDay());
}
RaplaBuilder builder = super.createBuilder();
final List<Allocatable> allocatables = getSortedAllocatables();
builder.selectAllocatables( allocatables);
builder.setSmallBlocks( true );
GroupStartTimesStrategy strategy = new GroupStartTimesStrategy();
strategy.setAllocatables(allocatables);
strategy.setFixedSlotsEnabled( true);
strategy.setResolveConflictsEnabled( false );
strategy.setStartTimes( startTimes );
builder.setBuildStrategy( strategy);
String[] slotNames = new String[ timeslots.size() ];
for (int i = 0; i <timeslots.size(); i++ ) {
slotNames[i] = XMLWriter.encode( timeslots.get( i ).getName());
}
((HTMLCompactWeekView)view).setSlots( slotNames );
return builder;
}
public int getIncrementSize() {
return Calendar.DAY_OF_YEAR;
}
}
| 04900db4-clienttest | src/org/rapla/plugin/timeslot/server/HTMLCompactDayViewPage.java | Java | gpl3 | 4,728 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.timeslot.server;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory;
import org.rapla.servletpages.RaplaPageGenerator;
public class CompactHTMLWeekViewFactory extends RaplaComponent implements HTMLViewFactory
{
public final static String WEEK_TIMESLOT = "week_timeslot";
public CompactHTMLWeekViewFactory( RaplaContext context )
{
super( context );
}
public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) throws RaplaException
{
return new HTMLCompactViewPage( context, model);
}
public String getViewId()
{
return WEEK_TIMESLOT;
}
public String getName()
{
return getString(WEEK_TIMESLOT);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/timeslot/server/CompactHTMLWeekViewFactory.java | Java | gpl3 | 1,856 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.timeslot;
import javax.swing.Icon;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.SwingCalendarView;
import org.rapla.gui.SwingViewFactory;
import org.rapla.gui.images.Images;
public class CompactWeekViewFactory extends RaplaComponent implements SwingViewFactory
{
public final static String WEEK_TIMESLOT = "week_timeslot";
public CompactWeekViewFactory( RaplaContext context )
{
super( context );
}
public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException
{
return new SwingCompactCalendar( context, model, editable);
}
public String getViewId()
{
return WEEK_TIMESLOT;
}
public String getName()
{
return getString(WEEK_TIMESLOT);
}
Icon icon;
public Icon getIcon()
{
if ( icon == null) {
icon = Images.getIcon("/org/rapla/plugin/compactweekview/images/week_compact.png");
}
return icon;
}
public String getMenuSortKey() {
return "B2";
}
}
| 04900db4-clienttest | src/org/rapla/plugin/timeslot/CompactWeekViewFactory.java | Java | gpl3 | 2,173 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.timeslot;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import org.rapla.components.calendar.RaplaTime;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.util.ParseDateException;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.gui.DefaultPluginOption;
import org.rapla.gui.toolkit.RaplaButton;
public class TimeslotOption extends DefaultPluginOption
{
JPanel list = new JPanel();
List<Timeslot> timeslots;
class TimeslotRow
{
RaplaTime raplatime;
JTextField textfield = new JTextField();
RaplaButton delete = new RaplaButton(RaplaButton.SMALL);
public TimeslotRow(Timeslot slot)
{
addCopyPaste( textfield);
textfield.setText( slot.getName());
int minuteOfDay = slot.getMinuteOfDay();
int hour = minuteOfDay /60;
int minute = minuteOfDay %60;
RaplaLocale raplaLocale = getRaplaLocale();
raplatime = new RaplaTime(raplaLocale.getLocale(),raplaLocale.getTimeZone());
raplatime.setTime(hour, minute);
delete.setIcon(getIcon("icon.remove"));
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
rows.remove( TimeslotRow.this);
update();
}
});
}
}
public TimeslotOption(RaplaContext sm)
{
super(sm);
}
List<TimeslotRow> rows = new ArrayList<TimeslotOption.TimeslotRow>();
JPanel main;
protected JPanel createPanel() throws RaplaException
{
main = super.createPanel();
JScrollPane jScrollPane = new JScrollPane(list);
JPanel container = new JPanel();
container.setLayout( new BorderLayout());
container.add(jScrollPane,BorderLayout.CENTER);
JPanel header = new JPanel();
RaplaButton reset = new RaplaButton(RaplaButton.SMALL);
RaplaButton resetButton = reset;
resetButton.setIcon(getIcon("icon.remove"));
resetButton.setText(getString("reset"));
RaplaButton newButton = new RaplaButton(RaplaButton.SMALL);
newButton.setIcon(getIcon("icon.new"));
newButton.setText(getString("new"));
header.add( newButton);
header.add( resetButton );
newButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int minuteOfDay = 0;
String lastName = "";
Timeslot slot = new Timeslot(lastName, minuteOfDay);
rows.add( new TimeslotRow(slot));
update();
}
});
resetButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
timeslots = TimeslotProvider.getDefaultTimeslots(getRaplaLocale());
initRows();
update();
}
});
container.add(header,BorderLayout.NORTH);
main.add( container, BorderLayout.CENTER);
return main;
}
protected void initRows() {
rows.clear();
for ( Timeslot slot:timeslots)
{
TimeslotRow row = new TimeslotRow( slot);
rows.add( row);
}
TimeslotRow firstRow = rows.get(0);
firstRow.delete.setEnabled( false);
firstRow.raplatime.setEnabled( false);
list.removeAll();
}
protected void update() {
timeslots = mapToTimeslots();
list.removeAll();
TableLayout tableLayout = new TableLayout();
list.setLayout(tableLayout);
tableLayout.insertColumn(0,TableLayout.PREFERRED);
tableLayout.insertColumn(1,10);
tableLayout.insertColumn(2,TableLayout.PREFERRED);
tableLayout.insertColumn(3,10);
tableLayout.insertColumn(4,TableLayout.FILL);
list.setLayout( tableLayout);
tableLayout.insertRow(0, TableLayout.PREFERRED);
list.add(new JLabel("time"),"2,0");
list.add(new JLabel("name"),"4,0");
int i = 0;
for ( TimeslotRow row:rows)
{
tableLayout.insertRow(++i, TableLayout.MINIMUM);
list.add(row.delete,"0,"+i);
list.add(row.raplatime,"2,"+i);
list.add(row.textfield,"4,"+i);
}
list.validate();
list.repaint();
main.validate();
main.repaint();
}
protected void addChildren( DefaultConfiguration newConfig)
{
if (!activate.isSelected())
{
return;
}
for ( Timeslot slot: timeslots)
{
DefaultConfiguration conf = new DefaultConfiguration("timeslot");
conf.setAttribute("name", slot.getName());
int minuteOfDay = slot.getMinuteOfDay();
Calendar cal = getRaplaLocale().createCalendar();
cal.set(Calendar.HOUR_OF_DAY, minuteOfDay / 60);
cal.set(Calendar.MINUTE, minuteOfDay % 60);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
SerializableDateTimeFormat format = getRaplaLocale().getSerializableFormat();
String time = format.formatTime(cal.getTime());
conf.setAttribute("time", time);
newConfig.addChild( conf);
}
if ( getContext().has(TimeslotProvider.class))
{
try {
getService(TimeslotProvider.class).update( newConfig);
} catch (ParseDateException e) {
getLogger().error(e.getMessage());
}
}
}
protected List<Timeslot> mapToTimeslots() {
List<Timeslot> timeslots = new ArrayList<Timeslot>();
for ( TimeslotRow row: rows)
{
String name = row.textfield.getText();
RaplaTime raplatime = row.raplatime;
Date time = raplatime.getTime();
Calendar cal = getRaplaLocale().createCalendar();
if ( time != null )
{
cal.setTime( time);
int minuteOfDay = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
timeslots.add( new Timeslot( name, minuteOfDay));
}
}
Collections.sort( timeslots);
return timeslots;
}
protected void readConfig( Configuration config)
{
RaplaLocale raplaLocale = getRaplaLocale();
try {
timeslots = TimeslotProvider.parseConfig(config, raplaLocale);
} catch (ParseDateException e) {
}
if ( timeslots == null)
{
timeslots = TimeslotProvider.getDefaultTimeslots(raplaLocale);
}
initRows();
update();
}
public void show() throws RaplaException {
super.show();
}
public void commit() throws RaplaException {
timeslots = mapToTimeslots();
super.commit();
}
/**
* @see org.rapla.gui.DefaultPluginOption#getPluginClass()
*/
public Class<? extends PluginDescriptor<?>> getPluginClass() {
return TimeslotPlugin.class;
}
public String getName(Locale locale) {
return "Timeslot Plugin";
}
}
| 04900db4-clienttest | src/org/rapla/plugin/timeslot/TimeslotOption.java | Java | gpl3 | 8,120 |
package org.rapla.plugin.timeslot;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.ParseDateException;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaLocale;
public class TimeslotProvider extends RaplaComponent {
private ArrayList<Timeslot> timeslots;
public TimeslotProvider(RaplaContext context, Configuration config) throws ParseDateException
{
super(context);
update(config);
// timeslots.clear();
// timeslots.add(new Timeslot("1. Stunde", 7*60 + 45));
// timeslots.add(new Timeslot("- Pause (5m)", 8*60 + 30));
// timeslots.add(new Timeslot("2. Stunde", 8 * 60 + 35 ));
// timeslots.add(new Timeslot("- Pause (15m)", 9 * 60 + 20 ));
// timeslots.add(new Timeslot("3. Stunde", 9 * 60 + 35 ));
// timeslots.add(new Timeslot("- Pause (5m)", 10*60 + 20));
// timeslots.add(new Timeslot("4. Stunde", 10 * 60 + 25 ));
// timeslots.add(new Timeslot("- Pause (15m)", 11 * 60 + 10 ));
// timeslots.add(new Timeslot("5. Stunde", 11 * 60 + 25 ));
// timeslots.add(new Timeslot("- Pause (5m)", 12*60 + 10));
// timeslots.add(new Timeslot("6. Stunde", 12 * 60 + 15 ));
// timeslots.add(new Timeslot("Nachmittag", 13 * 60 + 0 ));
}
public void update(Configuration config) throws ParseDateException {
ArrayList<Timeslot> timeslots = parseConfig(config, getRaplaLocale());
if ( timeslots == null)
{
timeslots = getDefaultTimeslots(getRaplaLocale());
}
this.timeslots = timeslots;
}
public static ArrayList<Timeslot> parseConfig(Configuration config,RaplaLocale locale) throws ParseDateException {
ArrayList<Timeslot> timeslots = null;
if ( config != null)
{
Calendar cal = locale.createCalendar();
SerializableDateTimeFormat format = locale.getSerializableFormat();
Configuration[] children = config.getChildren("timeslot");
if ( children.length > 0)
{
timeslots = new ArrayList<Timeslot>();
int i=0;
for (Configuration conf:children)
{
String name = conf.getAttribute("name","");
String time = conf.getAttribute("time",null);
int minuteOfDay;
if ( time == null)
{
time = i + ":00:00";
}
cal.setTime(format.parseTime( time));
int hour = cal.get(Calendar.HOUR_OF_DAY);
if ( i != 0)
{
minuteOfDay= hour * 60 + cal.get(Calendar.MINUTE);
}
else
{
minuteOfDay = 0;
}
if ( name == null)
{
name = format.formatTime( cal.getTime());
}
Timeslot slot = new Timeslot( name, minuteOfDay);
timeslots.add( slot);
i=hour+1;
}
}
}
return timeslots;
}
public static ArrayList<Timeslot> getDefaultTimeslots(RaplaLocale raplaLocale) {
ArrayList<Timeslot> timeslots = new ArrayList<Timeslot>();
Calendar cal = raplaLocale.createCalendar();
cal.setTime(DateTools.cutDate( new Date()));
for (int i = 0; i <=23; i++ ) {
int minuteOfDay = i * 60;
cal.set(Calendar.HOUR_OF_DAY, i);
String name =raplaLocale.formatTime( cal.getTime());
//String name = minuteOfDay / 60 + ":" + minuteOfDay%60;
Timeslot slot = new Timeslot(name, minuteOfDay);
timeslots.add(slot);
}
return timeslots;
}
public List<Timeslot> getTimeslots()
{
return timeslots;
}
}
| 04900db4-clienttest | src/org/rapla/plugin/timeslot/TimeslotProvider.java | Java | gpl3 | 3,611 |
/*--------------------------------------------------------------------------*
| 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.plugin.timeslot;
import java.awt.Font;
import java.awt.Point;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.JLabel;
import org.rapla.components.calendar.DateRenderer;
import org.rapla.components.calendar.DateRenderer.RenderingInfo;
import org.rapla.components.calendar.DateRendererAdapter;
import org.rapla.components.calendarview.Block;
import org.rapla.components.calendarview.GroupStartTimesStrategy;
import org.rapla.components.calendarview.swing.AbstractSwingCalendar;
import org.rapla.components.calendarview.swing.SwingBlock;
import org.rapla.components.calendarview.swing.SwingCompactWeekView;
import org.rapla.components.calendarview.swing.ViewListener;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarOptions;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.abstractcalendar.AbstractRaplaSwingCalendar;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.plugin.abstractcalendar.RaplaCalendarViewListener;
public class SwingCompactCalendar extends AbstractRaplaSwingCalendar
{
List<Timeslot> timeslots;
public SwingCompactCalendar(RaplaContext sm,CalendarModel settings, boolean editable) throws RaplaException {
super( sm, settings, editable);
}
@Override
protected AbstractSwingCalendar createView(boolean showScrollPane)
throws RaplaException {
final DateRendererAdapter dateRenderer = new DateRendererAdapter(getService(DateRenderer.class), getRaplaLocale().getTimeZone(), getRaplaLocale().getLocale());
SwingCompactWeekView compactWeekView = new SwingCompactWeekView( showScrollPane ) {
@Override
protected JComponent createColumnHeader(Integer column) {
JLabel component = (JLabel) super.createColumnHeader(column);
if ( column != null ) {
Date date = getDateFromColumn(column);
boolean today = DateTools.isSameDay(getQuery().today().getTime(), date.getTime());
if ( today)
{
component.setFont(component.getFont().deriveFont( Font.BOLD));
}
if (isEditable() ) {
component.setOpaque(true);
RenderingInfo info = dateRenderer.getRenderingInfo(date);
if ( info.getBackgroundColor() != null)
{
component.setBackground(info.getBackgroundColor());
}
if ( info.getForegroundColor() != null)
{
component.setForeground(info.getForegroundColor());
}
component.setToolTipText(info.getTooltipText());
}
}
else
{
String calendarWeek = MessageFormat.format(getString("calendarweek.abbreviation"), getStartDate());
component.setText( calendarWeek);
}
return component;
}
protected int getColumnCount()
{
return getDaysInView();
}
@Override
public TimeInterval normalizeBlockIntervall(SwingBlock block)
{
Date start = block.getStart();
Date end = block.getEnd();
for (Timeslot slot:timeslots)
{
int minuteOfDay = DateTools.getMinuteOfDay( start.getTime());
if ( minuteOfDay >= slot.minuteOfDay)
{
start = new Date(DateTools.cutDate( start).getTime() + slot.minuteOfDay);
break;
}
}
for (Timeslot slot:timeslots)
{
int minuteOfDay = DateTools.getMinuteOfDay( end.getTime());
if ( minuteOfDay < slot.minuteOfDay)
{
end = new Date(DateTools.cutDate( end).getTime() + slot.minuteOfDay);
}
if ( slot.minuteOfDay > minuteOfDay)
{
break;
}
}
return new TimeInterval(start,end);
}
};
return compactWeekView;
}
@Override
public int getIncrementSize() {
return Calendar.WEEK_OF_YEAR;
}
protected ViewListener createListener() throws RaplaException {
return new RaplaCalendarViewListener(getContext(), model, view.getComponent()) {
/** override to change the allocatable to the row that is selected */
@Override
public void selectionChanged(Date start,Date end)
{
TimeInterval inter = getMarkedInterval(start);
super.selectionChanged(inter.getStart(), inter.getEnd());
}
public void moved(Block block, Point p, Date newStart, int slotNr) {
int days = view.getDaysInView();
int columns = days;
int index = slotNr;
int rowIndex = index/columns;
Timeslot timeslot = timeslots.get(rowIndex);
int time = timeslot.minuteOfDay;
Calendar cal = getRaplaLocale().createCalendar();
int lastMinuteOfDay;
cal.setTime ( block.getStart() );
lastMinuteOfDay = cal.get( Calendar.HOUR_OF_DAY) * 60 + cal.get( Calendar.MINUTE);
boolean sameTimeSlot = true;
if ( lastMinuteOfDay < time)
{
sameTimeSlot = false;
}
if ( rowIndex +1 < timeslots.size())
{
Timeslot nextTimeslot = timeslots.get(rowIndex+1);
if ( lastMinuteOfDay >= nextTimeslot.minuteOfDay )
{
sameTimeSlot = false;
}
}
cal.setTime ( newStart );
if ( sameTimeSlot)
{
time = lastMinuteOfDay;
}
cal.set( Calendar.HOUR_OF_DAY, time /60);
cal.set( Calendar.MINUTE, time %60);
newStart = cal.getTime();
moved(block, p, newStart);
}
protected TimeInterval getMarkedInterval(Date start) {
int columns = view.getDaysInView();
Date end;
Integer startTime = null;
Integer endTime = null;
int slots = columns*timeslots.size();
for ( int i=0;i<slots;i++)
{
if ( ((SwingCompactWeekView)view).isSelected(i))
{
int index = i/columns;
int time = timeslots.get(index).minuteOfDay;
if ( startTime == null || time < startTime )
{
startTime = time;
}
time = index<timeslots.size()-1 ? timeslots.get(index+1).minuteOfDay : 24* 60;
if ( endTime == null || time >= endTime )
{
endTime = time;
}
}
}
CalendarOptions calendarOptions = getCalendarOptions();
if ( startTime == null)
{
startTime = calendarOptions.getWorktimeStartMinutes();
}
if ( endTime == null)
{
endTime = calendarOptions.getWorktimeEndMinutes() + (calendarOptions.isWorktimeOvernight() ? 24*60:0);
}
Calendar cal = getRaplaLocale().createCalendar();
cal.setTime ( start );
cal.set( Calendar.HOUR_OF_DAY, startTime/60);
cal.set( Calendar.MINUTE, startTime%60);
start = cal.getTime();
cal.set( Calendar.HOUR_OF_DAY, endTime/60);
cal.set( Calendar.MINUTE, endTime%60);
end = cal.getTime();
TimeInterval intervall = new TimeInterval(start,end);
return intervall;
}
};
}
protected RaplaBuilder createBuilder() throws RaplaException {
timeslots = getService(TimeslotProvider.class).getTimeslots();
List<Integer> startTimes = new ArrayList<Integer>();
for (Timeslot slot:timeslots) {
startTimes.add( slot.getMinuteOfDay());
}
RaplaBuilder builder = super.createBuilder();
builder.setSmallBlocks( true );
GroupStartTimesStrategy strategy = new GroupStartTimesStrategy();
strategy.setFixedSlotsEnabled( true);
strategy.setResolveConflictsEnabled( false );
strategy.setStartTimes( startTimes );
//Uncommont if you want to sort by resource name instead of event name
// strategy.setBlockComparator( new Comparator<Block>() {
//
// public int compare(Block b1, Block b2) {
// int result = b1.getStart().compareTo(b2.getStart());
// if (result != 0)
// {
// return result;
// }
// Allocatable a1 = ((AbstractRaplaBlock) b1).getGroupAllocatable();
// Allocatable a2 = ((AbstractRaplaBlock) b2).getGroupAllocatable();
// if ( a1 != null && a2 != null)
// {
// String name1 = a1.getName( getLocale());
// String name2 = a2.getName(getLocale());
//
// result = name1.compareTo(name2);
// if (result != 0)
// {
// return result;
// }
//
// }
// return b1.getName().compareTo(b2.getName());
// }
// });
builder.setBuildStrategy( strategy);
builder.setSplitByAllocatables( false );
String[] slotNames = new String[ timeslots.size() ];
int maxSlotLength = 5;
for (int i = 0; i <timeslots.size(); i++ ) {
String slotName = timeslots.get( i ).getName();
maxSlotLength = Math.max( maxSlotLength, slotName.length());
slotNames[i] = slotName;
}
((SwingCompactWeekView)view).setLeftColumnSize( 30+ maxSlotLength * 6);
((SwingCompactWeekView)view).setSlots( slotNames );
return builder;
}
@Override
protected void configureView() throws RaplaException {
CalendarOptions calendarOptions = getCalendarOptions();
Set<Integer> excludeDays = calendarOptions.getExcludeDays();
view.setExcludeDays( excludeDays );
view.setDaysInView( calendarOptions.getDaysInWeekview());
int firstDayOfWeek = calendarOptions.getFirstDayOfWeek();
view.setFirstWeekday( firstDayOfWeek);
view.setToDate(model.getSelectedDate());
}
}
| 04900db4-clienttest | src/org/rapla/plugin/timeslot/SwingCompactCalendar.java | Java | gpl3 | 12,032 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.notification;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.entities.domain.Allocatable;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.TypedComponentRole;
/** Users can subscribe for allocation change notifications for selected resources or persons.*/
public class NotificationPlugin implements PluginDescriptor<ClientServiceContainer>
{
public static final TypedComponentRole<I18nBundle> RESOURCE_FILE = new TypedComponentRole<I18nBundle>(NotificationPlugin.class.getPackage().getName() + ".NotificationResources");
public static final boolean ENABLE_BY_DEFAULT = false;
public final static TypedComponentRole<Boolean> NOTIFY_IF_OWNER_CONFIG = new TypedComponentRole<Boolean>("org.rapla.plugin.notification.notify_if_owner");
public final static TypedComponentRole<RaplaMap<Allocatable>> ALLOCATIONLISTENERS_CONFIG = new TypedComponentRole<RaplaMap<Allocatable>>("org.rapla.plugin.notification.allocationlisteners");
public void provideServices(ClientServiceContainer container, Configuration config) {
if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig( RESOURCE_FILE.getId() ) );
container.addContainerProvidedComponent( RaplaClientExtensionPoints.USER_OPTION_PANEL_EXTENSION, NotificationOption.class);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/notification/NotificationPlugin.java | Java | gpl3 | 2,659 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.notification.server;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.rapla.RaplaMainContainer;
import org.rapla.components.util.Command;
import org.rapla.components.util.CommandScheduler;
import org.rapla.components.xmlbundle.I18nBundle;
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.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.facade.AllocationChangeEvent;
import org.rapla.facade.AllocationChangeListener;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.mail.MailToUserInterface;
import org.rapla.plugin.notification.NotificationPlugin;
import org.rapla.server.ServerExtension;
/** Sends Notification Mails on allocation change.*/
public class NotificationService extends RaplaComponent
implements
AllocationChangeListener,
ServerExtension
{
ClientFacade clientFacade;
MailToUserInterface mailToUserInterface;
protected CommandScheduler mailQueue;
public NotificationService(RaplaContext context) throws RaplaException
{
super( context);
setLogger( getLogger().getChildLogger("notification"));
clientFacade = context.lookup(ClientFacade.class);
setChildBundleName( NotificationPlugin.RESOURCE_FILE );
if ( !context.has( MailToUserInterface.class ))
{
getLogger().error("Could not start notification service, because Mail Plugin not activated. Check for mail plugin activation or errors.");
return;
}
mailToUserInterface = context.lookup( MailToUserInterface.class );
mailQueue = context.lookup( CommandScheduler.class);
clientFacade.addAllocationChangedListener(this);
getLogger().info("NotificationServer Plugin started");
}
public void changed(AllocationChangeEvent[] changeEvents) {
try {
getLogger().debug("Mail check triggered") ;
User[] users = clientFacade.getUsers();
List<AllocationMail> mailList = new ArrayList<AllocationMail>();
for ( int i=0;i< users.length;i++) {
User user = users[i];
if(user.getEmail().trim().length() == 0)
continue;
Preferences preferences = clientFacade.getPreferences(user);
Map<String,Allocatable> allocatableMap = null ;
if (preferences != null && preferences.getEntry(NotificationPlugin.ALLOCATIONLISTENERS_CONFIG)!= null ) {
allocatableMap = preferences.getEntry(NotificationPlugin.ALLOCATIONLISTENERS_CONFIG);
}else {
continue;
}
if ( allocatableMap != null && allocatableMap.size()> 0)
{
boolean notifyIfOwner = preferences.getEntryAsBoolean(NotificationPlugin.NOTIFY_IF_OWNER_CONFIG, false);
AllocationMail mail = getAllocationMail( new HashSet<Allocatable>(allocatableMap.values()), changeEvents, preferences.getOwner(),notifyIfOwner);
if (mail != null) {
mailList.add(mail);
}
}
}
if(!mailList.isEmpty()) {
MailCommand mailCommand = new MailCommand(mailList);
mailQueue.schedule(mailCommand,0);
}
} catch (RaplaException ex) {
getLogger().error("Can't trigger notification service." + ex.getMessage(),ex);
}
}
AllocationMail getAllocationMail(Collection<Allocatable> allocatables, AllocationChangeEvent[] changeEvents, User owner,boolean notifyIfOwner) throws RaplaException {
HashMap<Reservation,List<AllocationChangeEvent>> reservationMap = null;
HashSet<Allocatable> changedAllocatables = null;
for ( int i = 0; i< changeEvents.length; i++) {
if (reservationMap == null)
reservationMap = new HashMap<Reservation,List<AllocationChangeEvent>>(4);
AllocationChangeEvent event = changeEvents[i];
Reservation reservation = event.getNewReservation();
Allocatable allocatable = event.getAllocatable();
if (!allocatables.contains(allocatable))
continue;
if (!notifyIfOwner && owner.equals(reservation.getOwner()))
continue;
List<AllocationChangeEvent> eventList = reservationMap.get(reservation);
if (eventList == null) {
eventList = new ArrayList<AllocationChangeEvent>(3);
reservationMap.put(reservation,eventList);
}
if ( changedAllocatables == null)
{
changedAllocatables = new HashSet<Allocatable>();
}
changedAllocatables.add(allocatable);
eventList.add(event);
}
if ( reservationMap == null || changedAllocatables == null) {
return null;
}
Set<Reservation> keySet = reservationMap.keySet();
// Check if we have any notifications.
if (keySet.size() == 0)
return null;
AllocationMail mail = new AllocationMail();
StringBuffer buf = new StringBuffer();
//buf.append(getString("mail_body") + "\n");
for (Reservation reservation:keySet) {
List<AllocationChangeEvent> eventList = reservationMap.get(reservation);
String eventBlock = printEvents(reservation,eventList);
buf.append( eventBlock );
buf.append("\n\n");
}
I18nBundle i18n = getI18n();
String raplaTitle = getQuery().getSystemPreferences().getEntryAsString(RaplaMainContainer.TITLE, getString("rapla.title"));
buf.append(i18n.format("disclaimer_1", raplaTitle));
StringBuffer allocatableNames = new StringBuffer();
for (Allocatable alloc: changedAllocatables) {
if ( allocatableNames.length() > 0)
{
allocatableNames.append(", ");
}
allocatableNames.append(alloc.getName(getLocale()));
}
String allocatablesString = allocatableNames.toString();
buf.append(i18n.format("disclaimer_2", allocatablesString));
mail.subject = i18n.format("mail_subject",allocatablesString);
mail.body = buf.toString();
mail.recipient = owner.getUsername();
return mail;
}
private String printEvents(Reservation reservation,List<AllocationChangeEvent> eventList) {
StringBuilder buf =new StringBuilder();
buf.append("\n");
buf.append("-----------");
buf.append(getString("changes"));
buf.append("-----------");
buf.append("\n");
buf.append("\n");
buf.append(getString("reservation"));
buf.append(": ");
buf.append(reservation.getName(getLocale()));
buf.append("\n");
buf.append("\n");
Iterator<AllocationChangeEvent> it = eventList.iterator();
boolean removed = true;
boolean changed = false;
// StringBuilder changes = new StringBuilder();
while (it.hasNext()) {
AllocationChangeEvent event = it.next();
if (!event.getType().equals( AllocationChangeEvent.REMOVE ))
removed = false;
buf.append(getI18n().format("appointment." + event.getType()
,event.getAllocatable().getName(getLocale()))
);
// changes.append("[" + event.getAllocatable().getName(getLocale()) + "]");
// if(it.hasNext())
// changes.append(", ");
if (!event.getType().equals(AllocationChangeEvent.ADD )) {
printAppointment (buf, event.getOldAppointment() );
}
if (event.getType().equals( AllocationChangeEvent.CHANGE )) {
buf.append(getString("moved_to"));
}
if (!event.getType().equals( AllocationChangeEvent.REMOVE )) {
printAppointment (buf, event.getNewAppointment() );
}
/*
if ( event.getUser() != null) {
buf.append("\n");
buf.append( getI18n().format("modified_by", event.getUser().getUsername() ) );
}
*/
Reservation newReservation = event.getNewReservation();
if ( newReservation != null && changed == false) {
User eventUser = event.getUser();
User lastChangedBy = newReservation.getLastChangedBy();
String name;
if ( lastChangedBy != null)
{
name = lastChangedBy.getName();
}
else if ( eventUser != null)
{
name = eventUser.getName();
}
else
{
name = "Rapla";
}
buf.insert(0, getI18n().format("mail_body", name) + "\n");
changed = true;
}
buf.append("\n");
buf.append("\n");
}
if (removed)
return buf.toString();
buf.append("-----------");
buf.append(getString("complete_reservation"));
buf.append("-----------");
buf.append("\n");
buf.append("\n");
buf.append(getString("reservation.owner"));
buf.append(": ");
buf.append(reservation.getOwner().getUsername());
buf.append(" <");
buf.append(reservation.getOwner().getName());
buf.append(">");
buf.append("\n");
buf.append(getString("reservation_type"));
buf.append(": ");
Classification classification = reservation.getClassification();
buf.append( classification.getType().getName(getLocale()) );
Attribute[] attributes = classification.getAttributes();
for (int i=0; i< attributes.length; i++) {
Object value = classification.getValue(attributes[i]);
if (value == null)
continue;
buf.append("\n");
buf.append(attributes[i].getName(getLocale()));
buf.append(": ");
buf.append(classification.getValueAsString(attributes[i], getLocale()));
}
Allocatable[] resources = reservation.getResources();
if (resources.length>0) {
buf.append("\n");
buf.append( getString("resources"));
buf.append( ": ");
printAllocatables(buf,reservation,resources);
}
Allocatable[] persons = reservation.getPersons();
if (persons.length>0) {
buf.append("\n");
buf.append( getString("persons"));
buf.append( ": ");
printAllocatables(buf,reservation,persons);
}
Appointment[] appointments = reservation.getAppointments();
if (appointments.length>0) {
buf.append("\n");
buf.append("\n");
buf.append( getString("appointments"));
buf.append( ": ");
buf.append("\n");
}
for (int i = 0;i<appointments.length;i++) {
printAppointment(buf, appointments[i]);
}
return buf.toString();
}
private void printAppointment(StringBuilder buf, Appointment app) {
buf.append("\n");
buf.append(getAppointmentFormater().getSummary(app));
buf.append("\n");
Repeating repeating = app.getRepeating();
if ( repeating != null ) {
buf.append(getAppointmentFormater().getSummary(app.getRepeating()));
buf.append("\n");
if ( repeating.hasExceptions() ) {
String exceptionString =
getString("appointment.exceptions") + ": " + repeating.getExceptions().length ;
buf.append(exceptionString);
buf.append("\n");
}
}
}
private String printAllocatables(StringBuilder buf
,Reservation reservation
,Allocatable[] allocatables) {
for (int i = 0;i<allocatables.length;i++) {
Allocatable allocatable = allocatables[i];
buf.append(allocatable.getName( getLocale()));
printRestriction(buf,reservation, allocatable);
if (i<allocatables.length-1) {
buf.append (",");
}
}
return buf.toString();
}
private void printRestriction(StringBuilder buf
,Reservation reservation
, Allocatable allocatable) {
Appointment[] restriction = reservation.getRestriction(allocatable);
if ( restriction.length == 0 )
return;
buf.append(" (");
for (int i = 0; i < restriction.length ; i++) {
if (i >0)
buf.append(", ");
buf.append( getAppointmentFormater().getShortSummary( restriction[i]) );
}
buf.append(")");
}
class AllocationMail {
String recipient;
String subject;
String body;
public String toString() {
return "TO Username: " + recipient + "\n"
+ "Subject: " + subject + "\n"
+ body;
}
}
final class MailCommand implements Command {
List<AllocationMail> mailList;
public MailCommand(List<AllocationMail> mailList) {
this.mailList = mailList;
}
public void execute() {
Iterator<AllocationMail> it = mailList.iterator();
while (it.hasNext()) {
AllocationMail mail = it.next();
if (getLogger().isDebugEnabled())
getLogger().debug("Sending mail " + mail.toString());
getLogger().info("AllocationChange. Sending mail to " + mail.recipient);
try {
mailToUserInterface.sendMail(mail.recipient, mail.subject, mail.body );
getLogger().info("AllocationChange. Mail sent.");
} catch (RaplaException ex) {
getLogger().error("Could not send mail to " + mail.recipient + " Cause: " + ex.getMessage(), ex);
}
}
}
}
} | 04900db4-clienttest | src/org/rapla/plugin/notification/server/NotificationService.java | Java | gpl3 | 15,642 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.notification.server;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.plugin.notification.NotificationPlugin;
import org.rapla.server.RaplaServerExtensionPoints;
import org.rapla.server.ServerServiceContainer;
/** Users can subscribe for allocation change notifications for selected resources or persons.*/
public class NotificationServerPlugin implements PluginDescriptor<ServerServiceContainer>
{
public void provideServices(ServerServiceContainer container, Configuration config) {
if ( !config.getAttributeAsBoolean("enabled", NotificationPlugin.ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( NotificationPlugin.RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig( NotificationPlugin.RESOURCE_FILE.getId() ) );
container.addContainerProvidedComponent( RaplaServerExtensionPoints.SERVER_EXTENSION, NotificationService.class);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/notification/server/NotificationServerPlugin.java | Java | gpl3 | 1,994 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.notification;
import java.util.Collection;
import java.util.Locale;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.entities.domain.Allocatable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.TreeAllocatableSelection;
public class NotificationOption extends RaplaGUIComponent implements OptionPanel {
JPanel content= new JPanel();
JCheckBox notifyIfOwnerCheckBox;
TreeAllocatableSelection selection;
Preferences preferences;
public NotificationOption(RaplaContext sm) {
super( sm);
setChildBundleName( NotificationPlugin.RESOURCE_FILE);
selection = new TreeAllocatableSelection(sm);
selection.setAddDialogTitle(getString("subscribe_notification"));
double[][] sizes = new double[][] {
{5,TableLayout.FILL,5}
,{TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.FILL}
};
TableLayout tableLayout = new TableLayout(sizes);
content.setLayout(tableLayout);
content.add(new JLabel(getStringAsHTML("notification.option.description")), "1,0");
notifyIfOwnerCheckBox = new JCheckBox();
content.add(notifyIfOwnerCheckBox, "1,2");
notifyIfOwnerCheckBox.setText(getStringAsHTML("notify_if_owner"));
content.add(selection.getComponent(), "1,4");
}
public JComponent getComponent() {
return content;
}
public String getName(Locale locale) {
return getString("notification_options");
}
public void show() throws RaplaException {
boolean notify = preferences.getEntryAsBoolean( NotificationPlugin.NOTIFY_IF_OWNER_CONFIG, false);
notifyIfOwnerCheckBox.setEnabled( false );
notifyIfOwnerCheckBox.setSelected(notify);
notifyIfOwnerCheckBox.setEnabled( true );
RaplaMap<Allocatable> raplaEntityList = preferences.getEntry( NotificationPlugin.ALLOCATIONLISTENERS_CONFIG );
if ( raplaEntityList != null ){
selection.setAllocatables(raplaEntityList.values());
}
}
public void setPreferences(Preferences preferences) {
this.preferences = preferences;
}
public void commit() {
preferences.putEntry( NotificationPlugin.NOTIFY_IF_OWNER_CONFIG, notifyIfOwnerCheckBox.isSelected());
Collection<Allocatable> allocatables = selection.getAllocatables();
preferences.putEntry( NotificationPlugin.ALLOCATIONLISTENERS_CONFIG ,getModification().newRaplaMap( allocatables ));
}
}
| 04900db4-clienttest | src/org/rapla/plugin/notification/NotificationOption.java | Java | gpl3 | 3,850 |
package org.rapla.plugin.setowner;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.TreeSet;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.rapla.entities.Entity;
import org.rapla.entities.Named;
import org.rapla.entities.NamedComparator;
import org.rapla.entities.Ownable;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.Reservation;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.MenuContext;
import org.rapla.gui.ObjectMenuFactory;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.RaplaMenuItem;
import org.rapla.gui.toolkit.RaplaTree;
public class SetOwnerMenuFactory extends RaplaGUIComponent implements ObjectMenuFactory
{
public SetOwnerMenuFactory( RaplaContext context)
{
super( context );
setChildBundleName( SetOwnerPlugin.RESOURCE_FILE);
}
public RaplaMenuItem[] create( final MenuContext menuContext, final RaplaObject focusedObject )
{
if (!isAdmin())
{
return RaplaMenuItem.EMPTY_ARRAY;
}
Collection<Object> selectedObjects = new HashSet<Object>();
Collection<?> selected = menuContext.getSelectedObjects();
if ( selected.size() != 0)
{
selectedObjects.addAll( selected);
}
if ( focusedObject != null)
{
selectedObjects.add( focusedObject);
}
final Collection<Entity<? extends Entity>> ownables = new HashSet<Entity<? extends Entity>>();
for ( Object obj: selectedObjects)
{
final Entity<? extends Entity> ownable;
if ( obj instanceof AppointmentBlock)
{
ownable = ((AppointmentBlock) obj).getAppointment().getReservation();
}
else if ( obj instanceof Entity )
{
RaplaType raplaType = ((RaplaObject)obj).getRaplaType();
if ( raplaType == Appointment.TYPE )
{
Appointment appointment = (Appointment) obj;
ownable = appointment.getReservation();
}
else if ( raplaType == Reservation.TYPE)
{
ownable = (Reservation) obj;
}
else if ( raplaType == Allocatable.TYPE)
{
ownable = (Allocatable) obj;
}
else
{
ownable = null;
}
}
else
{
ownable = null;
}
if ( ownable != null)
{
ownables.add( ownable);
}
}
if ( ownables.size() == 0 )
{
return RaplaMenuItem.EMPTY_ARRAY;
}
// create the menu entry
final RaplaMenuItem setOwnerItem = new RaplaMenuItem("SETOWNER");
setOwnerItem.setText(getI18n().getString("changeowner"));
setOwnerItem.setIcon(getI18n().getIcon("icon.tree.persons"));
setOwnerItem.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
try
{
User newOwner = showAddDialog();
if(newOwner != null) {
ArrayList<Entity<?>> toStore = new ArrayList<Entity<?>>();
for ( Entity<? extends Entity> ownable: ownables)
{
Entity<?> editableOwnables = getClientFacade().edit( ownable);
Ownable casted = (Ownable)editableOwnables;
casted.setOwner(newOwner);
toStore.add( editableOwnables);
}
//((SimpleEntity) editableEvent).setLastChangedBy(newOwner);
getClientFacade().storeObjects( toStore.toArray( Entity.ENTITY_ARRAY) );
}
}
catch (RaplaException ex )
{
showException( ex, menuContext.getComponent());
}
}
});
return new RaplaMenuItem[] {setOwnerItem };
}
final private TreeFactory getTreeFactory() {
return getService(TreeFactory.class);
}
private User showAddDialog() throws RaplaException {
final DialogUI dialog;
RaplaTree treeSelection = new RaplaTree();
treeSelection.setMultiSelect(true);
treeSelection.getTree().setCellRenderer(getTreeFactory().createRenderer());
DefaultMutableTreeNode userRoot = new DefaultMutableTreeNode("ROOT");
//DefaultMutableTreeNode userRoot = TypeNode(User.TYPE, getString("users"));
User[] userList = getQuery().getUsers();
for (final User user: sorted(userList)) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode();
node.setUserObject( user );
userRoot.add(node);
}
treeSelection.exchangeTreeModel(new DefaultTreeModel(userRoot));
treeSelection.setMinimumSize(new java.awt.Dimension(300, 200));
treeSelection.setPreferredSize(new java.awt.Dimension(400, 260));
dialog = DialogUI.create(
getContext()
,getMainComponent()
,true
,treeSelection
,new String[] { getString("apply"),getString("cancel")});
dialog.setTitle(getI18n().getString("changeownerto"));
dialog.getButton(0).setEnabled(false);
final JTree tree = treeSelection.getTree();
tree.addMouseListener(new MouseAdapter() {
// End dialog when a leaf is double clicked
public void mousePressed(MouseEvent e) {
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if (selPath != null && e.getClickCount() == 2) {
final Object lastPathComponent = selPath.getLastPathComponent();
if (((TreeNode) lastPathComponent).isLeaf() ) {
dialog.getButton(0).doClick();
return;
}
}
else
if (selPath != null && e.getClickCount() == 1) {
final Object lastPathComponent = selPath.getLastPathComponent();
if (((TreeNode) lastPathComponent).isLeaf() ) {
dialog.getButton(0).setEnabled(true);
return;
}
}
tree.removeSelectionPath(selPath);
}
});
dialog.start();
if (dialog.getSelectedIndex() == 1) {
return null;
}
return (User) treeSelection.getSelectedElement();
}
private <T extends Named> Collection<T> sorted(T[] allocatables) {
TreeSet<T> sortedList = new TreeSet<T>(new NamedComparator<T>(getLocale()));
sortedList.addAll(Arrays.asList(allocatables));
return sortedList;
}
}
| 04900db4-clienttest | src/org/rapla/plugin/setowner/SetOwnerMenuFactory.java | Java | gpl3 | 7,505 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.setowner;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.TypedComponentRole;
public class SetOwnerPlugin implements PluginDescriptor<ClientServiceContainer>
{
public final static boolean ENABLE_BY_DEFAULT = false;
public static final TypedComponentRole<I18nBundle> RESOURCE_FILE = new TypedComponentRole<I18nBundle>(SetOwnerPlugin.class.getPackage().getName() + ".SetOwnerResources");
public String toString() {
return "Set Owner";
}
public void provideServices(ClientServiceContainer container, Configuration config) {
if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig( RESOURCE_FILE.getId() ) );
container.addContainerProvidedComponent( RaplaClientExtensionPoints.OBJECT_MENU_EXTENSION, SetOwnerMenuFactory.class);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/setowner/SetOwnerPlugin.java | Java | gpl3 | 2,173 |
package org.rapla.plugin.archiver;
import javax.jws.WebService;
import org.rapla.framework.RaplaException;
@WebService
public interface ArchiverService
{
String REMOVE_OLDER_THAN_ENTRY = "remove-older-than";
String EXPORT = "export";
void delete(Integer olderThanInDays) throws RaplaException;
boolean isExportEnabled() throws RaplaException;
void backupNow() throws RaplaException;
void restore() throws RaplaException;
}
| 04900db4-clienttest | src/org/rapla/plugin/archiver/ArchiverService.java | Java | gpl3 | 452 |
/*--------------------------------------------------------------------------*
| 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.plugin.archiver;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
public class ArchiverPlugin implements PluginDescriptor<ClientServiceContainer>
{
public final static boolean ENABLE_BY_DEFAULT = false;
public void provideServices(ClientServiceContainer container, Configuration config) {
container.addContainerProvidedComponent( RaplaClientExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION,ArchiverOption.class);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/archiver/ArchiverPlugin.java | Java | gpl3 | 1,526 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.archiver;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Locale;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.rapla.components.calendar.RaplaNumber;
import org.rapla.components.layout.TableLayout;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.DefaultPluginOption;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.storage.dbrm.RestartServer;
public class ArchiverOption extends DefaultPluginOption implements ActionListener {
RaplaNumber dayField = new RaplaNumber(new Integer(25), new Integer(0),null,false);
JCheckBox removeOlderYesNo = new JCheckBox();
JCheckBox exportToDataXML = new JCheckBox();
RaplaButton deleteNow;
RaplaButton backupButton;
RaplaButton restoreButton;
ArchiverService archiver;
public ArchiverOption(RaplaContext sm, ArchiverService archiver){
super(sm);
this.archiver = archiver;
}
protected JPanel createPanel() throws RaplaException {
JPanel panel = super.createPanel();
JPanel content = new JPanel();
double[][] sizes = new double[][] {
{5,TableLayout.PREFERRED, 5,TableLayout.PREFERRED,5, TableLayout.PREFERRED}
,{TableLayout.PREFERRED,5,TableLayout.PREFERRED,15,TableLayout.PREFERRED,5,TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED}
};
TableLayout tableLayout = new TableLayout(sizes);
content.setLayout(tableLayout);
//content.add(new JLabel("Remove old events"), "1,0");
removeOlderYesNo.setText("Remove events older than");
content.add( removeOlderYesNo, "1,0");
//content.add(new JLabel("Older than"), "1,2");
content.add( dayField, "3,0");
content.add( new JLabel("days"), "5,0");
deleteNow = new RaplaButton(RaplaButton.DEFAULT);
deleteNow.setText("delete now");
content.add(deleteNow, "3,2");
exportToDataXML.setText("Export db to file");
content.add(exportToDataXML, "1,4");
backupButton = new RaplaButton(RaplaButton.DEFAULT);
backupButton.setText("backup now");
content.add( backupButton, "3,4");
restoreButton = new RaplaButton(RaplaButton.DEFAULT);
restoreButton.setText("restore and restart");
content.add( restoreButton, "3,6");
removeOlderYesNo.addActionListener( this );
exportToDataXML.addActionListener( this );
deleteNow.addActionListener( this );
backupButton.addActionListener( this );
restoreButton.addActionListener( this );
panel.add( content, BorderLayout.CENTER);
return panel;
}
private void updateEnabled()
{
{
boolean selected = removeOlderYesNo.isSelected();
dayField.setEnabled( selected);
deleteNow.setEnabled( selected );
}
{
boolean selected = exportToDataXML.isSelected();
backupButton.setEnabled(selected);
restoreButton.setEnabled( selected);
}
}
protected void addChildren( DefaultConfiguration newConfig) {
if ( removeOlderYesNo.isSelected())
{
DefaultConfiguration conf = new DefaultConfiguration(ArchiverService.REMOVE_OLDER_THAN_ENTRY);
conf.setValue(dayField.getNumber().intValue() );
newConfig.addChild( conf );
}
if ( exportToDataXML.isSelected())
{
DefaultConfiguration conf = new DefaultConfiguration(ArchiverService.EXPORT);
conf.setValue( true );
newConfig.addChild( conf );
}
}
protected void readConfig( Configuration config) {
int days = config.getChild(ArchiverService.REMOVE_OLDER_THAN_ENTRY).getValueAsInteger(-20);
boolean isEnabled = days != -20;
removeOlderYesNo.setSelected( isEnabled );
if ( days == -20 )
{
days = 30;
}
dayField.setNumber( new Integer(days));
boolean exportSelected= config.getChild(ArchiverService.EXPORT).getValueAsBoolean(false);
try {
boolean exportEnabled = archiver.isExportEnabled();
exportToDataXML.setEnabled( exportEnabled );
exportToDataXML.setSelected( exportSelected && exportEnabled );
} catch (RaplaException e) {
exportToDataXML.setEnabled( false );
exportToDataXML.setSelected( false );
getLogger().error(e.getMessage(), e);
}
updateEnabled();
}
public void show() throws RaplaException {
super.show();
}
public void commit() throws RaplaException {
super.commit();
}
/**
* @see org.rapla.gui.DefaultPluginOption#getPluginClass()
*/
public Class<? extends PluginDescriptor<?>> getPluginClass() {
return ArchiverPlugin.class;
}
public String getName(Locale locale) {
return "Archiver Plugin";
}
public void actionPerformed(ActionEvent e) {
try
{
Object source = e.getSource();
if ( source == exportToDataXML || source == removeOlderYesNo)
{
updateEnabled();
}
else
{
if ( source == deleteNow)
{
Number days = dayField.getNumber();
if ( days != null)
{
archiver.delete(new Integer(days.intValue()));
}
}
else if (source == backupButton)
{
archiver.backupNow();
}
else if (source == restoreButton)
{
boolean modal = true;
DialogUI dialog = DialogUI.create(getContext(), getMainComponent(),modal,"Warning", "The current data will be overwriten by the backup version. Do you want to proceed?", new String[]{"restore data","abort"});
dialog.setDefault( 1);
dialog.start();
if (dialog.getSelectedIndex() == 0)
{
archiver.restore();
RestartServer service = getService(RestartServer.class);
service.restartServer();
}
}
}
}
catch (RaplaException ex)
{
showException(ex, getMainComponent());
}
}
}
| 04900db4-clienttest | src/org/rapla/plugin/archiver/ArchiverOption.java | Java | gpl3 | 7,243 |
package org.rapla.plugin.archiver.server;
import org.rapla.components.util.Command;
import org.rapla.components.util.CommandScheduler;
import org.rapla.components.util.DateTools;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.archiver.ArchiverService;
import org.rapla.server.ServerExtension;
public class ArchiverServiceTask extends RaplaComponent implements ServerExtension
{
public ArchiverServiceTask( final RaplaContext context, final Configuration config ) throws RaplaContextException
{
super( context );
final int days = config.getChild( ArchiverService.REMOVE_OLDER_THAN_ENTRY).getValueAsInteger(-20);
final boolean export = config.getChild( ArchiverService.EXPORT).getValueAsBoolean(false);
if ( days != -20 || export)
{
CommandScheduler timer = context.lookup( CommandScheduler.class);
Command removeTask = new Command() {
public void execute() throws RaplaException {
ArchiverServiceImpl task = new ArchiverServiceImpl(getContext());
try
{
if ( days != -20 )
{
task.delete( days );
}
if ( export && task.isExportEnabled())
{
task.backupNow();
}
}
catch (RaplaException e) {
getLogger().error("Could not execute archiver task ", e);
}
}
};
// Call it each hour
timer.schedule(removeTask, 0, DateTools.MILLISECONDS_PER_HOUR);
}
}
}
| 04900db4-clienttest | src/org/rapla/plugin/archiver/server/ArchiverServiceTask.java | Java | gpl3 | 1,864 |
package org.rapla.plugin.archiver.server;
import org.rapla.entities.User;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.archiver.ArchiverService;
import org.rapla.server.RemoteMethodFactory;
import org.rapla.server.RemoteSession;
import org.rapla.storage.RaplaSecurityException;
public class ArchiverServiceFactory extends RaplaComponent implements RemoteMethodFactory<ArchiverService>
{
public ArchiverServiceFactory(RaplaContext context) {
super(context);
}
public ArchiverService createService(final RemoteSession remoteSession) {
RaplaContext context = getContext();
return new ArchiverServiceImpl( context)
{
@Override
protected void checkAccess() throws RaplaException {
User user = remoteSession.getUser();
if ( user != null && !user.isAdmin())
{
throw new RaplaSecurityException("ArchiverService can only be triggered by admin users");
}
}
};
}
}
| 04900db4-clienttest | src/org/rapla/plugin/archiver/server/ArchiverServiceFactory.java | Java | gpl3 | 1,040 |
/*--------------------------------------------------------------------------*
| 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.plugin.archiver.server;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.plugin.archiver.ArchiverPlugin;
import org.rapla.plugin.archiver.ArchiverService;
import org.rapla.server.RaplaServerExtensionPoints;
import org.rapla.server.ServerServiceContainer;
public class ArchiverServerPlugin implements PluginDescriptor<ServerServiceContainer>
{
public void provideServices(ServerServiceContainer container, Configuration config) {
container.addRemoteMethodFactory(ArchiverService.class, ArchiverServiceFactory.class, config);
if ( !config.getAttributeAsBoolean("enabled", ArchiverPlugin.ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( RaplaServerExtensionPoints.SERVER_EXTENSION, ArchiverServiceTask.class, config);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/archiver/server/ArchiverServerPlugin.java | Java | gpl3 | 1,836 |
package org.rapla.plugin.archiver.server;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.rapla.components.util.DateTools;
import org.rapla.entities.User;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.archiver.ArchiverService;
import org.rapla.storage.ImportExportManager;
import org.rapla.storage.StorageOperator;
import org.rapla.storage.dbsql.DBOperator;
public class ArchiverServiceImpl extends RaplaComponent implements ArchiverService
{
public ArchiverServiceImpl(RaplaContext context) {
super(context);
}
/** can be overriden to check if user has admin rights when triggered as RemoteService
* @throws RaplaException */
protected void checkAccess() throws RaplaException
{
}
public boolean isExportEnabled() throws RaplaException {
ClientFacade clientFacade = getContext().lookup(ClientFacade.class);
StorageOperator operator = clientFacade.getOperator();
boolean enabled = operator instanceof DBOperator;
return enabled;
}
public void backupNow() throws RaplaException {
checkAccess();
if (!isExportEnabled())
{
throw new RaplaException("Export not enabled");
}
ImportExportManager lookup = getContext().lookup(ImportExportManager.class);
lookup.doExport();
}
public void restore() throws RaplaException {
checkAccess();
if (!isExportEnabled())
{
throw new RaplaException("Export not enabled");
}
// We only do an import here
ImportExportManager lookup = getContext().lookup(ImportExportManager.class);
lookup.doImport();
}
public void delete(Integer removeOlderInDays) throws RaplaException {
checkAccess();
ClientFacade clientFacade = getContext().lookup(ClientFacade.class);
Date endDate = new Date(clientFacade.today().getTime() - removeOlderInDays * DateTools.MILLISECONDS_PER_DAY);
Reservation[] events = clientFacade.getReservations((User) null, null, endDate, null); //ClassificationFilter.CLASSIFICATIONFILTER_ARRAY );
List<Reservation> toRemove = new ArrayList<Reservation>();
for ( int i=0;i< events.length;i++)
{
Reservation event = events[i];
if ( isOlderThan( event, endDate))
{
toRemove.add(event);
}
}
if ( toRemove.size() > 0)
{
getLogger().info("Removing " + toRemove.size() + " old events.");
Reservation[] eventsToRemove = toRemove.toArray( Reservation.RESERVATION_ARRAY);
int STEP_SIZE = 100;
for ( int i=0;i< eventsToRemove.length;i+=STEP_SIZE)
{
int blockSize = Math.min( eventsToRemove.length- i, STEP_SIZE);
Reservation[] eventBlock = new Reservation[blockSize];
System.arraycopy( eventsToRemove,i, eventBlock,0, blockSize);
clientFacade.removeObjects( eventBlock);
}
}
}
private boolean isOlderThan( Reservation event, Date maxAllowedDate )
{
Appointment[] appointments = event.getAppointments();
for ( int i=0;i<appointments.length;i++)
{
Appointment appointment = appointments[i];
Date start = appointment.getStart();
Date end = appointment.getMaxEnd();
if ( start == null || end == null )
{
return false;
}
if ( end.after( maxAllowedDate))
{
return false;
}
if ( start.after( maxAllowedDate))
{
return false;
}
}
return true;
}
} | 04900db4-clienttest | src/org/rapla/plugin/archiver/server/ArchiverServiceImpl.java | Java | gpl3 | 3,811 |
package org.rapla.plugin.appointmentcounter;
import java.awt.Font;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLabel;
import org.rapla.components.util.DateTools;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.AppointmentListener;
import org.rapla.gui.AppointmentStatusFactory;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.ReservationEdit;
import org.rapla.gui.toolkit.RaplaWidget;
public class AppointmentCounterFactory implements AppointmentStatusFactory
{
public RaplaWidget createStatus(RaplaContext context, ReservationEdit reservationEdit) throws RaplaException
{
return new AppointmentCounter(context, reservationEdit);
}
class AppointmentCounter extends RaplaGUIComponent implements RaplaWidget
{
JLabel statusBar = new JLabel();
ReservationEdit reservationEdit;
public AppointmentCounter(final RaplaContext context, final ReservationEdit reservationEdit) {
super(context);
Font font = statusBar.getFont().deriveFont( (float)9.0);
statusBar.setFont( font );
this.reservationEdit = reservationEdit;
reservationEdit.addAppointmentListener( new AppointmentListener() {
public void appointmentRemoved(Collection<Appointment> appointment) {
updateStatus();
}
public void appointmentChanged(Collection<Appointment> appointment) {
updateStatus();
}
public void appointmentAdded(Collection<Appointment> appointment) {
updateStatus();
}
public void appointmentSelected(Collection<Appointment> appointment) {
updateStatus();
}
});
updateStatus();
}
private void updateStatus() {
Reservation event = reservationEdit.getReservation();
if ( event == null)
{
return;
}
Appointment[] appointments = event.getAppointments();
int count = 0;
for (int i = 0; i<appointments.length; i++) {
Appointment appointment = appointments[i];
Repeating repeating = appointment.getRepeating();
if ( repeating == null ) {
count ++;
continue;
}
if ( repeating.getEnd() == null ){ // Repeats foreever ?
count = -1;
break;
}
List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
appointment.createBlocks( appointment.getStart(), DateTools.fillDate(repeating.getEnd()), blocks);
count += blocks.size();
}
String status = "";
if (count >= 0)
status = getString("total_occurances")+ ": " + count;
else
status = getString("total_occurances")+ ": ? ";
// uncomment for selection change test
// status += "Selected Appointments " + reservationEdit.getSelectedAppointments();
statusBar.setText( status );
}
public JComponent getComponent() {
return statusBar;
}
}
}
| 04900db4-clienttest | src/org/rapla/plugin/appointmentcounter/AppointmentCounterFactory.java | Java | gpl3 | 3,448 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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.appointmentcounter;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
public class AppointmentCounterPlugin implements PluginDescriptor<ClientServiceContainer>
{
public final static boolean ENABLE_BY_DEFAULT = true;
public String toString() {
return "Appointment Counter";
}
public void provideServices(ClientServiceContainer container, Configuration config) {
if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( RaplaClientExtensionPoints.APPOINTMENT_STATUS, AppointmentCounterFactory.class, config);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/appointmentcounter/AppointmentCounterPlugin.java | Java | gpl3 | 1,743 |
package org.rapla.plugin.ical;
import javax.jws.WebService;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
@WebService
public interface ICalImport {
FutureResult<Integer[]> importICal(String content, boolean isURL, String[] allocatableIds, String eventTypeKey, String eventTypeNameAttributeKey);
} | 04900db4-clienttest | src/org/rapla/plugin/ical/ICalImport.java | Java | gpl3 | 310 |
package org.rapla.plugin.ical.server;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContextException;
import org.rapla.plugin.export2ical.Export2iCalPlugin;
import org.rapla.plugin.ical.ICalImport;
import org.rapla.plugin.ical.ImportFromICalPlugin;
import org.rapla.server.ServerServiceContainer;
public class ImportFromICalServerPlugin implements PluginDescriptor<ServerServiceContainer> {
public void provideServices(ServerServiceContainer container, Configuration config) throws RaplaContextException {
if (!config.getAttributeAsBoolean("enabled", Export2iCalPlugin.ENABLE_BY_DEFAULT))
return;
container.addContainerProvidedComponent(ImportFromICalPlugin.RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig(Export2iCalPlugin.RESOURCE_FILE.getId()));
container.addRemoteMethodFactory(ICalImport.class, RaplaICalImport.class, config);
}
} | 04900db4-clienttest | src/org/rapla/plugin/ical/server/ImportFromICalServerPlugin.java | Java | gpl3 | 1,007 |
package org.rapla.plugin.ical.server;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.data.ParserException;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ComponentList;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Dur;
import net.fortuna.ical4j.model.NumberList;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.PeriodList;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.PropertyList;
import net.fortuna.ical4j.model.Recur;
import net.fortuna.ical4j.model.WeekDayList;
import net.fortuna.ical4j.model.property.DateProperty;
import net.fortuna.ical4j.model.property.RRule;
import net.fortuna.ical4j.util.CompatibilityHints;
import org.rapla.components.util.DateTools;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.User;
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.domain.RaplaObjectAnnotations;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.ical.ICalImport;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.rest.gwtjsonrpc.common.ResultImpl;
import org.rapla.server.RemoteMethodFactory;
import org.rapla.server.RemoteSession;
import org.rapla.server.TimeZoneConverter;
import org.rapla.storage.impl.AbstractCachableOperator;
public class RaplaICalImport extends RaplaComponent implements RemoteMethodFactory<ICalImport> {
private TimeZone timeZone;
private TimeZoneConverter timeZoneConverter;
public RaplaICalImport( RaplaContext context) throws RaplaContextException{
this( context, context.lookup(TimeZoneConverter.class).getImportExportTimeZone());
}
public RaplaICalImport( RaplaContext context, TimeZone timeZone) throws RaplaContextException{
super( context);
this.timeZone = timeZone;
this.timeZoneConverter = context.lookup( TimeZoneConverter.class);
}
public ICalImport createService(final RemoteSession remoteSession) {
return new ICalImport() {
@Override
public FutureResult<Integer[]> importICal(String content, boolean isURL, String[] allocatableIds, String eventTypeKey, String eventTypeNameAttributeKey)
{
try
{
List<Allocatable> allocatables = new ArrayList<Allocatable>();
if ( allocatableIds.length > 0)
{
for ( String id:allocatableIds)
{
Allocatable allocatable = getAllocatable(id);
allocatables.add ( allocatable);
}
}
User user = remoteSession.getUser();
Integer[] count = importCalendar(content, isURL, allocatables, user, eventTypeKey, eventTypeNameAttributeKey);
return new ResultImpl<Integer[]>(count);
} catch (RaplaException ex)
{
return new ResultImpl<Integer[]>(ex);
}
}
};
}
private Allocatable getAllocatable( final String id) throws EntityNotFoundException
{
AbstractCachableOperator operator = (AbstractCachableOperator) getClientFacade().getOperator();
final Allocatable refEntity = operator.resolve( id, Allocatable.class);
return refEntity;
}
/**
* parses iCal calendar and creates reservations for the contained VEVENTS.
* SUMMARY will match to the name of the reservation.
* can handle events with DTEND or DURATION.
* recurrance information from RRULE will be handled by google-rfc-2445.
* reads TZID information from given file. If the is none, passedTimezone
* will be used.
*
* @param content
* path of the *.ics file
* @param isURL
* set true if the path is a URL and no local filepath
* @param resources
* if you want to add resources to all event in the given
* calendar, pass a list.
* each element of the list has to be a String[] and stands for
* one resource.
*
* <pre>
* element[0] contains the name of the dynamic Type for the allocatable
* element[1] contains the name of the allocatable
* </pre>
* @param user
* @param eventTypeKey
* @throws FileNotFoundException
* @throws MalformedURLException
* @throws RaplaException
*/
public Integer[] importCalendar(String content, boolean isURL, List<Allocatable> resources, User user, String eventTypeKey, String eventTypeNameAttributeKey) throws RaplaException {
CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_NOTES_COMPATIBILITY, true);
CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY, true);
CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_RELAXED_PARSING, true);
CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_RELAXED_VALIDATION, true);
CalendarBuilder builder = new CalendarBuilder();
Calendar calendar = null;
int eventsInICal = 0;
int eventsImported = 0;
int eventsPresent = 0;
int eventsSkipped = 0;
try {
if (isURL) {
InputStream in = new URL(content).openStream();
calendar = builder.build(in);
in.close();
}
else
{
StringReader fin = new StringReader(content);
calendar = builder.build(fin);
}
} catch (IOException ioe) {
throw new RaplaException(ioe.getMessage());
} catch (ParserException pe) {
throw new RaplaException(pe.getMessage());
} catch (IllegalArgumentException pe) {
throw new RaplaException(pe.getMessage());
}
ComponentList events = calendar.getComponents();
@SuppressWarnings("unchecked")
Iterator<Component> iterator = events.iterator();
List<Reservation> eventList = new ArrayList<Reservation>();
Map<String, Reservation> reservationMap = new HashMap<String, Reservation>();
while (iterator.hasNext()) {
Component component = iterator.next();
if (component.getName().equalsIgnoreCase("VEVENT") ) {
try {
eventsInICal ++;
String uid = null;
Reservation lookupEvent = null;
String name = component.getProperty("SUMMARY").getValue();
Property uidProperty = component.getProperty("UID");
if ( uidProperty != null)
{
uid = uidProperty.getValue();
lookupEvent = reservationMap.get( uid);
}
if (name == null || name.trim().length() == 0)
{
getLogger().debug("Ignoring event with empty name [" + uid + "]" );
eventsSkipped ++;
continue;
}
if ( lookupEvent == null)
{
// create the reservation
Classification classification = getClientFacade().getDynamicType(eventTypeKey).newClassification();
lookupEvent = getClientFacade().newReservation(classification,user);
if ( uid != null)
{
lookupEvent.setAnnotation( RaplaObjectAnnotations.KEY_EXTERNALID, uid);
}
classification.setValue(eventTypeNameAttributeKey, name);
}
Reservation event = lookupEvent;
DateProperty startDateProperty = (DateProperty)component.getProperty("DTSTART");
Date startdate = startDateProperty.getDate();
Date enddate = null;
boolean wholeDay = false;
long duration_millis = 0;
Dur duration;
if (component.getProperties("DTEND").size() > 0) {
DateProperty endDateProperty = (DateProperty)component.getProperty("DTEND");
enddate = endDateProperty.getDate();
duration = null;
} else if (component.getProperties("DURATION").size() > 0) {
duration = new Dur(component.getProperty("DURATION").getValue());
Date t1 = new Date();
Date t2 = duration.getTime(t1);
duration_millis = t2.getTime() - t1.getTime();
} else {
getLogger().warn("Error in ics File. There is an event without DTEND or DURATION. "
+ "SUMMARY: " + name + ", DTSTART: " + startdate);
eventsSkipped ++;
continue;
}
for (Allocatable allocatable: resources)
{
event.addAllocatable(allocatable);
}
if (duration_millis == 0 && enddate != null) {
duration_millis = enddate.getTime() - startdate.getTime();
}
// create appointment
Appointment appointment;
if ( !(startdate instanceof DateTime))
{
Date begin = new Date( startdate.getTime());
Date end = new Date(begin.getTime() + duration_millis);
appointment = newAppointment(user,begin, end);
wholeDay = true;
appointment.setWholeDays(wholeDay);
}
else
{
Date begin = timeZoneConverter.toRaplaTime(timeZone, startdate);
Date end = new Date(begin.getTime() + duration_millis);
appointment = newAppointment(user,begin, end);
}
PropertyList rrules = component.getProperties("RRULE");
if ( rrules.size() >0)
{
List<Recur> recurList = new ArrayList<Recur>(rrules.size());
for ( int i=0;i<rrules.size();i++)
{
Property prop = (Property) rrules.get( i);
RRule rrule = new RRule(prop.getParameters(),prop.getValue());
recurList.add(rrule.getRecur());
}
List<Appointment> list = calcRepeating( recurList, appointment);
if ( list != null)
{
for ( Appointment app: list)
{
event.addAppointment( app);
}
}
else
{
net.fortuna.ical4j.model.Date periodEnd = null;
for (Recur recur: recurList)
{
net.fortuna.ical4j.model.Date until = recur.getUntil();
if ( until != null)
{
if ( periodEnd == null || periodEnd.before( until))
{
periodEnd = until;
}
}
}
if ( periodEnd == null)
{
periodEnd = new net.fortuna.ical4j.model.Date(startdate.getTime() + DateTools.MILLISECONDS_PER_WEEK * 52 *6);
}
PeriodList periodList;
{
long e4 = DateTools.addDays( periodEnd, 1).getTime();
long s1 = startdate.getTime();
Period period = new Period(new DateTime( s1), new DateTime(e4));
periodList = component.calculateRecurrenceSet(period);
}
for ( @SuppressWarnings("unchecked") Iterator<Period> it = periodList.iterator();it.hasNext();)
{
Period p = it.next();
Date s = timeZoneConverter.toRaplaTime(timeZone, p.getStart());
Date e = timeZoneConverter.toRaplaTime(timeZone,p.getEnd());
Appointment singleAppointment = newAppointment( user,s, e);
event.addAppointment( singleAppointment);
}
}
}
else
{
event.addAppointment( appointment);
}
/*
* get a date iterable for given startdate and recurrance
* rule.
* timezone passed is UTC, because timezone calculation has
* already been taken care of earlier
*/
if (uid != null)
{
reservationMap.put( uid, lookupEvent);
}
eventList.add( lookupEvent);
}
catch (ParseException ex)
{
}
} else if (component.getName().equalsIgnoreCase("VTIMEZONE")) {
if (component.getProperties("TZID").size() > 0) {
// TimeZone timezoneFromICal = TimeZone.getTimeZone(component.getProperty("TZID").getValue());
}
}
}
Date minStart = null;
Map<String, List<Entity<Reservation>>> imported = getImportedReservations(minStart);
List<Reservation> toImport = new ArrayList<Reservation>();
for (Reservation reservation:eventList)
{
String uid = reservation.getAnnotation(RaplaObjectAnnotations.KEY_EXTERNALID);
if ( uid == null)
{
eventsImported++;
toImport.add( reservation);
}
else
{
List<Entity<Reservation>> alreadyImported = imported.get( uid);
if ( alreadyImported == null || alreadyImported.isEmpty())
{
eventsImported++;
toImport.add( reservation);
}
else
{
getLogger().debug("Ignoring event with uid " + uid + " already imported. Ignoring" );
eventsPresent++;
}
}
}
getClientFacade().storeObjects(toImport.toArray(Reservation.RESERVATION_ARRAY));
return new Integer[] {eventsInICal, eventsImported, eventsPresent, eventsSkipped};
}
protected Map<String, List<Entity<Reservation>>> getImportedReservations(Date start)
throws RaplaException {
Map<String,List<Entity<Reservation>>> keyMap;
User user = null;
Date end = null;
keyMap = new LinkedHashMap<String, List<Entity<Reservation>>>();
Reservation[] reservations = getQuery().getReservations(user, start, end, null);
for ( Reservation r:reservations)
{
String key = r.getAnnotation(RaplaObjectAnnotations.KEY_EXTERNALID);
if ( key != null )
{
List<Entity<Reservation>> list = keyMap.get( key);
if ( list == null)
{
list = new ArrayList<Entity<Reservation>>();
keyMap.put( key, list);
}
list.add( r);
}
}
return keyMap;
}
//
// private Date toRaplaDate(TimeZone timeZone2,
// net.fortuna.ical4j.model.Date startdate)
// {
// java.util.Calendar cal = java.util.Calendar.getInstance( getRaplaLocale().getSystemTimeZone());
// cal.setTime(startdate);
// cal.add( java.util.Calendar.HOUR_OF_DAY, 2);
// int date = cal.get( java.util.Calendar.DATE);
// int month = cal.get( java.util.Calendar.MONTH);
// int year = cal.get( java.util.Calendar.YEAR);
//
// Date time = cal.getTime();
// Date convertedDate = getRaplaLocale().toRaplaTime(timeZone2, time);
// return null;
// }
private Appointment newAppointment(User user,Date begin, Date end) throws RaplaException {
Appointment appointment = getClientFacade().newAppointment(begin,end,user);
return appointment;
}
/** if the recurances can be matched to one or more appointments return the appointment list else return null*/
private List<Appointment> calcRepeating(List<Recur> recurList, Appointment start) throws RaplaException {
final List<Appointment> appointments = new ArrayList<Appointment>();
for (Recur recur : recurList) {
// FIXME need to implement UTC mapping
final Appointment appointment = getClientFacade().newAppointment(start.getStart(), start.getEnd(), start.getOwner());
appointment.setRepeatingEnabled(true);
WeekDayList dayList = recur.getDayList();
if (dayList.size() > 1 || (dayList.size() == 1 && !recur.getFrequency().equals(Recur.WEEKLY) ))
{
return null;
}
NumberList yearDayList = recur.getYearDayList();
if ( yearDayList.size() > 0)
{
return null;
}
NumberList weekNoList = recur.getWeekNoList();
if ( weekNoList.size() > 0){
return null;
}
NumberList hourList = recur.getHourList();
if ( hourList.size() > 0){
return null;
}
NumberList monthList = recur.getMonthList();
if (monthList.size() > 1 || (monthList.size() == 1 && !recur.getFrequency().equals(Recur.MONTHLY) ))
{
return null;
}
if (recur.getFrequency().equals(Recur.DAILY))
appointment.getRepeating().setType(RepeatingType.DAILY);
else if (recur.getFrequency().equals(Recur.MONTHLY))
appointment.getRepeating().setType(RepeatingType.MONTHLY);
else if (recur.getFrequency().equals(Recur.YEARLY))
appointment.getRepeating().setType(RepeatingType.YEARLY);
else if (recur.getFrequency().equals(Recur.WEEKLY))
appointment.getRepeating().setType(RepeatingType.WEEKLY);
else throw new IllegalStateException("Repeating type "+recur.getFrequency()+" not (yet) supported");
//recur.getCount() == -1 when it never ends
int count = recur.getCount();
appointment.getRepeating().setNumber(count);
if (count <= 0)
{
net.fortuna.ical4j.model.Date until = recur.getUntil();
Date repeatingEnd;
if ( until instanceof DateTime)
{
repeatingEnd = timeZoneConverter.toRaplaTime( timeZone, until);
}
else if ( until != null)
{
repeatingEnd = new Date(until.getTime());
}
else
{
repeatingEnd = null;
}
appointment.getRepeating().setEnd(repeatingEnd);
}
//interval
appointment.getRepeating().setInterval(recur.getInterval());
appointments.add(appointment);
}
return appointments;
}
}
| 04900db4-clienttest | src/org/rapla/plugin/ical/server/RaplaICalImport.java | Java | gpl3 | 19,615 |
package org.rapla.plugin.ical;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.BevelBorder;
import org.rapla.components.iolayer.FileContent;
import org.rapla.components.iolayer.IOInterface;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.Named;
import org.rapla.entities.domain.Allocatable;
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.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.internal.TreeAllocatableSelection;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.IdentifiableMenuEntry;
/**
*
* Creates and shows a dialog for the iCal-import to select a URL or file. Also, you can add resources if you like.
*
* @author Jan Fischer
*/
public class ImportFrom2iCalMenu extends RaplaGUIComponent implements IdentifiableMenuEntry, ActionListener {
JMenuItem item;
String id = "ical";
ICalImport importService;
public ImportFrom2iCalMenu(RaplaContext context,ICalImport importService)
{
super(context);
this.importService = importService;
setChildBundleName(ImportFromICalPlugin.RESOURCE_FILE);
item = new JMenuItem(getString("ical.import"));
item.setIcon(getIcon("icon.import"));
item.addActionListener(this);
}
public JMenuItem getMenuElement() {
return item;
}
public String getId() {
return id;
}
public void actionPerformed(ActionEvent evt) {
try {
show();
} catch (Exception ex) {
showException(ex, getMainComponent());
}
}
String bufferedICal;
/**
* shows a dialog to to import an iCal calendar.
*
* @throws RaplaException
*/
public void show() throws RaplaException {
final TreeAllocatableSelection resourceSelection = new TreeAllocatableSelection( getContext());
JPanel container = new JPanel();
final JPanel superpanel = new JPanel();
superpanel.setLayout(new TableLayout(
new double[][] { { TableLayout.PREFERRED }, { TableLayout.PREFERRED, 2, TableLayout.PREFERRED } }));
superpanel.setAlignmentX(Component.LEFT_ALIGNMENT);
superpanel.setAlignmentY(Component.TOP_ALIGNMENT);
final JPanel panel1 = new JPanel();
Dimension size = new Dimension(850, 125);
panel1.setPreferredSize(size);
panel1.setMinimumSize(size);
panel1.setLayout(new TableLayout(
new double[][] { {TableLayout.PREFERRED, 5, TableLayout.FILL, },
{ TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5, } }));
panel1.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
final String urlText = getString("enter_url");
final JTextField urlField = new JTextField(urlText);
addCopyPaste(urlField);
panel1.add(urlField, "2,0");
final JTextField fileField = new JTextField(getString("click_for_file"));
panel1.add(fileField, "2,2");
fileField.setEditable(false);
fileField.setBackground(new Color(240, 240, 255));
fileField.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
ButtonGroup bg = new ButtonGroup();
final JRadioButton urlRadio = new JRadioButton(getString("url"));
panel1.add(urlRadio, "0,0");
bg.add(urlRadio);
final JRadioButton fileRadio = new JRadioButton(getString("file"));
panel1.add(fileRadio, "0,2");
bg.add(fileRadio);
@SuppressWarnings("unchecked")
final JComboBox comboEventType = new JComboBox(getClientFacade().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION));
final JLabel labelEventType = new JLabel(getString("reservation_type"));
panel1.add(labelEventType, "0,4");
panel1.add(comboEventType, "2,4");
final JComboBox comboNameAttribute = new JComboBox();
final JLabel labelNameAttribute = new JLabel(getString("attribute"));
panel1.add(labelNameAttribute, "0,6");
panel1.add(comboNameAttribute, "2,6");
comboEventType.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
updateNameAttributes(comboEventType, comboNameAttribute);
}
}
});
updateNameAttributes(comboEventType, comboNameAttribute);
urlRadio.setSelected(true);
fileField.setEnabled(false);
setRenderer(comboEventType, comboNameAttribute);
superpanel.add(panel1, "0,0");
superpanel.add(resourceSelection.getComponent(), "0,2");
container.setLayout( new BorderLayout());
JLabel warning = new JLabel("Warning: The ical import is still experimental. Not all events maybe imported correctly.");
warning.setForeground( Color.RED);
container.add( warning, BorderLayout.NORTH);
container.add( superpanel, BorderLayout.CENTER);
final DialogUI dlg = DialogUI.create(getContext(),
getMainComponent(), false, container, new String[] { getString("import"), getString("cancel") });
final ActionListener radioListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean isURL = urlRadio.isSelected() && urlRadio.isEnabled();
boolean isFile = fileRadio.isSelected() && fileRadio.isEnabled();
urlField.setEnabled(isURL);
fileField.setEnabled(isFile);
}
};
urlRadio.addActionListener(radioListener);
fileRadio.addActionListener(radioListener);
MouseAdapter listener = new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e) {
Object source = e.getSource();
if ( source == urlField)
{
if (urlField.isEnabled() && urlField.getText().equalsIgnoreCase(urlText)) {
urlField.setText("");
}
dlg.getButton(0).setEnabled( true );
}
else if ( source == fileField)
{
dlg.getButton(0).setEnabled( bufferedICal != null );
if (fileField.isEnabled()) {
final Frame frame = (Frame) SwingUtilities.getRoot(getMainComponent());
IOInterface io = getService( IOInterface.class);
try {
FileContent file = io.openFile( frame, null, new String[] {".ics"});
if ( file != null)
{
BufferedReader reader = new BufferedReader(new InputStreamReader( file.getInputStream()));
StringBuffer buf = new StringBuffer();
while ( true)
{
String line = reader.readLine();
if ( line == null)
{
break;
}
buf.append( line);
buf.append( "\n");
}
fileField.setText(file.getName());
bufferedICal = buf.toString();
dlg.getButton(0).setEnabled( true );
}
} catch (IOException ex) {
bufferedICal = null;
dlg.getButton(0).setEnabled( false );
showException(ex, getMainComponent());
}
}
}
}
};
urlField.addMouseListener(listener);
fileField.addMouseListener(listener);
final String title = "iCal-" + getString("import");
dlg.setTitle(title);
dlg.setSize(new Dimension(850, 100));
// dlg.setResizable(false);
dlg.getButton(0).setIcon(getIcon("icon.import"));
dlg.getButton(1).setIcon(getIcon("icon.cancel"));
dlg.getButton(0).setAction(new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
Collection<Allocatable> liste = resourceSelection.getAllocatables();
try {
boolean isURL = urlRadio.isSelected() && urlRadio.isEnabled();
String iCal;
if (isURL) {
iCal = urlField.getText();
} else {
iCal = bufferedICal;
}
String[] allocatableIds = new String[liste.size()];
int i = 0;
for ( Allocatable alloc:liste)
{
allocatableIds[i++] = alloc.getId();
}
final DynamicType dynamicType = (DynamicType) comboEventType.getSelectedItem();
if (dynamicType == null)
return;
String eventTypeKey = dynamicType.getKey();
Object selectedItem = comboNameAttribute.getSelectedItem();
if (selectedItem == null)
return;
String eventTypeAttributeNameKey = ((Attribute) selectedItem).getKey();
Integer[] status = importService.importICal(iCal, isURL, allocatableIds, eventTypeKey, eventTypeAttributeNameKey).get();
int eventsInICal = status[0];
int eventsImported = status[1];
int eventsPresent = status[2];
int eventsSkipped = status[3];
getClientFacade().refresh();
dlg.close();
String text = "Imported " + eventsImported + "/" + eventsInICal + ". " + eventsPresent + " present";
if (eventsSkipped > 0)
{
text += " and " + eventsSkipped + " skipped ";
}
else
{
text+=".";
}
DialogUI okDlg = DialogUI.create(getContext(), getMainComponent(), false, title, text);
okDlg.start();
} catch (Exception e1) {
showException(e1, getMainComponent());
}
}
});
dlg.start();
}
@SuppressWarnings("unchecked")
private void setRenderer(final JComboBox comboEventType,
final JComboBox comboNameAttribute) {
final DefaultListCellRenderer aRenderer = new NamedListCellRenderer();
comboEventType.setRenderer(aRenderer);
comboNameAttribute.setRenderer(aRenderer);
}
final protected TreeFactory getTreeFactory() {
return getService(TreeFactory.class);
}
private class NamedListCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
if (value != null && value instanceof Named)
value = ((Named) value).getName(ImportFrom2iCalMenu.this.getLocale());
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}
}
@SuppressWarnings("unchecked")
private void updateNameAttributes(JComboBox comboEventType, JComboBox comboNameAttribute) {
final DynamicType dynamicType = (DynamicType) comboEventType.getSelectedItem();
ComboBoxModel result;
if (dynamicType == null) {
//no dynamic type found, so empty combobox model
result = new DefaultComboBoxModel();
} else {
// found one, so determine all string attribute of event type and update model
final Attribute[] attributes = dynamicType.getAttributes();
final List<Attribute> attributeResult = new ArrayList<Attribute>();
for (Attribute attribute : attributes) {
if (attribute.getType().is(AttributeType.STRING))
{
attributeResult.add(attribute);
}
}
DefaultComboBoxModel defaultComboBoxModel = new DefaultComboBoxModel(attributeResult.toArray());
result = defaultComboBoxModel;
}
//initialize model
comboNameAttribute.setModel(result);
}
}
| 04900db4-clienttest | src/org/rapla/plugin/ical/ImportFrom2iCalMenu.java | Java | gpl3 | 13,202 |