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.servletpages;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
public interface RaplaMenuGenerator {
public void generatePage( HttpServletRequest request, PrintWriter out );
}
| 04900db4-rob | src/org/rapla/servletpages/RaplaMenuGenerator.java | Java | gpl3 | 233 |
/**
*
*/
package org.rapla.servletpages;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.components.util.IOUtil;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
public class RaplaStatusPageGenerator implements RaplaPageGenerator{
I18nBundle m_i18n;
public RaplaStatusPageGenerator(RaplaContext context) throws RaplaContextException {
m_i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
}
public void generatePage( ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws IOException {
response.setContentType("text/html; charset=ISO-8859-1");
String linkPrefix = request.getPathTranslated() != null ? "../": "";
java.io.PrintWriter out = response.getWriter();
out.println( "<html>" );
out.println( "<head>" );
out.println(" <link REL=\"stylesheet\" href=\"" + linkPrefix + "default.css\" type=\"text/css\">");
out.println(" <title>Rapla Server status!</title>");
out.println("</head>" );
out.println( "<body>" );
boolean isSigned = IOUtil.isSigned();
String signed = m_i18n.getString( isSigned ? "yes": "no");
String javaversion = System.getProperty("java.version");
out.println( "<p>Server running </p>" + m_i18n.format("info.text", signed, javaversion));
out.println( "<hr>" );
out.println( "</body>" );
out.println( "</html>" );
out.close();
}
} | 04900db4-rob | src/org/rapla/servletpages/RaplaStatusPageGenerator.java | Java | gpl3 | 1,732 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.servletpages;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* You can add arbitrary serlvet pages to your rapla webapp.
*
*/
public interface RaplaPageGenerator
{
void generatePage( ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException;
}
| 04900db4-rob | src/org/rapla/servletpages/RaplaPageGenerator.java | Java | gpl3 | 1,425 |
<body>
<p>Contains the default pages served by the rapla server servlet</p>
</body>
| 04900db4-rob | src/org/rapla/servletpages/package.html | HTML | gpl3 | 86 |
package org.rapla.servletpages;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
/**
* User: kuestermann
* Date: 15.08.12
* Time: 19:24
*/
public interface ServletRequestPreprocessor {
/**
* will return request handle to service
*
* @param context
* @param servletContext
* @param request
* @return null values will be ignored, otherwise return object will be used for further processing
*/
HttpServletRequest handleRequest(RaplaContext context, ServletContext servletContext, HttpServletRequest request,HttpServletResponse response) throws RaplaException;
}
| 04900db4-rob | src/org/rapla/servletpages/ServletRequestPreprocessor.java | Java | gpl3 | 814 |
package org.rapla.servletpages;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
public class DefaultHTMLMenuEntry extends RaplaComponent implements RaplaMenuGenerator
{
protected String name;
protected String linkName;
public DefaultHTMLMenuEntry(RaplaContext context,String name, String linkName)
{
super( context);
this.name = name;
this.linkName = linkName;
}
public DefaultHTMLMenuEntry(RaplaContext context)
{
super( context);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLinkName() {
return linkName;
}
public void setLinkName(String linkName) {
this.linkName = linkName;
}
public void generatePage( HttpServletRequest request, PrintWriter out )
{
// writing the html code line for a button
// including the link to the appropriate servletpage
out.println("<span class=\"button\"><a href=\"" + getLinkName() + "\">" + getName() + "</a></span>");
}
}
| 04900db4-rob | src/org/rapla/servletpages/DefaultHTMLMenuEntry.java | Java | gpl3 | 1,150 |
/**
*
*/
package org.rapla.servletpages;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.RaplaMainContainer;
import org.rapla.components.util.IOUtil;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class RaplaJNLPPageGenerator extends RaplaComponent implements RaplaPageGenerator{
public RaplaJNLPPageGenerator( RaplaContext context )
{
super( context);
}
private String getCodebase( HttpServletRequest request) {
StringBuffer codebaseBuffer = new StringBuffer();
String forwardProto = request.getHeader("X-Forwarded-Proto");
boolean secure = (forwardProto != null && forwardProto.toLowerCase().equals("https")) || request.isSecure();
codebaseBuffer.append(secure ? "https://" : "http://");
codebaseBuffer.append(request.getServerName());
if (request.getServerPort() != (!secure ? 80 : 443))
{
codebaseBuffer.append(':');
codebaseBuffer.append(request.getServerPort());
}
codebaseBuffer.append(request.getContextPath());
codebaseBuffer.append('/');
return codebaseBuffer.toString();
}
private String getLibsJNLP(ServletContext context, String webstartRoot) throws java.io.IOException {
List<String> list = getClientLibs(context);
StringBuffer buf = new StringBuffer();
for (String file:list) {
buf.append("\n<jar href=\""+webstartRoot + "/");
buf.append(file);
buf.append("\"");
if (file.equals("raplaclient.jar")) {
buf.append(" main=\"true\"");
}
buf.append("/>");
}
return buf.toString();
}
public static List<String> getClientLibs(ServletContext context)
throws IOException {
List<String> list = new ArrayList<String>();
URL resource = RaplaJNLPPageGenerator.class.getResource("/clientlibs.properties");
if (resource != null)
{
byte[] bytes = IOUtil.readBytes( resource);
String string = new String( bytes);
String[] split = string.split(";");
for ( String file:split)
{
list.add( "webclient/" + file);
}
}
else
{
String base = context.getRealPath(".");
if ( base != null)
{
java.io.File baseFile = new java.io.File(base);
java.io.File[] files = IOUtil.getJarFiles(base,"webclient");
for (File file:files) {
String relativeURL = IOUtil.getRelativeURL(baseFile,file);
list.add( relativeURL);
}
}
}
return list;
}
protected List<String> getProgramArguments() {
List<String> list = new ArrayList<String>();
return list;
}
public void generatePage( ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws IOException {
java.io.PrintWriter out = response.getWriter();
String webstartRoot = ".";
long currentTimeMillis = System.currentTimeMillis();
response.setDateHeader("Last-Modified",currentTimeMillis);
response.addDateHeader("Expires", 0);
response.addDateHeader("Date", currentTimeMillis);
response.setHeader("Cache-Control", "no-cache");
final String defaultTitle = getI18n().getString("rapla.title");
String menuName;
try
{
menuName= getQuery().getSystemPreferences().getEntryAsString(RaplaMainContainer.TITLE, defaultTitle);
}
catch (RaplaException e) {
menuName = defaultTitle;
}
response.setContentType("application/x-java-jnlp-file;charset=utf-8");
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
out.println("<jnlp spec=\"1.0+\" codebase=\"" + getCodebase(request) + "\">");
out.println("<information>");
out.println(" <title>"+menuName+"</title>");
out.println(" <vendor>Rapla team</vendor>");
out.println(" <homepage href=\"http://code.google.com/p/rapla/\"/>");
out.println(" <description>Resource Scheduling Application</description>");
// we changed the logo from .gif to .png to make it more sexy
//differentiate between icon and splash because of different sizes!
out.println(" <icon kind=\"default\" href=\""+webstartRoot+"/webclient/rapla_64x64.png\" width=\"64\" height=\"64\"/> ");
out.println(" <icon kind=\"desktop\" href=\""+webstartRoot+"/webclient/rapla_128x128.png\" width=\"128\" height=\"128\"/> ");
out.println(" <icon kind=\"shortcut\" href=\""+webstartRoot+"/webclient/rapla_64x64.png\" width=\"64\" height=\"64\"/> ");
// and here aswell
out.println(" <icon kind=\"splash\" href=\""+webstartRoot+ "/webclient/logo.png\"/> ");
out.println(" <update check=\"always\" policy=\"always\"/>");
out.println(" <shortcut online=\"true\">");
out.println(" <desktop/>");
out.println(" <menu submenu=\"" + menuName + "\"/>");
out.println(" </shortcut>");
out.println("</information>");
boolean allpermissionsAllowed = IOUtil.isSigned();
final String parameter = request.getParameter("sandbox");
if (allpermissionsAllowed && (parameter== null || parameter.trim().toLowerCase().equals("false")))
{
out.println("<security>");
out.println(" <all-permissions/>");
out.println("</security>");
}
out.println("<resources>");
out.println(" <j2se version=\"1.4+\"/>");
out.println(getLibsJNLP(context, webstartRoot));
out.println("</resources>");
out.println("<application-desc main-class=\"org.rapla.client.MainWebstart\">");
for (Iterator<String> it = getProgramArguments().iterator(); it.hasNext();)
{
out.println(" <argument>" + it.next() + "</argument> ");
}
out.println("</application-desc>");
out.println("</jnlp>");
out.close();
}
} | 04900db4-rob | src/org/rapla/servletpages/RaplaJNLPPageGenerator.java | Java | gpl3 | 6,075 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.rapla.entities.Category;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaException;
/** Methods for quering the various entities of the backend
*/
public interface QueryModule
{
/** returns all DynamicTypes matching the specified classification
possible keys are reservation, person and resource.
@see org.rapla.entities.dynamictype.DynamicTypeAnnotations
*/
DynamicType[] getDynamicTypes(String classificationType) throws RaplaException;
/** returns the DynamicType with the passed elementKey */
DynamicType getDynamicType(String elementKey) throws RaplaException;
/** returns The root category. */
Category getSuperCategory();
/** returns The category that contains all the user-groups of rapla */
Category getUserGroupsCategory() throws RaplaException;
/** returns all users */
User[] getUsers() throws RaplaException;
/** returns the user with the specified username */
User getUser(String username) throws RaplaException;
/** returns all allocatables that match the passed ClassificationFilter. If null all readable allocatables are returned*/
Allocatable[] getAllocatables(ClassificationFilter[] filters) throws RaplaException;
/** returns all readable allocatables, same as getAllocatables(null)*/
Allocatable[] getAllocatables() throws RaplaException;
/** returns the reservations of the specified user in the specified interval
@param user A user-object or null for all users
@param start only reservations beginning after the start-date will be returned (can be null).
@param end only reservations beginning before the end-date will be returned (can be null).
@param filters you can specify classificationfilters or null for all reservations .
*/
Reservation[] getReservations(User user,Date start,Date end,ClassificationFilter[] filters) throws RaplaException;
/**returns all reservations that have allocated at least one Resource or Person that is part of the allocatables array.
@param allocatables only reservations that allocate at least on element of this array will be returned.
@param start only reservations beginning after the start-date will be returned (can be null).
@param end only reservations beginning before the end-date will be returned (can be null).
**/
Reservation[] getReservations(Allocatable[] allocatables,Date start,Date end) throws RaplaException;
Reservation[] getReservationsForAllocatable(Allocatable[] allocatables, Date start,Date end,ClassificationFilter[] filters) throws RaplaException;
List<Reservation> getReservations(Collection<Conflict> conflicts) throws RaplaException;
/** returns all available periods */
Period[] getPeriods() throws RaplaException;
/** returns an Interface for accessing the periods
* @throws RaplaException */
PeriodModel getPeriodModel() throws RaplaException;
/** returns the current date in GMT+0 Timezone. If rapla operates
in multi-user mode, the date should be calculated from the
server date.
*/
Date today();
/** returns all allocatables from the set of passed allocatables, that are already allocated by different parallel reservations at the time-slices, that are described by the appointment */
public Map<Allocatable, Collection<Appointment>> getAllocatableBindings(Collection<Allocatable> allocatables,Collection<Appointment> forAppointment) throws RaplaException;
/** returns all allocatables, that are already allocated by different parallel reservations at the time-slices, that are described by the appointment
* @deprecated use {@link #getAllocatableBindings(Collection,Collection)} instead
* */
@Deprecated
Allocatable[] getAllocatableBindings(Appointment appointment) throws RaplaException;
/** returns all existing conflicts with the reservation */
Conflict[] getConflicts(Reservation reservation) throws RaplaException;
/** returns all existing conflicts that are visible for the user
conflicts
*/
Conflict[] getConflicts() throws RaplaException;
/** returns if the user has the permissions to change/create an
allocation on the passed appointment. Changes of an
existing appointment that are in an permisable
timeframe are allowed. Example: The extension of an exisiting appointment,
doesn't affect allocations in the past and should not create a
conflict with the permissions.
*/
//boolean hasPermissionToAllocate( Appointment appointment, Allocatable allocatable );
/** returns the preferences for the passed user, must be admin todo this. creates a new prefence object if not set*/
Preferences getPreferences(User user) throws RaplaException;
/** returns the preferences for the passed user, must be admin todo this.*/
Preferences getPreferences(User user, boolean createIfNotNull) throws RaplaException;
/** returns the preferences for the login user */
Preferences getPreferences() throws RaplaException;
Preferences getSystemPreferences() throws RaplaException;
/** returns if the user is allowed to exchange the allocatables of this reservation. A user can do it if he has
* at least admin privileges for one allocatable. He can only exchange or remove or insert allocatables he has admin privileges on.
* The User cannot change appointments.*/
boolean canExchangeAllocatables(Reservation reservation);
boolean canReadReservationsFromOthers(User user);
boolean canCreateReservations(User user);
boolean canEditTemplats(User user);
public Collection<String> getTemplateNames() throws RaplaException;
public Collection<Reservation> getTemplateReservations(String name) throws RaplaException;
Date getNextAllocatableDate(Collection<Allocatable> asList, Appointment appointment, CalendarOptions options) throws RaplaException;
}
| 04900db4-rob | src/org/rapla/facade/QueryModule.java | Java | gpl3 | 7,420 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import org.rapla.ConnectInfo;
import org.rapla.entities.User;
import org.rapla.framework.RaplaException;
/** Encapsulates the methods responsible for authentification.
*/
public interface UserModule {
/** The login method establishes the connection and loads data.
* @return false on an invalid login.
* @throws RaplaException if the connection can't be established.
*/
boolean login(String username,char[] password) throws RaplaException;
boolean login(ConnectInfo connectInfo) throws RaplaException;
/** logout of the current user */
void logout() throws RaplaException;
/** returns if a session is active. True between a successful login and logout. */
boolean isSessionActive();
/** throws an Exception if no user has loged in.
@return the user that has loged in. */
User getUser() throws RaplaException;
void changePassword(User user,char[] oldPassword,char[] newPassword) throws RaplaException;
boolean canChangePassword();
/** changes the name for the logged in user. If a person is connected then all three fields are used. Otherwise only lastname is used*/
void changeName(String title, String firstname, String surname) throws RaplaException;
void confirmEmail(String newEmail) throws RaplaException;
/** changes the name for the user that is logged in. */
void changeEmail(String newEmail) throws RaplaException;
}
| 04900db4-rob | src/org/rapla/facade/UserModule.java | Java | gpl3 | 2,403 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.User;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.RepeatingType;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaException;
/** All methods that allow modifing the entity-objects.
*/
public interface ModificationModule {
/** check if the reservation can be saved */
void checkReservation(Reservation reservation) throws RaplaException;
/** creates a new Rapla Map. Keep in mind that only RaplaObjects and Strings are allowed as entries for a RaplaMap!*/
<T> RaplaMap<T> newRaplaMap( Map<String,T> map);
/** creates an ordered RaplaMap with the entries of the collection as values and their position in the collection from 1..n as keys*/
<T> RaplaMap<T> newRaplaMap( Collection<T> col);
CalendarSelectionModel newCalendarModel( User user) throws RaplaException;
/** Creates a new event, Creates a new event from the first dynamic type found, basically a shortcut to newReservation(getDynamicType(VALUE_CLASSIFICATION_TYPE_RESERVATION)[0].newClassification())
* This is a convenience method for testing.
*/
Reservation newReservation() throws RaplaException;
/** Shortcut for newReservation(classification,getUser()*/
Reservation newReservation(Classification classification) throws RaplaException;
/** Creates a new reservation from the classifcation object and with the passed user as its owner
* You can create a new classification from a {@link DynamicType} with newClassification method.
* @see DynamicType#newClassification()
*/
Reservation newReservation(Classification classification,User user) throws RaplaException;
Appointment newAppointment(Date startDate,Date endDate) throws RaplaException;
Appointment newAppointment(Date startDate,Date endDate, User user) throws RaplaException;
/** @deprecated use newAppointment and change the repeating type of the appointment afterwards*/
Appointment newAppointment(Date startDate,Date endDate, RepeatingType repeatingType, int repeatingDuration) throws RaplaException;
/** Creates a new resource from the first dynamic type found, basically a shortcut to newAlloctable(getDynamicType(VALUE_CLASSIFICATION_TYPE_RESOURCE)[0].newClassification()).
* This is a convenience method for testing.
* */
Allocatable newResource() throws RaplaException;
/** Creates a new person resource, Creates a new resource from the first dynamic type found, basically a shortcut to newAlloctable(getDynamicType(VALUE_CLASSIFICATION_TYPE_PERSON)[0].newClassification())
* This is a convenience method for testing.
*/
Allocatable newPerson() throws RaplaException;
/** Creates a new allocatable from the classifcation object and with the passed user as its owner
* You can create a new classification from a {@link DynamicType} with newClassification method.
* @see DynamicType#newClassification()*/
Allocatable newAllocatable( Classification classification, User user) throws RaplaException;
/** Shortcut for newAllocatble(classification,getUser()*/
Allocatable newAllocatable( Classification classification) throws RaplaException;
Allocatable newPeriod() throws RaplaException;
Category newCategory() throws RaplaException;
Attribute newAttribute(AttributeType attributeType) throws RaplaException;
DynamicType newDynamicType(String classificationType) throws RaplaException;
User newUser() throws RaplaException;
/** Clones an entity. The entities will get new identifier and
won't be equal to the original. The resulting object is not persistant and therefore
can be editet.
*/
<T extends Entity> T clone(T obj) throws RaplaException;
/** This call will be delegated to the {@link org.rapla.storage.StorageOperator}. It
* returns an editable working copy of an object. Only objects return by this method and new objects are editable.
* To get the persistant, non-editable version of a working copy use {@link #getPersistant} */
<T extends Entity> T edit(T obj) throws RaplaException;
<T extends Entity> Collection<T> edit(Collection<T> list) throws RaplaException;
/** Returns the persistant version of a working copy.
* Throws an {@link org.rapla.entities.EntityNotFoundException} when the
* object is not found
* @see #edit
* @see #clone
*/
<T extends Entity> T getPersistant(T working) throws RaplaException;
<T extends Entity> Map<T,T> getPersistant(Collection<T> list) throws RaplaException;
/** This call will be delegated to the {@link org.rapla.storage.StorageOperator} */
void storeObjects(Entity<?>[] obj) throws RaplaException;
/** @see #storeObjects(Entity[]) */
void store(Entity<?> obj) throws RaplaException;
/** This call will be delegated to the {@link org.rapla.storage.StorageOperator} */
void removeObjects(Entity<?>[] obj) throws RaplaException;
/** @see #removeObjects(Entity[]) */
void remove(Entity<?> obj) throws RaplaException;
/** stores and removes objects in the one transaction
* @throws RaplaException */
void storeAndRemove( Entity<?>[] storedObjects, Entity<?>[] removedObjects) throws RaplaException;
void setTemplateName(String templateName);
String getTemplateName();
CommandHistory getCommandHistory();
}
| 04900db4-rob | src/org/rapla/facade/ModificationModule.java | Java | gpl3 | 6,904 |
package org.rapla.facade;
import org.rapla.framework.RaplaException;
public class CalendarNotFoundExeption extends RaplaException {
public CalendarNotFoundExeption(String text) {
super(text);
}
private static final long serialVersionUID = 1L;
}
| 04900db4-rob | src/org/rapla/facade/CalendarNotFoundExeption.java | Java | gpl3 | 268 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.rapla.components.util.Assert;
import org.rapla.entities.Entity;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.internal.PeriodImpl;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.facade.PeriodModel;
import org.rapla.facade.QueryModule;
import org.rapla.framework.RaplaException;
import org.rapla.storage.StorageOperator;
class PeriodModelImpl implements PeriodModel,ModificationListener
{
TreeSet<Period> m_periods = new TreeSet<Period>(new Comparator<Period>() {
public int compare(Period o1, Period o2) {
int compareTo = o1.compareTo(o2);
return -compareTo;
}
}
);
ClientFacade facade;
Period defaultPeriod;
PeriodModelImpl( ClientFacade query ) throws RaplaException {
this.facade = query;
update();
}
public void update() throws RaplaException {
m_periods.clear();
DynamicType type = facade.getDynamicType(StorageOperator.PERIOD_TYPE);
ClassificationFilter[] filters = type.newClassificationFilter().toArray();
Collection<Allocatable> allocatables = facade.getOperator().getAllocatables( filters);
for ( Allocatable alloc:allocatables)
{
Classification classification = alloc.getClassification();
String name = (String)classification.getValue("name");
Date start = (Date) classification.getValue("start");
Date end = (Date) classification.getValue("end");
PeriodImpl period = new PeriodImpl(name,start,end);
m_periods.add(period);
}
}
public void dataChanged(ModificationEvent evt) throws RaplaException
{
if (isPeriodModified(evt))
{
update();
}
}
protected boolean isPeriodModified(ModificationEvent evt) {
for (Entity changed:evt.getChanged())
{
if ( isPeriod( changed))
{
return true;
}
}
for (Entity changed:evt.getRemoved())
{
if ( isPeriod( changed))
{
return true;
}
}
return false;
}
private boolean isPeriod(Entity entity) {
if ( entity.getRaplaType() != Allocatable.TYPE)
{
return false;
}
Allocatable alloc = (Allocatable) entity;
Classification classification = alloc.getClassification();
if ( classification == null)
{
return false;
}
if (!classification.getType().getKey().equals(StorageOperator.PERIOD_TYPE))
{
return false;
}
return true;
}
protected QueryModule getQuery() {
return facade;
}
/** returns the first matching period or null if no period matches.*/
public Period getPeriodFor(Date date) {
if (date == null)
return null;
PeriodImpl comparePeriod = new PeriodImpl("DUMMY",date,date);
Iterator<Period> it = m_periods.tailSet(comparePeriod).iterator();
while (it.hasNext()) {
Period period = it.next();
if (period.contains(date)) {
return period;
}
}
return null;
}
static private long diff(Date d1,Date d2) {
long diff = d1.getTime()-d2.getTime();
if (diff<0)
diff = diff * -1;
return diff;
}
public Period getNearestPeriodForDate(Date date) {
return getNearestPeriodForStartDate( m_periods, date, null);
}
public Period getNearestPeriodForStartDate(Date date) {
return getNearestPeriodForStartDate( date, null);
}
public Period getNearestPeriodForStartDate(Date date, Date endDate) {
return getNearestPeriodForStartDate( getPeriodsFor( date ), date, endDate);
}
public Period getNearestPeriodForEndDate(Date date) {
return getNearestPeriodForEndDate( getPeriodsFor( date ), date);
}
static private Period getNearestPeriodForStartDate(Collection<Period> periodList, Date date, Date endDate) {
Period result = null;
long min_from_start=Long.MAX_VALUE, min_from_end=0;
long from_start, from_end=0;
Iterator<Period> it = periodList.iterator();
while (it.hasNext())
{
Period period = it.next();
if ( period == null)
{ // EXCO: Why this test ?
continue;
}
from_start = diff(period.getStart(),date);
if ( endDate != null )
{
from_end = Math.abs(diff(period.getEnd(), endDate));
}
if ( from_start < min_from_start
|| (from_start == min_from_start && from_end < min_from_end)
)
{
min_from_start = from_start;
min_from_end = from_end;
result = period;
}
}
return result;
}
static private Period getNearestPeriodForEndDate(Collection<Period> periodList, Date date) {
Period result = null;
long min=-1;
Iterator<Period> it = periodList.iterator();
while (it.hasNext()) {
Period period = it.next();
if (min == -1) {
min = diff(period.getEnd(),date);
result = period;
}
if (diff(period.getEnd(),date) < min) {
min = diff(period.getStart(),date);
result = period;
}
}
return result;
}
/** return all matching periods.*/
public List<Period> getPeriodsFor(Date date) {
ArrayList<Period> list = new ArrayList<Period>();
if (date == null)
return list;
PeriodImpl comparePeriod = new PeriodImpl("DUMMY",date,date);
SortedSet<Period> set = m_periods.tailSet(comparePeriod);
Iterator<Period> it = set.iterator();
while (it.hasNext()) {
Period period = it.next();
//System.out.println(m_periods[i].getStart() + " - " + m_periods[i].getEnd());
if (period.contains(date)) {
list.add( period );
}
}
return list;
}
public int getSize() {
Assert.notNull(m_periods,"Componenet not setup!");
return m_periods.size();
}
public Period[] getAllPeriods() {
Period[] sortedPriods = m_periods.toArray( Period.PERIOD_ARRAY);
return sortedPriods;
}
public Object getElementAt(int index) {
Assert.notNull(m_periods,"Componenet not setup!");
Iterator<Period> it = m_periods.iterator();
for (int i=0;it.hasNext();i++) {
Object obj = it.next();
if (i == index)
return obj;
}
return null;
}
}
| 04900db4-rob | src/org/rapla/facade/internal/PeriodModelImpl.java | Java | gpl3 | 8,119 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade.internal;
import static org.rapla.entities.configuration.CalendarModelConfiguration.EXPORT_ENTRY;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.rapla.components.util.Assert;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.IllegalAnnotationException;
import org.rapla.entities.Named;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.configuration.CalendarModelConfiguration;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.configuration.internal.CalendarModelConfigurationImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.AppointmentBlockStartComparator;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.entities.dynamictype.internal.ParsedText;
import org.rapla.entities.dynamictype.internal.ParsedText.EvalContext;
import org.rapla.entities.dynamictype.internal.ParsedText.Function;
import org.rapla.entities.dynamictype.internal.ParsedText.ParseContext;
import org.rapla.entities.storage.CannotExistWithoutTypeException;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarNotFoundExeption;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.Conflict;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.storage.UpdateResult;
public class CalendarModelImpl implements CalendarSelectionModel
{
private static final String DEFAULT_VIEW = "week";//WeekViewFactory.WEEK_VIEW;
private static final String ICAL_EXPORT_ENABLED = "org.rapla.plugin.export2ical"+ ".selected";
private static final String HTML_EXPORT_ENABLED = EXPORT_ENTRY + ".selected";
Date startDate;
Date endDate;
Date selectedDate;
List<RaplaObject> selectedObjects = new ArrayList<RaplaObject>();
String title;
ClientFacade m_facade;
String selectedView;
I18nBundle i18n;
RaplaContext context;
RaplaLocale raplaLocale;
User user;
Map<String,String> optionMap = new HashMap<String,String>();
//Map<String,String> viewOptionMap = new HashMap<String,String>();
boolean defaultEventTypes = true;
boolean defaultResourceTypes = true;
Collection<TimeInterval> timeIntervals = Collections.emptyList();
Collection<Allocatable> markedAllocatables = Collections.emptyList();
Map<DynamicType,ClassificationFilter> reservationFilter = new LinkedHashMap<DynamicType, ClassificationFilter>();
Map<DynamicType,ClassificationFilter> allocatableFilter = new LinkedHashMap<DynamicType, ClassificationFilter>();
public static final RaplaConfiguration ALLOCATABLES_ROOT = new RaplaConfiguration("rootnode", "allocatables");
public CalendarModelImpl(RaplaContext context, User user, ClientFacade facade) throws RaplaException {
this.context = context;
this.raplaLocale =context.lookup(RaplaLocale.class);
i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
m_facade = facade;
if ( user == null && m_facade.isSessionActive()) {
user = m_facade.getUser();
}
Date today = m_facade.today();
setSelectedDate( today);
setStartDate( today);
setEndDate( DateTools.addYear(getStartDate()));
DynamicType[] types = m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE);
if ( types.length == 0 ) {
types = m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON);
}
setSelectedObjects( Collections.singletonList( types[0]) );
setViewId( DEFAULT_VIEW);
this.user = user;
if ( user != null && !user.isAdmin()) {
boolean selected = m_facade.getSystemPreferences().getEntryAsBoolean( CalendarModel.ONLY_MY_EVENTS_DEFAULT, true);
optionMap.put( CalendarModel.ONLY_MY_EVENTS, selected ? "true" : "false");
}
optionMap.put( CalendarModel.SAVE_SELECTED_DATE, "false");
resetExports();
}
public void resetExports()
{
setTitle(null);
setOption( CalendarModel.SHOW_NAVIGATION_ENTRY, "true");
setOption(HTML_EXPORT_ENABLED, "false");
setOption(ICAL_EXPORT_ENABLED, "false");
}
public boolean isMatchingSelectionAndFilter( Appointment appointment) throws RaplaException
{
Reservation reservation = appointment.getReservation();
if ( reservation == null)
{
return false;
}
Allocatable[] allocatables = reservation.getAllocatablesFor(appointment);
HashSet<RaplaObject> hashSet = new HashSet<RaplaObject>( Arrays.asList(allocatables));
Collection<RaplaObject> selectedObjectsAndChildren = getSelectedObjectsAndChildren();
hashSet.retainAll( selectedObjectsAndChildren);
boolean matchesAllotables = hashSet.size() != 0;
if ( !matchesAllotables)
{
return false;
}
Classification classification = reservation.getClassification();
if ( isDefaultEventTypes())
{
return true;
}
ClassificationFilter[] reservationFilter = getReservationFilter();
for ( ClassificationFilter filter:reservationFilter)
{
if (filter.matches(classification))
{
return true;
}
}
return false;
}
public boolean setConfiguration(CalendarModelConfiguration config, final Map<String,String> alternativOptions) throws RaplaException {
ArrayList<RaplaObject> selectedObjects = new ArrayList<RaplaObject>();
allocatableFilter.clear();
reservationFilter.clear();
if ( config == null)
{
defaultEventTypes = true;
defaultResourceTypes = true;
DynamicType type =null;
{
DynamicType[] dynamicTypes = m_facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE);
if ( dynamicTypes.length > 0)
{
type = dynamicTypes[0];
}
}
if ( type == null)
{
DynamicType[] dynamicTypes = m_facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON);
if ( dynamicTypes.length > 0)
{
type = dynamicTypes[0];
}
}
if ( type != null)
{
setSelectedObjects( Collections.singletonList(type));
}
return true;
}
else
{
defaultEventTypes = config.isDefaultEventTypes();
defaultResourceTypes = config.isDefaultResourceTypes();
}
boolean couldResolveAllEntities = true;
// get filter
title = config.getTitle();
selectedView = config.getView();
//selectedObjects
optionMap = new TreeMap<String,String>();
// viewOptionMap = new TreeMap<String,String>();
if ( config.getOptionMap() != null)
{
Map<String,String> configOptions = config.getOptionMap();
addOptions(configOptions);
}
if (alternativOptions != null )
{
addOptions(alternativOptions);
}
final String saveDate = optionMap.get( CalendarModel.SAVE_SELECTED_DATE);
if ( config.getSelectedDate() != null && (saveDate == null || saveDate.equals("true"))) {
setSelectedDate( config.getSelectedDate() );
}
else
{
setSelectedDate( m_facade.today());
}
if ( config.getStartDate() != null) {
setStartDate( config.getStartDate() );
}
else
{
setStartDate( m_facade.today());
}
if ( config.getEndDate() != null && (saveDate == null || saveDate.equals("true"))) {
setEndDate( config.getEndDate() );
}
else
{
setEndDate( DateTools.addYear(getStartDate()));
}
selectedObjects.addAll( config.getSelected());
if ( config.isResourceRootSelected())
{
selectedObjects.add( ALLOCATABLES_ROOT);
}
Set<User> selectedUsers = getSelected(User.TYPE);
User currentUser = getUser();
if (currentUser != null && selectedUsers.size() == 1 && selectedUsers.iterator().next().equals( currentUser))
{
if ( getOption( CalendarModel.ONLY_MY_EVENTS) == null)
{
setOption( CalendarModel.ONLY_MY_EVENTS, "true");
selectedObjects.remove( currentUser);
}
}
setSelectedObjects( selectedObjects );
for ( ClassificationFilter f:config.getFilter())
{
final DynamicType type = f.getType();
final String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
boolean eventType = annotation != null &&annotation.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
Map<DynamicType,ClassificationFilter> map = eventType ? reservationFilter : allocatableFilter;
map.put(type, f);
}
return couldResolveAllEntities;
}
protected void addOptions(Map<String,String> configOptions) {
for (Map.Entry<String, String> entry:configOptions.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
optionMap.put( key, value);
}
}
public User getUser() {
return user;
}
public CalendarModelConfigurationImpl createConfiguration() throws RaplaException {
ClassificationFilter[] allocatableFilter = isDefaultResourceTypes() ? null : getAllocatableFilter();
ClassificationFilter[] eventFilter = isDefaultEventTypes() ? null : getReservationFilter();
return createConfiguration(allocatableFilter, eventFilter);
}
CalendarModelConfigurationImpl beforeTemplateConf;
public void dataChanged(ModificationEvent evt) throws RaplaException
{
Collection<RaplaObject> selectedObjects = getSelectedObjects();
if ( evt == null)
{
return;
}
boolean switchTemplate = ((UpdateResult)evt).isSwitchTemplateMode();
if (switchTemplate)
{
boolean changeToTemplate= m_facade.getTemplateName() != null;
if (changeToTemplate)
{
beforeTemplateConf = createConfiguration();
setSelectedObjects(Collections.singleton(ALLOCATABLES_ROOT));
}
else if ( beforeTemplateConf != null)
{
setConfiguration( beforeTemplateConf, null);
beforeTemplateConf = null;
}
}
{
Collection<RaplaObject> newSelection = new ArrayList<RaplaObject>();
boolean changed = false;
for ( RaplaObject obj: selectedObjects)
{
if ( obj instanceof Entity)
{
if (!evt.isRemoved((Entity) obj))
{
newSelection.add( obj);
}
else
{
changed = true;
}
}
}
if ( changed)
{
setSelectedObjects( newSelection);
}
}
{
if (evt.isModified( DynamicType.TYPE) || evt.isModified( Category.TYPE) || evt.isModified( User.TYPE))
{
CalendarModelConfigurationImpl config = (CalendarModelConfigurationImpl)createConfiguration();
updateConfig(evt, config);
if ( beforeTemplateConf != null)
{
updateConfig(evt, beforeTemplateConf);
}
setConfiguration( config, null);
}
}
}
public void updateConfig(ModificationEvent evt, CalendarModelConfigurationImpl config) throws CannotExistWithoutTypeException {
User user2 = getUser();
if ( user2 != null && evt.isModified( user2))
{
Set<User> changed = RaplaType.retainObjects(evt.getChanged(), Collections.singleton(user2));
if ( changed.size() > 0)
{
User newUser = changed.iterator().next();
user = newUser;
}
}
for ( RaplaObject obj:evt.getChanged())
{
if ( obj.getRaplaType() == DynamicType.TYPE)
{
DynamicType type = (DynamicType) obj;
if ( config.needsChange(type))
{
config.commitChange( type);
}
}
}
for ( RaplaObject obj:evt.getRemoved())
{
if ( obj.getRaplaType() == DynamicType.TYPE)
{
DynamicType type = (DynamicType) obj;
config.commitRemove( type);
}
}
}
private CalendarModelConfigurationImpl createConfiguration(ClassificationFilter[] allocatableFilter, ClassificationFilter[] eventFilter) throws RaplaException {
String viewName = selectedView;
Set<Entity> selected = new HashSet<Entity>( );
Collection<RaplaObject> selectedObjects = getSelectedObjects();
for (RaplaObject object:selectedObjects) {
if ( !(object instanceof Conflict) && (object instanceof Entity))
{
// throw new RaplaException("Storing the conflict view is not possible with Rapla.");
selected.add( (Entity) object );
}
}
final Date selectedDate = getSelectedDate();
final Date startDate = getStartDate();
final Date endDate = getEndDate();
boolean resourceRootSelected = selectedObjects.contains( ALLOCATABLES_ROOT);
return newRaplaCalendarModel( selected,resourceRootSelected, allocatableFilter,eventFilter, title, startDate, endDate, selectedDate, viewName, optionMap);
}
public CalendarModelConfigurationImpl newRaplaCalendarModel(Collection<Entity> selected,
boolean resourceRootSelected,
ClassificationFilter[] allocatableFilter,
ClassificationFilter[] eventFilter, String title, Date startDate,
Date endDate, Date selectedDate, String view, Map<String,String> optionMap) throws RaplaException
{
boolean defaultResourceTypes;
boolean defaultEventTypes;
int eventTypes = 0;
int resourceTypes = 0;
defaultResourceTypes = true;
defaultEventTypes = true;
List<ClassificationFilter> filter = new ArrayList<ClassificationFilter>();
if (allocatableFilter != null) {
for (ClassificationFilter entry : allocatableFilter) {
ClassificationFilter clone = entry.clone();
filter.add(clone);
resourceTypes++;
if (entry.ruleSize() > 0) {
defaultResourceTypes = false;
}
}
}
if (eventFilter != null) {
for (ClassificationFilter entry : eventFilter) {
ClassificationFilter clone = entry.clone();
filter.add(clone);
eventTypes++;
if (entry.ruleSize() > 0) {
defaultEventTypes = false;
}
}
}
DynamicType[] allEventTypes;
allEventTypes = m_facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
if (allEventTypes.length > eventTypes && eventFilter != null) {
defaultEventTypes = false;
}
final DynamicType[] allTypes = m_facade.getDynamicTypes(null);
final int allResourceTypes = allTypes.length - allEventTypes.length;
if (allResourceTypes > resourceTypes && allocatableFilter != null) {
defaultResourceTypes = false;
}
final ClassificationFilter[] filterArray = filter.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY);
List<String> selectedIds = new ArrayList<String>();
Collection<RaplaType> idTypeList = new ArrayList<RaplaType>();
for (Entity obj:selected)
{
selectedIds.add( obj.getId());
idTypeList.add( obj.getRaplaType());
}
CalendarModelConfigurationImpl calendarModelConfigurationImpl = new CalendarModelConfigurationImpl(selectedIds, idTypeList,resourceRootSelected,filterArray, defaultResourceTypes, defaultEventTypes, title, startDate, endDate, selectedDate, view, optionMap);
calendarModelConfigurationImpl.setResolver( m_facade.getOperator());
return calendarModelConfigurationImpl;
}
public void setReservationFilter(ClassificationFilter[] array) {
reservationFilter.clear();
if ( array == null)
{
defaultEventTypes = true;
return;
}
try {
defaultEventTypes = createConfiguration(null,array).isDefaultEventTypes();
} catch (RaplaException e) {
// DO Not set the types
}
for (ClassificationFilter entry: array)
{
final DynamicType type = entry.getType();
reservationFilter.put( type, entry);
}
}
public void setAllocatableFilter(ClassificationFilter[] array) {
allocatableFilter.clear();
if ( array == null)
{
defaultResourceTypes = true;
return;
}
try {
defaultResourceTypes = createConfiguration(array,null).isDefaultResourceTypes();
} catch (RaplaException e) {
// DO Not set the types
}
for (ClassificationFilter entry: array)
{
final DynamicType type = entry.getType();
allocatableFilter.put( type, entry);
}
}
@Override
public Date getSelectedDate() {
return selectedDate;
}
@Override
public void setSelectedDate(Date date) {
if ( date == null)
throw new IllegalStateException("Date can't be null");
this.selectedDate = date;
}
@Override
public Date getStartDate() {
return startDate;
}
@Override
public void setStartDate(Date date) {
if ( date == null)
throw new IllegalStateException("Date can't be null");
this.startDate = date;
}
@Override
public Date getEndDate() {
return endDate;
}
@Override
public void setEndDate(Date date) {
if ( date == null)
throw new IllegalStateException("Date can't be null");
this.endDate = date;
}
@Override
public String getTitle()
{
return title;
}
@Override
public void setTitle(String title) {
this.title = title;
}
@Override
public void setViewId(String view) {
this.selectedView = view;
}
@Override
public String getViewId() {
return this.selectedView;
}
class CalendarModelParseContext implements ParseContext
{
public Function resolveVariableFunction(String variableName) throws IllegalAnnotationException {
if ( variableName.equals("allocatables"))
{
List<Function> emptyList = Collections.emptyList();
return new Function(variableName, emptyList)
{
@Override
public Object eval(EvalContext context) {
try {
return Arrays.asList(getSelectedAllocatables());
} catch (RaplaException e) {
return Collections.emptyList();
}
}
};
}
else if ( variableName.equals("timeIntervall"))
{
List<Function> emptyList = Collections.emptyList();
return new Function(variableName, emptyList)
{
@Override
public Object eval(EvalContext context) {
return getTimeIntervall();
}
};
}
else if ( variableName.equals("selectedDate"))
{
List<Function> emptyList = Collections.emptyList();
return new Function(variableName, emptyList)
{
@Override
public Object eval(EvalContext context) {
return getSelectedDate();
}
};
}
return null;
}
}
public TimeInterval getTimeIntervall()
{
return new TimeInterval(getStartDate(), getEndDate());
}
@Override
public String getNonEmptyTitle() {
String title = getTitle();
if (title != null && title.trim().length()>0)
{
ParseContext parseContext = new CalendarModelParseContext();
ParsedText parsedTitle;
try {
parsedTitle = new ParsedText( title);
parsedTitle.init(parseContext);
} catch (IllegalAnnotationException e) {
return e.getMessage();
}
Locale locale = raplaLocale.getLocale();
EvalContext evalContext = new EvalContext( locale);
String result = parsedTitle.formatName( evalContext);
return result;
}
String types = "";
/*
String dateString = getRaplaLocale().formatDate(getSelectedDate());
if ( isListingAllocatables()) {
try {
Collection list = getSelectedObjectsAndChildren();
if (list.size() == 1) {
Object obj = list.iterator().next();
if (!( obj instanceof DynamicType))
{
types = getI18n().format("allocation_view",getName( obj ),dateString);
}
}
} catch (RaplaException ex) {
}
if ( types == null )
types = getI18n().format("allocation_view", getI18n().getString("resources_persons"));
} else if ( isListingReservations()) {
types = getI18n().getString("reservations");
} else {
types = "unknown";
}
*/
return types;
}
public String getName(Object object) {
if (object == null)
return "";
if (object instanceof Named) {
String name = ((Named) object).getName(getI18n().getLocale());
return (name != null) ? name : "";
}
return object.toString();
}
private Collection<Allocatable> getFilteredAllocatables() throws RaplaException {
List<Allocatable> list = new ArrayList<Allocatable>();
for ( Allocatable allocatable :m_facade.getAllocatables())
{
if ( isInFilter( allocatable) && (user == null || allocatable.canRead(user))) {
list.add( allocatable);
}
}
return list;
}
private boolean isInFilter( Allocatable classifiable) {
if (isTemplateModus())
{
return true;
}
final Classification classification = classifiable.getClassification();
final DynamicType type = classification.getType();
final ClassificationFilter classificationFilter = allocatableFilter.get( type);
if ( classificationFilter != null)
{
final boolean matches = classificationFilter.matches(classification);
return matches;
}
else
{
return defaultResourceTypes;
}
}
@Override
public Collection<RaplaObject> getSelectedObjectsAndChildren() throws RaplaException
{
Assert.notNull(selectedObjects);
ArrayList<DynamicType> dynamicTypes = new ArrayList<DynamicType>();
for (Iterator<RaplaObject> it = selectedObjects.iterator();it.hasNext();)
{
Object obj = it.next();
if (obj instanceof DynamicType) {
dynamicTypes.add ((DynamicType)obj);
}
}
HashSet<RaplaObject> result = new HashSet<RaplaObject>();
result.addAll( selectedObjects );
boolean allAllocatablesSelected = selectedObjects.contains( CalendarModelImpl.ALLOCATABLES_ROOT);
Collection<Allocatable> filteredList = getFilteredAllocatables();
for (Iterator<Allocatable> it = filteredList.iterator();it.hasNext();)
{
Allocatable oneSelectedItem = it.next();
if ( selectedObjects.contains(oneSelectedItem)) {
continue;
}
Classification classification = oneSelectedItem.getClassification();
if ( classification == null)
{
continue;
}
if ( allAllocatablesSelected || dynamicTypes.contains(classification.getType()))
{
result.add( oneSelectedItem );
continue;
}
}
return result;
}
@Override
public void setSelectedObjects(Collection<? extends Object> selectedObjects) {
this.selectedObjects = retainRaplaObjects(selectedObjects);
if (markedAllocatables != null && !markedAllocatables.isEmpty())
{
markedAllocatables = new LinkedHashSet<Allocatable>(markedAllocatables);
try {
markedAllocatables.retainAll( Arrays.asList(getSelectedAllocatables()));
} catch (RaplaException e) {
markedAllocatables = Collections.emptyList();
}
}
}
private List<RaplaObject> retainRaplaObjects(Collection<? extends Object> list ){
List<RaplaObject> result = new ArrayList<RaplaObject>();
for ( Iterator<? extends Object> it = list.iterator();it.hasNext();) {
Object obj = it.next();
if ( obj instanceof RaplaObject) {
result.add( (RaplaObject)obj );
}
}
return result;
}
@Override
public Collection<RaplaObject> getSelectedObjects()
{
return selectedObjects;
}
@Override
public ClassificationFilter[] getReservationFilter() throws RaplaException
{
Collection<ClassificationFilter> filter ;
if ( isDefaultEventTypes() || isTemplateModus())
{
filter = new ArrayList<ClassificationFilter>();
for (DynamicType type :m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION))
{
filter.add( type.newClassificationFilter());
}
}
else
{
filter = reservationFilter.values();
}
return filter.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY);
}
protected boolean isTemplateModus() {
return m_facade.getTemplateName() != null;
}
@Override
public ClassificationFilter[] getAllocatableFilter() throws RaplaException {
Collection<ClassificationFilter> filter ;
if ( isDefaultResourceTypes() || isTemplateModus())
{
filter = new ArrayList<ClassificationFilter>();
for (DynamicType type :m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE))
{
filter.add( type.newClassificationFilter());
}
for (DynamicType type :m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON))
{
filter.add( type.newClassificationFilter());
}
}
else
{
filter = allocatableFilter.values();
}
return filter.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY);
}
public CalendarSelectionModel clone() {
CalendarModelImpl clone;
try
{
clone = new CalendarModelImpl(context, user, m_facade);
CalendarModelConfiguration config = createConfiguration();
Map<String, String> alternativOptions = null;
clone.setConfiguration( config, alternativOptions);
}
catch ( RaplaException e )
{
throw new IllegalStateException( e.getMessage() );
}
return clone;
}
@Override
public Reservation[] getReservations() throws RaplaException {
return getReservations( getStartDate(), getEndDate() );
}
@Override
public Reservation[] getReservations(Date startDate, Date endDate) throws RaplaException
{
return getReservationsAsList( startDate, endDate ).toArray( Reservation.RESERVATION_ARRAY);
}
private List<Reservation> getReservationsAsList(Date start, Date end) throws RaplaException
{
Allocatable[] allocatables = getSelectedAllocatables();
if ( isNoAllocatableSelected())
{
allocatables = null;
}
Collection<Conflict> conflicts = getSelectedConflicts();
if ( conflicts.size() > 0)
{
return m_facade.getReservations(conflicts);
}
Reservation[] reservationArray =m_facade.getReservations(allocatables, start, end);
List<Reservation> asList = Arrays.asList( reservationArray );
return restrictReservations(asList);
}
public List<Reservation> restrictReservations(Collection<Reservation> reservationsToRestrict) throws RaplaException {
List<Reservation> reservations = new ArrayList<Reservation>(reservationsToRestrict);
// Don't restrict templates
if ( isTemplateModus())
{
return reservations;
}
ClassificationFilter[] reservationFilter = getReservationFilter();
if ( isDefaultEventTypes())
{
reservationFilter = null;
}
Set<User> users = getUserRestrictions();
for ( Iterator<Reservation> it = reservations.iterator();it.hasNext();)
{
Reservation event = it.next();
if ( !users.isEmpty() && !users.contains( event.getOwner() )) {
it.remove();
}
else if (reservationFilter != null && !ClassificationFilter.Util.matches( reservationFilter,event))
{
it.remove();
}
}
return reservations;
}
private Set<User> getUserRestrictions() {
User currentUser = getUser();
if ( currentUser != null && isOnlyCurrentUserSelected() || !m_facade.canReadReservationsFromOthers( currentUser))
{
return Collections.singleton( currentUser );
}
else if ( currentUser != null && currentUser.isAdmin())
{
return getSelected(User.TYPE);
}
else
{
return Collections.emptySet();
}
}
private boolean isNoAllocatableSelected()
{
for (RaplaObject obj :getSelectedObjects())
{
RaplaType raplaType = obj.getRaplaType();
if ( raplaType == Allocatable.TYPE)
{
return false;
}
else if (raplaType == DynamicType.TYPE)
{
DynamicType type = (DynamicType) obj;
String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
if ( annotation.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON ) || annotation.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE))
{
return false;
}
}
else if ( obj.equals(ALLOCATABLES_ROOT) )
{
return false;
}
}
return true;
}
@Override
public Allocatable[] getSelectedAllocatables() throws RaplaException {
Collection<Allocatable> result = getSelectedAllocatablesAsList();
return result.toArray(Allocatable.ALLOCATABLE_ARRAY);
}
protected Collection<Allocatable> getSelectedAllocatablesAsList()
throws RaplaException {
Collection<Allocatable> result = new HashSet<Allocatable>();
for(RaplaObject object:getSelectedObjectsAndChildren()) {
if ( object.getRaplaType() == Conflict.TYPE ) {
result.add( ((Conflict)object).getAllocatable() );
}
}
// We ignore the allocatable selection if there are conflicts selected
if ( result.isEmpty())
{
for(RaplaObject object:getSelectedObjectsAndChildren()) {
if ( object.getRaplaType() ==Allocatable.TYPE ) {
result.add( (Allocatable)object );
}
}
}
Collection<Allocatable> filteredAllocatables = getFilteredAllocatables();
result.retainAll( filteredAllocatables);
return result;
}
public Collection<Conflict> getSelectedConflicts() {
return getSelected(Conflict.TYPE);
}
public Set<DynamicType> getSelectedTypes(String classificationType) throws RaplaException {
Set<DynamicType> result = new HashSet<DynamicType>();
Iterator<RaplaObject> it = getSelectedObjectsAndChildren().iterator();
while (it.hasNext()) {
RaplaObject object = it.next();
if ( object.getRaplaType() == DynamicType.TYPE ) {
if (classificationType == null || (( DynamicType) object).getAnnotation( DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE).equals( classificationType))
{
result.add((DynamicType) object );
}
}
}
return result;
}
private <T extends RaplaObject<T>> Set<T> getSelected(RaplaType<T> type) {
Set<T> result = new HashSet<T>();
Iterator<RaplaObject> it = getSelectedObjects().iterator();
while (it.hasNext()) {
RaplaObject object = it.next();
if ( object.getRaplaType() == type ) {
@SuppressWarnings("unchecked")
T casted = (T)object;
result.add( casted );
}
}
return result;
}
protected I18nBundle getI18n() {
return i18n;
}
protected RaplaLocale getRaplaLocale() {
return raplaLocale;
}
@Override
public boolean isOnlyCurrentUserSelected() {
String option = getOption(CalendarModel.ONLY_MY_EVENTS );
if ( option != null && option.equalsIgnoreCase("TRUE"))
{
return true;
}
return false;
}
@Override
public void selectUser(User user) {
List<RaplaObject> selectedObjects = new ArrayList<RaplaObject>(getSelectedObjects());
for (Iterator<RaplaObject> it = selectedObjects.iterator();it.hasNext();) {
RaplaObject obj = it.next();
if (obj.getRaplaType() == User.TYPE ) {
it.remove();
}
}
if ( user != null)
{
selectedObjects.add( user );
}
setSelectedObjects(selectedObjects);
}
@Override
public String getOption( String name )
{
return optionMap.get( name );
}
@Override
public void setOption( String name, String string )
{
if ( string == null)
{
optionMap.remove( name);
}
else
{
optionMap.put( name, string);
}
}
@Override
public boolean isDefaultEventTypes()
{
return defaultEventTypes;
}
@Override
public boolean isDefaultResourceTypes()
{
return defaultResourceTypes;
}
@Override
public void save(final String filename) throws RaplaException,
EntityNotFoundException {
Preferences clone = createStorablePreferences(filename);
m_facade.store(clone);
}
public Preferences createStorablePreferences(final String filename) throws RaplaException, EntityNotFoundException {
final CalendarModelConfiguration conf = createConfiguration();
Preferences clone = m_facade.edit(m_facade.getPreferences(user));
if ( filename == null)
{
clone.putEntry( CalendarModelConfiguration.CONFIG_ENTRY, conf);
}
else
{
Map<String,CalendarModelConfiguration> exportMap= clone.getEntry(EXPORT_ENTRY);
Map<String,CalendarModelConfiguration> newMap;
if ( exportMap == null)
newMap = new TreeMap<String,CalendarModelConfiguration>();
else
newMap = new TreeMap<String,CalendarModelConfiguration>( exportMap);
newMap.put(filename, conf);
clone.putEntry( EXPORT_ENTRY, m_facade.newRaplaMap( newMap ));
}
return clone;
}
// Old defaultname behaviour. Duplication of language resource names. But the system has to be replaced anyway in the future, because it doesnt allow for multiple language outputs on the server.
private boolean isOldDefaultNameBehavoir(final String filename)
{
List<String> translations = new ArrayList<String>();
translations.add( getI18n().getString("default") );
translations.add( "default" );
translations.add( "Default" );
translations.add( "Standard" );
translations.add( "Standaard");
// special for polnish
if (filename.startsWith( "Domy") && filename.endsWith("lne"))
{
return true;
}
if (filename.startsWith( "Est") && filename.endsWith("ndar"))
{
return true;
}
return translations.contains(filename);
}
@Override
public void load(final String filename) throws RaplaException, EntityNotFoundException, CalendarNotFoundExeption {
final CalendarModelConfiguration modelConfig;
boolean createIfNotNull =false;
{
final Preferences preferences = m_facade.getPreferences(user, createIfNotNull);
modelConfig = getModelConfig(filename, preferences);
}
if ( modelConfig == null && filename != null )
{
throw new CalendarNotFoundExeption("Calendar with name " + filename + " not found.");
}
else
{
final boolean isDefault = filename == null ;
Map<String,String> alternativeOptions = new HashMap<String,String>();
if (modelConfig != null && modelConfig.getOptionMap() != null)
{
// All old default calendars have no selected date
if (isDefault && (modelConfig.getOptionMap().get( CalendarModel.SAVE_SELECTED_DATE) == null))
{
alternativeOptions.put(CalendarModel.SAVE_SELECTED_DATE , "false");
}
// All old calendars are exported
if ( !isDefault && modelConfig.getOptionMap().get(HTML_EXPORT_ENABLED) == null)
{
alternativeOptions.put(HTML_EXPORT_ENABLED,"true");
}
}
setConfiguration(modelConfig, alternativeOptions);
}
}
public CalendarModelConfiguration getModelConfig(final String filename,final Preferences preferences) {
final CalendarModelConfiguration modelConfig;
if (preferences != null)
{
final boolean isDefault = filename == null ;
if ( isDefault )
{
modelConfig = preferences.getEntry(CalendarModelConfiguration.CONFIG_ENTRY);
}
else if ( filename != null && !isDefault)
{
Map<String,CalendarModelConfiguration> exportMap= preferences.getEntry(EXPORT_ENTRY);
final CalendarModelConfiguration config;
if ( exportMap != null)
{
config = exportMap.get(filename);
}
else
{
config = null;
}
if ( config == null && isOldDefaultNameBehavoir(filename) )
{
modelConfig = preferences.getEntry(CalendarModelConfiguration.CONFIG_ENTRY);
}
else
{
modelConfig = config;
}
}
else
{
modelConfig = null;
}
}
else
{
modelConfig = null;
}
return modelConfig;
}
//Set<Appointment> conflictList = new HashSet<Appointment>();
// if ( selectedConflicts != null)
// {
// for (Conflict conflict: selectedConflicts)
// {
// if ( conflict.getAppointment1().equals( app.getId()))
// {
// conflictList.add(conflict.getAppointment2());
// }
// else if ( conflict.getAppointment2().equals( app.getId()))
// {
// conflictList.add(conflict.getAppointment1());
// }
// }
// }
@Override
public List<AppointmentBlock> getBlocks() throws RaplaException
{
List<AppointmentBlock> appointments = new ArrayList<AppointmentBlock>();
Set<Allocatable> selectedAllocatables = new HashSet<Allocatable>(Arrays.asList(getSelectedAllocatables()));
if ( isNoAllocatableSelected())
{
selectedAllocatables = null;
}
Collection<Conflict> selectedConflicts = getSelectedConflicts();
List<Reservation> reservations = m_facade.getReservations( selectedConflicts);
Map<Appointment,Set<Appointment>> conflictingAppointments = ConflictImpl.getMap(selectedConflicts,reservations);
for ( Reservation event:getReservations())
{
for (Appointment app: event.getAppointments())
{
//
Allocatable[] allocatablesFor = event.getAllocatablesFor(app);
if ( selectedAllocatables == null || containsOne(selectedAllocatables, allocatablesFor))
{
Collection<Appointment> conflictList = conflictingAppointments.get( app );
if ( conflictList == null || conflictList.isEmpty())
{
app.createBlocks(getStartDate(), getEndDate(), appointments);
}
else
{
List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
app.createBlocks(getStartDate(), getEndDate(), blocks);
Iterator<AppointmentBlock> it = blocks.iterator();
while ( it.hasNext())
{
AppointmentBlock block = it.next();
boolean found = false;
for ( Appointment conflictingApp:conflictList)
{
if (conflictingApp.overlaps( block ))
{
found = true;
break;
}
}
if ( !found)
{
it.remove();
}
}
appointments.addAll( blocks);
}
}
}
}
Collections.sort(appointments, new AppointmentBlockStartComparator());
return appointments;
}
private boolean containsOne(Set<Allocatable> allocatableSet,
Allocatable[] listOfAllocatablesToMatch) {
for ( Allocatable alloc: listOfAllocatablesToMatch)
{
if (allocatableSet.contains(alloc))
{
return true;
}
}
return false;
}
@Override
public DynamicType guessNewEventType() throws RaplaException {
Set<DynamicType> selectedTypes = getSelectedTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
DynamicType guessedType;
if (selectedTypes.size()>0)
{
guessedType = selectedTypes.iterator().next();
}
else
{
guessedType = m_facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)[0];
}
ClassificationFilter[] reservationFilter = getReservationFilter();
DynamicType firstType = null;
boolean found = false;
// assure that the guessed type is in the filter selection list
for (ClassificationFilter filter : reservationFilter)
{
DynamicType type = filter.getType();
if ( firstType == null)
{
firstType = type;
}
if ( type.equals( guessedType))
{
found = true;
break;
}
}
if (!found && firstType != null)
{
guessedType = firstType;
}
return guessedType;
}
@Override
public Collection<TimeInterval> getMarkedIntervals()
{
return timeIntervals;
}
@Override
public void setMarkedIntervals(Collection<TimeInterval> timeIntervals)
{
if ( timeIntervals != null)
{
this.timeIntervals = Collections.unmodifiableCollection(timeIntervals);
}
else
{
this.timeIntervals = Collections.emptyList();
}
}
@Override
public void markInterval(Date start, Date end) {
TimeInterval timeInterval = new TimeInterval( start, end);
setMarkedIntervals( Collections.singletonList( timeInterval));
}
@Override
public Collection<Allocatable> getMarkedAllocatables() {
return markedAllocatables;
}
@Override
public void setMarkedAllocatables(Collection<Allocatable> allocatables) {
this.markedAllocatables = allocatables;
}
public Collection<Appointment> getAppointments(TimeInterval interval) throws RaplaException
{
Date startDate = interval.getStart();
Date endDate = interval.getEnd();
List<Reservation> reservations = getReservationsAsList(startDate, endDate);
Collection<Allocatable> allocatables =getSelectedAllocatablesAsList();
List<Appointment> result = RaplaBuilder.getAppointments(reservations, allocatables);
return result;
}
}
| 04900db4-rob | src/org/rapla/facade/internal/CalendarModelImpl.java | Java | gpl3 | 46,126 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import org.rapla.ConnectInfo;
import org.rapla.components.util.Command;
import org.rapla.components.util.CommandScheduler;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.MultiLanguageName;
import org.rapla.entities.Ownable;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.entities.configuration.internal.RaplaMapImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.domain.RepeatingType;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.RaplaObjectAnnotations;
import org.rapla.entities.domain.ResourceAnnotations;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.domain.internal.AppointmentImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.entities.dynamictype.internal.DynamicTypeImpl;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.entities.internal.ModifiableTimestamp;
import org.rapla.entities.internal.UserImpl;
import org.rapla.entities.storage.ParentEntity;
import org.rapla.entities.storage.internal.SimpleEntity;
import org.rapla.facade.AllocationChangeEvent;
import org.rapla.facade.AllocationChangeListener;
import org.rapla.facade.CalendarOptions;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.Conflict;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.facade.PeriodModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.facade.UpdateErrorListener;
import org.rapla.framework.Configuration;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.internal.ContextTools;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.RaplaSecurityException;
import org.rapla.storage.StorageOperator;
import org.rapla.storage.StorageUpdateListener;
import org.rapla.storage.UpdateResult;
/**
* This is the default implementation of the necessary Client-Facade to the
* DB-Subsystem.
* <p>
* Sample configuration 1:
*
* <pre>
* <facade id="facade">
* <store>file</store>
* </facade>
* </pre>
*
* </p>
* <p>
* The store entry contains the id of a storage-component. Storage-Components
* are all components that implement the {@link StorageOperator} interface.
* </p>
*/
public class FacadeImpl implements ClientFacade,StorageUpdateListener {
protected CommandScheduler notifyQueue;
private String workingUserId = null;
private StorageOperator operator;
private Vector<ModificationListener> modificatonListenerList = new Vector<ModificationListener>();
private Vector<AllocationChangeListener> allocationListenerList = new Vector<AllocationChangeListener>();
private Vector<UpdateErrorListener> errorListenerList = new Vector<UpdateErrorListener>();
private I18nBundle i18n;
private PeriodModelImpl periodModel;
// private ConflictFinder conflictFinder;
private Vector<ModificationListener> directListenerList = new Vector<ModificationListener>();
public CommandHistory commandHistory = new CommandHistory();
Locale locale;
RaplaContext context;
Logger logger;
String templateName;
public FacadeImpl(RaplaContext context, Configuration config, Logger logger) throws RaplaException {
this( context, getOperator(context, config, logger), logger);
}
private static StorageOperator getOperator(RaplaContext context, Configuration config, Logger logger)
throws RaplaContextException {
String configEntry = config.getChild("store").getValue("*");
String storeSelector = ContextTools.resolveContext(configEntry, context ).toString();
logger.info("Using rapladatasource " +storeSelector);
try {
Container container = context.lookup(Container.class);
StorageOperator operator = container.lookup(StorageOperator.class, storeSelector);
return operator;
}
catch (RaplaContextException ex) {
throw new RaplaContextException("Store "
+ storeSelector
+ " is not found (or could not be initialized)", ex);
}
}
public static FacadeImpl create(RaplaContext context, StorageOperator operator, Logger logger) throws RaplaException
{
return new FacadeImpl(context, operator, logger);
}
private FacadeImpl(RaplaContext context, StorageOperator operator, Logger logger) throws RaplaException {
this.operator = operator;
this.logger = logger;
i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
locale = context.lookup(RaplaLocale.class).getLocale();
this.context = context;
operator.addStorageUpdateListener(this);
notifyQueue = context.lookup( CommandScheduler.class );
//org.rapla.components.util.CommandQueue.createCommandQueue();
}
public Logger getLogger()
{
return logger;
}
public StorageOperator getOperator() {
return operator;
}
// Implementation of StorageUpdateListener.
/**
* This method is called by the storage-operator, when stored objects have
* changed.
*
* <strong>Caution:</strong> You must not lock the storage operator during
* processing of this call, because it could have been locked by the store
* method, causing deadlocks
*/
public void objectsUpdated(UpdateResult evt) {
if (getLogger().isDebugEnabled())
getLogger().debug("Objects updated");
cacheValidString = null;
cachedReservations = null;
if (workingUserId != null)
{
if ( evt.isModified( User.TYPE))
{
if (operator.tryResolve( workingUserId, User.class) == null)
{
EntityNotFoundException ex = new EntityNotFoundException("User for id " + workingUserId + " not found. Maybe it was removed.");
fireUpdateError(ex);
}
}
}
fireUpdateEvent(evt);
}
public void updateError(RaplaException ex) {
getLogger().error(ex.getMessage(), ex);
fireUpdateError(ex);
}
public void storageDisconnected(String message) {
fireStorageDisconnected(message);
}
/******************************
* Update-module *
******************************/
public boolean isClientForServer() {
return operator.supportsActiveMonitoring();
}
public void refresh() throws RaplaException {
if (operator.supportsActiveMonitoring()) {
operator.refresh();
}
}
void setName(MultiLanguageName name, String to)
{
String currentLang = i18n.getLang();
name.setName("en", to);
try
{
// try to find a translation in the current locale
String translation = i18n.getString( to);
name.setName(currentLang, translation);
}
catch (Exception ex)
{
// go on, if non is found
}
}
public void addModificationListener(ModificationListener listener) {
modificatonListenerList.add(listener);
}
public void addDirectModificationListener(ModificationListener listener)
{
directListenerList.add(listener);
}
public void removeModificationListener(ModificationListener listener) {
directListenerList.remove(listener);
modificatonListenerList.remove(listener);
}
private Collection<ModificationListener> getModificationListeners() {
if (modificatonListenerList.size() == 0)
{
return Collections.emptyList();
}
synchronized (this) {
Collection<ModificationListener> list = new ArrayList<ModificationListener>(3);
if (periodModel != null) {
list.add(periodModel);
}
Iterator<ModificationListener> it = modificatonListenerList.iterator();
while (it.hasNext()) {
ModificationListener listener = it.next();
list.add(listener);
}
return list;
}
}
public void addAllocationChangedListener(AllocationChangeListener listener) {
if ( operator.supportsActiveMonitoring())
{
throw new IllegalStateException("You can't add an allocation listener to a client facade because reservation objects are not updated");
}
allocationListenerList.add(listener);
}
public void removeAllocationChangedListener(AllocationChangeListener listener) {
allocationListenerList.remove(listener);
}
private Collection<AllocationChangeListener> getAllocationChangeListeners() {
if (allocationListenerList.size() == 0)
{
return Collections.emptyList();
}
synchronized (this) {
Collection<AllocationChangeListener> list = new ArrayList<AllocationChangeListener>( 3);
Iterator<AllocationChangeListener> it = allocationListenerList.iterator();
while (it.hasNext()) {
AllocationChangeListener listener = it.next();
list.add(listener);
}
return list;
}
}
public AllocationChangeEvent[] createAllocationChangeEvents(UpdateResult evt) {
Logger logger = getLogger().getChildLogger("trigger.allocation");
List<AllocationChangeEvent> triggerEvents = AllocationChangeFinder.getTriggerEvents(evt, logger);
return triggerEvents.toArray( new AllocationChangeEvent[0]);
}
public void addUpdateErrorListener(UpdateErrorListener listener) {
errorListenerList.add(listener);
}
public void removeUpdateErrorListener(UpdateErrorListener listener) {
errorListenerList.remove(listener);
}
public UpdateErrorListener[] getUpdateErrorListeners() {
return errorListenerList.toArray(new UpdateErrorListener[] {});
}
protected void fireUpdateError(RaplaException ex) {
UpdateErrorListener[] listeners = getUpdateErrorListeners();
for (int i = 0; i < listeners.length; i++) {
listeners[i].updateError(ex);
}
}
protected void fireStorageDisconnected(String message) {
UpdateErrorListener[] listeners = getUpdateErrorListeners();
for (int i = 0; i < listeners.length; i++) {
listeners[i].disconnected(message);
}
}
final class UpdateCommandAllocation implements Runnable, Command {
Collection<AllocationChangeListener> listenerList;
AllocationChangeEvent[] allocationChangeEvents;
public UpdateCommandAllocation(Collection<AllocationChangeListener> allocationChangeListeners, UpdateResult evt) {
this.listenerList= new ArrayList<AllocationChangeListener>(allocationChangeListeners);
if ( allocationChangeListeners.size() > 0)
{
allocationChangeEvents = createAllocationChangeEvents(evt);
}
}
public void execute() {
run();
}
public void run() {
for (AllocationChangeListener listener: listenerList)
{
try {
if (isAborting())
return;
if (getLogger().isDebugEnabled())
getLogger().debug("Notifying " + listener);
if (allocationChangeEvents.length > 0) {
listener.changed(allocationChangeEvents);
}
} catch (Exception ex) {
getLogger().error("update-exception", ex);
}
}
}
}
final class UpdateCommandModification implements Runnable, Command {
Collection<ModificationListener> listenerList;
ModificationEvent modificationEvent;
public UpdateCommandModification(Collection<ModificationListener> modificationListeners, UpdateResult evt) {
this.listenerList = new ArrayList<ModificationListener>(modificationListeners);
this.modificationEvent = evt;
}
public void execute() {
run();
}
public void run() {
for (ModificationListener listener: listenerList) {
try {
if (isAborting())
return;
if (getLogger().isDebugEnabled())
getLogger().debug("Notifying " + listener);
listener.dataChanged(modificationEvent);
} catch (Exception ex) {
getLogger().error("update-exception", ex);
}
}
}
} /**
* fires update event asynchronous.
*/
protected void fireUpdateEvent(UpdateResult evt) {
if (periodModel != null) {
try {
periodModel.update();
} catch (RaplaException e) {
getLogger().error("Can't update Period Model", e);
}
}
{
Collection<ModificationListener> modificationListeners = directListenerList;
if (modificationListeners.size() > 0 ) {
new UpdateCommandModification(modificationListeners,evt).execute();
}
}
{
Collection<ModificationListener> modificationListeners = getModificationListeners();
if (modificationListeners.size() > 0 ) {
notifyQueue.schedule(new UpdateCommandModification(modificationListeners, evt),0);
}
Collection<AllocationChangeListener> allocationChangeListeners = getAllocationChangeListeners();
if (allocationChangeListeners.size() > 0) {
notifyQueue.schedule(new UpdateCommandAllocation(allocationChangeListeners, evt),0);
}
}
}
/******************************
* Query-module *
******************************/
private Collection<Allocatable> getVisibleAllocatables( ClassificationFilter[] filters) throws RaplaException {
User workingUser = getWorkingUser();
Collection<Allocatable> objects = operator.getAllocatables(filters);
Iterator<Allocatable> it = objects.iterator();
while (it.hasNext()) {
Allocatable allocatable = it.next();
if (workingUser == null || workingUser.isAdmin())
continue;
if (!allocatable.canRead(workingUser))
it.remove();
}
return objects;
}
int queryCounter = 0;
private Collection<Reservation> getVisibleReservations(User user, Allocatable[] allocatables, Date start, Date end, ClassificationFilter[] reservationFilters)
throws RaplaException {
if ( templateName != null)
{
Collection<Reservation> reservations = getTemplateReservations( templateName);
return reservations;
}
List<Allocatable> allocList;
if (allocatables != null)
{
if ( allocatables.length == 0 )
{
return Collections.emptyList();
}
allocList = Arrays.asList( allocatables);
}
else
{
allocList = Collections.emptyList();
}
Collection<Reservation> reservations =operator.getReservations(user,allocList, start, end, reservationFilters,null);
// Category can_see = getUserGroupsCategory().getCategory(
// Permission.GROUP_CAN_READ_EVENTS_FROM_OTHERS);
if (getLogger().isDebugEnabled())
{
getLogger().debug((++queryCounter)+". Query reservation called user=" + user + " start=" +start + " end=" + end);
}
return reservations;
}
public Allocatable[] getAllocatables() throws RaplaException {
return getAllocatables(null);
}
public Allocatable[] getAllocatables(ClassificationFilter[] filters) throws RaplaException {
return getVisibleAllocatables(filters).toArray( Allocatable.ALLOCATABLE_ARRAY);
}
public boolean canExchangeAllocatables(Reservation reservation) {
try {
Allocatable[] all = getAllocatables(null);
User user = getUser();
for (int i = 0; i < all.length; i++) {
if (all[i].canModify(user)) {
return true;
}
}
} catch (RaplaException ex) {
}
return false;
}
public Preferences getPreferences() throws RaplaException {
return getPreferences(getUser());
}
public Preferences getSystemPreferences() throws RaplaException
{
return operator.getPreferences(null, true);
}
public Preferences getPreferences(User user) throws RaplaException {
return operator.getPreferences(user, true);
}
public Preferences getPreferences(User user,boolean createIfNotNull) throws RaplaException {
return operator.getPreferences(user, createIfNotNull);
}
public Category getSuperCategory() {
return operator.getSuperCategory();
}
public Category getUserGroupsCategory() throws RaplaException {
Category userGroups = getSuperCategory().getCategory(
Permission.GROUP_CATEGORY_KEY);
if (userGroups == null) {
throw new RaplaException("No category '"+ Permission.GROUP_CATEGORY_KEY + "' available");
}
return userGroups;
}
public Collection<String> getTemplateNames() throws RaplaException
{
return operator.getTemplateNames();
}
public Collection<Reservation> getTemplateReservations(String name) throws RaplaException
{
User user = null;
Collection<Allocatable> allocList = null;
Date start = null;
Date end = null;
Map<String,String> annotationQuery = new LinkedHashMap<String,String>();
annotationQuery.put(RaplaObjectAnnotations.KEY_TEMPLATE, name);
Collection<Reservation> result = operator.getReservations(user,allocList, start, end,null, annotationQuery);
return result;
}
public Reservation[] getReservations(User user, Date start, Date end,ClassificationFilter[] filters) throws RaplaException {
return getVisibleReservations(user, null,start, end, filters).toArray(Reservation.RESERVATION_ARRAY);
}
private String cacheValidString;
private Reservation[] cachedReservations;
public Reservation[] getReservations(Allocatable[] allocatables,Date start, Date end) throws RaplaException {
String cacheKey = createCacheKey( allocatables, start, end);
if ( cacheValidString != null && cacheValidString.equals( cacheKey) && cachedReservations != null)
{
return cachedReservations;
}
Reservation[] reservationsForAllocatable = getReservationsForAllocatable(allocatables, start, end, null);
cachedReservations = reservationsForAllocatable;
cacheValidString = cacheKey;
return reservationsForAllocatable;
}
private String createCacheKey(Allocatable[] allocatables, Date start,
Date end) {
StringBuilder buf = new StringBuilder();
if ( allocatables != null)
{
for ( Allocatable alloc:allocatables)
{
buf.append(alloc.getId());
buf.append(";");
}
}
else
{
buf.append("all_reservations;");
}
if ( start != null)
{
buf.append(start.getTime() + ";");
}
if ( end != null)
{
buf.append(end.getTime() + ";");
}
return buf.toString();
}
public List<Reservation> getReservations(Collection<Conflict> conflicts) throws RaplaException
{
Collection<String> ids = new ArrayList<String>();
for ( Conflict conflict:conflicts)
{
ids.add(conflict.getReservation1());
ids.add(conflict.getReservation2());
}
Collection<Entity> values = operator.getFromId( ids, true).values();
@SuppressWarnings("unchecked")
ArrayList<Reservation> converted = new ArrayList(values);
return converted;
}
public Reservation[] getReservationsForAllocatable(Allocatable[] allocatables, Date start, Date end,ClassificationFilter[] reservationFilters) throws RaplaException {
//System.gc();
Collection<Reservation> reservations = getVisibleReservations(null, allocatables,start, end, reservationFilters);
return reservations.toArray(Reservation.RESERVATION_ARRAY);
}
public Period[] getPeriods() throws RaplaException {
Period[] result = getPeriodModel().getAllPeriods();
return result;
}
public PeriodModel getPeriodModel() throws RaplaException {
if (periodModel == null) {
periodModel = new PeriodModelImpl(this);
}
return periodModel;
}
public DynamicType[] getDynamicTypes(String classificationType)
throws RaplaException {
ArrayList<DynamicType> result = new ArrayList<DynamicType>();
Collection<DynamicType> collection = operator.getDynamicTypes();
for (DynamicType type: collection) {
String classificationTypeAnno = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
// ignore internal types for backward compatibility
if ((( DynamicTypeImpl)type).isInternal())
{
continue;
}
if ( classificationType == null || classificationType.equals(classificationTypeAnno)) {
result.add(type);
}
}
return result.toArray(DynamicType.DYNAMICTYPE_ARRAY);
}
public DynamicType getDynamicType(String elementKey) throws RaplaException {
DynamicType dynamicType = operator.getDynamicType(elementKey);
if ( dynamicType == null)
{
throw new EntityNotFoundException("No dynamictype with elementKey "
+ elementKey);
}
return dynamicType;
}
public User[] getUsers() throws RaplaException {
User[] result = operator.getUsers().toArray(User.USER_ARRAY);
return result;
}
public User getUser(String username) throws RaplaException {
User user = operator.getUser(username);
if (user == null)
throw new EntityNotFoundException("No User with username " + username);
return user;
}
public Conflict[] getConflicts(Reservation reservation) throws RaplaException {
Date today = operator.today();
if ( RaplaComponent.isTemplate( reservation))
{
return Conflict.CONFLICT_ARRAY;
}
Collection<Allocatable> allocatables = Arrays.asList(reservation.getAllocatables());
Collection<Appointment> appointments = Arrays.asList(reservation.getAppointments());
Collection<Reservation> ignoreList = Collections.singleton( reservation );
Map<Allocatable, Map<Appointment, Collection<Appointment>>> allocatableBindings = operator.getAllAllocatableBindings( allocatables, appointments, ignoreList);
ArrayList<Conflict> conflictList = new ArrayList<Conflict>();
for ( Map.Entry<Allocatable, Map<Appointment, Collection<Appointment>>> entry: allocatableBindings.entrySet() )
{
Allocatable allocatable= entry.getKey();
String annotation = allocatable.getAnnotation( ResourceAnnotations.KEY_CONFLICT_CREATION);
boolean holdBackConflicts = annotation != null && annotation.equals( ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE);
if ( holdBackConflicts)
{
continue;
}
Map<Appointment, Collection<Appointment>> appointmentMap = entry.getValue();
for (Map.Entry<Appointment, Collection<Appointment>> appointmentEntry: appointmentMap.entrySet())
{
Appointment appointment = appointmentEntry.getKey();
if ( reservation.hasAllocated( allocatable, appointment))
{
Collection<Appointment> conflictionAppointments = appointmentEntry.getValue();
if ( conflictionAppointments != null)
{
for ( Appointment conflictingAppointment: conflictionAppointments)
{
Appointment appointment1 = appointment;
Appointment appointment2 = conflictingAppointment;
if (ConflictImpl.isConflict(appointment1, appointment2, today))
{
ConflictImpl.addConflicts(conflictList, allocatable,appointment1, appointment2, today);
}
}
}
}
}
}
return conflictList.toArray(Conflict.CONFLICT_ARRAY);
}
public Conflict[] getConflicts() throws RaplaException {
final User user;
User workingUser = getWorkingUser();
if ( workingUser != null && !workingUser.isAdmin())
{
user = workingUser;
}
else
{
user = null;
}
Collection<Conflict> conflicts = operator.getConflicts( user);
if (getLogger().isDebugEnabled())
{
getLogger().debug("getConflits called. Returned " + conflicts.size() + " conflicts.");
}
return conflicts.toArray(new Conflict[] {});
}
public static boolean hasPermissionToAllocate( User user, Appointment appointment,Allocatable allocatable, Reservation original, Date today) {
if ( user.isAdmin()) {
return true;
}
Date start = appointment.getStart();
Date end = appointment.getMaxEnd();
Permission[] permissions = allocatable.getPermissions();
for ( int i = 0; i < permissions.length; i++)
{
Permission p = permissions[i];
int accessLevel = p.getAccessLevel();
if ( (!p.affectsUser( user )) || accessLevel< Permission.READ) {
continue;
}
if ( accessLevel == Permission.ADMIN)
{
// user has the right to allocate
return true;
}
if ( accessLevel >= Permission.ALLOCATE && p.covers( start, end, today ) )
{
return true;
}
if ( original == null )
{
continue;
}
// We must check if the changes of the existing appointment
// are in a permisable timeframe (That should be allowed)
// 1. check if appointment is old,
// 2. check if allocatable was already assigned to the appointment
Appointment originalAppointment = original.findAppointment( appointment );
if ( originalAppointment == null || !original.hasAllocated( allocatable, originalAppointment))
{
continue;
}
// 3. check if the appointment has changed during
// that time
if ( appointment.matches( originalAppointment ) )
{
return true;
}
if ( accessLevel >= Permission.ALLOCATE )
{
Date maxTime = DateTools.max(appointment.getMaxEnd(), originalAppointment.getMaxEnd());
if (maxTime == null)
{
maxTime = DateTools.addYears( today, 4);
}
Date minChange = appointment.getFirstDifference( originalAppointment, maxTime );
Date maxChange = appointment.getLastDifference( originalAppointment, maxTime );
//System.out.println ( "minChange: " + minChange + ", maxChange: " + maxChange );
if ( p.covers( minChange, maxChange, today ) ) {
return true;
}
}
}
return false;
}
public boolean canEditTemplats(User user) {
return hasGroupRights(user, Permission.GROUP_CAN_EDIT_TEMPLATES);
}
public boolean canReadReservationsFromOthers(User user) {
return hasGroupRights(user, Permission.GROUP_CAN_READ_EVENTS_FROM_OTHERS);
}
protected boolean hasGroupRights(User user, String groupKey) {
if (user == null) {
User workingUser;
try {
workingUser = getWorkingUser();
} catch (EntityNotFoundException e) {
return false;
}
return workingUser == null || workingUser.isAdmin();
}
if (user.isAdmin()) {
return true;
}
try {
Category group = getUserGroupsCategory().getCategory( groupKey);
if ( group == null)
{
return true;
}
return user.belongsTo(group);
} catch (Exception ex) {
getLogger().error("Can't get permissions!", ex);
}
return false;
}
public boolean canCreateReservations(User user) {
return hasGroupRights(user, Permission.GROUP_CAN_CREATE_EVENTS);
}
@Deprecated
public Allocatable[] getAllocatableBindings(Appointment forAppointment) throws RaplaException {
List<Allocatable> allocatableList = Arrays.asList(getAllocatables());
List<Allocatable> result = new ArrayList<Allocatable>();
Map<Allocatable, Collection<Appointment>> bindings = getAllocatableBindings( allocatableList, Collections.singletonList(forAppointment));
for (Map.Entry<Allocatable, Collection<Appointment>> entry: bindings.entrySet())
{
Collection<Appointment> appointments = entry.getValue();
if ( appointments.contains( forAppointment))
{
Allocatable alloc = entry.getKey();
result.add( alloc);
}
}
return result.toArray(Allocatable.ALLOCATABLE_ARRAY);
}
public Map<Allocatable,Collection<Appointment>> getAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments) throws RaplaException {
Collection<Reservation> ignoreList = new HashSet<Reservation>();
if ( appointments != null)
{
for (Appointment app: appointments)
{
Reservation r = app.getReservation();
if ( r != null)
{
ignoreList.add( r );
}
}
}
return operator.getFirstAllocatableBindings(allocatables, appointments, ignoreList);
}
public Date getNextAllocatableDate(Collection<Allocatable> allocatables, Appointment appointment, CalendarOptions options) throws RaplaException {
int worktimeStartMinutes = options.getWorktimeStartMinutes();
int worktimeEndMinutes = options.getWorktimeEndMinutes();
Integer[] excludeDays = options.getExcludeDays().toArray( new Integer[] {});
int rowsPerHour = options.getRowsPerHour();
Reservation reservation = appointment.getReservation();
Collection<Reservation> ignoreList;
if (reservation != null)
{
ignoreList = Collections.singleton( reservation);
}
else
{
ignoreList = Collections.emptyList();
}
return operator.getNextAllocatableDate(allocatables, appointment,ignoreList, worktimeStartMinutes, worktimeEndMinutes, excludeDays, rowsPerHour);
}
/******************************
* Login - Module *
******************************/
public User getUser() throws RaplaException {
if (this.workingUserId == null) {
throw new RaplaException("no user loged in");
}
return operator.resolve( workingUserId, User.class);
}
/** unlike getUser this can be null if working user not set*/
private User getWorkingUser() throws EntityNotFoundException {
if ( workingUserId == null)
{
return null;
}
return operator.resolve( workingUserId, User.class);
}
public boolean login(String username, char[] password)
throws RaplaException {
return login( new ConnectInfo(username, password));
}
public boolean login(ConnectInfo connectInfo)
throws RaplaException {
User user = null;
try {
if (!operator.isConnected()) {
user = operator.connect( connectInfo);
}
} catch (RaplaSecurityException ex) {
return false;
} finally {
// Clear password
// for (int i = 0; i < password.length; i++)
// password[i] = 0;
}
if ( user == null)
{
String username = connectInfo.getUsername();
if ( connectInfo.getConnectAs() != null)
{
username = connectInfo.getConnectAs();
}
user = operator.getUser(username);
}
if (user != null) {
this.workingUserId = user.getId();
getLogger().info("Login " + user.getUsername());
return true;
} else {
return false;
}
}
public boolean canChangePassword() {
try {
return operator.canChangePassword();
} catch (RaplaException e) {
return false;
}
}
public boolean isSessionActive() {
return (this.workingUserId != null);
}
private boolean aborting;
public void logout() throws RaplaException {
if (this.workingUserId == null )
return;
getLogger().info("Logout " + workingUserId);
aborting = true;
try
{
// now we can add it again
this.workingUserId = null;
// we need to remove the storage update listener, because the disconnect
// would trigger a restart otherwise
operator.removeStorageUpdateListener(this);
operator.disconnect();
operator.addStorageUpdateListener(this);
}
finally
{
aborting = false;
}
}
private boolean isAborting() {
return aborting || !operator.isConnected();
}
public void changePassword(User user, char[] oldPassword, char[] newPassword) throws RaplaException {
operator.changePassword( user, oldPassword, newPassword);
}
/******************************
* Modification-module *
******************************/
public String getTemplateName()
{
if ( templateName != null)
{
return templateName;
}
return null;
}
public void setTemplateName(String templateName)
{
this.templateName = templateName;
cachedReservations = null;
cacheValidString = null;
User workingUser;
try {
workingUser = getWorkingUser();
} catch (EntityNotFoundException e) {
// system user as change initiator won't hurt
workingUser = null;
getLogger().error(e.getMessage(),e);
}
UpdateResult updateResult = new UpdateResult( workingUser);
updateResult.setSwitchTemplateMode(true);
updateResult.setInvalidateInterval( new TimeInterval(null, null));
fireUpdateEvent( updateResult);
}
@SuppressWarnings("unchecked")
public <T> RaplaMap<T> newRaplaMap(Map<String, T> map) {
return (RaplaMap<T>) new RaplaMapImpl(map);
}
@SuppressWarnings("unchecked")
public <T> RaplaMap<T> newRaplaMap(Collection<T> col) {
return (RaplaMap<T>) new RaplaMapImpl(col);
}
public Appointment newAppointment(Date startDate, Date endDate) throws RaplaException {
User user = getUser();
return newAppointment(startDate, endDate, user);
}
public Reservation newReservation() throws RaplaException
{
Classification classification = getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)[0].newClassification();
return newReservation( classification );
}
public Reservation newReservation(Classification classification) throws RaplaException
{
User user = getUser();
return newReservation( classification,user );
}
public Reservation newReservation(Classification classification,User user) throws RaplaException
{
if (!canCreateReservations( user))
{
throw new RaplaException("User not allowed to create events");
}
Date now = operator.getCurrentTimestamp();
ReservationImpl reservation = new ReservationImpl(now ,now );
if ( templateName != null )
{
reservation.setAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE, templateName);
}
reservation.setClassification(classification);
setNew(reservation, user);
return reservation;
}
public Allocatable newAllocatable( Classification classification) throws RaplaException
{
return newAllocatable(classification, getUser());
}
public Allocatable newAllocatable( Classification classification, User user) throws RaplaException {
Date now = operator.getCurrentTimestamp();
AllocatableImpl allocatable = new AllocatableImpl(now, now);
DynamicTypeImpl type = (DynamicTypeImpl)classification.getType();
if ( type.getElementKey().equals(StorageOperator.PERIOD_TYPE))
{
Permission newPermission =allocatable.newPermission();
newPermission.setAccessLevel( Permission.READ);
allocatable.addPermission(newPermission);
}
if ( !type.isInternal())
{
allocatable.addPermission(allocatable.newPermission());
if (user != null && !user.isAdmin()) {
Permission permission = allocatable.newPermission();
permission.setUser(user);
permission.setAccessLevel(Permission.ADMIN);
allocatable.addPermission(permission);
}
}
allocatable.setClassification(classification);
setNew(allocatable, user);
return allocatable;
}
private Classification newClassification(String classificationType)
throws RaplaException {
DynamicType[] dynamicTypes = getDynamicTypes(classificationType);
DynamicType dynamicType = dynamicTypes[0];
Classification classification = dynamicType.newClassification();
return classification;
}
public Appointment newAppointment(Date startDate, Date endDate, User user) throws RaplaException {
AppointmentImpl appointment = new AppointmentImpl(startDate, endDate);
setNew(appointment, user);
return appointment;
}
public Appointment newAppointment(Date startDate, Date endDate, RepeatingType repeatingType, int repeatingDuration) throws RaplaException {
AppointmentImpl appointment = new AppointmentImpl(startDate, endDate, repeatingType, repeatingDuration);
User user = getUser();
setNew(appointment, user);
return appointment;
}
public Allocatable newResource() throws RaplaException {
User user = getUser();
Classification classification = newClassification(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE);
return newAllocatable(classification, user);
}
public Allocatable newPerson() throws RaplaException {
User user = getUser();
Classification classification = newClassification(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON);
return newAllocatable(classification, user);
}
public Allocatable newPeriod() throws RaplaException {
DynamicType periodType = getDynamicType(StorageOperator.PERIOD_TYPE);
Classification classification = periodType.newClassification();
classification.setValue("name", "");
Date today = today();
classification.setValue("start", DateTools.cutDate(today));
classification.setValue("end", DateTools.addDays(DateTools.fillDate(today),7));
Allocatable period = newAllocatable(classification);
setNew(period);
return period;
}
public Date today() {
return operator.today();
}
public Category newCategory() throws RaplaException {
Date now = operator.getCurrentTimestamp();
CategoryImpl category = new CategoryImpl(now, now);
setNew(category);
return category;
}
private Attribute createStringAttribute(String key, String name) throws RaplaException {
Attribute attribute = newAttribute(AttributeType.STRING);
attribute.setKey(key);
setName(attribute.getName(), name);
return attribute;
}
public DynamicType newDynamicType(String classificationType) throws RaplaException {
Date now = operator.getCurrentTimestamp();
DynamicTypeImpl dynamicType = new DynamicTypeImpl(now,now);
dynamicType.setAnnotation("classification-type", classificationType);
dynamicType.setKey(createDynamicTypeKey(classificationType));
setNew(dynamicType);
if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE)) {
dynamicType.addAttribute(createStringAttribute("name", "name"));
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}");
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS,"automatic");
} else if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)) {
dynamicType.addAttribute(createStringAttribute("name","eventname"));
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}");
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS, null);
} else if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON)) {
dynamicType.addAttribute(createStringAttribute("surname", "surname"));
dynamicType.addAttribute(createStringAttribute("firstname", "firstname"));
dynamicType.addAttribute(createStringAttribute("email", "email"));
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT, "{surname} {firstname}");
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS, null);
}
return dynamicType;
}
public Attribute newAttribute(AttributeType attributeType) throws RaplaException {
AttributeImpl attribute = new AttributeImpl(attributeType);
setNew(attribute);
return attribute;
}
public User newUser() throws RaplaException {
Date now = operator.getCurrentTimestamp();
UserImpl user = new UserImpl( now, now);
setNew(user);
String[] defaultGroups = new String[] {Permission.GROUP_MODIFY_PREFERENCES_KEY,Permission.GROUP_CAN_READ_EVENTS_FROM_OTHERS,Permission.GROUP_CAN_CREATE_EVENTS};
for ( String groupKey: defaultGroups)
{
Category group = getUserGroupsCategory().getCategory( groupKey);
if (group != null)
{
user.addGroup(group);
}
}
return user;
}
public CalendarSelectionModel newCalendarModel(User user) throws RaplaException{
User workingUser = getWorkingUser();
if ( workingUser != null && !workingUser.isAdmin() && !user.equals(workingUser))
{
throw new RaplaException("Can't create a calendar model for a different user.");
}
return new CalendarModelImpl( context, user, this);
}
private String createDynamicTypeKey(String classificationType)
throws RaplaException {
DynamicType[] dts = getDynamicTypes(classificationType);
int max = 1;
for (int i = 0; i < dts.length; i++) {
String key = dts[i].getKey();
int len = classificationType.length();
if (key.indexOf(classificationType) >= 0 && key.length() > len && Character.isDigit(key.charAt(len))) {
try {
int value = Integer.valueOf(key.substring(len)).intValue();
if (value >= max)
max = value + 1;
} catch (NumberFormatException ex) {
}
}
}
return classificationType + (max);
}
private void setNew(Entity entity) throws RaplaException {
setNew(entity, null);
}
private void setNew(Entity entity,User user) throws RaplaException {
setNew(Collections.singleton(entity), entity.getRaplaType(), user);
}
private <T extends Entity> void setNew(Collection<T> entities, RaplaType raplaType,User user)
throws RaplaException {
for ( T entity: entities)
{
if ((entity instanceof ParentEntity) && (((ParentEntity)entity).getSubEntities().iterator().hasNext()) && ! (entity instanceof Reservation) ) {
throw new RaplaException("The current Rapla Version doesnt support cloning entities with sub-entities. (Except reservations)");
}
}
String[] ids = operator.createIdentifier(raplaType, entities.size());
int i = 0;
for ( T uncasted: entities)
{
String id = ids[i++];
SimpleEntity entity = (SimpleEntity) uncasted;
entity.setId(id);
entity.setResolver(operator);
if (getLogger() != null && getLogger().isDebugEnabled()) {
getLogger().debug("new " + entity.getId());
}
if (entity instanceof Reservation) {
if (user == null)
throw new RaplaException("The reservation " + entity + " needs an owner but user specified is null ");
((Ownable) entity).setOwner(user);
}
}
}
public void checkReservation(Reservation reservation) throws RaplaException {
if (reservation.getAppointments().length == 0) {
throw new RaplaException(i18n.getString("error.no_appointment"));
}
Locale locale = i18n.getLocale();
String name = reservation.getName(locale);
if (name.trim().length() == 0) {
throw new RaplaException(i18n.getString("error.no_reservation_name"));
}
}
public <T extends Entity> T edit(T obj) throws RaplaException {
if (obj == null)
throw new NullPointerException("Can't edit null objects");
Set<T> singleton = Collections.singleton( obj);
Collection<T> edit = edit(singleton);
T result = edit.iterator().next();
return result;
}
public <T extends Entity> Collection<T> edit(Collection<T> list) throws RaplaException
{
List<Entity> castedList = new ArrayList<Entity>();
for ( Entity entity:list)
{
castedList.add( entity);
}
User workingUser = getWorkingUser();
Collection<Entity> result = operator.editObjects(castedList, workingUser);
List<T> castedResult = new ArrayList<T>();
for ( Entity entity:result)
{
@SuppressWarnings("unchecked")
T casted = (T) entity;
castedResult.add( casted);
}
return castedResult;
}
@SuppressWarnings("unchecked")
private <T extends Entity> T _clone(T obj) throws RaplaException {
T deepClone = (T) obj.clone();
T clone = deepClone;
RaplaType raplaType = clone.getRaplaType();
if (raplaType == Appointment.TYPE) {
// Hack for 1.6 compiler compatibility
Object temp = clone;
((AppointmentImpl) temp).removeParent();
}
if (raplaType == Category.TYPE) {
// Hack for 1.6 compiler compatibility
Object temp = clone;
((CategoryImpl) temp).removeParent();
}
User workingUser = getWorkingUser();
setNew((Entity) clone, workingUser);
return clone;
}
@SuppressWarnings("unchecked")
public <T extends Entity> T clone(T obj) throws RaplaException {
if (obj == null)
throw new NullPointerException("Can't clone null objects");
User workingUser = getWorkingUser();
T result;
RaplaType<T> raplaType = obj.getRaplaType();
// Hack for 1.6 compiler compatibility
if (((Object)raplaType) == Appointment.TYPE ){
T _clone = _clone(obj);
// Hack for 1.6 compiler compatibility
Object temp = _clone;
((AppointmentImpl) temp).setParent(null);
result = _clone;
// Hack for 1.6 compiler compatibility
} else if (((Object)raplaType) == Reservation.TYPE) {
// Hack for 1.6 compiler compatibility
Object temp = obj;
Reservation clonedReservation = cloneReservation((Reservation) temp);
// Hack for 1.6 compiler compatibility
Reservation r = clonedReservation;
if ( workingUser != null)
{
r.setOwner( workingUser );
}
if ( templateName != null )
{
r.setAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE, templateName);
}
else
{
String originalTemplate = r.getAnnotation( RaplaObjectAnnotations.KEY_TEMPLATE);
if (originalTemplate != null)
{
r.setAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE_COPYOF, originalTemplate);
}
r.setAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE, null);
}
// Hack for 1.6 compiler compatibility
Object r2 = r;
result = (T)r2;
}
else
{
try {
T _clone = _clone(obj);
result = _clone;
} catch (ClassCastException ex) {
throw new RaplaException("This entity can't be cloned ", ex);
} finally {
}
}
if (result instanceof ModifiableTimestamp) {
Date now = operator.getCurrentTimestamp();
((ModifiableTimestamp) result).setLastChanged(now);
if (workingUser != null) {
((ModifiableTimestamp) result).setLastChangedBy(workingUser);
}
}
return result;
}
/** Clones a reservation and sets new ids for all appointments and the reservation itsel
*/
private Reservation cloneReservation(Reservation obj) throws RaplaException {
User workingUser = getWorkingUser();
// first we do a reservation deep clone
Reservation clone = obj.clone();
HashMap<Allocatable, Appointment[]> restrictions = new HashMap<Allocatable, Appointment[]>();
Allocatable[] allocatables = clone.getAllocatables();
for (Allocatable allocatable:allocatables) {
restrictions.put(allocatable, clone.getRestriction(allocatable));
}
// then we set new ids for all appointments
Appointment[] clonedAppointments = clone.getAppointments();
setNew(Arrays.asList(clonedAppointments),Appointment.TYPE, workingUser);
for (Appointment clonedAppointment:clonedAppointments) {
clone.removeAppointment(clonedAppointment);
}
// and now a new id for the reservation
setNew( clone, workingUser);
for (Appointment clonedAppointment:clonedAppointments) {
clone.addAppointment(clonedAppointment);
}
for (Allocatable allocatable:allocatables) {
clone.addAllocatable( allocatable);
Appointment[] appointments = restrictions.get(allocatable);
if (appointments != null) {
clone.setRestriction(allocatable, appointments);
}
}
return clone;
}
public <T extends Entity> T getPersistant(T entity) throws RaplaException {
Set<T> persistantList = Collections.singleton( entity);
Map<T,T> map = getPersistant( persistantList);
T result = map.get( entity);
if ( result == null)
{
throw new EntityNotFoundException( "There is no persistant version of " + entity);
}
return result;
}
public <T extends Entity> Map<T,T> getPersistant(Collection<T> list) throws RaplaException {
Map<Entity,Entity> result = operator.getPersistant(list);
LinkedHashMap<T, T> castedResult = new LinkedHashMap<T, T>();
for ( Map.Entry<Entity,Entity> entry: result.entrySet())
{
@SuppressWarnings("unchecked")
T key = (T) entry.getKey();
@SuppressWarnings("unchecked")
T value = (T) entry.getValue();
castedResult.put( key, value);
}
return castedResult;
}
public void store(Entity<?> obj) throws RaplaException {
if (obj == null)
throw new NullPointerException("Can't store null objects");
storeObjects(new Entity[] { obj });
}
public void remove(Entity<?> obj) throws RaplaException {
if (obj == null)
throw new NullPointerException("Can't remove null objects");
removeObjects(new Entity[] { obj });
}
public void storeObjects(Entity<?>[] obj) throws RaplaException {
storeAndRemove(obj, Entity.ENTITY_ARRAY);
}
public void removeObjects(Entity<?>[] obj) throws RaplaException {
storeAndRemove(Entity.ENTITY_ARRAY, obj);
}
public void storeAndRemove(Entity<?>[] storeObjects, Entity<?>[] removedObjects) throws RaplaException {
if (storeObjects.length == 0 && removedObjects.length == 0)
return;
long time = System.currentTimeMillis();
for (int i = 0; i < storeObjects.length; i++) {
if (storeObjects[i] == null) {
throw new RaplaException("Stored Objects cant be null");
}
if (storeObjects[i].getRaplaType() == Reservation.TYPE) {
checkReservation((Reservation) storeObjects[i]);
}
}
for (int i = 0; i < removedObjects.length; i++) {
if (removedObjects[i] == null) {
throw new RaplaException("Removed Objects cant be null");
}
}
ArrayList<Entity>storeList = new ArrayList<Entity>();
ArrayList<Entity>removeList = new ArrayList<Entity>();
for (Entity toStore : storeObjects) {
storeList.add( toStore);
}
for (Entity<?> toRemove : removedObjects) {
removeList.add( toRemove);
}
User workingUser = getWorkingUser();
operator.storeAndRemove(storeList, removeList, workingUser);
if (getLogger().isDebugEnabled())
getLogger().debug("Storing took " + (System.currentTimeMillis() - time) + " ms.");
}
public CommandHistory getCommandHistory()
{
return commandHistory;
}
public void changeName(String title, String firstname, String surname) throws RaplaException
{
User user = getUser();
getOperator().changeName(user,title,firstname,surname);
}
public void changeEmail(String newEmail) throws RaplaException
{
User user = getUser();
getOperator().changeEmail(user, newEmail);
}
public void confirmEmail(String newEmail) throws RaplaException {
User user = getUser();
getOperator().confirmEmail(user, newEmail);
}
}
| 04900db4-rob | src/org/rapla/facade/internal/FacadeImpl.java | Java | gpl3 | 51,573 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.AllocationChangeEvent;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.UpdateResult;
/** Converts updateResults into AllocationChangeEvents */
public class AllocationChangeFinder
{
ArrayList<AllocationChangeEvent> changeList = new ArrayList<AllocationChangeEvent>();
UpdateResult updateResult;
Logger logger;
private AllocationChangeFinder(Logger logger, UpdateResult updateResult) {
this.logger = logger;
if ( updateResult == null)
return;
User user = updateResult.getUser();
for (Iterator<UpdateResult.Add> it = updateResult.getOperations( UpdateResult.Add.class );it.hasNext();) {
UpdateResult.Add addOp = it.next();
added( addOp.getNew(), user );
}
for (Iterator<UpdateResult.Remove> it = updateResult.getOperations( UpdateResult.Remove.class );it.hasNext();) {
UpdateResult.Remove removeOp = it.next();
removed( removeOp.getCurrent(), user );
}
for (Iterator<UpdateResult.Change> it = updateResult.getOperations( UpdateResult.Change.class );it.hasNext();) {
UpdateResult.Change changeOp = it.next();
Entity old = changeOp.getOld();
Entity newObj = changeOp.getNew();
changed(old , newObj, user );
}
}
public Logger getLogger()
{
return logger;
}
static public List<AllocationChangeEvent> getTriggerEvents(UpdateResult result,Logger logger) {
AllocationChangeFinder finder = new AllocationChangeFinder(logger, result);
return finder.changeList;
}
private void added(RaplaObject entity, User user) {
RaplaType raplaType = entity.getRaplaType();
if ( raplaType == Reservation.TYPE ) {
Reservation newRes = (Reservation) entity;
addAppointmentAdd(
user
,newRes
,Arrays.asList(newRes.getAllocatables())
,Arrays.asList(newRes.getAppointments())
);
}
}
private void removed(RaplaObject entity,User user) {
RaplaType raplaType = entity.getRaplaType();
if ( raplaType == Reservation.TYPE ) {
if (getLogger().isDebugEnabled())
getLogger().debug("Reservation removed: " + entity);
Reservation oldRes = (Reservation) entity;
addAppointmentRemove(
user
,oldRes
,oldRes
,Arrays.asList(oldRes.getAllocatables())
,Arrays.asList(oldRes.getAppointments())
);
}
}
private void changed(Entity oldEntity,Entity newEntity, User user) {
RaplaType raplaType = oldEntity.getRaplaType();
if (raplaType == Reservation.TYPE ) {
if (getLogger().isDebugEnabled())
getLogger().debug("Reservation changed: " + oldEntity);
Reservation oldRes = (Reservation) oldEntity;
Reservation newRes = (Reservation) newEntity;
List<Allocatable> alloc1 = Arrays.asList(oldRes.getAllocatables());
List<Allocatable> alloc2 = Arrays.asList(newRes.getAllocatables());
List<Appointment> app1 = Arrays.asList(oldRes.getAppointments());
List<Appointment> app2 = Arrays.asList(newRes.getAppointments());
ArrayList<Allocatable> removeList = new ArrayList<Allocatable>(alloc1);
removeList.removeAll(alloc2);
// add removed allocations to the change list
addAppointmentRemove(user, oldRes,newRes, removeList, app1);
ArrayList<Allocatable> addList = new ArrayList<Allocatable>(alloc2);
addList.removeAll(alloc1);
// add new allocations to the change list
addAppointmentAdd(user, newRes, addList, app2);
ArrayList<Allocatable> changeList = new ArrayList<Allocatable>(alloc2);
changeList.retainAll(alloc1);
addAllocationDiff(user, changeList,oldRes,newRes);
}
if ( Appointment.TYPE == raplaType ) {
if (getLogger().isDebugEnabled())
getLogger().debug("Appointment changed: " + oldEntity + " to " + newEntity);
}
}
/*
private void printList(List list) {
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
*/
/**
* Calculates the allocations that have changed
*/
private void addAllocationDiff(User user,List<Allocatable> allocatableList,Reservation oldRes,Reservation newRes) {
List<Appointment> app1 = Arrays.asList(oldRes.getAppointments());
List<Appointment> app2 = Arrays.asList(newRes.getAppointments());
ArrayList<Appointment> removeList = new ArrayList<Appointment>(app1);
removeList.removeAll(app2);
addAppointmentRemove(user, oldRes,newRes,allocatableList,removeList);
ArrayList<Appointment> addList = new ArrayList<Appointment>(app2);
addList.removeAll(app1);
addAppointmentAdd(user, newRes,allocatableList,addList);
/*
System.out.println("OLD appointments");
printList(app1);
System.out.println("NEW appointments");
printList(app2);
*/
Set<Appointment> newList = new HashSet<Appointment>(app2);
newList.retainAll(app1);
ArrayList<Appointment> oldList = new ArrayList<Appointment>(app1);
oldList.retainAll(app2);
sort(oldList);
for (int i=0;i<oldList.size();i++) {
Appointment oldApp = oldList.get(i);
Appointment newApp = null;
for ( Appointment app:newList)
{
if ( app.equals( oldApp))
{
newApp = app;
}
}
if ( newApp == null)
{
// This should never happen as we call retainAll before
getLogger().error("Not found matching pair for " + oldApp);
continue;
}
for (Allocatable allocatable: allocatableList )
{
boolean oldAllocated = oldRes.hasAllocated(allocatable, oldApp);
boolean newAllocated = newRes.hasAllocated(allocatable, newApp);
if (!oldAllocated && !newAllocated) {
continue;
}
else if (!oldAllocated && newAllocated)
{
changeList.add(new AllocationChangeEvent(AllocationChangeEvent.ADD,user,newRes,allocatable,newApp));
}
else if (oldAllocated && !newAllocated)
{
changeList.add(new AllocationChangeEvent(AllocationChangeEvent.REMOVE,user,newRes,allocatable,newApp));
}
else if (!newApp.matches(oldApp))
{
getLogger().debug("\n" + newApp + " doesn't match \n" + oldApp);
changeList.add(new AllocationChangeEvent(user,newRes,allocatable,newApp,oldApp));
}
}
}
}
@SuppressWarnings("unchecked")
public void sort(ArrayList<Appointment> oldList) {
Collections.sort(oldList);
}
private void addAppointmentAdd(User user,Reservation newRes,List<Allocatable> allocatables,List<Appointment> appointments) {
for (Allocatable allocatable:allocatables)
{
for (Appointment appointment:appointments)
{
if (!newRes.hasAllocated(allocatable,appointment))
continue;
changeList.add(new AllocationChangeEvent(AllocationChangeEvent.ADD,user, newRes,allocatable,appointment));
}
}
}
private void addAppointmentRemove(User user,Reservation oldRes,Reservation newRes,List<Allocatable> allocatables,List<Appointment> appointments) {
for (Allocatable allocatable:allocatables)
{
for (Appointment appointment:appointments)
{
if (!oldRes.hasAllocated(allocatable,appointment))
continue;
changeList.add(new AllocationChangeEvent(AllocationChangeEvent.REMOVE,user, newRes,allocatable,appointment));
}
}
}
}
| 04900db4-rob | src/org/rapla/facade/internal/AllocationChangeFinder.java | Java | gpl3 | 9,952 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade.internal;
import java.util.Calendar;
import java.util.LinkedHashSet;
import java.util.Set;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.facade.CalendarOptions;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
/** <strong>WARNING!!</strong> This class should not be public to the outside. Please use the interface */
public class CalendarOptionsImpl implements CalendarOptions {
public final static TypedComponentRole<RaplaConfiguration> CALENDAR_OPTIONS= new TypedComponentRole<RaplaConfiguration>("org.rapla.calendarview");
public final static TypedComponentRole<Boolean> SHOW_CONFLICT_WARNING = new TypedComponentRole<Boolean>("org.rapla.conflict.showWarning");
public static final String WORKTIME = "worktime";
public static final String EXCLUDE_DAYS = "exclude-days";
public static final String WEEKSTART = "exclude-days";
public static final String ROWS_PER_HOUR = "rows-per-hour";
public final static String EXCEPTIONS_VISIBLE="exceptions-visible";
public final static String COMPACT_COLUMNS="compact-columns";
public final static String COLOR_BLOCKS="color";
public final static String COLOR_RESOURCES="resources";
public final static String COLOR_EVENTS="reservations";
public final static String COLOR_EVENTS_AND_RESOURCES="reservations_and_resources";
public final static String COLOR_NONE="disabled";
public final static String DAYS_IN_WEEKVIEW = "days-in-weekview";
public final static String FIRST_DAY_OF_WEEK = "first-day-of-week";
public final static String MIN_BLOCK_WIDTH = "minimum-block-width";
/** The following fields will be replaced in version 1.7 as they don't refer to the calendar but to the creation of appointment. Please don't use*/
public final static String REPEATING="repeating";
public final static String NTIMES="repeating.ntimes";
public final static String CALNAME="calendar-name";
public final static String REPEATINGTYPE="repeatingtype";
public final static String NON_FILTERED_EVENTS= "non-filtered-events";
public final static String NON_FILTERED_EVENTS_TRANSPARENT= "transparent";
public final static String NON_FILTERED_EVENTS_HIDDEN= "not_visible";
int nTimes;
/** Ends here*/
Set<Integer> excludeDays = new LinkedHashSet<Integer>();
int maxtimeMinutes = -1;
int mintimeMinutes = -1;
int rowsPerHour = 4;
boolean exceptionsVisible;
boolean compactColumns = false; // use for strategy.setFixedSlotsEnabled
Configuration config;
String colorField;
boolean nonFilteredEventsVisible = false;
int daysInWeekview;
int firstDayOfWeek;
private int minBlockWidth;
public CalendarOptionsImpl(Configuration config ) throws RaplaException {
this.config = config;
Configuration worktime = config.getChild( WORKTIME );
String worktimesString = worktime.getValue("8-18");
int minusIndex = worktimesString.indexOf("-");
try {
if ( minusIndex >= 0)
{
String firstPart = worktimesString.substring(0,minusIndex);
String secondPart = worktimesString.substring(minusIndex+ 1);
mintimeMinutes = parseMinutes( firstPart );
maxtimeMinutes = parseMinutes( secondPart );
}
else
{
mintimeMinutes = parseMinutes( worktimesString);
}
} catch ( NumberFormatException e ) {
throw new RaplaException( "Invalid time in " + worktime + ". use the following format : 8-18 or 8:30-18:00!");
}
Configuration exclude = config.getChild( EXCLUDE_DAYS );
String excludeString = exclude.getValue("");
if ( excludeString.trim().length() > 0)
{
String[] tokens = excludeString.split(",");
for ( String token:tokens)
{
String normalizedToken = token.toLowerCase().trim();
try {
excludeDays.add( new Integer(normalizedToken) );
} catch ( NumberFormatException e ) {
throw new RaplaException("Invalid day in " + excludeDays + ". only numbers are allowed!");
}
} // end of while ()
}
int firstDayOfWeekDefault = Calendar.getInstance().getFirstDayOfWeek();
firstDayOfWeek = config.getChild(FIRST_DAY_OF_WEEK).getValueAsInteger(firstDayOfWeekDefault);
daysInWeekview = config.getChild(DAYS_IN_WEEKVIEW).getValueAsInteger( 7 );
rowsPerHour = config.getChild( ROWS_PER_HOUR ).getValueAsInteger( 4 );
exceptionsVisible = config.getChild(EXCEPTIONS_VISIBLE).getValueAsBoolean(false);
colorField = config.getChild( COLOR_BLOCKS ).getValue( COLOR_EVENTS_AND_RESOURCES );
minBlockWidth = config.getChild( MIN_BLOCK_WIDTH).getValueAsInteger(0);
nTimes = config.getChild( NTIMES ).getValueAsInteger( 1 );
nonFilteredEventsVisible = config.getChild( NON_FILTERED_EVENTS).getValue(NON_FILTERED_EVENTS_TRANSPARENT).equals( NON_FILTERED_EVENTS_TRANSPARENT);
}
private int parseMinutes(String string) {
String[] split = string.split(":");
int hour = Integer.parseInt(split[0].toLowerCase().trim());
int minute = 0;
if ( split.length > 1)
{
minute = Integer.parseInt(split[1].toLowerCase().trim());
}
int result = Math.max(0,Math.min(24 * 60,hour * 60 + minute));
return result;
}
public Configuration getConfig() {
return config;
}
public int getWorktimeStart() {
return mintimeMinutes / 60;
}
public int getRowsPerHour() {
return rowsPerHour;
}
public int getWorktimeEnd() {
return maxtimeMinutes / 60;
}
public Set<Integer> getExcludeDays() {
return excludeDays;
}
public boolean isNonFilteredEventsVisible()
{
return nonFilteredEventsVisible;
}
public void setNonFilteredEventsVisible(boolean nonFilteredEventsVisible)
{
this.nonFilteredEventsVisible = nonFilteredEventsVisible;
}
public boolean isExceptionsVisible() {
return exceptionsVisible;
}
public boolean isCompactColumns() {
return compactColumns;
}
public boolean isResourceColoring() {
return colorField.equals( COLOR_RESOURCES ) || colorField.equals( COLOR_EVENTS_AND_RESOURCES);
}
public boolean isEventColoring() {
return colorField.equals( COLOR_EVENTS ) || colorField.equals( COLOR_EVENTS_AND_RESOURCES);
}
public int getDaysInWeekview() {
return daysInWeekview;
}
public int getFirstDayOfWeek()
{
return firstDayOfWeek;
}
public int getMinBlockWidth()
{
return minBlockWidth;
}
public boolean isWorktimeOvernight() {
int worktimeS = getWorktimeStartMinutes();
int worktimeE = getWorktimeEndMinutes();
worktimeE = (worktimeE == 0)?24*60:worktimeE;
boolean overnight = worktimeS >= worktimeE|| worktimeE == 24*60;
return overnight;
}
public int getWorktimeStartMinutes() {
return mintimeMinutes;
}
public int getWorktimeEndMinutes() {
return maxtimeMinutes;
}
}
| 04900db4-rob | src/org/rapla/facade/internal/CalendarOptionsImpl.java | Java | gpl3 | 8,174 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.rapla.components.util.DateTools;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.entities.storage.EntityResolver;
import org.rapla.entities.storage.internal.SimpleEntity;
import org.rapla.facade.Conflict;
import org.rapla.facade.RaplaComponent;
/**
* A conflict is the allocation of the same resource at the same time by different
* reservations. There's one conflict for each resource and each overlapping of
* two allocations. So if there are 3 reservations that allocate the same 2 resources
* on 2 days of the week, then we got ( 3 * 2 ) * 2 * 2 = 24 conflicts. Thats
* 3 reservations, each conflicting with two other 2 reservations on 2 days with 2 resources.
*
* @author Christopher Kohlhaas
*/
public class ConflictImpl extends SimpleEntity implements Conflict
{
Date startDate;
String reservation1Name;
String reservation2Name;
ConflictImpl() {
}
public ConflictImpl(
Allocatable allocatable,
Appointment app1,
Appointment app2,
Date today
)
{
this(allocatable,app1,app2, today,createId(allocatable.getId(), app1.getId(), app2.getId()));
}
public ConflictImpl(
Allocatable allocatable,
Appointment app1,
Appointment app2,
Date today,
String id
)
{
putEntity("allocatable", allocatable);
startDate = getStartDate_(today, app1, app2);
putEntity("appointment1", app1);
putEntity("appointment2", app2);
Reservation reservation1 = app1.getReservation();
Reservation reservation2 = app2.getReservation();
putEntity("reservation1", reservation1);
putEntity("reservation2", reservation2);
putEntity("owner1", reservation1.getOwner());
putEntity("owner2", reservation2.getOwner());
this.reservation1Name = reservation1.getName(Locale.getDefault());
this.reservation2Name = reservation2.getName(Locale.getDefault());
setResolver( ((AllocatableImpl)allocatable).getResolver());
setId( id);
}
public String getReservation1Name() {
return reservation1Name;
}
public String getReservation2Name() {
return reservation2Name;
}
public Date getStartDate()
{
return startDate;
}
@Override
public Iterable<ReferenceInfo> getReferenceInfo() {
return Collections.emptyList();
}
private Date getStartDate_(Date today,Appointment app1, Appointment app2) {
Date fromDate = today;
Date start1 = app1.getStart();
if ( start1.before( fromDate))
{
fromDate = start1;
}
Date start2 = app2.getStart();
if ( start2.before( fromDate))
{
fromDate = start2;
}
Date toDate = DateTools.addDays( today, 365 * 10);
Date date = getFirstConflictDate(fromDate, toDate, app1, app2);
return date;
}
static public String createId(String allocId, String id1, String id2)
{
StringBuilder buf = new StringBuilder();
//String id1 = getId("appointment1");
//String id2 = getId("appointment2");
if ( id1.equals( id2))
{
throw new IllegalStateException("ids of conflicting appointments are the same " + id1);
}
buf.append(allocId);
buf.append(';');
buf.append(id1.compareTo( id2) > 0 ? id1 : id2);
buf.append(';');
buf.append(id1.compareTo( id2) > 0 ? id2 : id1);
return buf.toString();
}
// public ConflictImpl(String id) throws RaplaException {
// String[] split = id.split(";");
// ReferenceHandler referenceHandler = getReferenceHandler();
// referenceHandler.putId("allocatable", LocalCache.getId(Allocatable.TYPE,split[0]));
// referenceHandler.putId("appointment1", LocalCache.getId(Appointment.TYPE,split[1]));
// referenceHandler.putId("appointment2", LocalCache.getId(Appointment.TYPE,split[2]));
// setId( id);
// }
// public static boolean isConflictId(String id) {
// if ( id == null)
// {
// return false;
// }
// String[] split = id.split(";");
// if ( split.length != 3)
// {
// return false;
// }
// try {
// LocalCache.getId(Allocatable.TYPE,split[0]);
// LocalCache.getId(Appointment.TYPE,split[1]);
// LocalCache.getId(Appointment.TYPE,split[2]);
// } catch (RaplaException e) {
// return false;
// }
// return true;
// }
/** @return the first Reservation, that is involed in the conflict.*/
// public Reservation getReservation1()
// {
// Appointment appointment1 = getAppointment1();
// if ( appointment1 == null)
// {
// throw new IllegalStateException("Appointment 1 is null resolve not called");
// }
// return appointment1.getReservation();
// }
/** The appointment of the first reservation, that causes the conflict. */
public String getAppointment1()
{
return getId("appointment1");
}
public String getReservation1()
{
return getId("reservation1");
}
public String getReservation2()
{
return getId("reservation2");
}
/** @return the allocatable, allocated for the same time by two different reservations. */
public Allocatable getAllocatable()
{
return getEntity("allocatable", Allocatable.class);
}
// /** @return the second Reservation, that is involed in the conflict.*/
// public Reservation getReservation2()
// {
// Appointment appointment2 = getAppointment2();
// if ( appointment2 == null)
// {
// throw new IllegalStateException("Appointment 2 is null resolve not called");
// }
// return appointment2.getReservation();
// }
// /** @return The User, who created the second Reservation.*/
// public User getUser2()
// {
// return getReservation2().getOwner();
// }
/** The appointment of the second reservation, that causes the conflict. */
public String getAppointment2()
{
return getId("appointment2");
}
public static final ConflictImpl[] CONFLICT_ARRAY= new ConflictImpl[] {};
/**
* @see org.rapla.entities.Named#getName(java.util.Locale)
*/
public String getName(Locale locale) {
return getAllocatable().getName( locale );
}
public boolean isOwner( User user)
{
User owner1 = getOwner1();
User owner2 = getOwner2();
if (user != null && !user.equals(owner1) && !user.equals(owner2)) {
return false;
}
return true;
}
// public Date getFirstConflictDate(final Date fromDate, Date toDate) {
// Appointment a1 =getAppointment1();
// Appointment a2 =getAppointment2();
// return getFirstConflictDate(fromDate, toDate, a1, a2);
//}
public User getOwner1() {
return getEntity("owner1", User.class);
}
public User getOwner2() {
return getEntity("owner2", User.class);
}
private boolean contains(String appointmentId) {
if ( appointmentId == null)
return false;
String app1 = getAppointment1();
String app2 = getAppointment2();
if ( app1 != null && app1.equals( appointmentId))
return true;
if ( app2 != null && app2.equals( appointmentId))
return true;
return false;
}
static public boolean equals( ConflictImpl firstConflict,Conflict secondConflict) {
if (secondConflict == null )
return false;
if (!firstConflict.contains( secondConflict.getAppointment1()))
return false;
if (!firstConflict.contains( secondConflict.getAppointment2()))
return false;
Allocatable allocatable = firstConflict.getAllocatable();
if ( allocatable != null && !allocatable.equals( secondConflict.getAllocatable())) {
return false;
}
return true;
}
private static boolean contains(ConflictImpl conflict,
Collection<Conflict> conflictList) {
for ( Conflict conf:conflictList)
{
if ( equals(conflict,conf))
{
return true;
}
}
return false;
}
public RaplaType<Conflict> getRaplaType()
{
return Conflict.TYPE;
}
public String toString()
{
Conflict conflict = this;
StringBuffer buf = new StringBuffer();
buf.append( "Conflict for");
buf.append( conflict.getAllocatable());
buf.append( " " );
buf.append( conflict.getAppointment1());
buf.append( " " );
buf.append( "with");
buf.append( " " );
buf.append( conflict.getAppointment2());
buf.append( " " );
return buf.toString();
}
static public Date getFirstConflictDate(final Date fromDate, Date toDate,
Appointment a1, Appointment a2) {
Date minEnd = a1.getMaxEnd();
if ( a1.getMaxEnd() != null && a2.getMaxEnd() != null && a2.getMaxEnd().before( a1.getMaxEnd())) {
minEnd = a2.getMaxEnd();
}
Date maxStart = a1.getStart();
if ( a2.getStart().after( a1.getStart())) {
maxStart = a2.getStart();
}
if ( fromDate != null && maxStart.before( fromDate))
{
maxStart = fromDate;
}
// look for 10 years in the future (520 weeks)
if ( minEnd == null)
minEnd = new Date(maxStart.getTime() + DateTools.MILLISECONDS_PER_DAY * 365 * 10 );
if ( toDate != null && minEnd.after( toDate))
{
minEnd = toDate;
}
List<AppointmentBlock> listA = new ArrayList<AppointmentBlock>();
a1.createBlocks(maxStart, minEnd, listA );
List<AppointmentBlock> listB = new ArrayList<AppointmentBlock>();
a2.createBlocks( maxStart, minEnd, listB );
for ( int i=0, j=0;i<listA.size() && j<listB.size();) {
long s1 = listA.get( i).getStart();
long s2 = listB.get( j).getStart();
long e1 = listA.get( i).getEnd();
long e2 = listB.get( j).getEnd();
if ( s1< e2 && s2 < e1) {
return new Date( Math.max( s1, s2));
}
if ( s1> s2)
j++;
else
i++;
}
return null;
}
public static void addConflicts(Collection<Conflict> conflictList, Allocatable allocatable,Appointment appointment1, Appointment appointment2,Date today)
{
final ConflictImpl conflict = new ConflictImpl(allocatable,appointment1, appointment2, today);
// Rapla 1.4: Don't add conflicts twice
if (!contains(conflict, conflictList) )
{
conflictList.add(conflict);
}
}
public static boolean endsBefore(Appointment appointment1,Appointment appointment2, Date date) {
Date maxEnd1 = appointment1.getMaxEnd();
Date maxEnd2 = appointment2.getMaxEnd();
if (maxEnd1 != null && maxEnd1.before( date))
{
return true;
}
if (maxEnd2 != null && maxEnd2.before( date))
{
return true;
}
return false;
}
public static boolean isConflict(Appointment appointment1,Appointment appointment2, Date today) {
// Don't add conflicts, when in the past
if (endsBefore(appointment1, appointment2, today))
{
return false;
}
if (appointment1.equals(appointment2))
return false;
if (RaplaComponent.isTemplate( appointment1))
{
return false;
}
if (RaplaComponent.isTemplate( appointment2))
{
return false;
}
boolean conflictTypes = checkForConflictTypes( appointment1, appointment2);
if ( !conflictTypes )
{
return false;
}
Date maxEnd1 = appointment1.getMaxEnd();
Date maxEnd2 = appointment2.getMaxEnd();
Date checkEnd = maxEnd1;
if ( maxEnd2 != null && checkEnd !=null && maxEnd2.before( checkEnd) )
{
checkEnd = maxEnd2;
}
if (checkEnd != null && ConflictImpl.getFirstConflictDate(today, checkEnd, appointment1, appointment2) == null)
{
return false;
}
return true;
}
public static boolean isConflictWithoutCheck(Appointment appointment1,Appointment appointment2, Date today) {
// Don't add conflicts, when in the past
if (appointment1.equals(appointment2))
return false;
boolean conflictTypes = checkForConflictTypes2( appointment1, appointment2);
if ( !conflictTypes )
{
return false;
}
Date maxEnd1 = appointment1.getMaxEnd();
Date maxEnd2 = appointment2.getMaxEnd();
Date checkEnd = maxEnd1;
if ( maxEnd2 != null && checkEnd !=null && maxEnd2.before( checkEnd) )
{
checkEnd = maxEnd2;
}
if (checkEnd != null && ConflictImpl.getFirstConflictDate(today, checkEnd, appointment1, appointment2) == null)
{
return false;
}
return true;
}
@SuppressWarnings("null")
private static boolean checkForConflictTypes(Appointment a1, Appointment a2) {
Reservation r1 = a1.getReservation();
DynamicType type1 = r1 != null ? r1.getClassification().getType() : null;
String annotation1 = getConflictAnnotation( type1);
if ( isNoConflicts( annotation1 ) )
{
return false;
}
Reservation r2 = a2.getReservation();
DynamicType type2 = r2 != null ? r2.getClassification().getType() : null;
String annotation2 = getConflictAnnotation( type2);
if ( isNoConflicts ( annotation2))
{
return false;
}
if ( annotation1 != null )
{
if ( annotation1.equals(DynamicTypeAnnotations.VALUE_CONFLICTS_WITH_OTHER_TYPES))
{
if (type2 != null)
{
if (type1.equals(type2))
{
return false;
}
}
}
}
return true;
}
@SuppressWarnings("null")
private static boolean checkForConflictTypes2(Appointment a1, Appointment a2) {
Reservation r1 = a1.getReservation();
DynamicType type1 = r1 != null ? r1.getClassification().getType() : null;
String annotation1 = getConflictAnnotation( type1);
Reservation r2 = a2.getReservation();
DynamicType type2 = r2 != null ? r2.getClassification().getType() : null;
if ( annotation1 != null )
{
if ( annotation1.equals(DynamicTypeAnnotations.VALUE_CONFLICTS_WITH_OTHER_TYPES))
{
if (type2 != null)
{
if (type1.equals(type2))
{
return false;
}
}
}
}
return true;
}
public static boolean isNoConflicts(String annotation) {
if ( annotation != null && annotation.equals(DynamicTypeAnnotations.VALUE_CONFLICTS_NONE))
{
return true;
}
return false;
}
public static String getConflictAnnotation( DynamicType type) {
if ( type == null)
{
return null;
}
return type.getAnnotation(DynamicTypeAnnotations.KEY_CONFLICTS);
}
public boolean hasAppointment(Appointment appointment)
{
boolean result = getAppointment1().equals( appointment) || getAppointment2().equals( appointment);
return result;
}
@Override
public Conflict clone()
{
ConflictImpl clone = new ConflictImpl();
super.deepClone( clone);
return clone;
}
static public boolean canModify(Conflict conflict,User user, EntityResolver resolver) {
Allocatable allocatable = conflict.getAllocatable();
if (user == null || user.isAdmin())
{
return true;
}
if (allocatable.canRead( user ))
{
Reservation reservation = resolver.tryResolve(conflict.getReservation1(), Reservation.class);
if ( reservation == null )
{
// reservation will be deleted, and conflict also so return
return false;
}
if (RaplaComponent.canModify(reservation, user) )
{
return true;
}
Reservation overlappingReservation = resolver.tryResolve(conflict.getReservation2(), Reservation.class);
if ( overlappingReservation == null )
{
return false;
}
if (RaplaComponent.canModify(overlappingReservation, user))
{
return true;
}
}
return false;
}
public static Map<Appointment, Set<Appointment>> getMap(Collection<Conflict> selectedConflicts,List<Reservation> reservations)
{
Map<Appointment, Set<Appointment>> result = new HashMap<Appointment,Set<Appointment>>();
Map<String, Appointment> map = new HashMap<String,Appointment>();
for ( Reservation reservation:reservations)
{
for (Appointment app:reservation.getAppointments())
{
map.put( app.getId(), app);
}
}
for ( Conflict conflict:selectedConflicts)
{
Appointment app1 = map.get(conflict.getAppointment1());
Appointment app2 = map.get(conflict.getAppointment2());
add(result, app1, app2);
add(result, app2, app1);
}
return result;
}
private static void add(Map<Appointment, Set<Appointment>> result,Appointment app1, Appointment app2) {
Set<Appointment> set = result.get( app1);
if ( set == null)
{
set = new HashSet<Appointment>();
result.put(app1,set);
}
set.add( app2);
}
}
| 04900db4-rob | src/org/rapla/facade/internal/ConflictImpl.java | Java | gpl3 | 18,525 |
package org.rapla.facade;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
public interface CalendarModel extends Cloneable, ClassifiableFilter
{
public static final String SHOW_NAVIGATION_ENTRY = "org.rapla.plugin.abstractcalendar.show_navigation";
public static final String ONLY_ALLOCATION_INFO = "org.rapla.plugin.abstractcalendar.only_allocation_info";
public static final String SAVE_SELECTED_DATE = "org.rapla.plugin.abstractcalendar.save_selected_date";
public static final String ONLY_MY_EVENTS = "only_own_reservations";
public static final TypedComponentRole<Boolean> ONLY_MY_EVENTS_DEFAULT = new TypedComponentRole<Boolean>("org.rapla.plugin.abstractcalendar.only_own_reservations");
String getNonEmptyTitle();
User getUser();
Date getSelectedDate();
void setSelectedDate( Date date );
Date getStartDate();
void setStartDate( Date date );
Date getEndDate();
void setEndDate( Date date );
Collection<RaplaObject> getSelectedObjects();
/** Calendar View Plugins can use the calendar options to store their requiered optional parameters for a calendar view */
String getOption(String name);
Collection<RaplaObject> getSelectedObjectsAndChildren() throws RaplaException;
/** Convenience method to extract the allocatables from the selectedObjects and their children
* @see #getSelectedObjectsAndChildren */
Allocatable[] getSelectedAllocatables() throws RaplaException;
Reservation[] getReservations( Date startDate, Date endDate ) throws RaplaException;
Reservation[] getReservations() throws RaplaException;
CalendarModel clone();
List<AppointmentBlock> getBlocks() throws RaplaException;
DynamicType guessNewEventType() throws RaplaException;
/** returns the marked time intervals in the calendar. */
Collection<TimeInterval> getMarkedIntervals();
Collection<Allocatable> getMarkedAllocatables();
} | 04900db4-rob | src/org/rapla/facade/CalendarModel.java | Java | gpl3 | 2,382 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.Set;
/** This class contains the configuration options for the calendar views
like Worktimes and dates configuration is done in the calendar option menu.
Hours belonging to the worktime get a different color in the
weekview. This is also the minimum interval that will be used for
printing.<br>
Excluded Days are only visible, when there is an appointment to
display.<br>
*/
public interface CalendarOptions {
/** return the worktimeStart in hours
* @deprecated use {@link #getWorktimeStartMinutes()} instead*/
@Deprecated
int getWorktimeStart();
int getRowsPerHour();
/** return the worktimeEnd in hours
* @deprecated use {@link #getWorktimeEndMinutes()} instead*/
@Deprecated
int getWorktimeEnd();
Set<Integer> getExcludeDays();
int getDaysInWeekview();
int getFirstDayOfWeek();
boolean isExceptionsVisible();
boolean isCompactColumns();
boolean isResourceColoring();
boolean isEventColoring();
int getMinBlockWidth();
int getWorktimeStartMinutes();
int getWorktimeEndMinutes();
boolean isNonFilteredEventsVisible();
boolean isWorktimeOvernight();
}
| 04900db4-rob | src/org/rapla/facade/CalendarOptions.java | Java | gpl3 | 2,102 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.HashMap;
import java.util.Map;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
public class AllocationChangeEvent
{
static Map<String,Type> TYPES = new HashMap<String,Type>();
public static class Type
{
private String type;
Type( String type )
{
TYPES.put( type, this );
this.type = type;
}
public String toString()
{
return type;
}
}
Type m_type;
public static Type CHANGE = new Type( "change" );
public static Type ADD = new Type( "add" );
public static Type REMOVE = new Type( "remove" );
User m_user;
Reservation m_newReservation;
Allocatable m_allocatable;
Appointment m_newAppointment;
Appointment m_oldAppointment;
public AllocationChangeEvent( Type type, User user, Reservation newReservation, Allocatable allocatable,
Appointment appointment )
{
m_user = user;
m_type = type;
m_allocatable = allocatable;
if ( type.equals( REMOVE ) )
m_oldAppointment = appointment;
m_newAppointment = appointment;
m_newReservation = newReservation;
}
public AllocationChangeEvent( User user, Reservation newReservation, Allocatable allocatable,
Appointment newAppointment, Appointment oldApp )
{
this( CHANGE, user, newReservation, allocatable, newAppointment );
m_oldAppointment = oldApp;
}
/** either Type.CHANGE,Type.REMOVE or Type.ADD */
public Type getType()
{
return m_type;
}
/** returns the user-object, of the user that made the change.
* <strong>Warning can be null</strong>
*/
public User getUser()
{
return m_user;
}
public Allocatable getAllocatable()
{
return m_allocatable;
}
public Appointment getNewAppointment()
{
return m_newAppointment;
}
public Reservation getNewReservation()
{
return m_newReservation;
}
/** only available if type is "change" */
public Appointment getOldAppointment()
{
return m_oldAppointment;
}
}
| 04900db4-rob | src/org/rapla/facade/AllocationChangeEvent.java | Java | gpl3 | 3,262 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.EventListener;
/** After a store all registered ChangeListeners get notified by calling
* the trigger method. A list with all changes is passed.
* At the moment only AllocationChangeEvents are triggered.
* By this you can get notified, when any Reservation changes.
* The difference between the UpdateEvent and a ChangeEvent is,
* that the UpdateEvent contains the new Versions of all updated enties,
* while a ChangeEvent contains Information about a single change.
* That change can be calculated as with the AllocationChangeEvent, which
* represents a single allocation change for one allocatable object
* ,including information about the old allocation and the new one.
* @see AllocationChangeEvent
*/
public interface AllocationChangeListener extends EventListener
{
void changed(AllocationChangeEvent[] changeEvents);
}
| 04900db4-rob | src/org/rapla/facade/AllocationChangeListener.java | Java | gpl3 | 1,832 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import org.rapla.storage.StorageOperator;
/** A collection of all module-interfaces
*/
public interface ClientFacade
extends
UserModule
,ModificationModule
,QueryModule
,UpdateModule
{
StorageOperator getOperator();
}
| 04900db4-rob | src/org/rapla/facade/ClientFacade.java | Java | gpl3 | 1,203 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
public interface UpdateModule
{
public final static TypedComponentRole<Integer> REFRESH_INTERVAL_ENTRY = new TypedComponentRole<Integer>("org.rapla.refreshInterval");
public final static TypedComponentRole<Integer> ARCHIVE_AGE = new TypedComponentRole<Integer>("org.rapla.archiveAge");
public static final int REFRESH_INTERVAL_DEFAULT = 30000;
/**
* Refreshes the data that is in the cache (or on the client)
and notifies all registered {@link ModificationListener ModificationListeners}
with an update-event.
There are two types of refreshs.
<ul>
<li>Incremental Refresh: Only the changes are propagated</li>
<li>Full Refresh: The complete data is reread. (Currently disabled in Rapla)</li>
</ul>
<p>
Incremental refreshs are the normal case if you have a client server basis.
(In a single user system no refreshs are necessary at all).
The refreshs are triggered in defined intervals if you use the webbased communication
and automaticaly if you use the old communication layer. You can change the refresh interval
via the admin options.
</p>
<p>
Of course you can call a refresh anytime you want to synchronize with the server, e.g. if
you want to ensure you are uptodate before editing. If you are on the server you dont need to refresh.
</p>
<strong>WARNING: When using full refresh on a local file storage
all information will be changed. So use it
only if you modify the data from external.
You better re-get and re-draw all
the information in the Frontend after a full refresh.
</strong>
*/
void refresh() throws RaplaException;
/** returns if the Facade is connected through a server (false if it has a local store)*/
boolean isClientForServer();
/**
* registers a new ModificationListener.
* A ModifictionEvent will be fired to every registered DateChangeListener
* when one or more entities have been added, removed or changed
* @see ModificationListener
* @see ModificationEvent
*/
void addModificationListener(ModificationListener listener);
void removeModificationListener(ModificationListener listener);
void addUpdateErrorListener(UpdateErrorListener listener);
void removeUpdateErrorListener(UpdateErrorListener listener);
void addAllocationChangedListener(AllocationChangeListener triggerListener);
void removeAllocationChangedListener(AllocationChangeListener triggerListener);
}
| 04900db4-rob | src/org/rapla/facade/UpdateModule.java | Java | gpl3 | 3,705 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import org.rapla.framework.RaplaException;
/** Classes implementing this interface will be notified when an update error
* occurred. The listener can be registered by calling
* <code>addUpdateErrorListener</code> of the <code>UpdateModule</code> <br>
* Don't forget to remove the listener by calling <code>removeUpdateErrorLister</code>
* when no longer need.
* @author Christopher Kohlhaas
* @see UpdateModule
*/
public interface UpdateErrorListener {
/** this notifies all listeners that the update of the data has
caused an error. A normal source for UpdateErrors is a broken
connection to the server.
*/
void updateError(RaplaException ex);
void disconnected(String message);
}
| 04900db4-rob | src/org/rapla/facade/UpdateErrorListener.java | Java | gpl3 | 1,698 |
<body>
<p>This package contains the facade, that encapsulate the storage and the entitie package and
provides a simple interface for accessing the rapla-system; Study this package to get a good summary of the functionality of Rapla. </p>
</body>
| 04900db4-rob | src/org/rapla/facade/package.html | HTML | gpl3 | 249 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.framework.RaplaException;
public interface ClassifiableFilter
{
ClassificationFilter[] getReservationFilter() throws RaplaException ;
ClassificationFilter[] getAllocatableFilter() throws RaplaException ;
boolean isDefaultEventTypes();
boolean isDefaultResourceTypes();
}
| 04900db4-rob | src/org/rapla/facade/ClassifiableFilter.java | Java | gpl3 | 1,333 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import org.rapla.entities.Entity;
import org.rapla.entities.Named;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
/**
* A conflict is the allocation of the same resource at the same time by different
* reservations. There's one conflict for each resource and each overlapping of
* two allocations. So if there are 3 reservations that allocate the same 2 resources
* on 2 days of the week, then we got ( 3 * 2 ) * 2 * 2 = 24 conflicts. Thats
* 3 reservations, each conflicting with two other 2 reservations on 2 days with 2 resources.
*
* @version 1.0
* @author Christopher Kohlhaas
*/
public interface Conflict extends Named, Entity<Conflict>
{
static public final RaplaType<Conflict> TYPE = new RaplaType<Conflict>(Conflict.class,"conflict");
/** @return the allocatable, allocated for the same time by two different reservations. */
public Allocatable getAllocatable();
// /** @return the first Reservation, that is involved in the conflict.*/
// public Reservation getReservation1();
/** The appointment of the first reservation, that causes the conflict. */
public String getAppointment1();
// /** @return the second Reservation, that is involved in the conflict.*/
// public Reservation getReservation2();
// /** @return The User, who created the second Reservation.*/
// public User getUser2();
/** The appointment of the second reservation, that causes the conflict. */
public String getAppointment2();
String getReservation1();
String getReservation2();
String getReservation1Name();
String getReservation2Name();
///** Find the first occurance of a conflict in the specified interval or null when not in intervall*/
//public Date getFirstConflictDate(final Date fromDate, final Date toDate);
//public boolean canModify(User user);
public boolean isOwner( User user);
public static final Conflict[] CONFLICT_ARRAY= new Conflict[] {};
public class Util
{
public static Collection<Allocatable> getAllocatables(
Collection<Conflict> conflictsSelected) {
LinkedHashSet<Allocatable> allocatables = new LinkedHashSet<Allocatable>();
for ( Conflict conflict: conflictsSelected)
{
allocatables.add(conflict.getAllocatable());
}
return allocatables;
}
// static public List<Reservation> getReservations(Collection<Conflict> conflicts) {
// Collection<Reservation> reservations = new LinkedHashSet<Reservation>();
// for (Conflict conflict:conflicts)
// {
// reservations.add(conflict.getReservation1());
// reservations.add(conflict.getReservation2());
//
// }
// return new ArrayList<Reservation>( reservations);
// }
//
}
boolean hasAppointment(Appointment appointment);
//boolean endsBefore(Date date);
Date getStartDate();
}
| 04900db4-rob | src/org/rapla/facade/Conflict.java | Java | gpl3 | 4,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.facade;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.components.xmlbundle.CompoundI18n;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.Annotatable;
import org.rapla.entities.Category;
import org.rapla.entities.Named;
import org.rapla.entities.Ownable;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.configuration.internal.PreferencesImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentFormater;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.RaplaObjectAnnotations;
import org.rapla.entities.domain.ReservationStartComparator;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.Classifiable;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ConstraintIds;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.facade.internal.CalendarOptionsImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.RaplaSynchronizationException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.framework.logger.ConsoleLogger;
import org.rapla.framework.logger.Logger;
/**
Base class for most components. Eases
access to frequently used services, e.g. {@link I18nBundle}.
*/
public class RaplaComponent
{
public static final TypedComponentRole<I18nBundle> RAPLA_RESOURCES = new TypedComponentRole<I18nBundle>("org.rapla.RaplaResources");
public static final TypedComponentRole<RaplaConfiguration> PLUGIN_CONFIG= new TypedComponentRole<RaplaConfiguration>("org.rapla.plugin");
private final ClientServiceManager serviceManager;
private TypedComponentRole<I18nBundle> childBundleName;
private Logger logger;
private RaplaContext context;
public RaplaComponent(RaplaContext context) {
try {
logger = context.lookup(Logger.class );
} catch (RaplaContextException e) {
logger = new ConsoleLogger();
}
this.context = context;
this.serviceManager = new ClientServiceManager();
}
protected void setLogger(Logger logger)
{
this.logger = logger;
}
final public TypedComponentRole<I18nBundle> getChildBundleName() {
return childBundleName;
}
final public void setChildBundleName(TypedComponentRole<I18nBundle> childBundleName) {
this.childBundleName = childBundleName;
}
final protected Container getContainer() throws RaplaContextException {
return getContext().lookup(Container.class);
}
/** returns if the session user is admin */
final public boolean isAdmin() {
try {
return getUser().isAdmin();
} catch (RaplaException ex) {
}
return false;
}
/** returns if the session user is a registerer */
final public boolean isRegisterer() {
if (isAdmin())
{
return true;
}
try {
Category registererGroup = getQuery().getUserGroupsCategory().getCategory(Permission.GROUP_REGISTERER_KEY);
return getUser().belongsTo(registererGroup);
} catch (RaplaException ex) {
}
return false;
}
final public boolean isModifyPreferencesAllowed() {
if (isAdmin())
{
return true;
}
try {
Category modifyPreferences = getQuery().getUserGroupsCategory().getCategory(Permission.GROUP_MODIFY_PREFERENCES_KEY);
if ( modifyPreferences == null ) {
return true;
}
return getUser().belongsTo(modifyPreferences);
} catch (RaplaException ex) {
}
return false;
}
/** returns if the user has allocation rights for one or more resource */
final public boolean canUserAllocateSomething(User user) throws RaplaException {
Allocatable[] allocatables =getQuery().getAllocatables();
if ( user.isAdmin() )
return true;
if (!canCreateReservation(user))
{
return false;
}
for ( int i=0;i<allocatables.length;i++) {
Permission[] permissions = allocatables[i].getPermissions();
for ( int j=0;j<permissions.length;j++) {
Permission p = permissions[j];
if (!p.affectsUser( user ))
{
continue;
}
if ( p.getAccessLevel() > Permission.READ)
{
return true;
}
}
}
return false;
}
final public boolean canCreateReservation(User user) {
boolean result = getQuery().canCreateReservations(user);
return result;
}
final public boolean canCreateReservation() {
try {
User user = getUser();
return canCreateReservation( user);
} catch (RaplaException ex) {
return false;
}
}
protected boolean canAllocate()
{
CalendarSelectionModel model = getService( CalendarSelectionModel.class);
//Date start, Date end,
Collection<Allocatable> allocatables = getService(CalendarSelectionModel.class).getMarkedAllocatables();
boolean canAllocate = true;
Date start = getStartDate( model);
Date end = getEndDate( model, start);
for (Allocatable allo:allocatables)
{
if (!canAllocate( start, end, allo))
{
canAllocate = false;
}
}
return canAllocate;
}
protected Date getStartDate(CalendarModel model) {
Collection<TimeInterval> markedIntervals = model.getMarkedIntervals();
Date startDate = null;
if ( markedIntervals.size() > 0)
{
TimeInterval first = markedIntervals.iterator().next();
startDate = first.getStart();
}
if ( startDate != null)
{
return startDate;
}
Date selectedDate = model.getSelectedDate();
if ( selectedDate == null)
{
selectedDate = getQuery().today();
}
Date time = new Date (DateTools.MILLISECONDS_PER_MINUTE * getCalendarOptions().getWorktimeStartMinutes());
startDate = getRaplaLocale().toDate(selectedDate,time);
return startDate;
}
protected Date getEndDate( CalendarModel model,Date startDate) {
Collection<TimeInterval> markedIntervals = model.getMarkedIntervals();
Date endDate = null;
if ( markedIntervals.size() > 0)
{
TimeInterval first = markedIntervals.iterator().next();
endDate = first.getEnd();
}
if ( endDate != null)
{
return endDate;
}
return new Date(startDate.getTime() + DateTools.MILLISECONDS_PER_HOUR);
}
protected boolean canAllocate(Date start, Date end, Allocatable allocatables) {
if ( allocatables == null) {
return true;
}
try {
User user = getUser();
Date today = getQuery().today();
return allocatables.canAllocate( user, start, end, today );
} catch (RaplaException ex) {
return false;
}
}
/** returns if the current user is allowed to modify the object. */
final public boolean canModify(Object object) {
try {
User user = getUser();
return canModify(object, user);
} catch (RaplaException ex) {
return false;
}
}
static public boolean canModify(Object object, User user) {
if (object == null || !(object instanceof RaplaObject))
{
return false;
}
if ( user == null)
{
return false;
}
if (user.isAdmin())
return true;
if (object instanceof Ownable) {
Ownable ownable = (Ownable) object;
User owner = ownable.getOwner();
if ( owner != null && user.equals(owner))
{
return true;
}
if (object instanceof Allocatable) {
Allocatable allocatable = (Allocatable) object;
if (allocatable.canModify( user ))
{
return true;
}
if ( owner == null)
{
Category[] groups = user.getGroups();
for ( Category group: groups)
{
if (group.getKey().equals(Permission.GROUP_REGISTERER_KEY))
{
return true;
}
}
}
}
}
if (checkClassifiableModifyPermissions(object, user))
{
return true;
}
return false;
}
public boolean canRead(Appointment appointment,User user)
{
Reservation reservation = appointment.getReservation();
boolean canReadReservationsFromOthers = getQuery().canReadReservationsFromOthers( user);
boolean result = canRead(reservation, user, canReadReservationsFromOthers);
return result;
}
static public boolean canRead(Reservation reservation,User user, boolean canReadReservationsFromOthers)
{
if ( user == null)
{
return true;
}
if ( canModify(reservation, user))
{
return true;
}
if ( !canReadReservationsFromOthers)
{
return false;
}
if (checkClassifiablerReadPermissions(reservation, user))
{
return true;
}
return false;
}
static public boolean canRead(Allocatable allocatable, User user) {
if ( canModify(allocatable, user))
{
return true;
}
if (checkClassifiablerReadPermissions(allocatable, user))
{
return true;
}
return false;
}
/** We check if an attribute with the permission_modify exists and look if the permission is set either globally (if boolean type is used) or for a specific user group (if category type is used)*/
public static boolean checkClassifiableModifyPermissions(Object object,
User user) {
return checkClassifiablePermissions(object, user, ReservationImpl.PERMISSION_MODIFY, false);
}
public static boolean checkClassifiablerReadPermissions(
Object object, User user) {
return checkClassifiablePermissions(object, user, ReservationImpl.PERMISSION_READ, true);
}
static Category dummyCategory = new CategoryImpl(new Date(), new Date());
// The dummy category is used if no permission attribute is found. Use permissionNotFoundReturns to set whether this means permssion granted or not
private static boolean checkClassifiablePermissions(Object object, User user, String permissionKey, boolean permssionNotFoundReturnsYesCategory) {
Collection<Category> cat = getPermissionGroups(object, dummyCategory,permissionKey, permssionNotFoundReturnsYesCategory);
if ( cat == null)
{
return false;
}
if ( cat.size() == 1 && cat.iterator().next() == dummyCategory)
{
return true;
}
for (Category c: cat)
{
if (user.belongsTo( c) )
{
return true;
}
}
return false;
}
/** returns the group that is has the requested permission on the object
**/
public static Collection<Category> getPermissionGroups(Object object, Category yesCategory, String permissionKey, boolean permssionNotFoundReturnsYesCategory)
{
if (object instanceof Classifiable ) {
final Classifiable classifiable = (Classifiable) object;
Classification classification = classifiable.getClassification();
if ( classification != null)
{
final DynamicType type = classification.getType();
final Attribute attribute = type.getAttribute(permissionKey);
if ( attribute != null)
{
return getPermissionGroups(classification, yesCategory, attribute);
}
else
{
if ( permssionNotFoundReturnsYesCategory && yesCategory != null)
{
return Collections.singleton(yesCategory);
}
else
{
return null;
}
}
}
}
return null;
}
private static Collection<Category> getPermissionGroups(Classification classification,
Category yesCategory, final Attribute attribute) {
final AttributeType type2 = attribute.getType();
if (type2 == AttributeType.BOOLEAN)
{
final Object value = classification.getValue( attribute);
if (Boolean.TRUE.equals(value))
{
return Collections.singleton(yesCategory);
}
else
{
return null;
}
}
if ( type2 == AttributeType.CATEGORY)
{
Collection<?> values = classification.getValues( attribute);
@SuppressWarnings("unchecked")
Collection<Category> cat = (Collection<Category>) values;
if ( cat == null || cat.size() == 0)
{
Category rootCat = (Category)attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY);
if ( rootCat.getCategories().length == 0)
{
cat = Collections.singleton(rootCat);
}
}
return cat;
}
return null;
}
public CalendarOptions getCalendarOptions() {
User user;
try
{
user = getUser();
}
catch (RaplaException ex) {
// Use system settings if an error occurs
user = null;
}
return getCalendarOptions( user);
}
protected CalendarOptions getCalendarOptions(User user) {
RaplaConfiguration conf = null;
try {
if ( user != null)
{
conf = getQuery().getPreferences( user ).getEntry(CalendarOptionsImpl.CALENDAR_OPTIONS);
}
if ( conf == null)
{
conf = getQuery().getPreferences( null ).getEntry(CalendarOptionsImpl.CALENDAR_OPTIONS);
}
if ( conf != null)
{
return new CalendarOptionsImpl( conf );
}
} catch (RaplaException ex) {
}
return getService( CalendarOptions.class);
}
protected User getUser() throws RaplaException {
return getUserModule().getUser();
}
protected Logger getLogger() {
return logger;
}
/** lookup the service in the serviceManager under the specified key:
serviceManager.lookup(role).
@throws IllegalStateException if GUIComponent wasn't serviced. No service method called
@throws UnsupportedOperationException if service not available.
*/
protected <T> T getService(Class<T> role) {
try {
return context.lookup( role);
} catch (RaplaContextException e) {
throw serviceExcption(role, e);
}
}
protected UnsupportedOperationException serviceExcption(Object role, RaplaContextException e) {
return new UnsupportedOperationException("Service not supported in this context: " + role, e);
}
protected <T> T getService(TypedComponentRole<T> role) {
try {
return context.lookup(role);
} catch (RaplaContextException e) {
throw serviceExcption(role, e);
}
}
protected RaplaContext getContext() {
return context;
}
/** lookup RaplaLocale from the context */
protected RaplaLocale getRaplaLocale() {
if (serviceManager.raplaLocale == null)
serviceManager.raplaLocale = getService(RaplaLocale.class);
return serviceManager.raplaLocale;
}
protected Locale getLocale() {
return getRaplaLocale().getLocale();
}
protected I18nBundle childBundle;
/** lookup I18nBundle from the serviceManager */
protected I18nBundle getI18n() {
TypedComponentRole<I18nBundle> childBundleName = getChildBundleName();
if ( childBundleName != null) {
if ( childBundle == null) {
I18nBundle pluginI18n = getService(childBundleName );
childBundle = new CompoundI18n(pluginI18n,getI18nDefault());
}
return childBundle;
}
return getI18nDefault();
}
private I18nBundle getI18nDefault() {
if (serviceManager.i18n == null)
serviceManager.i18n = getService(RaplaComponent.RAPLA_RESOURCES);
return serviceManager.i18n;
}
/** lookup AppointmentFormater from the serviceManager */
protected AppointmentFormater getAppointmentFormater() {
if (serviceManager.appointmentFormater == null)
serviceManager.appointmentFormater = getService(AppointmentFormater.class);
return serviceManager.appointmentFormater;
}
/** lookup PeriodModel from the serviceManager */
protected PeriodModel getPeriodModel() {
try {
return getQuery().getPeriodModel();
} catch (RaplaException ex) {
throw new UnsupportedOperationException("Service not supported in this context: " );
}
}
/** lookup QueryModule from the serviceManager */
protected QueryModule getQuery() {
return getClientFacade();
}
final protected ClientFacade getClientFacade() {
if (serviceManager.facade == null)
serviceManager.facade = getService( ClientFacade.class );
return serviceManager.facade;
}
/** lookup ModificationModule from the serviceManager */
protected ModificationModule getModification() {
return getClientFacade();
}
/** lookup UpdateModule from the serviceManager */
protected UpdateModule getUpdateModule() {
return getClientFacade();
}
/** lookup UserModule from the serviceManager */
protected UserModule getUserModule() {
return getClientFacade();
}
/** returns a translation for the object name into the selected language. If
a translation into the selected language is not possible an english translation will be tried next.
If theres no translation for the default language, the first available translation will be used. */
public String getName(Object object) {
if (object == null)
return "";
if (object instanceof Named) {
String name = ((Named) object).getName(getI18n().getLocale());
return (name != null) ? name : "";
}
return object.toString();
}
/** calls getI18n().getString(key) */
final public String getString(String key) {
return getI18n().getString(key);
}
/** calls "<html>" + getI18n().getString(key) + "</html>"*/
final public String getStringAsHTML(String key) {
return "<html>" + getI18n().getString(key) + "</html>";
}
private static class ClientServiceManager {
I18nBundle i18n;
ClientFacade facade;
RaplaLocale raplaLocale;
AppointmentFormater appointmentFormater;
}
final public Preferences newEditablePreferences() throws RaplaException {
Preferences preferences = getQuery().getPreferences();
ModificationModule modification = getModification();
return modification.edit(preferences);
}
/** @deprecated demand webservice in constructor instead*/
@Deprecated
final public <T> T getWebservice(Class<T> a) throws RaplaException
{
org.rapla.storage.dbrm.RemoteServiceCaller remote = getService( org.rapla.storage.dbrm.RemoteServiceCaller.class);
return remote.getRemoteMethod(a);
}
@Deprecated
public Configuration getPluginConfig(String pluginClassName) throws RaplaException
{
Preferences systemPreferences = getQuery().getSystemPreferences();
return ((PreferencesImpl)systemPreferences).getOldPluginConfig(pluginClassName);
}
public static boolean isTemplate(RaplaObject<?> obj)
{
if ( obj instanceof Appointment)
{
obj = ((Appointment) obj).getReservation();
}
if ( obj instanceof Annotatable)
{
String template = ((Annotatable)obj).getAnnotation( RaplaObjectAnnotations.KEY_TEMPLATE);
return template != null;
}
return false;
}
protected List<Reservation> copy(Collection<Reservation> toCopy, Date beginn) throws RaplaException
{
List<Reservation> sortedReservations = new ArrayList<Reservation>( toCopy);
Collections.sort( sortedReservations, new ReservationStartComparator(getLocale()));
List<Reservation> copies = new ArrayList<Reservation>();
Date firstStart = null;
for (Reservation reservation: sortedReservations) {
if ( firstStart == null )
{
firstStart = ReservationStartComparator.getStart( reservation);
}
Reservation copy = copy(reservation, beginn, firstStart);
copies.add( copy);
}
return copies;
}
public Reservation copyAppointment(Reservation reservation, Date beginn) throws RaplaException
{
Date firstStart = ReservationStartComparator.getStart( reservation);
Reservation copy = copy(reservation, beginn, firstStart);
return copy;
}
private Reservation copy(Reservation reservation, Date destStart,Date firstStart) throws RaplaException {
Reservation r = getModification().clone( reservation);
Appointment[] appointments = r.getAppointments();
for ( Appointment app :appointments) {
Repeating repeating = app.getRepeating();
Date oldStart = app.getStart();
// we need to calculate an offset so that the reservations will place themself relativ to the first reservation in the list
long offset = DateTools.countDays( firstStart, oldStart) * DateTools.MILLISECONDS_PER_DAY;
Date newStart ;
Date destWithOffset = new Date(destStart.getTime() + offset );
newStart = getRaplaLocale().toDate( destWithOffset , oldStart );
app.move( newStart) ;
if (repeating != null)
{
Date[] exceptions = repeating.getExceptions();
repeating.clearExceptions();
for (Date exc: exceptions)
{
long days = DateTools.countDays(oldStart, exc);
Date newDate = DateTools.addDays(newStart, days);
repeating.addException( newDate);
}
if ( !repeating.isFixedNumber())
{
Date oldEnd = repeating.getEnd();
if ( oldEnd != null)
{
// If we don't have and endig destination, just make the repeating to the original length
long days = DateTools.countDays(oldStart, oldEnd);
Date end = DateTools.addDays(newStart, days);
repeating.setEnd( end);
}
}
}
}
return r;
}
public static void unlock(Lock lock)
{
if ( lock != null)
{
lock.unlock();
}
}
public static Lock lock(Lock lock, int seconds) throws RaplaException {
try
{
if ( lock.tryLock())
{
return lock;
}
if (lock.tryLock(seconds, TimeUnit.SECONDS))
{
return lock;
}
else
{
throw new RaplaSynchronizationException("Someone is currently writing. Please try again! Can't acquire lock " + lock );
}
}
catch (InterruptedException ex)
{
throw new RaplaSynchronizationException( ex);
}
}
}
| 04900db4-rob | src/org/rapla/facade/RaplaComponent.java | Java | gpl3 | 25,165 |
package org.rapla.facade;
import java.util.Collection;
import java.util.Date;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.framework.RaplaException;
public interface CalendarSelectionModel extends CalendarModel{
String getTitle();
void setTitle(String title);
void setViewId(String viewId);
String getViewId();
void setSelectedObjects(Collection<? extends Object> selectedObjects);
void setOption( String name, String string );
void selectUser( User user );
/** If show only own reservations is selected. Thats if the current user is selected with select User*/
boolean isOnlyCurrentUserSelected();
void setReservationFilter(ClassificationFilter[] array);
void setAllocatableFilter(ClassificationFilter[] filters);
public void resetExports();
public void save(final String filename) throws RaplaException;
public void load(final String filename) throws RaplaException, EntityNotFoundException, CalendarNotFoundExeption;
CalendarSelectionModel clone();
void setMarkedIntervals(Collection<TimeInterval> timeIntervals);
/** calls setMarkedIntervals with a single interval from start to end*/
void markInterval(Date start, Date end);
void setMarkedAllocatables(Collection<Allocatable> allocatable);
/** CalendarModels do not update automatically but need to be notified on changes from the outside*/
void dataChanged(ModificationEvent evt) throws RaplaException;
} | 04900db4-rob | src/org/rapla/facade/CalendarSelectionModel.java | Java | gpl3 | 1,653 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.Date;
import java.util.List;
import org.rapla.entities.domain.Period;
/** ListModel that contains all periods. Updates the list automatically if a period is added, changed or deleted.
* */
public interface PeriodModel
{
/** returns the first matching period or null if no period matches.*/
public Period getPeriodFor(Date date);
public Period getNearestPeriodForDate(Date date);
public Period getNearestPeriodForStartDate(Date date);
public Period getNearestPeriodForStartDate(Date date, Date endDate);
public Period getNearestPeriodForEndDate(Date date);
/** return all matching periods.*/
public List<Period> getPeriodsFor(Date date);
public int getSize();
public Period[] getAllPeriods();
}
| 04900db4-rob | src/org/rapla/facade/PeriodModel.java | Java | gpl3 | 1,722 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.Set;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaType;
/** Encapsulate the changes that are made in the backend-store.*/
public interface ModificationEvent
{
/** returns if the objects has changed.*/
boolean hasChanged(Entity object);
/** returns if the objects was removed.*/
boolean isRemoved(Entity object);
/** returns if the objects has changed or was removed.*/
boolean isModified(Entity object);
/** returns if any object of the specified type has changed or was removed.*/
boolean isModified(RaplaType raplaType);
/** returns all removed objects .*/
Set<Entity> getRemoved();
/** returns all changed object .*/
Set<Entity> getChanged();
Set<Entity> getAddObjects();
TimeInterval getInvalidateInterval();
boolean isModified();
}
| 04900db4-rob | src/org/rapla/facade/ModificationEvent.java | Java | gpl3 | 1,868 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.EventListener;
import org.rapla.framework.RaplaException;
/** Classes implementing this interface will be notified when changes to
* reservations or resources occurred. The listener can be registered by calling
* <code>addModificationListener</code> of the <code>UpdateModule</code> <br>
* Don't forget to remove the listener by calling <code>removeModificationLister</code>
* when no longer needed.
* @author Christopher Kohlhaas
* @see UpdateModule
* @see ModificationEvent
*/
public interface ModificationListener extends EventListener {
/** this notifies all listeners that data in the rapla-backend has changed.
* The {@link ModificationEvent} describes these changes.
*/
void dataChanged(ModificationEvent evt) throws RaplaException;
}
| 04900db4-rob | src/org/rapla/facade/ModificationListener.java | Java | gpl3 | 1,765 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.rapla.components.util.CommandScheduler;
import org.rapla.components.util.IOUtil;
import org.rapla.components.util.xml.RaplaNonValidatedInput;
import org.rapla.components.xmlbundle.CompoundI18n;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.LocaleSelector;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.entities.domain.AppointmentFormater;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.facade.CalendarOptions;
import org.rapla.facade.RaplaComponent;
import org.rapla.facade.internal.CalendarOptionsImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.Provider;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaDefaultContext;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.ServiceListCreator;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.TypedComponentRole;
import org.rapla.framework.internal.ComponentInfo;
import org.rapla.framework.internal.ConfigTools;
import org.rapla.framework.internal.ContainerImpl;
import org.rapla.framework.internal.RaplaJDKLoggingAdapter;
import org.rapla.framework.internal.RaplaLocaleImpl;
import org.rapla.framework.internal.RaplaMetaConfigInfo;
import org.rapla.framework.logger.Logger;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.rest.gwtjsonrpc.common.ResultImpl;
import org.rapla.storage.dbrm.RaplaConnectException;
import org.rapla.storage.dbrm.RaplaHTTPConnector;
import org.rapla.storage.dbrm.RemoteConnectionInfo;
import org.rapla.storage.dbrm.RemoteMethodStub;
import org.rapla.storage.dbrm.RemoteServiceCaller;
import org.rapla.storage.dbrm.StatusUpdater;
import org.rapla.storage.dbrm.StatusUpdater.Status;
/**
The Rapla Main Container class for the basic container for Rapla specific services and the rapla plugin architecture.
The rapla container has only one instance at runtime. Configuration of the RaplaMainContainer is done in the rapla*.xconf
files. Typical configurations of the MainContainer are
<ol>
<li>Client: A ClientContainerService, one facade and a remote storage ( automaticaly pointing to the download server in webstart mode)</li>
<li>Server: A ServerContainerService (providing a facade) a messaging server for handling the connections with the clients, a storage (file or db) and an extra service for importing and exporting in the db</li>
<li>Standalone: A ClientContainerService (with preconfigured auto admin login) and a ServerContainerService that is directly connected to the client without http communication.</li>
<li>Embedded: Configuration example follows.</li>
</ol>
<p>
Configuration of the main container is usually done via the raplaserver.xconf
</p>
<p>
The Main Container provides the following Services to all RaplaComponents
<ul>
<li>I18nBundle</li>
<li>AppointmentFormater</li>
<li>RaplaLocale</li>
<li>LocaleSelector</li>
<li>RaplaMainContainer.PLUGIN_LIST (A list of all available plugins)</li>
</ul>
</p>
@see I18nBundle
@see RaplaLocale
@see AppointmentFormater
@see LocaleSelector
*/
final public class RaplaMainContainer extends ContainerImpl
{
public static final TypedComponentRole<Configuration> RAPLA_MAIN_CONFIGURATION = new TypedComponentRole<Configuration>("org.rapla.MainConfiguration");
public static final TypedComponentRole<String> DOWNLOAD_SERVER = new TypedComponentRole<String>("download-server");
public static final TypedComponentRole<URL> DOWNLOAD_URL = new TypedComponentRole<URL>("download-url");
public static final TypedComponentRole<String> ENV_RAPLADATASOURCE = new TypedComponentRole<String>("env.rapladatasource");
public static final TypedComponentRole<String> ENV_RAPLAFILE = new TypedComponentRole<String>("env.raplafile");
public static final TypedComponentRole<Object> ENV_RAPLADB= new TypedComponentRole<Object>("env.rapladb");
public static final TypedComponentRole<Object> ENV_RAPLAMAIL= new TypedComponentRole<Object>("env.raplamail");
public static final TypedComponentRole<Boolean> ENV_DEVELOPMENT = new TypedComponentRole<Boolean>("env.development");
public static final TypedComponentRole<Object> TIMESTAMP = new TypedComponentRole<Object>("timestamp");
public static final TypedComponentRole<String> CONTEXT_ROOT = new TypedComponentRole<String>("context-root");
public final static TypedComponentRole<Set<String>> PLUGIN_LIST = new TypedComponentRole<Set<String>>("plugin-list");
public final static TypedComponentRole<String> TITLE = new TypedComponentRole<String>("org.rapla.title");
public final static TypedComponentRole<String> TIMEZONE = new TypedComponentRole<String>("org.rapla.timezone");
Logger callLogger;
public RaplaMainContainer() throws Exception {
this(new RaplaStartupEnvironment());
}
public RaplaMainContainer(StartupEnvironment env) throws Exception {
this( env, new RaplaDefaultContext() );
}
public RaplaMainContainer( StartupEnvironment env, RaplaContext context) throws Exception
{
this( env,context,createRaplaLogger());
}
RemoteConnectionInfo globalConnectInfo;
CommandScheduler commandQueue;
public RaplaMainContainer( StartupEnvironment env, RaplaContext context,Logger logger) throws Exception{
super( context, env.getStartupConfiguration(),logger );
addContainerProvidedComponentInstance( StartupEnvironment.class, env);
addContainerProvidedComponentInstance( DOWNLOAD_SERVER, env.getDownloadURL().getHost());
addContainerProvidedComponentInstance( DOWNLOAD_URL, env.getDownloadURL());
commandQueue = createCommandQueue();
addContainerProvidedComponentInstance( CommandScheduler.class, commandQueue);
addContainerProvidedComponentInstance( RemoteServiceCaller.class, new RemoteServiceCaller() {
@Override
public <T> T getRemoteMethod(Class<T> a) throws RaplaContextException {
return RaplaMainContainer.this.getRemoteMethod(getContext(), a);
}
} );
if (env.getContextRootURL() != null)
{
File file = IOUtil.getFileFrom( env.getContextRootURL());
addContainerProvidedComponentInstance( CONTEXT_ROOT, file.getPath());
}
addContainerProvidedComponentInstance( TIMESTAMP, new Object() {
public String toString() {
DateFormat formatter = new SimpleDateFormat("yyyyMMdd-HHmmss");
String formatNow = formatter.format(new Date());
return formatNow;
}
});
initialize();
}
private static Logger createRaplaLogger()
{
Logger logger;
try {
RaplaMainContainer.class.getClassLoader().loadClass("org.slf4j.Logger");
@SuppressWarnings("unchecked")
Provider<Logger> logManager = (Provider<Logger>) RaplaMainContainer.class.getClassLoader().loadClass("org.rapla.framework.internal.Slf4jAdapter").newInstance();
logger = logManager.get();
logger.info("Logging via SLF4J API.");
} catch (Throwable e1) {
Provider<Logger> logManager = new RaplaJDKLoggingAdapter( );
logger = logManager.get();
logger.info("Logging via java.util.logging API. " + e1.toString());
}
return logger;
}
protected Map<String,ComponentInfo> getComponentInfos() {
return new RaplaMetaConfigInfo();
}
private void initialize() throws Exception {
Logger logger = getLogger();
int startupMode = getStartupEnvironment().getStartupMode();
logger.debug("----------- Rapla startup mode = " + startupMode);
RaplaLocaleImpl raplaLocale = new RaplaLocaleImpl(m_config.getChild("locale"), logger);
Configuration localeConfig = m_config.getChild("locale");
CalendarOptions calendarOptions = new CalendarOptionsImpl(localeConfig);
addContainerProvidedComponentInstance( CalendarOptions.class, calendarOptions );
addContainerProvidedComponentInstance( RAPLA_MAIN_CONFIGURATION, m_config );
addContainerProvidedComponent( RaplaNonValidatedInput.class, ConfigTools.RaplaReaderImpl.class);
// Startup mode= EMBEDDED = 0, CONSOLE = 1, WEBSTART = 2, APPLET = 3, SERVLET = 4
addContainerProvidedComponentInstance( RaplaLocale.class,raplaLocale);
addContainerProvidedComponentInstance( LocaleSelector.class,raplaLocale.getLocaleSelector());
m_config.getChildren("rapla-client");
String defaultBundleName = m_config.getChild("default-bundle").getValue( null);
// Override the intern Resource Bundle with user provided
Configuration parentConfig = I18nBundleImpl.createConfig( RaplaComponent.RAPLA_RESOURCES.getId() );
if ( defaultBundleName!=null) {
I18nBundleImpl i18n = new I18nBundleImpl( getContext(), I18nBundleImpl.createConfig( defaultBundleName ), logger);
String parentId = i18n.getParentId();
if ( parentId != null && parentId.equals(RaplaComponent.RAPLA_RESOURCES.getId()))
{
I18nBundleImpl parent = new I18nBundleImpl( getContext(), parentConfig, logger);
I18nBundle compound = new CompoundI18n( i18n, parent);
addContainerProvidedComponentInstance(RaplaComponent.RAPLA_RESOURCES, compound);
}
else
{
addContainerProvidedComponent(RaplaComponent.RAPLA_RESOURCES,I18nBundleImpl.class, parentConfig);
}
}
else
{
addContainerProvidedComponent(RaplaComponent.RAPLA_RESOURCES,I18nBundleImpl.class, parentConfig);
}
addContainerProvidedComponentInstance( AppointmentFormater.class, new AppointmentFormaterImpl( getContext()));
// Discover and register the plugins for Rapla
Set<String> pluginNames = new LinkedHashSet<String>();
boolean isDevelopment = getContext().has(RaplaMainContainer.ENV_DEVELOPMENT) && getContext().lookup( RaplaMainContainer.ENV_DEVELOPMENT);
Enumeration<URL> pluginEnum = ConfigTools.class.getClassLoader().getResources("META-INF/rapla-plugin.list");
if (!pluginEnum.hasMoreElements() || isDevelopment)
{
Collection<String> result = ServiceListCreator.findPluginClasses(logger);
pluginNames.addAll(result);
}
while ( pluginEnum.hasMoreElements() ) {
BufferedReader reader = new BufferedReader(new InputStreamReader((pluginEnum.nextElement()).openStream()));
while ( true ) {
String plugin = reader.readLine();
if ( plugin == null)
break;
pluginNames.add(plugin);
}
}
addContainerProvidedComponentInstance( PLUGIN_LIST, pluginNames);
logger.info("Config=" + getStartupEnvironment().getConfigURL());
I18nBundle i18n = getContext().lookup(RaplaComponent.RAPLA_RESOURCES);
String version = i18n.getString( "rapla.version" );
logger.info("Rapla.Version=" + version);
version = i18n.getString( "rapla.build" );
logger.info("Rapla.Build=" + version);
AttributeImpl.TRUE_TRANSLATION.setName(i18n.getLang(), i18n.getString("yes"));
AttributeImpl.FALSE_TRANSLATION.setName(i18n.getLang(), i18n.getString("no"));
try {
version = System.getProperty("java.version");
logger.info("Java.Version=" + version);
} catch (SecurityException ex) {
version = "-";
logger.warn("Permission to system property java.version is denied!");
}
callLogger =logger.getChildLogger("call");
}
public void dispose() {
getLogger().info("Shutting down rapla-container");
if ( commandQueue != null)
{
((DefaultScheduler)commandQueue).cancel();
}
super.dispose();
}
public <T> T getRemoteMethod(final RaplaContext context,final Class<T> a) throws RaplaContextException
{
if (context.has( RemoteMethodStub.class))
{
RemoteMethodStub server = context.lookup(RemoteMethodStub.class);
return server.getWebserviceLocalStub(a);
}
InvocationHandler proxy = new InvocationHandler()
{
RemoteConnectionInfo localConnectInfo;
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
if ( method.getName().equals("setConnectInfo") && method.getParameterTypes()[0].equals(RemoteConnectionInfo.class))
{
localConnectInfo = (RemoteConnectionInfo) args[0];
if ( globalConnectInfo == null)
{
globalConnectInfo =localConnectInfo;
}
return null;
}
RemoteConnectionInfo remoteConnectionInfo = localConnectInfo != null ? localConnectInfo : globalConnectInfo;
if ( remoteConnectionInfo == null)
{
throw new IllegalStateException("you need to call setConnectInfo first");
}
Class<?> returnType = method.getReturnType();
String methodName = method.getName();
final URL server;
try
{
server = new URL( remoteConnectionInfo.getServerURL());
}
catch (MalformedURLException e)
{
throw new RaplaContextException(e.getMessage());
}
StatusUpdater statusUpdater = remoteConnectionInfo.getStatusUpdater();
if ( statusUpdater != null)
{
statusUpdater.setStatus( Status.BUSY );
}
FutureResult result;
try
{
result = call(context,server, a, methodName, args, remoteConnectionInfo);
if (callLogger.isDebugEnabled())
{
callLogger.debug("Calling " + server + " " + a.getName() + "."+methodName);
}
}
finally
{
if ( statusUpdater != null)
{
statusUpdater.setStatus( Status.READY );
}
}
if ( !FutureResult.class.isAssignableFrom(returnType))
{
return result.get();
}
return result;
}
};
ClassLoader classLoader = a.getClassLoader();
@SuppressWarnings("unchecked")
Class<T>[] interfaces = new Class[] {a};
@SuppressWarnings("unchecked")
T proxyInstance = (T)Proxy.newProxyInstance(classLoader, interfaces, proxy);
return proxyInstance;
}
static private FutureResult call( RaplaContext context,URL server,Class<?> service, String methodName,Object[] args,RemoteConnectionInfo connectionInfo) {
RaplaHTTPConnector connector = new RaplaHTTPConnector();
try {
FutureResult result =connector.call(service, methodName, args, connectionInfo);
return result;
} catch (RaplaConnectException ex) {
return new ResultImpl(getConnectError(context,ex, server.toString()));
} catch (Exception ex) {
return new ResultImpl(ex);
}
}
static private RaplaConnectException getConnectError(RaplaContext context,RaplaConnectException ex2, String server) {
try
{
String message = context.lookup(RaplaComponent.RAPLA_RESOURCES).format("error.connect", server) + " " + ex2.getMessage();
return new RaplaConnectException(message);
}
catch (Exception ex)
{
return new RaplaConnectException("Connection error with server " + server + ": " + ex2.getMessage());
}
}
}
| 04900db4-rob | src/org/rapla/RaplaMainContainer.java | Java | gpl3 | 17,720 |
/*--------------------------------------------------------------------------*
| 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.framework;
/** the base-class for all Rapla specific Exceptions */
public class RaplaException extends Exception {
private static final long serialVersionUID = 1L;
public RaplaException(String text) {
super(text);
}
public RaplaException(Throwable throwable) {
super(throwable.getMessage(),throwable);
}
public RaplaException(String text,Throwable ex) {
super(text,ex);
}
}
| 04900db4-rob | src/org/rapla/framework/RaplaException.java | Java | gpl3 | 1,402 |
package org.rapla.framework;
public interface Configuration {
String getName();
Configuration getChild(String name);
Configuration[] getChildren(String name);
Configuration[] getChildren();
String getValue() throws ConfigurationException;
String getValue(String defaultValue);
boolean getValueAsBoolean(boolean defaultValue);
long getValueAsLong(int defaultValue);
int getValueAsInteger(int defaultValue);
String getAttribute(String name) throws ConfigurationException;
String getAttribute(String name, String defaultValue);
boolean getAttributeAsBoolean(String string, boolean defaultValue);
String[] getAttributeNames();
public Configuration find( String localName);
public Configuration find( String attributeName, String attributeValue);
}
| 04900db4-rob | src/org/rapla/framework/Configuration.java | Java | gpl3 | 836 |
package org.rapla.framework;
public class RaplaContextException
extends RaplaException
{
private static final long serialVersionUID = 1L;
public RaplaContextException( final String key ) {
super( "Unable to provide implementation for " + key + " " );
}
public RaplaContextException( final Class<?> clazz, final String message ) {
super("Unable to provide implementation for " + clazz.getName() + " " + message);
}
public RaplaContextException( final String message, final Throwable throwable )
{
super( message, throwable );
}
}
| 04900db4-rob | src/org/rapla/framework/RaplaContextException.java | Java | gpl3 | 611 |
package org.rapla.framework;
public interface Provider<T> {
T get();
}
| 04900db4-rob | src/org/rapla/framework/Provider.java | Java | gpl3 | 78 |
package org.rapla.framework.logger;
public class NullLogger extends AbstractLogger {
public NullLogger() {
super(LEVEL_FATAL);
}
public Logger getChildLogger(String childLoggerName) {
return this;
}
protected void write(int logLevel, String message, Throwable cause) {
}
}
| 04900db4-rob | src/org/rapla/framework/logger/NullLogger.java | Java | gpl3 | 335 |
package org.rapla.framework.logger;
public abstract class AbstractLogger implements Logger{
protected int logLevel;
public static final int LEVEL_FATAL = 4;
public static final int LEVEL_ERROR = 3;
public static final int LEVEL_WARN = 2;
public static final int LEVEL_INFO = 1;
public static final int LEVEL_DEBUG = 0;
public AbstractLogger(int logLevel) {
this.logLevel = logLevel;
}
public void error(String message, Throwable cause) {
log( LEVEL_ERROR,message, cause);
}
private void log(int logLevel, String message) {
log( logLevel, message, null);
}
private void log(int logLevel, String message, Throwable cause)
{
if ( logLevel < this.logLevel)
{
return;
}
write( logLevel, message, cause);
}
protected abstract void write(int logLevel, String message, Throwable cause);
public void debug(String message) {
log( LEVEL_DEBUG,message);
}
public void info(String message) {
log( LEVEL_INFO,message);
}
public void warn(String message) {
log( LEVEL_WARN,message);
}
public void warn(String message, Throwable cause) {
log( LEVEL_WARN,message, cause);
}
public void error(String message) {
log( LEVEL_ERROR,message);
}
public void fatalError(String message) {
log( LEVEL_FATAL,message);
}
public void fatalError(String message, Throwable cause) {
log( LEVEL_FATAL,message, cause);
}
public boolean isDebugEnabled() {
return logLevel<= LEVEL_DEBUG;
}
}
| 04900db4-rob | src/org/rapla/framework/logger/AbstractLogger.java | Java | gpl3 | 1,757 |
package org.rapla.framework.logger;
public interface Logger {
boolean isDebugEnabled();
void debug(String message);
void info(String message);
void warn(String message);
void warn(String message, Throwable cause);
void error(String message);
void error(String message, Throwable cause);
Logger getChildLogger(String childLoggerName);
}
| 04900db4-rob | src/org/rapla/framework/logger/Logger.java | Java | gpl3 | 391 |
package org.rapla.framework.logger;
public class ConsoleLogger extends AbstractLogger {
String prefix;
public ConsoleLogger(int logLevel)
{
super(logLevel);
}
public ConsoleLogger(String prefix,int logLevel)
{
super(logLevel);
this.prefix = prefix;
}
public ConsoleLogger()
{
this(LEVEL_INFO);
}
public Logger getChildLogger(String prefix)
{
String newPrefix = prefix;
if ( this.prefix != null)
{
newPrefix = this.prefix + "." + prefix;
}
return new ConsoleLogger( newPrefix, logLevel);
}
String getLogLevelString(int logLevel)
{
switch (logLevel)
{
case LEVEL_DEBUG: return "DEBUG";
case LEVEL_INFO: return "INFO";
case LEVEL_WARN: return "WARN";
case LEVEL_ERROR: return "ERROR";
case LEVEL_FATAL: return "FATAL";
}
return "";
}
protected void write(int logLevel, String message, Throwable cause)
{
String logLevelString = getLogLevelString( logLevel );
StringBuffer buf = new StringBuffer();
buf.append( logLevelString );
buf.append( " " );
if ( prefix != null)
{
buf.append( prefix);
buf.append( ": " );
}
if ( message != null)
{
buf.append( message);
if ( cause != null)
{
buf.append( ": " );
}
}
while( cause!= null)
{
StackTraceElement[] stackTrace = cause.getStackTrace();
buf.append( cause.getMessage());
buf.append( "\n" );
for ( StackTraceElement element:stackTrace)
{
buf.append(" ");
buf.append( element.toString());
buf.append( "\n");
}
cause = cause.getCause();
if ( cause != null)
{
buf.append(" caused by ");
buf.append( cause.getMessage());
buf.append( " " );
}
}
System.out.println(buf.toString());
}
}
| 04900db4-rob | src/org/rapla/framework/logger/ConsoleLogger.java | Java | gpl3 | 2,342 |
package org.rapla.framework;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.rapla.components.util.SerializableDateTimeFormat;
/** This class contains all locale specific information for Rapla. Like
<ul>
<li>Selected language.</li>
<li>Selected country.</li>
<li>Available languages (if the user has the possibility to choose a language)</li>
<li>TimeZone for appointments (This is always GMT+0)</li>
</ul>
<p>
Also it provides basic formating information for the dates.
</p>
<p>
Configuration is done in the rapla.xconf:
<pre>
<locale>
<languages default="de">
<language>de</language>
<language>en</language>
</languages>
<country>US</country>
</locale>
</pre>
If languages default is not set, the system default wil be used.<br>
If country code is not set, the system default will be used.<br>
</p>
<p>
Rapla hasn't a support for different Timezones yet.
if you look into RaplaLocale you find
3 timzones in Rapla:
</p>
<ul>
<li>{@link RaplaLocale#getTimeZone}</li>
<li>{@link RaplaLocale#getSystemTimeZone}</li>
<li>{@link RaplaLocale#getImportExportTimeZone}</li>
</ul>
*/
public interface RaplaLocale
{
TypedComponentRole<String> LANGUAGE_ENTRY = new TypedComponentRole<String>("org.rapla.language");
String[] getAvailableLanguages();
/** creates a calendar initialized with the Rapla timezone ( that is always GMT+0 for Rapla ) and the selected locale*/
Calendar createCalendar();
String formatTime( Date date );
Date fromUTCTimestamp(Date timestamp);
/** sets time to 0:00:00 or 24:00:00 */
Date toDate( Date date, boolean fillDate );
/** sets time to 0:00:00
* Warning month is zero based so January is 0
* @deprecated use toRaplaDate*/
Date toDate( int year, int month, int date );
/**
* month is 1-12 January is 1
*/
Date toRaplaDate( int year, int month, int date );
/** sets date to 0:00:00 */
Date toTime( int hour, int minute, int second );
/** Uses the first date parameter for year, month, date information and
the second for hour, minutes, second, millisecond information.*/
Date toDate( Date date, Date time );
/** format long with the local NumberFormat */
String formatNumber( long number );
/** format without year */
String formatDateShort( Date date );
/** format with locale DateFormat.SHORT */
String formatDate( Date date );
/** format with locale DateFormat.MEDIUM */
String formatDateLong( Date date );
String formatTimestamp(Date timestamp);
@Deprecated
String formatTimestamp(Date timestamp, TimeZone timezone);
/** Abbreviation of locale weekday name of date. */
String getWeekday( Date date );
/** Monthname of date. */
String getMonth( Date date );
String getCharsetNonUtf();
/**
This method always returns GMT+0. This is used for all internal calls. All dates and times are stored internaly with this Timezone.
Rapla can't work with timezones but to use the Date api it needs a timezone, so GMT+0 is used, because it doesn't have DaylightSavingTimes which would confuse the conflict detection. This timezone (GMT+0) is only used internaly and never shown in Rapla. Rapla only displays the time e.g. 10:00am without the timezone.
*/
TimeZone getTimeZone();
/**
returns the timezone of the system where Rapla is running (java default)
this is used on the server for storing the dates in mysql. Prior to 1.7 Rapla always switched the system time to gmt for the mysql api. But now the dates are converted from GMT+0 to system time before storing.
Converted meens: 10:00am GMT+0 Raplatime is converted to 10:00am Europe/Berlin, if thats the system timezone. When loading 10:00am Europe/Berlin is converted back to 10:00am GMT+0.
This timezone is also used for the timestamps, so created-at and last-changed dates are always stored in system time.
Also the logging api uses this timezone and now logs are in system time.
@see RaplaLocale#toRaplaTime(TimeZone, long)
@deprecated only used internally by the storage api
*/
@Deprecated
TimeZone getSystemTimeZone();
/**
returns the timezone configured via main options, this is per default the system timezon. This timezone is used for ical/exchange import/export
If Rapla will support timezones in the future, than this will be the default timezone for all times. Now its only used on import and export. It works as with system time above. 10:00am GMT+0 is converted to 10:00am of the configured timezone on export and on import all times are converted to GMT+0.
@see RaplaLocale#toRaplaTime(TimeZone, long)
@deprecated moved to ImportExportLocale
*/
@Deprecated
TimeZone getImportExportTimeZone();
/**
@deprecated moved to TimeZoneConverter
*/
@Deprecated
long fromRaplaTime(TimeZone timeZone,long raplaTime);
/**
@deprecated moved to TimeZoneConverter
*/
@Deprecated
long toRaplaTime(TimeZone timeZone,long time);
/**
@deprecated moved to TimeZoneConverter
*/
@Deprecated
Date fromRaplaTime(TimeZone timeZone,Date raplaTime);
/**
* converts a common Date object into a Date object that
* assumes that the user (being in the given timezone) is in the
* UTC-timezone by adding the offset between UTC and the given timezone.
*
* <pre>
* Example: If you pass the Date "2013 Jan 15 11:00:00 UTC"
* and the TimeZone "GMT+1", this method will return a Date
* "2013 Jan 15 12:00:00 UTC" which is effectivly 11:00:00 GMT+1
* </pre>
*
* @param timeZone
* the orgin timezone
* @param time
* the Date object in the passed timezone
* @see RaplaLocale#fromRaplaTime
@deprecated moved to TimeZoneConverter
*/
Date toRaplaTime(TimeZone timeZone,Date time);
Locale getLocale();
SerializableDateTimeFormat getSerializableFormat();
} | 04900db4-rob | src/org/rapla/framework/RaplaLocale.java | Java | gpl3 | 6,038 |
/*--------------------------------------------------------------------------*
| 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.framework;
public interface PluginDescriptor<T extends Container>{
public void provideServices(T container, Configuration configuration) throws RaplaContextException;
}
| 04900db4-rob | src/org/rapla/framework/PluginDescriptor.java | Java | gpl3 | 1,127 |
package org.rapla.framework;
public class SimpleProvider<T> implements Provider<T>
{
T value;
public T get() {
return value;
}
public void setValue(T value)
{
this.value = value;
}
} | 04900db4-rob | src/org/rapla/framework/SimpleProvider.java | Java | gpl3 | 212 |
package org.rapla.framework.internal;
import org.rapla.framework.ConfigurationException;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.TypedComponentRole;
public class ContextTools {
/** resolves a context value in the passed string.
If the string begins with <code>${</code> the method will lookup the String-Object in the context and returns it.
If it doesn't, the method returns the unmodified string.
Example:
<code>resolveContext("${download-server}")</code> returns the same as
context.get("download-server").toString();
@throws ConfigurationException when no contex-object was found for the given variable.
*/
public static String resolveContext( String s, RaplaContext context ) throws RaplaContextException
{
return ContextTools.resolveContextObject(s, context).toString();
}
public static Object resolveContextObject( String s, RaplaContext context ) throws RaplaContextException
{
StringBuffer value = new StringBuffer();
s = s.trim();
int startToken = s.indexOf( "${" );
if ( startToken < 0 )
return s;
int endToken = s.indexOf( "}", startToken );
String token = s.substring( startToken + 2, endToken );
String preToken = s.substring( 0, startToken );
String unresolvedRest = s.substring( endToken + 1 );
TypedComponentRole<Object> untypedIdentifier = new TypedComponentRole<Object>(token);
Object lookup = context.lookup( untypedIdentifier );
if ( preToken.length() == 0 && unresolvedRest.length() == 0 )
{
return lookup;
}
String contextObject = lookup.toString();
value.append( preToken );
String stringRep = contextObject.toString();
value.append( stringRep );
Object resolvedRest = resolveContext(unresolvedRest, context );
value.append( resolvedRest.toString());
return value.toString();
}
}
| 04900db4-rob | src/org/rapla/framework/internal/ContextTools.java | Java | gpl3 | 1,966 |
package org.rapla.framework.internal;
import java.util.Date;
import java.util.TimeZone;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.framework.RaplaLocale;
public abstract class AbstractRaplaLocale implements RaplaLocale {
public String formatTimestamp( Date date )
{
Date raplaDate = fromUTCTimestamp(date);
StringBuffer buf = new StringBuffer();
{
String formatDate= formatDate( raplaDate );
buf.append( formatDate);
}
buf.append(" ");
{
String formatTime = formatTime( raplaDate );
buf.append( formatTime);
}
return buf.toString();
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#toDate(java.util.Date, boolean)
*/
public Date toDate( Date date, boolean fillDate ) {
Date result = DateTools.cutDate(DateTools.addDay(date));
return result;
//
// Calendar cal1 = createCalendar();
// cal1.setTime( date );
// if ( fillDate ) {
// cal1.add( Calendar.DATE, 1);
// }
// cal1.set( Calendar.HOUR_OF_DAY, 0 );
// cal1.set( Calendar.MINUTE, 0 );
// cal1.set( Calendar.SECOND, 0 );
// cal1.set( Calendar.MILLISECOND, 0 );
// return cal1.getTime();
}
@Deprecated
public Date toDate( int year,int month, int day ) {
Date result = toRaplaDate(year, month+1, day);
return result;
}
public Date toRaplaDate( int year,int month, int day ) {
Date result = new Date(DateTools.toDate(year, month, day));
return result;
}
public Date toTime( int hour,int minute, int second ) {
Date result = new Date(DateTools.toTime(hour, minute, second));
return result;
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#toDate(java.util.Date, java.util.Date)
*/
public Date toDate( Date date, Date time ) {
long millisTime = time.getTime() - DateTools.cutDate( time.getTime());
Date result = new Date( DateTools.cutDate(date.getTime()) + millisTime);
return result;
// Calendar cal1 = createCalendar();
// Calendar cal2 = createCalendar();
// cal1.setTime( date );
// cal2.setTime( time );
// cal1.set( Calendar.HOUR_OF_DAY, cal2.get(Calendar.HOUR_OF_DAY) );
// cal1.set( Calendar.MINUTE, cal2.get(Calendar.MINUTE) );
// cal1.set( Calendar.SECOND, cal2.get(Calendar.SECOND) );
// cal1.set( Calendar.MILLISECOND, cal2.get(Calendar.MILLISECOND) );
// return cal1.getTime();
}
public long fromRaplaTime(TimeZone timeZone,long raplaTime)
{
long offset = getOffset(timeZone, raplaTime);
return raplaTime - offset;
}
public long toRaplaTime(TimeZone timeZone,long time)
{
long offset = getOffset(timeZone,time);
return time + offset;
}
public Date fromRaplaTime(TimeZone timeZone,Date raplaTime)
{
return new Date( fromRaplaTime(timeZone, raplaTime.getTime()));
}
public Date toRaplaTime(TimeZone timeZone,Date time)
{
return new Date( toRaplaTime(timeZone, time.getTime()));
}
private long getOffset(TimeZone timeZone,long time) {
long offsetSystem;
long offsetRapla;
{
// Calendar cal =Calendar.getInstance( timeZone);
// cal.setTimeInMillis( time );
// int zoneOffset = cal.get(Calendar.ZONE_OFFSET);
// int dstOffset = cal.get(Calendar.DST_OFFSET);
offsetSystem = timeZone.getOffset(time);
}
{
TimeZone utc = getTimeZone();
// Calendar cal =Calendar.getInstance( utc);
// cal.setTimeInMillis( time );
// offsetRapla = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET);
offsetRapla = utc.getOffset(time);
}
return offsetSystem - offsetRapla;
}
public SerializableDateTimeFormat getSerializableFormat()
{
return new SerializableDateTimeFormat();
}
}
| 04900db4-rob | src/org/rapla/framework/internal/AbstractRaplaLocale.java | Java | gpl3 | 3,876 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.framework.internal;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import org.rapla.components.util.Assert;
import org.rapla.components.util.JNLPUtil;
import org.rapla.components.util.xml.RaplaContentHandler;
import org.rapla.components.util.xml.RaplaErrorHandler;
import org.rapla.components.util.xml.RaplaNonValidatedInput;
import org.rapla.components.util.xml.RaplaSAXHandler;
import org.rapla.components.util.xml.XMLReaderAdapter;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaException;
import org.rapla.framework.logger.Logger;
import org.rapla.framework.logger.NullLogger;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/** Tools for configuring the rapla-system. */
public abstract class ConfigTools
{
/** parse startup parameters. The parse format:
<pre>
[-?|-c PATH_TO_CONFIG_FILE] [ACTION]
</pre>
Possible map entries:
<ul>
<li>config: the config-file</li>
<li>action: the start action</li>
</ul>
@return a map with the parameter-entries or null if format is invalid or -? is used
*/
public static Map<String,String> parseParams( String[] args )
{
boolean bInvalid = false;
Map<String,String> map = new HashMap<String,String>();
String config = null;
String action = null;
// Investigate the passed arguments
for ( int i = 0; i < args.length; i++ )
{
if ( args[i].toLowerCase().equals( "-c" ) )
{
if ( i + 1 == args.length )
{
bInvalid = true;
break;
}
config = args[++i];
continue;
}
if ( args[i].toLowerCase().equals( "-?" ) )
{
bInvalid = true;
break;
}
if ( args[i].toLowerCase().substring( 0, 1 ).equals( "-" ) )
{
bInvalid = true;
break;
}
action = args[i].toLowerCase();
}
if ( bInvalid )
{
return null;
}
if ( config != null )
map.put( "config", config );
if ( action != null )
map.put( "action", action );
return map;
}
/** Creates a configuration from a URL.*/
public static Configuration createConfig( String configURL ) throws RaplaException
{
try
{
URLConnection conn = new URL( configURL).openConnection();
InputStreamReader stream = new InputStreamReader(conn.getInputStream());
StringBuilder builder = new StringBuilder();
//System.out.println( "File Content:");
int s= -1;
do {
s = stream.read();
// System.out.print( (char)s );
if ( s != -1)
{
builder.append( (char) s );
}
} while ( s != -1);
stream.close();
Assert.notNull( stream );
Logger logger = new NullLogger();
RaplaNonValidatedInput parser = new RaplaReaderImpl();
final SAXConfigurationHandler handler = new SAXConfigurationHandler();
String xml = builder.toString();
parser.read(xml, handler, logger);
Configuration config = handler.getConfiguration();
Assert.notNull( config );
return config;
}
catch ( EOFException ex )
{
throw new RaplaException( "Can't load configuration-file at " + configURL );
}
catch ( Exception ex )
{
throw new RaplaException( ex );
}
}
static public class RaplaReaderImpl implements RaplaNonValidatedInput
{
public void read(String xml, RaplaSAXHandler handler, Logger logger) throws RaplaException
{
InputSource source = new InputSource( new StringReader(xml));
try {
XMLReader reader = XMLReaderAdapter.createXMLReader(false);
reader.setContentHandler( new RaplaContentHandler(handler));
reader.parse(source );
reader.setErrorHandler( new RaplaErrorHandler( logger));
} catch (SAXException ex) {
Throwable cause = ex.getException();
if (cause instanceof SAXParseException) {
ex = (SAXParseException) cause;
cause = ex.getException();
}
if (ex instanceof SAXParseException) {
throw new RaplaException("Line: " + ((SAXParseException)ex).getLineNumber()
+ " Column: "+ ((SAXParseException)ex).getColumnNumber() + " "
+ ((cause != null) ? cause.getMessage() : ex.getMessage())
,(cause != null) ? cause : ex );
}
if (cause == null) {
throw new RaplaException( ex);
}
if (cause instanceof RaplaException)
throw (RaplaException) cause;
else
throw new RaplaException( cause);
} catch (IOException ex) {
throw new RaplaException( ex.getMessage(), ex);
}
}
}
/** Creates an configuration URL from a configuration path.
If path is null the URL of the defaultPropertiesFile
will be returned.
*/
public static URL configFileToURL( String path, String defaultPropertiesFile ) throws RaplaException
{
URL configURL = null;
try
{
if ( path != null )
{
File file = new File( path );
if ( file.exists() )
{
configURL = ( file.getCanonicalFile() ).toURI().toURL();
}
}
if ( configURL == null )
{
configURL = ConfigTools.class.getClassLoader().getResource( defaultPropertiesFile );
if ( configURL == null )
{
File file = new File( defaultPropertiesFile );
if ( !file.exists() )
{
file = new File( "war/WEB-INF/" + defaultPropertiesFile );
}
if ( !file.exists() )
{
file = new File( "war/webclient/" + defaultPropertiesFile );
}
if ( file.exists() )
{
configURL = file.getCanonicalFile().toURI().toURL();
}
}
}
}
catch ( MalformedURLException ex )
{
throw new RaplaException( "malformed config path" + path );
}
catch ( IOException ex )
{
throw new RaplaException( "Can't resolve config path" + path );
}
if ( configURL == null )
{
throw new RaplaException( defaultPropertiesFile
+ " not found on classpath and in working folder "
+ " Path config file with -c argument. "
+ " For more information start rapla -? or read the api-docs." );
}
return configURL;
}
/** Creates an configuration URL from a configuration filename and
the webstart codebae.
If filename is null the URL of the defaultPropertiesFile
will be returned.
*/
public static URL webstartConfigToURL( String defaultPropertiesFilename ) throws RaplaException
{
try
{
URL base = JNLPUtil.getCodeBase();
URL configURL = new URL( base, defaultPropertiesFilename );
return configURL;
}
catch ( Exception ex )
{
throw new RaplaException( "Can't get configuration file in webstart mode." );
}
}
}
| 04900db4-rob | src/org/rapla/framework/internal/ConfigTools.java | Java | gpl3 | 9,197 |
/*--------------------------------------------------------------------------*
| 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.framework.internal;
import org.rapla.framework.Provider;
import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
@SuppressWarnings("restriction")
public class Slf4jAdapter implements Provider<org.rapla.framework.logger.Logger> {
static ILoggerFactory logManager = LoggerFactory.getILoggerFactory();
static public org.rapla.framework.logger.Logger getLoggerForCategory(String categoryName) {
LocationAwareLogger loggerForCategory = (LocationAwareLogger)logManager.getLogger(categoryName);
return new Wrapper(loggerForCategory, categoryName);
}
public org.rapla.framework.logger.Logger get() {
return getLoggerForCategory( "rapla");
}
static class Wrapper implements org.rapla.framework.logger.Logger{
LocationAwareLogger logger;
String id;
public Wrapper( LocationAwareLogger loggerForCategory, String id) {
this.logger = loggerForCategory;
this.id = id;
}
public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
public void debug(String message) {
log(LocationAwareLogger.DEBUG_INT, message);
}
public void info(String message) {
log( LocationAwareLogger.INFO_INT, message);
}
private void log(int infoInt, String message) {
log( infoInt, message, null);
}
private void log( int level, String message,Throwable t) {
Object[] argArray = null;
String fqcn = Wrapper.class.getName();
logger.log(null, fqcn, level,message,argArray, t);
}
public void warn(String message) {
log( LocationAwareLogger.WARN_INT, message);
}
public void warn(String message, Throwable cause) {
log( LocationAwareLogger.WARN_INT, message, cause);
}
public void error(String message) {
log( LocationAwareLogger.ERROR_INT, message);
}
public void error(String message, Throwable cause) {
log( LocationAwareLogger.ERROR_INT, message, cause);
}
public org.rapla.framework.logger.Logger getChildLogger(String childLoggerName)
{
String childId = id + "." + childLoggerName;
return getLoggerForCategory( childId);
}
}
}
| 04900db4-rob | src/org/rapla/framework/internal/Slf4jAdapter.java | Java | gpl3 | 3,398 |
/*--------------------------------------------------------------------------*
| 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.framework.internal;
import java.util.HashMap;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.internal.RaplaClientServiceImpl;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.internal.FacadeImpl;
import org.rapla.storage.CachableStorageOperator;
import org.rapla.storage.ImportExportManager;
import org.rapla.storage.StorageOperator;
import org.rapla.storage.dbrm.RemoteOperator;
public class RaplaMetaConfigInfo extends HashMap<String,ComponentInfo> {
private static final long serialVersionUID = 1L;
public RaplaMetaConfigInfo() {
put( "rapla-client", new ComponentInfo(RaplaClientServiceImpl.class.getName(),ClientServiceContainer.class.getName()));
put( "resource-bundle",new ComponentInfo(I18nBundleImpl.class.getName(),I18nBundle.class.getName()));
put( "facade",new ComponentInfo(FacadeImpl.class.getName(),ClientFacade.class.getName()));
put( "remote-storage",new ComponentInfo(RemoteOperator.class.getName(),new String[] {StorageOperator.class.getName(), CachableStorageOperator.class.getName()}));
// now the server configurations
put( "rapla-server", new ComponentInfo("org.rapla.server.internal.ServerServiceImpl",new String[]{"org.rapla.server.ServerServiceContainer"}));
put( "file-storage",new ComponentInfo("org.rapla.storage.dbfile.FileOperator",new String[] {StorageOperator.class.getName(), CachableStorageOperator.class.getName()}));
put( "db-storage",new ComponentInfo("org.rapla.storage.dbsql.DBOperator",new String[] {StorageOperator.class.getName(), CachableStorageOperator.class.getName()}));
put( "sql-storage",new ComponentInfo("org.rapla.storage.dbsql.DBOperator",new String[] {StorageOperator.class.getName(), CachableStorageOperator.class.getName()}));
put( "importexport", new ComponentInfo("org.rapla.storage.impl.server.ImportExportManagerImpl",ImportExportManager.class.getName()));
}
}
| 04900db4-rob | src/org/rapla/framework/internal/RaplaMetaConfigInfo.java | Java | gpl3 | 3,027 |
package org.rapla.framework.internal;
import java.util.Map;
import java.util.Stack;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXHandler;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
public class SAXConfigurationHandler implements RaplaSAXHandler
{
final Stack<DefaultConfiguration> configStack = new Stack<DefaultConfiguration>();
Configuration parsedConfiguration;
public Configuration getConfiguration()
{
return parsedConfiguration;
}
public void startElement(String namespaceURI, String localName,
RaplaSAXAttributes atts) throws RaplaSAXParseException
{
DefaultConfiguration defaultConfiguration = new DefaultConfiguration(localName);
for ( Map.Entry<String,String> entry :atts.getMap().entrySet())
{
String name = entry.getKey();
String value = entry.getValue();
defaultConfiguration.setAttribute( name, value);
}
configStack.push( defaultConfiguration);
}
public void endElement(
String namespaceURI,
String localName
) throws RaplaSAXParseException
{
DefaultConfiguration current =configStack.pop();
if ( configStack.isEmpty())
{
parsedConfiguration = current;
}
else
{
DefaultConfiguration parent = configStack.peek();
parent.addChild( current);
}
}
public void characters(char[] ch, int start, int length) {
DefaultConfiguration peek = configStack.peek();
String value = peek.getValue(null);
StringBuffer buf = new StringBuffer();
if ( value != null)
{
buf.append( value);
}
buf.append( ch, start, length);
String string = buf.toString();
if ( string.trim().length() > 0)
{
peek.setValue( string);
}
}
}
| 04900db4-rob | src/org/rapla/framework/internal/SAXConfigurationHandler.java | Java | gpl3 | 2,038 |
/*--------------------------------------------------------------------------*
| 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.framework.internal;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.rapla.components.util.DateTools;
import org.rapla.components.xmlbundle.LocaleSelector;
import org.rapla.components.xmlbundle.impl.LocaleSelectorImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.logger.Logger;
public class RaplaLocaleImpl extends AbstractRaplaLocale {
TimeZone zone;
TimeZone systemTimezone;
TimeZone importExportTimeZone;
LocaleSelector localeSelector = new LocaleSelectorImpl();
String[] availableLanguages;
String COUNTRY = "country";
String LANGUAGES = "languages";
String LANGUAGE = "language";
String CHARSET = "charset";
String charsetForHtml;
public RaplaLocaleImpl(Configuration config,Logger logger )
{
String selectedCountry = config.getChild( COUNTRY).getValue(Locale.getDefault().getCountry() );
Configuration languageConfig = config.getChild( LANGUAGES );
Configuration[] languages = languageConfig.getChildren( LANGUAGE );
charsetForHtml = config.getChild(CHARSET).getValue("iso-8859-15");
availableLanguages = new String[languages.length];
for ( int i=0;i<languages.length;i++ ) {
availableLanguages[i] = languages[i].getValue("en");
}
String selectedLanguage = languageConfig.getAttribute( "default", Locale.getDefault().getLanguage() );
if (selectedLanguage.trim().length() == 0)
selectedLanguage = Locale.getDefault().getLanguage();
localeSelector.setLocale( new Locale(selectedLanguage, selectedCountry) );
zone = DateTools.getTimeZone();
systemTimezone = TimeZone.getDefault();
importExportTimeZone = systemTimezone;
logger.info("Configured Locale= " + getLocaleSelector().getLocale().toString());
}
public TimeZone getSystemTimeZone() {
return systemTimezone;
}
public LocaleSelector getLocaleSelector() {
return localeSelector;
}
public Date fromUTCTimestamp(Date date)
{
Date raplaTime = toRaplaTime( importExportTimeZone,date );
return raplaTime;
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#getAvailableLanguages()
*/
public String[] getAvailableLanguages() {
return availableLanguages;
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#createCalendar()
*/
public Calendar createCalendar() {
return Calendar.getInstance( zone, getLocale() );
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#formatTime(java.util.Date)
*/
public String formatTime( Date date ) {
Locale locale = getLocale();
TimeZone timezone = getTimeZone();
DateFormat format = DateFormat.getTimeInstance( DateFormat.SHORT, locale );
format.setTimeZone( timezone );
String formatTime = format.format( date );
return formatTime;
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#formatNumber(long)
*/
public String formatNumber( long number ) {
Locale locale = getLocale();
return NumberFormat.getInstance( locale).format(number );
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#formatDateShort(java.util.Date)
*/
public String formatDateShort( Date date ) {
Locale locale = getLocale();
TimeZone timezone = zone;
StringBuffer buf = new StringBuffer();
FieldPosition fieldPosition = new FieldPosition( DateFormat.YEAR_FIELD );
DateFormat format = DateFormat.getDateInstance( DateFormat.SHORT, locale );
format.setTimeZone( timezone );
buf = format.format(date,
buf,
fieldPosition
);
if ( fieldPosition.getEndIndex()<buf.length() ) {
buf.delete( fieldPosition.getBeginIndex(), fieldPosition.getEndIndex()+1 );
} else if ( (fieldPosition.getBeginIndex()>=0) ) {
buf.delete( fieldPosition.getBeginIndex(), fieldPosition.getEndIndex() );
}
String result = buf.toString();
return result;
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#formatDate(java.util.Date)
*/
public String formatDate( Date date ) {
TimeZone timezone = zone;
Locale locale = getLocale();
DateFormat format = DateFormat.getDateInstance( DateFormat.SHORT, locale );
format.setTimeZone( timezone );
return format.format( date );
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#formatDateLong(java.util.Date)
*/
public String formatDateLong( Date date ) {
TimeZone timezone = zone;
Locale locale = getLocale();
DateFormat format = DateFormat.getDateInstance( DateFormat.MEDIUM, locale );
format.setTimeZone( timezone );
String dateFormat = format.format( date);
return dateFormat + " (" + getWeekday(date) + ")";
}
@Deprecated
public String formatTimestamp( Date date, TimeZone timezone )
{
Locale locale = getLocale();
StringBuffer buf = new StringBuffer();
{
DateFormat format = DateFormat.getDateInstance( DateFormat.SHORT, locale );
format.setTimeZone( timezone );
String formatDate= format.format( date );
buf.append( formatDate);
}
buf.append(" ");
{
DateFormat format = DateFormat.getTimeInstance( DateFormat.SHORT, locale );
format.setTimeZone( timezone );
String formatTime = format.format( date );
buf.append( formatTime);
}
return buf.toString();
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#getWeekday(java.util.Date)
*/
public String getWeekday( Date date ) {
TimeZone timeZone = getTimeZone();
Locale locale = getLocale();
SimpleDateFormat format = new SimpleDateFormat( "EE", locale );
format.setTimeZone( timeZone );
return format.format( date );
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#getMonth(java.util.Date)
*/
public String getMonth( Date date ) {
TimeZone timeZone = getTimeZone();
Locale locale = getLocale();
SimpleDateFormat format = new SimpleDateFormat( "MMMMM", locale );
format.setTimeZone( timeZone );
return format.format( date );
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#getTimeZone()
*/
public TimeZone getTimeZone() {
return zone;
}
public TimeZone getImportExportTimeZone() {
return importExportTimeZone;
}
public void setImportExportTimeZone(TimeZone importExportTimeZone) {
this.importExportTimeZone = importExportTimeZone;
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#getLocale()
*/
public Locale getLocale() {
return localeSelector.getLocale();
}
public String getCharsetNonUtf()
{
return charsetForHtml;
}
}
| 04900db4-rob | src/org/rapla/framework/internal/RaplaLocaleImpl.java | Java | gpl3 | 7,997 |
/*--------------------------------------------------------------------------*
| 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.framework.internal;
public class ComponentInfo {
String className;
String[] roles;
public ComponentInfo(String className) {
this( className, className );
}
public ComponentInfo(String className, String roleName) {
this( className, new String[] {roleName} );
}
public ComponentInfo(String className, String[] roleNames) {
this.className = className;
this.roles = roleNames;
}
public String[] getRoles() {
return roles;
}
public String getClassname() {
return className;
}
}
| 04900db4-rob | src/org/rapla/framework/internal/ComponentInfo.java | Java | gpl3 | 1,535 |
/*--------------------------------------------------------------------------*
| 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.framework.internal;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.rapla.framework.Provider;
public class RaplaJDKLoggingAdapter implements Provider<org.rapla.framework.logger.Logger> {
public org.rapla.framework.logger.Logger get() {
final Logger logger = getLogger( "rapla");
return new Wrapper(logger, "rapla");
}
static private java.util.logging.Logger getLogger(String categoryName)
{
Logger logger = Logger.getLogger(categoryName);
return logger;
}
static String WRAPPER_NAME = RaplaJDKLoggingAdapter.class.getName();
class Wrapper implements org.rapla.framework.logger.Logger{
java.util.logging.Logger logger;
String id;
public Wrapper( java.util.logging.Logger logger, String id) {
this.logger = logger;
this.id = id;
}
public boolean isDebugEnabled() {
return logger.isLoggable(Level.CONFIG);
}
public void debug(String message) {
log(Level.CONFIG, message);
}
public void info(String message) {
log(Level.INFO, message);
}
public void warn(String message) {
log(Level.WARNING,message);
}
public void warn(String message, Throwable cause) {
log(Level.WARNING,message, cause);
}
public void error(String message) {
log(Level.SEVERE, message);
}
public void error(String message, Throwable cause) {
log(Level.SEVERE, message, cause);
}
private void log(Level level,String message) {
log(level, message, null);
}
private void log(Level level,String message, Throwable cause) {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
String sourceClass = null;
String sourceMethod =null;
for (StackTraceElement element:stackTrace)
{
String classname = element.getClassName();
if ( !classname.startsWith(WRAPPER_NAME))
{
sourceClass=classname;
sourceMethod =element.getMethodName();
break;
}
}
logger.logp(level,sourceClass, sourceMethod,message, cause);
}
public org.rapla.framework.logger.Logger getChildLogger(String childLoggerName)
{
String childId = id+ "." + childLoggerName;
Logger childLogger = getLogger( childId);
return new Wrapper( childLogger, childId);
}
}
}
| 04900db4-rob | src/org/rapla/framework/internal/RaplaJDKLoggingAdapter.java | Java | gpl3 | 3,626 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.framework.internal;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.jws.WebService;
import org.rapla.components.util.Cancelable;
import org.rapla.components.util.Command;
import org.rapla.components.util.CommandScheduler;
import org.rapla.framework.Configuration;
import org.rapla.framework.ConfigurationException;
import org.rapla.framework.Container;
import org.rapla.framework.Disposable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaDefaultContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.TypedComponentRole;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.dbrm.RemoteServiceCaller;
/** Base class for the ComponentContainers in Rapla.
* Containers are the RaplaMainContainer, the Client- and the Server-Service
*/
public class ContainerImpl implements Container
{
protected Container m_parent;
protected RaplaDefaultContext m_context;
protected Configuration m_config;
protected List<ComponentHandler> m_componentHandler = Collections.synchronizedList(new ArrayList<ComponentHandler>());
protected Map<String,RoleEntry> m_roleMap = Collections.synchronizedMap(new LinkedHashMap<String,RoleEntry>());
Logger logger;
public ContainerImpl(RaplaContext parentContext, Configuration config, Logger logger) throws RaplaException {
m_config = config;
// if ( parentContext.has(Logger.class ) )
// {
// logger = parentContext.lookup( Logger.class);
// }
// else
// {
// logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
// }
this.logger = logger;
if ( parentContext.has(Container.class )) {
m_parent = parentContext.lookup( Container.class);
}
m_context = new RaplaDefaultContext(parentContext) {
@Override
protected Object lookup(String role) throws RaplaContextException {
ComponentHandler handler = getHandler( role );
if ( handler != null ) {
return handler.get();
}
return null;
}
@Override
protected boolean has(String role) {
if (getHandler( role ) != null)
return true;
return false;
}
};
addContainerProvidedComponentInstance(Logger.class,logger);
init( );
}
@SuppressWarnings("unchecked")
public <T> T lookup(Class<T> componentRole, String hint) throws RaplaContextException {
String key = componentRole.getName()+ "/" + hint;
ComponentHandler handler = getHandler( key );
if ( handler != null ) {
return (T) handler.get();
}
if ( m_parent != null)
{
return m_parent.lookup(componentRole, hint);
}
throw new RaplaContextException( key );
}
public Logger getLogger()
{
return logger;
}
protected void init() throws RaplaException {
configure( m_config );
addContainerProvidedComponentInstance( Container.class, this );
addContainerProvidedComponentInstance( Logger.class, getLogger());
}
public StartupEnvironment getStartupEnvironment() {
try
{
return getContext().lookup( StartupEnvironment.class);
}
catch ( RaplaContextException e )
{
throw new IllegalStateException(" Container not initialized with a startup environment");
}
}
protected void configure( final Configuration config )
throws RaplaException
{
Map<String,ComponentInfo> m_componentInfos = getComponentInfos();
final Configuration[] elements = config.getChildren();
for ( int i = 0; i < elements.length; i++ )
{
final Configuration element = elements[i];
final String id = element.getAttribute( "id", null );
if ( null == id )
{
// Only components with an id attribute are treated as components.
getLogger().debug( "Ignoring configuration for component, " + element.getName()
+ ", because the id attribute is missing." );
}
else
{
final String className;
final String[] roles;
if ( "component".equals( element.getName() ) )
{
try {
className = element.getAttribute( "class" );
Configuration[] roleConfigs = element.getChildren("roles");
roles = new String[ roleConfigs.length ];
for ( int j=0;j< roles.length;j++) {
roles[j] = roleConfigs[j].getValue();
}
} catch ( ConfigurationException ex) {
throw new RaplaException( ex);
}
}
else
{
String configName = element.getName();
final ComponentInfo roleEntry = m_componentInfos.get( configName );
if ( null == roleEntry )
{
final String message = "No class found matching configuration name " + "[name: " + element.getName() + "]";
getLogger().error( message );
continue;
}
roles = roleEntry.getRoles();
className = roleEntry.getClassname();
}
if ( getLogger().isDebugEnabled() )
{
getLogger().debug( "Configuration processed for: " + className );
}
Logger logger = this.logger.getChildLogger( id );
ComponentHandler handler =new ComponentHandler( element, className, logger);
for ( int j=0;j< roles.length;j++) {
String roleName = (roles[j]);
addHandler( roleName, id, handler );
}
}
}
}
protected Map<String,ComponentInfo> getComponentInfos() {
return Collections.emptyMap();
}
public <T, I extends T> void addContainerProvidedComponent(Class<T> roleInterface, Class<I> implementingClass) {
addContainerProvidedComponent(roleInterface, implementingClass, null, (Configuration)null);
}
public <T, I extends T> void addContainerProvidedComponent(Class<T> roleInterface, Class<I> implementingClass, Configuration config) {
addContainerProvidedComponent(roleInterface, implementingClass, null,config);
}
public <T, I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass) {
addContainerProvidedComponent(roleInterface, implementingClass, (Configuration) null);
}
public <T, I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass, Configuration config) {
addContainerProvidedComponent( roleInterface, implementingClass, null, config);
}
public <T, I extends T> void addContainerProvidedComponentInstance(TypedComponentRole<T> roleInterface, I implementingInstance) {
addContainerProvidedComponentInstance(roleInterface.getId(), implementingInstance, null);
}
public <T, I extends T> void addContainerProvidedComponentInstance(Class<T> roleInterface, I implementingInstance) {
addContainerProvidedComponentInstance(roleInterface, implementingInstance, implementingInstance.toString());
}
public <T> Collection< T> lookupServicesFor(TypedComponentRole<T> role) throws RaplaContextException {
Collection<T> list = new LinkedHashSet<T>();
for (T service: getAllServicesForThisContainer(role)) {
list.add(service);
}
if ( m_parent != null)
{
for (T service:m_parent.lookupServicesFor(role))
{
list.add( service);
}
}
return list;
}
public <T> Collection<T> lookupServicesFor(Class<T> role) throws RaplaContextException {
Collection<T> list = new LinkedHashSet<T>();
for (T service:getAllServicesForThisContainer(role)) {
list.add( service);
}
if ( m_parent != null)
{
for (T service:m_parent.lookupServicesFor(role))
{
list.add( service);
}
}
return list;
}
protected <T, I extends T> void addContainerProvidedComponentInstance(Class<T> roleInterface, I implementingInstance, String hint) {
addContainerProvidedComponentInstance(roleInterface.getName(), implementingInstance, hint);
}
protected <T, I extends T> void addContainerProvidedComponent(Class<T> roleInterface, Class<I> implementingClass, String hint, Configuration config) {
addContainerProvidedComponent( roleInterface.getName(), implementingClass.getName(), hint, config);
}
private <T, I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass, String hint, Configuration config)
{
addContainerProvidedComponent( roleInterface.getId(), implementingClass.getName(), hint, config);
}
synchronized private void addContainerProvidedComponent(String role,String classname, String hint,Configuration config) {
addContainerProvidedComponent( new String[] {role}, classname, hint, config);
}
synchronized private void addContainerProvidedComponentInstance(String role,Object componentInstance,String hint) {
addHandler( role, hint, new ComponentHandler(componentInstance));
}
synchronized private void addContainerProvidedComponent(String[] roles,String classname,String hint, Configuration config) {
ComponentHandler handler = new ComponentHandler( config, classname, getLogger() );
for ( int i=0;i<roles.length;i++) {
addHandler( roles[i], hint, handler);
}
}
protected <T> Collection<T> getAllServicesForThisContainer(TypedComponentRole<T> role) {
RoleEntry entry = m_roleMap.get( role.getId() );
return getAllServicesForThisContainer( entry);
}
protected <T> Collection<T> getAllServicesForThisContainer(Class<T> role) {
RoleEntry entry = m_roleMap.get( role.getName() );
return getAllServicesForThisContainer( entry);
}
private <T> Collection<T> getAllServicesForThisContainer(RoleEntry entry) {
if ( entry == null)
{
return Collections.emptyList();
}
List<T> result = new ArrayList<T>();
Set<String> hintSet = entry.getHintSet();
for (String hint: hintSet)
{
ComponentHandler handler = entry.getHandler(hint);
try
{
Object service = handler.get();
// we can safely cast here because the method is only called from checked methods
@SuppressWarnings("unchecked")
T casted = (T)service;
result.add(casted);
}
catch (Exception e)
{
Throwable ex = e;
while( ex.getCause() != null)
{
ex = ex.getCause();
}
getLogger().error("Could not initialize component " + handler + " due to " + ex.getMessage() + " removing from service list" , e);
entry.remove(hint);
}
}
return result;
}
/**
* @param roleName
* @param hint
* @param handler
*/
private void addHandler(String roleName, String hint, ComponentHandler handler) {
m_componentHandler.add( handler);
RoleEntry entry = m_roleMap.get( roleName );
if ( entry == null)
entry = new RoleEntry(roleName);
entry.put( hint , handler);
m_roleMap.put( roleName, entry);
}
ComponentHandler getHandler( String role) {
int hintSeperator = role.indexOf('/');
String roleName = role;
String hint = null;
if ( hintSeperator > 0 ) {
roleName = role.substring( 0, hintSeperator );
hint = role.substring( hintSeperator + 1 );
}
return getHandler( roleName, hint );
}
ComponentHandler getHandler( String role,Object hint) {
RoleEntry entry = m_roleMap.get( role );
if ( entry == null)
{
return null;
}
ComponentHandler handler = entry.getHandler( hint );
if ( handler != null)
{
return handler;
}
if ( hint == null || hint.equals("*" ) )
return entry.getFirstHandler();
// Try the first accessible handler
return null;
}
protected final class DefaultScheduler implements CommandScheduler {
private final ScheduledExecutorService executor;
private DefaultScheduler() {
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(5,new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
String name = thread.getName();
if ( name == null)
{
name = "";
}
thread.setName("raplascheduler-" + name.toLowerCase().replaceAll("thread", "").replaceAll("-|\\[|\\]", ""));
thread.setDaemon(true);
return thread;
}
});
this.executor = executor;
}
public Cancelable schedule(Command command, long delay)
{
Runnable task = createTask(command);
return schedule(task, delay);
}
public Cancelable schedule(Runnable task, long delay) {
if (executor.isShutdown())
{
RaplaException ex = new RaplaException("Can't schedule command because executer is already shutdown " + task.toString());
getLogger().error(ex.getMessage(), ex);
return createCancable( null);
}
TimeUnit unit = TimeUnit.MILLISECONDS;
ScheduledFuture<?> schedule = executor.schedule(task, delay, unit);
return createCancable( schedule);
}
private Cancelable createCancable(final ScheduledFuture<?> schedule) {
return new Cancelable() {
public void cancel() {
if ( schedule != null)
{
schedule.cancel(true);
}
}
};
}
public Cancelable schedule(Runnable task, long delay, long period) {
if (executor.isShutdown())
{
RaplaException ex = new RaplaException("Can't schedule command because executer is already shutdown " + task.toString());
getLogger().error(ex.getMessage(), ex);
return createCancable( null);
}
TimeUnit unit = TimeUnit.MILLISECONDS;
ScheduledFuture<?> schedule = executor.scheduleAtFixedRate(task, delay, period, unit);
return createCancable( schedule);
}
public Cancelable schedule(Command command, long delay, long period)
{
Runnable task = createTask(command);
return schedule(task, delay, period);
}
public void cancel() {
try{
getLogger().info("Stopping scheduler thread.");
List<Runnable> shutdownNow = executor.shutdownNow();
for ( Runnable task: shutdownNow)
{
long delay = -1;
if ( task instanceof ScheduledFuture)
{
ScheduledFuture scheduledFuture = (ScheduledFuture) task;
delay = scheduledFuture.getDelay( TimeUnit.SECONDS);
}
if ( delay <=0)
{
getLogger().warn("Interrupted active task " + task );
}
}
getLogger().info("Stopped scheduler thread.");
}
catch ( Throwable ex)
{
getLogger().warn(ex.getMessage());
}
// we give the update threads some time to execute
try
{
Thread.sleep( 50);
}
catch (InterruptedException e)
{
}
}
}
class RoleEntry {
Map<String,ComponentHandler> componentMap = Collections.synchronizedMap(new LinkedHashMap<String,ComponentHandler>());
ComponentHandler firstEntry;
int generatedHintCounter = 0;
String roleName;
RoleEntry(String roleName) {
this.roleName = roleName;
}
String generateHint()
{
return roleName + "_" +generatedHintCounter++;
}
void put( String hint, ComponentHandler handler ){
if ( hint == null)
{
hint = generateHint();
}
synchronized (this) {
componentMap.put( hint, handler);
}
if (firstEntry == null)
firstEntry = handler;
}
void remove(String hint)
{
componentMap.remove( hint);
}
Set<String> getHintSet() {
// we return a clone to avoid concurrent modification exception
synchronized (this) {
LinkedHashSet<String> result = new LinkedHashSet<String>(componentMap.keySet());
return result;
}
}
ComponentHandler getHandler(Object hint) {
return componentMap.get( hint );
}
ComponentHandler getFirstHandler() {
return firstEntry;
}
public String toString()
{
return componentMap.toString();
}
}
public RaplaContext getContext() {
return m_context;
}
boolean disposing;
public void dispose() {
// prevent reentrence in dispose
synchronized ( this)
{
if ( disposing)
{
getLogger().warn("Disposing is called twice",new RaplaException(""));
return;
}
disposing = true;
}
try
{
removeAllComponents();
}
finally
{
disposing = false;
}
}
protected void removeAllComponents() {
Iterator<ComponentHandler> it = new ArrayList<ComponentHandler>(m_componentHandler).iterator();
while ( it.hasNext() ) {
it.next().dispose();
}
m_componentHandler.clear();
m_roleMap.clear();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
Constructor findDependantConstructor(Class componentClass) {
Constructor[] constructors= componentClass.getConstructors();
TreeMap<Integer,Constructor> constructorMap = new TreeMap<Integer, Constructor>();
for (Constructor constructor:constructors) {
Class[] types = constructor.getParameterTypes();
boolean compatibleParameters = true;
for (int j=0; j< types.length; j++ ) {
Class type = types[j];
if (!( type.isAssignableFrom( RaplaContext.class) || type.isAssignableFrom( Configuration.class) || type.isAssignableFrom(Logger.class) || type.isAnnotationPresent(WebService.class) || getContext().has( type)))
{
compatibleParameters = false;
}
}
if ( compatibleParameters )
{
//return constructor;
constructorMap.put( types.length, constructor);
}
}
// return the constructor with the most paramters
if (!constructorMap.isEmpty())
{
return constructorMap.lastEntry().getValue();
}
return null;
}
/** Instantiates a class and passes the config, logger and the parent context to the object if needed by the constructor.
* This concept is taken form pico container.*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object instanciate( String componentClassName, Configuration config, Logger logger ) throws RaplaContextException
{
RaplaContext context = m_context;
Class componentClass;
try {
componentClass = Class.forName( componentClassName );
} catch (ClassNotFoundException e1) {
throw new RaplaContextException("Component class " + componentClassName + " not found." , e1);
}
Constructor c = findDependantConstructor( componentClass );
Object[] params = null;
if ( c != null) {
Class[] types = c.getParameterTypes();
params = new Object[ types.length ];
for (int i=0; i< types.length; i++ ) {
Class type = types[i];
Object p;
if ( type.isAssignableFrom( RaplaContext.class)) {
p = context;
} else if ( type.isAssignableFrom( Configuration.class)) {
p = config;
} else if ( type.isAssignableFrom( Logger.class)) {
p = logger;
} else if ( type.isAnnotationPresent(WebService.class)) {
RemoteServiceCaller lookup = context.lookup(RemoteServiceCaller.class);
p = lookup.getRemoteMethod( type);
} else {
Class guessedRole = type;
if ( context.has( guessedRole )) {
p = context.lookup( guessedRole );
} else {
throw new RaplaContextException(componentClass, "Can't statisfy constructor dependency " + type.getName() );
}
}
params[i] = p;
}
}
try {
final Object component;
if ( c!= null) {
component = c.newInstance( params);
} else {
component = componentClass.newInstance();
}
return component;
}
catch (Exception e)
{
throw new RaplaContextException(componentClassName + " could not be initialized due to " + e.getMessage(), e);
}
}
protected class ComponentHandler implements Disposable {
protected Configuration config;
protected Logger logger;
protected Object component;
protected String componentClassName;
boolean dispose = true;
protected ComponentHandler( Object component) {
this.component = component;
this.dispose = false;
}
protected ComponentHandler( Configuration config, String componentClass, Logger logger) {
this.config = config;
this.componentClassName = componentClass;
this.logger = logger;
}
Semaphore instanciating = new Semaphore(1);
Object get() throws RaplaContextException {
if ( component != null)
{
return component;
}
boolean acquired;
try {
acquired = instanciating.tryAcquire(60,TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RaplaContextException("Timeout while waiting for instanciation of " + componentClassName );
}
if ( !acquired)
{
throw new RaplaContextException("Instanciating component " + componentClassName + " twice. Possible a cyclic dependency.",new RaplaException(""));
}
else
{
try
{
// test again, maybe instanciated by another thread
if ( component != null)
{
return component;
}
component = instanciate( componentClassName, config, logger );
return component;
}
finally
{
instanciating.release();
}
}
}
boolean disposing;
public void dispose() {
// prevent reentrence in dispose
synchronized ( this)
{
if ( disposing)
{
getLogger().warn("Disposing is called twice",new RaplaException(""));
return;
}
disposing = true;
}
try
{
if (component instanceof Disposable)
{
if ( component == ContainerImpl.this)
{
return;
}
((Disposable) component).dispose();
}
} catch ( Exception ex) {
getLogger().error("Error disposing component ", ex );
}
finally
{
disposing = false;
}
}
public String toString()
{
if ( component != null)
{
return component.toString();
}
if ( componentClassName != null)
{
return componentClassName.toString();
}
return super.toString();
}
}
protected Runnable createTask(final Command command) {
Runnable timerTask = new Runnable() {
public void run() {
try {
command.execute();
} catch (Exception e) {
getLogger().error( e.getMessage(), e);
}
}
public String toString()
{
return command.toString();
}
};
return timerTask;
}
protected CommandScheduler createCommandQueue() {
CommandScheduler commandQueue = new DefaultScheduler();
return commandQueue;
}
}
| 04900db4-rob | src/org/rapla/framework/internal/ContainerImpl.java | Java | gpl3 | 26,542 |
package org.rapla.framework;
@SuppressWarnings("unused")
public class TypedComponentRole<T> {
String id;
public TypedComponentRole(String id) {
this.id = id.intern();
}
public String getId()
{
return id;
}
public String toString()
{
return id;
}
public boolean equals(Object obj)
{
if (obj == null)
{
return false;
}
if ( !(obj instanceof TypedComponentRole))
{
return false;
}
return id.equals(obj.toString());
}
@Override
public int hashCode() {
return id.hashCode();
}
}
| 04900db4-rob | src/org/rapla/framework/TypedComponentRole.java | Java | gpl3 | 636 |
package org.rapla.framework;
import java.net.URL;
import org.rapla.framework.logger.Logger;
public interface StartupEnvironment
{
int CONSOLE = 1;
int WEBSTART = 2;
int APPLET = 3;
Configuration getStartupConfiguration() throws RaplaException;
URL getDownloadURL() throws RaplaException;
URL getConfigURL() throws RaplaException;
/** either EMBEDDED, CONSOLE, WEBSTART, APPLET,SERVLET or CLIENT */
int getStartupMode();
URL getContextRootURL() throws RaplaException;
Logger getBootstrapLogger();
} | 04900db4-rob | src/org/rapla/framework/StartupEnvironment.java | Java | gpl3 | 550 |
package org.rapla.framework;
public interface RaplaContext
{
/** Returns a reference to the requested object (e.g. a component instance).
* throws a RaplaContextException if the object can't be returned. This could have
* different reasons: For example it is not found in the context, or there has been
* a problem during the component creation.
*/
<T> T lookup(Class<T> componentRole) throws RaplaContextException;
boolean has(Class<?> clazz);
<T> T lookup(TypedComponentRole<T> componentRole) throws RaplaContextException;
//<T> T lookup(TypedComponentRole<T> componentRole, String hint) throws RaplaContextException;
boolean has(TypedComponentRole<?> componentRole);
}
| 04900db4-rob | src/org/rapla/framework/RaplaContext.java | Java | gpl3 | 717 |
package org.rapla.framework;
public interface Disposable {
public void dispose();
}
| 04900db4-rob | src/org/rapla/framework/Disposable.java | Java | gpl3 | 94 |
package org.rapla.framework;
import java.util.HashMap;
public class RaplaDefaultContext implements RaplaContext
{
private final HashMap<String,Object> contextObjects = new HashMap<String,Object>();
protected final RaplaContext parent;
public RaplaDefaultContext()
{
this( null );
}
public RaplaDefaultContext( final RaplaContext parent )
{
this.parent = parent;
}
/**
* @throws RaplaContextException
*/
protected Object lookup( final String key ) throws RaplaContextException
{
return contextObjects.get( key );
}
protected boolean has( final String key )
{
return contextObjects.get( key ) != null;
}
public <T> void put(Class<T> componentRole, T instance) {
contextObjects.put(componentRole.getName(), instance );
}
public <T> void put(TypedComponentRole<T> componentRole, T instance) {
contextObjects.put(componentRole.getId(), instance );
}
public boolean has(Class<?> componentRole) {
if (has(componentRole.getName()))
{
return true;
}
return parent != null && parent.has( componentRole);
}
public boolean has(TypedComponentRole<?> componentRole) {
if (has( componentRole.getId()))
{
return true;
}
return parent != null && parent.has( componentRole);
}
@SuppressWarnings("unchecked")
public <T> T lookup(Class<T> componentRole) throws RaplaContextException {
final String key = componentRole.getName();
T lookup = (T) lookup(key);
if ( lookup == null)
{
if ( parent != null)
{
return parent.lookup( componentRole);
}
else
{
throw new RaplaContextException( key );
}
}
return lookup;
}
@SuppressWarnings("unchecked")
public <T> T lookup(TypedComponentRole<T> componentRole) throws RaplaContextException {
final String key = componentRole.getId();
T lookup = (T) lookup(key);
if ( lookup == null)
{
if ( parent != null)
{
return parent.lookup( componentRole);
}
else
{
throw new RaplaContextException( key );
}
}
return lookup;
}
// @SuppressWarnings("unchecked")
// public <T> T lookup(TypedComponentRole<T> componentRole, String hint) throws RaplaContextException {
// String key = componentRole.getId()+ "/" + hint;
// T lookup = (T) lookup(key);
// if ( lookup == null)
// {
// if ( parent != null)
// {
// return parent.lookup( componentRole, hint);
// }
// else
// {
// throw new RaplaContextException( key );
// }
// }
// return lookup;
// }
}
| 04900db4-rob | src/org/rapla/framework/RaplaDefaultContext.java | Java | gpl3 | 3,019 |
/*--------------------------------------------------------------------------*
| 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.framework;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Stack;
import org.rapla.framework.logger.Logger;
/** Helper Class for automated creation of the rapla-plugin.list in the
* META-INF directory. Can be used in the build environment.
*/
public class ServiceListCreator {
public static void main (String[] args) {
try {
String sourceDir = args[0];
String destDir = (args.length>1) ? args[1] : sourceDir;
processDir(sourceDir,destDir);
} catch (IOException e) {
throw new RuntimeException( e.getMessage());
} catch (ClassNotFoundException e) {
throw new RuntimeException( e.getMessage());
}
}
public static void processDir(String srcDir,String destFile)
throws ClassNotFoundException, IOException
{
File topDir = new File(srcDir);
List<String> list = findPluginClasses(topDir, null);
Writer writer = new BufferedWriter(new FileWriter( destFile ));
try
{
for ( String className:list)
{
System.out.println("Found PluginDescriptor for " + className);
writer.write( className );
writer.write( "\n" );
}
} finally {
writer.close();
}
}
public static List<String> findPluginClasses(File topDir,Logger logger)
throws ClassNotFoundException {
List<String> list = new ArrayList<String>();
Stack<File> stack = new Stack<File>();
stack.push(topDir);
while (!stack.empty()) {
File file = stack.pop();
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i=0;i<files.length;i++)
stack.push(files[i]);
} else {
String name = file.getName();
if (file.getAbsolutePath().contains("rapla") && (name.endsWith("Plugin.class") || name.endsWith("PluginServer.class"))) {
String absolut = file.getAbsolutePath();
String relativePath = absolut.substring(topDir.getAbsolutePath().length());
String pathName = relativePath.substring(1,relativePath.length()-".class".length());
String className = pathName.replace(File.separatorChar,'.');
try
{
Class<?> pluginClass = ServiceListCreator.class.getClassLoader().loadClass(className );
if (!pluginClass.isInterface() ) {
if ( PluginDescriptor.class.isAssignableFrom(pluginClass)) {
list.add( className);
} else {
if ( logger != null)
{
logger.warn("No PluginDescriptor found for Class " + className );
}
}
}
}
catch (NoClassDefFoundError ex)
{
System.out.println(ex.getMessage());
}
}
}
}
return list;
}
/** lookup for plugin classes in classpath*/
public static Collection<String> findPluginClasses(Logger logger)
throws ClassNotFoundException {
Collection<String> result = new LinkedHashSet<String>();
URL mainDir = ServiceListCreator.class.getResource("/");
if ( mainDir != null)
{
String classpath = System.getProperty("java.class.path");
final String[] split;
if (classpath != null)
{
split = classpath.split(""+File.pathSeparatorChar);
}
else
{
split = new String[] { mainDir.toExternalForm()};
}
for ( String path: split)
{
File pluginPath = new File(path);
List<String> foundInClasspathEntry = findPluginClasses(pluginPath, logger);
result.addAll(foundInClasspathEntry);
}
}
return result;
}
/** lookup for plugin classes in classpath*/
public static Collection<File> findPluginWebappfolders(Logger logger)
throws ClassNotFoundException {
Collection<File> result = new LinkedHashSet<File>();
URL mainDir = ServiceListCreator.class.getResource("/");
if ( mainDir != null)
{
String classpath = System.getProperty("java.class.path");
final String[] split;
if (classpath != null)
{
split = classpath.split(""+File.pathSeparatorChar);
}
else
{
split = new String[] { mainDir.toExternalForm()};
}
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name != null && name.equals("war");
}
};
for ( String path: split)
{
File pluginPath = new File(path);
List<String> foundInClasspathEntry = findPluginClasses(pluginPath, logger);
if ( foundInClasspathEntry.size() > 0)
{
File parent = pluginPath.getParentFile().getAbsoluteFile();
int depth= 0;
while ( parent != null && parent.isDirectory())
{
File[] listFiles = parent.listFiles( filter);
if (listFiles != null && listFiles.length == 1)
{
result.add( listFiles[0]);
}
depth ++;
if ( depth > 5)
{
break;
}
parent = parent.getParentFile();
}
}
}
}
return result;
}
}
| 04900db4-rob | src/org/rapla/framework/ServiceListCreator.java | Java | gpl3 | 6,541 |
package org.rapla.framework;
public class ConfigurationException extends Exception {
private static final long serialVersionUID = 1L;
public ConfigurationException(String string, Throwable exception) {
super( string, exception);
}
public ConfigurationException(String string) {
super( string );
}
}
| 04900db4-rob | src/org/rapla/framework/ConfigurationException.java | Java | gpl3 | 355 |
<body>
<p>This package contains the framework, that is
responsible for component creation with dependency injection.
It also provides the basic services for the plugin facility
of Rapla.</p>
<p>
It combines functionality of the avalon framework with that
of the pico container. It was programmed to fit the need of Rapla
but contains no domain knowledge. It can also
be used in other Software.
</p>
</body>
| 04900db4-rob | src/org/rapla/framework/package.html | HTML | gpl3 | 409 |
package org.rapla.framework;
public class RaplaSynchronizationException extends RaplaException {
private static final long serialVersionUID = 1L;
public RaplaSynchronizationException(String text) {
super(text);
}
public RaplaSynchronizationException(Throwable ex) {
super( ex.getMessage(), ex);
}
}
| 04900db4-rob | src/org/rapla/framework/RaplaSynchronizationException.java | Java | gpl3 | 328 |
/*--------------------------------------------------------------------------*
| 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.framework;
import java.util.Collection;
public interface Container extends Disposable
{
StartupEnvironment getStartupEnvironment();
RaplaContext getContext();
/** lookup an named component from the raplaserver.xconf */
<T> T lookup(Class<T> componentRole, String hint) throws RaplaContextException;
<T,I extends T> void addContainerProvidedComponent(Class<T> roleInterface,Class<I> implementingClass);
<T,I extends T> void addContainerProvidedComponent(Class<T> roleInterface,Class<I> implementingClass, Configuration config);
<T,I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass);
<T,I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass, Configuration config);
/** lookup all services for this role*/
<T> Collection<T> lookupServicesFor(TypedComponentRole<T> extensionPoint) throws RaplaContextException;
/** lookup all services for this role*/
<T> Collection<T> lookupServicesFor(Class<T> role) throws RaplaContextException;
}
| 04900db4-rob | src/org/rapla/framework/Container.java | Java | gpl3 | 2,083 |
package org.rapla.framework;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class DefaultConfiguration implements Configuration {
Map<String,String> attributes = new LinkedHashMap<String, String>();
List<DefaultConfiguration> children = new ArrayList<DefaultConfiguration>();
String value;
String name;
public DefaultConfiguration()
{
}
public DefaultConfiguration(String localName) {
this.name = localName;
}
public DefaultConfiguration(String localName, String value) {
this.name = localName;
if ( value != null)
{
this.value = value;
}
}
public DefaultConfiguration(Configuration config)
{
this.name = config.getName();
for (Configuration conf: config.getChildren())
{
children.add( new DefaultConfiguration( conf));
}
this.value = ((DefaultConfiguration)config).value;
attributes.putAll(((DefaultConfiguration)config).attributes);
}
public void addChild(Configuration configuration) {
children.add( (DefaultConfiguration) configuration);
}
public void setAttribute(String name, boolean value) {
attributes.put( name, value ? "true" : "false");
}
public void setAttribute(String name, String value) {
attributes.put( name, value);
}
public void setValue(String value) {
this.value = value;
}
public void setValue(int intValue) {
this.value = Integer.toString( intValue);
}
public void setValue(boolean selected) {
this.value = Boolean.toString( selected);
}
public DefaultConfiguration getMutableChild(String name, boolean create) {
for (DefaultConfiguration child:children)
{
if ( child.getName().equals( name))
{
return child;
}
}
if ( create )
{
DefaultConfiguration newConfig = new DefaultConfiguration( name);
children.add( newConfig);
return newConfig;
}
else
{
return null;
}
}
public void removeChild(Configuration child) {
children.remove( child);
}
public String getName()
{
return name;
}
public Configuration getChild(String name)
{
for (DefaultConfiguration child:children)
{
if ( child.getName().equals( name))
{
return child;
}
}
return new DefaultConfiguration( name);
}
public Configuration[] getChildren(String name) {
List<Configuration> result = new ArrayList<Configuration>();
for (DefaultConfiguration child:children)
{
if ( child.getName().equals( name))
{
result.add( child);
}
}
return result.toArray( new Configuration[] {});
}
public Configuration[] getChildren()
{
return children.toArray( new Configuration[] {});
}
public String getValue() throws ConfigurationException {
if ( value == null)
{
throw new ConfigurationException("Value not set in configuration " + name);
}
return value;
}
public String getValue(String defaultValue) {
if ( value == null)
{
return defaultValue;
}
return value;
}
public boolean getValueAsBoolean(boolean defaultValue) {
if ( value == null)
{
return defaultValue;
}
if ( value.equalsIgnoreCase("yes"))
{
return true;
}
if ( value.equalsIgnoreCase("no"))
{
return false;
}
return Boolean.parseBoolean( value);
}
public long getValueAsLong(int defaultValue) {
if ( value == null)
{
return defaultValue;
}
return Long.parseLong( value);
}
public int getValueAsInteger(int defaultValue) {
if ( value == null)
{
return defaultValue;
}
return Integer.parseInt( value);
}
public String getAttribute(String name) throws ConfigurationException {
String value = attributes.get(name);
if ( value == null)
{
throw new ConfigurationException("Attribute " + name + " not found ");
}
return value;
}
public String getAttribute(String name, String defaultValue) {
String value = attributes.get(name);
if ( value == null)
{
return defaultValue;
}
return value;
}
public boolean getAttributeAsBoolean(String string, boolean defaultValue) {
String value = getAttribute(string, defaultValue ? "true": "false");
return Boolean.parseBoolean( value);
}
public String[] getAttributeNames() {
String[] attributeNames = attributes.keySet().toArray( new String[] {});
return attributeNames;
}
public Configuration find( String localName) {
Configuration[] childList= getChildren();
for ( int i=0;i<childList.length;i++) {
if (childList[i].getName().equals( localName)) {
return childList[i];
}
}
return null;
}
public Configuration find( String attributeName, String attributeValue) {
Configuration[] childList= getChildren();
for ( int i=0;i<childList.length;i++) {
String attribute = childList[i].getAttribute( attributeName,null);
if (attributeValue.equals( attribute)) {
return childList[i];
}
}
return null;
}
public DefaultConfiguration replace( Configuration newChild) throws ConfigurationException {
Configuration find = find( newChild.getName());
if ( find == null)
{
throw new ConfigurationException(" could not find " + newChild.getName());
}
return replace( find, newChild );
}
public DefaultConfiguration replace( Configuration oldChild, Configuration newChild) {
String localName = getName();
DefaultConfiguration newConfig = newConfiguration(localName);
boolean present = false;
Configuration[] childList= getChildren();
for ( int i=0;i<childList.length;i++) {
if (childList[i] != oldChild) {
newConfig.addChild( childList[i]);
} else {
present = true;
newConfig.addChild( newChild );
}
}
if (!present) {
newConfig.addChild( newChild );
}
return newConfig;
}
protected DefaultConfiguration newConfiguration(String localName) {
return new DefaultConfiguration( localName);
}
public DefaultConfiguration add( Configuration newChild) {
String localName = getName();
DefaultConfiguration newConfig = newConfiguration(localName);
boolean present = false;
Configuration[] childList= getChildren();
for ( int i=0;i<childList.length;i++) {
if (childList[i] == newChild) {
present = true;
}
}
if (!present) {
newConfig.addChild( newChild );
}
return newConfig;
}
/**
* @param configuration
* @throws ConfigurationException
*/
public DefaultConfiguration remove(Configuration configuration) {
String localName = getName();
DefaultConfiguration newConfig = newConfiguration(localName);
Configuration[] childList= getChildren();
for ( int i=0;i<childList.length;i++) {
if (childList[i] != configuration) {
newConfig.addChild( childList[i]);
}
}
return newConfig;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((attributes == null) ? 0 : attributes.hashCode());
result = prime * result + ((children == null) ? 0 : children.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DefaultConfiguration other = (DefaultConfiguration) obj;
if (attributes == null) {
if (other.attributes != null)
return false;
} else if (!attributes.equals(other.attributes))
return false;
if (children == null) {
if (other.children != null)
return false;
} else if (!children.equals(other.children))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append( name);
if (attributes.size() > 0)
{
buf.append( "[");
boolean first= true;
for ( Map.Entry<String, String> entry: attributes.entrySet())
{
if (!first)
{
buf.append( ", ");
}
else
{
first = false;
}
buf.append(entry.getKey());
buf.append( "='");
buf.append(entry.getValue());
buf.append( "'");
}
buf.append( "]");
}
buf.append( "{");
boolean first= true;
for ( Configuration child:children)
{
if (first)
{
buf.append("\n");
first =false;
}
buf.append( child.toString());
buf.append("\n");
}
if ( value != null)
{
buf.append( value);
}
buf.append( "}");
return buf.toString();
}
}
| 04900db4-rob | src/org/rapla/framework/DefaultConfiguration.java | Java | gpl3 | 10,661 |
package org.rapla.client;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.framework.TypedComponentRole;
import org.rapla.gui.AppointmentStatusFactory;
import org.rapla.gui.ObjectMenuFactory;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.PluginOptionPanel;
import org.rapla.gui.PublishExtensionFactory;
import org.rapla.gui.ReservationCheck;
import org.rapla.gui.SwingViewFactory;
import org.rapla.gui.toolkit.IdentifiableMenuEntry;
/** Constant Pool of basic extension points of the Rapla client.
* You can add your extension in the provideService Method of your PluginDescriptor
* <pre>
* container.addContainerProvidedComponent( REPLACE_WITH_EXTENSION_POINT_NAME, REPLACE_WITH_CLASS_IMPLEMENTING_EXTENSION, config);
* </pre>
* @see org.rapla.framework.PluginDescriptor
*/
public interface RaplaClientExtensionPoints
{
/** add your own views to Rapla, by providing a org.rapla.gui.ViewFactory
* @see SwingViewFactory
* */
Class<SwingViewFactory> CALENDAR_VIEW_EXTENSION = SwingViewFactory.class;
/** A client extension is started automaticaly when a user has successfully login into the Rapla system. A class added as service doesn't need to implement a specific interface and is instanciated automaticaly after client login. You can add a RaplaContext parameter to your constructor to get access to the services of rapla.
*/
Class<ClientExtension> CLIENT_EXTENSION = ClientExtension.class;
/** You can add a specific configuration panel for your plugin.
* Note if you add a pluginOptionPanel you need to provide the PluginClass as hint.
* Example
* <code>
* container.addContainerProvidedComponent( RaplaExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION, AutoExportPluginOption.class, getClass().getName());
* </code>
* @see org.rapla.entities.configuration.Preferences
* @see OptionPanel
* */
TypedComponentRole<PluginOptionPanel> PLUGIN_OPTION_PANEL_EXTENSION = new TypedComponentRole<PluginOptionPanel>("org.rapla.plugin.Option");
/** You can add additional option panels for editing the user preference.
* @see org.rapla.entities.configuration.Preferences
* @see OptionPanel
* */
TypedComponentRole<OptionPanel> USER_OPTION_PANEL_EXTENSION = new TypedComponentRole<OptionPanel>("org.rapla.UserOptions");
/** You can add additional option panels for the editing the system preferences
* @see org.rapla.entities.configuration.Preferences
* @see OptionPanel
* */
TypedComponentRole<OptionPanel> SYSTEM_OPTION_PANEL_EXTENSION = new TypedComponentRole<OptionPanel>("org.rapla.SystemOptions");
/** add your own wizard menus to create events. Use the CalendarSelectionModel service to get access to the current calendar
* @see CalendarSelectionModel
**/
TypedComponentRole<IdentifiableMenuEntry> RESERVATION_WIZARD_EXTENSION = new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ReservationWizardExtension");
/** you can add an interactive check when the user stores a reservation
*@see ReservationCheck
**/
Class<ReservationCheck> RESERVATION_SAVE_CHECK = ReservationCheck.class;
/** add your own menu entries in the context menu of an object. To do this provide
an ObjectMenuFactory under this entry.
@see ObjectMenuFactory
*/
Class<ObjectMenuFactory> OBJECT_MENU_EXTENSION = ObjectMenuFactory.class;
/** add a footer for summary of appointments in edit window
* provide an AppointmentStatusFactory to add your own footer to the appointment edit
@see AppointmentStatusFactory
* */
Class<AppointmentStatusFactory> APPOINTMENT_STATUS = AppointmentStatusFactory.class;
/** add your own submenus to the admin menu.
*/
TypedComponentRole<IdentifiableMenuEntry> ADMIN_MENU_EXTENSION_POINT = new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.AdminMenuInsert");
/** add your own import-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> IMPORT_MENU_EXTENSION_POINT =new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ImportMenuInsert");
/** add your own export-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> EXPORT_MENU_EXTENSION_POINT =new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ExportMenuInsert");
/** add your own view-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> VIEW_MENU_EXTENSION_POINT =new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ViewMenuInsert");
/** add your own edit-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> EDIT_MENU_EXTENSION_POINT = new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.EditMenuInsert");
/** add your own help-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> HELP_MENU_EXTENSION_POINT = new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ExtraMenuInsert");
/** add your own publish options for the calendars*/
Class<PublishExtensionFactory> PUBLISH_EXTENSION_OPTION = PublishExtensionFactory.class;
}
| 04900db4-rob | src/org/rapla/client/RaplaClientExtensionPoints.java | Java | gpl3 | 5,148 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Frithjof Kurtz |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.client.internal;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.image.ImageObserver;
import java.beans.PropertyVetoException;
import java.net.URL;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.LocaleChangeEvent;
import org.rapla.components.xmlbundle.LocaleChangeListener;
import org.rapla.components.xmlbundle.LocaleSelector;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.toolkit.RaplaFrame;
public final class LoginDialog extends RaplaFrame implements LocaleChangeListener
{
private static final long serialVersionUID = -1887723833652617352L;
Container container;
JPanel upperpanel = new JPanel();
JPanel lowerpanel = new JPanel();
JLabel chooseLanguageLabel = new JLabel();
JPanel userandpassword = new JPanel();
JPanel buttonPanel = new JPanel();
JTextField username = new JTextField(15);
JPasswordField password = new JPasswordField(15);
JLabel usernameLabel = new JLabel();
JLabel passwordLabel = new JLabel();
JButton loginBtn = new JButton();
JButton exitBtn = new JButton();
I18nBundle i18n;
ImageObserver observer;
Image image;
JPanel canvas;
protected LocaleSelector localeSelector;
StartupEnvironment env;
// we have to add an extra gui component here because LoginDialog extends RaplaFrame and therefore can't extent RaplaGUIComponent
RaplaGUIComponent guiComponent;
public LoginDialog(RaplaContext context) throws RaplaException
{
super(context);
this.guiComponent = new RaplaGUIComponent(context);
env = context.lookup( StartupEnvironment.class );
i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
localeSelector = context.lookup(LocaleSelector.class);
localeSelector.addLocaleChangeListener(this);
}
public static LoginDialog create(RaplaContext sm, JComponent languageSelector) throws RaplaException
{
LoginDialog dlg = new LoginDialog(sm);
dlg.init(languageSelector);
return dlg;
}
Action exitAction;
public void setLoginAction(Action action)
{
loginBtn.setAction(action);
}
public void setExitAction(Action action)
{
exitAction = action;
exitBtn.setAction( action );
}
private void init(JComponent languageSelector)
{
container = getContentPane();
container.setLayout(new BorderLayout());
((JComponent) container).setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// ################## BEGIN LOGO ###################
observer = new ImageObserver()
{
public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h)
{
if ((flags & ALLBITS) != 0)
{
canvas.repaint();
}
return (flags & (ALLBITS | ABORT | ERROR)) == 0;
}
};
canvas = new JPanel()
{
private static final long serialVersionUID = 1L;
public void paint(Graphics g)
{
g.drawImage(image, 0, 0, observer);
}
};
Toolkit toolkit = Toolkit.getDefaultToolkit();
// creating an URL to the path of the picture
URL url = LoginDialog.class.getResource("/org/rapla/gui/images/tafel.png");
// getting it as image object
image = toolkit.createImage(url);
container.add(canvas, BorderLayout.CENTER);
MediaTracker mt = new MediaTracker(container);
mt.addImage(image, 0);
try
{
mt.waitForID(0);
}
catch (InterruptedException e)
{
}
// ################## END LOGO ###################
// ################## BEGIN LABELS AND TEXTFIELDS ###################
container.add(lowerpanel, BorderLayout.SOUTH);
lowerpanel.setLayout(new BorderLayout());
lowerpanel.add(userandpassword, BorderLayout.NORTH);
double pre = TableLayout.PREFERRED;
double fill = TableLayout.FILL;
double[][] sizes = { { pre, 10, fill }, { pre, 5, pre, 5, pre, 5 } };
TableLayout tableLayout = new TableLayout(sizes);
userandpassword.setLayout(tableLayout);
userandpassword.add(chooseLanguageLabel,"0,0");
userandpassword.add(languageSelector, "2,0");
userandpassword.add(usernameLabel, "0,2");
userandpassword.add(passwordLabel, "0,4");
userandpassword.add(username, "2,2");
userandpassword.add(password, "2,4");
username.setColumns(14);
password.setColumns(14);
Listener listener = new Listener();
password.addActionListener(listener);
languageSelector.addFocusListener(listener);
guiComponent.addCopyPaste( username);
guiComponent.addCopyPaste( password );
// ################## END LABELS AND TEXTFIELDS ###################
// ################## BEGIN BUTTONS ###################
// this is a separate JPanel for the buttons at the bottom
GridLayout gridLayout = new GridLayout(1, 2);
gridLayout.setHgap(20);
buttonPanel.setLayout(gridLayout);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// adding a button for exiting
buttonPanel.add(exitBtn);
// and to login
buttonPanel.add(loginBtn);
setLocale();
username.requestFocus();
int startupEnv = env.getStartupMode();
if( startupEnv != StartupEnvironment.WEBSTART && startupEnv != StartupEnvironment.APPLET) {
try
{
String userName = System.getProperty("user.name");
username.setText(userName);
username.selectAll();
}
catch (SecurityException ex)
{
// Not sure if it is needed, to catch this. I don't know if a custom system property is by default protected in a sandbox environment
}
}
lowerpanel.add(buttonPanel, BorderLayout.SOUTH);
// ################## END BUTTONS ###################
// ################## BEGIN FRAME ###################
// these are the dimensions of the rapla picture
int picturewidth = 362;
int pictureheight = 182;
// and a border around it
int border = 10;
// canvas.setBounds(0, 0, picturewidth, pictureheight);
this.getRootPane().setDefaultButton(loginBtn);
// with the picture dimensions as basis we determine the size
// of the frame, including some additional space below the picture
this.setSize(picturewidth + 2 * border, pictureheight + 210);
this.setResizable(false);
// ################## END FRAME ###################
}
boolean closeCalledFromOutside = false;
@Override
public void close() {
closeCalledFromOutside = true;
super.close();
}
protected void fireFrameClosing() throws PropertyVetoException {
super.fireFrameClosing();
if ( !closeCalledFromOutside && exitAction != null)
{
exitAction.actionPerformed( new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "exit"));
}
}
public String getUsername()
{
return username.getText();
}
public char[] getPassword()
{
return password.getPassword();
}
public void resetPassword() {
password.setText("");
}
/** overrides localeChanged from DialogUI */
public void localeChanged(LocaleChangeEvent evt)
{
setLocale();
}
private I18nBundle getI18n()
{
return i18n;
}
private void setLocale()
{
chooseLanguageLabel.setText(getI18n().getString("choose_language"));
exitBtn.setText(getI18n().getString("exit"));
loginBtn.setText(getI18n().getString("login"));
usernameLabel.setText(getI18n().getString("username") + ":");
passwordLabel.setText(getI18n().getString("password") + ":");
setTitle(getI18n().getString("logindialog.title"));
repaint();
}
public void dispose()
{
super.dispose();
localeSelector.removeLocaleChangeListener(this);
}
public void testEnter(String newUsername, String newPassword)
{
username.setText(newUsername);
password.setText(newPassword);
}
class Listener extends FocusAdapter implements ActionListener
{
boolean bInit = false;
public void focusGained(FocusEvent e)
{
if (!bInit)
{
username.requestFocus();
bInit = true;
}
}
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == password)
{
loginBtn.doClick();
return;
}
}
}
}
| 04900db4-rob | src/org/rapla/client/internal/LoginDialog.java | Java | gpl3 | 9,699 |
/*--------------------------------------------------------------------------*
main.raplaContainer.dispose();
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.client.internal;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.Semaphore;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import org.rapla.ConnectInfo;
import org.rapla.RaplaMainContainer;
import org.rapla.client.ClientService;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.client.RaplaClientListener;
import org.rapla.components.calendar.DateRenderer;
import org.rapla.components.iolayer.DefaultIO;
import org.rapla.components.iolayer.IOInterface;
import org.rapla.components.iolayer.WebstartIO;
import org.rapla.components.util.Cancelable;
import org.rapla.components.util.Command;
import org.rapla.components.util.CommandScheduler;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.LocaleSelector;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.facade.RaplaComponent;
import org.rapla.facade.UpdateErrorListener;
import org.rapla.facade.UserModule;
import org.rapla.facade.internal.FacadeImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.internal.ComponentInfo;
import org.rapla.framework.internal.ContainerImpl;
import org.rapla.framework.internal.RaplaMetaConfigInfo;
import org.rapla.framework.logger.Logger;
import org.rapla.gui.AnnotationEditExtension;
import org.rapla.gui.EditController;
import org.rapla.gui.InfoFactory;
import org.rapla.gui.MenuFactory;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.ReservationController;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.images.Images;
import org.rapla.gui.internal.CalendarOption;
import org.rapla.gui.internal.MainFrame;
import org.rapla.gui.internal.MenuFactoryImpl;
import org.rapla.gui.internal.RaplaDateRenderer;
import org.rapla.gui.internal.RaplaStartOption;
import org.rapla.gui.internal.UserOption;
import org.rapla.gui.internal.WarningsOption;
import org.rapla.gui.internal.common.InternMenus;
import org.rapla.gui.internal.common.RaplaClipboard;
import org.rapla.gui.internal.edit.EditControllerImpl;
import org.rapla.gui.internal.edit.annotation.CategorizationAnnotationEdit;
import org.rapla.gui.internal.edit.annotation.ColorAnnotationEdit;
import org.rapla.gui.internal.edit.annotation.EmailAnnotationEdit;
import org.rapla.gui.internal.edit.annotation.ExpectedColumnsAnnotationEdit;
import org.rapla.gui.internal.edit.annotation.ExpectedRowsAnnotationEdit;
import org.rapla.gui.internal.edit.reservation.ConflictReservationCheck;
import org.rapla.gui.internal.edit.reservation.DefaultReservationCheck;
import org.rapla.gui.internal.edit.reservation.ReservationControllerImpl;
import org.rapla.gui.internal.view.InfoFactoryImpl;
import org.rapla.gui.internal.view.LicenseInfoUI;
import org.rapla.gui.internal.view.TreeFactoryImpl;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.FrameControllerList;
import org.rapla.gui.toolkit.RaplaFrame;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaMenubar;
import org.rapla.gui.toolkit.RaplaSeparator;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.storage.StorageOperator;
import org.rapla.storage.dbrm.RemoteConnectionInfo;
import org.rapla.storage.dbrm.RemoteOperator;
import org.rapla.storage.dbrm.RestartServer;
import org.rapla.storage.dbrm.StatusUpdater;
/** Implementation of the ClientService.
*/
public class RaplaClientServiceImpl extends ContainerImpl implements ClientServiceContainer,ClientService,UpdateErrorListener
{
Vector<RaplaClientListener> listenerList = new Vector<RaplaClientListener>();
I18nBundle i18n;
boolean started;
boolean restartingGUI;
String facadeName;
boolean defaultLanguageChoosen;
FrameControllerList frameControllerList;
Configuration config;
boolean logoutAvailable;
ConnectInfo reconnectInfo;
static boolean lookAndFeelSet;
CommandScheduler commandQueueWrapper;
public RaplaClientServiceImpl(RaplaContext parentContext,Configuration config,Logger logger) throws RaplaException {
super(parentContext,config, logger);
this.config = config;
}
@Override
protected Map<String,ComponentInfo> getComponentInfos() {
return new RaplaMetaConfigInfo();
}
public static void setLookandFeel() {
if ( lookAndFeelSet )
{
return;
}
UIDefaults defaults = UIManager.getDefaults();
Font textFont = defaults.getFont("Label.font");
if ( textFont == null)
{
textFont = new Font("SansSerif", Font.PLAIN, 12);
}
else
{
textFont = textFont.deriveFont( Font.PLAIN );
}
defaults.put("Label.font", textFont);
defaults.put("Button.font", textFont);
defaults.put("Menu.font", textFont);
defaults.put("MenuItem.font", textFont);
defaults.put("RadioButton.font", textFont);
defaults.put("CheckBoxMenuItem.font", textFont);
defaults.put("CheckBox.font", textFont);
defaults.put("ComboBox.font", textFont);
defaults.put("Tree.expandedIcon",Images.getIcon("/org/rapla/gui/images/eclipse-icons/tree_minus.gif"));
defaults.put("Tree.collapsedIcon",Images.getIcon("/org/rapla/gui/images/eclipse-icons/tree_plus.gif"));
defaults.put("TitledBorder.font", textFont.deriveFont(Font.PLAIN,(float)10.));
lookAndFeelSet = true;
}
protected void init() throws RaplaException {
advanceLoading(false);
StartupEnvironment env = getContext().lookup(StartupEnvironment.class);
int startupMode = env.getStartupMode();
final Logger logger = getLogger();
if ( startupMode != StartupEnvironment.APPLET && startupMode != StartupEnvironment.WEBSTART)
{
try
{
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
logger.error("uncaught exception", e);
}
});
}
catch (Throwable ex)
{
logger.error("Can't set default exception handler-", ex);
}
}
setLookandFeel();
defaultLanguageChoosen = true;
getLogger().info("Starting gui ");
super.init( );
facadeName = m_config.getChild("facade").getValue("*");
addContainerProvidedComponent( WELCOME_FIELD, LicenseInfoUI.class );
addContainerProvidedComponent( MAIN_COMPONENT, RaplaFrame.class);
// overwrite commandqueue because we need to synchronize with swing
commandQueueWrapper = new AWTWrapper((DefaultScheduler)getContext().lookup(CommandScheduler.class));
addContainerProvidedComponentInstance( CommandScheduler.class, commandQueueWrapper);
addContainerProvidedComponent( RaplaClipboard.class, RaplaClipboard.class );
addContainerProvidedComponent( TreeFactory.class, TreeFactoryImpl.class );
addContainerProvidedComponent( MenuFactory.class, MenuFactoryImpl.class );
addContainerProvidedComponent( InfoFactory.class, InfoFactoryImpl.class );
addContainerProvidedComponent( EditController.class, EditControllerImpl.class );
addContainerProvidedComponent( ReservationController.class, ReservationControllerImpl.class );
addContainerProvidedComponent( RaplaClientExtensionPoints.USER_OPTION_PANEL_EXTENSION ,UserOption.class);
addContainerProvidedComponent( RaplaClientExtensionPoints.USER_OPTION_PANEL_EXTENSION , CalendarOption.class);
addContainerProvidedComponent( RaplaClientExtensionPoints.USER_OPTION_PANEL_EXTENSION , WarningsOption.class);
addContainerProvidedComponent( RaplaClientExtensionPoints.SYSTEM_OPTION_PANEL_EXTENSION, CalendarOption.class );
addContainerProvidedComponent( RaplaClientExtensionPoints.SYSTEM_OPTION_PANEL_EXTENSION, RaplaStartOption.class );
addContainerProvidedComponent( AnnotationEditExtension.ATTRIBUTE_ANNOTATION_EDIT, ColorAnnotationEdit.class);
addContainerProvidedComponent( AnnotationEditExtension.ATTRIBUTE_ANNOTATION_EDIT, CategorizationAnnotationEdit.class);
addContainerProvidedComponent( AnnotationEditExtension.ATTRIBUTE_ANNOTATION_EDIT, ExpectedRowsAnnotationEdit.class);
addContainerProvidedComponent( AnnotationEditExtension.ATTRIBUTE_ANNOTATION_EDIT, ExpectedColumnsAnnotationEdit.class);
addContainerProvidedComponent( AnnotationEditExtension.ATTRIBUTE_ANNOTATION_EDIT, EmailAnnotationEdit.class);
frameControllerList = new FrameControllerList(getLogger().getChildLogger("framelist"));
addContainerProvidedComponentInstance(FrameControllerList.class,frameControllerList);
RaplaMenubar menuBar = new RaplaMenubar();
RaplaMenu systemMenu = new RaplaMenu( InternMenus.FILE_MENU_ROLE.getId() );
RaplaMenu editMenu = new RaplaMenu( InternMenus.EDIT_MENU_ROLE.getId() );
RaplaMenu viewMenu = new RaplaMenu( InternMenus.VIEW_MENU_ROLE.getId() );
RaplaMenu helpMenu = new RaplaMenu( InternMenus.EXTRA_MENU_ROLE.getId() );
RaplaMenu newMenu = new RaplaMenu( InternMenus.NEW_MENU_ROLE.getId() );
RaplaMenu settingsMenu = new RaplaMenu( InternMenus.CALENDAR_SETTINGS.getId());
RaplaMenu adminMenu = new RaplaMenu( InternMenus.ADMIN_MENU_ROLE.getId() );
RaplaMenu importMenu = new RaplaMenu( InternMenus.IMPORT_MENU_ROLE.getId());
RaplaMenu exportMenu = new RaplaMenu( InternMenus.EXPORT_MENU_ROLE.getId());
menuBar.add( systemMenu );
menuBar.add( editMenu );
menuBar.add( viewMenu );
menuBar.add( helpMenu );
addContainerProvidedComponentInstance( SESSION_MAP, new HashMap<Object,Object>());
addContainerProvidedComponentInstance( InternMenus.MENU_BAR, menuBar);
addContainerProvidedComponentInstance( InternMenus.FILE_MENU_ROLE, systemMenu );
addContainerProvidedComponentInstance( InternMenus.EDIT_MENU_ROLE, editMenu);
addContainerProvidedComponentInstance( InternMenus.VIEW_MENU_ROLE, viewMenu);
addContainerProvidedComponentInstance( InternMenus.ADMIN_MENU_ROLE, adminMenu);
addContainerProvidedComponentInstance( InternMenus.IMPORT_MENU_ROLE, importMenu );
addContainerProvidedComponentInstance( InternMenus.EXPORT_MENU_ROLE, exportMenu );
addContainerProvidedComponentInstance( InternMenus.NEW_MENU_ROLE, newMenu );
addContainerProvidedComponentInstance( InternMenus.CALENDAR_SETTINGS, settingsMenu );
addContainerProvidedComponentInstance( InternMenus.EXTRA_MENU_ROLE, helpMenu );
editMenu.add( new RaplaSeparator("EDIT_BEGIN"));
editMenu.add( new RaplaSeparator("EDIT_END"));
addContainerProvidedComponent(RaplaClientExtensionPoints.RESERVATION_SAVE_CHECK, DefaultReservationCheck.class);
addContainerProvidedComponent(RaplaClientExtensionPoints.RESERVATION_SAVE_CHECK, ConflictReservationCheck.class);
boolean webstartEnabled =getContext().lookup(StartupEnvironment.class).getStartupMode() == StartupEnvironment.WEBSTART;
if (webstartEnabled) {
addContainerProvidedComponent( IOInterface.class,WebstartIO.class );
} else {
addContainerProvidedComponent( IOInterface.class,DefaultIO.class );
}
//Add this service to the container
addContainerProvidedComponentInstance(ClientService.class, this);
}
protected Runnable createTask(final Command command) {
Runnable timerTask = new Runnable() {
public void run() {
Runnable runnable = RaplaClientServiceImpl.super.createTask( command);
javax.swing.SwingUtilities.invokeLater(runnable);
}
public String toString()
{
return command.toString();
}
};
return timerTask;
}
/** override to synchronize tasks with the swing event queue*/
class AWTWrapper implements CommandScheduler
{
DefaultScheduler parent;
public AWTWrapper(DefaultScheduler parent) {
this.parent = parent;
}
@Override
public Cancelable schedule(Command command, long delay) {
Runnable task = createTask(command);
return parent.schedule(task, delay);
}
@Override
public Cancelable schedule(Command command, long delay, long period) {
Runnable task = createTask(command);
return parent.schedule(task, delay, period);
}
public String toString()
{
return parent.toString();
}
}
public ClientFacade getFacade() throws RaplaContextException {
return lookup(ClientFacade.class, facadeName);
}
public void start(ConnectInfo connectInfo) throws Exception {
if (started)
return;
try {
getLogger().debug("RaplaClient started");
i18n = getContext().lookup(RaplaComponent.RAPLA_RESOURCES );
ClientFacade facade = getFacade();
facade.addUpdateErrorListener(this);
StorageOperator operator = facade.getOperator();
if ( operator instanceof RemoteOperator)
{
RemoteConnectionInfo remoteConnection = ((RemoteOperator) operator).getRemoteConnectionInfo();
remoteConnection.setStatusUpdater( new StatusUpdater()
{
private Cursor waitCursor = new Cursor(Cursor.WAIT_CURSOR);
private Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR);
public void setStatus(Status status) {
Cursor cursor =( status == Status.BUSY) ? waitCursor: defaultCursor;
frameControllerList.setCursor( cursor);
}
}
);
}
advanceLoading(true);
logoutAvailable = true;
if ( connectInfo != null && connectInfo.getUsername() != null)
{
if (login( connectInfo))
{
beginRaplaSession();
return;
}
}
startLogin();
} catch (Exception ex) {
throw ex;
} finally {
}
}
protected void advanceLoading(boolean finish) {
try
{
Class<?> LoadingProgressC= null;
Object progressBar = null;
if ( getContext().lookup(StartupEnvironment.class).getStartupMode() == StartupEnvironment.CONSOLE)
{
LoadingProgressC = getClass().getClassLoader().loadClass("org.rapla.bootstrap.LoadingProgress");
progressBar = LoadingProgressC.getMethod("getInstance").invoke(null);
if ( finish)
{
LoadingProgressC.getMethod("close").invoke( progressBar);
}
else
{
LoadingProgressC.getMethod("advance").invoke( progressBar);
}
}
}
catch (Exception ex)
{
// Loading progress failure is not crucial to rapla excecution
}
}
/**
* @throws RaplaException
*
*/
private void beginRaplaSession() throws RaplaException {
initLanguage();
ClientFacade facade = getFacade();
addContainerProvidedComponentInstance( ClientFacade.class, facade);
final CalendarSelectionModel model = createCalendarModel();
addContainerProvidedComponentInstance( CalendarModel.class, model );
addContainerProvidedComponentInstance( CalendarSelectionModel.class, model );
StorageOperator operator = facade.getOperator();
if ( operator instanceof RestartServer)
{
addContainerProvidedComponentInstance(RestartServer.class, (RestartServer)operator);
}
((FacadeImpl)facade).addDirectModificationListener( new ModificationListener() {
public void dataChanged(ModificationEvent evt) throws RaplaException {
model.dataChanged( evt );
}
});
// if ( facade.isClientForServer() )
// {
// addContainerProvidedComponent (RaplaClientExtensionPoints.SYSTEM_OPTION_PANEL_EXTENSION , ConnectionOption.class);
// }
Set<String> pluginNames;
//List<PluginDescriptor<ClientServiceContainer>> pluginList;
try {
pluginNames = getContext().lookup( RaplaMainContainer.PLUGIN_LIST);
} catch (RaplaContextException ex) {
throw new RaplaException (ex );
}
List<PluginDescriptor<ClientServiceContainer>> pluginList = new ArrayList<PluginDescriptor<ClientServiceContainer>>( );
Logger logger = getLogger().getChildLogger("plugin");
for ( String plugin:pluginNames)
{
try {
boolean found = false;
try {
if ( plugin.toLowerCase().endsWith("serverplugin") || plugin.contains(".server."))
{
continue;
}
Class<?> componentClass = RaplaClientServiceImpl.class.getClassLoader().loadClass( plugin );
Method[] methods = componentClass.getMethods();
for ( Method method:methods)
{
if ( method.getName().equals("provideServices"))
{
Class<?> type = method.getParameterTypes()[0];
if (ClientServiceContainer.class.isAssignableFrom(type))
{
found = true;
}
}
}
} catch (ClassNotFoundException ex) {
continue;
} catch (NoClassDefFoundError ex) {
getLogger().error("Error loading plugin " + plugin + " " +ex.getMessage());
continue;
} catch (Exception e1) {
getLogger().error("Error loading plugin " + plugin + " " +e1.getMessage());
continue;
}
if ( found )
{
@SuppressWarnings("unchecked")
PluginDescriptor<ClientServiceContainer> descriptor = (PluginDescriptor<ClientServiceContainer>) instanciate(plugin, null, logger);
pluginList.add(descriptor);
logger.info("Installed plugin "+plugin);
}
} catch (RaplaContextException e) {
if (e.getCause() instanceof ClassNotFoundException) {
logger.error("Could not instanciate plugin "+ plugin, e);
}
}
}
addContainerProvidedComponentInstance(ClientServiceContainer.CLIENT_PLUGIN_LIST, pluginList);
initializePlugins( pluginList, facade.getSystemPreferences() );
// Add daterender if not provided by the plugins
if ( !getContext().has( DateRenderer.class))
{
addContainerProvidedComponent( DateRenderer.class, RaplaDateRenderer.class );
}
started = true;
User user = model.getUser();
boolean showToolTips = facade.getPreferences( user ).getEntryAsBoolean( RaplaBuilder.SHOW_TOOLTIP_CONFIG_ENTRY, true);
javax.swing.ToolTipManager.sharedInstance().setEnabled(showToolTips);
//javax.swing.ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);
javax.swing.ToolTipManager.sharedInstance().setInitialDelay( 1000 );
javax.swing.ToolTipManager.sharedInstance().setDismissDelay( 10000 );
javax.swing.ToolTipManager.sharedInstance().setReshowDelay( 0 );
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
RaplaFrame mainComponent = getContext().lookup( MAIN_COMPONENT );
mainComponent.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
try {
if ( !isRestartingGUI()) {
stop();
} else {
restartingGUI = false;
}
} catch (Exception ex) {
getLogger().error(ex.getMessage(),ex);
}
}
});
MainFrame mainFrame = new MainFrame( getContext());
fireClientStarted();
mainFrame.show();
}
private void initLanguage() throws RaplaException, RaplaContextException
{
ClientFacade facade = getFacade();
if ( !defaultLanguageChoosen)
{
Preferences prefs = facade.edit(facade.getPreferences());
RaplaLocale raplaLocale = getContext().lookup(RaplaLocale.class );
String currentLanguage = raplaLocale.getLocale().getLanguage();
prefs.putEntry( RaplaLocale.LANGUAGE_ENTRY, currentLanguage);
try
{
facade.store( prefs);
}
catch (Exception e)
{
getLogger().error("Can't store language change", e);
}
}
else
{
String language = facade.getPreferences().getEntryAsString( RaplaLocale.LANGUAGE_ENTRY, null);
if ( language != null)
{
LocaleSelector localeSelector = getContext().lookup(LocaleSelector.class);
localeSelector.setLanguage( language );
}
}
AttributeImpl.TRUE_TRANSLATION.setName(i18n.getLang(), i18n.getString("yes"));
AttributeImpl.FALSE_TRANSLATION.setName(i18n.getLang(), i18n.getString("no"));
}
protected void initializePlugins(List<PluginDescriptor<ClientServiceContainer>> pluginList, Preferences preferences) throws RaplaException {
RaplaConfiguration raplaConfig =preferences.getEntry(RaplaComponent.PLUGIN_CONFIG);
// Add plugin configs
for ( Iterator<PluginDescriptor<ClientServiceContainer>> it = pluginList.iterator(); it.hasNext(); ) {
PluginDescriptor<ClientServiceContainer> pluginDescriptor = it.next();
String pluginClassname = pluginDescriptor.getClass().getName();
Configuration pluginConfig = null;
if ( raplaConfig != null) {
pluginConfig = raplaConfig.find("class", pluginClassname);
}
if ( pluginConfig == null) {
pluginConfig = new DefaultConfiguration("plugin");
}
pluginDescriptor.provideServices( this, pluginConfig );
}
//Collection<?> clientPlugins = getAllServicesForThisContainer(RaplaExtensionPoints.CLIENT_EXTENSION);
// start plugins
getAllServicesForThisContainer(RaplaClientExtensionPoints.CLIENT_EXTENSION);
// for (Iterator<?> it = clientPlugins.iterator();it.hasNext();) {
// String hint = (String) it.next();
// try {
// getContext().lookup( RaplaExtensionPoints.CLIENT_EXTENSION , hint);
// getLogger().info( "Initialize " + hint );
// } catch (RaplaContextException ex ) {
// getLogger().error( "Can't initialize " + hint, ex );
// }
// }
}
public boolean isRestartingGUI()
{
return restartingGUI;
}
public void addRaplaClientListener(RaplaClientListener listener) {
listenerList.add(listener);
}
public void removeRaplaClientListener(RaplaClientListener listener) {
listenerList.remove(listener);
}
public RaplaClientListener[] getRaplaClientListeners() {
return listenerList.toArray(new RaplaClientListener[]{});
}
protected void fireClientClosed(ConnectInfo reconnect) {
RaplaClientListener[] listeners = getRaplaClientListeners();
for (int i=0;i<listeners.length;i++)
listeners[i].clientClosed(reconnect);
}
protected void fireClientStarted() {
RaplaClientListener[] listeners = getRaplaClientListeners();
for (int i=0;i<listeners.length;i++)
listeners[i].clientStarted();
}
protected void fireClientAborted() {
RaplaClientListener[] listeners = getRaplaClientListeners();
for (int i=0;i<listeners.length;i++)
listeners[i].clientAborted();
}
public boolean isRunning() {
return started;
}
public void switchTo(User user) throws RaplaException
{
ClientFacade facade = getFacade();
if ( user == null)
{
if ( reconnectInfo == null || reconnectInfo.getConnectAs() == null)
{
throw new RaplaException( "Can't switch back because there were no previous logins.");
}
final String oldUser = facade.getUser().getUsername();
String newUser = reconnectInfo.getUsername();
char[] password = reconnectInfo.getPassword();
getLogger().info("Login From:" + oldUser + " To:" + newUser);
ConnectInfo reconnectInfo = new ConnectInfo( newUser, password);
stop( reconnectInfo);
}
else
{
if ( reconnectInfo == null)
{
throw new RaplaException( "Can't switch to user, because admin login information not provided due missing login.");
}
if ( reconnectInfo.getConnectAs() != null)
{
throw new RaplaException( "Can't switch to user, because already switched.");
}
final String oldUser = reconnectInfo.getUsername();
final String newUser = user.getUsername();
getLogger().info("Login From:" + oldUser + " To:" + newUser);
ConnectInfo newInfo = new ConnectInfo( oldUser, reconnectInfo.getPassword(), newUser);
stop( newInfo);
}
// fireUpdateEvent(new ModificationEvent());
}
public boolean canSwitchBack() {
return reconnectInfo != null && reconnectInfo.getConnectAs() != null;
}
private void stop() {
stop( null );
}
private void stop(ConnectInfo reconnect) {
if (!started)
return;
try {
ClientFacade facade = getFacade();
facade.removeUpdateErrorListener( this);
if ( facade.isSessionActive())
{
facade.logout();
}
} catch (RaplaException ex) {
getLogger().error("Clean logout failed. " + ex.getMessage());
}
started = false;
fireClientClosed(reconnect);
}
public void dispose() {
if (frameControllerList != null)
frameControllerList.closeAll();
stop();
super.dispose();
getLogger().debug("RaplaClient disposed");
}
private void startLogin() throws Exception {
Command object = new Command()
{
public void execute() throws Exception {
startLoginInThread();
}
};
commandQueueWrapper.schedule( object, 0);
}
private void startLoginInThread() {
final Semaphore loginMutex = new Semaphore(1);
try {
final RaplaContext context = getContext();
final Logger logger = getLogger();
final LanguageChooser languageChooser = new LanguageChooser(logger, context);
final LoginDialog dlg = LoginDialog.create(context, languageChooser.getComponent());
Action languageChanged = new AbstractAction()
{
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
try {
String lang = languageChooser.getSelectedLanguage();
if (lang == null)
{
defaultLanguageChoosen = true;
}
else
{
defaultLanguageChoosen = false;
getLogger().debug("Language changing to " + lang );
LocaleSelector localeSelector = context.lookup( LocaleSelector.class );
localeSelector.setLanguage(lang);
getLogger().info("Language changed " + localeSelector.getLanguage() );
}
} catch (Exception ex) {
getLogger().error("Can't change language",ex);
}
}
};
languageChooser.setChangeAction( languageChanged);
//dlg.setIcon( i18n.getIcon("icon.rapla-small"));
Action loginAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
String username = dlg.getUsername();
char[] password = dlg.getPassword();
boolean success = false;
try {
String connectAs = null;
reconnectInfo = new ConnectInfo(username, password, connectAs);
success = login(reconnectInfo);
if ( !success )
{
dlg.resetPassword();
RaplaGUIComponent.showWarning(i18n.getString("error.login"), dlg,context,logger);
}
}
catch (RaplaException ex)
{
dlg.resetPassword();
RaplaGUIComponent.showException(ex, dlg, context, logger);
}
if ( success) {
dlg.close();
loginMutex.release();
try {
beginRaplaSession();
} catch (Throwable ex) {
RaplaGUIComponent.showException(ex, null, context, logger);
fireClientAborted();
}
} // end of else
}
};
Action exitAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
dlg.close();
loginMutex.release();
stop();
fireClientAborted();
}
};
loginAction.putValue(Action.NAME,i18n.getString("login"));
exitAction.putValue(Action.NAME,i18n.getString("exit"));
dlg.setIconImage(i18n.getIcon("icon.rapla_small").getImage());
dlg.setLoginAction( loginAction);
dlg.setExitAction( exitAction );
//dlg.setSize( 480, 270);
FrameControllerList.centerWindowOnScreen( dlg) ;
dlg.setVisible( true );
loginMutex.acquire();
} catch (Exception ex) {
getLogger().error("Error during Login ", ex);
stop();
fireClientAborted();
} finally {
loginMutex.release();
}
}
public void updateError(RaplaException ex) {
getLogger().error("Error updating data", ex);
}
/**
* @see org.rapla.facade.UpdateErrorListener#disconnected()
*/
public void disconnected(final String message) {
if ( started )
{
SwingUtilities.invokeLater( new Runnable() {
public void run() {
boolean modal = true;
String title = i18n.getString("restart_client");
try {
Component owner = frameControllerList.getMainWindow();
DialogUI dialog = DialogUI.create(getContext(), owner, modal, title, message);
Action action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
getLogger().warn("restart");
restart();
}
};
dialog.setAbortAction(action);
dialog.getButton(0).setAction( action);
dialog.start();
} catch (Throwable e) {
getLogger().error(e.getMessage(), e);
}
}
});
}
}
public void restart()
{
if ( reconnectInfo != null)
{
stop(reconnectInfo);
}
}
public void logout()
{
stop(new ConnectInfo(null, "".toCharArray()));
}
private boolean login(ConnectInfo connect) throws RaplaException
{
UserModule facade = getFacade();
if (facade.login(connect)) {
this.reconnectInfo = connect;
return true;
} else {
return false;
}
}
public boolean isLogoutAvailable()
{
return logoutAvailable;
}
private CalendarSelectionModel createCalendarModel() throws RaplaException {
User user = getFacade().getUser();
CalendarSelectionModel model = getFacade().newCalendarModel( user);
model.load( null );
return model;
}
}
| 04900db4-rob | src/org/rapla/client/internal/RaplaClientServiceImpl.java | Java | gpl3 | 35,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.client.internal;
import java.awt.Component;
import java.util.Locale;
import javax.swing.Action;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JList;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.logger.Logger;
import org.rapla.gui.toolkit.RaplaWidget;
final public class LanguageChooser implements RaplaWidget
{
JComboBox jComboBox;
String country;
RaplaContext context;
Logger logger;
public LanguageChooser(Logger logger,RaplaContext context) throws RaplaException {
this.logger = logger;
this.context = context;
final I18nBundle i18n = context.lookup( RaplaComponent.RAPLA_RESOURCES);
final RaplaLocale raplaLocale = context.lookup( RaplaLocale.class );
country = raplaLocale.getLocale().getCountry();
String[] languages = raplaLocale.getAvailableLanguages();
String[] entries = new String[languages.length + 1];
System.arraycopy( languages, 0, entries, 1, languages.length);
@SuppressWarnings("unchecked")
JComboBox jComboBox2 = new JComboBox(entries);
jComboBox = jComboBox2;
DefaultListCellRenderer aRenderer = new DefaultListCellRenderer() {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
if ( value != null)
{
value = new Locale( (String) value,country).getDisplayLanguage( raplaLocale.getLocale());
}
else
{
value = i18n.getString("default") + " " + i18n.getString("preferences");
}
return super.getListCellRendererComponent(list,
value,
index,
isSelected,
cellHasFocus);
}
};
setRenderer(aRenderer);
//jComboBox.setSelectedItem( raplaLocale.getLocale().getLanguage());
}
@SuppressWarnings("unchecked")
private void setRenderer(DefaultListCellRenderer aRenderer) {
jComboBox.setRenderer(aRenderer);
}
public JComponent getComponent() {
return jComboBox;
}
public void setSelectedLanguage(String lang) {
jComboBox.setSelectedItem(lang);
}
public String getSelectedLanguage()
{
return (String) jComboBox.getSelectedItem();
}
public void setChangeAction( Action languageChanged )
{
jComboBox.setAction( languageChanged );
}
}
| 04900db4-rob | src/org/rapla/client/internal/LanguageChooser.java | Java | gpl3 | 4,250 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.client;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.internal.ConfigTools;
final public class MainWebstart
{
public static void main(String[] args) {
MainWebclient main = new MainWebclient();
try {
main.init( ConfigTools.webstartConfigToURL( MainWebclient.CLIENT_CONFIG_SERVLET_URL),StartupEnvironment.WEBSTART);
main.startRapla("client");
} catch (Throwable ex) {
main.getLogger().error("Couldn't start Rapla",ex);
main.raplaContainer.dispose();
System.out.flush();
try
{
Thread.sleep( 2000 );
}
catch ( InterruptedException e )
{
}
System.exit(1);
}
}
}
| 04900db4-rob | src/org/rapla/client/MainWebstart.java | Java | gpl3 | 1,750 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.client;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.rapla.framework.StartupEnvironment;
/** The applet-encapsulation of the Main.class reads the configuration
* from the document-base of the applet and displays
* an applet with a start button.
* @author Christopher Kohlhaas
* @see MainWebstart
*/
final public class MainApplet extends JApplet
{
private static final long serialVersionUID = 1L;
JPanel dlg = new JPanel();
JButton button;
JLabel label;
boolean startable = false;
public MainApplet()
{
JPanel panel1 = new JPanel();
panel1.setBackground( new Color( 255, 255, 204 ) );
GridLayout gridLayout1 = new GridLayout();
gridLayout1.setColumns( 1 );
gridLayout1.setRows( 3 );
gridLayout1.setHgap( 10 );
gridLayout1.setVgap( 10 );
panel1.setLayout( gridLayout1 );
label = new JLabel( "Rapla-Applet loading" );
panel1.add( label );
button = new JButton( "StartRapla" );
button.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
startThread();
}
} );
panel1.add( button );
dlg.setBackground( new Color( 255, 255, 204 ) );
dlg.setBorder( BorderFactory.createMatteBorder( 1, 1, 2, 2, Color.black ) );
dlg.add( panel1 );
}
public void start()
{
getRootPane().putClientProperty( "defeatSystemEventQueueCheck", Boolean.TRUE );
try
{
setContentPane( dlg );
button.setEnabled( startable );
startable = true;
button.setEnabled( startable );
}
catch ( Exception ex )
{
ex.printStackTrace();
}
}
private void updateStartable()
{
javax.swing.SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
button.setEnabled( startable );
}
} );
}
private void startThread()
{
( new Thread()
{
public void run()
{
try
{
startable = false;
updateStartable();
MainWebclient main = new MainWebclient();
URL configURL = new URL( getDocumentBase(), MainWebclient.CLIENT_CONFIG_SERVLET_URL );
main.init( configURL, StartupEnvironment.APPLET );
main.env.setDownloadURL( getDocumentBase() );
System.out.println( "Docbase " + getDocumentBase() );
main.startRapla("client");
}
catch ( Exception ex )
{
ex.printStackTrace();
}
finally
{
startable = true;
updateStartable();
}
}
} ).start();
}
}
| 04900db4-rob | src/org/rapla/client/MainApplet.java | Java | gpl3 | 4,230 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.client;
import org.rapla.ConnectInfo;
public interface RaplaClientListener
{
public void clientStarted();
public void clientClosed(ConnectInfo reconnect);
public void clientAborted();
}
| 04900db4-rob | src/org/rapla/client/RaplaClientListener.java | Java | gpl3 | 1,155 |
package org.rapla.client;
import java.util.List;
import org.rapla.ConnectInfo;
import org.rapla.framework.Container;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.TypedComponentRole;
public interface ClientServiceContainer extends Container
{
TypedComponentRole<List<PluginDescriptor<ClientServiceContainer>>> CLIENT_PLUGIN_LIST = new TypedComponentRole<List<PluginDescriptor<ClientServiceContainer>>>("client-plugin-list");
void start(ConnectInfo connectInfo) throws Exception;
//void addCompontentOnClientStart(Class<ClientExtension> componentToStart);
boolean isRunning();
}
| 04900db4-rob | src/org/rapla/client/ClientServiceContainer.java | Java | gpl3 | 637 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.client;
import java.net.URL;
import org.rapla.ConnectInfo;
import org.rapla.RaplaMainContainer;
import org.rapla.RaplaStartupEnvironment;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.logger.ConsoleLogger;
import org.rapla.framework.logger.Logger;
public class MainWebclient
{
/** The default config filename for client-mode raplaclient.xconf*/
public final static String CLIENT_CONFIG_SERVLET_URL = "rapla/raplaclient.xconf";
private Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_WARN).getChildLogger("init");
RaplaStartupEnvironment env = new RaplaStartupEnvironment();
Container raplaContainer;
void init(URL configURL,int mode) throws Exception {
env.setStartupMode( mode );
env.setConfigURL( configURL );
env.setBootstrapLogger( getLogger() );
}
void startRapla(final String id) throws Exception {
ConnectInfo connectInfo = null;
startRapla(id, connectInfo);
}
protected void startRapla(final String id, ConnectInfo connectInfo) throws Exception, RaplaContextException {
raplaContainer = new RaplaMainContainer( env);
ClientServiceContainer clientContainer = raplaContainer.lookup(ClientServiceContainer.class, id );
ClientService client = clientContainer.getContext().lookup( ClientService.class);
client.addRaplaClientListener(new RaplaClientListenerAdapter() {
public void clientClosed(ConnectInfo reconnect) {
if ( reconnect != null) {
raplaContainer.dispose();
try {
startRapla(id, reconnect);
} catch (Exception ex) {
getLogger().error("Error restarting client",ex);
exit();
}
} else {
exit();
}
}
public void clientAborted()
{
exit();
}
});
clientContainer.start(connectInfo);
}
public static void main(String[] args) {
MainWebclient main = new MainWebclient();
try {
main.init( new URL("http://localhost:8051/rapla/raplaclient.xconf"),StartupEnvironment.CONSOLE);
main.startRapla("client");
} catch (Throwable ex) {
main.getLogger().error("Couldn't start Rapla",ex);
main.raplaContainer.dispose();
System.out.flush();
try
{
Thread.sleep( 2000 );
}
catch ( InterruptedException e )
{
}
System.exit(1);
}
}
private void exit() {
if ( raplaContainer != null)
{
raplaContainer.dispose();
}
if (env.getStartupMode() != StartupEnvironment.APPLET)
{
System.exit(0);
}
}
Logger getLogger() {
return logger;
}
}
| 04900db4-rob | src/org/rapla/client/MainWebclient.java | Java | gpl3 | 4,119 |
<body>
<p>
The client package is responsible for initialize the gui
and the client-plugins and providing the services for the
client application.
</p>
</body>
| 04900db4-rob | src/org/rapla/client/package.html | HTML | gpl3 | 164 |
package org.rapla.client;
/** classes implementing ClientExtension are started automaticaly when a user has successfully login into the Rapla system. A class added as service doesn't need to implement a specific interface and is instanciated automaticaly after client login. You can add a RaplaContext parameter to your constructor to get access to the services of rapla.
* Generally you don't need to start a client service. It is better to provide functionality through the RaplaClientExtensionPoints
*/
public interface ClientExtension {
}
| 04900db4-rob | src/org/rapla/client/ClientExtension.java | Java | gpl3 | 557 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.client;
import org.rapla.ConnectInfo;
public class RaplaClientListenerAdapter implements RaplaClientListener
{
public void clientStarted() {
}
public void clientClosed(ConnectInfo reconnect) {
}
public void clientAborted()
{
}
}
| 04900db4-rob | src/org/rapla/client/RaplaClientListenerAdapter.java | Java | gpl3 | 1,223 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.client;
import java.util.Map;
import org.rapla.entities.User;
import org.rapla.facade.ClientFacade;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.gui.toolkit.RaplaFrame;
import org.rapla.gui.toolkit.RaplaWidget;
/** This service starts and manages the rapla-gui-client.
*/
public interface ClientService
{
public static TypedComponentRole<Map<Object,Object>> SESSION_MAP = new TypedComponentRole<Map<Object,Object>>("org.rapla.SessionMap");
public static TypedComponentRole<RaplaFrame> MAIN_COMPONENT = new TypedComponentRole<RaplaFrame>("org.rapla.MainComponent");
public static TypedComponentRole<RaplaWidget> WELCOME_FIELD = new TypedComponentRole<RaplaWidget>("org.rapla.gui.WelcomeField");
void addRaplaClientListener(RaplaClientListener listener);
void removeRaplaClientListener(RaplaClientListener listener);
ClientFacade getFacade() throws RaplaContextException;
/** setup a component with the services logger,context and servicemanager */
boolean isRunning();
/** the admin can switch to another user!
* @throws RaplaContextException
* @throws RaplaException */
void switchTo(User user) throws RaplaException;
/** returns true if the admin has switched to anoter user!*/
boolean canSwitchBack();
/** restarts the complete Client and displays a new login*/
void restart();
/** returns true if an logout option is available. This is true when the user used an login dialog.*/
boolean isLogoutAvailable();
RaplaContext getContext();
void logout();
}
| 04900db4-rob | src/org/rapla/client/ClientService.java | Java | gpl3 | 2,673 |
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-rob | src/org/rapla/examples/SimpleConnectorStartupEnvironment.java | Java | gpl3 | 2,457 |
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-rob | src/org/rapla/examples/RaplaConnectorTest.java | Java | gpl3 | 1,670 |
/*--------------------------------------------------------------------------*
| 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-rob | src/org/rapla/examples/RaplaImportUsers.java | Java | gpl3 | 4,453 |
<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-rob | src/org/rapla/overview.html | HTML | gpl3 | 509 |
// 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-rob | src/org/rapla/rest/gwtjsonrpc/common/RemoteJsonService.java | Java | gpl3 | 1,932 |
// 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-rob | src/org/rapla/rest/gwtjsonrpc/common/AsyncCallback.java | Java | gpl3 | 1,288 |
// 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-rob | src/org/rapla/rest/gwtjsonrpc/common/JsonConstants.java | Java | gpl3 | 1,719 |
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-rob | src/org/rapla/rest/gwtjsonrpc/common/JSONParserWrapper.java | Java | gpl3 | 4,093 |
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-rob | src/org/rapla/rest/gwtjsonrpc/common/FutureResult.java | Java | gpl3 | 203 |
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-rob | src/org/rapla/rest/gwtjsonrpc/common/ResultType.java | Java | gpl3 | 296 |
// 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-rob | 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;
/** Mock object for AsyncCallbacks which do not need to return data. */
public class VoidResult {
public static final VoidResult INSTANCE = new VoidResult();
protected VoidResult() {
}
}
| 04900db4-rob | 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-rob | src/org/rapla/rest/gwtjsonrpc/common/ResultImpl.java | Java | gpl3 | 920 |
// 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-rob | 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.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-rob | src/org/rapla/rest/gwtjsonrpc/server/RPCServletUtils.java | Java | gpl3 | 2,195 |
// 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-rob | 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;
/** Indicates the requested method is not known. */
@SuppressWarnings("serial")
class NoSuchRemoteMethodException extends RuntimeException {
}
| 04900db4-rob | 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;
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-rob | 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;
/** 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-rob | 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;
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-rob | 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.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-rob | 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;
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-rob | src/org/rapla/rest/gwtjsonrpc/server/ActiveCall.java | Java | gpl3 | 2,653 |