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.plugin.export2ical;
import java.beans.PropertyChangeListener;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.PublishExtension;
import org.rapla.gui.PublishExtensionFactory;
public class IcalPublicExtensionFactory extends RaplaComponent implements PublishExtensionFactory
{
public IcalPublicExtensionFactory(RaplaContext context)
{
super(context);
}
public PublishExtension creatExtension(CalendarSelectionModel model,
PropertyChangeListener revalidateCallback) throws RaplaException
{
return new IcalPublishExtension(getContext(), model);
}
} | 04900db4-rob | src/org/rapla/plugin/export2ical/IcalPublicExtensionFactory.java | Java | gpl3 | 752 |
package org.rapla.plugin.export2ical;
import javax.jws.WebService;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.rest.gwtjsonrpc.common.RemoteJsonService;
import org.rapla.rest.gwtjsonrpc.common.ResultType;
@WebService
public interface ICalTimezones extends RemoteJsonService
{
@ResultType(String.class)
FutureResult<String> getICalTimezones();
@ResultType(String.class)
FutureResult<String> getDefaultTimezone();
} | 04900db4-rob | src/org/rapla/plugin/export2ical/ICalTimezones.java | Java | gpl3 | 451 |
package org.rapla.plugin.export2ical;
import javax.jws.WebService;
import org.rapla.framework.RaplaException;
@WebService
public interface ICalExport {
String export(String[] appointments) throws RaplaException;
} | 04900db4-rob | src/org/rapla/plugin/export2ical/ICalExport.java | Java | gpl3 | 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.plugin.export2ical.server;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.TimeZone;
import net.fortuna.ical4j.data.CalendarOutputter;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.ValidationException;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.storage.EntityResolver;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.export2ical.ICalExport;
import org.rapla.server.RemoteMethodFactory;
import org.rapla.server.RemoteSession;
import org.rapla.server.TimeZoneConverter;
public class RaplaICalExport extends RaplaComponent implements RemoteMethodFactory<ICalExport>, ICalExport
{
public RaplaICalExport( RaplaContext context) {
super( context );
}
public void export(String[] appointmentIds, OutputStream out ) throws RaplaException, IOException
{
TimeZone timeZone = getContext().lookup( TimeZoneConverter.class).getImportExportTimeZone();
Export2iCalConverter converter = new Export2iCalConverter(getContext(),timeZone, null);
if ( appointmentIds.length == 0)
{
return;
}
EntityResolver operator = (EntityResolver) getClientFacade().getOperator();
Collection<Appointment> appointments = new ArrayList<Appointment>();
for ( String id:appointmentIds)
{
Appointment app = operator.resolve( id , Appointment.class);
appointments.add( app );
}
Calendar iCal = converter.createiCalender(appointments);
if (null != iCal) {
export(iCal, out);
}
}
private void export(Calendar ical, OutputStream out) throws RaplaException,IOException
{
CalendarOutputter calOutputter = new CalendarOutputter();
try {
calOutputter.output(ical, out);
} catch (ValidationException e) {
throw new RaplaException(e.getMessage());
}
}
@Override
public String export( String[] appointmentIds) throws RaplaException
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
export(appointmentIds, out);
} catch (IOException e) {
throw new RaplaException( e.getMessage() , e);
}
return out.toString();
}
public ICalExport createService(RemoteSession remoteSession) {
return RaplaICalExport.this;
}
}
| 04900db4-rob | src/org/rapla/plugin/export2ical/server/RaplaICalExport.java | Java | gpl3 | 3,564 |
package org.rapla.plugin.export2ical.server;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.plugin.export2ical.Export2iCalPlugin;
import org.rapla.plugin.export2ical.ICalExport;
import org.rapla.plugin.export2ical.ICalTimezones;
import org.rapla.server.ServerServiceContainer;
import org.rapla.server.internal.RemoteStorageImpl;
public class Export2iCalServerPlugin implements PluginDescriptor<ServerServiceContainer> {
public void provideServices(ServerServiceContainer container, Configuration config) throws RaplaContextException {
container.addRemoteMethodFactory(ICalTimezones.class, RaplaICalTimezones.class, config);
convertSettings(container.getContext(), config);
if (!config.getAttributeAsBoolean("enabled", Export2iCalPlugin.ENABLE_BY_DEFAULT))
return;
container.addContainerProvidedComponent(Export2iCalPlugin.RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig(Export2iCalPlugin.RESOURCE_FILE.getId()));
container.addRemoteMethodFactory(ICalExport.class, RaplaICalExport.class);
container.addWebpage(Export2iCalPlugin.GENERATOR,Export2iCalServlet.class);
}
private void convertSettings(RaplaContext context,Configuration config) throws RaplaContextException
{
String className = Export2iCalPlugin.class.getName();
TypedComponentRole<RaplaConfiguration> newConfKey = Export2iCalPlugin.ICAL_CONFIG;
if ( config.getChildren().length > 0)
{
RemoteStorageImpl.convertToNewPluginConfig(context, className, newConfKey);
}
}
} | 04900db4-rob | src/org/rapla/plugin/export2ical/server/Export2iCalServerPlugin.java | Java | gpl3 | 1,841 |
package org.rapla.plugin.export2ical.server;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import net.fortuna.ical4j.model.TimeZone;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.plugin.export2ical.ICalTimezones;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.rest.gwtjsonrpc.common.ResultImpl;
import org.rapla.server.RemoteMethodFactory;
import org.rapla.server.RemoteSession;
import org.rapla.server.TimeZoneConverter;
public class RaplaICalTimezones extends RaplaComponent implements ICalTimezones, RemoteMethodFactory<ICalTimezones>{
List<String> availableIDs;
TimeZoneConverter converter;
public RaplaICalTimezones(RaplaContext context) throws RaplaContextException {
super( context);
availableIDs = new ArrayList<String>(Arrays.asList( TimeZone.getAvailableIDs()));
Collections.sort(availableIDs, String.CASE_INSENSITIVE_ORDER);
this.converter = context.lookup( TimeZoneConverter.class);
}
public ICalTimezones createService(RemoteSession remoteSession) {
return this;
}
public FutureResult<String> getICalTimezones() {
StringBuffer buf = new StringBuffer();
for (String id:availableIDs)
{
buf.append(id);
buf.append(";");
}
String result = buf.toString();
return new ResultImpl<String>( result);
}
//public static final String TIMEZONE = "timezone";
public FutureResult<String> getDefaultTimezone()
{
String id = converter.getImportExportTimeZone().getID();
return new ResultImpl<String>(id);
}
}
| 04900db4-rob | src/org/rapla/plugin/export2ical/server/RaplaICalTimezones.java | Java | gpl3 | 1,650 |
package org.rapla.plugin.export2ical.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.fortuna.ical4j.data.CalendarOutputter;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.ValidationException;
import org.rapla.components.util.DateTools;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarNotFoundExeption;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaDefaultContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.logger.Logger;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.plugin.export2ical.Export2iCalPlugin;
import org.rapla.server.TimeZoneConverter;
import org.rapla.servletpages.RaplaPageGenerator;
public class Export2iCalServlet extends RaplaComponent implements RaplaPageGenerator {
private int global_daysBefore;
private int global_daysAfter;
// private String username;
// private String filename;
private boolean global_interval;
//private HttpServletResponse response;
private SimpleDateFormat rfc1123DateFormat;
// private SimpleTimeZone gmt = new SimpleTimeZone(0, "GMT");
//private java.util.Calendar calendar;
//private Preferences preferences;
private Date firstPluginStartDate = new Date(0);
//private TimeZone pluginTimeZone;
private int lastModifiedIntervall;
public Export2iCalServlet(RaplaContext context) throws RaplaException{
super(createLoggerContext(context));
RaplaConfiguration config = context.lookup(ClientFacade.class).getSystemPreferences().getEntry(Export2iCalPlugin.ICAL_CONFIG, new RaplaConfiguration());
global_interval = config.getChild(Export2iCalPlugin.GLOBAL_INTERVAL).getValueAsBoolean(Export2iCalPlugin.DEFAULT_globalIntervall);
global_daysBefore = config.getChild(Export2iCalPlugin.DAYS_BEFORE).getValueAsInteger(Export2iCalPlugin.DEFAULT_daysBefore);
global_daysAfter = config.getChild(Export2iCalPlugin.DAYS_AFTER).getValueAsInteger(Export2iCalPlugin.DEFAULT_daysAfter);
rfc1123DateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.US);
rfc1123DateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));
lastModifiedIntervall = config.getChild(Export2iCalPlugin.LAST_MODIFIED_INTERVALL).getValueAsInteger(10);
}
public static RaplaContext createLoggerContext(RaplaContext context) throws RaplaContextException
{
Logger logger = context.lookup(Logger.class);
RaplaDefaultContext newContext = new RaplaDefaultContext( context);
newContext.put(Logger.class, logger.getChildLogger("ical"));
return newContext;
}
public void generatePage(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
//this.response = response;
final String filename = request.getParameter("file");
final String username = request.getParameter("user");
getLogger().debug("File: "+filename);
getLogger().debug("User: "+username);
boolean isAllAppointmentsSet = request.getParameter("complete") != null;
// if param COMPLETE is given, retrieve all appointments
try {
final User user;
String message = "The calendar '" + filename + "' you tried to retrieve is not published or available for the user " + username + ".";
try
{
user = getQuery().getUser(username);
}
catch (EntityNotFoundException ex)
{
response.getWriter().println(message);
getLogger().getChildLogger("404").warn(message);
response.setStatus( 404);
return;
}
final Preferences preferences = getQuery().getPreferences(user);
final CalendarModel calModel = getCalendarModel(preferences, user, filename);
if (calModel == null) {
response.getWriter().println(message);
response.setStatus( 404);
getLogger().getChildLogger("404").warn(message);
return;
}
response.setHeader("Last-Modified", rfc1123DateFormat.format(getLastModified(calModel)));
final Object isSet = calModel.getOption(Export2iCalPlugin.ICAL_EXPORT);
if((isSet == null || isSet.equals("false")))
{
response.getWriter().println(message);
getLogger().getChildLogger("404").warn(message);
response.setStatus( 404);
return;
}
if (request.getMethod().equals("HEAD")) {
return;
}
final Reservation[] reserv = isAllAppointmentsSet ? getAllReservations(calModel) : calModel.getReservations();
Allocatable[] allocatables = calModel.getSelectedAllocatables();
Collection<Appointment> appointments = RaplaBuilder.getAppointments(Arrays.asList( reserv), Arrays.asList(allocatables));
write(response, appointments, filename, null);
} catch (Exception e) {
response.getWriter().println(("An error occured giving you the Calendarview for user " + username + " named " + filename));
response.getWriter().println();
e.printStackTrace(response.getWriter());
getLogger().error( e.getMessage(), e);
}
}
/**
* Retrieves CalendarModel by username && filename, sets appropriate before
* and after times (only if global intervall is false)
*
* @param user
* the Rapla-User
* @param filename
* the Filename of the exported view
* @return
*/
private CalendarModel getCalendarModel(Preferences preferences, User user, String filename) {
try {
final CalendarSelectionModel calModel = getClientFacade().newCalendarModel( user);
calModel.load(filename);
int daysBefore = global_interval ? global_daysBefore : preferences.getEntryAsInteger(Export2iCalPlugin.PREF_BEFORE_DAYS, 11);
int daysAfter = global_interval ? global_daysAfter : preferences.getEntryAsInteger(Export2iCalPlugin.PREF_AFTER_DAYS, global_daysAfter);
final Date now = new Date();
//calModel.getReservations(startDate, endDate)
final RaplaLocale raplaLocale = getRaplaLocale();
final java.util.Calendar calendar = raplaLocale.createCalendar();
// set start Date
calendar.setTime(now);
calendar.add(java.util.Calendar.DAY_OF_YEAR, -daysBefore);
calModel.setStartDate(calendar.getTime());
// set end Date
calendar.setTime(now);
calendar.add(java.util.Calendar.DAY_OF_YEAR, daysAfter);
calModel.setEndDate(calendar.getTime());
//debug sysout
//System.out.println("startdate - before "+ calModel.getStartDate() + " - " + daysBefore);
//System.out.println("enddate - after "+ calModel.getStartDate() + " - " + daysAfter);
return calModel;
}
catch (CalendarNotFoundExeption ex)
{
return null;
}
catch (RaplaException e)
{
getLogger().getChildLogger("404").error("The Calendarmodel " + filename + " could not be read for the user " + user + " due to " + e.getMessage());
return null;
} catch (NullPointerException e)
{
return null;
}
}
private Reservation[] getAllReservations(final CalendarModel calModel) throws RaplaException {
final RaplaLocale raplaLocale = getRaplaLocale();
final java.util.Calendar calendar = raplaLocale.createCalendar();
calendar.set(calendar.getMinimum(java.util.Calendar.YEAR), calendar.getMinimum(java.util.Calendar.MONTH), calendar.getMinimum(java.util.Calendar.DAY_OF_MONTH));
calModel.setStartDate(calendar.getTime());
// Calendar.getMaximum doesn't work with iCal4j. Using 9999
calendar.set(9999, calendar.getMaximum(java.util.Calendar.MONTH), calendar.getMaximum(java.util.Calendar.DAY_OF_MONTH));
calModel.setEndDate(calendar.getTime());
return calModel.getReservations();
}
private void write(final HttpServletResponse response, final Collection<Appointment> appointments, String filename, final Preferences preferences) throws RaplaException, IOException {
if (filename == null )
{
filename = getString("default");
}
RaplaLocale raplaLocale = getRaplaLocale();
response.setContentType("text/calendar; charset=" + raplaLocale.getCharsetNonUtf());
response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".ics");
if (appointments == null) {
throw new RaplaException("Error with returning '" + filename);
}
final RaplaContext context = getContext();
TimeZone timezone = context.lookup( TimeZoneConverter.class).getImportExportTimeZone();
final Export2iCalConverter converter = new Export2iCalConverter(context,timezone, preferences);
final Calendar iCal = converter.createiCalender(appointments);
final CalendarOutputter calOutputter = new CalendarOutputter();
final PrintWriter responseWriter = response.getWriter();
try {
calOutputter.output(iCal, responseWriter);
} catch (ValidationException e) {
getLogger().error("The calendar file is invalid!\n" + e);
} finally
{
responseWriter.close();
}
}
/**
* Calculates Global-Lastmod By modulo operations, this returns a fresh
* last-mod every n days n can be set for all users in the last-modified
* intervall settings
*
* @return
*/
public Date getGlobalLastModified()
{
if (lastModifiedIntervall == -1)
{
return firstPluginStartDate;
}
java.util.Calendar calendar = getRaplaLocale().createCalendar();
long nowInMillis = DateTools.cutDate(new Date()).getTime();
long daysSinceStart = (nowInMillis - firstPluginStartDate.getTime()) / DateTools.MILLISECONDS_PER_DAY;
calendar.setTimeInMillis(nowInMillis - (daysSinceStart % lastModifiedIntervall) * DateTools.MILLISECONDS_PER_DAY);
return calendar.getTime();
}
/**
* Get last modified if a list of allocatables
*
* @param allocatable
* @return
*/
public Date getLastModified(CalendarModel calModel) throws RaplaException {
Date endDate = null;
Date startDate = getClientFacade().today();
final Reservation[] reservations = calModel.getReservations(startDate, endDate);
// set to minvalue
Date maxDate = new Date();
maxDate.setTime(0);
for (Reservation r:reservations)
{
Date lastMod = r.getLastChanged();
if (lastMod != null && maxDate.before(lastMod)) {
maxDate = lastMod;
}
}
if (lastModifiedIntervall != -1 && DateTools.countDays(maxDate, new Date()) < lastModifiedIntervall) {
return maxDate;
} else {
return getGlobalLastModified();
}
}
}
| 04900db4-rob | src/org/rapla/plugin/export2ical/server/Export2iCalServlet.java | Java | gpl3 | 11,285 |
package org.rapla.plugin.export2ical.server;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.TimeZone;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.ComponentList;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.PropertyList;
import net.fortuna.ical4j.model.Recur;
import net.fortuna.ical4j.model.TimeZoneRegistry;
import net.fortuna.ical4j.model.TimeZoneRegistryFactory;
import net.fortuna.ical4j.model.WeekDay;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.component.VTimeZone;
import net.fortuna.ical4j.model.parameter.Cn;
import net.fortuna.ical4j.model.parameter.PartStat;
import net.fortuna.ical4j.model.parameter.Role;
import net.fortuna.ical4j.model.property.Attendee;
import net.fortuna.ical4j.model.property.Categories;
import net.fortuna.ical4j.model.property.Created;
import net.fortuna.ical4j.model.property.DtEnd;
import net.fortuna.ical4j.model.property.DtStamp;
import net.fortuna.ical4j.model.property.DtStart;
import net.fortuna.ical4j.model.property.ExDate;
import net.fortuna.ical4j.model.property.LastModified;
import net.fortuna.ical4j.model.property.Location;
import net.fortuna.ical4j.model.property.Method;
import net.fortuna.ical4j.model.property.Organizer;
import net.fortuna.ical4j.model.property.ProdId;
import net.fortuna.ical4j.model.property.RRule;
import net.fortuna.ical4j.model.property.Summary;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Version;
import net.fortuna.ical4j.util.CompatibilityHints;
import org.rapla.components.util.DateTools;
import org.rapla.entities.Entity;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.ConfigurationException;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.plugin.export2ical.Export2iCalPlugin;
import org.rapla.server.TimeZoneConverter;
public class Export2iCalConverter extends RaplaComponent {
public boolean attendeeToTitle = true;
net.fortuna.ical4j.model.TimeZone timeZone;
private java.util.Calendar calendar;
private String exportAttendeesAttribute;
private String exportAttendeesParticipationStatus;
private boolean doExportAsMeeting;
TimeZoneConverter timezoneConverter;
boolean hasLocationType;
public Export2iCalConverter(RaplaContext context, TimeZone zone, Preferences preferences) throws RaplaException {
super(context);
timezoneConverter = context.lookup( TimeZoneConverter.class);
calendar = context.lookup(RaplaLocale.class).createCalendar();
doExportAsMeeting = false;
DynamicType[] dynamicTypes = getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE);
for ( DynamicType type:dynamicTypes)
{
if (type.getAnnotation( DynamicTypeAnnotations.KEY_LOCATION) != null)
{
hasLocationType = true;
}
}
CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true);
RaplaConfiguration config = context.lookup(ClientFacade.class).getSystemPreferences().getEntry(Export2iCalPlugin.ICAL_CONFIG, new RaplaConfiguration());
boolean global_export_attendees = config.getChild(Export2iCalPlugin.EXPORT_ATTENDEES).getValueAsBoolean(Export2iCalPlugin.DEFAULT_exportAttendees);
String global_export_attendees_participation_status = config.getChild(Export2iCalPlugin.EXPORT_ATTENDEES_PARTICIPATION_STATUS).getValue(Export2iCalPlugin.DEFAULT_attendee_participation_status);
doExportAsMeeting = preferences == null ? global_export_attendees : preferences.getEntryAsBoolean(Export2iCalPlugin.EXPORT_ATTENDEES_PREFERENCE, global_export_attendees);
exportAttendeesParticipationStatus = preferences == null ? global_export_attendees_participation_status : preferences.getEntryAsString(Export2iCalPlugin.EXPORT_ATTENDEES_PARTICIPATION_STATUS_PREFERENCE, global_export_attendees_participation_status);
try {
exportAttendeesAttribute = config.getChild(Export2iCalPlugin.EXPORT_ATTENDEES_EMAIL_ATTRIBUTE).getValue();
} catch (ConfigurationException e) {
exportAttendeesAttribute = "";
getLogger().info("ExportAttendeesMailAttribute is not set. So do not export as meeting");
}
//ensure the stored value is not empty string, if so, do not export attendees
doExportAsMeeting = doExportAsMeeting && (exportAttendeesAttribute != null && exportAttendeesAttribute.trim().length() > 0);
if (zone != null) {
final String timezoneId = zone.getID();
try {
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
timeZone = registry.getTimeZone(timezoneId);
} catch (Exception rc) {
final VTimeZone vTimeZone = new VTimeZone();
timeZone = new net.fortuna.ical4j.model.TimeZone(vTimeZone);
final int rawOffset = zone.getRawOffset();
timeZone.setRawOffset(rawOffset);
}
}
}
public Calendar createiCalender(Collection<Appointment> appointments)
{
Calendar calendar = initiCalendar();
addICalMethod(calendar, Method.PUBLISH);
addVTimeZone(calendar);
ComponentList components = calendar.getComponents();
for (Appointment app:appointments)
{
VEvent event = createVEvent(app);
components.add(event);
}
return calendar;
}
private void addVTimeZone(Calendar calendar) {
if (timeZone != null) {
VTimeZone tz = timeZone.getVTimeZone();
calendar.getComponents().add(tz);
}
}
/**
* Initialisiert ein neues leeres iCalendar-Objekt.
*
* @return Ein neues leeres iCalendar-Objekt.
*/
public Calendar initiCalendar() {
Calendar calendar = new Calendar();
calendar.getProperties().add(new ProdId("-//Rapla//iCal Plugin//EN"));
calendar.getProperties().add(Version.VERSION_2_0);
return calendar;
}
public void addICalMethod(Calendar iCalendar, Method method) {
iCalendar.getProperties().add(method);
}
public void addVEvent(Calendar iCalendar, Appointment appointment) {
iCalendar.getComponents().add(createVEvent(appointment));
}
/**
* Erstellt anhand des übergebenen Appointment-Objekts einen
* iCalendar-Event.
*
* @param appointment Ein Rapla Appointment.
* @return Ein iCalendar-Event mit den Daten des Appointments.
*/
private VEvent createVEvent(Appointment appointment) {
PropertyList properties = new PropertyList();
boolean isAllDayEvent = appointment.isWholeDaysSet() ;
addDateStampToEvent(appointment, properties);
addCreateDateToEvent(appointment, properties);
addStartDateToEvent(appointment, properties, isAllDayEvent);
addLastModifiedDateToEvent(appointment, properties);
addEndDateToEvent(appointment, properties, isAllDayEvent);
addEventNameToEvent(appointment, properties);
addUidToEvent(appointment, properties);
addLocationToEvent(appointment, properties);
addCategories(appointment, properties);
addOrganizer(appointment, properties);
addAttendees(appointment, properties);
addRepeatings(appointment, properties);
VEvent event = new VEvent(properties);
return event;
}
/**
* add organizer to properties
*
* @param appointment
* @param properties
*/
private void addOrganizer(Appointment appointment, PropertyList properties) {
// means we do not export attendees so we do not have a meeting
if (!doExportAsMeeting)
return;
final User owner = appointment.getReservation().getOwner();
try {
Organizer organizer = null;
if (owner.getEmail() != null && owner.getEmail().trim().length() > 0) {
try {
final URI uri = new URI("MAILTO:" + owner.getEmail().trim());
organizer = new Organizer(uri);
} catch (URISyntaxException e) {
}
}
if (organizer == null) {
organizer = new Organizer("MAILTO:" + URLEncoder.encode(owner.getUsername(), "UTF-8"));
}
if (!"".equals(owner.getName()))
organizer.getParameters().add(new Cn(owner.getName()));
properties.add(organizer);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
}
/**
* add attenddees if system property ical4j.validation.relaxed is set ony
*
* @param appointment
* @param properties
*/
private void addAttendees(Appointment appointment, PropertyList properties) {
if (!doExportAsMeeting)
return;
Allocatable[] persons = appointment.getReservation().getAllocatablesFor(appointment);
for (Allocatable person : persons) {
if ( !person.isPerson() )
{
continue;
}
String email = null;
Attribute attr = person.getClassification().getAttribute(exportAttendeesAttribute);
if (attr != null && person.getClassification().getValue(attr) != null)
email = person.getClassification().getValue(attr).toString().trim();
// determine if person has email attribute
if (email != null && email.length() > 0) {
try {
Attendee attendee = new Attendee(new URI(email));
attendee.getParameters().add(Role.REQ_PARTICIPANT);
attendee.getParameters().add(new Cn(person.getName(Locale.getDefault())));
attendee.getParameters().add(new PartStat(exportAttendeesParticipationStatus));
properties.add(attendee);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
}
}
/**
* Fuegt dem Termin das Modifizierungsdatum hinzu
*
* @param appointment
* @param event
*/
private void addDateStampToEvent(Appointment appointment, PropertyList properties) {
Date lastChange = appointment.getReservation().getLastChanged();
properties.add(new LastModified(convertRaplaLocaleToUTC(lastChange)));
}
/**
* Fuegt dem Termin den DTSTAMP hinzu lt. rfc muss dies dem Erstellungdatum
* des Objektes entsprechen. Da dies jedoch den Import erschwert und sinnlos
* ist, wird es auf das letzte Modifizierungsdatum geschrieben.
*
* @param appointment
* @param event
*/
private void addLastModifiedDateToEvent(Appointment appointment, PropertyList properties) {
Date lastChange = appointment.getReservation().getLastChanged();
properties.add(new DtStamp(convertRaplaLocaleToUTC(lastChange)));
}
/**
* Fügt die Wiederholungen des übergebenen Appointment-Objekts dem
* übergebenen Event-Objekt hinzu.
*
* @param appointment Ein Rapla Appointment.
* @param event Ein iCalendar Event.
*/
private void addRepeatings(Appointment appointment, PropertyList properties) {
Repeating repeating = appointment.getRepeating();
if (repeating == null) {
return;
}
// This returns the strings DAYLY, WEEKLY, MONTHLY, YEARLY
String type = repeating.getType().toString().toUpperCase();
Recur recur;
// here is evaluated, if a COUNT is set in Rapla, or an enddate is
// specified
if (repeating.getNumber() == -1) {
recur = new Recur(type, -1);
} else if (repeating.isFixedNumber()) {
recur = new Recur(type, repeating.getNumber());
} else {
net.fortuna.ical4j.model.Date endDate = new net.fortuna.ical4j.model.Date(repeating.getEnd());
// TODO do we need to translate the enddate in utc?
recur = new Recur(type, endDate);
}
if (repeating.isDaily()) {
// DAYLY -> settings : intervall
recur.setInterval(repeating.getInterval());
} else if (repeating.isWeekly()) {
// WEEKLY -> settings : every nTh Weekday
recur.setInterval(repeating.getInterval());
calendar.setTime(appointment.getStart());
recur.getDayList().add(WeekDay.getWeekDay(calendar));
} else if (repeating.isMonthly()) {
// MONTHLY -> settings : every nTh Weekday
recur.setInterval(repeating.getInterval());
calendar.setTime(appointment.getStart());
int weekofmonth = Math.round(calendar.get(java.util.Calendar.DAY_OF_MONTH) / DateTools.DAYS_PER_WEEK) + 1;
recur.getDayList().add(new WeekDay(WeekDay.getWeekDay(calendar), weekofmonth));
} else if (repeating.isYearly()) {
// YEARLY -> settings : every nTh day mTh Monthname
calendar.setTime(appointment.getStart());
calendar.get(java.util.Calendar.DAY_OF_YEAR);
} else {
getLogger().warn("Invalid data in recurrency rule!");
}
properties.add(new RRule(recur));
// bugfix - if rapla has no exceptions, an empty EXDATE: element is
// produced. This may bother some iCal tools
if (repeating.getExceptions().length == 0) {
return;
}
// Add exception dates
//DateList dl = new DateList(Value.DATE);
ExDate exDate = new ExDate();
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
net.fortuna.ical4j.model.TimeZone tz = registry.getTimeZone(timeZone.getID());
// rku: use seperate EXDATE for each exception
for (Iterator<Date> itExceptions = Arrays.asList(repeating.getExceptions()).iterator(); itExceptions.hasNext(); ) {
//DateList dl = new DateList(Value.DATE);
Date date = itExceptions.next();
//dl.add(new net.fortuna.ical4j.model.Date( date));
java.util.Calendar cal = getRaplaLocale().createCalendar();
cal.setTime( date );
int year = cal.get( java.util.Calendar.YEAR );
int day_of_year = cal.get( java.util.Calendar.DAY_OF_YEAR);
cal.setTime( appointment.getStart());
cal.set(java.util.Calendar.YEAR, year);
cal.set(java.util.Calendar.DAY_OF_YEAR, day_of_year);
int offset =(int) (tz.getOffset( DateTools.cutDate( date).getTime())/ DateTools.MILLISECONDS_PER_HOUR);
cal.add(java.util.Calendar.HOUR, -offset);
Date dateToSave = cal.getTime();
net.fortuna.ical4j.model.DateTime dateTime = new net.fortuna.ical4j.model.DateTime();
dateTime.setTime( dateToSave.getTime());
exDate.getDates().add( dateTime);
}
exDate.setTimeZone(tz );
properties.add(exDate);
//properties.add(new ExDate(dl));
}
public String getAttendeeString(Appointment appointment) {
String attendeeString = "";
Reservation raplaReservation = appointment.getReservation();
Allocatable[] raplaPersons = raplaReservation.getPersons();
for (int i = 0; i < raplaPersons.length; i++) {
if (!isReserved(raplaPersons[i], appointment))
continue;
attendeeString += raplaPersons[i].getName(Locale.getDefault());
attendeeString = attendeeString.trim();
if (i != raplaPersons.length - 1) {
attendeeString += ", ";
} else {
attendeeString = " [" + attendeeString + "]";
}
}
return attendeeString;
}
/**
* Fügt die Kategorien hinzu.
*
* @param appointment Ein Rapla Appointment.
* @param event Ein iCalendar Event.
*/
private void addCategories(Appointment appointment, PropertyList properties) {
Classification cls = appointment.getReservation().getClassification();
Categories cat = new Categories();
cat.getCategories().add(cls.getType().getName(Locale.getDefault()));
properties.add(cat);
}
/**
* Prüfe, ob eine Ressource für ein bestimmten Appointment
* reserviert ist.
*
* @param alloc
* @param when
* @return <code>true</code>, wenn die Ressource reserviert ist.
* <code>false</code> sonst
*/
private boolean isReserved(Allocatable alloc, Appointment when) {
Reservation reservation = when.getReservation();
Appointment[] restrictions = reservation.getRestriction(alloc);
for (int restIt = 0, restLen = restrictions.length; restIt < restLen; restIt++) {
if (when.equals(restrictions[restIt]))
return true;
}
return (restrictions.length == 0);
}
/**
* Fügt einem iCal-Event den Ort aus dem übergebenen
* Appointment-Objekt hinzu.
*
* @param appointment
* @param event
*/
private void addLocationToEvent(Appointment appointment, PropertyList properties) {
Allocatable[] allocatables = appointment.getReservation().getAllocatablesFor(appointment);
StringBuffer buffer = new StringBuffer();
for (Allocatable alloc:allocatables) {
if ( hasLocationType)
{
if (alloc.getClassification().getType().getAnnotation( DynamicTypeAnnotations.KEY_LOCATION) == null )
{
continue;
}
}
else if (alloc.isPerson())
{
continue;
}
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append(alloc.getName(Locale.getDefault()));
}
properties.add(new Location(buffer.toString()));
}
/**
* Fügt einem iCal-Event die Termin-ID aus dem übergebenen
* Appointment-Objekt hinzu.
*
* @param appointment
* @param event
*/
private void addUidToEvent(Appointment appointment, PropertyList properties) {
// multiple vevents can have the same id
String uid = getId(appointment.getReservation());// + getId(appointment);
properties.add(new Uid(uid));
}
/**
* Erzeugt eine eindeutige ID für den übergebenen Appointment.
*
* @param entity
* @return
*/
private String getId(Entity entity) {
String id = entity.getId();
return id;
}
/**
* Fügt einem iCal-Event den Termin-Namen aus dem übergebenen
* Appointment-Objekt hinzu.
*
* @param appointment
* @param event
*/
private void addEventNameToEvent(Appointment appointment, PropertyList properties) {
String eventDescription = appointment.getReservation().getName(Locale.getDefault());
if (attendeeToTitle) {
eventDescription += getAttendeeString(appointment);
}
properties.add(new Summary(eventDescription));
}
/**
* Fügt einem iCal-Event das Enddatum aus dem übergebenen
* Appointment-Objekt hinzu.
*
* @param appointment
* @param event
*/
private void addEndDateToEvent(Appointment appointment, PropertyList properties, boolean isAllDayEvent) {
Date endDate = appointment.getEnd();
java.util.Calendar calendar = java.util.Calendar.getInstance();
if (isAllDayEvent) {
DtEnd end = getDtEndFromAllDayEvent(endDate, calendar);
properties.add(end);
} else {
if (appointment.getRepeating() == null) {
DtEnd end = new DtEnd(convertRaplaLocaleToUTC(endDate));
end.setUtc(true);
properties.add(end);
} else {
DtEnd end = getEndDateProperty( endDate);
properties.add(end);
}
}
}
private DtEnd getEndDateProperty( Date endDate) {
DateTime date = convertRaplaLocaleToUTC(endDate);
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
net.fortuna.ical4j.model.TimeZone tz = registry.getTimeZone(timeZone.getID());
date.setTimeZone(tz);
return new DtEnd(date);
}
private DtEnd getDtEndFromAllDayEvent(Date endDate, java.util.Calendar calendar) {
calendar.clear();
calendar.setTime(endDate);
int year = calendar.get(java.util.Calendar.YEAR);
calendar.add(java.util.Calendar.DATE, 1);
int month = calendar.get(java.util.Calendar.MONTH);
int date = calendar.get(java.util.Calendar.DAY_OF_MONTH);
calendar.clear();
calendar.set(year, month, date);
DtEnd end = new DtEnd(new net.fortuna.ical4j.model.Date(calendar.getTime()));
return end;
}
/**
* Fügt einem iCal-Event das Startdatum aus dem übergebenen
* Appointment-Objekt hinzu.
*
* @param appointment
* @param event
*/
private void addStartDateToEvent(Appointment appointment, PropertyList properties, boolean isAllDayEvent) {
Date startDate = appointment.getStart();
if (isAllDayEvent) {
DtStart start = getDtStartFromAllDayEvent(startDate, calendar);
properties.add(start);
} else {
if (appointment.getRepeating() == null) {
DtStart start = new DtStart(convertRaplaLocaleToUTC(startDate));
start.setUtc(true);
properties.add(start);
} else {
DtStart start = getStartDateProperty(startDate);
properties.add(start);
}
}
}
private DtStart getStartDateProperty( Date startDate) {
DateTime date = convertRaplaLocaleToUTC(startDate);
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
net.fortuna.ical4j.model.TimeZone tz = registry.getTimeZone(timeZone.getID());
date.setTimeZone(tz);
return new DtStart(date);
}
private DtStart getDtStartFromAllDayEvent(Date startDate, java.util.Calendar calendar) {
calendar.clear();
calendar.setTime(startDate);
int year = calendar.get(java.util.Calendar.YEAR);
int month = calendar.get(java.util.Calendar.MONTH);
int date = calendar.get(java.util.Calendar.DAY_OF_MONTH);
calendar.clear();
calendar.set(year, month, date);
DtStart start = new DtStart(new net.fortuna.ical4j.model.Date(calendar.getTime()));
return start;
}
/**
* Fügt einem iCal-Event das Erstelldatum aus dem übergebenen
* Appointment-Objekt hinzu.
*
* @param appointment
* @param event
*/
private void addCreateDateToEvent(Appointment appointment, PropertyList properties) {
Date createTime = appointment.getReservation().getCreateTime();
properties.add(new Created(convertRaplaLocaleToUTC(createTime)));
}
private DateTime convertRaplaLocaleToUTC(Date date) {
Date converted = timezoneConverter.fromRaplaTime(timeZone, date);
DateTime result = new DateTime(converted.getTime());
return result;
}
} | 04900db4-rob | src/org/rapla/plugin/export2ical/server/Export2iCalConverter.java | Java | gpl3 | 24,548 |
package org.rapla.plugin.export2ical;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.TypedComponentRole;
public class Export2iCalPlugin implements PluginDescriptor<ClientServiceContainer>{
public static final TypedComponentRole<I18nBundle> RESOURCE_FILE = new TypedComponentRole<I18nBundle>(Export2iCalPlugin.class.getPackage().getName() + ".Export2iCalResources");
public static final String PLUGIN_CLASS = Export2iCalPlugin.class.getName();
public static final TypedComponentRole<RaplaConfiguration> ICAL_CONFIG = new TypedComponentRole<RaplaConfiguration>("org.rapla.plugin.export2ical.server.Config");
public static final String ICAL_EXPORT = "org.rapla.plugin.export2ical.selected";
public static final String DAYS_BEFORE = "days_before";
public static final String DAYS_AFTER = "days_after";
public static final TypedComponentRole<Integer> PREF_BEFORE_DAYS = new TypedComponentRole<Integer>("export2iCal_before_days");
public static final TypedComponentRole<Integer> PREF_AFTER_DAYS = new TypedComponentRole<Integer>("export2iCal_after_days");
public static final String GLOBAL_INTERVAL = "global_interval";
public static final String EXPORT_ATTENDEES = "export_attendees";
public static final TypedComponentRole<Boolean> EXPORT_ATTENDEES_PREFERENCE = new TypedComponentRole<Boolean>("export_attendees");
public static final String EXPORT_ATTENDEES_EMAIL_ATTRIBUTE = "export_attendees_email_attribute";
public static final String LAST_MODIFIED_INTERVALL = "last_modified_intervall";
public static final int DEFAULT_daysBefore = 30;
public static final int DEFAULT_daysAfter = 30;
public static final boolean DEFAULT_basedOnAutoExport = true;
public static final boolean DEFAULT_globalIntervall = true;
public static final int DEFAULT_lastModifiedIntervall = 5;
public static final String DEFAULT_attendee_resource_attribute = "email";
public static final String DEFAULT_attendee_participation_status= "TENTATIVE";
public static final String GENERATOR = "ical";
public static final boolean ENABLE_BY_DEFAULT = true;
public static final boolean DEFAULT_exportAttendees = false;
public static final String EXPORT_ATTENDEES_PARTICIPATION_STATUS = "export_attendees_participation_status";
public static final TypedComponentRole<String> EXPORT_ATTENDEES_PARTICIPATION_STATUS_PREFERENCE = new TypedComponentRole<String>("export_attendees_participation_status");
public void provideServices(ClientServiceContainer container, Configuration config) throws RaplaContextException {
container.addContainerProvidedComponent(RaplaClientExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION, Export2iCalAdminOption.class);
if (!config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT))
return;
container.addContainerProvidedComponent(RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig(RESOURCE_FILE.getId()));
container.addContainerProvidedComponent( RaplaClientExtensionPoints.PUBLISH_EXTENSION_OPTION, IcalPublicExtensionFactory.class);
final int startupMode = container.getStartupEnvironment().getStartupMode();
if ( startupMode != StartupEnvironment.APPLET)
{
container.addContainerProvidedComponent(RaplaClientExtensionPoints.EXPORT_MENU_EXTENSION_POINT, Export2iCalMenu.class);
}
container.addContainerProvidedComponent(RaplaClientExtensionPoints.USER_OPTION_PANEL_EXTENSION, Export2iCalUserOption.class, config);
}
} | 04900db4-rob | src/org/rapla/plugin/export2ical/Export2iCalPlugin.java | Java | gpl3 | 3,884 |
package org.rapla.plugin.export2ical;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Locale;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.configuration.Preferences;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.RaplaGUIComponent;
/***
* This is the user-option panel
* @author Twardon
*
*/
public class Export2iCalUserOption extends RaplaGUIComponent implements OptionPanel, ActionListener {
private Preferences preferences;
private Configuration config;
private JPanel panel = new JPanel();
private JSpinner spiDaysBefore;
private JSpinner spiDaysAfter;
private JCheckBox chkUseUserdefinedIntervall;
public boolean addButtons = true;
private boolean global_interval;
private int user_days_before;
private int user_days_after;
private int global_days_before;
private int global_days_after;
private boolean userdefined;
private JCheckBox chkExportAttendees;
private JComboBox cbDefaultParticipationsStatusRessourceAttribute;
private boolean user_export_attendees;
private String user_export_attendees_participants_status;
public Export2iCalUserOption(RaplaContext sm, Configuration config) {
super(sm);
setChildBundleName(Export2iCalPlugin.RESOURCE_FILE);
this.config = config;
}
public JComponent getComponent() {
return panel;
}
public String getName(Locale locale) {
return getString("ical_export_user_settings");
}
public void createList() {
panel.removeAll();
chkExportAttendees = new JCheckBox(getString("export_attendees_of_vevent"));
chkExportAttendees.addActionListener(this);
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(new String [] {
"ACCEPTED",
"TENTATIVE"
});
cbDefaultParticipationsStatusRessourceAttribute = jComboBox;
cbDefaultParticipationsStatusRessourceAttribute.setSelectedItem(Export2iCalPlugin.DEFAULT_attendee_participation_status);
cbDefaultParticipationsStatusRessourceAttribute.setToolTipText("Define the default value for participation status");
double[][] sizes = new double[][] { { 5, TableLayout.FILL, 5,TableLayout.FILL, 5 },
{ TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.FILL, 5,
TableLayout.PREFERRED } };
TableLayout tableLayout = new TableLayout(sizes);
panel.setLayout(tableLayout);
JPanel interval = new JPanel();
interval.add(new JLabel(getString("previous_days_text")));
spiDaysBefore = new JSpinner(new SpinnerNumberModel(30, 0, 100, 1));
interval.add(spiDaysBefore);
interval.add(new JLabel(getString("subsequent_days_text")));
spiDaysAfter = new JSpinner(new SpinnerNumberModel(30, 0, 100, 1));
interval.add(spiDaysAfter);
chkUseUserdefinedIntervall = new JCheckBox(getString("use_user_interval_setting_text"));
chkUseUserdefinedIntervall.setSelected(userdefined);
interval.add(chkUseUserdefinedIntervall);
int before = global_interval ? global_days_before : user_days_before;
spiDaysBefore.setValue(new Integer(before));
int after = global_interval ? global_days_after : user_days_after;
spiDaysAfter.setValue(new Integer(after));
if (addButtons) {
panel.add(new JLabel(getString("user_interval_setting_text")), "1,0");
panel.add(chkUseUserdefinedIntervall,"1,2");
panel.add(interval, "1,4");
}
// set values
chkExportAttendees.setSelected(user_export_attendees);
cbDefaultParticipationsStatusRessourceAttribute.setSelectedItem(user_export_attendees_participants_status);
cbDefaultParticipationsStatusRessourceAttribute.setEnabled(user_export_attendees);
panel.add(chkExportAttendees, "1,6");
panel.add(new JLabel(getString("participation_status")), "1,8");
panel.add(cbDefaultParticipationsStatusRessourceAttribute, "3,8");
chkUseUserdefinedIntervall.setEnabled(!global_interval);
spiDaysAfter.setEnabled(userdefined);
spiDaysBefore.setEnabled(userdefined);
chkUseUserdefinedIntervall.addActionListener(this);
}
public void show() throws RaplaException {
global_days_before = config.getChild(Export2iCalPlugin.DAYS_BEFORE).getValueAsInteger(Export2iCalPlugin.DEFAULT_daysBefore);
global_days_after = config.getChild(Export2iCalPlugin.DAYS_AFTER).getValueAsInteger(Export2iCalPlugin.DEFAULT_daysAfter);
userdefined = (preferences.hasEntry(Export2iCalPlugin.PREF_BEFORE_DAYS) || preferences.hasEntry(Export2iCalPlugin.PREF_AFTER_DAYS));
user_days_before = preferences.getEntryAsInteger(Export2iCalPlugin.PREF_BEFORE_DAYS, global_days_before);
user_days_after = preferences.getEntryAsInteger(Export2iCalPlugin.PREF_AFTER_DAYS, global_days_after);
global_interval = config.getChild(Export2iCalPlugin.GLOBAL_INTERVAL).getValueAsBoolean(Export2iCalPlugin.DEFAULT_globalIntervall);
boolean global_export_attendees = config.getChild(Export2iCalPlugin.EXPORT_ATTENDEES).getValueAsBoolean(Export2iCalPlugin.DEFAULT_exportAttendees);
String global_export_attendees_participants_status = config.getChild(Export2iCalPlugin.EXPORT_ATTENDEES_PARTICIPATION_STATUS).getValue(Export2iCalPlugin.DEFAULT_attendee_participation_status);
user_export_attendees = preferences.getEntryAsBoolean(Export2iCalPlugin.EXPORT_ATTENDEES_PREFERENCE, global_export_attendees);
user_export_attendees_participants_status = preferences.getEntryAsString(Export2iCalPlugin.EXPORT_ATTENDEES_PARTICIPATION_STATUS_PREFERENCE, global_export_attendees_participants_status);
createList();
}
public void setPreferences(Preferences preferences) {
this.preferences = preferences;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==chkUseUserdefinedIntervall){
spiDaysBefore.setEnabled(chkUseUserdefinedIntervall.isSelected());
spiDaysAfter.setEnabled(chkUseUserdefinedIntervall.isSelected());
}
if (e.getSource() == chkExportAttendees) {
cbDefaultParticipationsStatusRessourceAttribute.setEnabled(chkExportAttendees.isSelected());
}
}
public void commit() {
//saving an null object will delete the setting
if(!chkUseUserdefinedIntervall.isSelected()){
preferences.putEntry(Export2iCalPlugin.PREF_BEFORE_DAYS, null);
preferences.putEntry(Export2iCalPlugin.PREF_AFTER_DAYS, null);
}else{
preferences.putEntry(Export2iCalPlugin.PREF_BEFORE_DAYS, new Integer(this.spiDaysBefore.getValue().toString()));
preferences.putEntry(Export2iCalPlugin.PREF_AFTER_DAYS, new Integer(this.spiDaysAfter.getValue().toString()));
}
preferences.putEntry(Export2iCalPlugin.EXPORT_ATTENDEES_PREFERENCE, chkExportAttendees.isSelected());
preferences.putEntry(Export2iCalPlugin.EXPORT_ATTENDEES_PARTICIPATION_STATUS_PREFERENCE, cbDefaultParticipationsStatusRessourceAttribute.getSelectedItem().toString());
}
}
| 04900db4-rob | src/org/rapla/plugin/export2ical/Export2iCalUserOption.java | Java | gpl3 | 7,575 |
package org.rapla.plugin.eventtimecalculator;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import org.rapla.components.util.DateTools;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.Reservation;
import org.rapla.framework.Configuration;
/**
* Created with IntelliJ IDEA.
* User: kuestermann
* Date: 10.06.13
* Time: 17:52
* To change this template use File | Settings | File Templates.
*/
public class EventTimeModel {
protected int timeTillBreak;
protected int durationOfBreak;
protected int timeUnit;
protected String timeFormat;
public EventTimeModel()
{
timeUnit = EventTimeCalculatorPlugin.DEFAULT_timeUnit;
timeFormat = EventTimeCalculatorPlugin.DEFAULT_timeFormat;
timeTillBreak = EventTimeCalculatorPlugin.DEFAULT_intervalNumber;
durationOfBreak = EventTimeCalculatorPlugin.DEFAULT_breakNumber;
}
public int getTimeTillBreak() {
return timeTillBreak;
}
public void setTimeTillBreak(int timeTillBreak) {
this.timeTillBreak = timeTillBreak;
}
public int getDurationOfBreak() {
return durationOfBreak;
}
public void setDurationOfBreak(int durationOfBreak) {
this.durationOfBreak = durationOfBreak;
}
public int getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(int timeUnit) {
this.timeUnit = timeUnit;
}
public String getTimeFormat() {
return timeFormat;
}
public void setTimeFormat(String timeFormat) {
this.timeFormat = timeFormat;
}
public EventTimeModel(Configuration configuration) {
timeTillBreak = configuration.getChild(EventTimeCalculatorPlugin.INTERVAL_NUMBER).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_intervalNumber);
durationOfBreak= configuration.getChild(EventTimeCalculatorPlugin.BREAK_NUMBER).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_breakNumber);
timeUnit= configuration.getChild(EventTimeCalculatorPlugin.TIME_UNIT).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_timeUnit);
timeFormat= configuration.getChild(EventTimeCalculatorPlugin.TIME_FORMAT).getValue(EventTimeCalculatorPlugin.DEFAULT_timeFormat);
}
public String format(long duration) {
if (duration < 0 || timeUnit == 0) {
return "";
}
return MessageFormat.format(timeFormat, duration / timeUnit, duration % timeUnit);
}
public long calcDuration(long minutes)
{
int blockTimeIncludingBreak = timeTillBreak + durationOfBreak;
if (timeTillBreak <= 0 || durationOfBreak <= 0 || minutes<=timeTillBreak)
return minutes;
long breaks = (minutes + durationOfBreak -1 ) / blockTimeIncludingBreak;
long fullBreaks = minutes / blockTimeIncludingBreak;
long partBreak;
if ( breaks > fullBreaks)
{
long timeInclFullBreak = timeTillBreak * (fullBreaks + 1) + fullBreaks * durationOfBreak ;
partBreak = minutes - timeInclFullBreak;
}
else
{
partBreak = 0;
}
long actualDuration = minutes - (fullBreaks * durationOfBreak) - partBreak;
return actualDuration;
}
public long calcDuration(Reservation reservation) {
return calcDuration(reservation.getAppointments());
}
public long calcDuration(AppointmentBlock block) {
long duration = DateTools.countMinutes(block.getStart(), block.getEnd());
return calcDuration(duration);
}
public long calcDuration(Appointment[] appointments){
final Collection<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
long totalDuration = 0;
for (Appointment app : appointments) {
Date start = app.getStart();
Date end = app.getMaxEnd();
if (end == null) {
totalDuration = -1;
break;
} else {
app.createBlocks(start, end, blocks);
}
}
for (AppointmentBlock block : blocks) {
long duration = calcDuration(block);
if (totalDuration >= 0) {
totalDuration += duration;
}
}
return totalDuration;
}
public boolean hasEnd(Appointment[] appointments) {
boolean hasEnd = true;
for (Appointment appointment : appointments) { // goes through all appointments of the reservation
if (hasEnd(appointment)) { // appoinment repeats forever?
hasEnd = false;
break;
}
}
return hasEnd;
}
public boolean hasEnd(Appointment appointment) {
return appointment != null && appointment.getRepeating() != null && appointment.getRepeating().getEnd() == null;
}
public boolean hasEnd(Reservation reservation) {
return hasEnd(reservation.getAppointments());
}
}
| 04900db4-rob | src/org/rapla/plugin/eventtimecalculator/EventTimeModel.java | Java | gpl3 | 5,010 |
package org.rapla.plugin.eventtimecalculator;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class EventTimeCalculatorFactory extends RaplaComponent
{
boolean isUserPrefAllowed;
Configuration config;
public EventTimeCalculatorFactory(RaplaContext context,Configuration config)
{
super( context);
isUserPrefAllowed = config.getChild(EventTimeCalculatorPlugin.USER_PREFS).getValueAsBoolean(EventTimeCalculatorPlugin.DEFAULT_userPrefs);
this.config = config;
}
public EventTimeModel getEventTimeModel () {
Configuration configuration = config;
if ( isUserPrefAllowed)
{
RaplaConfiguration raplaConfig;
try {
raplaConfig = getQuery().getPreferences().getEntry(EventTimeCalculatorPlugin.USER_CONFIG);
if ( raplaConfig != null)
{
configuration = raplaConfig;
}
} catch (RaplaException e) {
getLogger().warn(e.getMessage());
}
}
EventTimeModel m = new EventTimeModel(configuration);
return m;
}
}
| 04900db4-rob | src/org/rapla/plugin/eventtimecalculator/EventTimeCalculatorFactory.java | Java | gpl3 | 1,287 |
package org.rapla.plugin.eventtimecalculator;
import org.rapla.entities.domain.Reservation;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.tableview.ReservationTableColumn;
/**
* User: kuestermann
* Date: 22.08.12
* Time: 09:29
*/
public final class DurationColumnReservation extends DurationColumn implements ReservationTableColumn {
private EventTimeModel eventTimeModel;
EventTimeCalculatorFactory factory;
public DurationColumnReservation(RaplaContext context) throws RaplaException {
super(context);
factory = context.lookup(EventTimeCalculatorFactory.class);
}
public String getValue(Reservation event) {
if ( !validConf )
{
eventTimeModel = factory.getEventTimeModel();
validConf = true;
}
return eventTimeModel.format(eventTimeModel.calcDuration(event));
}
public String getHtmlValue(Reservation object) {
String dateString= getValue(object);
return dateString;
}
}
| 04900db4-rob | src/org/rapla/plugin/eventtimecalculator/DurationColumnReservation.java | Java | gpl3 | 1,062 |
package org.rapla.plugin.eventtimecalculator;
import javax.swing.table.TableColumn;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.configuration.Preferences;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
/**
* User: kuestermann
* Date: 22.08.12
* Time: 09:30
*/
public class DurationColumn extends RaplaComponent implements ModificationListener {
public DurationColumn(RaplaContext context)
{
super(context);
getUpdateModule().addModificationListener( this);
}
public void init(TableColumn column) {
column.setMaxWidth(90);
column.setPreferredWidth(90);
}
public String getColumnName() {
I18nBundle i18n = getService(EventTimeCalculatorPlugin.RESOURCE_FILE);
return i18n.getString("duration");
}
public Class<?> getColumnClass() {
return String.class;
}
protected boolean validConf = false;
public void dataChanged(ModificationEvent evt) throws RaplaException {
if ( evt.isModified(Preferences.TYPE))
{
validConf = false;
}
}
}
| 04900db4-rob | src/org/rapla/plugin/eventtimecalculator/DurationColumn.java | Java | gpl3 | 1,296 |
package org.rapla.plugin.eventtimecalculator;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.tableview.AppointmentTableColumn;
/**
* User: kuestermann
* Date: 22.08.12
* Time: 09:30
*/
public final class DurationColumnAppoimentBlock extends DurationColumn implements AppointmentTableColumn {
EventTimeCalculatorFactory factory;
private EventTimeModel eventTimeModel;
public DurationColumnAppoimentBlock(RaplaContext context) throws RaplaException {
super(context);
factory = context.lookup(EventTimeCalculatorFactory.class);
}
public String getValue(AppointmentBlock block) {
if ( !validConf )
{
eventTimeModel = factory.getEventTimeModel();
validConf = true;
}
return eventTimeModel.format(eventTimeModel.calcDuration(block));
}
public String getHtmlValue(AppointmentBlock block) {
String dateString = getValue(block);
return dateString;
}
}
| 04900db4-rob | src/org/rapla/plugin/eventtimecalculator/DurationColumnAppoimentBlock.java | Java | gpl3 | 1,093 |
package org.rapla.plugin.eventtimecalculator;
import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;
import org.rapla.components.tablesorter.TableSorter;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.tableview.internal.AppointmentTableModel;
import org.rapla.plugin.tableview.internal.ReservationTableModel;
import org.rapla.plugin.tableview.internal.SummaryExtension;
/**
* User: kuestermann
* Date: 22.08.12
* Time: 09:29
*/
public final class DurationCounter extends RaplaComponent implements SummaryExtension {
EventTimeCalculatorFactory factory;
public DurationCounter(RaplaContext context) throws RaplaException {
super(context);
factory = context.lookup(EventTimeCalculatorFactory.class);
}
public void init(final JTable table, JPanel summaryRow) {
final JLabel counter = new JLabel();
summaryRow.add( Box.createHorizontalStrut(30));
summaryRow.add( counter);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0)
{
EventTimeModel eventTimeModel = factory.getEventTimeModel();
int[] selectedRows = table.getSelectedRows();
TableModel model = table.getModel();
TableSorter sorterModel = null;
if ( model instanceof TableSorter)
{
sorterModel = ((TableSorter) model);
model = ((TableSorter)model).getTableModel();
}
long totalduration = 0;
for ( int row:selectedRows)
{
if (sorterModel != null)
row = sorterModel.modelIndex(row);
if ( model instanceof AppointmentTableModel)
{
AppointmentBlock block = ((AppointmentTableModel) model).getAppointmentAt(row);
long duration = eventTimeModel.calcDuration(block);
totalduration+= duration;
}
if ( model instanceof ReservationTableModel)
{
Reservation block = ((ReservationTableModel) model).getReservationAt(row);
long duration = eventTimeModel.calcDuration(block);
if ( duration <0)
{
totalduration = -1;
break;
}
totalduration+= duration;
}
}
I18nBundle i18n = getService(EventTimeCalculatorPlugin.RESOURCE_FILE);
String durationString = totalduration < 0 ? i18n.getString("infinite") : eventTimeModel.format(totalduration);
counter.setText( i18n.getString("total_duration") + " " + durationString);
}
});
}
}
| 04900db4-rob | src/org/rapla/plugin/eventtimecalculator/DurationCounter.java | Java | gpl3 | 3,507 |
package org.rapla.plugin.eventtimecalculator.client;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.AppointmentStatusFactory;
import org.rapla.gui.ReservationEdit;
import org.rapla.gui.toolkit.RaplaWidget;
public class EventTimeCalculatorStatusFactory implements AppointmentStatusFactory {
public RaplaWidget createStatus(RaplaContext context, ReservationEdit reservationEdit) throws RaplaException {
return new EventTimeCalculatorStatusWidget(context, reservationEdit);
}
}
| 04900db4-rob | src/org/rapla/plugin/eventtimecalculator/client/EventTimeCalculatorStatusFactory.java | Java | gpl3 | 561 |
package org.rapla.plugin.eventtimecalculator.client;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.rapla.components.calendar.RaplaNumber;
import org.rapla.components.layout.TableLayout;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.plugin.eventtimecalculator.EventTimeCalculatorPlugin;
/**
* ****************************************************************************
* This is the admin-option panel.
*
* @author Tobias Bertram
*/
public class EventTimeCalculatorOption extends RaplaGUIComponent {
private RaplaNumber intervalNumber;
private RaplaNumber breakNumber;
//private RaplaNumber lunchbreakNumber;
private RaplaNumber timeUnit;
private JTextField timeFormat;
private JCheckBox chkAllowUserPrefs;
boolean adminOptions;
public EventTimeCalculatorOption(RaplaContext sm, boolean adminOptions) {
super(sm);
this.adminOptions = adminOptions;
setChildBundleName(EventTimeCalculatorPlugin.RESOURCE_FILE);
}
/**
* creates the panel shown in the admin option dialog.
*/
protected JPanel createPanel() {
JPanel content = new JPanel();
double[][] sizes = new double[][]{
{5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5},
{TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5,
TableLayout.PREFERRED, 5
}};
TableLayout tableLayout = new TableLayout(sizes);
content.setLayout(tableLayout);
content.add(new JLabel(getString("time_till_break") + ":"), "1,0");
content.add(new JLabel(getString("break_duration") + ":"), "1,2");
// content.add(new JLabel(i18n.getString("lunch_break_duration") + ":"), "1,4");
content.add(new JLabel(getString("time_unit") + ":"), "1,6");
content.add(new JLabel(getString("time_format") + ":"), "1,8");
intervalNumber = new RaplaNumber(EventTimeCalculatorPlugin.DEFAULT_intervalNumber, 0, null, false);
content.add(intervalNumber, "3,0");
content.add(new JLabel(getString("minutes")), "5,0");
breakNumber = new RaplaNumber(EventTimeCalculatorPlugin.DEFAULT_breakNumber, 0, null, false);
content.add(breakNumber, "3,2");
content.add(new JLabel(getString("minutes")), "5,2");
// lunchbreakNumber = new RaplaNumber(EventTimeCalculatorPlugin.DEFAULT_lunchbreakNumber, new Integer(1), null, false);
// content.add(lunchbreakNumber, "3,4");
// content.add(new JLabel(i18n.getString("minutes")), "5,4");
timeUnit = new RaplaNumber(EventTimeCalculatorPlugin.DEFAULT_timeUnit, 1, null, false);
content.add(timeUnit, "3,6");
content.add(new JLabel(getString("minutes")), "5,6");
timeFormat = new JTextField();
content.add(timeFormat, "3,8");
if ( adminOptions)
{
chkAllowUserPrefs = new JCheckBox();
content.add(chkAllowUserPrefs, "3,10");
content.add(new JLabel(getString("allow_user_prefs")), "1,10");
}
return content;
}
/**
* adds new configuration to the children to overwrite the default configuration.
*/
protected void addChildren(DefaultConfiguration newConfig) {
newConfig.getMutableChild(EventTimeCalculatorPlugin.INTERVAL_NUMBER, true).setValue(intervalNumber.getNumber().intValue());
newConfig.getMutableChild(EventTimeCalculatorPlugin.BREAK_NUMBER, true).setValue(breakNumber.getNumber().intValue());
// newConfig.getMutableChild(EventTimeCalculatorPlugin.LUNCHBREAK_NUMBER, true).setValue(lunchbreakNumber.getNumber().intValue());
newConfig.getMutableChild(EventTimeCalculatorPlugin.TIME_UNIT, true).setValue(timeUnit.getNumber().intValue());
newConfig.getMutableChild(EventTimeCalculatorPlugin.TIME_FORMAT, true).setValue(timeFormat.getText());
if ( adminOptions)
{
newConfig.getMutableChild(EventTimeCalculatorPlugin.USER_PREFS, true).setValue(chkAllowUserPrefs.isSelected());
}
}
/**
* reads children out of the configuration and shows them in the admin option panel.
*/
protected void readConfig(Configuration config) {
int intervalNumberInt = config.getChild(EventTimeCalculatorPlugin.INTERVAL_NUMBER).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_intervalNumber);
intervalNumber.setNumber(intervalNumberInt);
int breakNumberInt = config.getChild(EventTimeCalculatorPlugin.BREAK_NUMBER).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_breakNumber);
breakNumber.setNumber(breakNumberInt);
// int lunchbreakNumberInt = config.getChild(EventTimeCalculatorPlugin.LUNCHBREAK_NUMBER).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_lunchbreakNumber);
// lunchbreakNumber.setNumber(new Integer(lunchbreakNumberInt));
int timeUnitInt = config.getChild(EventTimeCalculatorPlugin.TIME_UNIT).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_timeUnit);
timeUnit.setNumber(timeUnitInt);
String timeFormatString = config.getChild(EventTimeCalculatorPlugin.TIME_FORMAT).getValue(EventTimeCalculatorPlugin.DEFAULT_timeFormat);
timeFormat.setText(timeFormatString);
if ( adminOptions)
{
boolean allowUserPrefs = config.getChild(EventTimeCalculatorPlugin.USER_PREFS).getValueAsBoolean(EventTimeCalculatorPlugin.DEFAULT_userPrefs);
chkAllowUserPrefs.setSelected(allowUserPrefs);
}
}
}
| 04900db4-rob | src/org/rapla/plugin/eventtimecalculator/client/EventTimeCalculatorOption.java | Java | gpl3 | 6,071 |
package org.rapla.plugin.eventtimecalculator.client;
import java.awt.BorderLayout;
import java.util.Locale;
import javax.swing.JPanel;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.DefaultPluginOption;
import org.rapla.plugin.eventtimecalculator.EventTimeCalculatorPlugin;
/**
* ****************************************************************************
* This is the admin-option panel.
*
* @author Tobias Bertram
*/
public class EventTimeCalculatorAdminOption extends DefaultPluginOption {
EventTimeCalculatorOption optionPanel;
public EventTimeCalculatorAdminOption(RaplaContext sm) {
super(sm);
setChildBundleName(EventTimeCalculatorPlugin.RESOURCE_FILE);
optionPanel = new EventTimeCalculatorOption(sm, true);
}
/**
* creates the panel shown in the admin option dialog.
*/
protected JPanel createPanel() throws RaplaException {
JPanel panel = super.createPanel();
JPanel content = optionPanel.createPanel();
panel.add(content, BorderLayout.CENTER);
return panel;
}
/**
* adds new configuration to the children to overwrite the default configuration.
*/
protected void addChildren(DefaultConfiguration newConfig) {
optionPanel.addChildren( newConfig);
}
/**
* reads children out of the configuration and shows them in the admin option panel.
*/
protected void readConfig(Configuration config) {
optionPanel.readConfig(config);
}
/**
* returns a string with the name of the class EventTimeCalculatorPlugin.
*/
public Class<? extends PluginDescriptor<?>> getPluginClass() {
return EventTimeCalculatorPlugin.class;
}
/**
* returns a string with the name of the plugin.
*/
public String getName(Locale locale) {
return getString("EventTimeCalculatorPlugin");
}
}
| 04900db4-rob | src/org/rapla/plugin/eventtimecalculator/client/EventTimeCalculatorAdminOption.java | Java | gpl3 | 2,154 |
package org.rapla.plugin.eventtimecalculator.client;
import java.util.Locale;
import javax.swing.JComponent;
import javax.swing.JPanel;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.plugin.eventtimecalculator.EventTimeCalculatorPlugin;
/**
* ****************************************************************************
* This is the admin-option panel.
*
* @author Tobias Bertram
*/
public class EventTimeCalculatorUserOption extends RaplaGUIComponent implements OptionPanel {
EventTimeCalculatorOption optionPanel;
private Preferences preferences;
Configuration config;
JPanel panel;
public EventTimeCalculatorUserOption(RaplaContext sm, Configuration config) {
super(sm);
this.config = config;
optionPanel = new EventTimeCalculatorOption(sm, false);
setChildBundleName(EventTimeCalculatorPlugin.RESOURCE_FILE);
panel = optionPanel.createPanel();
}
@Override
public JComponent getComponent() {
return panel;
}
public void show() throws RaplaException {
Configuration config = preferences.getEntry( EventTimeCalculatorPlugin.USER_CONFIG);
if ( config == null)
{
config = this.config;
}
optionPanel.readConfig( config);
}
public void setPreferences(Preferences preferences) {
this.preferences = preferences;
}
public void commit() {
RaplaConfiguration config = new RaplaConfiguration("eventtime");
optionPanel.addChildren(config);
preferences.putEntry( EventTimeCalculatorPlugin.USER_CONFIG, config);
}
/**
* returns a string with the name of the plugin.
*/
public String getName(Locale locale) {
return getString("EventTimeCalculatorPlugin");
}
}
| 04900db4-rob | src/org/rapla/plugin/eventtimecalculator/client/EventTimeCalculatorUserOption.java | Java | gpl3 | 2,118 |
package org.rapla.plugin.eventtimecalculator.client;
import java.awt.Font;
import java.util.Collection;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.AppointmentListener;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.ReservationEdit;
import org.rapla.gui.toolkit.RaplaWidget;
import org.rapla.plugin.eventtimecalculator.EventTimeCalculatorFactory;
import org.rapla.plugin.eventtimecalculator.EventTimeCalculatorPlugin;
import org.rapla.plugin.eventtimecalculator.EventTimeModel;
/**
* @author Tobias Bertram
* Class EventTimeCalculator provides the service to show the actual duration of all appointments of a reservation.
*/
public class EventTimeCalculatorStatusWidget extends RaplaGUIComponent implements RaplaWidget {
JPanel content = new JPanel();
JLabel totalDurationLabel = new JLabel();
JLabel selectedDurationLabel = new JLabel();
I18nBundle i18n;
ReservationEdit reservationEdit;
EventTimeCalculatorFactory factory;
/**
* creates the panel for the GUI in window "reservation".
*/
public EventTimeCalculatorStatusWidget(final RaplaContext context, final ReservationEdit reservationEdit) throws RaplaException {
super(context);
factory = context.lookup(EventTimeCalculatorFactory.class);
//this.config = config;
i18n = context.lookup(EventTimeCalculatorPlugin.RESOURCE_FILE);
setChildBundleName(EventTimeCalculatorPlugin.RESOURCE_FILE);
double[][] sizes = new double[][]{
{5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5},
{TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5}};
TableLayout tableLayout = new TableLayout(sizes);
content.setLayout(tableLayout);
Font font1 = totalDurationLabel.getFont().deriveFont((float) 9.0);
totalDurationLabel.setFont(font1);
selectedDurationLabel.setFont(font1);
content.add(selectedDurationLabel, "1,2");
content.add(totalDurationLabel, "3,2");
this.reservationEdit = reservationEdit;
/**
* updates Panel if an appointment is removed, changed, added.
*/
reservationEdit.addAppointmentListener(new AppointmentListener() {
public void appointmentSelected(Collection<Appointment> appointment) {
updateStatus();
}
public void appointmentRemoved(Collection<Appointment> appointment) {
updateStatus();
}
public void appointmentChanged(Collection<Appointment> appointment) {
updateStatus();
}
public void appointmentAdded(Collection<Appointment> appointment) {
updateStatus();
}
});
updateStatus();
}
/**
* provides the necessary parameters to use the class TimeCalculator.
* also provides some logic needed for the calculation of the actual duration of all appointments in the shown reservation.
*/
private void updateStatus() {
Reservation event = reservationEdit.getReservation();
if (event == null)
{
return;
}
final EventTimeModel eventTimeModel = factory.getEventTimeModel();
boolean totalDurationVisible = eventTimeModel.hasEnd(event.getAppointments());
if (totalDurationVisible) {
long totalDuration = 0;
totalDuration = eventTimeModel.calcDuration(event.getAppointments());
totalDurationLabel.setText(getString("total_duration") + ": " + eventTimeModel.format(totalDuration));
}
final Collection<Appointment> selectedAppointmentsCollection = reservationEdit.getSelectedAppointments();
final Appointment [] selectedAppointments = selectedAppointmentsCollection.toArray(new Appointment[selectedAppointmentsCollection.size()]);
boolean selectedDurationVisible = eventTimeModel.hasEnd(event.getAppointments());
if (selectedDurationVisible) {
long totalDuration = 0;
totalDuration = eventTimeModel.calcDuration(selectedAppointments);
selectedDurationLabel.setText(getString("duration") + ": " + eventTimeModel.format(totalDuration));
}
/*
Appointment[] appointments = event.getAppointments();
boolean noEnd = false;
long totalDuration = 0;
EventTimeModel eventTimeModel = factory.getEventTimeModel();
for (Appointment appointment : appointments) { // goes through all appointments of the reservation
if (appointment.getRepeating() != null && appointment.getRepeating().getEnd() == null) { // appoinment repeats forever?
noEnd = true;
break;
}
List<AppointmentBlock> splits = new ArrayList<AppointmentBlock>(); // split appointment block
appointment.createBlocks(appointment.getStart(),
DateTools.fillDate(appointment.getMaxEnd()), splits);
for (AppointmentBlock block : splits) { // goes through the block
long duration = DateTools.countMinutes(block.getStart(), block.getEnd());
// lunch break flag: here the lunchBreakActivated-Flag should be taken out of the preferences and given to the calculateActualDuration-method
// final long TIME_TILL_BREAK_DURATION = config.getChild(EventTimeCalculatorPlugin.INTERVAL_NUMBER).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_timeUnit);
// final long BREAK_DURATION = config.getChild(EventTimeCalculatorPlugin.BREAK_NUMBER).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_breakNumber);
long actualDuration = eventTimeModel.calcDuration(duration); // EventTimeCalculatorFactory.calculateActualDuration(duration, TIME_TILL_BREAK_DURATION, BREAK_DURATION);
totalDuration += actualDuration;
}
}
*/
// String format = EventTimeCalculatorFactory.format(config, totalDuration);
totalDurationLabel.setVisible(totalDurationVisible);
selectedDurationLabel.setVisible(selectedDurationVisible);
}
/* public String formatDuration(Configuration config, long totalDuration) {
final String format = config.getChild(EventTimeCalculatorPlugin.TIME_FORMAT).getValue(EventTimeCalculatorPlugin.DEFAULT_timeFormat);
final int timeUnit = config.getChild(EventTimeCalculatorPlugin.TIME_UNIT).getValueAsInteger(EventTimeCalculatorPlugin.DEFAULT_timeUnit);
return MessageFormat.format(format, totalDuration / timeUnit, totalDuration % timeUnit);
}*/
/**
* returns the panel shown in the window "reservation"
*/
public JComponent getComponent() {
return content;
}
}
| 04900db4-rob | src/org/rapla/plugin/eventtimecalculator/client/EventTimeCalculatorStatusWidget.java | Java | gpl3 | 7,126 |
package org.rapla.plugin.eventtimecalculator.server;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.plugin.eventtimecalculator.DurationColumnAppoimentBlock;
import org.rapla.plugin.eventtimecalculator.DurationColumnReservation;
import org.rapla.plugin.eventtimecalculator.DurationCounter;
import org.rapla.plugin.eventtimecalculator.EventTimeCalculatorFactory;
import org.rapla.plugin.eventtimecalculator.EventTimeCalculatorPlugin;
import org.rapla.plugin.tableview.TableViewExtensionPoints;
import org.rapla.server.ServerServiceContainer;
public class EventTimeCalculatorServerPlugin implements PluginDescriptor<ServerServiceContainer> {
/**
* provides the resource file of the plugin.
* uses the extension points to provide the different services of the plugin.
*/
public void provideServices(ServerServiceContainer container, Configuration config) {
container.addContainerProvidedComponent(EventTimeCalculatorPlugin.RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig(EventTimeCalculatorPlugin.RESOURCE_FILE.getId()));
if (!config.getAttributeAsBoolean("enabled", EventTimeCalculatorPlugin.ENABLE_BY_DEFAULT))
return;
container.addContainerProvidedComponent(EventTimeCalculatorFactory.class,EventTimeCalculatorFactory.class, config);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, DurationColumnAppoimentBlock.class, config);
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, DurationColumnReservation.class, config);
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_SUMMARY, DurationCounter.class, config);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_SUMMARY, DurationCounter.class, config);
}
} | 04900db4-rob | src/org/rapla/plugin/eventtimecalculator/server/EventTimeCalculatorServerPlugin.java | Java | gpl3 | 2,013 |
package org.rapla.plugin.eventtimecalculator;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.TypedComponentRole;
import org.rapla.plugin.eventtimecalculator.client.EventTimeCalculatorAdminOption;
import org.rapla.plugin.eventtimecalculator.client.EventTimeCalculatorStatusFactory;
import org.rapla.plugin.eventtimecalculator.client.EventTimeCalculatorUserOption;
import org.rapla.plugin.tableview.TableViewExtensionPoints;
public class EventTimeCalculatorPlugin implements PluginDescriptor<ClientServiceContainer> {
public static final TypedComponentRole<I18nBundle> RESOURCE_FILE = new TypedComponentRole<I18nBundle>( EventTimeCalculatorPlugin.class.getPackage().getName() + ".EventTimeCalculatorResources");
public static final String PLUGIN_CLASS = EventTimeCalculatorPlugin.class.getName();
public static final boolean ENABLE_BY_DEFAULT = false;
// public static String PREF_LUNCHBREAK_NUMBER = "eventtimecalculator_lunchbreak_number";
public static final TypedComponentRole<RaplaConfiguration> USER_CONFIG = new TypedComponentRole<RaplaConfiguration>("org.rapla.plugin.eventtimecalculator");
public static final String INTERVAL_NUMBER = "interval_number";
public static final String BREAK_NUMBER = "break_number";
// public static final String LUNCHBREAK_NUMBER = "lunchbreak_number";
public static final String TIME_UNIT = "time_unit";
public static final String TIME_FORMAT = "time_format";
public static final String USER_PREFS = "user_prefs";
public static final int DEFAULT_intervalNumber = 60;
public static final int DEFAULT_timeUnit = 60;
public static final String DEFAULT_timeFormat = "{0},{1}";
public static final int DEFAULT_breakNumber = 0;
public static final boolean DEFAULT_userPrefs = false;
//public static final int DEFAULT_lunchbreakNumber = 30;
/**
* provides the resource file of the plugin.
* uses the extension points to provide the different services of the plugin.
*/
public void provideServices(ClientServiceContainer container, Configuration config) {
container.addContainerProvidedComponent(RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig(RESOURCE_FILE.getId()));
container.addContainerProvidedComponent(RaplaClientExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION, EventTimeCalculatorAdminOption.class);
if (!config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT))
return;
container.addContainerProvidedComponent(EventTimeCalculatorFactory.class,EventTimeCalculatorFactory.class, config);
if ( config.getChild(USER_PREFS).getValueAsBoolean(false))
{
container.addContainerProvidedComponent(RaplaClientExtensionPoints.USER_OPTION_PANEL_EXTENSION, EventTimeCalculatorUserOption.class, config);
}
container.addContainerProvidedComponent(RaplaClientExtensionPoints.APPOINTMENT_STATUS, EventTimeCalculatorStatusFactory.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, DurationColumnAppoimentBlock.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, DurationColumnReservation.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_SUMMARY, DurationCounter.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_SUMMARY, DurationCounter.class);
}
} | 04900db4-rob | src/org/rapla/plugin/eventtimecalculator/EventTimeCalculatorPlugin.java | Java | gpl3 | 3,882 |
/**
*
*/
package org.rapla.plugin.tableview;
import java.awt.Component;
import java.util.Date;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import org.rapla.components.util.DateTools;
import org.rapla.framework.RaplaLocale;
final public class DateCellRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
RaplaLocale raplaLocale;
private boolean substractDayWhenFullDay;
public DateCellRenderer(RaplaLocale raplaLocale) {
this.raplaLocale = raplaLocale;
}
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column )
{
final Date date = (Date) value;
if ( date == null)
{
value = "";
}
else
{
// don't append time when 0 or 24
boolean appendTime = !raplaLocale.toDate(date, false ).equals( date);
if ( appendTime )
{
value = raplaLocale.formatDateLong( date) + " " + raplaLocale.formatTime( date ) ;
}
else
{
if ( substractDayWhenFullDay )
{
value = raplaLocale.formatDateLong( DateTools.addDays(date, -1));
}
else
{
value = raplaLocale.formatDateLong( date);
}
}
}
//setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT );
return super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column);
}
public boolean isSubstractDayWhenFullDay() {
return substractDayWhenFullDay;
}
public void setSubstractDayWhenFullDay(boolean substractDayWhenFullDay) {
this.substractDayWhenFullDay = substractDayWhenFullDay;
}
} | 04900db4-rob | src/org/rapla/plugin/tableview/DateCellRenderer.java | Java | gpl3 | 1,880 |
/* Page background color */
body { background-color: #FFFFFF;
text : #000000;
}
.dayheader {
border: 2px solid #000000;
background-color: #FFFF88;
width: 600px;
}
.time {
vertical-align:top;
font-weight: bold;
font-size: 8pt;
padding-right: 20px;
padding-top: 0px;
padding-bottom: 0px;
margin: 0px;
}
.value {
vertical-align:top;
font-size: 8pt;
margin: 0px;
padding: 0px;
}
.label {
vertical-align:top;
font-weight: bold;
font-size: 8pt;
margin: 0px;
padding: 0px;
}
.infotable {
font-size:small;
border-spacing:0px;
}
.separation_row {
height:5px;
}
.datechooser {
text-align:center;
}
@page {
size: portrait;
}
@media print {
.datechooser {
display: none;
}
}
| 04900db4-rob | src/org/rapla/plugin/tableview/report.css | CSS | gpl3 | 761 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2012 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.tableview;
import org.rapla.entities.domain.AppointmentBlock;
public interface AppointmentTableColumn extends RaplaTableColumn<AppointmentBlock>
{
}
| 04900db4-rob | src/org/rapla/plugin/tableview/AppointmentTableColumn.java | Java | gpl3 | 1,134 |
package org.rapla.plugin.tableview.internal;
import java.util.Date;
import javax.swing.table.TableColumn;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaLocale;
import org.rapla.plugin.tableview.DateCellRenderer;
import org.rapla.plugin.tableview.ReservationTableColumn;
public class ReservationLastChangedColumn extends RaplaComponent implements ReservationTableColumn {
public ReservationLastChangedColumn(RaplaContext context) {
super(context);
}
public void init(TableColumn column) {
column.setCellRenderer( new DateCellRenderer( getRaplaLocale()));
column.setMaxWidth( 130 );
column.setPreferredWidth( 130 );
}
public Object getValue(Reservation reservation) {
return reservation.getLastChanged();
}
public String getColumnName() {
return getString("last_changed");
}
public Class<?> getColumnClass() {
return Date.class;
}
public String getHtmlValue(Reservation reservation)
{
RaplaLocale raplaLocale = getRaplaLocale();
final Date lastChangeTime = reservation.getLastChanged();
String lastChanged= raplaLocale.formatDateLong(lastChangeTime);
return lastChanged;
}
} | 04900db4-rob | src/org/rapla/plugin/tableview/internal/ReservationLastChangedColumn.java | Java | gpl3 | 1,254 |
package org.rapla.plugin.tableview.internal;
import javax.swing.JPanel;
import javax.swing.JTable;
public interface SummaryExtension
{
void init(JTable table, JPanel summaryRow);
}
| 04900db4-rob | src/org/rapla/plugin/tableview/internal/SummaryExtension.java | Java | gpl3 | 194 |
package org.rapla.plugin.tableview.internal;
import javax.swing.table.TableColumn;
import org.rapla.components.util.xml.XMLWriter;
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.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.plugin.tableview.AppointmentTableColumn;
public class AllocatableListColumn extends RaplaComponent implements AppointmentTableColumn {
public AllocatableListColumn(RaplaContext context) {
super(context);
}
public void init(TableColumn column) {
column.setMaxWidth( 130 );
column.setPreferredWidth( 130 );
}
public Object getValue(AppointmentBlock block)
{
Appointment appointment = block.getAppointment();
Reservation reservation = appointment.getReservation();
Allocatable[] allocatablesFor = reservation.getAllocatablesFor(appointment);
StringBuilder buf = new StringBuilder();
boolean first = true;
for (Allocatable alloc: allocatablesFor)
{
if ( !contains( alloc))
{
continue;
}
if (!first)
{
buf.append(", ");
}
first = false;
String name = alloc.getName( getLocale());
buf.append( name);
}
return buf.toString();
}
/**
* @param alloc
*/
protected boolean contains(Allocatable alloc)
{
return true;
}
public String getColumnName() {
return getString("resources");
}
public Class<?> getColumnClass() {
return String.class;
}
public String getHtmlValue(AppointmentBlock block)
{
String names = getValue(block).toString();
return XMLWriter.encode(names);
}
} | 04900db4-rob | src/org/rapla/plugin/tableview/internal/AllocatableListColumn.java | Java | gpl3 | 1,768 |
package org.rapla.plugin.tableview.internal;
import java.util.Date;
import javax.swing.table.TableColumn;
import org.rapla.components.util.DateTools;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaLocale;
import org.rapla.plugin.tableview.AppointmentTableColumn;
import org.rapla.plugin.tableview.DateCellRenderer;
public final class AppointmentEndDate extends RaplaComponent implements AppointmentTableColumn {
public AppointmentEndDate(RaplaContext context) {
super(context);
}
public void init(TableColumn column) {
DateCellRenderer cellRenderer = new DateCellRenderer( getRaplaLocale());
cellRenderer.setSubstractDayWhenFullDay(true);
column.setCellRenderer( cellRenderer);
column.setMaxWidth( 175 );
column.setPreferredWidth( 175 );
}
public Object getValue(AppointmentBlock block) {
return new Date(block.getEnd());
}
public String getColumnName() {
return getString("end_date");
}
public Class<?> getColumnClass() {
return Date.class;
}
public String getHtmlValue(AppointmentBlock block)
{
RaplaLocale raplaLocale = getRaplaLocale();
final Date date = new Date(block.getEnd());
if ( block.getAppointment().isWholeDaysSet())
{
String dateString= raplaLocale.formatDateLong(DateTools.addDays(date,-1));
return dateString;
}
else
{
String dateString= raplaLocale.formatDateLong(date) + " " + raplaLocale.formatTime( date );
return dateString;
}
}
} | 04900db4-rob | src/org/rapla/plugin/tableview/internal/AppointmentEndDate.java | Java | gpl3 | 1,573 |
package org.rapla.plugin.tableview.internal;
import javax.swing.table.TableColumn;
import org.rapla.components.util.xml.XMLWriter;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.plugin.tableview.ReservationTableColumn;
public final class ReservationNameColumn extends RaplaComponent implements ReservationTableColumn{
public ReservationNameColumn(RaplaContext context) {
super(context);
}
public void init(TableColumn column) {
}
public Object getValue(Reservation reservation)
{
// getLocale().
return reservation.getName(getLocale());
}
public String getColumnName() {
return getString("name");
}
public Class<?> getColumnClass() {
return String.class;
}
public String getHtmlValue(Reservation event) {
String value = getValue(event).toString();
return XMLWriter.encode(value);
}
} | 04900db4-rob | src/org/rapla/plugin/tableview/internal/ReservationNameColumn.java | Java | gpl3 | 973 |
package org.rapla.plugin.tableview.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.swing.table.DefaultTableModel;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.plugin.tableview.AppointmentTableColumn;
public class AppointmentTableModel extends DefaultTableModel
{
private static final long serialVersionUID = 1L;
List<AppointmentBlock> appointments= new ArrayList<AppointmentBlock>();
Locale locale;
I18nBundle i18n;
Map<Integer,AppointmentTableColumn> columns = new LinkedHashMap<Integer, AppointmentTableColumn>();
//String[] columns;
public AppointmentTableModel(Locale locale, I18nBundle i18n, Collection<? extends AppointmentTableColumn> columnPlugins) {
this.locale = locale;
this.i18n = i18n;
List<String> columnNames = new ArrayList<String>();
int column = 0;
for (AppointmentTableColumn col: columnPlugins)
{
columnNames.add( col.getColumnName());
columns.put( column, col);
column++;
}
this.setColumnIdentifiers( columnNames.toArray());
}
public void setAppointments(List<AppointmentBlock> appointments2) {
this.appointments = appointments2;
super.fireTableDataChanged();
}
public AppointmentBlock getAppointmentAt(int row) {
return this.appointments.get(row);
}
public boolean isCellEditable(int row, int column) {
return false;
}
public int getRowCount() {
if ( appointments != null)
return appointments.size();
else
return 0;
}
public Object getValueAt( int rowIndex, int columnIndex )
{
AppointmentBlock event = getAppointmentAt(rowIndex);
AppointmentTableColumn tableColumn = columns.get( columnIndex);
return tableColumn.getValue(event);
}
public Class<?> getColumnClass(int columnIndex) {
AppointmentTableColumn tableColumn = columns.get( columnIndex);
return tableColumn.getColumnClass();
}
}
| 04900db4-rob | src/org/rapla/plugin/tableview/internal/AppointmentTableModel.java | Java | gpl3 | 2,299 |
package org.rapla.plugin.tableview.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.swing.table.DefaultTableModel;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.domain.Reservation;
import org.rapla.plugin.tableview.RaplaTableColumn;
import org.rapla.plugin.tableview.ReservationTableColumn;
public class ReservationTableModel extends DefaultTableModel
{
private static final long serialVersionUID = 1L;
Reservation[] reservations = new Reservation[] {};
Locale locale;
I18nBundle i18n;
Map<Integer,ReservationTableColumn> columns = new LinkedHashMap<Integer, ReservationTableColumn>();
//String[] columns;
public ReservationTableModel(Locale locale, I18nBundle i18n, Collection<? extends ReservationTableColumn> reservationColumnPlugins) {
this.locale = locale;
this.i18n = i18n;
List<String> columnNames = new ArrayList<String>();
int column = 0;
for (ReservationTableColumn col: reservationColumnPlugins)
{
columnNames.add( col.getColumnName());
columns.put( column, col);
column++;
}
this.setColumnIdentifiers( columnNames.toArray());
}
public void setReservations(Reservation[] events) {
this.reservations = events;
super.fireTableDataChanged();
}
public Reservation getReservationAt(int row) {
return this.reservations[row];
}
public boolean isCellEditable(int row, int column) {
return false;
}
public int getRowCount() {
if ( reservations != null)
return reservations.length;
else
return 0;
}
public Object getValueAt( int rowIndex, int columnIndex )
{
Reservation event = reservations[rowIndex];
RaplaTableColumn<Reservation> tableColumn = columns.get( columnIndex);
return tableColumn.getValue(event);
}
public Class<?> getColumnClass(int columnIndex) {
RaplaTableColumn<Reservation> tableColumn = columns.get( columnIndex);
return tableColumn.getColumnClass();
}
}
| 04900db4-rob | src/org/rapla/plugin/tableview/internal/ReservationTableModel.java | Java | gpl3 | 2,246 |
package org.rapla.plugin.tableview.internal;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.calendar.DateChangeEvent;
import org.rapla.components.calendar.DateChangeListener;
import org.rapla.components.tablesorter.TableSorter;
import org.rapla.components.util.TimeInterval;
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.facade.CalendarModel;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.gui.MenuContext;
import org.rapla.gui.MenuFactory;
import org.rapla.gui.ObjectMenuFactory;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.SwingCalendarView;
import org.rapla.gui.VisibleTimeInterval;
import org.rapla.gui.internal.action.AppointmentAction;
import org.rapla.gui.internal.common.InternMenus;
import org.rapla.gui.toolkit.MenuInterface;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaMenuItem;
import org.rapla.gui.toolkit.RaplaPopupMenu;
import org.rapla.plugin.abstractcalendar.IntervalChooserPanel;
import org.rapla.plugin.abstractcalendar.RaplaCalendarViewListener;
import org.rapla.plugin.tableview.AppointmentTableColumn;
import org.rapla.plugin.tableview.TableViewExtensionPoints;
public class SwingAppointmentTableView extends RaplaGUIComponent implements SwingCalendarView, Printable, VisibleTimeInterval
{
AppointmentTableModel appointmentTableModel;
JTable table;
CalendarModel model;
IntervalChooserPanel dateChooser;
JComponent scrollpane;
TableSorter sorter;
ActionListener copyListener = new ActionListener() {
public void actionPerformed(ActionEvent evt)
{
List<AppointmentBlock> selectedEvents = getSelectedEvents();
if ( selectedEvents.size() == 1) {
AppointmentBlock appointmentBlock = selectedEvents.get( 0);
try {
Component sourceComponent = table;
Point p = null;
Collection<Allocatable> contextAllocatables = Collections.emptyList();
getReservationController().copyAppointment(appointmentBlock,sourceComponent,p, contextAllocatables);
} catch (RaplaException e) {
showException( e, getComponent());
}
}
copy(table, evt);
}
};
private JComponent container;
public SwingAppointmentTableView( RaplaContext context, CalendarModel model, final boolean editable ) throws RaplaException
{
super( context );
table = new JTable() {
private static final long serialVersionUID = 1L;
public String getToolTipText(MouseEvent e)
{
if (!editable)
return null;
int rowIndex = rowAtPoint( e.getPoint() );
AppointmentBlock app = appointmentTableModel.getAppointmentAt( sorter.modelIndex( rowIndex ));
Reservation reservation = app.getAppointment().getReservation();
return getInfoFactory().getToolTip( reservation );
}
};
scrollpane = new JScrollPane( table);
if ( editable )
{
scrollpane.setPreferredSize( new Dimension(600,800));
PopupTableHandler popupHandler = new PopupTableHandler();
scrollpane.addMouseListener( popupHandler);
table.addMouseListener( popupHandler );
container = new JPanel();
container.setLayout( new BorderLayout());
container.add( scrollpane, BorderLayout.CENTER);
JPanel extensionPanel = new JPanel();
extensionPanel.setLayout( new BoxLayout(extensionPanel, BoxLayout.X_AXIS));
container.add( extensionPanel, BorderLayout.SOUTH);
Collection< ? extends SummaryExtension> reservationSummaryExtensions = getContainer().lookupServicesFor(TableViewExtensionPoints.APPOINTMENT_TABLE_SUMMARY);
for ( SummaryExtension summary:reservationSummaryExtensions)
{
summary.init(table, extensionPanel);
}
}
else
{
Dimension size = table.getPreferredSize();
scrollpane.setBounds( 0,0,600, (int)size.getHeight());
container = scrollpane;
}
this.model = model;
Collection< ? extends AppointmentTableColumn> columnPlugins = getContainer().lookupServicesFor(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN);
appointmentTableModel = new AppointmentTableModel( getLocale(),getI18n(), columnPlugins );
sorter = SwingReservationTableView.createAndSetSorter(model, table, TableViewPlugin.BLOCKS_SORTING_STRING_OPTION, appointmentTableModel);
int column = 0;
for (AppointmentTableColumn col: columnPlugins)
{
col.init(table.getColumnModel().getColumn(column ));
column++;
}
table.setColumnSelectionAllowed( true );
table.setRowSelectionAllowed( true);
table.getTableHeader().setReorderingAllowed(false);
table.registerKeyboardAction(copyListener,getString("copy"),COPY_STROKE,JComponent.WHEN_FOCUSED);
dateChooser = new IntervalChooserPanel( context, model);
dateChooser.addDateChangeListener( new DateChangeListener() {
public void dateChanged( DateChangeEvent evt )
{
try {
update( );
} catch (RaplaException ex ){
showException( ex, getComponent());
}
}
});
update(model);
table.getSelectionModel().addListSelectionListener( new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
updateEditMenu();
}
});
}
protected void update(CalendarModel model) throws RaplaException
{
List<AppointmentBlock> blocks = model.getBlocks();
appointmentTableModel.setAppointments(blocks);
}
public void update() throws RaplaException
{
update(model);
dateChooser.update();
}
public JComponent getDateSelection()
{
return dateChooser.getComponent();
}
public void scrollToStart()
{
}
public JComponent getComponent()
{
return container;
}
List<AppointmentBlock> getSelectedEvents() {
int[] rows = table.getSelectedRows();
List<AppointmentBlock> selectedEvents = new ArrayList<AppointmentBlock>();
for (int i=0;i<rows.length;i++)
{
AppointmentBlock reservation =appointmentTableModel.getAppointmentAt( sorter.modelIndex(rows[i]) );
selectedEvents.add( reservation);
}
return selectedEvents;
}
protected void updateEditMenu() {
List<AppointmentBlock> selectedEvents = getSelectedEvents();
if ( selectedEvents.size() == 0 )
{
return;
}
RaplaMenu editMenu = getService(InternMenus.EDIT_MENU_ROLE);
RaplaMenu newMenu = getService(InternMenus.NEW_MENU_ROLE);
editMenu.removeAllBetween("EDIT_BEGIN", "EDIT_END");
newMenu.removeAll();
Point p = null;
try {
updateMenu(editMenu,newMenu, p);
newMenu.setEnabled(newMenu.getMenuComponentCount() > 0 && canUserAllocateSomething(getUser()));
editMenu.setEnabled(canUserAllocateSomething(getUser()));
} catch (RaplaException ex) {
showException (ex,getComponent());
}
}
class PopupTableHandler extends MouseAdapter
{
void showPopup(MouseEvent me)
{
Point p = new Point(me.getX(), me.getY());
RaplaPopupMenu menu= new RaplaPopupMenu();
try {
RaplaMenu newMenu = new RaplaMenu("EDIT_BEGIN");
newMenu.setText(getString("new"));
menu.add( newMenu );
updateMenu( menu, newMenu, p);
newMenu.setEnabled(newMenu.getMenuComponentCount() > 0 && canUserAllocateSomething(getUser()));
menu.show( table, p.x, p.y);
} catch (RaplaException ex) {
showException (ex,getComponent());
}
}
/** Implementation-specific. Should be private.*/
public void mousePressed(MouseEvent me) {
if (me.isPopupTrigger())
showPopup(me);
}
/** Implementation-specific. Should be private.*/
public void mouseReleased(MouseEvent me) {
if (me.isPopupTrigger())
showPopup(me);
}
/** we want to edit the reservation on double click*/
public void mouseClicked(MouseEvent me) {
List<AppointmentBlock> selectedEvents = getSelectedEvents();
if (me.getClickCount() > 1 && selectedEvents.size() == 1 )
{
AppointmentBlock block = selectedEvents.get( 0);
Appointment appointment = block.getAppointment();
Reservation reservation = appointment.getReservation();
if (!canModify( reservation ))
{
return;
}
try {
getReservationController().edit( block);
} catch (RaplaException ex) {
showException (ex,getComponent());
}
}
}
}
protected void updateMenu(MenuInterface editMenu,MenuInterface newMenu,Point p)
throws RaplaException, RaplaContextException {
List<AppointmentBlock> selectedEvents = getSelectedEvents();
AppointmentBlock focusedObject = null;
if ( selectedEvents.size() == 1)
{
focusedObject = selectedEvents.get( 0);
}
MenuContext menuContext = new MenuContext( getContext(), focusedObject,getComponent(), p);
menuContext.put(RaplaCalendarViewListener.SELECTED_DATE, focusedObject != null ? new Date(focusedObject.getStart()): new Date());
{
menuContext.setSelectedObjects( selectedEvents);
}
// add the new reservations wizards
{
MenuFactory menuFactory = getService(MenuFactory.class);
menuFactory.addReservationWizards( newMenu, menuContext, null);
}
if ( selectedEvents.size() != 0)
{
final JMenuItem copyItem = new JMenuItem();
copyItem.addActionListener( copyListener);
copyItem.setIcon( getIcon("icon.copy"));
copyItem.setText(getString("copy"));
editMenu.insertAfterId(copyItem, "EDIT_BEGIN");
addObjectMenu(editMenu, menuContext, "EDIT_BEGIN");
}
}
Printable printable = null;
/**
* @see java.awt.print.Printable#print(java.awt.Graphics, java.awt.print.PageFormat, int)
*/
public int print(Graphics graphics, PageFormat format, int page) throws PrinterException {
MessageFormat f1 = new MessageFormat( model.getNonEmptyTitle());
MessageFormat f2 = new MessageFormat("- {0} -");
Printable printable = table.getPrintable( JTable.PrintMode.FIT_WIDTH,f1, f2 );
return printable.print( graphics, format, page);
}
private MenuInterface addObjectMenu( MenuInterface menu, MenuContext context, String afterId ) throws RaplaException
{
Component parent = getComponent();
AppointmentBlock appointmentBlock = (AppointmentBlock) context.getFocusedObject();
Point p = context.getPoint();
@SuppressWarnings("unchecked")
Collection<AppointmentBlock> selection = (Collection<AppointmentBlock>)context.getSelectedObjects();
if ( appointmentBlock != null)
{
{
AppointmentAction action = new AppointmentAction(getContext(),parent,p);
action.setDelete(appointmentBlock);
menu.insertAfterId(new JMenuItem(action), afterId);
}
{
AppointmentAction action = new AppointmentAction(getContext(),parent,p);
action.setView(appointmentBlock);
menu.insertAfterId(new JMenuItem(action), afterId);
}
{
AppointmentAction action = new AppointmentAction(getContext(),parent,p);
action.setEdit(appointmentBlock);
menu.insertAfterId(new JMenuItem(action), afterId);
}
}
else if ( selection != null && selection.size() > 0)
{
AppointmentAction action = new AppointmentAction(getContext(),parent,p);
action.setDeleteSelection(selection);
menu.insertAfterId(new JMenuItem(action), afterId);
}
Iterator<?> it = getContainer().lookupServicesFor( RaplaClientExtensionPoints.OBJECT_MENU_EXTENSION).iterator();
while (it.hasNext())
{
ObjectMenuFactory objectMenuFact = (ObjectMenuFactory) it.next();
Appointment appointment = appointmentBlock != null ? appointmentBlock.getAppointment(): null;
RaplaMenuItem[] items = objectMenuFact.create( context, appointment);
for ( int i =0;i<items.length;i++)
{
RaplaMenuItem item = items[i];
menu.insertAfterId( item, afterId);
}
}
return menu;
}
public TimeInterval getVisibleTimeInterval() {
return new TimeInterval(model.getStartDate(), model.getEndDate());
}
}
| 04900db4-rob | src/org/rapla/plugin/tableview/internal/SwingAppointmentTableView.java | Java | gpl3 | 14,515 |
package org.rapla.plugin.tableview.internal;
import java.util.Date;
import javax.swing.table.TableColumn;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaLocale;
import org.rapla.plugin.tableview.DateCellRenderer;
import org.rapla.plugin.tableview.ReservationTableColumn;
public class ReservationStartColumn extends RaplaComponent implements ReservationTableColumn {
public ReservationStartColumn(RaplaContext context) {
super(context);
}
public void init(TableColumn column) {
column.setCellRenderer( new DateCellRenderer( getRaplaLocale()));
column.setMaxWidth( 130 );
column.setPreferredWidth( 130 );
}
public Object getValue(Reservation reservation) {
return reservation.getFirstDate();
}
public String getColumnName() {
return getString("start_date");
}
public Class<?> getColumnClass() {
return Date.class;
}
public String getHtmlValue(Reservation reservation)
{
RaplaLocale raplaLocale = getRaplaLocale();
final Date firstDate = reservation.getFirstDate();
String string= raplaLocale.formatDateLong(firstDate) + " " + raplaLocale.formatTime( firstDate);
return string;
}
} | 04900db4-rob | src/org/rapla/plugin/tableview/internal/ReservationStartColumn.java | Java | gpl3 | 1,307 |
package org.rapla.plugin.tableview.internal;
import java.util.Date;
import javax.swing.table.TableColumn;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaLocale;
import org.rapla.plugin.tableview.AppointmentTableColumn;
import org.rapla.plugin.tableview.DateCellRenderer;
public final class AppointmentStartDate extends RaplaComponent implements AppointmentTableColumn {
public AppointmentStartDate(RaplaContext context) {
super(context);
}
public void init(TableColumn column) {
column.setCellRenderer( new DateCellRenderer( getRaplaLocale()));
column.setMaxWidth( 175 );
column.setPreferredWidth( 175 );
}
public Object getValue(AppointmentBlock block) {
return new Date(block.getStart());
}
public String getColumnName() {
return getString("start_date");
}
public Class<?> getColumnClass() {
return Date.class;
}
public String getHtmlValue(AppointmentBlock block)
{
RaplaLocale raplaLocale = getRaplaLocale();
final Date date = new Date(block.getStart());
if ( block.getAppointment().isWholeDaysSet())
{
String dateString= raplaLocale.formatDateLong(date);
return dateString;
}
else
{
String dateString= raplaLocale.formatDateLong(date) + " " + raplaLocale.formatTime( date);
return dateString;
}
}
} | 04900db4-rob | src/org/rapla/plugin/tableview/internal/AppointmentStartDate.java | Java | gpl3 | 1,427 |
package org.rapla.plugin.tableview.internal;
import org.rapla.entities.domain.Allocatable;
import org.rapla.framework.RaplaContext;
public final class PersonColumn extends AllocatableListColumn {
public PersonColumn(RaplaContext context) {
super(context);
}
@Override
protected boolean contains(Allocatable alloc)
{
return alloc.isPerson();
}
public String getColumnName()
{
return getString("persons");
}
} | 04900db4-rob | src/org/rapla/plugin/tableview/internal/PersonColumn.java | Java | gpl3 | 447 |
package org.rapla.plugin.tableview.internal;
import org.rapla.entities.domain.Allocatable;
import org.rapla.framework.RaplaContext;
public final class ResourceColumn extends AllocatableListColumn {
public ResourceColumn(RaplaContext context) {
super(context);
}
@Override
protected boolean contains(Allocatable alloc)
{
return !alloc.isPerson();
}
public String getColumnName()
{
return getString("resources");
}
} | 04900db4-rob | src/org/rapla/plugin/tableview/internal/ResourceColumn.java | Java | gpl3 | 457 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.tableview.internal;
import javax.swing.Icon;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.SwingCalendarView;
import org.rapla.gui.SwingViewFactory;
import org.rapla.gui.images.Images;
public class ReservationTableViewFactory extends RaplaComponent implements SwingViewFactory
{
public ReservationTableViewFactory( RaplaContext context )
{
super( context );
}
public final static String TABLE_VIEW = "table";
public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException
{
return new SwingReservationTableView( context, model, editable);
}
public String getViewId()
{
return TABLE_VIEW;
}
public String getName()
{
return getString("reservations");
}
Icon icon;
public Icon getIcon()
{
if ( icon == null) {
icon = Images.getIcon("/org/rapla/plugin/tableview/images/eventlist.png");
}
return icon;
}
public String getMenuSortKey() {
return "0";
}
}
| 04900db4-rob | src/org/rapla/plugin/tableview/internal/ReservationTableViewFactory.java | Java | gpl3 | 2,175 |
package org.rapla.plugin.tableview.internal;
import javax.swing.table.TableColumn;
import org.rapla.components.util.xml.XMLWriter;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.plugin.tableview.AppointmentTableColumn;
public final class AppointmentNameColumn extends RaplaComponent implements AppointmentTableColumn {
public AppointmentNameColumn(RaplaContext context) {
super(context);
}
public void init(TableColumn column) {
}
public Object getValue(AppointmentBlock block)
{
// getLocale().
Appointment appointment = block.getAppointment();
Reservation reservation = appointment.getReservation();
return reservation.getName(getLocale());
}
public String getColumnName() {
return getString("name");
}
public Class<?> getColumnClass() {
return String.class;
}
public String getHtmlValue(AppointmentBlock block) {
String value = getValue(block).toString();
return XMLWriter.encode(value);
}
} | 04900db4-rob | src/org/rapla/plugin/tableview/internal/AppointmentNameColumn.java | Java | gpl3 | 1,182 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.tableview.internal;
import java.awt.Component;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
import org.rapla.RaplaMainContainer;
import org.rapla.components.iolayer.IOInterface;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.IdentifiableMenuEntry;
import org.rapla.plugin.tableview.RaplaTableColumn;
import org.rapla.plugin.tableview.TableViewExtensionPoints;
public class CSVExportMenu extends RaplaGUIComponent implements IdentifiableMenuEntry, ActionListener
{
JMenuItem exportEntry;
String idString = "csv";
public CSVExportMenu( RaplaContext context )
{
super( context );
exportEntry = new JMenuItem(getString("csv.export"));
exportEntry.setIcon( getIcon("icon.export") );
exportEntry.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
try {
CalendarSelectionModel model = getService(CalendarSelectionModel.class);
export( model);
} catch (Exception ex) {
showException( ex, getMainComponent() );
}
}
public String getId() {
return idString;
}
public JMenuItem getMenuElement() {
return exportEntry;
}
private static final String LINE_BREAK = "\n";
private static final String CELL_BREAK = ";";
@SuppressWarnings({ "unchecked", "rawtypes" })
public void export(final CalendarSelectionModel model) throws Exception
{
// generates a text file from all filtered events;
StringBuffer buf = new StringBuffer();
Collection< ? extends RaplaTableColumn<?>> columns;
List<Object> objects = new ArrayList<Object>();
if (model.getViewId().equals(ReservationTableViewFactory.TABLE_VIEW))
{
columns = getContainer().lookupServicesFor(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN);
objects.addAll(Arrays.asList( model.getReservations()));
}
else
{
columns = getContainer().lookupServicesFor(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN);
objects.addAll( model.getBlocks());
}
for (RaplaTableColumn column: columns)
{
buf.append( column.getColumnName());
buf.append(CELL_BREAK);
}
for (Object row: objects)
{
buf.append(LINE_BREAK);
for (RaplaTableColumn column: columns)
{
Object value = column.getValue( row);
Class columnClass = column.getColumnClass();
boolean isDate = columnClass.isAssignableFrom( java.util.Date.class);
String formated = "";
if(value != null) {
if ( isDate)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone( getRaplaLocale().getTimeZone());
String timestamp = format.format( (java.util.Date)value);
formated = timestamp;
}
else
{
String escaped = escape(value);
formated = escaped;
}
}
buf.append( formated );
buf.append(CELL_BREAK);
}
}
byte[] bytes = buf.toString().getBytes();
DateFormat sdfyyyyMMdd = new SimpleDateFormat("yyyyMMdd");
final String calendarName = getQuery().getSystemPreferences().getEntryAsString(RaplaMainContainer.TITLE, getString("rapla.title"));
String filename = calendarName + "-" + sdfyyyyMMdd.format( model.getStartDate() ) + "-" + sdfyyyyMMdd.format( model.getEndDate() ) + ".csv";
if (saveFile( bytes, filename,"csv"))
{
exportFinished(getMainComponent());
}
}
protected boolean exportFinished(Component topLevel) {
try {
DialogUI dlg = DialogUI.create(
getContext()
,topLevel
,true
,getString("export")
,getString("file_saved")
,new String[] { getString("ok")}
);
dlg.setIcon(getIcon("icon.export"));
dlg.setDefault(0);
dlg.start();
return (dlg.getSelectedIndex() == 0);
} catch (RaplaException e) {
return true;
}
}
private String escape(Object cell) {
return cell.toString().replace(LINE_BREAK, " ").replace(CELL_BREAK, " ");
}
public boolean saveFile(byte[] content,String filename, String extension) throws RaplaException {
final Frame frame = (Frame) SwingUtilities.getRoot(getMainComponent());
IOInterface io = getService( IOInterface.class);
try
{
String file = io.saveFile( frame, null, new String[] {extension}, filename, content);
return file != null;
}
catch (IOException e)
{
throw new RaplaException(e.getMessage(), e);
}
}
}
| 04900db4-rob | src/org/rapla/plugin/tableview/internal/CSVExportMenu.java | Java | gpl3 | 6,092 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.tableview.internal;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.framework.Configuration;
import org.rapla.framework.Container;
import org.rapla.framework.PluginDescriptor;
import org.rapla.plugin.tableview.TableViewExtensionPoints;
public class TableViewPlugin implements PluginDescriptor<ClientServiceContainer>
{
public static final String PLUGIN_CLASS = TableViewPlugin.class.getName();
public static final String EVENTS_SORTING_STRING_OPTION = "org.rapla.plugin.tableview.events.sortingstring";
public static final String BLOCKS_SORTING_STRING_OPTION = "org.rapla.plugin.tableview.blocks.sortingstring";
public final static boolean ENABLE_BY_DEFAULT = true;
public void provideServices(final ClientServiceContainer container, Configuration config)
{
if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( RaplaClientExtensionPoints.EXPORT_MENU_EXTENSION_POINT, CSVExportMenu.class);
container.addContainerProvidedComponent( RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,ReservationTableViewFactory.class);
container.addContainerProvidedComponent( RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,AppointmentTableViewFactory.class);
addReservationTableColumns(container);
addAppointmentTableColumns(container);
//Summary rows
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_SUMMARY, EventCounter.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_SUMMARY, AppointmentCounter.class);
}
protected void addAppointmentTableColumns(final Container container) {
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, AppointmentNameColumn.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, AppointmentStartDate.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, AppointmentEndDate.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, ResourceColumn.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, PersonColumn.class);
}
protected void addReservationTableColumns(final Container container) {
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, ReservationNameColumn.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, ReservationStartColumn.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, ReservationLastChangedColumn.class);
}
}
| 04900db4-rob | src/org/rapla/plugin/tableview/internal/TableViewPlugin.java | Java | gpl3 | 3,841 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2012 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.tableview.internal.server;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.CalendarModel;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.tableview.RaplaTableColumn;
import org.rapla.plugin.tableview.TableViewExtensionPoints;
import org.rapla.plugin.tableview.internal.TableViewPlugin;
public class ReservationTableViewPage extends TableViewPage<Reservation>
{
public ReservationTableViewPage( RaplaContext context, CalendarModel calendarModel )
{
super( context, calendarModel );
}
String getCalendarHTML() throws RaplaException {
final Date startDate = model.getStartDate();
final Date endDate = model.getEndDate();
final List<Reservation> reservations = Arrays.asList(model.getReservations(startDate, endDate));
List< RaplaTableColumn<Reservation>> columPluigns = new ArrayList<RaplaTableColumn<Reservation>>(getContainer().lookupServicesFor(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN));
return getCalendarHTML( columPluigns, reservations,TableViewPlugin.EVENTS_SORTING_STRING_OPTION );
}
@Override
int compareTo(Reservation r1, Reservation r2) {
if ( r1.equals( r2))
{
return 0;
}
int compareTo = r1.getFirstDate().compareTo( r2.getFirstDate());
return compareTo;
}
}
| 04900db4-rob | src/org/rapla/plugin/tableview/internal/server/ReservationTableViewPage.java | Java | gpl3 | 2,541 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.tableview.internal.server;
import org.rapla.framework.Configuration;
import org.rapla.framework.Container;
import org.rapla.framework.PluginDescriptor;
import org.rapla.plugin.tableview.TableViewExtensionPoints;
import org.rapla.plugin.tableview.internal.AppointmentCounter;
import org.rapla.plugin.tableview.internal.AppointmentEndDate;
import org.rapla.plugin.tableview.internal.AppointmentNameColumn;
import org.rapla.plugin.tableview.internal.AppointmentStartDate;
import org.rapla.plugin.tableview.internal.EventCounter;
import org.rapla.plugin.tableview.internal.PersonColumn;
import org.rapla.plugin.tableview.internal.ReservationLastChangedColumn;
import org.rapla.plugin.tableview.internal.ReservationNameColumn;
import org.rapla.plugin.tableview.internal.ReservationStartColumn;
import org.rapla.plugin.tableview.internal.ResourceColumn;
import org.rapla.plugin.tableview.internal.TableViewPlugin;
import org.rapla.server.RaplaServerExtensionPoints;
import org.rapla.server.ServerServiceContainer;
public class TableViewServerPlugin implements PluginDescriptor<ServerServiceContainer>
{
public void provideServices(final ServerServiceContainer container, Configuration config)
{
if ( !config.getAttributeAsBoolean("enabled", TableViewPlugin.ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,ReservationHTMLTableViewFactory.class);
container.addContainerProvidedComponent( RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,AppointmentHTMLTableViewFactory.class);
addReservationTableColumns(container);
addAppointmentTableColumns(container);
//Summary rows
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_SUMMARY, EventCounter.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_SUMMARY, AppointmentCounter.class);
}
protected void addAppointmentTableColumns(final Container container) {
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, AppointmentNameColumn.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, AppointmentStartDate.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, AppointmentEndDate.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, ResourceColumn.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, PersonColumn.class);
}
protected void addReservationTableColumns(final Container container) {
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, ReservationNameColumn.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, ReservationStartColumn.class);
container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, ReservationLastChangedColumn.class);
}
}
| 04900db4-rob | src/org/rapla/plugin/tableview/internal/server/TableViewServerPlugin.java | Java | gpl3 | 4,122 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2012 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.tableview.internal.server;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.facade.CalendarModel;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.tableview.AppointmentTableColumn;
import org.rapla.plugin.tableview.RaplaTableColumn;
import org.rapla.plugin.tableview.TableViewExtensionPoints;
import org.rapla.plugin.tableview.internal.TableViewPlugin;
public class AppointmentTableViewPage extends TableViewPage<AppointmentBlock>
{
public AppointmentTableViewPage( RaplaContext context, CalendarModel calendarModel )
{
super( context,calendarModel );
}
public String getCalendarHTML() throws RaplaException {
final List<AppointmentBlock> blocks = model.getBlocks();
Collection<AppointmentTableColumn> map2 = getContainer().lookupServicesFor(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN);
List<RaplaTableColumn<AppointmentBlock>> appointmentColumnPlugins = new ArrayList<RaplaTableColumn<AppointmentBlock>>(map2);
return getCalendarHTML(appointmentColumnPlugins, blocks, TableViewPlugin.BLOCKS_SORTING_STRING_OPTION);
}
int compareTo(AppointmentBlock object1, AppointmentBlock object2)
{
return object1.compareTo( object2);
}
}
| 04900db4-rob | src/org/rapla/plugin/tableview/internal/server/AppointmentTableViewPage.java | Java | gpl3 | 2,394 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.tableview.internal.server;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory;
import org.rapla.servletpages.RaplaPageGenerator;
public class ReservationHTMLTableViewFactory extends RaplaComponent implements HTMLViewFactory
{
public ReservationHTMLTableViewFactory( RaplaContext context )
{
super( context );
}
public final static String TABLE_VIEW = "table";
public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) throws RaplaException
{
return new ReservationTableViewPage( context, model);
}
public String getViewId()
{
return TABLE_VIEW;
}
public String getName()
{
return getString("reservations");
}
}
| 04900db4-rob | src/org/rapla/plugin/tableview/internal/server/ReservationHTMLTableViewFactory.java | Java | gpl3 | 1,870 |
package org.rapla.plugin.tableview.internal.server;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.entities.domain.Allocatable;
import org.rapla.facade.CalendarModel;
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.server.AbstractHTMLCalendarPage;
import org.rapla.plugin.tableview.RaplaTableColumn;
import org.rapla.servletpages.RaplaPageGenerator;
abstract public class TableViewPage<T> extends RaplaComponent implements RaplaPageGenerator {
protected CalendarModel model;
public TableViewPage(RaplaContext context, CalendarModel model) {
super(context);
this.model = model;
}
public String getTitle() {
return model.getNonEmptyTitle();
}
public void generatePage(ServletContext context, HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html; charset=" + getRaplaLocale().getCharsetNonUtf() );
java.io.PrintWriter out = response.getWriter();
RaplaLocale raplaLocale= getRaplaLocale();
String linkPrefix = request.getPathTranslated() != null ? "../": "";
out.println("<html>");
out.println("<head>");
out.println(" <title>" + getTitle() + "</title>");
out.println(" <link REL=\"stylesheet\" href=\""+linkPrefix + "calendar.css\" type=\"text/css\">");
out.println(" <link REL=\"stylesheet\" href=\""+linkPrefix + "default.css\" type=\"text/css\">");
// tell the html page where its favourite icon is stored
out.println(" <link REL=\"shortcut icon\" type=\"image/x-icon\" href=\"/images/favicon.ico\">");
out.println(" <meta HTTP-EQUIV=\"Content-Type\" content=\"text/html; charset=" + raplaLocale.getCharsetNonUtf() + "\">");
out.println("</head>");
out.println("<body>");
if (request.getParameter("selected_allocatables") != null && request.getParameter("allocatable_id")==null)
{
try {
Allocatable[] selectedAllocatables = model.getSelectedAllocatables();
AbstractHTMLCalendarPage.printAllocatableList(request, out, getLocale(), selectedAllocatables);
} catch (RaplaException e) {
throw new ServletException(e);
}
}
else
{
out.println("<h2 class=\"title\">");
out.println(getTitle());
out.println("</h2>");
out.println("<div id=\"calendar\">");
try {
final String calendarHTML = getCalendarHTML();
out.println(calendarHTML);
} catch (RaplaException e) {
out.close();
throw new ServletException( e);
}
out.println("</div>");
}
// end weekview
out.println("</body>");
out.println("</html>");
out.close();
}
class TableRow implements Comparable<TableRow>
{
T object;
@SuppressWarnings("rawtypes")
RaplaTableColumn reservationColumnPlugins;
int direction;
TableRow(T originalObject, RaplaTableColumn<T> reservationColumnPlugins, int sortDirection)
{
this.object = originalObject;
this.reservationColumnPlugins = reservationColumnPlugins;
this.direction = sortDirection;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public int compareTo(TableRow o) {
if (o.equals( this))
{
return 0;
}
if ( reservationColumnPlugins != null)
{
Object v1 = reservationColumnPlugins.getValue( object );
Object v2 = o.reservationColumnPlugins.getValue( o.object);
if ( v1 != null && v2 != null)
{
Class<?> columnClass = reservationColumnPlugins.getColumnClass();
if ( columnClass.equals( String.class))
{
return String.CASE_INSENSITIVE_ORDER.compare( v1.toString(), v2.toString()) * direction;
}
else if (columnClass.isAssignableFrom(Comparable.class))
{
return ((Comparable)v1).compareTo( v2) * direction;
}
}
}
T object1 = object;
T object2 = o.object;
return TableViewPage.this.compareTo(object1,object2);
}
}
public String getCalendarHTML(List< RaplaTableColumn<T>> columPluigns, List<T> rowObjects,String sortingStringOption) {
RaplaTableColumn<T> columPlugin = null;
int sortDirection =1;
String sorting = model.getOption(sortingStringOption);
if ( sorting != null)
{
Enumeration<Object> e = new StringTokenizer( sorting,";", false);
for (Object stringToCast:Collections.list(e))
{
String string = (String) stringToCast;
int length = string.length();
int column = Integer.parseInt(string.substring(0,length-1));
char order = string.charAt( length-1);
if ( columPluigns.size() > column)
{
columPlugin = columPluigns.get( column );
sortDirection= order == '+' ? 1: -1;
}
}
}
List<TableRow> rows = new ArrayList<TableRow>();
for (T r :rowObjects)
{
rows.add( new TableRow( r, columPlugin, sortDirection));
}
Collections.sort( rows);
StringBuffer buf = new StringBuffer();
buf.append("<table class='eventtable'>");
for (RaplaTableColumn<?> col: columPluigns)
{
buf.append("<th>");
buf.append(col.getColumnName());
buf.append("</th>");
}
for (TableRow row :rows)
{
buf.append("<tr>");
for (RaplaTableColumn<T> col: columPluigns)
{
buf.append("<td>");
T rowObject = row.object;
buf.append(col.getHtmlValue(rowObject));
buf.append("</td>");
}
buf.append("</tr>");
}
buf.append("</table>");
final String result = buf.toString();
return result;
}
abstract String getCalendarHTML() throws RaplaException;
abstract int compareTo(T object1, T object2);
} | 04900db4-rob | src/org/rapla/plugin/tableview/internal/server/TableViewPage.java | Java | gpl3 | 6,903 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.tableview.internal.server;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory;
import org.rapla.servletpages.RaplaPageGenerator;
public class AppointmentHTMLTableViewFactory extends RaplaComponent implements HTMLViewFactory
{
public AppointmentHTMLTableViewFactory( RaplaContext context )
{
super( context );
}
public final static String TABLE_VIEW = "table_appointments";
public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model)
{
return new AppointmentTableViewPage( context, model);
}
public String getViewId()
{
return TABLE_VIEW;
}
public String getName()
{
return getString("appointments");
}
}
| 04900db4-rob | src/org/rapla/plugin/tableview/internal/server/AppointmentHTMLTableViewFactory.java | Java | gpl3 | 1,818 |
package org.rapla.plugin.tableview.internal;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
public final class AppointmentCounter extends RaplaComponent implements SummaryExtension {
public AppointmentCounter(RaplaContext context)
{
super(context);
}
public void init(final JTable table, JPanel summaryRow) {
final JLabel counter = new JLabel();
summaryRow.add( counter);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0)
{
int count = table.getSelectedRows().length;
counter.setText( count+ " " + (count == 1 ? getString("appointment") : getString("appointments")) + " ");
}
});
}
} | 04900db4-rob | src/org/rapla/plugin/tableview/internal/AppointmentCounter.java | Java | gpl3 | 943 |
package org.rapla.plugin.tableview.internal;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
public final class EventCounter extends RaplaComponent implements SummaryExtension {
public EventCounter(RaplaContext context)
{
super(context);
}
public void init(final JTable table, JPanel summaryRow) {
final JLabel counter = new JLabel();
summaryRow.add( counter);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0)
{
int count = table.getSelectedRows().length;
counter.setText( count+ " " + (count == 1 ? getString("reservation") : getString("reservations")) + " " );
}
});
}
} | 04900db4-rob | src/org/rapla/plugin/tableview/internal/EventCounter.java | Java | gpl3 | 932 |
package org.rapla.plugin.tableview.internal;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import org.rapla.components.calendar.DateChangeEvent;
import org.rapla.components.calendar.DateChangeListener;
import org.rapla.components.tablesorter.TableSorter;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.MenuContext;
import org.rapla.gui.MenuFactory;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.SwingCalendarView;
import org.rapla.gui.VisibleTimeInterval;
import org.rapla.gui.internal.common.InternMenus;
import org.rapla.gui.internal.common.RaplaClipboard;
import org.rapla.gui.toolkit.MenuInterface;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaPopupMenu;
import org.rapla.plugin.abstractcalendar.IntervalChooserPanel;
import org.rapla.plugin.tableview.RaplaTableColumn;
import org.rapla.plugin.tableview.ReservationTableColumn;
import org.rapla.plugin.tableview.TableViewExtensionPoints;
public class SwingReservationTableView extends RaplaGUIComponent implements SwingCalendarView, Printable, VisibleTimeInterval
{
ReservationTableModel reservationTableModel;
JTable table;
CalendarModel model;
IntervalChooserPanel dateChooser;
JScrollPane scrollpane;
JComponent container;
TableSorter sorter;
ActionListener copyListener = new ActionListener() {
public void actionPerformed(ActionEvent evt)
{
List<Reservation> selectedEvents = getSelectedEvents();
List<Reservation> clones = new ArrayList<Reservation>();
try {
for (Reservation r:selectedEvents)
{
Reservation copyReservation = getModification().clone(r);
clones.add( copyReservation);
}
} catch (RaplaException e) {
showException( e, getComponent());
}
Collection<Allocatable> markedAllocatables = model.getMarkedAllocatables();
getClipboard().setReservation( clones, markedAllocatables);
copy(table, evt);
}
private RaplaClipboard getClipboard() {
return getService(RaplaClipboard.class);
}
};
public SwingReservationTableView( RaplaContext context, final CalendarModel model, final boolean editable ) throws RaplaException
{
super( context );
table = new JTable() {
private static final long serialVersionUID = 1L;
public String getToolTipText(MouseEvent e)
{
if (!editable)
return null;
int rowIndex = rowAtPoint( e.getPoint() );
Reservation reservation = reservationTableModel.getReservationAt( sorter.modelIndex( rowIndex ));
return getInfoFactory().getToolTip( reservation );
}
};
scrollpane = new JScrollPane( table);
if ( editable )
{
container = new JPanel();
container.setLayout( new BorderLayout());
container.add( scrollpane, BorderLayout.CENTER);
JPanel extensionPanel = new JPanel();
extensionPanel.setLayout( new BoxLayout(extensionPanel, BoxLayout.X_AXIS));
container.add( extensionPanel, BorderLayout.SOUTH);
scrollpane.setPreferredSize( new Dimension(600,800));
PopupTableHandler popupHandler = new PopupTableHandler();
scrollpane.addMouseListener( popupHandler);
table.addMouseListener( popupHandler );
Collection< ? extends SummaryExtension> reservationSummaryExtensions = getContainer().lookupServicesFor(TableViewExtensionPoints.RESERVATION_TABLE_SUMMARY);
for ( SummaryExtension summary:reservationSummaryExtensions)
{
summary.init(table, extensionPanel);
}
}
else
{
Dimension size = table.getPreferredSize();
scrollpane.setBounds( 0,0,600, (int)size.getHeight());
container = scrollpane;
}
this.model = model;
//Map<?,?> map = getContainer().lookupServicesFor(RaplaExtensionPoints.APPOINTMENT_STATUS);
//Collection<AppointmentStatusFactory> appointmentStatusFactories = (Collection<AppointmentStatusFactory>) map.values();
List< ? extends ReservationTableColumn> reservationColumnPlugins = new ArrayList<ReservationTableColumn>(getContainer().lookupServicesFor(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN));
reservationTableModel = new ReservationTableModel( getLocale(),getI18n(), reservationColumnPlugins );
ReservationTableModel tableModel = reservationTableModel;
sorter = createAndSetSorter(model, table, TableViewPlugin.EVENTS_SORTING_STRING_OPTION, tableModel);
int column = 0;
for (RaplaTableColumn<?> col: reservationColumnPlugins)
{
col.init(table.getColumnModel().getColumn(column ));
column++;
}
table.setColumnSelectionAllowed( true );
table.setRowSelectionAllowed( true);
table.getTableHeader().setReorderingAllowed(false);
table.registerKeyboardAction(copyListener,getString("copy"),COPY_STROKE,JComponent.WHEN_FOCUSED);
dateChooser = new IntervalChooserPanel( context, model);
dateChooser.addDateChangeListener( new DateChangeListener() {
public void dateChanged( DateChangeEvent evt )
{
try {
update( );
} catch (RaplaException ex ){
showException( ex, getComponent());
}
}
});
reservationTableModel.setReservations( model.getReservations() );
Listener listener = new Listener();
table.getSelectionModel().addListSelectionListener( listener);
table.addFocusListener( listener);
}
class Listener implements ListSelectionListener, FocusListener
{
public void valueChanged(ListSelectionEvent e) {
updateEditMenu();
}
public void focusGained(FocusEvent e) {
updateEditMenu();
}
public void focusLost(FocusEvent e) {
}
}
public static TableSorter createAndSetSorter(final CalendarModel model, final JTable table, final String sortingStringOptionName, TableModel tableModel) {
final TableSorter sorter = new TableSorter( tableModel, table.getTableHeader());
String sorting = model.getOption(sortingStringOptionName);
if ( sorting != null)
{
Enumeration<Object> e = new StringTokenizer( sorting,";", false);
for (Object stringToCast:Collections.list(e))
{
String string = (String) stringToCast;
int length = string.length();
int column = Integer.parseInt(string.substring(0,length-1));
char order = string.charAt( length-1);
if ( column < tableModel.getColumnCount())
{
sorter.setSortingStatus( column, order == '-' ? TableSorter.DESCENDING : TableSorter.ASCENDING);
}
}
}
sorter.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e)
{
StringBuffer buf = new StringBuffer();
for ( int i=0;i<table.getColumnCount();i++)
{
int sortingStatus = sorter.getSortingStatus( i);
if (sortingStatus == TableSorter.ASCENDING)
{
buf.append(i + "+;");
}
if (sortingStatus == TableSorter.DESCENDING)
{
buf.append(i + "-;");
}
}
String sortingString = buf.toString();
((CalendarSelectionModel)model).setOption(sortingStringOptionName, sortingString.length() > 0 ? sortingString : null);
}
});
table.setModel( sorter );
return sorter;
}
protected void updateEditMenu() {
List<Reservation> selectedEvents = getSelectedEvents();
if ( selectedEvents.size() == 0 )
{
return;
}
RaplaMenu editMenu = getService(InternMenus.EDIT_MENU_ROLE);
RaplaMenu newMenu = getService(InternMenus.NEW_MENU_ROLE);
editMenu.removeAllBetween("EDIT_BEGIN", "EDIT_END");
newMenu.removeAll();
Point p = null;
try {
updateMenu(editMenu,newMenu, p);
boolean canUserAllocateSomething = canUserAllocateSomething(getUser());
boolean enableNewMenu = newMenu.getMenuComponentCount() > 0 && canUserAllocateSomething;
newMenu.setEnabled(enableNewMenu);
editMenu.setEnabled(canUserAllocateSomething(getUser()));
} catch (RaplaException ex) {
showException (ex,getComponent());
}
}
public void update() throws RaplaException
{
reservationTableModel.setReservations( model.getReservations() );
dateChooser.update();
}
public JComponent getDateSelection()
{
return dateChooser.getComponent();
}
public void scrollToStart()
{
}
public JComponent getComponent()
{
return container;
}
protected void updateMenu(MenuInterface editMenu,MenuInterface newMenu, Point p) throws RaplaException {
List<Reservation> selectedEvents = getSelectedEvents();
Reservation focusedObject = null;
if ( selectedEvents.size() == 1) {
focusedObject = selectedEvents.get( 0);
}
MenuContext menuContext = new MenuContext( getContext(), focusedObject,getComponent(),p);
menuContext.setSelectedObjects( selectedEvents);
// add the new reservations wizards
MenuFactory menuFactory = getService(MenuFactory.class);
menuFactory.addReservationWizards( newMenu, menuContext, null);
// add the edit methods
if ( selectedEvents.size() != 0) {
final JMenuItem copyItem = new JMenuItem();
copyItem.addActionListener( copyListener);
copyItem.setText(getString("copy"));
copyItem.setIcon( getIcon("icon.copy"));
editMenu.insertAfterId(copyItem, "EDIT_BEGIN");
menuFactory.addObjectMenu( editMenu, menuContext, "EDIT_BEGIN");
}
}
List<Reservation> getSelectedEvents() {
int[] rows = table.getSelectedRows();
List<Reservation> selectedEvents = new ArrayList<Reservation>();
for (int i=0;i<rows.length;i++)
{
Reservation reservation =reservationTableModel.getReservationAt( sorter.modelIndex(rows[i]) );
selectedEvents.add( reservation);
}
return selectedEvents;
}
class PopupTableHandler extends MouseAdapter {
void showPopup(MouseEvent me) {
try
{
RaplaPopupMenu menu= new RaplaPopupMenu();
Point p = new Point(me.getX(), me.getY());
RaplaMenu newMenu = new RaplaMenu("EDIT_BEGIN");
newMenu.setText(getString("new"));
menu.add(newMenu);
boolean canUserAllocateSomething = canUserAllocateSomething(getUser());
updateMenu(menu,newMenu, p);
boolean enableNewMenu = newMenu.getMenuComponentCount() > 0 && canUserAllocateSomething;
newMenu.setEnabled(enableNewMenu);
menu.show( table, p.x, p.y);
} catch (RaplaException ex) {
showException (ex,getComponent());
}
}
/** Implementation-specific. Should be private.*/
public void mousePressed(MouseEvent me) {
if (me.isPopupTrigger())
showPopup(me);
}
/** Implementation-specific. Should be private.*/
public void mouseReleased(MouseEvent me) {
if (me.isPopupTrigger())
showPopup(me);
}
/** we want to edit the reservation on double click*/
public void mouseClicked(MouseEvent me) {
List<Reservation> selectedEvents = getSelectedEvents();
if (me.getClickCount() > 1 && selectedEvents.size() == 1 )
{
Reservation reservation = selectedEvents.get( 0);
if (!canModify( reservation ))
{
return;
}
try {
getReservationController().edit( reservation );
} catch (RaplaException ex) {
showException (ex,getComponent());
}
}
}
}
Printable printable = null;
/**
* @see java.awt.print.Printable#print(java.awt.Graphics, java.awt.print.PageFormat, int)
*/
public int print(Graphics graphics, PageFormat format, int page) throws PrinterException {
MessageFormat f1 = new MessageFormat( model.getNonEmptyTitle());
Printable printable = table.getPrintable( JTable.PrintMode.FIT_WIDTH,f1, null );
return printable.print( graphics, format, page);
}
public TimeInterval getVisibleTimeInterval() {
return new TimeInterval(model.getStartDate(), model.getEndDate());
}
}
| 04900db4-rob | src/org/rapla/plugin/tableview/internal/SwingReservationTableView.java | Java | gpl3 | 14,402 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.tableview.internal;
import javax.swing.Icon;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.SwingCalendarView;
import org.rapla.gui.SwingViewFactory;
import org.rapla.gui.images.Images;
public class AppointmentTableViewFactory extends RaplaComponent implements SwingViewFactory
{
public AppointmentTableViewFactory( RaplaContext context )
{
super( context );
}
public final static String TABLE_VIEW = "table_appointments";
public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException
{
return new SwingAppointmentTableView( context, model, editable);
}
public String getViewId()
{
return TABLE_VIEW;
}
public String getName()
{
return getString("appointments");
}
Icon icon;
public Icon getIcon()
{
if ( icon == null) {
icon = Images.getIcon("/org/rapla/plugin/tableview/images/table.png");
}
return icon;
}
public String getMenuSortKey() {
return "0";
}
}
| 04900db4-rob | src/org/rapla/plugin/tableview/internal/AppointmentTableViewFactory.java | Java | gpl3 | 2,183 |
package org.rapla.plugin.tableview;
import org.rapla.framework.TypedComponentRole;
import org.rapla.plugin.tableview.internal.SummaryExtension;
public interface TableViewExtensionPoints {
/** add a summary footer for the reservation table
@see SummaryExtension
* */
TypedComponentRole<SummaryExtension> RESERVATION_TABLE_SUMMARY = new TypedComponentRole<SummaryExtension>("org.rapla.plugin.tableview.reservationsummary");
/** add a column for the reservation table
*
@see ReservationTableColumn
*/
Class<ReservationTableColumn> RESERVATION_TABLE_COLUMN = ReservationTableColumn.class;
/** add a column for the appointment table
@see AppointmentTableColumn
* */
Class<AppointmentTableColumn> APPOINTMENT_TABLE_COLUMN = AppointmentTableColumn.class;
/** add a summary footer for the appointment table
@see SummaryExtension
* */
TypedComponentRole<SummaryExtension> APPOINTMENT_TABLE_SUMMARY = new TypedComponentRole<SummaryExtension>("org.rapla.plugin.tableview.appointmentsummary");
}
| 04900db4-rob | src/org/rapla/plugin/tableview/TableViewExtensionPoints.java | Java | gpl3 | 1,051 |
package org.rapla.plugin.tableview;
import javax.swing.table.TableColumn;
public interface RaplaTableColumn<T> {
public abstract String getColumnName();
public abstract Object getValue(T object);
public abstract void init(TableColumn column);
public abstract Class<?> getColumnClass();
public abstract String getHtmlValue(T object);
} | 04900db4-rob | src/org/rapla/plugin/tableview/RaplaTableColumn.java | Java | gpl3 | 363 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2012 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.tableview;
import org.rapla.entities.domain.Reservation;
public interface ReservationTableColumn extends RaplaTableColumn<Reservation>
{
}
| 04900db4-rob | src/org/rapla/plugin/tableview/ReservationTableColumn.java | Java | gpl3 | 1,124 |
<body>
This is the base package of the GUI-client. Communication through the backend
is done through the modules of <code>org.rapla.facade</code> package.
The gui-client is normally started through the <code>RaplaClientService</code>.
You can also plug-in your own components into the gui.
</body>
| 04900db4-rob | src/org/rapla/plugin/package.html | HTML | gpl3 | 301 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.periodcopy;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.TypedComponentRole;
public class PeriodCopyPlugin implements PluginDescriptor<ClientServiceContainer>
{
public static final boolean ENABLE_BY_DEFAULT = true;
public static final TypedComponentRole<I18nBundle> RESOURCE_FILE = new TypedComponentRole<I18nBundle>(PeriodCopyPlugin.class.getPackage().getName() + ".PeriodCopy");
public void provideServices(ClientServiceContainer container, Configuration config) {
if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( RESOURCE_FILE, I18nBundleImpl.class,I18nBundleImpl.createConfig( RESOURCE_FILE.getId() ) );
container.addContainerProvidedComponent( RaplaClientExtensionPoints.EDIT_MENU_EXTENSION_POINT, CopyPluginMenu.class);
}
}
| 04900db4-rob | src/org/rapla/plugin/periodcopy/PeriodCopyPlugin.java | Java | gpl3 | 2,089 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.periodcopy;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.components.calendar.DateChangeEvent;
import org.rapla.components.calendar.DateChangeListener;
import org.rapla.components.calendar.RaplaCalendar;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.internal.PeriodImpl;
import org.rapla.facade.CalendarModel;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.common.NamedListCellRenderer;
import org.rapla.gui.internal.edit.fields.BooleanField;
import org.rapla.gui.toolkit.RaplaWidget;
/** sample UseCase that only displays the text of the configuration and
all reservations of the user.*/
class CopyDialog extends RaplaGUIComponent implements RaplaWidget
{
@SuppressWarnings("unchecked")
JComboBox sourcePeriodChooser = new JComboBox(new String[] {"a", "b"});
@SuppressWarnings("unchecked")
JComboBox destPeriodChooser = new JComboBox(new String[] {"a", "b"});
RaplaLocale locale = getRaplaLocale();
RaplaCalendar destBegin;
RaplaCalendar sourceBegin;
RaplaCalendar sourceEnd;
JPanel panel = new JPanel();
JLabel label = new JLabel();
JList selectedReservations = new JList();
BooleanField singleChooser;
PeriodImpl customPeriod = new PeriodImpl("", null, null);
JPanel customSourcePanel = new JPanel();
JPanel customDestPanel = new JPanel();
@SuppressWarnings("unchecked")
public CopyDialog(RaplaContext sm) throws RaplaException {
super(sm);
locale = getRaplaLocale();
sourceBegin = createRaplaCalendar();
sourceEnd = createRaplaCalendar();
destBegin = createRaplaCalendar();
setChildBundleName( PeriodCopyPlugin.RESOURCE_FILE);
Period[] periods = getQuery().getPeriods();
singleChooser = new BooleanField(sm, "singleChooser");
singleChooser.addChangeListener( new ChangeListener() {
public void stateChanged(ChangeEvent e) {
try {
updateReservations();
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
});
DefaultComboBoxModel sourceModel = new DefaultComboBoxModel( periods );
Date today = getQuery().today();
final PeriodImpl customSource = new PeriodImpl(getString("custom_period"), today, today);
sourceModel.insertElementAt(customSource, 0);
DefaultComboBoxModel destModel = new DefaultComboBoxModel( periods );
final PeriodImpl customDest = new PeriodImpl(getString("custom_period"),today, null);
{
destModel.insertElementAt(customDest, 0);
}
//customEnd.setStart( destDate.getDate());
sourcePeriodChooser.setModel( sourceModel);
destPeriodChooser.setModel( destModel);
label.setText(getString("copy_selected_events_from"));
panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
panel.setLayout(new TableLayout(new double[][]{
{TableLayout.PREFERRED ,5 , TableLayout.FILL }
,{20, 5, TableLayout.PREFERRED ,5 ,TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED,5, TableLayout.PREFERRED,5, TableLayout.PREFERRED }
}
));
selectedReservations.setEnabled( false );
customSourcePanel.add( sourceBegin );
customSourcePanel.add( new JLabel(getString("time_until")) );
customSourcePanel.add( sourceEnd );
customDestPanel.add( destBegin);
panel.add(label, "0,0,2,1");
panel.add( new JLabel(getString("source")),"0,2" );
panel.add( sourcePeriodChooser,"2,2" );
panel.add( customSourcePanel,"2,4" );
panel.add( new JLabel(getString("destination")),"0,6" );
panel.add( destPeriodChooser,"2,6" );
panel.add( customDestPanel,"2,8" );
panel.add( new JLabel(getString("copy_single")),"0,10" );
panel.add( singleChooser.getComponent(),"2,10" );
singleChooser.setValue( Boolean.TRUE);
panel.add( new JLabel(getString("reservations")) , "0,12,l,t");
panel.add( new JScrollPane( selectedReservations ),"2,12" );
updateView();
sourcePeriodChooser.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateView();
if ( sourcePeriodChooser.getSelectedIndex() > 1)
{
Period beginPeriod = (Period)sourcePeriodChooser.getSelectedItem();
sourceBegin.setDate(beginPeriod.getStart());
sourceEnd.setDate(beginPeriod.getEnd());
}
}
});
NamedListCellRenderer aRenderer = new NamedListCellRenderer( getRaplaLocale().getLocale());
sourcePeriodChooser.setRenderer( aRenderer);
destPeriodChooser.setRenderer( aRenderer);
destPeriodChooser.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateView();
if ( destPeriodChooser.getSelectedIndex() > 0)
{
Period endPeriod = (Period)destPeriodChooser.getSelectedItem();
destBegin.setDate(endPeriod.getStart());
}
}
});
DateChangeListener dateChangeListener = new DateChangeListener() {
public void dateChanged(DateChangeEvent evt) {
customSource.setStart( sourceBegin.getDate());
customSource.setEnd( sourceEnd.getDate());
customDest.setStart( destBegin.getDate());
try {
updateReservations();
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
};
sourceBegin.addDateChangeListener(dateChangeListener);
sourceEnd.addDateChangeListener(dateChangeListener);
destBegin.addDateChangeListener(dateChangeListener);
sourcePeriodChooser.setSelectedIndex(0);
destPeriodChooser.setSelectedIndex(0);
updateReservations();
}
public Date getSourceStart()
{
return sourceBegin.getDate();
}
public Date getSourceEnd()
{
return sourceEnd.getDate();
}
public Date getDestStart()
{ return destBegin.getDate();
}
public Date getDestEnd()
{
if ( destPeriodChooser.getSelectedIndex() > 0)
{
Period endPeriod = (Period)destPeriodChooser.getSelectedItem();
return endPeriod.getStart();
}
else
{
return null;
}
}
private boolean isIncluded(Reservation r, boolean includeSingleAppointments)
{
Appointment[] appointments = r.getAppointments();
int count = 0;
for ( int j=0;j<appointments.length;j++) {
Appointment app = appointments[j];
Repeating repeating = app.getRepeating();
if (( repeating == null && !includeSingleAppointments) || (repeating != null && repeating.getEnd() == null)) {
continue;
}
count++;
}
return count > 0;
}
private void updateView() {
boolean customStartEnabled = sourcePeriodChooser.getSelectedIndex() == 0;
sourceBegin.setEnabled( customStartEnabled);
sourceEnd.setEnabled( customStartEnabled);
boolean customDestEnabled = destPeriodChooser.getSelectedIndex() == 0;
destBegin.setEnabled( customDestEnabled);
}
@SuppressWarnings("unchecked")
private void updateReservations() throws RaplaException
{
DefaultListModel listModel = new DefaultListModel();
List<Reservation> reservations = getReservations();
for ( Reservation reservation: reservations) {
listModel.addElement( reservation.getName( getLocale() ) );
}
selectedReservations.setModel( listModel);
}
public JComponent getComponent() {
return panel;
}
public boolean isSingleAppointments() {
Object value = singleChooser.getValue();
return value != null && ((Boolean)value).booleanValue();
}
public List<Reservation> getReservations() throws RaplaException {
final CalendarModel model = getService( CalendarModel.class);
Reservation[] reservations = model.getReservations( getSourceStart(), getSourceEnd() );
List<Reservation> listModel = new ArrayList<Reservation>();
for ( Reservation reservation:reservations) {
boolean includeSingleAppointments = isSingleAppointments();
if (isIncluded(reservation, includeSingleAppointments))
{
listModel.add( reservation );
}
}
return listModel;
}
}
| 04900db4-rob | src/org/rapla/plugin/periodcopy/CopyDialog.java | Java | gpl3 | 10,207 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.periodcopy;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.swing.JMenuItem;
import org.rapla.components.util.DateTools;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.ReservationStartComparator;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.edit.SaveUndo;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.IdentifiableMenuEntry;
import org.rapla.gui.toolkit.RaplaMenuItem;
public class CopyPluginMenu extends RaplaGUIComponent implements IdentifiableMenuEntry,ActionListener
{
RaplaMenuItem item;
String id = "copy_events";
final String label ;
public CopyPluginMenu(RaplaContext sm) {
super(sm);
setChildBundleName( PeriodCopyPlugin.RESOURCE_FILE);
//menu.insert( new RaplaSeparator("info_end"));
label =getString(id) ;
item = new RaplaMenuItem(id);
// ResourceBundle bundle = ResourceBundle.getBundle( "org.rapla.plugin.periodcopy.PeriodCopy");
//bundle.getString("copy_events");
item.setText( label );
item.setIcon( getIcon("icon.copy") );
item.addActionListener(this);
}
public String getId() {
return id;
}
public JMenuItem getMenuElement() {
return item;
}
// public void copy(CalendarModel model, Period sourcePeriod, Period destPeriod,boolean includeSingleAppointments) throws RaplaException {
// Reservation[] reservations = model.getReservations( sourcePeriod.getStart(), sourcePeriod.getEnd() );
// copy( reservations, destPeriod.getStart(), destPeriod.getEnd(),includeSingleAppointments);
// }
public void actionPerformed(ActionEvent evt) {
try {
final CopyDialog useCase = new CopyDialog(getContext());
String[] buttons = new String[]{getString("abort"), getString("copy") };
final DialogUI dialog = DialogUI.create( getContext(),getMainComponent(),true, useCase.getComponent(), buttons);
dialog.setTitle( label);
dialog.setSize( 600, 500);
dialog.getButton( 0).setIcon( getIcon("icon.abort"));
dialog.getButton( 1).setIcon( getIcon("icon.copy"));
// ActionListener listener = new ActionListener() {
// public void actionPerformed(ActionEvent arg0) {
// dialog.getButton( 1).setEnabled( useCase.isSourceDifferentFromDest() );
// }
// };
//
dialog.startNoPack();
final boolean includeSingleAppointments = useCase.isSingleAppointments();
if ( dialog.getSelectedIndex() == 1) {
List<Reservation> reservations = useCase.getReservations();
copy( reservations, useCase.getDestStart(), useCase.getDestEnd(), includeSingleAppointments );
}
} catch (Exception ex) {
showException( ex, getMainComponent() );
}
}
public void copy( List<Reservation> reservations , Date destStart, Date destEnd,boolean includeSingleAppointmentsAndExceptions) throws RaplaException {
List<Reservation> newReservations = new ArrayList<Reservation>();
List<Reservation> sortedReservations = new ArrayList<Reservation>( reservations);
Collections.sort( sortedReservations, new ReservationStartComparator(getLocale()));
Date firstStart = null;
for (Reservation reservation: sortedReservations) {
if ( firstStart == null )
{
firstStart = ReservationStartComparator.getStart( reservation);
}
Reservation r = copy(reservation, destStart,
destEnd, includeSingleAppointmentsAndExceptions,
firstStart);
if ( r.getAppointments().length > 0) {
newReservations.add( r );
}
}
Collection<Reservation> originalEntity = null;
SaveUndo<Reservation> cmd = new SaveUndo<Reservation>(getContext(), newReservations, originalEntity);
getModification().getCommandHistory().storeAndExecute( cmd);
}
public Reservation copy(Reservation reservation, Date destStart,
Date destEnd, boolean includeSingleAppointmentsAndExceptions,
Date firstStart) throws RaplaException {
Reservation r = getModification().clone( reservation);
if ( firstStart == null )
{
firstStart = ReservationStartComparator.getStart( reservation);
}
Appointment[] appointments = r.getAppointments();
for ( Appointment app :appointments) {
Repeating repeating = app.getRepeating();
if (( repeating == null && !includeSingleAppointmentsAndExceptions) || (repeating != null && repeating.getEnd() == null)) {
r.removeAppointment( app );
continue;
}
Date oldStart = app.getStart();
// we need to calculate an offset so that the reservations will place themself relativ to the first reservation in the list
long offset = DateTools.countDays( firstStart, oldStart) * DateTools.MILLISECONDS_PER_DAY;
Date newStart ;
Date destWithOffset = new Date(destStart.getTime() + offset );
if ( repeating != null && repeating.getType().equals ( Repeating.DAILY) )
{
newStart = getRaplaLocale().toDate( destWithOffset , oldStart );
}
else
{
newStart = getNewStartWeekly(oldStart, destWithOffset);
}
app.move( newStart) ;
if (repeating != null)
{
Date[] exceptions = repeating.getExceptions();
if ( includeSingleAppointmentsAndExceptions )
{
repeating.clearExceptions();
for (Date exc: exceptions)
{
long days = DateTools.countDays(oldStart, exc);
Date newDate = DateTools.addDays(newStart, days);
repeating.addException( newDate);
}
}
if ( !repeating.isFixedNumber())
{
Date oldEnd = repeating.getEnd();
if ( oldEnd != null)
{
if (destEnd != null)
{
repeating.setEnd( destEnd);
}
else
{
// If we don't have and endig destination, just make the repeating to the original length
long days = DateTools.countDays(oldStart, oldEnd);
Date end = DateTools.addDays(newStart, days);
repeating.setEnd( end);
}
}
}
}
// System.out.println(reservations[i].getName( getRaplaLocale().getLocale()));
}
return r;
}
private Date getNewStartWeekly(Date oldStart, Date destStart) {
Date newStart;
Calendar calendar = getRaplaLocale().createCalendar();
calendar.setTime( oldStart);
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
calendar = getRaplaLocale().createCalendar();
calendar.setTime(destStart);
calendar.set( Calendar.DAY_OF_WEEK, weekday);
if ( calendar.getTime().before( destStart))
{
calendar.add( Calendar.DATE, 7);
}
Date firstOccOfWeekday = calendar.getTime();
newStart = getRaplaLocale().toDate( firstOccOfWeekday, oldStart );
return newStart;
}
}
| 04900db4-rob | src/org/rapla/plugin/periodcopy/CopyPluginMenu.java | Java | gpl3 | 8,533 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.notification.server;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.plugin.notification.NotificationPlugin;
import org.rapla.server.RaplaServerExtensionPoints;
import org.rapla.server.ServerServiceContainer;
/** Users can subscribe for allocation change notifications for selected resources or persons.*/
public class NotificationServerPlugin implements PluginDescriptor<ServerServiceContainer>
{
public void provideServices(ServerServiceContainer container, Configuration config) {
if ( !config.getAttributeAsBoolean("enabled", NotificationPlugin.ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( NotificationPlugin.RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig( NotificationPlugin.RESOURCE_FILE.getId() ) );
container.addContainerProvidedComponent( RaplaServerExtensionPoints.SERVER_EXTENSION, NotificationService.class);
}
}
| 04900db4-rob | src/org/rapla/plugin/notification/server/NotificationServerPlugin.java | Java | gpl3 | 1,994 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.notification.server;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.rapla.RaplaMainContainer;
import org.rapla.components.util.Command;
import org.rapla.components.util.CommandScheduler;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.facade.AllocationChangeEvent;
import org.rapla.facade.AllocationChangeListener;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.mail.MailToUserInterface;
import org.rapla.plugin.notification.NotificationPlugin;
import org.rapla.server.ServerExtension;
/** Sends Notification Mails on allocation change.*/
public class NotificationService extends RaplaComponent
implements
AllocationChangeListener,
ServerExtension
{
ClientFacade clientFacade;
MailToUserInterface mailToUserInterface;
protected CommandScheduler mailQueue;
public NotificationService(RaplaContext context) throws RaplaException
{
super( context);
setLogger( getLogger().getChildLogger("notification"));
clientFacade = context.lookup(ClientFacade.class);
setChildBundleName( NotificationPlugin.RESOURCE_FILE );
if ( !context.has( MailToUserInterface.class ))
{
getLogger().error("Could not start notification service, because Mail Plugin not activated. Check for mail plugin activation or errors.");
return;
}
mailToUserInterface = context.lookup( MailToUserInterface.class );
mailQueue = context.lookup( CommandScheduler.class);
clientFacade.addAllocationChangedListener(this);
getLogger().info("NotificationServer Plugin started");
}
public void changed(AllocationChangeEvent[] changeEvents) {
try {
getLogger().debug("Mail check triggered") ;
User[] users = clientFacade.getUsers();
List<AllocationMail> mailList = new ArrayList<AllocationMail>();
for ( int i=0;i< users.length;i++) {
User user = users[i];
if(user.getEmail().trim().length() == 0)
continue;
Preferences preferences = clientFacade.getPreferences(user);
Map<String,Allocatable> allocatableMap = null ;
if (preferences != null && preferences.getEntry(NotificationPlugin.ALLOCATIONLISTENERS_CONFIG)!= null ) {
allocatableMap = preferences.getEntry(NotificationPlugin.ALLOCATIONLISTENERS_CONFIG);
}else {
continue;
}
if ( allocatableMap != null && allocatableMap.size()> 0)
{
boolean notifyIfOwner = preferences.getEntryAsBoolean(NotificationPlugin.NOTIFY_IF_OWNER_CONFIG, false);
AllocationMail mail = getAllocationMail( new HashSet<Allocatable>(allocatableMap.values()), changeEvents, preferences.getOwner(),notifyIfOwner);
if (mail != null) {
mailList.add(mail);
}
}
}
if(!mailList.isEmpty()) {
MailCommand mailCommand = new MailCommand(mailList);
mailQueue.schedule(mailCommand,0);
}
} catch (RaplaException ex) {
getLogger().error("Can't trigger notification service." + ex.getMessage(),ex);
}
}
AllocationMail getAllocationMail(Collection<Allocatable> allocatables, AllocationChangeEvent[] changeEvents, User owner,boolean notifyIfOwner) throws RaplaException {
HashMap<Reservation,List<AllocationChangeEvent>> reservationMap = null;
HashSet<Allocatable> changedAllocatables = null;
for ( int i = 0; i< changeEvents.length; i++) {
if (reservationMap == null)
reservationMap = new HashMap<Reservation,List<AllocationChangeEvent>>(4);
AllocationChangeEvent event = changeEvents[i];
Reservation reservation = event.getNewReservation();
Allocatable allocatable = event.getAllocatable();
if (!allocatables.contains(allocatable))
continue;
if (!notifyIfOwner && owner.equals(reservation.getOwner()))
continue;
List<AllocationChangeEvent> eventList = reservationMap.get(reservation);
if (eventList == null) {
eventList = new ArrayList<AllocationChangeEvent>(3);
reservationMap.put(reservation,eventList);
}
if ( changedAllocatables == null)
{
changedAllocatables = new HashSet<Allocatable>();
}
changedAllocatables.add(allocatable);
eventList.add(event);
}
if ( reservationMap == null || changedAllocatables == null) {
return null;
}
Set<Reservation> keySet = reservationMap.keySet();
// Check if we have any notifications.
if (keySet.size() == 0)
return null;
AllocationMail mail = new AllocationMail();
StringBuffer buf = new StringBuffer();
//buf.append(getString("mail_body") + "\n");
for (Reservation reservation:keySet) {
List<AllocationChangeEvent> eventList = reservationMap.get(reservation);
String eventBlock = printEvents(reservation,eventList);
buf.append( eventBlock );
buf.append("\n\n");
}
I18nBundle i18n = getI18n();
String raplaTitle = getQuery().getSystemPreferences().getEntryAsString(RaplaMainContainer.TITLE, getString("rapla.title"));
buf.append(i18n.format("disclaimer_1", raplaTitle));
StringBuffer allocatableNames = new StringBuffer();
for (Allocatable alloc: changedAllocatables) {
if ( allocatableNames.length() > 0)
{
allocatableNames.append(", ");
}
allocatableNames.append(alloc.getName(getLocale()));
}
String allocatablesString = allocatableNames.toString();
buf.append(i18n.format("disclaimer_2", allocatablesString));
mail.subject = i18n.format("mail_subject",allocatablesString);
mail.body = buf.toString();
mail.recipient = owner.getUsername();
return mail;
}
private String printEvents(Reservation reservation,List<AllocationChangeEvent> eventList) {
StringBuilder buf =new StringBuilder();
buf.append("\n");
buf.append("-----------");
buf.append(getString("changes"));
buf.append("-----------");
buf.append("\n");
buf.append("\n");
buf.append(getString("reservation"));
buf.append(": ");
buf.append(reservation.getName(getLocale()));
buf.append("\n");
buf.append("\n");
Iterator<AllocationChangeEvent> it = eventList.iterator();
boolean removed = true;
boolean changed = false;
// StringBuilder changes = new StringBuilder();
while (it.hasNext()) {
AllocationChangeEvent event = it.next();
if (!event.getType().equals( AllocationChangeEvent.REMOVE ))
removed = false;
buf.append(getI18n().format("appointment." + event.getType()
,event.getAllocatable().getName(getLocale()))
);
// changes.append("[" + event.getAllocatable().getName(getLocale()) + "]");
// if(it.hasNext())
// changes.append(", ");
if (!event.getType().equals(AllocationChangeEvent.ADD )) {
printAppointment (buf, event.getOldAppointment() );
}
if (event.getType().equals( AllocationChangeEvent.CHANGE )) {
buf.append(getString("moved_to"));
}
if (!event.getType().equals( AllocationChangeEvent.REMOVE )) {
printAppointment (buf, event.getNewAppointment() );
}
/*
if ( event.getUser() != null) {
buf.append("\n");
buf.append( getI18n().format("modified_by", event.getUser().getUsername() ) );
}
*/
Reservation newReservation = event.getNewReservation();
if ( newReservation != null && changed == false) {
User eventUser = event.getUser();
User lastChangedBy = newReservation.getLastChangedBy();
String name;
if ( lastChangedBy != null)
{
name = lastChangedBy.getName();
}
else if ( eventUser != null)
{
name = eventUser.getName();
}
else
{
name = "Rapla";
}
buf.insert(0, getI18n().format("mail_body", name) + "\n");
changed = true;
}
buf.append("\n");
buf.append("\n");
}
if (removed)
return buf.toString();
buf.append("-----------");
buf.append(getString("complete_reservation"));
buf.append("-----------");
buf.append("\n");
buf.append("\n");
buf.append(getString("reservation.owner"));
buf.append(": ");
buf.append(reservation.getOwner().getUsername());
buf.append(" <");
buf.append(reservation.getOwner().getName());
buf.append(">");
buf.append("\n");
buf.append(getString("reservation_type"));
buf.append(": ");
Classification classification = reservation.getClassification();
buf.append( classification.getType().getName(getLocale()) );
Attribute[] attributes = classification.getAttributes();
for (int i=0; i< attributes.length; i++) {
Object value = classification.getValue(attributes[i]);
if (value == null)
continue;
buf.append("\n");
buf.append(attributes[i].getName(getLocale()));
buf.append(": ");
buf.append(classification.getValueAsString(attributes[i], getLocale()));
}
Allocatable[] resources = reservation.getResources();
if (resources.length>0) {
buf.append("\n");
buf.append( getString("resources"));
buf.append( ": ");
printAllocatables(buf,reservation,resources);
}
Allocatable[] persons = reservation.getPersons();
if (persons.length>0) {
buf.append("\n");
buf.append( getString("persons"));
buf.append( ": ");
printAllocatables(buf,reservation,persons);
}
Appointment[] appointments = reservation.getAppointments();
if (appointments.length>0) {
buf.append("\n");
buf.append("\n");
buf.append( getString("appointments"));
buf.append( ": ");
buf.append("\n");
}
for (int i = 0;i<appointments.length;i++) {
printAppointment(buf, appointments[i]);
}
return buf.toString();
}
private void printAppointment(StringBuilder buf, Appointment app) {
buf.append("\n");
buf.append(getAppointmentFormater().getSummary(app));
buf.append("\n");
Repeating repeating = app.getRepeating();
if ( repeating != null ) {
buf.append(getAppointmentFormater().getSummary(app.getRepeating()));
buf.append("\n");
if ( repeating.hasExceptions() ) {
String exceptionString =
getString("appointment.exceptions") + ": " + repeating.getExceptions().length ;
buf.append(exceptionString);
buf.append("\n");
}
}
}
private String printAllocatables(StringBuilder buf
,Reservation reservation
,Allocatable[] allocatables) {
for (int i = 0;i<allocatables.length;i++) {
Allocatable allocatable = allocatables[i];
buf.append(allocatable.getName( getLocale()));
printRestriction(buf,reservation, allocatable);
if (i<allocatables.length-1) {
buf.append (",");
}
}
return buf.toString();
}
private void printRestriction(StringBuilder buf
,Reservation reservation
, Allocatable allocatable) {
Appointment[] restriction = reservation.getRestriction(allocatable);
if ( restriction.length == 0 )
return;
buf.append(" (");
for (int i = 0; i < restriction.length ; i++) {
if (i >0)
buf.append(", ");
buf.append( getAppointmentFormater().getShortSummary( restriction[i]) );
}
buf.append(")");
}
class AllocationMail {
String recipient;
String subject;
String body;
public String toString() {
return "TO Username: " + recipient + "\n"
+ "Subject: " + subject + "\n"
+ body;
}
}
final class MailCommand implements Command {
List<AllocationMail> mailList;
public MailCommand(List<AllocationMail> mailList) {
this.mailList = mailList;
}
public void execute() {
Iterator<AllocationMail> it = mailList.iterator();
while (it.hasNext()) {
AllocationMail mail = it.next();
if (getLogger().isDebugEnabled())
getLogger().debug("Sending mail " + mail.toString());
getLogger().info("AllocationChange. Sending mail to " + mail.recipient);
try {
mailToUserInterface.sendMail(mail.recipient, mail.subject, mail.body );
getLogger().info("AllocationChange. Mail sent.");
} catch (RaplaException ex) {
getLogger().error("Could not send mail to " + mail.recipient + " Cause: " + ex.getMessage(), ex);
}
}
}
}
} | 04900db4-rob | src/org/rapla/plugin/notification/server/NotificationService.java | Java | gpl3 | 15,642 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.notification;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.entities.domain.Allocatable;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.TypedComponentRole;
/** Users can subscribe for allocation change notifications for selected resources or persons.*/
public class NotificationPlugin implements PluginDescriptor<ClientServiceContainer>
{
public static final TypedComponentRole<I18nBundle> RESOURCE_FILE = new TypedComponentRole<I18nBundle>(NotificationPlugin.class.getPackage().getName() + ".NotificationResources");
public static final boolean ENABLE_BY_DEFAULT = false;
public final static TypedComponentRole<Boolean> NOTIFY_IF_OWNER_CONFIG = new TypedComponentRole<Boolean>("org.rapla.plugin.notification.notify_if_owner");
public final static TypedComponentRole<RaplaMap<Allocatable>> ALLOCATIONLISTENERS_CONFIG = new TypedComponentRole<RaplaMap<Allocatable>>("org.rapla.plugin.notification.allocationlisteners");
public void provideServices(ClientServiceContainer container, Configuration config) {
if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig( RESOURCE_FILE.getId() ) );
container.addContainerProvidedComponent( RaplaClientExtensionPoints.USER_OPTION_PANEL_EXTENSION, NotificationOption.class);
}
}
| 04900db4-rob | src/org/rapla/plugin/notification/NotificationPlugin.java | Java | gpl3 | 2,659 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.notification;
import java.util.Collection;
import java.util.Locale;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.entities.domain.Allocatable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.TreeAllocatableSelection;
public class NotificationOption extends RaplaGUIComponent implements OptionPanel {
JPanel content= new JPanel();
JCheckBox notifyIfOwnerCheckBox;
TreeAllocatableSelection selection;
Preferences preferences;
public NotificationOption(RaplaContext sm) {
super( sm);
setChildBundleName( NotificationPlugin.RESOURCE_FILE);
selection = new TreeAllocatableSelection(sm);
selection.setAddDialogTitle(getString("subscribe_notification"));
double[][] sizes = new double[][] {
{5,TableLayout.FILL,5}
,{TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.FILL}
};
TableLayout tableLayout = new TableLayout(sizes);
content.setLayout(tableLayout);
content.add(new JLabel(getStringAsHTML("notification.option.description")), "1,0");
notifyIfOwnerCheckBox = new JCheckBox();
content.add(notifyIfOwnerCheckBox, "1,2");
notifyIfOwnerCheckBox.setText(getStringAsHTML("notify_if_owner"));
content.add(selection.getComponent(), "1,4");
}
public JComponent getComponent() {
return content;
}
public String getName(Locale locale) {
return getString("notification_options");
}
public void show() throws RaplaException {
boolean notify = preferences.getEntryAsBoolean( NotificationPlugin.NOTIFY_IF_OWNER_CONFIG, false);
notifyIfOwnerCheckBox.setEnabled( false );
notifyIfOwnerCheckBox.setSelected(notify);
notifyIfOwnerCheckBox.setEnabled( true );
RaplaMap<Allocatable> raplaEntityList = preferences.getEntry( NotificationPlugin.ALLOCATIONLISTENERS_CONFIG );
if ( raplaEntityList != null ){
selection.setAllocatables(raplaEntityList.values());
}
}
public void setPreferences(Preferences preferences) {
this.preferences = preferences;
}
public void commit() {
preferences.putEntry( NotificationPlugin.NOTIFY_IF_OWNER_CONFIG, notifyIfOwnerCheckBox.isSelected());
Collection<Allocatable> allocatables = selection.getAllocatables();
preferences.putEntry( NotificationPlugin.ALLOCATIONLISTENERS_CONFIG ,getModification().newRaplaMap( allocatables ));
}
}
| 04900db4-rob | src/org/rapla/plugin/notification/NotificationOption.java | Java | gpl3 | 3,850 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.monthview;
import javax.swing.Icon;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.SwingCalendarView;
import org.rapla.gui.SwingViewFactory;
import org.rapla.gui.images.Images;
public class MonthViewFactory extends RaplaComponent implements SwingViewFactory
{
public MonthViewFactory( RaplaContext context )
{
super( context );
}
public final static String MONTH_VIEW = "month";
public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException
{
return new SwingMonthCalendar( context, model, editable);
}
public String getViewId()
{
return MONTH_VIEW;
}
public String getName()
{
return getString(MONTH_VIEW);
}
Icon icon;
public Icon getIcon()
{
if ( icon == null) {
icon = Images.getIcon("/org/rapla/plugin/monthview/images/month.png");
}
return icon;
}
public String getMenuSortKey() {
return "C";
}
}
| 04900db4-rob | src/org/rapla/plugin/monthview/MonthViewFactory.java | Java | gpl3 | 2,129 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.monthview;
import java.awt.Color;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import javax.swing.JComponent;
import org.rapla.components.calendar.DateRenderer;
import org.rapla.components.calendar.DateRendererAdapter;
import org.rapla.components.calendar.WeekendHighlightRenderer;
import org.rapla.components.calendarview.GroupStartTimesStrategy;
import org.rapla.components.calendarview.swing.AbstractSwingCalendar;
import org.rapla.components.calendarview.swing.SmallDaySlot;
import org.rapla.components.calendarview.swing.SwingMonthView;
import org.rapla.components.calendarview.swing.ViewListener;
import org.rapla.components.util.DateTools;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarOptions;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.abstractcalendar.AbstractRaplaSwingCalendar;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.plugin.abstractcalendar.RaplaCalendarViewListener;
public class SwingMonthCalendar extends AbstractRaplaSwingCalendar
{
public SwingMonthCalendar(RaplaContext context,CalendarModel settings, boolean editable) throws RaplaException {
super( context, settings, editable);
}
public static Color DATE_NUMBER_COLOR_HIGHLIGHTED = Color.black;
protected AbstractSwingCalendar createView(boolean editable) {
boolean showScrollPane = editable;
final DateRenderer dateRenderer;
final DateRendererAdapter dateRendererAdapter;
dateRenderer = getService(DateRenderer.class);
dateRendererAdapter = new DateRendererAdapter(dateRenderer, getRaplaLocale().getTimeZone(), getRaplaLocale().getLocale());
final WeekendHighlightRenderer weekdayRenderer = new WeekendHighlightRenderer();
/** renderer for weekdays in month-view */
SwingMonthView monthView = new SwingMonthView( showScrollPane ) {
protected JComponent createSlotHeader(int weekday) {
JComponent component = super.createSlotHeader( weekday );
if (isEditable()) {
component.setOpaque(true);
Color color = weekdayRenderer.getRenderingInfo(weekday, 1, 1, 1).getBackgroundColor();
component.setBackground(color);
}
return component;
}
@Override
protected SmallDaySlot createSmallslot(int pos, Date date) {
String header = "" + (pos + 1);
DateRenderer.RenderingInfo info = dateRendererAdapter.getRenderingInfo(date);
Color color = getNumberColor( date);
Color backgroundColor = null;
String tooltipText = null;
if (info != null) {
backgroundColor = info.getBackgroundColor();
if (info.getForegroundColor() != null) {
color = info.getForegroundColor();
}
tooltipText = info.getTooltipText();
if ( tooltipText != null)
{
// commons not on client lib path
//StringUtils.abbreviate(tooltipText, 15)
// header = tooltipText + " " + (pos+1);
}
}
final SmallDaySlot smallslot = super.createSmallslot(header, color, backgroundColor);
if (tooltipText != null) {
smallslot.setToolTipText(tooltipText);
}
return smallslot;
}
protected Color getNumberColor( Date date )
{
boolean today = DateTools.isSameDay(getQuery().today().getTime(), date.getTime());
if ( today)
{
return DATE_NUMBER_COLOR_HIGHLIGHTED;
}
else
{
return super.getNumberColor( date );
}
}
};
monthView.setDaysInView( 25);
return monthView;
}
protected ViewListener createListener() throws RaplaException {
RaplaCalendarViewListener listener = new RaplaCalendarViewListener(getContext(), model, view.getComponent());
listener.setKeepTime( true);
return listener;
}
protected RaplaBuilder createBuilder() throws RaplaException
{
RaplaBuilder builder = super.createBuilder();
builder.setSmallBlocks( true );
GroupStartTimesStrategy strategy = new GroupStartTimesStrategy( );
builder.setBuildStrategy( strategy );
return builder;
}
protected void configureView() throws RaplaException {
CalendarOptions calendarOptions = getCalendarOptions();
Set<Integer> excludeDays = calendarOptions.getExcludeDays();
view.setExcludeDays( excludeDays );
view.setToDate(model.getSelectedDate());
}
public int getIncrementSize()
{
return Calendar.MONTH;
}
}
| 04900db4-rob | src/org/rapla/plugin/monthview/SwingMonthCalendar.java | Java | gpl3 | 6,014 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.monthview.server;
import java.util.Calendar;
import java.util.Set;
import org.rapla.components.calendarview.GroupStartTimesStrategy;
import org.rapla.components.calendarview.html.AbstractHTMLView;
import org.rapla.components.calendarview.html.HTMLMonthView;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarOptions;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.plugin.abstractcalendar.server.AbstractHTMLCalendarPage;
public class HTMLMonthViewPage extends AbstractHTMLCalendarPage
{
public HTMLMonthViewPage( RaplaContext context, CalendarModel calendarModel )
{
super( context, calendarModel );
}
protected AbstractHTMLView createCalendarView() {
HTMLMonthView monthView = new HTMLMonthView();
return monthView;
}
protected RaplaBuilder createBuilder() throws RaplaException {
RaplaBuilder builder = super.createBuilder();
builder.setSmallBlocks( true );
GroupStartTimesStrategy strategy = new GroupStartTimesStrategy( );
builder.setBuildStrategy( strategy );
return builder;
}
protected int getIncrementSize() {
return Calendar.MONTH;
}
@Override
protected void configureView() throws RaplaException {
CalendarOptions opt = getCalendarOptions();
Set<Integer> excludeDays = opt.getExcludeDays();
view.setExcludeDays( excludeDays );
view.setDaysInView( 30);
}
}
| 04900db4-rob | src/org/rapla/plugin/monthview/server/HTMLMonthViewPage.java | Java | gpl3 | 2,492 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.monthview.server;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.server.RaplaServerExtensionPoints;
import org.rapla.server.ServerServiceContainer;
public class MonthViewServerPlugin implements PluginDescriptor<ServerServiceContainer>
{
public void provideServices(ServerServiceContainer container, Configuration config) {
if ( !config.getAttributeAsBoolean("enabled", true))
return;
container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,HTMLMonthViewFactory.class);
}
}
| 04900db4-rob | src/org/rapla/plugin/monthview/server/MonthViewServerPlugin.java | Java | gpl3 | 1,571 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.monthview.server;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory;
import org.rapla.servletpages.RaplaPageGenerator;
public class HTMLMonthViewFactory extends RaplaComponent implements HTMLViewFactory
{
public HTMLMonthViewFactory( RaplaContext context )
{
super( context );
}
public final static String MONTH_VIEW = "month";
public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) throws RaplaException
{
return new HTMLMonthViewPage( context, model);
}
public String getViewId()
{
return MONTH_VIEW;
}
public String getName()
{
return getString(MONTH_VIEW);
}
}
| 04900db4-rob | src/org/rapla/plugin/monthview/server/HTMLMonthViewFactory.java | Java | gpl3 | 1,826 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.monthview;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
public class MonthViewPlugin implements PluginDescriptor<ClientServiceContainer>
{
public static final boolean ENABLE_BY_DEFAULT = true;
public void provideServices(ClientServiceContainer container, Configuration config) {
if ( !config.getAttributeAsBoolean("enabled",ENABLE_BY_DEFAULT))
return;
container.addContainerProvidedComponent(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,MonthViewFactory.class);
}
}
| 04900db4-rob | src/org/rapla/plugin/monthview/MonthViewPlugin.java | Java | gpl3 | 1,618 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.jndi;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.entities.Category;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.TypedComponentRole;
import org.rapla.plugin.jndi.internal.JNDIOption;
public class JNDIPlugin implements PluginDescriptor<ClientServiceContainer> {
public final static boolean ENABLE_BY_DEFAULT = false;
public static final String PLUGIN_CLASS = JNDIPlugin.class.getName();
public static final String PLUGIN_NAME = "Ldap or other JNDI Authentication";
public static final TypedComponentRole<RaplaConfiguration> JNDISERVER_CONFIG = new TypedComponentRole<RaplaConfiguration>("org.rapla.plugin.jndi.server.config");
public final static TypedComponentRole<RaplaMap<Category>> USERGROUP_CONFIG = new TypedComponentRole<RaplaMap<Category>>("org.rapla.plugin.jndi.newusergroups");
public void provideServices(ClientServiceContainer container, Configuration config)
{
container.addContainerProvidedComponent( RaplaClientExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION,JNDIOption.class);
if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) )
return;
}
}
| 04900db4-rob | src/org/rapla/plugin/jndi/JNDIPlugin.java | Java | gpl3 | 2,361 |
package org.rapla.plugin.jndi.internal;
import javax.jws.WebService;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.RaplaException;
@WebService
public interface JNDIConfig
{
public void test(DefaultConfiguration config,String username,String password) throws RaplaException;
public DefaultConfiguration getConfig() throws RaplaException;
}
| 04900db4-rob | src/org/rapla/plugin/jndi/internal/JNDIConfig.java | Java | gpl3 | 381 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.jndi.internal;
import java.awt.GridLayout;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.toolkit.RaplaWidget;
public class PasswordEnterUI extends RaplaGUIComponent
implements
RaplaWidget
{
JPanel panel = new JPanel();
GridLayout gridLayout1 = new GridLayout();
// The Controller for this Dialog
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
JTextField tf1 = new JTextField(10);
JPasswordField tf2 = new JPasswordField(10);
public PasswordEnterUI(RaplaContext sm) {
super( sm);
panel.setLayout(gridLayout1);
gridLayout1.setRows( 2);
gridLayout1.setColumns(2);
gridLayout1.setHgap(10);
gridLayout1.setVgap(10);
panel.add(label1);
panel.add(tf1);
panel.add(label2);
panel.add(tf2);
label1.setText(getString("username") + ":");
label2.setText(getString("password") + ":");
}
public JComponent getComponent() {
return panel;
}
public String getUsername() {
return tf1.getText();
}
public char[] getNewPassword() {
return tf2.getPassword();
}
}
| 04900db4-rob | src/org/rapla/plugin/jndi/internal/PasswordEnterUI.java | Java | gpl3 | 2,340 |
package org.rapla.plugin.jndi.internal;
public interface JNDIConf {
public static final String USER_BASE = "userBase";
public static final String USER_SEARCH = "userSearch";
public static final String USER_CN = "userCn";
public static final String USER_MAIL = "userMail";
public static final String USER_PASSWORD = "userPassword";
public static final String DIGEST = "digest";
public static final String CONTEXT_FACTORY = "contextFactory";
public static final String CONNECTION_URL = "connectionURL";
public static final String CONNECTION_PASSWORD = "connectionPassword";
public static final String CONNECTION_NAME = "connectionName";
}
| 04900db4-rob | src/org/rapla/plugin/jndi/internal/JNDIConf.java | Java | gpl3 | 694 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.jndi.internal;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.Category;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.gui.DefaultPluginOption;
import org.rapla.gui.internal.edit.fields.GroupListField;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.plugin.jndi.JNDIPlugin;
import org.rapla.storage.RaplaSecurityException;
public class JNDIOption extends DefaultPluginOption implements JNDIConf {
TableLayout tableLayout;
JPanel content;
JTextField digest;
JTextField connectionName;
JPasswordField connectionPassword;
JTextField connectionURL;
JTextField contextFactory;
JTextField userPassword;
JTextField userMail;
JTextField userCn;
JTextField userSearch;
JTextField userBase;
GroupListField groupField;
JNDIConfig configService;
public JNDIOption(RaplaContext sm,JNDIConfig config) {
super(sm);
this.configService = config;
}
protected JPanel createPanel() throws RaplaException {
digest = newTextField();
connectionName = newTextField();
connectionPassword = new JPasswordField();
groupField = new GroupListField( getContext());
JPanel passwordPanel = new JPanel();
passwordPanel.setLayout( new BorderLayout());
passwordPanel.add( connectionPassword, BorderLayout.CENTER);
final JCheckBox showPassword = new JCheckBox("show password");
passwordPanel.add( showPassword, BorderLayout.EAST);
showPassword.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean show = showPassword.isSelected();
connectionPassword.setEchoChar( show ? ((char) 0): '*');
}
});
addCopyPaste( connectionPassword );
connectionURL = newTextField();
contextFactory= newTextField();
userPassword = newTextField();
userMail = newTextField();
userCn = newTextField();
userSearch = newTextField();
userBase = newTextField();
JPanel panel = super.createPanel();
content = new JPanel();
tableLayout = new TableLayout();
tableLayout.insertColumn( 0, TableLayout.PREFERRED);
tableLayout.insertColumn( 1, 5);
tableLayout.insertColumn( 2, TableLayout.FILL);
tableLayout.insertColumn( 3, 5);
content.setLayout(tableLayout);
tableLayout.insertRow( 0, TableLayout.PREFERRED);
content.add( new JLabel("WARNING! Rapla standard authentification will be used if ldap authentification fails."), "0,0,2,0");
addRow(CONNECTION_NAME, connectionName);
addRow(CONNECTION_PASSWORD, passwordPanel );
addRow(CONNECTION_URL, connectionURL );
addRow(CONTEXT_FACTORY, contextFactory);
addRow(DIGEST, digest);
addRow(USER_PASSWORD, userPassword );
addRow(USER_MAIL, userMail );
addRow(USER_CN, userCn );
addRow(USER_SEARCH, userSearch );
addRow(USER_BASE, userBase );
JButton testButton = new JButton("Test access");
addRow("TestAccess", testButton );
groupField.mapFrom( Collections.singletonList(getUser()));
addRow("Default Groups", groupField.getComponent() );
testButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e) {
try
{
DefaultConfiguration conf = new DefaultConfiguration("test");
addChildren(conf);
String username = "admin";
String password ="";
{
PasswordEnterUI testUser = new PasswordEnterUI(getContext());
DialogUI dialog =DialogUI.create( getContext(), getComponent(), true,testUser.getComponent(),new String[] {"test","abort"});
dialog.setTitle("Please enter valid user!");
dialog.start();
username = testUser.getUsername();
password = new String(testUser.getNewPassword());
int index=dialog.getSelectedIndex();
if ( index > 0)
{
return;
}
}
configService.test(conf,username,password);
{
DialogUI dialog =DialogUI.create( getContext(), getComponent(), true, "JNDI","JNDI Authentification successfull");
dialog.start();
}
}
catch (RaplaSecurityException ex)
{
showWarning(ex.getMessage(), getComponent());
}
catch (Exception ex)
{
showException(ex, getComponent());
}
}
});
panel.add( content, BorderLayout.CENTER);
return panel;
}
private JTextField newTextField() {
final JTextField jTextField = new JTextField();
addCopyPaste( jTextField);
return jTextField;
}
private void addRow(String title, JComponent component) {
int row = tableLayout.getNumRow();
tableLayout.insertRow( row, TableLayout.PREFERRED);
content.add(new JLabel(title), "0," + row);
content.add( component, "2," + row);
tableLayout.insertRow( row + 1, 5);
}
protected void addChildren( DefaultConfiguration newConfig) {
setAttribute(newConfig,CONNECTION_NAME, connectionName);
setAttribute(newConfig,CONNECTION_PASSWORD, connectionPassword );
setAttribute(newConfig,CONNECTION_URL, connectionURL );
setAttribute(newConfig,CONTEXT_FACTORY, contextFactory);
setAttribute(newConfig,DIGEST, digest);
setAttribute(newConfig,USER_BASE, userBase );
newConfig.setAttribute( USER_CN, userCn.getText());
newConfig.setAttribute( USER_MAIL, userMail.getText());
newConfig.setAttribute( USER_PASSWORD, userPassword.getText());
setAttribute(newConfig,USER_SEARCH, userSearch );
}
public void setAttribute( DefaultConfiguration newConfig, String attributeName, JTextField text) {
String value = text.getText().trim();
if ( value.length() > 0)
{
newConfig.setAttribute( attributeName, value);
}
}
public void readAttribute( String attributeName, JTextField text) {
readAttribute( attributeName, text, "");
}
public void readAttribute( String attributeName, JTextField text, String defaultValue) {
text.setText(config.getAttribute(attributeName, defaultValue));
}
@Override
protected void readConfig( Configuration config) {
try
{
this.config = configService.getConfig();
}
catch (RaplaException ex)
{
showException(ex, getComponent());
this.config = config;
}
readAttribute("digest", digest);
readAttribute("connectionName", connectionName, "uid=admin,ou=system" );
readAttribute("connectionPassword", connectionPassword, "secret" );
readAttribute("connectionURL", connectionURL, "ldap://localhost:10389");
readAttribute("contextFactory", contextFactory, "com.sun.jndi.ldap.LdapCtxFactory");
readAttribute("userPassword", userPassword,"" );
readAttribute("userMail", userMail,"mail" );
readAttribute("userCn", userCn,"cn" );
readAttribute("userSearch", userSearch,"(uid={0})" );
//uid={0}, ou=Users, dc=example,dc=com
readAttribute("userBase", userBase,"dc=example,dc=com" );
}
public void show() throws RaplaException {
super.show();
RaplaMap<Category> groupList = preferences.getEntry(JNDIPlugin.USERGROUP_CONFIG);
Collection<Category> groups;
if (groupList == null)
{
groups = new ArrayList<Category>();
}
else
{
groups = Arrays.asList(groupList.values().toArray(Category.CATEGORY_ARRAY));
}
this.groupField.mapFromList( groups);
}
public void commit() throws RaplaException {
writePluginConfig(false);
TypedComponentRole<RaplaConfiguration> configEntry = JNDIPlugin.JNDISERVER_CONFIG;
RaplaConfiguration newConfig = new RaplaConfiguration("config" );
addChildren( newConfig );
preferences.putEntry( configEntry,newConfig);
Set<Category> set = new LinkedHashSet<Category>();
this.groupField.mapToList( set);
preferences.putEntry( JNDIPlugin.USERGROUP_CONFIG, getModification().newRaplaMap( set) );
}
/**
* @see org.rapla.gui.DefaultPluginOption#getPluginClass()
*/
public Class<? extends PluginDescriptor<?>> getPluginClass() {
return JNDIPlugin.class;
}
@Override
public String getName(Locale locale) {
return JNDIPlugin.PLUGIN_NAME;
}
}
| 04900db4-rob | src/org/rapla/plugin/jndi/internal/JNDIOption.java | Java | gpl3 | 10,692 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.jndi.server;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.plugin.jndi.JNDIPlugin;
import org.rapla.plugin.jndi.internal.JNDIConfig;
import org.rapla.server.AuthenticationStore;
import org.rapla.server.ServerServiceContainer;
import org.rapla.server.internal.RemoteStorageImpl;
public class JNDIServerPlugin implements PluginDescriptor<ServerServiceContainer> {
public void provideServices(ServerServiceContainer container, Configuration config) throws RaplaContextException
{
container.addRemoteMethodFactory(JNDIConfig.class, RaplaJNDITestOnLocalhost.class);
convertSettings(container.getContext(),config);
if ( !config.getAttributeAsBoolean("enabled", JNDIPlugin.ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( AuthenticationStore.class, JNDIAuthenticationStore.class);
}
private void convertSettings(RaplaContext context,Configuration config) throws RaplaContextException
{
String className = JNDIPlugin.class.getName();
TypedComponentRole<RaplaConfiguration> newConfKey = JNDIPlugin.JNDISERVER_CONFIG;
if ( config.getAttributeNames().length > 2)
{
RemoteStorageImpl.convertToNewPluginConfig(context, className, newConfKey);
}
}
}
| 04900db4-rob | src/org/rapla/plugin/jndi/server/JNDIServerPlugin.java | Java | gpl3 | 2,505 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.jndi.server;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.internal.PreferencesImpl;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.logger.Logger;
import org.rapla.plugin.jndi.JNDIPlugin;
import org.rapla.plugin.jndi.internal.JNDIConfig;
import org.rapla.server.RemoteMethodFactory;
import org.rapla.server.RemoteSession;
import org.rapla.storage.RaplaSecurityException;
public class RaplaJNDITestOnLocalhost extends RaplaComponent implements RemoteMethodFactory<JNDIConfig>
{
public RaplaJNDITestOnLocalhost( RaplaContext context) {
super( context );
}
public JNDIConfig createService(final RemoteSession remoteSession) {
return new JNDIConfig() {
@Override
public void test(DefaultConfiguration config,String username,String password ) throws RaplaException
{
User user = remoteSession.getUser();
if ( !user.isAdmin())
{
throw new RaplaSecurityException("Access only for admin users");
}
Logger logger = getLogger();
JNDIAuthenticationStore testStore = new JNDIAuthenticationStore(getContext(), logger);
testStore.initWithConfig( config);
logger.info("Test of JNDI Plugin started");
boolean authenticate;
if ( password == null || password.equals(""))
{
throw new RaplaException("LDAP Plugin doesnt accept empty passwords.");
}
try {
authenticate = testStore.authenticate(username, password);
} catch (Exception e) {
throw new RaplaException(e);
} finally {
testStore.dispose();
}
if (!authenticate)
{
throw new RaplaSecurityException("Can establish connection but can't authenticate test user " + username);
}
logger.info("Test of JNDI Plugin successfull");
}
@SuppressWarnings("deprecation")
@Override
public DefaultConfiguration getConfig() throws RaplaException {
User user = remoteSession.getUser();
if ( !user.isAdmin())
{
throw new RaplaSecurityException("Access only for admin users");
}
Preferences preferences = getQuery().getSystemPreferences();
DefaultConfiguration config = preferences.getEntry( JNDIPlugin.JNDISERVER_CONFIG);
if ( config == null)
{
config = (DefaultConfiguration) ((PreferencesImpl)preferences).getOldPluginConfig(JNDIPlugin.class.getName());
}
return config;
}
};
}
}
| 04900db4-rob | src/org/rapla/plugin/jndi/server/RaplaJNDITestOnLocalhost.java | Java | gpl3 | 4,353 |
/*
* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.rapla.plugin.jndi.server;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Map;
import java.util.TreeMap;
import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.PartialResultException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.rapla.components.util.Tools;
import org.rapla.entities.Category;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.facade.ClientFacade;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.Disposable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.logger.ConsoleLogger;
import org.rapla.framework.logger.Logger;
import org.rapla.plugin.jndi.JNDIPlugin;
import org.rapla.plugin.jndi.internal.JNDIConf;
import org.rapla.server.AuthenticationStore;
import org.rapla.storage.RaplaSecurityException;
/**
* This Plugin is based on the jakarta.apache.org/tomcat JNDI Realm
* and enables the authentication of a rapla user against a JNDI-Directory.
* The most commen usecase is LDAP-Authentication, but ActiveDirectory
* may be possible, too.
* <li>Each user element has a distinguished name that can be formed by
* substituting the presented username into a pattern configured by the
* <code>userPattern</code> property.</li>
* </li>
*
* <li>The user may be authenticated by binding to the directory with the
* username and password presented. This method is used when the
* <code>userPassword</code> property is not specified.</li>
*
* <li>The user may be authenticated by retrieving the value of an attribute
* from the directory and comparing it explicitly with the value presented
* by the user. This method is used when the <code>userPassword</code>
* property is specified, in which case:
* <ul>
* <li>The element for this user must contain an attribute named by the
* <code>userPassword</code> property.
* <li>The value of the user password attribute is either a cleartext
* String, or the result of passing a cleartext String through the
* <code>digest()</code> method (using the standard digest
* support included in <code>RealmBase</code>).
* <li>The user is considered to be authenticated if the presented
* credentials (after being passed through
* <code>digest()</code>) are equal to the retrieved value
* for the user password attribute.</li>
* </ul></li>
*
*/
public class JNDIAuthenticationStore implements AuthenticationStore,Disposable,JNDIConf {
// ----------------------------------------------------- Instance Variables
/**
* Digest algorithm used in storing passwords in a non-plaintext format.
* Valid values are those accepted for the algorithm name by the
* MessageDigest class, or <code>null</code> if no digesting should
* be performed.
*/
protected String digest = null;
/**
* The MessageDigest object for digesting user credentials (passwords).
*/
protected MessageDigest md = null;
/**
* The connection username for the server we will contact.
*/
protected String connectionName = null;
/**
* The connection password for the server we will contact.
*/
protected String connectionPassword = null;
/**
* The connection URL for the server we will contact.
*/
protected String connectionURL = null;
/**
* The directory context linking us to our directory server.
*/
protected DirContext context = null;
/**
* The JNDI context factory used to acquire our InitialContext. By
* default, assumes use of an LDAP server using the standard JNDI LDAP
* provider.
*/
protected String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
/**
* The attribute name used to retrieve the user password.
*/
protected String userPassword = null;
/**
* The attribute name used to retrieve the user email.
*/
protected String userMail = null;
/**
* The attribute name used to retrieve the complete name of the user.
*/
protected String userCn = null;
/**
* The base element for user searches.
*/
protected String userBase = "";
/**
* The message format used to search for a user, with "{0}" marking
* the spot where the username goes.
*/
protected String userSearch = null;
/**
* The MessageFormat object associated with the current
* <code>userSearch</code>.
*/
protected MessageFormat userSearchFormat = null;
/**
* The number of connection attempts. If greater than zero we use the
* alternate url.
*/
protected int connectionAttempt = 0;
RaplaContext rapla_context;
Logger logger;
public JNDIAuthenticationStore(RaplaContext context,Logger logger) throws RaplaException {
this.logger = logger.getChildLogger("ldap");
this.rapla_context = context;
Preferences preferences = context.lookup(ClientFacade.class).getSystemPreferences();
DefaultConfiguration config = preferences.getEntry( JNDIPlugin.JNDISERVER_CONFIG, new RaplaConfiguration());
initWithConfig(config);
/*
setDigest( config.getAttribute( DIGEST, null ) );
setConnectionName( config.getAttribute( CONNECTION_NAME ) );
setConnectionPassword( config.getAttribute( CONNECTION_PASSWORD, null) );
setConnectionURL( config.getAttribute( CONNECTION_URL ) );
setContextFactory( config.getAttribute( CONTEXT_FACTORY, contextFactory ) );
setUserPassword( config.getAttribute( USER_PASSWORD, null ) );
setUserMail( config.getAttribute( USER_MAIL, null ) );
setUserCn( config.getAttribute( USER_CN, null ) );
setUserSearch( config.getAttribute( USER_SEARCH) );
setUserBase( config.getAttribute( USER_BASE) );
*/
}
public void initWithConfig(Configuration config) throws RaplaException
{
Map<String,String> map = generateMap(config);
initWithMap(map);
}
public JNDIAuthenticationStore() {
this.logger = new ConsoleLogger();
}
private JNDIAuthenticationStore(Map<String,String> config, Logger logger) throws RaplaException
{
this.logger = logger.getChildLogger("ldap");
initWithMap(config);
}
public Logger getLogger()
{
return logger;
}
static public Map<String,String> generateMap(Configuration config) {
String[] attributes = config.getAttributeNames();
Map<String,String> map = new TreeMap<String,String>();
for (int i=0;i<attributes.length;i++)
{
map.put( attributes[i], config.getAttribute(attributes[i], null));
}
return map;
}
public static JNDIAuthenticationStore createJNDIAuthenticationStore(
Map<String,String> config, Logger logger) throws RaplaException {
return new JNDIAuthenticationStore(config, logger);
}
private void initWithMap(Map<String,String> config) throws RaplaException {
try {
setDigest( getAttribute( config,DIGEST, null ) );
} catch (NoSuchAlgorithmException e) {
throw new RaplaException( e.getMessage());
}
setConnectionURL( getAttribute( config,CONNECTION_URL ) );
setUserBase( getAttribute( config,USER_BASE) );
setConnectionName( getAttribute(config, CONNECTION_NAME, null) );
setConnectionPassword( getAttribute( config,CONNECTION_PASSWORD, null) );
setContextFactory( getAttribute( config,CONTEXT_FACTORY, contextFactory ) );
setUserPassword( getAttribute( config,USER_PASSWORD, null ) );
setUserMail( getAttribute( config,USER_MAIL, null ) );
setUserCn( getAttribute( config,USER_CN, null ) );
setUserSearch( getAttribute( config,USER_SEARCH, null) );
}
private String getAttribute(Map<String,String> config, String key, String defaultValue) {
String object = config.get(key);
if (object == null)
{
return defaultValue;
}
return object;
}
private String getAttribute(Map<String,String> config, String key) throws RaplaException{
String result = getAttribute(config, key, null);
if ( result == null)
{
throw new RaplaException("Can't find provided configuration entry for key " + key);
}
return result;
}
private void log( String message,Exception ex ) {
getLogger().error ( message, ex );
}
private void log( String message ) {
getLogger().debug ( message );
}
public String getName() {
return ("JNDIAuthenticationStore with contectFactory " + contextFactory );
}
/**
* Set the digest algorithm used for storing credentials.
*
* @param digest The new digest algorithm
* @throws NoSuchAlgorithmException
*/
public void setDigest(String digest) throws NoSuchAlgorithmException {
this.digest = digest;
if (digest != null) {
md = MessageDigest.getInstance(digest);
}
}
public boolean isCreateUserEnabled() {
return true;
}
/** queries the user and initialize the name and the email field. */
public boolean initUser( org.rapla.entities.User user, String username, String password, Category userGroupCategory)
throws RaplaException
{
boolean modified = false;
JNDIUser intUser = authenticateUser( username, password );
if ( intUser == null )
throw new RaplaSecurityException("Can't authenticate user " + username);
String oldUsername = user.getUsername();
if ( oldUsername == null || !oldUsername.equals( username ) ) {
user.setUsername( username );
modified = true;
}
String oldEmail = user.getEmail();
if ( intUser.mail != null && (oldEmail == null || !oldEmail.equals( intUser.mail ))) {
user.setEmail( intUser.mail );
modified = true;
}
String oldName = user.getName();
if ( intUser.cn != null && (oldName == null || !oldName.equals( intUser.cn )) ) {
user.setName( intUser.cn );
modified = true;
}
/*
* Adds the default user groups if the user doesnt already have a group*/
if (rapla_context != null && user.getGroups().length == 0)
{
ClientFacade facade = rapla_context.lookup(ClientFacade.class);
Preferences preferences = facade.getSystemPreferences();
RaplaMap<Category> groupList = preferences.getEntry(JNDIPlugin.USERGROUP_CONFIG);
Collection<Category> groups;
if (groupList == null)
{
groups = new ArrayList<Category>();
}
else
{
groups = Arrays.asList(groupList.values().toArray(Category.CATEGORY_ARRAY));
}
for (Category group:groups)
{
user.addGroup( group);
}
modified = true;
}
return modified;
}
/**
* Set the connection username for this Realm.
*
* @param connectionName The new connection username
*/
public void setConnectionName(String connectionName) {
this.connectionName = connectionName;
}
/**
* Set the connection password for this Realm.
*
* @param connectionPassword The new connection password
*/
public void setConnectionPassword(String connectionPassword) {
this.connectionPassword = connectionPassword;
}
/**
* Set the connection URL for this Realm.
*
* @param connectionURL The new connection URL
*/
public void setConnectionURL(String connectionURL) {
this.connectionURL = connectionURL;
}
/**
* Set the JNDI context factory for this Realm.
*
* @param contextFactory The new context factory
*/
public void setContextFactory(String contextFactory) {
this.contextFactory = contextFactory;
}
/**
* Set the password attribute used to retrieve the user password.
*
* @param userPassword The new password attribute
*/
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
/**
* Set the mail attribute used to retrieve the user mail-address.
*/
public void setUserMail(String userMail) {
this.userMail = userMail;
}
/**
* Set the password attribute used to retrieve the users completeName.
*/
public void setUserCn(String userCn) {
this.userCn = userCn;
}
/**
* Set the base element for user searches.
*
* @param userBase The new base element
*/
public void setUserBase(String userBase) {
this.userBase = userBase;
}
/**
* Set the message format pattern for selecting users in this Realm.
*
* @param userSearch The new user search pattern
*/
public void setUserSearch(String userSearch) {
this.userSearch = userSearch;
if (userSearch == null)
userSearchFormat = null;
else
userSearchFormat = new MessageFormat(userSearch);
}
// ---------------------------------------------------------- Realm Methods
public boolean authenticate(String username, String credentials) throws RaplaException {
if ( credentials == null || credentials.length() == 0)
{
getLogger().warn("Empty passwords are not allowed for ldap authentification.");
return false;
}
return authenticateUser( username, credentials ) != null;
}
/**
* Return the Principal associated with the specified username and
* credentials, if there is one; otherwise return <code>null</code>.
*
* If there are any errors with the JDBC connection, executing
* the query or anything we return null (don't authenticate). This
* event is also logged, and the connection will be closed so that
* a subsequent request will automatically re-open it.
*
* @param username Username of the Principal to look up
* @param credentials Password or other credentials to use in
* authenticating this username
* @throws RaplaException
*/
private JNDIUser authenticateUser(String username, String credentials) throws RaplaException {
DirContext context = null;
JNDIUser user = null;
try {
// Ensure that we have a directory context available
context = open();
// Occassionally the directory context will timeout. Try one more
// time before giving up.
try {
// Authenticate the specified username if possible
user = authenticate(context, username, credentials);
} catch (CommunicationException e) {
// If contains the work closed. Then assume socket is closed.
// If message is null, assume the worst and allow the
// connection to be closed.
if (e.getMessage()!=null &&
e.getMessage().indexOf("closed") < 0)
throw(e);
// log the exception so we know it's there.
log("jndiRealm.exception", e);
// close the connection so we know it will be reopened.
if (context != null)
close(context);
// open a new directory context.
context = open();
// Try the authentication again.
user = authenticate(context, username, credentials);
}
// Return the authenticated Principal (if any)
return user;
} catch (NamingException e) {
// Log the problem for posterity
throw new RaplaException(e.getClass() + " " +e.getMessage(), e);
}
finally
{
// Close the connection so that it gets reopened next time
if (context != null)
close(context);
}
}
// -------------------------------------------------------- Package Methods
// ------------------------------------------------------ Protected Methods
/**
* Return the Principal associated with the specified username and
* credentials, if there is one; otherwise return <code>null</code>.
*
* @param context The directory context
* @param username Username of the Principal to look up
* @param credentials Password or other credentials to use in
* authenticating this username
*
* @exception NamingException if a directory server error occurs
*/
protected JNDIUser authenticate(DirContext context,
String username,
String credentials)
throws NamingException {
if (username == null || username.equals("") || credentials == null || credentials.equals(""))
return (null);
if ( userBase.contains("{0}"))
{
String userPath = userBase.replaceAll("\\{0\\}", username);
JNDIUser user = getUserNew( context, userPath, username,credentials);
return user;
}
// Retrieve user information
JNDIUser user = getUser(context, username);
if (user != null && checkCredentials(context, user, credentials))
return user;
return null;
}
private JNDIUser getUserNew(DirContext context, String userPath,
String username, String credentials) throws NamingException
{
// Validate the credentials specified by the user
if ( getLogger().isDebugEnabled() ) {
log(" validating credentials by binding as the user");
}
// Set up security environment to bind as the user
context.addToEnvironment(Context.SECURITY_PRINCIPAL, userPath);
context.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
try {
if ( getLogger().isDebugEnabled() ) {
log(" binding as " + userPath);
}
//Attributes attr =
String attributeName = userPath;
Attributes attributes = context.getAttributes(attributeName, null);
JNDIUser user = createUser(username, userPath, attributes);
return user;
}
catch (NamingException e) {
if ( getLogger().isDebugEnabled() ) {
log(" bind attempt failed" + e.getMessage());
}
return null;
}
finally
{
context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
}
}
/**
* Return a User object containing information about the user
* with the specified username, if found in the directory;
* otherwise return <code>null</code>.
*
* If the <code>userPassword</code> configuration attribute is
* specified, the value of that attribute is retrieved from the
* user's directory entry. If the <code>userRoleName</code>
* configuration attribute is specified, all values of that
* attribute are retrieved from the directory entry.
*
* @param context The directory context
* @param username Username to be looked up
*
* @exception NamingException if a directory server error occurs
*/
protected JNDIUser getUser(DirContext context, String username)
throws NamingException {
JNDIUser user = null;
// Get attributes to retrieve from user entry
ArrayList<String> list = new ArrayList<String>();
if (userPassword != null)
list.add(userPassword);
if (userMail != null)
list.add(userMail);
if (userCn != null)
list.add(userCn);
String[] attrIds = new String[list.size()];
list.toArray(attrIds);
// Use pattern or search for user entry
user = getUserBySearch(context, username, attrIds);
return user;
}
/**
* Search the directory to return a User object containing
* information about the user with the specified username, if
* found in the directory; otherwise return <code>null</code>.
*
* @param context The directory context
* @param username The username
* @param attrIds String[]containing names of attributes to retrieve.
*
* @exception NamingException if a directory server error occurs
*/
protected JNDIUser getUserBySearch(DirContext context,
String username,
String[] attrIds)
throws NamingException {
if (userSearchFormat == null) {
getLogger().error("no userSearchFormat specied");
return null;
}
// Form the search filter
String filter = userSearchFormat.format(new String[] { username });
// Set up the search controls
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
// Specify the attributes to be retrieved
if (attrIds == null)
attrIds = new String[0];
constraints.setReturningAttributes(attrIds);
if (getLogger().isDebugEnabled()) {
log(" Searching for " + username);
log(" base: " + userBase + " filter: " + filter);
}
//filter = "";
//Attributes attributes = new BasicAttributes(true);
//attributes.put(new BasicAttribute("uid","admin"));
NamingEnumeration<?> results =
//context.search(userBase,attributes);//
context.search(userBase, filter,constraints);
/*
while ( results.hasMore())
{
System.out.println( results.next());
}
*/ // Fail if no entries found
try
{
if (results == null || !results.hasMore()) {
if (getLogger().isDebugEnabled()) {
log(" username not found");
}
return (null);
}
}
catch ( PartialResultException ex)
{
getLogger().info("User "+ username + " not found in jndi due to partial result.");
return (null);
}
// Get result for the first entry found
SearchResult result = (SearchResult)results.next();
// Check no further entries were found
try {
if (results.hasMore()) {
log("username " + username + " has multiple entries");
return (null);
}
} catch (PartialResultException ex) {
// this may occur but is legal
getLogger().debug("Partial result for username " + username);
}
// Get the entry's distinguished name
NameParser parser = context.getNameParser("");
Name contextName = parser.parse(context.getNameInNamespace());
Name baseName = parser.parse(userBase);
Name entryName = parser.parse(result.getName());
Name name = contextName.addAll(baseName);
name = name.addAll(entryName);
String dn = name.toString();
if (getLogger().isDebugEnabled())
log(" entry found for " + username + " with dn " + dn);
// Get the entry's attributes
Attributes attrs = result.getAttributes();
if (attrs == null)
return null;
return createUser(username, dn, attrs);
}
private JNDIUser createUser(String username, String dn, Attributes attrs) throws NamingException {
// Retrieve value of userPassword
String password = null;
if (userPassword != null && userPassword.length() > 0)
password = getAttributeValue(userPassword, attrs);
String mail = null;
if ( userMail != null && userMail.length() > 0) {
mail = getAttributeValue( userMail, attrs );
}
String cn = null;
if ( userCn != null && userCn.length() > 0 ) {
cn = getAttributeValue( userCn, attrs );
}
return new JNDIUser(username, dn, password, mail, cn);
}
/**
* Check whether the given User can be authenticated with the
* given credentials. If the <code>userPassword</code>
* configuration attribute is specified, the credentials
* previously retrieved from the directory are compared explicitly
* with those presented by the user. Otherwise the presented
* credentials are checked by binding to the directory as the
* user.
*
* @param context The directory context
* @param user The User to be authenticated
* @param credentials The credentials presented by the user
*
* @exception NamingException if a directory server error occurs
*/
protected boolean checkCredentials(DirContext context,
JNDIUser user,
String credentials)
throws NamingException {
boolean validated = false;
if (userPassword == null || userPassword.length() ==0) {
validated = bindAsUser(context, user, credentials);
} else {
validated = compareCredentials(context, user, credentials);
}
if ( getLogger().isDebugEnabled() ) {
if (validated) {
log("jndiRealm.authenticateSuccess: " + user.username);
} else {
log("jndiRealm.authenticateFailure: " + user.username);
}
}
return (validated);
}
/**
* Check whether the credentials presented by the user match those
* retrieved from the directory.
*
* @param context The directory context
* @param info The User to be authenticated
* @param credentials Authentication credentials
*
* @exception NamingException if a directory server error occurs
*/
protected boolean compareCredentials(DirContext context,
JNDIUser info,
String credentials)
throws NamingException {
if (info == null || credentials == null)
return (false);
String password = info.password;
if (password == null)
return (false);
// Validate the credentials specified by the user
if ( getLogger().isDebugEnabled() )
log(" validating credentials");
boolean validated = false;
if (hasMessageDigest()) {
// Hex hashes should be compared case-insensitive
String digestCredential = digest(credentials);
validated = digestCredential.equalsIgnoreCase(password);
} else {
validated = credentials.equals(password);
}
return (validated);
}
protected boolean hasMessageDigest() {
return !(md == null);
}
/**
* Digest the password using the specified algorithm and
* convert the result to a corresponding hexadecimal string.
* If exception, the plain credentials string is returned.
*
* <strong>IMPLEMENTATION NOTE</strong> - This implementation is
* synchronized because it reuses the MessageDigest instance.
* This should be faster than cloning the instance on every request.
*
* @param credentials Password or other credentials to use in
* authenticating this username
*/
protected String digest(String credentials) {
// If no MessageDigest instance is specified, return unchanged
if ( hasMessageDigest() == false)
return (credentials);
// Digest the user credentials and return as hexadecimal
synchronized (this) {
try {
md.reset();
md.update(credentials.getBytes());
return (Tools.convert(md.digest()));
} catch (Exception e) {
log("realmBase.digest", e);
return (credentials);
}
}
}
/**
* Check credentials by binding to the directory as the user
*
* @param context The directory context
* @param user The User to be authenticated
* @param credentials Authentication credentials
*
* @exception NamingException if a directory server error occurs
*/
protected boolean bindAsUser(DirContext context,
JNDIUser user,
String credentials)
throws NamingException {
if (credentials == null || user == null)
return (false);
String dn = user.dn;
if (dn == null)
return (false);
// Validate the credentials specified by the user
if ( getLogger().isDebugEnabled() ) {
log(" validating credentials by binding as the user");
}
// Set up security environment to bind as the user
context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
context.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
// Elicit an LDAP bind operation
boolean validated = false;
try {
if ( getLogger().isDebugEnabled() ) {
log(" binding as " + dn);
}
//Attributes attr =
String attributeName;
attributeName = "";
context.getAttributes(attributeName, null);
validated = true;
}
catch (NamingException e) {
if ( getLogger().isDebugEnabled() ) {
log(" bind attempt failed" + e.getMessage());
}
}
// Restore the original security environment
if (connectionName != null) {
context.addToEnvironment(Context.SECURITY_PRINCIPAL,
connectionName);
} else {
context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
}
if (connectionPassword != null) {
context.addToEnvironment(Context.SECURITY_CREDENTIALS,
connectionPassword);
}
else {
context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
}
return (validated);
}
/**
* Return a String representing the value of the specified attribute.
*
* @param attrId Attribute name
* @param attrs Attributes containing the required value
*
* @exception NamingException if a directory server error occurs
*/
private String getAttributeValue(String attrId, Attributes attrs)
throws NamingException {
if ( getLogger().isDebugEnabled() )
log(" retrieving attribute " + attrId);
if (attrId == null || attrs == null)
return null;
Attribute attr = attrs.get(attrId);
if (attr == null)
return (null);
Object value = attr.get();
if (value == null)
return (null);
String valueString = null;
if (value instanceof byte[])
valueString = new String((byte[]) value);
else
valueString = value.toString();
return valueString;
}
/**
* Close any open connection to the directory server for this Realm.
*
* @param context The directory context to be closed
*/
protected void close(DirContext context) {
// Do nothing if there is no opened connection
if (context == null)
return;
// Close our opened connection
try {
if ( getLogger().isDebugEnabled() )
log("Closing directory context");
context.close();
} catch (NamingException e) {
log("jndiRealm.close", e);
}
this.context = null;
}
/**
* Open (if necessary) and return a connection to the configured
* directory server for this Realm.
*
* @exception NamingException if a directory server error occurs
*/
protected DirContext open() throws NamingException {
// Do nothing if there is a directory server connection already open
if (context != null)
return (context);
try {
// Ensure that we have a directory context available
context = new InitialDirContext(getDirectoryContextEnvironment());
/*
} catch (NamingException e) {
connectionAttempt = 1;
// log the first exception.
log("jndiRealm.exception", e);
// Try connecting to the alternate url.
context = new InitialDirContext(getDirectoryContextEnvironment());
*/
} finally {
// reset it in case the connection times out.
// the primary may come back.
connectionAttempt = 0;
}
return (context);
}
/**
* Create our directory context configuration.
*
* @return java.util.Hashtable the configuration for the directory context.
*/
protected Hashtable<String,Object> getDirectoryContextEnvironment() {
Hashtable<String,Object> env = new Hashtable<String,Object>();
// Configure our directory context environment.
if ( getLogger().isDebugEnabled() && connectionAttempt == 0)
log("Connecting to URL " + connectionURL);
env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
if (connectionName != null)
env.put(Context.SECURITY_PRINCIPAL, connectionName);
if (connectionPassword != null)
env.put(Context.SECURITY_CREDENTIALS, connectionPassword);
if (connectionURL != null && connectionAttempt == 0)
env.put(Context.PROVIDER_URL, connectionURL);
//env.put("com.sun.jndi.ldap.connect.pool", "true");
env.put("com.sun.jndi.ldap.read.timeout", "5000");
env.put("com.sun.jndi.ldap.connect.timeout", "15000");
env.put("java.naming.ldap.derefAliases", "never");
return env;
}
// ------------------------------------------------------ Lifecycle Methods
/**
* Gracefully shut down active use of the public methods of this Component.
*/
public void dispose()
{
// Close any open directory server connection
close(this.context);
}
public static void main(String[] args) {
JNDIAuthenticationStore aut = new JNDIAuthenticationStore();
aut.setConnectionName( "uid=admin,ou=system" );
aut.setConnectionPassword( "secret" );
aut.setConnectionURL( "ldap://localhost:10389" );
//aut.setUserPassword ( "userPassword" );
aut.setUserBase ( "dc=example,dc=com" );
aut.setUserSearch ("(uid={0})" );
try {
if ( aut.authenticate ( "admin", "admin" ) ) {
System.out.println( "Authentication succeeded." );
} else {
System.out.println( "Authentication failed" );
}
} catch (Exception ex ) {
ex.printStackTrace();
}
}
/**
* A private class representing a User
*/
static class JNDIUser {
String username = null;
String dn = null;
String password = null;
String mail = null;
String cn = null;
JNDIUser(String username, String dn, String password, String mail, String cn) {
this.username = username;
this.dn = dn;
this.password = password;
this.mail = mail;
this.cn = cn;
}
}
}
| 04900db4-rob | src/org/rapla/plugin/jndi/server/JNDIAuthenticationStore.java | Java | gpl3 | 39,454 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.archiver;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
public class ArchiverPlugin implements PluginDescriptor<ClientServiceContainer>
{
public final static boolean ENABLE_BY_DEFAULT = false;
public void provideServices(ClientServiceContainer container, Configuration config) {
container.addContainerProvidedComponent( RaplaClientExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION,ArchiverOption.class);
}
}
| 04900db4-rob | src/org/rapla/plugin/archiver/ArchiverPlugin.java | Java | gpl3 | 1,526 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.archiver;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Locale;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.rapla.components.calendar.RaplaNumber;
import org.rapla.components.layout.TableLayout;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.DefaultPluginOption;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.storage.dbrm.RestartServer;
public class ArchiverOption extends DefaultPluginOption implements ActionListener {
RaplaNumber dayField = new RaplaNumber(new Integer(25), new Integer(0),null,false);
JCheckBox removeOlderYesNo = new JCheckBox();
JCheckBox exportToDataXML = new JCheckBox();
RaplaButton deleteNow;
RaplaButton backupButton;
RaplaButton restoreButton;
ArchiverService archiver;
public ArchiverOption(RaplaContext sm, ArchiverService archiver){
super(sm);
this.archiver = archiver;
}
protected JPanel createPanel() throws RaplaException {
JPanel panel = super.createPanel();
JPanel content = new JPanel();
double[][] sizes = new double[][] {
{5,TableLayout.PREFERRED, 5,TableLayout.PREFERRED,5, TableLayout.PREFERRED}
,{TableLayout.PREFERRED,5,TableLayout.PREFERRED,15,TableLayout.PREFERRED,5,TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED}
};
TableLayout tableLayout = new TableLayout(sizes);
content.setLayout(tableLayout);
//content.add(new JLabel("Remove old events"), "1,0");
removeOlderYesNo.setText("Remove events older than");
content.add( removeOlderYesNo, "1,0");
//content.add(new JLabel("Older than"), "1,2");
content.add( dayField, "3,0");
content.add( new JLabel("days"), "5,0");
deleteNow = new RaplaButton(RaplaButton.DEFAULT);
deleteNow.setText("delete now");
content.add(deleteNow, "3,2");
exportToDataXML.setText("Export db to file");
content.add(exportToDataXML, "1,4");
backupButton = new RaplaButton(RaplaButton.DEFAULT);
backupButton.setText("backup now");
content.add( backupButton, "3,4");
restoreButton = new RaplaButton(RaplaButton.DEFAULT);
restoreButton.setText("restore and restart");
content.add( restoreButton, "3,6");
removeOlderYesNo.addActionListener( this );
exportToDataXML.addActionListener( this );
deleteNow.addActionListener( this );
backupButton.addActionListener( this );
restoreButton.addActionListener( this );
panel.add( content, BorderLayout.CENTER);
return panel;
}
private void updateEnabled()
{
{
boolean selected = removeOlderYesNo.isSelected();
dayField.setEnabled( selected);
deleteNow.setEnabled( selected );
}
{
boolean selected = exportToDataXML.isSelected();
backupButton.setEnabled(selected);
restoreButton.setEnabled( selected);
}
}
protected void addChildren( DefaultConfiguration newConfig) {
if ( removeOlderYesNo.isSelected())
{
DefaultConfiguration conf = new DefaultConfiguration(ArchiverService.REMOVE_OLDER_THAN_ENTRY);
conf.setValue(dayField.getNumber().intValue() );
newConfig.addChild( conf );
}
if ( exportToDataXML.isSelected())
{
DefaultConfiguration conf = new DefaultConfiguration(ArchiverService.EXPORT);
conf.setValue( true );
newConfig.addChild( conf );
}
}
protected void readConfig( Configuration config) {
int days = config.getChild(ArchiverService.REMOVE_OLDER_THAN_ENTRY).getValueAsInteger(-20);
boolean isEnabled = days != -20;
removeOlderYesNo.setSelected( isEnabled );
if ( days == -20 )
{
days = 30;
}
dayField.setNumber( new Integer(days));
boolean exportSelected= config.getChild(ArchiverService.EXPORT).getValueAsBoolean(false);
try {
boolean exportEnabled = archiver.isExportEnabled();
exportToDataXML.setEnabled( exportEnabled );
exportToDataXML.setSelected( exportSelected && exportEnabled );
} catch (RaplaException e) {
exportToDataXML.setEnabled( false );
exportToDataXML.setSelected( false );
getLogger().error(e.getMessage(), e);
}
updateEnabled();
}
public void show() throws RaplaException {
super.show();
}
public void commit() throws RaplaException {
super.commit();
}
/**
* @see org.rapla.gui.DefaultPluginOption#getPluginClass()
*/
public Class<? extends PluginDescriptor<?>> getPluginClass() {
return ArchiverPlugin.class;
}
public String getName(Locale locale) {
return "Archiver Plugin";
}
public void actionPerformed(ActionEvent e) {
try
{
Object source = e.getSource();
if ( source == exportToDataXML || source == removeOlderYesNo)
{
updateEnabled();
}
else
{
if ( source == deleteNow)
{
Number days = dayField.getNumber();
if ( days != null)
{
archiver.delete(new Integer(days.intValue()));
}
}
else if (source == backupButton)
{
archiver.backupNow();
}
else if (source == restoreButton)
{
boolean modal = true;
DialogUI dialog = DialogUI.create(getContext(), getMainComponent(),modal,"Warning", "The current data will be overwriten by the backup version. Do you want to proceed?", new String[]{"restore data","abort"});
dialog.setDefault( 1);
dialog.start();
if (dialog.getSelectedIndex() == 0)
{
archiver.restore();
RestartServer service = getService(RestartServer.class);
service.restartServer();
}
}
}
}
catch (RaplaException ex)
{
showException(ex, getMainComponent());
}
}
}
| 04900db4-rob | src/org/rapla/plugin/archiver/ArchiverOption.java | Java | gpl3 | 7,243 |
package org.rapla.plugin.archiver;
import javax.jws.WebService;
import org.rapla.framework.RaplaException;
@WebService
public interface ArchiverService
{
String REMOVE_OLDER_THAN_ENTRY = "remove-older-than";
String EXPORT = "export";
void delete(Integer olderThanInDays) throws RaplaException;
boolean isExportEnabled() throws RaplaException;
void backupNow() throws RaplaException;
void restore() throws RaplaException;
}
| 04900db4-rob | src/org/rapla/plugin/archiver/ArchiverService.java | Java | gpl3 | 452 |
package org.rapla.plugin.archiver.server;
import org.rapla.entities.User;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.archiver.ArchiverService;
import org.rapla.server.RemoteMethodFactory;
import org.rapla.server.RemoteSession;
import org.rapla.storage.RaplaSecurityException;
public class ArchiverServiceFactory extends RaplaComponent implements RemoteMethodFactory<ArchiverService>
{
public ArchiverServiceFactory(RaplaContext context) {
super(context);
}
public ArchiverService createService(final RemoteSession remoteSession) {
RaplaContext context = getContext();
return new ArchiverServiceImpl( context)
{
@Override
protected void checkAccess() throws RaplaException {
User user = remoteSession.getUser();
if ( user != null && !user.isAdmin())
{
throw new RaplaSecurityException("ArchiverService can only be triggered by admin users");
}
}
};
}
}
| 04900db4-rob | src/org/rapla/plugin/archiver/server/ArchiverServiceFactory.java | Java | gpl3 | 1,040 |
package org.rapla.plugin.archiver.server;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.rapla.components.util.DateTools;
import org.rapla.entities.User;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.archiver.ArchiverService;
import org.rapla.storage.ImportExportManager;
import org.rapla.storage.StorageOperator;
import org.rapla.storage.dbsql.DBOperator;
public class ArchiverServiceImpl extends RaplaComponent implements ArchiverService
{
public ArchiverServiceImpl(RaplaContext context) {
super(context);
}
/** can be overriden to check if user has admin rights when triggered as RemoteService
* @throws RaplaException */
protected void checkAccess() throws RaplaException
{
}
public boolean isExportEnabled() throws RaplaException {
ClientFacade clientFacade = getContext().lookup(ClientFacade.class);
StorageOperator operator = clientFacade.getOperator();
boolean enabled = operator instanceof DBOperator;
return enabled;
}
public void backupNow() throws RaplaException {
checkAccess();
if (!isExportEnabled())
{
throw new RaplaException("Export not enabled");
}
ImportExportManager lookup = getContext().lookup(ImportExportManager.class);
lookup.doExport();
}
public void restore() throws RaplaException {
checkAccess();
if (!isExportEnabled())
{
throw new RaplaException("Export not enabled");
}
// We only do an import here
ImportExportManager lookup = getContext().lookup(ImportExportManager.class);
lookup.doImport();
}
public void delete(Integer removeOlderInDays) throws RaplaException {
checkAccess();
ClientFacade clientFacade = getContext().lookup(ClientFacade.class);
Date endDate = new Date(clientFacade.today().getTime() - removeOlderInDays * DateTools.MILLISECONDS_PER_DAY);
Reservation[] events = clientFacade.getReservations((User) null, null, endDate, null); //ClassificationFilter.CLASSIFICATIONFILTER_ARRAY );
List<Reservation> toRemove = new ArrayList<Reservation>();
for ( int i=0;i< events.length;i++)
{
Reservation event = events[i];
if ( isOlderThan( event, endDate))
{
toRemove.add(event);
}
}
if ( toRemove.size() > 0)
{
getLogger().info("Removing " + toRemove.size() + " old events.");
Reservation[] eventsToRemove = toRemove.toArray( Reservation.RESERVATION_ARRAY);
int STEP_SIZE = 100;
for ( int i=0;i< eventsToRemove.length;i+=STEP_SIZE)
{
int blockSize = Math.min( eventsToRemove.length- i, STEP_SIZE);
Reservation[] eventBlock = new Reservation[blockSize];
System.arraycopy( eventsToRemove,i, eventBlock,0, blockSize);
clientFacade.removeObjects( eventBlock);
}
}
}
private boolean isOlderThan( Reservation event, Date maxAllowedDate )
{
Appointment[] appointments = event.getAppointments();
for ( int i=0;i<appointments.length;i++)
{
Appointment appointment = appointments[i];
Date start = appointment.getStart();
Date end = appointment.getMaxEnd();
if ( start == null || end == null )
{
return false;
}
if ( end.after( maxAllowedDate))
{
return false;
}
if ( start.after( maxAllowedDate))
{
return false;
}
}
return true;
}
} | 04900db4-rob | src/org/rapla/plugin/archiver/server/ArchiverServiceImpl.java | Java | gpl3 | 3,811 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.archiver.server;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.plugin.archiver.ArchiverPlugin;
import org.rapla.plugin.archiver.ArchiverService;
import org.rapla.server.RaplaServerExtensionPoints;
import org.rapla.server.ServerServiceContainer;
public class ArchiverServerPlugin implements PluginDescriptor<ServerServiceContainer>
{
public void provideServices(ServerServiceContainer container, Configuration config) {
container.addRemoteMethodFactory(ArchiverService.class, ArchiverServiceFactory.class, config);
if ( !config.getAttributeAsBoolean("enabled", ArchiverPlugin.ENABLE_BY_DEFAULT) )
return;
container.addContainerProvidedComponent( RaplaServerExtensionPoints.SERVER_EXTENSION, ArchiverServiceTask.class, config);
}
}
| 04900db4-rob | src/org/rapla/plugin/archiver/server/ArchiverServerPlugin.java | Java | gpl3 | 1,836 |
package org.rapla.plugin.archiver.server;
import org.rapla.components.util.Command;
import org.rapla.components.util.CommandScheduler;
import org.rapla.components.util.DateTools;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.archiver.ArchiverService;
import org.rapla.server.ServerExtension;
public class ArchiverServiceTask extends RaplaComponent implements ServerExtension
{
public ArchiverServiceTask( final RaplaContext context, final Configuration config ) throws RaplaContextException
{
super( context );
final int days = config.getChild( ArchiverService.REMOVE_OLDER_THAN_ENTRY).getValueAsInteger(-20);
final boolean export = config.getChild( ArchiverService.EXPORT).getValueAsBoolean(false);
if ( days != -20 || export)
{
CommandScheduler timer = context.lookup( CommandScheduler.class);
Command removeTask = new Command() {
public void execute() throws RaplaException {
ArchiverServiceImpl task = new ArchiverServiceImpl(getContext());
try
{
if ( days != -20 )
{
task.delete( days );
}
if ( export && task.isExportEnabled())
{
task.backupNow();
}
}
catch (RaplaException e) {
getLogger().error("Could not execute archiver task ", e);
}
}
};
// Call it each hour
timer.schedule(removeTask, 0, DateTools.MILLISECONDS_PER_HOUR);
}
}
}
| 04900db4-rob | src/org/rapla/plugin/archiver/server/ArchiverServiceTask.java | Java | gpl3 | 1,864 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.timeslot;
import javax.swing.Icon;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.SwingCalendarView;
import org.rapla.gui.SwingViewFactory;
import org.rapla.gui.images.Images;
public class CompactWeekViewFactory extends RaplaComponent implements SwingViewFactory
{
public final static String WEEK_TIMESLOT = "week_timeslot";
public CompactWeekViewFactory( RaplaContext context )
{
super( context );
}
public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException
{
return new SwingCompactCalendar( context, model, editable);
}
public String getViewId()
{
return WEEK_TIMESLOT;
}
public String getName()
{
return getString(WEEK_TIMESLOT);
}
Icon icon;
public Icon getIcon()
{
if ( icon == null) {
icon = Images.getIcon("/org/rapla/plugin/compactweekview/images/week_compact.png");
}
return icon;
}
public String getMenuSortKey() {
return "B2";
}
}
| 04900db4-rob | src/org/rapla/plugin/timeslot/CompactWeekViewFactory.java | Java | gpl3 | 2,173 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.timeslot;
import javax.swing.Icon;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.SwingCalendarView;
import org.rapla.gui.SwingViewFactory;
import org.rapla.gui.images.Images;
public class CompactDayViewFactory extends RaplaComponent implements SwingViewFactory
{
public final static String DAY_TIMESLOT = "day_timeslot";
public CompactDayViewFactory( RaplaContext context )
{
super( context );
}
public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException
{
return new SwingCompactDayCalendar( context, model, editable);
}
public String getViewId()
{
return DAY_TIMESLOT;
}
public String getName()
{
return getString(DAY_TIMESLOT);
}
Icon icon;
public Icon getIcon()
{
if ( icon == null) {
icon = Images.getIcon("/org/rapla/plugin/compactweekview/images/week_compact.png");
}
return icon;
}
public String getMenuSortKey() {
return "B2";
}
}
| 04900db4-rob | src/org/rapla/plugin/timeslot/CompactDayViewFactory.java | Java | gpl3 | 2,170 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.timeslot.server;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory;
import org.rapla.servletpages.RaplaPageGenerator;
public class CompactHTMLWeekViewFactory extends RaplaComponent implements HTMLViewFactory
{
public final static String WEEK_TIMESLOT = "week_timeslot";
public CompactHTMLWeekViewFactory( RaplaContext context )
{
super( context );
}
public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) throws RaplaException
{
return new HTMLCompactViewPage( context, model);
}
public String getViewId()
{
return WEEK_TIMESLOT;
}
public String getName()
{
return getString(WEEK_TIMESLOT);
}
}
| 04900db4-rob | src/org/rapla/plugin/timeslot/server/CompactHTMLWeekViewFactory.java | Java | gpl3 | 1,856 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.timeslot.server;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory;
import org.rapla.servletpages.RaplaPageGenerator;
public class CompactHTMLDayViewFactory extends RaplaComponent implements HTMLViewFactory
{
public final static String DAY_TIMESLOT = "day_timeslot";
public CompactHTMLDayViewFactory( RaplaContext context )
{
super( context );
}
public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model)
{
return new HTMLCompactDayViewPage( context, model);
}
public String getViewId()
{
return DAY_TIMESLOT;
}
public String getName()
{
return getString(DAY_TIMESLOT);
}
}
| 04900db4-rob | src/org/rapla/plugin/timeslot/server/CompactHTMLDayViewFactory.java | Java | gpl3 | 1,790 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.timeslot.server;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.rapla.components.calendarview.GroupStartTimesStrategy;
import org.rapla.components.calendarview.html.AbstractHTMLView;
import org.rapla.components.calendarview.html.HTMLCompactWeekView;
import org.rapla.components.util.xml.XMLWriter;
import org.rapla.entities.domain.Allocatable;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarOptions;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.plugin.abstractcalendar.server.AbstractHTMLCalendarPage;
import org.rapla.plugin.timeslot.Timeslot;
import org.rapla.plugin.timeslot.TimeslotProvider;
public class HTMLCompactDayViewPage extends AbstractHTMLCalendarPage
{
public HTMLCompactDayViewPage( RaplaContext context, CalendarModel calendarModel)
{
super( context, calendarModel);
}
protected AbstractHTMLView createCalendarView() {
HTMLCompactWeekView weekView = new HTMLCompactWeekView()
{
protected List<String> getHeaderNames()
{
List<String> headerNames = new ArrayList<String>();
try
{
List<Allocatable> sortedAllocatables = getSortedAllocatables();
for (Allocatable alloc: sortedAllocatables)
{
headerNames.add( alloc.getName( getLocale()));
}
}
catch (RaplaException ex)
{
}
return headerNames;
}
protected int getColumnCount()
{
try {
Allocatable[] selectedAllocatables =model.getSelectedAllocatables();
return selectedAllocatables.length;
} catch (RaplaException e) {
return 0;
}
}
@Override
public void rebuild() {
setWeeknumber(getRaplaLocale().formatDateShort(getStartDate()));
super.rebuild();
}
};
weekView.setLeftColumnSize(0.01);
return weekView;
}
@Override
protected void configureView() throws RaplaException {
CalendarOptions opt = getCalendarOptions();
int days = 1;
view.setDaysInView( days);
int firstDayOfWeek = opt.getFirstDayOfWeek();
view.setFirstWeekday( firstDayOfWeek);
Set<Integer> excludeDays = new HashSet<Integer>();
view.setExcludeDays( excludeDays );
}
protected RaplaBuilder createBuilder() throws RaplaException
{
List<Timeslot> timeslots = getService(TimeslotProvider.class).getTimeslots();
List<Integer> startTimes = new ArrayList<Integer>();
for (Timeslot slot:timeslots) {
startTimes.add( slot.getMinuteOfDay());
}
RaplaBuilder builder = super.createBuilder();
final List<Allocatable> allocatables = getSortedAllocatables();
builder.selectAllocatables( allocatables);
builder.setSmallBlocks( true );
GroupStartTimesStrategy strategy = new GroupStartTimesStrategy();
strategy.setAllocatables(allocatables);
strategy.setFixedSlotsEnabled( true);
strategy.setResolveConflictsEnabled( false );
strategy.setStartTimes( startTimes );
builder.setBuildStrategy( strategy);
String[] slotNames = new String[ timeslots.size() ];
for (int i = 0; i <timeslots.size(); i++ ) {
slotNames[i] = XMLWriter.encode( timeslots.get( i ).getName());
}
((HTMLCompactWeekView)view).setSlots( slotNames );
return builder;
}
public int getIncrementSize() {
return Calendar.DAY_OF_YEAR;
}
}
| 04900db4-rob | src/org/rapla/plugin/timeslot/server/HTMLCompactDayViewPage.java | Java | gpl3 | 4,728 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.timeslot.server;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
import org.rapla.components.calendarview.GroupStartTimesStrategy;
import org.rapla.components.calendarview.html.AbstractHTMLView;
import org.rapla.components.calendarview.html.HTMLCompactWeekView;
import org.rapla.components.util.xml.XMLWriter;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarOptions;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.plugin.abstractcalendar.server.AbstractHTMLCalendarPage;
import org.rapla.plugin.timeslot.Timeslot;
import org.rapla.plugin.timeslot.TimeslotProvider;
public class HTMLCompactViewPage extends AbstractHTMLCalendarPage
{
public HTMLCompactViewPage( RaplaContext context, CalendarModel calendarModel)
{
super( context, calendarModel);
}
protected AbstractHTMLView createCalendarView() {
HTMLCompactWeekView weekView = new HTMLCompactWeekView()
{
@Override
public void rebuild() {
String weeknumberString = MessageFormat.format(getString("calendarweek.abbreviation"), getStartDate());
setWeeknumber(weeknumberString);
super.rebuild();
}
};
weekView.setLeftColumnSize(0.01);
return weekView;
}
@Override
protected void configureView() throws RaplaException {
CalendarOptions opt = getCalendarOptions();
Set<Integer> excludeDays = opt.getExcludeDays();
view.setExcludeDays( excludeDays );
view.setDaysInView( opt.getDaysInWeekview());
int firstDayOfWeek = opt.getFirstDayOfWeek();
view.setFirstWeekday( firstDayOfWeek);
view.setExcludeDays( excludeDays );
}
protected RaplaBuilder createBuilder() throws RaplaException
{
List<Timeslot> timeslots = getService(TimeslotProvider.class).getTimeslots();
List<Integer> startTimes = new ArrayList<Integer>();
for (Timeslot slot:timeslots) {
startTimes.add( slot.getMinuteOfDay());
}
RaplaBuilder builder = super.createBuilder();
builder.setSmallBlocks( true );
GroupStartTimesStrategy strategy = new GroupStartTimesStrategy();
strategy.setFixedSlotsEnabled( true);
strategy.setResolveConflictsEnabled( false );
strategy.setStartTimes( startTimes );
builder.setBuildStrategy( strategy);
builder.setSplitByAllocatables( false );
String[] slotNames = new String[ timeslots.size() ];
for (int i = 0; i <timeslots.size(); i++ ) {
slotNames[i] = XMLWriter.encode( timeslots.get( i ).getName());
}
((HTMLCompactWeekView)view).setSlots( slotNames );
return builder;
}
protected int getIncrementSize() {
return Calendar.WEEK_OF_YEAR;
}
}
| 04900db4-rob | src/org/rapla/plugin/timeslot/server/HTMLCompactViewPage.java | Java | gpl3 | 3,925 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.timeslot.server;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.plugin.timeslot.TimeslotPlugin;
import org.rapla.plugin.timeslot.TimeslotProvider;
import org.rapla.server.RaplaServerExtensionPoints;
import org.rapla.server.ServerServiceContainer;
public class TimeslotServerPlugin implements PluginDescriptor<ServerServiceContainer>
{
public void provideServices(ServerServiceContainer container, Configuration config) {
if ( !config.getAttributeAsBoolean("enabled", TimeslotPlugin.ENABLE_BY_DEFAULT))
return;
container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,CompactHTMLDayViewFactory.class);
container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,CompactHTMLWeekViewFactory.class);
container.addContainerProvidedComponent(TimeslotProvider.class,TimeslotProvider.class,config );
}
}
| 04900db4-rob | src/org/rapla/plugin/timeslot/server/TimeslotServerPlugin.java | Java | gpl3 | 1,950 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.timeslot;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.framework.Configuration;
import org.rapla.framework.PluginDescriptor;
public class TimeslotPlugin implements PluginDescriptor<ClientServiceContainer>
{
public final static boolean ENABLE_BY_DEFAULT = false;
public void provideServices(ClientServiceContainer container, Configuration config) {
container.addContainerProvidedComponent( RaplaClientExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION,TimeslotOption.class);
if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT))
return;
container.addContainerProvidedComponent(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,CompactDayViewFactory.class);
container.addContainerProvidedComponent(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,CompactWeekViewFactory.class);
container.addContainerProvidedComponent(TimeslotProvider.class,TimeslotProvider.class,config );
}
}
| 04900db4-rob | src/org/rapla/plugin/timeslot/TimeslotPlugin.java | Java | gpl3 | 1,980 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.timeslot;
import java.awt.Font;
import java.awt.Point;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.JLabel;
import org.rapla.components.calendar.DateRenderer;
import org.rapla.components.calendar.DateRenderer.RenderingInfo;
import org.rapla.components.calendar.DateRendererAdapter;
import org.rapla.components.calendarview.Block;
import org.rapla.components.calendarview.GroupStartTimesStrategy;
import org.rapla.components.calendarview.swing.AbstractSwingCalendar;
import org.rapla.components.calendarview.swing.SwingBlock;
import org.rapla.components.calendarview.swing.SwingCompactWeekView;
import org.rapla.components.calendarview.swing.ViewListener;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarOptions;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.abstractcalendar.AbstractRaplaSwingCalendar;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.plugin.abstractcalendar.RaplaCalendarViewListener;
public class SwingCompactCalendar extends AbstractRaplaSwingCalendar
{
List<Timeslot> timeslots;
public SwingCompactCalendar(RaplaContext sm,CalendarModel settings, boolean editable) throws RaplaException {
super( sm, settings, editable);
}
@Override
protected AbstractSwingCalendar createView(boolean showScrollPane)
throws RaplaException {
final DateRendererAdapter dateRenderer = new DateRendererAdapter(getService(DateRenderer.class), getRaplaLocale().getTimeZone(), getRaplaLocale().getLocale());
SwingCompactWeekView compactWeekView = new SwingCompactWeekView( showScrollPane ) {
@Override
protected JComponent createColumnHeader(Integer column) {
JLabel component = (JLabel) super.createColumnHeader(column);
if ( column != null ) {
Date date = getDateFromColumn(column);
boolean today = DateTools.isSameDay(getQuery().today().getTime(), date.getTime());
if ( today)
{
component.setFont(component.getFont().deriveFont( Font.BOLD));
}
if (isEditable() ) {
component.setOpaque(true);
RenderingInfo info = dateRenderer.getRenderingInfo(date);
if ( info.getBackgroundColor() != null)
{
component.setBackground(info.getBackgroundColor());
}
if ( info.getForegroundColor() != null)
{
component.setForeground(info.getForegroundColor());
}
component.setToolTipText(info.getTooltipText());
}
}
else
{
String calendarWeek = MessageFormat.format(getString("calendarweek.abbreviation"), getStartDate());
component.setText( calendarWeek);
}
return component;
}
protected int getColumnCount()
{
return getDaysInView();
}
@Override
public TimeInterval normalizeBlockIntervall(SwingBlock block)
{
Date start = block.getStart();
Date end = block.getEnd();
for (Timeslot slot:timeslots)
{
int minuteOfDay = DateTools.getMinuteOfDay( start.getTime());
if ( minuteOfDay >= slot.minuteOfDay)
{
start = new Date(DateTools.cutDate( start).getTime() + slot.minuteOfDay);
break;
}
}
for (Timeslot slot:timeslots)
{
int minuteOfDay = DateTools.getMinuteOfDay( end.getTime());
if ( minuteOfDay < slot.minuteOfDay)
{
end = new Date(DateTools.cutDate( end).getTime() + slot.minuteOfDay);
}
if ( slot.minuteOfDay > minuteOfDay)
{
break;
}
}
return new TimeInterval(start,end);
}
};
return compactWeekView;
}
@Override
public int getIncrementSize() {
return Calendar.WEEK_OF_YEAR;
}
protected ViewListener createListener() throws RaplaException {
return new RaplaCalendarViewListener(getContext(), model, view.getComponent()) {
/** override to change the allocatable to the row that is selected */
@Override
public void selectionChanged(Date start,Date end)
{
TimeInterval inter = getMarkedInterval(start);
super.selectionChanged(inter.getStart(), inter.getEnd());
}
public void moved(Block block, Point p, Date newStart, int slotNr) {
int days = view.getDaysInView();
int columns = days;
int index = slotNr;
int rowIndex = index/columns;
Timeslot timeslot = timeslots.get(rowIndex);
int time = timeslot.minuteOfDay;
Calendar cal = getRaplaLocale().createCalendar();
int lastMinuteOfDay;
cal.setTime ( block.getStart() );
lastMinuteOfDay = cal.get( Calendar.HOUR_OF_DAY) * 60 + cal.get( Calendar.MINUTE);
boolean sameTimeSlot = true;
if ( lastMinuteOfDay < time)
{
sameTimeSlot = false;
}
if ( rowIndex +1 < timeslots.size())
{
Timeslot nextTimeslot = timeslots.get(rowIndex+1);
if ( lastMinuteOfDay >= nextTimeslot.minuteOfDay )
{
sameTimeSlot = false;
}
}
cal.setTime ( newStart );
if ( sameTimeSlot)
{
time = lastMinuteOfDay;
}
cal.set( Calendar.HOUR_OF_DAY, time /60);
cal.set( Calendar.MINUTE, time %60);
newStart = cal.getTime();
moved(block, p, newStart);
}
protected TimeInterval getMarkedInterval(Date start) {
int columns = view.getDaysInView();
Date end;
Integer startTime = null;
Integer endTime = null;
int slots = columns*timeslots.size();
for ( int i=0;i<slots;i++)
{
if ( ((SwingCompactWeekView)view).isSelected(i))
{
int index = i/columns;
int time = timeslots.get(index).minuteOfDay;
if ( startTime == null || time < startTime )
{
startTime = time;
}
time = index<timeslots.size()-1 ? timeslots.get(index+1).minuteOfDay : 24* 60;
if ( endTime == null || time >= endTime )
{
endTime = time;
}
}
}
CalendarOptions calendarOptions = getCalendarOptions();
if ( startTime == null)
{
startTime = calendarOptions.getWorktimeStartMinutes();
}
if ( endTime == null)
{
endTime = calendarOptions.getWorktimeEndMinutes() + (calendarOptions.isWorktimeOvernight() ? 24*60:0);
}
Calendar cal = getRaplaLocale().createCalendar();
cal.setTime ( start );
cal.set( Calendar.HOUR_OF_DAY, startTime/60);
cal.set( Calendar.MINUTE, startTime%60);
start = cal.getTime();
cal.set( Calendar.HOUR_OF_DAY, endTime/60);
cal.set( Calendar.MINUTE, endTime%60);
end = cal.getTime();
TimeInterval intervall = new TimeInterval(start,end);
return intervall;
}
};
}
protected RaplaBuilder createBuilder() throws RaplaException {
timeslots = getService(TimeslotProvider.class).getTimeslots();
List<Integer> startTimes = new ArrayList<Integer>();
for (Timeslot slot:timeslots) {
startTimes.add( slot.getMinuteOfDay());
}
RaplaBuilder builder = super.createBuilder();
builder.setSmallBlocks( true );
GroupStartTimesStrategy strategy = new GroupStartTimesStrategy();
strategy.setFixedSlotsEnabled( true);
strategy.setResolveConflictsEnabled( false );
strategy.setStartTimes( startTimes );
//Uncommont if you want to sort by resource name instead of event name
// strategy.setBlockComparator( new Comparator<Block>() {
//
// public int compare(Block b1, Block b2) {
// int result = b1.getStart().compareTo(b2.getStart());
// if (result != 0)
// {
// return result;
// }
// Allocatable a1 = ((AbstractRaplaBlock) b1).getGroupAllocatable();
// Allocatable a2 = ((AbstractRaplaBlock) b2).getGroupAllocatable();
// if ( a1 != null && a2 != null)
// {
// String name1 = a1.getName( getLocale());
// String name2 = a2.getName(getLocale());
//
// result = name1.compareTo(name2);
// if (result != 0)
// {
// return result;
// }
//
// }
// return b1.getName().compareTo(b2.getName());
// }
// });
builder.setBuildStrategy( strategy);
builder.setSplitByAllocatables( false );
String[] slotNames = new String[ timeslots.size() ];
int maxSlotLength = 5;
for (int i = 0; i <timeslots.size(); i++ ) {
String slotName = timeslots.get( i ).getName();
maxSlotLength = Math.max( maxSlotLength, slotName.length());
slotNames[i] = slotName;
}
((SwingCompactWeekView)view).setLeftColumnSize( 30+ maxSlotLength * 6);
((SwingCompactWeekView)view).setSlots( slotNames );
return builder;
}
@Override
protected void configureView() throws RaplaException {
CalendarOptions calendarOptions = getCalendarOptions();
Set<Integer> excludeDays = calendarOptions.getExcludeDays();
view.setExcludeDays( excludeDays );
view.setDaysInView( calendarOptions.getDaysInWeekview());
int firstDayOfWeek = calendarOptions.getFirstDayOfWeek();
view.setFirstWeekday( firstDayOfWeek);
view.setToDate(model.getSelectedDate());
}
}
| 04900db4-rob | src/org/rapla/plugin/timeslot/SwingCompactCalendar.java | Java | gpl3 | 12,032 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.timeslot;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.JLabel;
import org.rapla.components.calendarview.Block;
import org.rapla.components.calendarview.GroupStartTimesStrategy;
import org.rapla.components.calendarview.swing.AbstractSwingCalendar;
import org.rapla.components.calendarview.swing.SwingBlock;
import org.rapla.components.calendarview.swing.SwingCompactWeekView;
import org.rapla.components.calendarview.swing.ViewListener;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarOptions;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.plugin.abstractcalendar.AbstractRaplaBlock;
import org.rapla.plugin.abstractcalendar.AbstractRaplaSwingCalendar;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.plugin.abstractcalendar.RaplaCalendarViewListener;
public class SwingCompactDayCalendar extends AbstractRaplaSwingCalendar
{
List<Timeslot> timeslots;
public SwingCompactDayCalendar(RaplaContext sm,CalendarModel settings, boolean editable) throws RaplaException {
super( sm, settings, editable);
}
protected AbstractSwingCalendar createView(boolean showScrollPane) throws RaplaException
{
SwingCompactWeekView compactWeekView = new SwingCompactWeekView( showScrollPane ) {
@Override
protected JComponent createColumnHeader(Integer column) {
JLabel component = (JLabel) super.createColumnHeader(column);
if ( column != null)
{
try {
List<Allocatable> sortedAllocatables = getSortedAllocatables();
Allocatable allocatable = sortedAllocatables.get(column);
String name = allocatable.getName( getLocale());
component.setText( name);
} catch (RaplaException e) {
}
}
else
{
String dateText = getRaplaLocale().formatDateShort(getStartDate());
component.setText( dateText);
}
return component;
}
protected int getColumnCount()
{
try {
Allocatable[] selectedAllocatables =model.getSelectedAllocatables();
return selectedAllocatables.length;
} catch (RaplaException e) {
return 0;
}
}
@Override
public TimeInterval normalizeBlockIntervall(SwingBlock block)
{
Date start = block.getStart();
Date end = block.getEnd();
for (Timeslot slot:timeslots)
{
int minuteOfDay = DateTools.getMinuteOfDay( start.getTime());
if ( minuteOfDay >= slot.minuteOfDay)
{
start = new Date(DateTools.cutDate( start).getTime() + slot.minuteOfDay);
break;
}
}
for (Timeslot slot:timeslots)
{
int minuteOfDay = DateTools.getMinuteOfDay( end.getTime());
if ( minuteOfDay < slot.minuteOfDay)
{
end = new Date(DateTools.cutDate( end).getTime() + slot.minuteOfDay);
}
if ( slot.minuteOfDay > minuteOfDay)
{
break;
}
}
return new TimeInterval(start,end);
}
};
compactWeekView.setDaysInView(1);
return compactWeekView;
}
protected ViewListener createListener() throws RaplaException {
return new RaplaCalendarViewListener(getContext(), model, view.getComponent()) {
@Override
protected Collection<Allocatable> getMarkedAllocatables()
{
List<Allocatable> selectedAllocatables = getSortedAllocatables();
int columns = selectedAllocatables.size();
Set<Allocatable> allSelected = new HashSet<Allocatable>();
int slots = columns*timeslots.size();
for ( int i=0;i<slots;i++)
{
if ( ((SwingCompactWeekView)view).isSelected(i))
{
int column = i%columns;
Allocatable allocatable = selectedAllocatables.get( column);
allSelected.add( allocatable);
}
}
if ( selectedAllocatables.size() == 1 ) {
allSelected.add(selectedAllocatables.get(0));
}
return allSelected;
}
@Override
public void selectionChanged(Date start,Date end)
{
TimeInterval inter = getMarkedInterval(start);
super.selectionChanged(inter.getStart(), inter.getEnd());
}
protected TimeInterval getMarkedInterval(Date start) {
List<Allocatable> selectedAllocatables = getSortedAllocatables();
int columns = selectedAllocatables.size();
Date end;
Integer startTime = null;
Integer endTime = null;
int slots = columns*timeslots.size();
for ( int i=0;i<slots;i++)
{
if ( ((SwingCompactWeekView)view).isSelected(i))
{
int index = i/columns;
int time = timeslots.get(index).minuteOfDay;
if ( startTime == null || time < startTime )
{
startTime = time;
}
time = index<timeslots.size()-1 ? timeslots.get(index+1).minuteOfDay : 24* 60;
if ( endTime == null || time >= endTime )
{
endTime = time;
}
}
}
CalendarOptions calendarOptions = getCalendarOptions();
if ( startTime == null)
{
startTime = calendarOptions.getWorktimeStartMinutes();
}
if ( endTime == null)
{
endTime = calendarOptions.getWorktimeEndMinutes() + (calendarOptions.isWorktimeOvernight() ? 24*60:0);
}
Calendar cal = getRaplaLocale().createCalendar();
cal.setTime ( start );
cal.set( Calendar.HOUR_OF_DAY, startTime/60);
cal.set( Calendar.MINUTE, startTime%60);
start = cal.getTime();
cal.set( Calendar.HOUR_OF_DAY, endTime/60);
cal.set( Calendar.MINUTE, endTime%60);
end = cal.getTime();
TimeInterval intervall = new TimeInterval(start,end);
return intervall;
}
@Override
public void moved(Block block, Point p, Date newStart, int slotNr) {
int index= slotNr;//getIndex( selectedAllocatables, block );
if ( index < 0)
{
return;
}
try
{
final List<Allocatable> selectedAllocatables = getSortedAllocatables();
int columns = selectedAllocatables.size();
int column = index%columns;
Allocatable newAlloc = selectedAllocatables.get(column);
AbstractRaplaBlock raplaBlock = (AbstractRaplaBlock)block;
Allocatable oldAlloc = raplaBlock.getGroupAllocatable();
int rowIndex = index/columns;
Timeslot timeslot = timeslots.get(rowIndex);
int time = timeslot.minuteOfDay;
Calendar cal = getRaplaLocale().createCalendar();
int lastMinuteOfDay;
cal.setTime ( block.getStart() );
lastMinuteOfDay = cal.get( Calendar.HOUR_OF_DAY) * 60 + cal.get( Calendar.MINUTE);
boolean sameTimeSlot = true;
if ( lastMinuteOfDay < time)
{
sameTimeSlot = false;
}
if ( rowIndex +1 < timeslots.size())
{
Timeslot nextTimeslot = timeslots.get(rowIndex+1);
if ( lastMinuteOfDay >= nextTimeslot.minuteOfDay )
{
sameTimeSlot = false;
}
}
cal.setTime ( newStart );
if ( sameTimeSlot)
{
time = lastMinuteOfDay;
}
cal.set( Calendar.HOUR_OF_DAY, time /60);
cal.set( Calendar.MINUTE, time %60);
newStart = cal.getTime();
if ( newAlloc != null && oldAlloc != null && !newAlloc.equals(oldAlloc))
{
AppointmentBlock appointmentBlock= raplaBlock.getAppointmentBlock();
getReservationController().exchangeAllocatable(appointmentBlock, oldAlloc,newAlloc, newStart, getMainComponent(),p);
}
else
{
moved( block,p ,newStart);
}
}
catch (RaplaException ex) {
showException(ex, getMainComponent());
}
}
};
}
protected RaplaBuilder createBuilder() throws RaplaException
{
RaplaBuilder builder = super.createBuilder();
timeslots = getService(TimeslotProvider.class).getTimeslots();
List<Integer> startTimes = new ArrayList<Integer>();
for (Timeslot slot:timeslots) {
startTimes.add( slot.getMinuteOfDay());
}
final List<Allocatable> allocatables = getSortedAllocatables();
builder.setSmallBlocks( true );
GroupStartTimesStrategy strategy = new GroupStartTimesStrategy();
strategy.setAllocatables(allocatables);
strategy.setFixedSlotsEnabled( true);
strategy.setResolveConflictsEnabled( false );
strategy.setStartTimes( startTimes );
builder.setBuildStrategy( strategy);
String[] slotNames = new String[ timeslots.size() ];
int maxSlotLength = 5;
for (int i = 0; i <timeslots.size(); i++ ) {
String slotName = timeslots.get( i ).getName();
maxSlotLength = Math.max( maxSlotLength, slotName.length());
slotNames[i] = slotName;
}
((SwingCompactWeekView)view).setLeftColumnSize( 30+ maxSlotLength * 6);
builder.setSplitByAllocatables( false );
((SwingCompactWeekView)view).setSlots( slotNames );
return builder;
}
protected void configureView() throws RaplaException {
view.setToDate(model.getSelectedDate());
// if ( !view.isEditable() ) {
// view.setSlotSize( model.getSize());
// } else {
// view.setSlotSize( 200 );
// }
}
public int getIncrementSize()
{
return Calendar.DATE;
}
}
| 04900db4-rob | src/org/rapla/plugin/timeslot/SwingCompactDayCalendar.java | Java | gpl3 | 11,901 |
package org.rapla.plugin.timeslot;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.ParseDateException;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaLocale;
public class TimeslotProvider extends RaplaComponent {
private ArrayList<Timeslot> timeslots;
public TimeslotProvider(RaplaContext context, Configuration config) throws ParseDateException
{
super(context);
update(config);
// timeslots.clear();
// timeslots.add(new Timeslot("1. Stunde", 7*60 + 45));
// timeslots.add(new Timeslot("- Pause (5m)", 8*60 + 30));
// timeslots.add(new Timeslot("2. Stunde", 8 * 60 + 35 ));
// timeslots.add(new Timeslot("- Pause (15m)", 9 * 60 + 20 ));
// timeslots.add(new Timeslot("3. Stunde", 9 * 60 + 35 ));
// timeslots.add(new Timeslot("- Pause (5m)", 10*60 + 20));
// timeslots.add(new Timeslot("4. Stunde", 10 * 60 + 25 ));
// timeslots.add(new Timeslot("- Pause (15m)", 11 * 60 + 10 ));
// timeslots.add(new Timeslot("5. Stunde", 11 * 60 + 25 ));
// timeslots.add(new Timeslot("- Pause (5m)", 12*60 + 10));
// timeslots.add(new Timeslot("6. Stunde", 12 * 60 + 15 ));
// timeslots.add(new Timeslot("Nachmittag", 13 * 60 + 0 ));
}
public void update(Configuration config) throws ParseDateException {
ArrayList<Timeslot> timeslots = parseConfig(config, getRaplaLocale());
if ( timeslots == null)
{
timeslots = getDefaultTimeslots(getRaplaLocale());
}
this.timeslots = timeslots;
}
public static ArrayList<Timeslot> parseConfig(Configuration config,RaplaLocale locale) throws ParseDateException {
ArrayList<Timeslot> timeslots = null;
if ( config != null)
{
Calendar cal = locale.createCalendar();
SerializableDateTimeFormat format = locale.getSerializableFormat();
Configuration[] children = config.getChildren("timeslot");
if ( children.length > 0)
{
timeslots = new ArrayList<Timeslot>();
int i=0;
for (Configuration conf:children)
{
String name = conf.getAttribute("name","");
String time = conf.getAttribute("time",null);
int minuteOfDay;
if ( time == null)
{
time = i + ":00:00";
}
cal.setTime(format.parseTime( time));
int hour = cal.get(Calendar.HOUR_OF_DAY);
if ( i != 0)
{
minuteOfDay= hour * 60 + cal.get(Calendar.MINUTE);
}
else
{
minuteOfDay = 0;
}
if ( name == null)
{
name = format.formatTime( cal.getTime());
}
Timeslot slot = new Timeslot( name, minuteOfDay);
timeslots.add( slot);
i=hour+1;
}
}
}
return timeslots;
}
public static ArrayList<Timeslot> getDefaultTimeslots(RaplaLocale raplaLocale) {
ArrayList<Timeslot> timeslots = new ArrayList<Timeslot>();
Calendar cal = raplaLocale.createCalendar();
cal.setTime(DateTools.cutDate( new Date()));
for (int i = 0; i <=23; i++ ) {
int minuteOfDay = i * 60;
cal.set(Calendar.HOUR_OF_DAY, i);
String name =raplaLocale.formatTime( cal.getTime());
//String name = minuteOfDay / 60 + ":" + minuteOfDay%60;
Timeslot slot = new Timeslot(name, minuteOfDay);
timeslots.add(slot);
}
return timeslots;
}
public List<Timeslot> getTimeslots()
{
return timeslots;
}
}
| 04900db4-rob | src/org/rapla/plugin/timeslot/TimeslotProvider.java | Java | gpl3 | 3,611 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.timeslot;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import org.rapla.components.calendar.RaplaTime;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.util.ParseDateException;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.gui.DefaultPluginOption;
import org.rapla.gui.toolkit.RaplaButton;
public class TimeslotOption extends DefaultPluginOption
{
JPanel list = new JPanel();
List<Timeslot> timeslots;
class TimeslotRow
{
RaplaTime raplatime;
JTextField textfield = new JTextField();
RaplaButton delete = new RaplaButton(RaplaButton.SMALL);
public TimeslotRow(Timeslot slot)
{
addCopyPaste( textfield);
textfield.setText( slot.getName());
int minuteOfDay = slot.getMinuteOfDay();
int hour = minuteOfDay /60;
int minute = minuteOfDay %60;
RaplaLocale raplaLocale = getRaplaLocale();
raplatime = new RaplaTime(raplaLocale.getLocale(),raplaLocale.getTimeZone());
raplatime.setTime(hour, minute);
delete.setIcon(getIcon("icon.remove"));
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
rows.remove( TimeslotRow.this);
update();
}
});
}
}
public TimeslotOption(RaplaContext sm)
{
super(sm);
}
List<TimeslotRow> rows = new ArrayList<TimeslotOption.TimeslotRow>();
JPanel main;
protected JPanel createPanel() throws RaplaException
{
main = super.createPanel();
JScrollPane jScrollPane = new JScrollPane(list);
JPanel container = new JPanel();
container.setLayout( new BorderLayout());
container.add(jScrollPane,BorderLayout.CENTER);
JPanel header = new JPanel();
RaplaButton reset = new RaplaButton(RaplaButton.SMALL);
RaplaButton resetButton = reset;
resetButton.setIcon(getIcon("icon.remove"));
resetButton.setText(getString("reset"));
RaplaButton newButton = new RaplaButton(RaplaButton.SMALL);
newButton.setIcon(getIcon("icon.new"));
newButton.setText(getString("new"));
header.add( newButton);
header.add( resetButton );
newButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int minuteOfDay = 0;
String lastName = "";
Timeslot slot = new Timeslot(lastName, minuteOfDay);
rows.add( new TimeslotRow(slot));
update();
}
});
resetButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
timeslots = TimeslotProvider.getDefaultTimeslots(getRaplaLocale());
initRows();
update();
}
});
container.add(header,BorderLayout.NORTH);
main.add( container, BorderLayout.CENTER);
return main;
}
protected void initRows() {
rows.clear();
for ( Timeslot slot:timeslots)
{
TimeslotRow row = new TimeslotRow( slot);
rows.add( row);
}
TimeslotRow firstRow = rows.get(0);
firstRow.delete.setEnabled( false);
firstRow.raplatime.setEnabled( false);
list.removeAll();
}
protected void update() {
timeslots = mapToTimeslots();
list.removeAll();
TableLayout tableLayout = new TableLayout();
list.setLayout(tableLayout);
tableLayout.insertColumn(0,TableLayout.PREFERRED);
tableLayout.insertColumn(1,10);
tableLayout.insertColumn(2,TableLayout.PREFERRED);
tableLayout.insertColumn(3,10);
tableLayout.insertColumn(4,TableLayout.FILL);
list.setLayout( tableLayout);
tableLayout.insertRow(0, TableLayout.PREFERRED);
list.add(new JLabel("time"),"2,0");
list.add(new JLabel("name"),"4,0");
int i = 0;
for ( TimeslotRow row:rows)
{
tableLayout.insertRow(++i, TableLayout.MINIMUM);
list.add(row.delete,"0,"+i);
list.add(row.raplatime,"2,"+i);
list.add(row.textfield,"4,"+i);
}
list.validate();
list.repaint();
main.validate();
main.repaint();
}
protected void addChildren( DefaultConfiguration newConfig)
{
if (!activate.isSelected())
{
return;
}
for ( Timeslot slot: timeslots)
{
DefaultConfiguration conf = new DefaultConfiguration("timeslot");
conf.setAttribute("name", slot.getName());
int minuteOfDay = slot.getMinuteOfDay();
Calendar cal = getRaplaLocale().createCalendar();
cal.set(Calendar.HOUR_OF_DAY, minuteOfDay / 60);
cal.set(Calendar.MINUTE, minuteOfDay % 60);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
SerializableDateTimeFormat format = getRaplaLocale().getSerializableFormat();
String time = format.formatTime(cal.getTime());
conf.setAttribute("time", time);
newConfig.addChild( conf);
}
if ( getContext().has(TimeslotProvider.class))
{
try {
getService(TimeslotProvider.class).update( newConfig);
} catch (ParseDateException e) {
getLogger().error(e.getMessage());
}
}
}
protected List<Timeslot> mapToTimeslots() {
List<Timeslot> timeslots = new ArrayList<Timeslot>();
for ( TimeslotRow row: rows)
{
String name = row.textfield.getText();
RaplaTime raplatime = row.raplatime;
Date time = raplatime.getTime();
Calendar cal = getRaplaLocale().createCalendar();
if ( time != null )
{
cal.setTime( time);
int minuteOfDay = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
timeslots.add( new Timeslot( name, minuteOfDay));
}
}
Collections.sort( timeslots);
return timeslots;
}
protected void readConfig( Configuration config)
{
RaplaLocale raplaLocale = getRaplaLocale();
try {
timeslots = TimeslotProvider.parseConfig(config, raplaLocale);
} catch (ParseDateException e) {
}
if ( timeslots == null)
{
timeslots = TimeslotProvider.getDefaultTimeslots(raplaLocale);
}
initRows();
update();
}
public void show() throws RaplaException {
super.show();
}
public void commit() throws RaplaException {
timeslots = mapToTimeslots();
super.commit();
}
/**
* @see org.rapla.gui.DefaultPluginOption#getPluginClass()
*/
public Class<? extends PluginDescriptor<?>> getPluginClass() {
return TimeslotPlugin.class;
}
public String getName(Locale locale) {
return "Timeslot Plugin";
}
}
| 04900db4-rob | src/org/rapla/plugin/timeslot/TimeslotOption.java | Java | gpl3 | 8,120 |
package org.rapla.plugin.timeslot;
public class Timeslot implements Comparable<Timeslot>
{
String name;
int minuteOfDay;
public Timeslot(String name, int minuteOfDay)
{
this.name = name;
this.minuteOfDay = minuteOfDay;
}
public String getName() {
return name;
}
public int getMinuteOfDay() {
return minuteOfDay;
}
public int compareTo(Timeslot other) {
if ( minuteOfDay == other.minuteOfDay)
{
return name.compareTo( other.name);
}
return minuteOfDay < other.minuteOfDay ? -1 : 1;
}
public String toString()
{
return name + " " + (minuteOfDay / 60) +":" + (minuteOfDay % 60);
}
} | 04900db4-rob | src/org/rapla/plugin/timeslot/Timeslot.java | Java | gpl3 | 652 |
/**
*
*/
package org.rapla.servletpages;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.RaplaMainContainer;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.server.RaplaServerExtensionPoints;
public class RaplaIndexPageGenerator extends RaplaComponent implements RaplaPageGenerator
{
Collection<RaplaMenuGenerator> entries;
public RaplaIndexPageGenerator( RaplaContext context ) throws RaplaContextException
{
super( context);
entries = context.lookup(Container.class).lookupServicesFor( RaplaServerExtensionPoints.HTML_MAIN_MENU_EXTENSION_POINT);
}
public void generatePage( ServletContext context, HttpServletRequest request, HttpServletResponse response )
throws IOException, ServletException
{
if ( request.getParameter("page") == null && request.getRequestURI().endsWith("/rapla/"))
{
response.sendRedirect("../rapla");
}
response.setContentType("text/html; charset=ISO-8859-1");
java.io.PrintWriter out = response.getWriter();
String linkPrefix = request.getPathTranslated() != null ? "../": "";
out.println("<html>");
out.println(" <head>");
// add the link to the stylesheet for this page within the <head> tag
out.println(" <link REL=\"stylesheet\" href=\""+linkPrefix+"default.css\" type=\"text/css\">");
// tell the html page where its favourite icon is stored
out.println(" <link REL=\"shortcut icon\" type=\"image/x-icon\" href=\""+linkPrefix+"images/favicon.ico\">");
out.println(" <title>");
String title;
final String defaultTitle = getI18n().getString("rapla.title");
try {
title= getQuery().getSystemPreferences().getEntryAsString(RaplaMainContainer.TITLE, defaultTitle);
} catch (RaplaException e) {
title = defaultTitle;
}
out.println(title);
out.println(" </title>");
out.println(" </head>");
out.println(" <body>");
out.println(" <h3>");
out.println(title);
out.println(" </h3>");
generateMenu( request, out);
out.println(getI18n().getString("webinfo.text"));
out.println(" </body>");
out.println("</html>");
out.close();
}
public void generateMenu( HttpServletRequest request, PrintWriter out )
{
if ( entries.size() == 0)
{
return;
}
// out.println("<ul>");
// there is an ArraList of entries that wants to be part of the HTML
// menu we go through this ArraList,
for (Iterator<RaplaMenuGenerator> it = entries.iterator();it.hasNext();)
{
RaplaMenuGenerator entry = it.next();
out.println("<div class=\"menuEntry\">");
entry.generatePage( request, out );
out.println("</div>");
}
// out.println("</ul>");
}
} | 04900db4-rob | src/org/rapla/servletpages/RaplaIndexPageGenerator.java | Java | gpl3 | 3,266 |
/**
*
*/
package org.rapla.servletpages;
import java.io.IOException;
import java.util.Collection;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RaplaAppletPageGenerator implements RaplaPageGenerator{
private String getLibsApplet(ServletContext context) throws java.io.IOException {
StringBuffer buf = new StringBuffer();
Collection<String> files = RaplaJNLPPageGenerator.getClientLibs(context);
boolean first= true;
for (String file:files) {
if ( !first)
{
buf.append(", ");
}
else
{
first = false;
}
buf.append(file);
}
return buf.toString();
}
public void generatePage( ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws IOException {
String linkPrefix = request.getPathTranslated() != null ? "../": "";
response.setContentType("text/html; charset=ISO-8859-1");
java.io.PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println(" <title>Rapla Applet</title>");
out.println(" <link REL=\"stylesheet\" href=\""+linkPrefix+"default.css\" type=\"text/css\">");
out.println("</head>");
out.println("<body>");
out.println(" <applet code=\"org.rapla.client.MainApplet\" codebase=\".\" align=\"baseline\"");
out.println(" width=\"300\" height=\"300\" archive=\""+getLibsApplet(context)+"\" codebase_lookup=\"false\"");
out.println(" >");
out.println(" <param name=\"archive\" value=\""+getLibsApplet(context) +"\"/>");
out.println(" <param name=\"java_code\" value=\"org.rapla.client.MainApplet\"/>");
out.println(" <param name=\"java_codebase\" value=\"./\">");
out.println(" <param name=\"java_type\" value=\"application/x-java-applet;jpi-version=1.4.1\"/>");
out.println(" <param name=\"codebase_lookup\" value=\"false\"/>");
out.println(" <param name=\"scriptable\" value=\"true\"/>");
out.println(" No Java support for APPLET tags please install java plugin for your browser!!");
out.println(" </applet>");
out.println("</body>");
out.println("</html>");
out.close();
}
} | 04900db4-rob | src/org/rapla/servletpages/RaplaAppletPageGenerator.java | Java | gpl3 | 2,430 |
package org.rapla.servletpages;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RaplaStorePage implements RaplaPageGenerator
{
public void generatePage(
ServletContext context,
HttpServletRequest request,
HttpServletResponse response ) throws IOException, ServletException
{
String storeString = request.getParameter("storeString");
PrintWriter writer = response.getWriter();
writer.println("<form method=\"POST\" action=\"\">");
writer.println("<input name=\"storeString\" value=\"" + storeString+"\"/>");
writer.println("<button type=\"submit\">Store</button>");
writer.println("</form>");
writer.close();
}
}
| 04900db4-rob | src/org/rapla/servletpages/RaplaStorePage.java | Java | gpl3 | 901 |