code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*--------------------------------------------------------------------------*
| 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";
}
}
| Java |
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");
}
| Java |
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);
} | Java |
/*--------------------------------------------------------------------------*
| 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>
{
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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);
}
}
}
}
} | Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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 ));
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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";
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.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;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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;
}
}
| Java |
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;
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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();
}
}
| Java |
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";
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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);
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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;
}
};
}
}
| Java |
/*
* ====================================================================
* 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;
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.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);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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());
}
}
}
| Java |
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;
}
| Java |
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");
}
}
};
}
}
| Java |
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;
}
} | Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.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);
}
}
| Java |
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);
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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";
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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";
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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 );
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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 );
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.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());
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.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;
}
}
| Java |
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;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.plugin.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";
}
}
| Java |
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);
}
} | Java |
/**
*
*/
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>");
}
} | Java |
/**
*
*/
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();
}
} | Java |
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();
}
}
| Java |
package org.rapla.servletpages;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
public interface RaplaMenuGenerator {
public void generatePage( HttpServletRequest request, PrintWriter out );
}
| Java |
/**
*
*/
package org.rapla.servletpages;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.components.util.IOUtil;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
public class RaplaStatusPageGenerator implements RaplaPageGenerator{
I18nBundle m_i18n;
public RaplaStatusPageGenerator(RaplaContext context) throws RaplaContextException {
m_i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
}
public void generatePage( ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws IOException {
response.setContentType("text/html; charset=ISO-8859-1");
String linkPrefix = request.getPathTranslated() != null ? "../": "";
java.io.PrintWriter out = response.getWriter();
out.println( "<html>" );
out.println( "<head>" );
out.println(" <link REL=\"stylesheet\" href=\"" + linkPrefix + "default.css\" type=\"text/css\">");
out.println(" <title>Rapla Server status!</title>");
out.println("</head>" );
out.println( "<body>" );
boolean isSigned = IOUtil.isSigned();
String signed = m_i18n.getString( isSigned ? "yes": "no");
String javaversion = System.getProperty("java.version");
out.println( "<p>Server running </p>" + m_i18n.format("info.text", signed, javaversion));
out.println( "<hr>" );
out.println( "</body>" );
out.println( "</html>" );
out.close();
}
} | Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.servletpages;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* You can add arbitrary serlvet pages to your rapla webapp.
*
*/
public interface RaplaPageGenerator
{
void generatePage( ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException;
}
| Java |
package org.rapla.servletpages;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
/**
* User: kuestermann
* Date: 15.08.12
* Time: 19:24
*/
public interface ServletRequestPreprocessor {
/**
* will return request handle to service
*
* @param context
* @param servletContext
* @param request
* @return null values will be ignored, otherwise return object will be used for further processing
*/
HttpServletRequest handleRequest(RaplaContext context, ServletContext servletContext, HttpServletRequest request,HttpServletResponse response) throws RaplaException;
}
| Java |
package org.rapla.servletpages;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
public class DefaultHTMLMenuEntry extends RaplaComponent implements RaplaMenuGenerator
{
protected String name;
protected String linkName;
public DefaultHTMLMenuEntry(RaplaContext context,String name, String linkName)
{
super( context);
this.name = name;
this.linkName = linkName;
}
public DefaultHTMLMenuEntry(RaplaContext context)
{
super( context);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLinkName() {
return linkName;
}
public void setLinkName(String linkName) {
this.linkName = linkName;
}
public void generatePage( HttpServletRequest request, PrintWriter out )
{
// writing the html code line for a button
// including the link to the appropriate servletpage
out.println("<span class=\"button\"><a href=\"" + getLinkName() + "\">" + getName() + "</a></span>");
}
}
| Java |
/**
*
*/
package org.rapla.servletpages;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.RaplaMainContainer;
import org.rapla.components.util.IOUtil;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class RaplaJNLPPageGenerator extends RaplaComponent implements RaplaPageGenerator{
public RaplaJNLPPageGenerator( RaplaContext context )
{
super( context);
}
private String getCodebase( HttpServletRequest request) {
StringBuffer codebaseBuffer = new StringBuffer();
String forwardProto = request.getHeader("X-Forwarded-Proto");
boolean secure = (forwardProto != null && forwardProto.toLowerCase().equals("https")) || request.isSecure();
codebaseBuffer.append(secure ? "https://" : "http://");
codebaseBuffer.append(request.getServerName());
if (request.getServerPort() != (!secure ? 80 : 443))
{
codebaseBuffer.append(':');
codebaseBuffer.append(request.getServerPort());
}
codebaseBuffer.append(request.getContextPath());
codebaseBuffer.append('/');
return codebaseBuffer.toString();
}
private String getLibsJNLP(ServletContext context, String webstartRoot) throws java.io.IOException {
List<String> list = getClientLibs(context);
StringBuffer buf = new StringBuffer();
for (String file:list) {
buf.append("\n<jar href=\""+webstartRoot + "/");
buf.append(file);
buf.append("\"");
if (file.equals("raplaclient.jar")) {
buf.append(" main=\"true\"");
}
buf.append("/>");
}
return buf.toString();
}
public static List<String> getClientLibs(ServletContext context)
throws IOException {
List<String> list = new ArrayList<String>();
URL resource = RaplaJNLPPageGenerator.class.getResource("/clientlibs.properties");
if (resource != null)
{
byte[] bytes = IOUtil.readBytes( resource);
String string = new String( bytes);
String[] split = string.split(";");
for ( String file:split)
{
list.add( "webclient/" + file);
}
}
else
{
String base = context.getRealPath(".");
if ( base != null)
{
java.io.File baseFile = new java.io.File(base);
java.io.File[] files = IOUtil.getJarFiles(base,"webclient");
for (File file:files) {
String relativeURL = IOUtil.getRelativeURL(baseFile,file);
list.add( relativeURL);
}
}
}
return list;
}
protected List<String> getProgramArguments() {
List<String> list = new ArrayList<String>();
return list;
}
public void generatePage( ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws IOException {
java.io.PrintWriter out = response.getWriter();
String webstartRoot = ".";
long currentTimeMillis = System.currentTimeMillis();
response.setDateHeader("Last-Modified",currentTimeMillis);
response.addDateHeader("Expires", 0);
response.addDateHeader("Date", currentTimeMillis);
response.setHeader("Cache-Control", "no-cache");
final String defaultTitle = getI18n().getString("rapla.title");
String menuName;
try
{
menuName= getQuery().getSystemPreferences().getEntryAsString(RaplaMainContainer.TITLE, defaultTitle);
}
catch (RaplaException e) {
menuName = defaultTitle;
}
response.setContentType("application/x-java-jnlp-file;charset=utf-8");
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
out.println("<jnlp spec=\"1.0+\" codebase=\"" + getCodebase(request) + "\">");
out.println("<information>");
out.println(" <title>"+menuName+"</title>");
out.println(" <vendor>Rapla team</vendor>");
out.println(" <homepage href=\"http://code.google.com/p/rapla/\"/>");
out.println(" <description>Resource Scheduling Application</description>");
// we changed the logo from .gif to .png to make it more sexy
//differentiate between icon and splash because of different sizes!
out.println(" <icon kind=\"default\" href=\""+webstartRoot+"/webclient/rapla_64x64.png\" width=\"64\" height=\"64\"/> ");
out.println(" <icon kind=\"desktop\" href=\""+webstartRoot+"/webclient/rapla_128x128.png\" width=\"128\" height=\"128\"/> ");
out.println(" <icon kind=\"shortcut\" href=\""+webstartRoot+"/webclient/rapla_64x64.png\" width=\"64\" height=\"64\"/> ");
// and here aswell
out.println(" <icon kind=\"splash\" href=\""+webstartRoot+ "/webclient/logo.png\"/> ");
out.println(" <update check=\"always\" policy=\"always\"/>");
out.println(" <shortcut online=\"true\">");
out.println(" <desktop/>");
out.println(" <menu submenu=\"" + menuName + "\"/>");
out.println(" </shortcut>");
out.println("</information>");
boolean allpermissionsAllowed = IOUtil.isSigned();
final String parameter = request.getParameter("sandbox");
if (allpermissionsAllowed && (parameter== null || parameter.trim().toLowerCase().equals("false")))
{
out.println("<security>");
out.println(" <all-permissions/>");
out.println("</security>");
}
out.println("<resources>");
out.println(" <j2se version=\"1.4+\"/>");
out.println(getLibsJNLP(context, webstartRoot));
out.println("</resources>");
out.println("<application-desc main-class=\"org.rapla.client.MainWebstart\">");
for (Iterator<String> it = getProgramArguments().iterator(); it.hasNext();)
{
out.println(" <argument>" + it.next() + "</argument> ");
}
out.println("</application-desc>");
out.println("</jnlp>");
out.close();
}
} | Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.rapla.entities.Category;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaException;
/** Methods for quering the various entities of the backend
*/
public interface QueryModule
{
/** returns all DynamicTypes matching the specified classification
possible keys are reservation, person and resource.
@see org.rapla.entities.dynamictype.DynamicTypeAnnotations
*/
DynamicType[] getDynamicTypes(String classificationType) throws RaplaException;
/** returns the DynamicType with the passed elementKey */
DynamicType getDynamicType(String elementKey) throws RaplaException;
/** returns The root category. */
Category getSuperCategory();
/** returns The category that contains all the user-groups of rapla */
Category getUserGroupsCategory() throws RaplaException;
/** returns all users */
User[] getUsers() throws RaplaException;
/** returns the user with the specified username */
User getUser(String username) throws RaplaException;
/** returns all allocatables that match the passed ClassificationFilter. If null all readable allocatables are returned*/
Allocatable[] getAllocatables(ClassificationFilter[] filters) throws RaplaException;
/** returns all readable allocatables, same as getAllocatables(null)*/
Allocatable[] getAllocatables() throws RaplaException;
/** returns the reservations of the specified user in the specified interval
@param user A user-object or null for all users
@param start only reservations beginning after the start-date will be returned (can be null).
@param end only reservations beginning before the end-date will be returned (can be null).
@param filters you can specify classificationfilters or null for all reservations .
*/
Reservation[] getReservations(User user,Date start,Date end,ClassificationFilter[] filters) throws RaplaException;
/**returns all reservations that have allocated at least one Resource or Person that is part of the allocatables array.
@param allocatables only reservations that allocate at least on element of this array will be returned.
@param start only reservations beginning after the start-date will be returned (can be null).
@param end only reservations beginning before the end-date will be returned (can be null).
**/
Reservation[] getReservations(Allocatable[] allocatables,Date start,Date end) throws RaplaException;
Reservation[] getReservationsForAllocatable(Allocatable[] allocatables, Date start,Date end,ClassificationFilter[] filters) throws RaplaException;
List<Reservation> getReservations(Collection<Conflict> conflicts) throws RaplaException;
/** returns all available periods */
Period[] getPeriods() throws RaplaException;
/** returns an Interface for accessing the periods
* @throws RaplaException */
PeriodModel getPeriodModel() throws RaplaException;
/** returns the current date in GMT+0 Timezone. If rapla operates
in multi-user mode, the date should be calculated from the
server date.
*/
Date today();
/** returns all allocatables from the set of passed allocatables, that are already allocated by different parallel reservations at the time-slices, that are described by the appointment */
public Map<Allocatable, Collection<Appointment>> getAllocatableBindings(Collection<Allocatable> allocatables,Collection<Appointment> forAppointment) throws RaplaException;
/** returns all allocatables, that are already allocated by different parallel reservations at the time-slices, that are described by the appointment
* @deprecated use {@link #getAllocatableBindings(Collection,Collection)} instead
* */
@Deprecated
Allocatable[] getAllocatableBindings(Appointment appointment) throws RaplaException;
/** returns all existing conflicts with the reservation */
Conflict[] getConflicts(Reservation reservation) throws RaplaException;
/** returns all existing conflicts that are visible for the user
conflicts
*/
Conflict[] getConflicts() throws RaplaException;
/** returns if the user has the permissions to change/create an
allocation on the passed appointment. Changes of an
existing appointment that are in an permisable
timeframe are allowed. Example: The extension of an exisiting appointment,
doesn't affect allocations in the past and should not create a
conflict with the permissions.
*/
//boolean hasPermissionToAllocate( Appointment appointment, Allocatable allocatable );
/** returns the preferences for the passed user, must be admin todo this. creates a new prefence object if not set*/
Preferences getPreferences(User user) throws RaplaException;
/** returns the preferences for the passed user, must be admin todo this.*/
Preferences getPreferences(User user, boolean createIfNotNull) throws RaplaException;
/** returns the preferences for the login user */
Preferences getPreferences() throws RaplaException;
Preferences getSystemPreferences() throws RaplaException;
/** returns if the user is allowed to exchange the allocatables of this reservation. A user can do it if he has
* at least admin privileges for one allocatable. He can only exchange or remove or insert allocatables he has admin privileges on.
* The User cannot change appointments.*/
boolean canExchangeAllocatables(Reservation reservation);
boolean canReadReservationsFromOthers(User user);
boolean canCreateReservations(User user);
boolean canEditTemplats(User user);
public Collection<String> getTemplateNames() throws RaplaException;
public Collection<Reservation> getTemplateReservations(String name) throws RaplaException;
Date getNextAllocatableDate(Collection<Allocatable> asList, Appointment appointment, CalendarOptions options) throws RaplaException;
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import org.rapla.ConnectInfo;
import org.rapla.entities.User;
import org.rapla.framework.RaplaException;
/** Encapsulates the methods responsible for authentification.
*/
public interface UserModule {
/** The login method establishes the connection and loads data.
* @return false on an invalid login.
* @throws RaplaException if the connection can't be established.
*/
boolean login(String username,char[] password) throws RaplaException;
boolean login(ConnectInfo connectInfo) throws RaplaException;
/** logout of the current user */
void logout() throws RaplaException;
/** returns if a session is active. True between a successful login and logout. */
boolean isSessionActive();
/** throws an Exception if no user has loged in.
@return the user that has loged in. */
User getUser() throws RaplaException;
void changePassword(User user,char[] oldPassword,char[] newPassword) throws RaplaException;
boolean canChangePassword();
/** changes the name for the logged in user. If a person is connected then all three fields are used. Otherwise only lastname is used*/
void changeName(String title, String firstname, String surname) throws RaplaException;
void confirmEmail(String newEmail) throws RaplaException;
/** changes the name for the user that is logged in. */
void changeEmail(String newEmail) throws RaplaException;
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.User;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.RepeatingType;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaException;
/** All methods that allow modifing the entity-objects.
*/
public interface ModificationModule {
/** check if the reservation can be saved */
void checkReservation(Reservation reservation) throws RaplaException;
/** creates a new Rapla Map. Keep in mind that only RaplaObjects and Strings are allowed as entries for a RaplaMap!*/
<T> RaplaMap<T> newRaplaMap( Map<String,T> map);
/** creates an ordered RaplaMap with the entries of the collection as values and their position in the collection from 1..n as keys*/
<T> RaplaMap<T> newRaplaMap( Collection<T> col);
CalendarSelectionModel newCalendarModel( User user) throws RaplaException;
/** Creates a new event, Creates a new event from the first dynamic type found, basically a shortcut to newReservation(getDynamicType(VALUE_CLASSIFICATION_TYPE_RESERVATION)[0].newClassification())
* This is a convenience method for testing.
*/
Reservation newReservation() throws RaplaException;
/** Shortcut for newReservation(classification,getUser()*/
Reservation newReservation(Classification classification) throws RaplaException;
/** Creates a new reservation from the classifcation object and with the passed user as its owner
* You can create a new classification from a {@link DynamicType} with newClassification method.
* @see DynamicType#newClassification()
*/
Reservation newReservation(Classification classification,User user) throws RaplaException;
Appointment newAppointment(Date startDate,Date endDate) throws RaplaException;
Appointment newAppointment(Date startDate,Date endDate, User user) throws RaplaException;
/** @deprecated use newAppointment and change the repeating type of the appointment afterwards*/
Appointment newAppointment(Date startDate,Date endDate, RepeatingType repeatingType, int repeatingDuration) throws RaplaException;
/** Creates a new resource from the first dynamic type found, basically a shortcut to newAlloctable(getDynamicType(VALUE_CLASSIFICATION_TYPE_RESOURCE)[0].newClassification()).
* This is a convenience method for testing.
* */
Allocatable newResource() throws RaplaException;
/** Creates a new person resource, Creates a new resource from the first dynamic type found, basically a shortcut to newAlloctable(getDynamicType(VALUE_CLASSIFICATION_TYPE_PERSON)[0].newClassification())
* This is a convenience method for testing.
*/
Allocatable newPerson() throws RaplaException;
/** Creates a new allocatable from the classifcation object and with the passed user as its owner
* You can create a new classification from a {@link DynamicType} with newClassification method.
* @see DynamicType#newClassification()*/
Allocatable newAllocatable( Classification classification, User user) throws RaplaException;
/** Shortcut for newAllocatble(classification,getUser()*/
Allocatable newAllocatable( Classification classification) throws RaplaException;
Allocatable newPeriod() throws RaplaException;
Category newCategory() throws RaplaException;
Attribute newAttribute(AttributeType attributeType) throws RaplaException;
DynamicType newDynamicType(String classificationType) throws RaplaException;
User newUser() throws RaplaException;
/** Clones an entity. The entities will get new identifier and
won't be equal to the original. The resulting object is not persistant and therefore
can be editet.
*/
<T extends Entity> T clone(T obj) throws RaplaException;
/** This call will be delegated to the {@link org.rapla.storage.StorageOperator}. It
* returns an editable working copy of an object. Only objects return by this method and new objects are editable.
* To get the persistant, non-editable version of a working copy use {@link #getPersistant} */
<T extends Entity> T edit(T obj) throws RaplaException;
<T extends Entity> Collection<T> edit(Collection<T> list) throws RaplaException;
/** Returns the persistant version of a working copy.
* Throws an {@link org.rapla.entities.EntityNotFoundException} when the
* object is not found
* @see #edit
* @see #clone
*/
<T extends Entity> T getPersistant(T working) throws RaplaException;
<T extends Entity> Map<T,T> getPersistant(Collection<T> list) throws RaplaException;
/** This call will be delegated to the {@link org.rapla.storage.StorageOperator} */
void storeObjects(Entity<?>[] obj) throws RaplaException;
/** @see #storeObjects(Entity[]) */
void store(Entity<?> obj) throws RaplaException;
/** This call will be delegated to the {@link org.rapla.storage.StorageOperator} */
void removeObjects(Entity<?>[] obj) throws RaplaException;
/** @see #removeObjects(Entity[]) */
void remove(Entity<?> obj) throws RaplaException;
/** stores and removes objects in the one transaction
* @throws RaplaException */
void storeAndRemove( Entity<?>[] storedObjects, Entity<?>[] removedObjects) throws RaplaException;
void setTemplateName(String templateName);
String getTemplateName();
CommandHistory getCommandHistory();
}
| Java |
package org.rapla.facade;
import org.rapla.framework.RaplaException;
public class CalendarNotFoundExeption extends RaplaException {
public CalendarNotFoundExeption(String text) {
super(text);
}
private static final long serialVersionUID = 1L;
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.rapla.components.util.Assert;
import org.rapla.entities.Entity;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.internal.PeriodImpl;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.facade.PeriodModel;
import org.rapla.facade.QueryModule;
import org.rapla.framework.RaplaException;
import org.rapla.storage.StorageOperator;
class PeriodModelImpl implements PeriodModel,ModificationListener
{
TreeSet<Period> m_periods = new TreeSet<Period>(new Comparator<Period>() {
public int compare(Period o1, Period o2) {
int compareTo = o1.compareTo(o2);
return -compareTo;
}
}
);
ClientFacade facade;
Period defaultPeriod;
PeriodModelImpl( ClientFacade query ) throws RaplaException {
this.facade = query;
update();
}
public void update() throws RaplaException {
m_periods.clear();
DynamicType type = facade.getDynamicType(StorageOperator.PERIOD_TYPE);
ClassificationFilter[] filters = type.newClassificationFilter().toArray();
Collection<Allocatable> allocatables = facade.getOperator().getAllocatables( filters);
for ( Allocatable alloc:allocatables)
{
Classification classification = alloc.getClassification();
String name = (String)classification.getValue("name");
Date start = (Date) classification.getValue("start");
Date end = (Date) classification.getValue("end");
PeriodImpl period = new PeriodImpl(name,start,end);
m_periods.add(period);
}
}
public void dataChanged(ModificationEvent evt) throws RaplaException
{
if (isPeriodModified(evt))
{
update();
}
}
protected boolean isPeriodModified(ModificationEvent evt) {
for (Entity changed:evt.getChanged())
{
if ( isPeriod( changed))
{
return true;
}
}
for (Entity changed:evt.getRemoved())
{
if ( isPeriod( changed))
{
return true;
}
}
return false;
}
private boolean isPeriod(Entity entity) {
if ( entity.getRaplaType() != Allocatable.TYPE)
{
return false;
}
Allocatable alloc = (Allocatable) entity;
Classification classification = alloc.getClassification();
if ( classification == null)
{
return false;
}
if (!classification.getType().getKey().equals(StorageOperator.PERIOD_TYPE))
{
return false;
}
return true;
}
protected QueryModule getQuery() {
return facade;
}
/** returns the first matching period or null if no period matches.*/
public Period getPeriodFor(Date date) {
if (date == null)
return null;
PeriodImpl comparePeriod = new PeriodImpl("DUMMY",date,date);
Iterator<Period> it = m_periods.tailSet(comparePeriod).iterator();
while (it.hasNext()) {
Period period = it.next();
if (period.contains(date)) {
return period;
}
}
return null;
}
static private long diff(Date d1,Date d2) {
long diff = d1.getTime()-d2.getTime();
if (diff<0)
diff = diff * -1;
return diff;
}
public Period getNearestPeriodForDate(Date date) {
return getNearestPeriodForStartDate( m_periods, date, null);
}
public Period getNearestPeriodForStartDate(Date date) {
return getNearestPeriodForStartDate( date, null);
}
public Period getNearestPeriodForStartDate(Date date, Date endDate) {
return getNearestPeriodForStartDate( getPeriodsFor( date ), date, endDate);
}
public Period getNearestPeriodForEndDate(Date date) {
return getNearestPeriodForEndDate( getPeriodsFor( date ), date);
}
static private Period getNearestPeriodForStartDate(Collection<Period> periodList, Date date, Date endDate) {
Period result = null;
long min_from_start=Long.MAX_VALUE, min_from_end=0;
long from_start, from_end=0;
Iterator<Period> it = periodList.iterator();
while (it.hasNext())
{
Period period = it.next();
if ( period == null)
{ // EXCO: Why this test ?
continue;
}
from_start = diff(period.getStart(),date);
if ( endDate != null )
{
from_end = Math.abs(diff(period.getEnd(), endDate));
}
if ( from_start < min_from_start
|| (from_start == min_from_start && from_end < min_from_end)
)
{
min_from_start = from_start;
min_from_end = from_end;
result = period;
}
}
return result;
}
static private Period getNearestPeriodForEndDate(Collection<Period> periodList, Date date) {
Period result = null;
long min=-1;
Iterator<Period> it = periodList.iterator();
while (it.hasNext()) {
Period period = it.next();
if (min == -1) {
min = diff(period.getEnd(),date);
result = period;
}
if (diff(period.getEnd(),date) < min) {
min = diff(period.getStart(),date);
result = period;
}
}
return result;
}
/** return all matching periods.*/
public List<Period> getPeriodsFor(Date date) {
ArrayList<Period> list = new ArrayList<Period>();
if (date == null)
return list;
PeriodImpl comparePeriod = new PeriodImpl("DUMMY",date,date);
SortedSet<Period> set = m_periods.tailSet(comparePeriod);
Iterator<Period> it = set.iterator();
while (it.hasNext()) {
Period period = it.next();
//System.out.println(m_periods[i].getStart() + " - " + m_periods[i].getEnd());
if (period.contains(date)) {
list.add( period );
}
}
return list;
}
public int getSize() {
Assert.notNull(m_periods,"Componenet not setup!");
return m_periods.size();
}
public Period[] getAllPeriods() {
Period[] sortedPriods = m_periods.toArray( Period.PERIOD_ARRAY);
return sortedPriods;
}
public Object getElementAt(int index) {
Assert.notNull(m_periods,"Componenet not setup!");
Iterator<Period> it = m_periods.iterator();
for (int i=0;it.hasNext();i++) {
Object obj = it.next();
if (i == index)
return obj;
}
return null;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade.internal;
import static org.rapla.entities.configuration.CalendarModelConfiguration.EXPORT_ENTRY;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.rapla.components.util.Assert;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.IllegalAnnotationException;
import org.rapla.entities.Named;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.configuration.CalendarModelConfiguration;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.configuration.internal.CalendarModelConfigurationImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.AppointmentBlockStartComparator;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.entities.dynamictype.internal.ParsedText;
import org.rapla.entities.dynamictype.internal.ParsedText.EvalContext;
import org.rapla.entities.dynamictype.internal.ParsedText.Function;
import org.rapla.entities.dynamictype.internal.ParsedText.ParseContext;
import org.rapla.entities.storage.CannotExistWithoutTypeException;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarNotFoundExeption;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.Conflict;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.storage.UpdateResult;
public class CalendarModelImpl implements CalendarSelectionModel
{
private static final String DEFAULT_VIEW = "week";//WeekViewFactory.WEEK_VIEW;
private static final String ICAL_EXPORT_ENABLED = "org.rapla.plugin.export2ical"+ ".selected";
private static final String HTML_EXPORT_ENABLED = EXPORT_ENTRY + ".selected";
Date startDate;
Date endDate;
Date selectedDate;
List<RaplaObject> selectedObjects = new ArrayList<RaplaObject>();
String title;
ClientFacade m_facade;
String selectedView;
I18nBundle i18n;
RaplaContext context;
RaplaLocale raplaLocale;
User user;
Map<String,String> optionMap = new HashMap<String,String>();
//Map<String,String> viewOptionMap = new HashMap<String,String>();
boolean defaultEventTypes = true;
boolean defaultResourceTypes = true;
Collection<TimeInterval> timeIntervals = Collections.emptyList();
Collection<Allocatable> markedAllocatables = Collections.emptyList();
Map<DynamicType,ClassificationFilter> reservationFilter = new LinkedHashMap<DynamicType, ClassificationFilter>();
Map<DynamicType,ClassificationFilter> allocatableFilter = new LinkedHashMap<DynamicType, ClassificationFilter>();
public static final RaplaConfiguration ALLOCATABLES_ROOT = new RaplaConfiguration("rootnode", "allocatables");
public CalendarModelImpl(RaplaContext context, User user, ClientFacade facade) throws RaplaException {
this.context = context;
this.raplaLocale =context.lookup(RaplaLocale.class);
i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
m_facade = facade;
if ( user == null && m_facade.isSessionActive()) {
user = m_facade.getUser();
}
Date today = m_facade.today();
setSelectedDate( today);
setStartDate( today);
setEndDate( DateTools.addYear(getStartDate()));
DynamicType[] types = m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE);
if ( types.length == 0 ) {
types = m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON);
}
setSelectedObjects( Collections.singletonList( types[0]) );
setViewId( DEFAULT_VIEW);
this.user = user;
if ( user != null && !user.isAdmin()) {
boolean selected = m_facade.getSystemPreferences().getEntryAsBoolean( CalendarModel.ONLY_MY_EVENTS_DEFAULT, true);
optionMap.put( CalendarModel.ONLY_MY_EVENTS, selected ? "true" : "false");
}
optionMap.put( CalendarModel.SAVE_SELECTED_DATE, "false");
resetExports();
}
public void resetExports()
{
setTitle(null);
setOption( CalendarModel.SHOW_NAVIGATION_ENTRY, "true");
setOption(HTML_EXPORT_ENABLED, "false");
setOption(ICAL_EXPORT_ENABLED, "false");
}
public boolean isMatchingSelectionAndFilter( Appointment appointment) throws RaplaException
{
Reservation reservation = appointment.getReservation();
if ( reservation == null)
{
return false;
}
Allocatable[] allocatables = reservation.getAllocatablesFor(appointment);
HashSet<RaplaObject> hashSet = new HashSet<RaplaObject>( Arrays.asList(allocatables));
Collection<RaplaObject> selectedObjectsAndChildren = getSelectedObjectsAndChildren();
hashSet.retainAll( selectedObjectsAndChildren);
boolean matchesAllotables = hashSet.size() != 0;
if ( !matchesAllotables)
{
return false;
}
Classification classification = reservation.getClassification();
if ( isDefaultEventTypes())
{
return true;
}
ClassificationFilter[] reservationFilter = getReservationFilter();
for ( ClassificationFilter filter:reservationFilter)
{
if (filter.matches(classification))
{
return true;
}
}
return false;
}
public boolean setConfiguration(CalendarModelConfiguration config, final Map<String,String> alternativOptions) throws RaplaException {
ArrayList<RaplaObject> selectedObjects = new ArrayList<RaplaObject>();
allocatableFilter.clear();
reservationFilter.clear();
if ( config == null)
{
defaultEventTypes = true;
defaultResourceTypes = true;
DynamicType type =null;
{
DynamicType[] dynamicTypes = m_facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE);
if ( dynamicTypes.length > 0)
{
type = dynamicTypes[0];
}
}
if ( type == null)
{
DynamicType[] dynamicTypes = m_facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON);
if ( dynamicTypes.length > 0)
{
type = dynamicTypes[0];
}
}
if ( type != null)
{
setSelectedObjects( Collections.singletonList(type));
}
return true;
}
else
{
defaultEventTypes = config.isDefaultEventTypes();
defaultResourceTypes = config.isDefaultResourceTypes();
}
boolean couldResolveAllEntities = true;
// get filter
title = config.getTitle();
selectedView = config.getView();
//selectedObjects
optionMap = new TreeMap<String,String>();
// viewOptionMap = new TreeMap<String,String>();
if ( config.getOptionMap() != null)
{
Map<String,String> configOptions = config.getOptionMap();
addOptions(configOptions);
}
if (alternativOptions != null )
{
addOptions(alternativOptions);
}
final String saveDate = optionMap.get( CalendarModel.SAVE_SELECTED_DATE);
if ( config.getSelectedDate() != null && (saveDate == null || saveDate.equals("true"))) {
setSelectedDate( config.getSelectedDate() );
}
else
{
setSelectedDate( m_facade.today());
}
if ( config.getStartDate() != null) {
setStartDate( config.getStartDate() );
}
else
{
setStartDate( m_facade.today());
}
if ( config.getEndDate() != null && (saveDate == null || saveDate.equals("true"))) {
setEndDate( config.getEndDate() );
}
else
{
setEndDate( DateTools.addYear(getStartDate()));
}
selectedObjects.addAll( config.getSelected());
if ( config.isResourceRootSelected())
{
selectedObjects.add( ALLOCATABLES_ROOT);
}
Set<User> selectedUsers = getSelected(User.TYPE);
User currentUser = getUser();
if (currentUser != null && selectedUsers.size() == 1 && selectedUsers.iterator().next().equals( currentUser))
{
if ( getOption( CalendarModel.ONLY_MY_EVENTS) == null)
{
setOption( CalendarModel.ONLY_MY_EVENTS, "true");
selectedObjects.remove( currentUser);
}
}
setSelectedObjects( selectedObjects );
for ( ClassificationFilter f:config.getFilter())
{
final DynamicType type = f.getType();
final String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
boolean eventType = annotation != null &&annotation.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
Map<DynamicType,ClassificationFilter> map = eventType ? reservationFilter : allocatableFilter;
map.put(type, f);
}
return couldResolveAllEntities;
}
protected void addOptions(Map<String,String> configOptions) {
for (Map.Entry<String, String> entry:configOptions.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
optionMap.put( key, value);
}
}
public User getUser() {
return user;
}
public CalendarModelConfigurationImpl createConfiguration() throws RaplaException {
ClassificationFilter[] allocatableFilter = isDefaultResourceTypes() ? null : getAllocatableFilter();
ClassificationFilter[] eventFilter = isDefaultEventTypes() ? null : getReservationFilter();
return createConfiguration(allocatableFilter, eventFilter);
}
CalendarModelConfigurationImpl beforeTemplateConf;
public void dataChanged(ModificationEvent evt) throws RaplaException
{
Collection<RaplaObject> selectedObjects = getSelectedObjects();
if ( evt == null)
{
return;
}
boolean switchTemplate = ((UpdateResult)evt).isSwitchTemplateMode();
if (switchTemplate)
{
boolean changeToTemplate= m_facade.getTemplateName() != null;
if (changeToTemplate)
{
beforeTemplateConf = createConfiguration();
setSelectedObjects(Collections.singleton(ALLOCATABLES_ROOT));
}
else if ( beforeTemplateConf != null)
{
setConfiguration( beforeTemplateConf, null);
beforeTemplateConf = null;
}
}
{
Collection<RaplaObject> newSelection = new ArrayList<RaplaObject>();
boolean changed = false;
for ( RaplaObject obj: selectedObjects)
{
if ( obj instanceof Entity)
{
if (!evt.isRemoved((Entity) obj))
{
newSelection.add( obj);
}
else
{
changed = true;
}
}
}
if ( changed)
{
setSelectedObjects( newSelection);
}
}
{
if (evt.isModified( DynamicType.TYPE) || evt.isModified( Category.TYPE) || evt.isModified( User.TYPE))
{
CalendarModelConfigurationImpl config = (CalendarModelConfigurationImpl)createConfiguration();
updateConfig(evt, config);
if ( beforeTemplateConf != null)
{
updateConfig(evt, beforeTemplateConf);
}
setConfiguration( config, null);
}
}
}
public void updateConfig(ModificationEvent evt, CalendarModelConfigurationImpl config) throws CannotExistWithoutTypeException {
User user2 = getUser();
if ( user2 != null && evt.isModified( user2))
{
Set<User> changed = RaplaType.retainObjects(evt.getChanged(), Collections.singleton(user2));
if ( changed.size() > 0)
{
User newUser = changed.iterator().next();
user = newUser;
}
}
for ( RaplaObject obj:evt.getChanged())
{
if ( obj.getRaplaType() == DynamicType.TYPE)
{
DynamicType type = (DynamicType) obj;
if ( config.needsChange(type))
{
config.commitChange( type);
}
}
}
for ( RaplaObject obj:evt.getRemoved())
{
if ( obj.getRaplaType() == DynamicType.TYPE)
{
DynamicType type = (DynamicType) obj;
config.commitRemove( type);
}
}
}
private CalendarModelConfigurationImpl createConfiguration(ClassificationFilter[] allocatableFilter, ClassificationFilter[] eventFilter) throws RaplaException {
String viewName = selectedView;
Set<Entity> selected = new HashSet<Entity>( );
Collection<RaplaObject> selectedObjects = getSelectedObjects();
for (RaplaObject object:selectedObjects) {
if ( !(object instanceof Conflict) && (object instanceof Entity))
{
// throw new RaplaException("Storing the conflict view is not possible with Rapla.");
selected.add( (Entity) object );
}
}
final Date selectedDate = getSelectedDate();
final Date startDate = getStartDate();
final Date endDate = getEndDate();
boolean resourceRootSelected = selectedObjects.contains( ALLOCATABLES_ROOT);
return newRaplaCalendarModel( selected,resourceRootSelected, allocatableFilter,eventFilter, title, startDate, endDate, selectedDate, viewName, optionMap);
}
public CalendarModelConfigurationImpl newRaplaCalendarModel(Collection<Entity> selected,
boolean resourceRootSelected,
ClassificationFilter[] allocatableFilter,
ClassificationFilter[] eventFilter, String title, Date startDate,
Date endDate, Date selectedDate, String view, Map<String,String> optionMap) throws RaplaException
{
boolean defaultResourceTypes;
boolean defaultEventTypes;
int eventTypes = 0;
int resourceTypes = 0;
defaultResourceTypes = true;
defaultEventTypes = true;
List<ClassificationFilter> filter = new ArrayList<ClassificationFilter>();
if (allocatableFilter != null) {
for (ClassificationFilter entry : allocatableFilter) {
ClassificationFilter clone = entry.clone();
filter.add(clone);
resourceTypes++;
if (entry.ruleSize() > 0) {
defaultResourceTypes = false;
}
}
}
if (eventFilter != null) {
for (ClassificationFilter entry : eventFilter) {
ClassificationFilter clone = entry.clone();
filter.add(clone);
eventTypes++;
if (entry.ruleSize() > 0) {
defaultEventTypes = false;
}
}
}
DynamicType[] allEventTypes;
allEventTypes = m_facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
if (allEventTypes.length > eventTypes && eventFilter != null) {
defaultEventTypes = false;
}
final DynamicType[] allTypes = m_facade.getDynamicTypes(null);
final int allResourceTypes = allTypes.length - allEventTypes.length;
if (allResourceTypes > resourceTypes && allocatableFilter != null) {
defaultResourceTypes = false;
}
final ClassificationFilter[] filterArray = filter.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY);
List<String> selectedIds = new ArrayList<String>();
Collection<RaplaType> idTypeList = new ArrayList<RaplaType>();
for (Entity obj:selected)
{
selectedIds.add( obj.getId());
idTypeList.add( obj.getRaplaType());
}
CalendarModelConfigurationImpl calendarModelConfigurationImpl = new CalendarModelConfigurationImpl(selectedIds, idTypeList,resourceRootSelected,filterArray, defaultResourceTypes, defaultEventTypes, title, startDate, endDate, selectedDate, view, optionMap);
calendarModelConfigurationImpl.setResolver( m_facade.getOperator());
return calendarModelConfigurationImpl;
}
public void setReservationFilter(ClassificationFilter[] array) {
reservationFilter.clear();
if ( array == null)
{
defaultEventTypes = true;
return;
}
try {
defaultEventTypes = createConfiguration(null,array).isDefaultEventTypes();
} catch (RaplaException e) {
// DO Not set the types
}
for (ClassificationFilter entry: array)
{
final DynamicType type = entry.getType();
reservationFilter.put( type, entry);
}
}
public void setAllocatableFilter(ClassificationFilter[] array) {
allocatableFilter.clear();
if ( array == null)
{
defaultResourceTypes = true;
return;
}
try {
defaultResourceTypes = createConfiguration(array,null).isDefaultResourceTypes();
} catch (RaplaException e) {
// DO Not set the types
}
for (ClassificationFilter entry: array)
{
final DynamicType type = entry.getType();
allocatableFilter.put( type, entry);
}
}
@Override
public Date getSelectedDate() {
return selectedDate;
}
@Override
public void setSelectedDate(Date date) {
if ( date == null)
throw new IllegalStateException("Date can't be null");
this.selectedDate = date;
}
@Override
public Date getStartDate() {
return startDate;
}
@Override
public void setStartDate(Date date) {
if ( date == null)
throw new IllegalStateException("Date can't be null");
this.startDate = date;
}
@Override
public Date getEndDate() {
return endDate;
}
@Override
public void setEndDate(Date date) {
if ( date == null)
throw new IllegalStateException("Date can't be null");
this.endDate = date;
}
@Override
public String getTitle()
{
return title;
}
@Override
public void setTitle(String title) {
this.title = title;
}
@Override
public void setViewId(String view) {
this.selectedView = view;
}
@Override
public String getViewId() {
return this.selectedView;
}
class CalendarModelParseContext implements ParseContext
{
public Function resolveVariableFunction(String variableName) throws IllegalAnnotationException {
if ( variableName.equals("allocatables"))
{
List<Function> emptyList = Collections.emptyList();
return new Function(variableName, emptyList)
{
@Override
public Object eval(EvalContext context) {
try {
return Arrays.asList(getSelectedAllocatables());
} catch (RaplaException e) {
return Collections.emptyList();
}
}
};
}
else if ( variableName.equals("timeIntervall"))
{
List<Function> emptyList = Collections.emptyList();
return new Function(variableName, emptyList)
{
@Override
public Object eval(EvalContext context) {
return getTimeIntervall();
}
};
}
else if ( variableName.equals("selectedDate"))
{
List<Function> emptyList = Collections.emptyList();
return new Function(variableName, emptyList)
{
@Override
public Object eval(EvalContext context) {
return getSelectedDate();
}
};
}
return null;
}
}
public TimeInterval getTimeIntervall()
{
return new TimeInterval(getStartDate(), getEndDate());
}
@Override
public String getNonEmptyTitle() {
String title = getTitle();
if (title != null && title.trim().length()>0)
{
ParseContext parseContext = new CalendarModelParseContext();
ParsedText parsedTitle;
try {
parsedTitle = new ParsedText( title);
parsedTitle.init(parseContext);
} catch (IllegalAnnotationException e) {
return e.getMessage();
}
Locale locale = raplaLocale.getLocale();
EvalContext evalContext = new EvalContext( locale);
String result = parsedTitle.formatName( evalContext);
return result;
}
String types = "";
/*
String dateString = getRaplaLocale().formatDate(getSelectedDate());
if ( isListingAllocatables()) {
try {
Collection list = getSelectedObjectsAndChildren();
if (list.size() == 1) {
Object obj = list.iterator().next();
if (!( obj instanceof DynamicType))
{
types = getI18n().format("allocation_view",getName( obj ),dateString);
}
}
} catch (RaplaException ex) {
}
if ( types == null )
types = getI18n().format("allocation_view", getI18n().getString("resources_persons"));
} else if ( isListingReservations()) {
types = getI18n().getString("reservations");
} else {
types = "unknown";
}
*/
return types;
}
public String getName(Object object) {
if (object == null)
return "";
if (object instanceof Named) {
String name = ((Named) object).getName(getI18n().getLocale());
return (name != null) ? name : "";
}
return object.toString();
}
private Collection<Allocatable> getFilteredAllocatables() throws RaplaException {
List<Allocatable> list = new ArrayList<Allocatable>();
for ( Allocatable allocatable :m_facade.getAllocatables())
{
if ( isInFilter( allocatable) && (user == null || allocatable.canRead(user))) {
list.add( allocatable);
}
}
return list;
}
private boolean isInFilter( Allocatable classifiable) {
if (isTemplateModus())
{
return true;
}
final Classification classification = classifiable.getClassification();
final DynamicType type = classification.getType();
final ClassificationFilter classificationFilter = allocatableFilter.get( type);
if ( classificationFilter != null)
{
final boolean matches = classificationFilter.matches(classification);
return matches;
}
else
{
return defaultResourceTypes;
}
}
@Override
public Collection<RaplaObject> getSelectedObjectsAndChildren() throws RaplaException
{
Assert.notNull(selectedObjects);
ArrayList<DynamicType> dynamicTypes = new ArrayList<DynamicType>();
for (Iterator<RaplaObject> it = selectedObjects.iterator();it.hasNext();)
{
Object obj = it.next();
if (obj instanceof DynamicType) {
dynamicTypes.add ((DynamicType)obj);
}
}
HashSet<RaplaObject> result = new HashSet<RaplaObject>();
result.addAll( selectedObjects );
boolean allAllocatablesSelected = selectedObjects.contains( CalendarModelImpl.ALLOCATABLES_ROOT);
Collection<Allocatable> filteredList = getFilteredAllocatables();
for (Iterator<Allocatable> it = filteredList.iterator();it.hasNext();)
{
Allocatable oneSelectedItem = it.next();
if ( selectedObjects.contains(oneSelectedItem)) {
continue;
}
Classification classification = oneSelectedItem.getClassification();
if ( classification == null)
{
continue;
}
if ( allAllocatablesSelected || dynamicTypes.contains(classification.getType()))
{
result.add( oneSelectedItem );
continue;
}
}
return result;
}
@Override
public void setSelectedObjects(Collection<? extends Object> selectedObjects) {
this.selectedObjects = retainRaplaObjects(selectedObjects);
if (markedAllocatables != null && !markedAllocatables.isEmpty())
{
markedAllocatables = new LinkedHashSet<Allocatable>(markedAllocatables);
try {
markedAllocatables.retainAll( Arrays.asList(getSelectedAllocatables()));
} catch (RaplaException e) {
markedAllocatables = Collections.emptyList();
}
}
}
private List<RaplaObject> retainRaplaObjects(Collection<? extends Object> list ){
List<RaplaObject> result = new ArrayList<RaplaObject>();
for ( Iterator<? extends Object> it = list.iterator();it.hasNext();) {
Object obj = it.next();
if ( obj instanceof RaplaObject) {
result.add( (RaplaObject)obj );
}
}
return result;
}
@Override
public Collection<RaplaObject> getSelectedObjects()
{
return selectedObjects;
}
@Override
public ClassificationFilter[] getReservationFilter() throws RaplaException
{
Collection<ClassificationFilter> filter ;
if ( isDefaultEventTypes() || isTemplateModus())
{
filter = new ArrayList<ClassificationFilter>();
for (DynamicType type :m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION))
{
filter.add( type.newClassificationFilter());
}
}
else
{
filter = reservationFilter.values();
}
return filter.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY);
}
protected boolean isTemplateModus() {
return m_facade.getTemplateName() != null;
}
@Override
public ClassificationFilter[] getAllocatableFilter() throws RaplaException {
Collection<ClassificationFilter> filter ;
if ( isDefaultResourceTypes() || isTemplateModus())
{
filter = new ArrayList<ClassificationFilter>();
for (DynamicType type :m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE))
{
filter.add( type.newClassificationFilter());
}
for (DynamicType type :m_facade.getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON))
{
filter.add( type.newClassificationFilter());
}
}
else
{
filter = allocatableFilter.values();
}
return filter.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY);
}
public CalendarSelectionModel clone() {
CalendarModelImpl clone;
try
{
clone = new CalendarModelImpl(context, user, m_facade);
CalendarModelConfiguration config = createConfiguration();
Map<String, String> alternativOptions = null;
clone.setConfiguration( config, alternativOptions);
}
catch ( RaplaException e )
{
throw new IllegalStateException( e.getMessage() );
}
return clone;
}
@Override
public Reservation[] getReservations() throws RaplaException {
return getReservations( getStartDate(), getEndDate() );
}
@Override
public Reservation[] getReservations(Date startDate, Date endDate) throws RaplaException
{
return getReservationsAsList( startDate, endDate ).toArray( Reservation.RESERVATION_ARRAY);
}
private List<Reservation> getReservationsAsList(Date start, Date end) throws RaplaException
{
Allocatable[] allocatables = getSelectedAllocatables();
if ( isNoAllocatableSelected())
{
allocatables = null;
}
Collection<Conflict> conflicts = getSelectedConflicts();
if ( conflicts.size() > 0)
{
return m_facade.getReservations(conflicts);
}
Reservation[] reservationArray =m_facade.getReservations(allocatables, start, end);
List<Reservation> asList = Arrays.asList( reservationArray );
return restrictReservations(asList);
}
public List<Reservation> restrictReservations(Collection<Reservation> reservationsToRestrict) throws RaplaException {
List<Reservation> reservations = new ArrayList<Reservation>(reservationsToRestrict);
// Don't restrict templates
if ( isTemplateModus())
{
return reservations;
}
ClassificationFilter[] reservationFilter = getReservationFilter();
if ( isDefaultEventTypes())
{
reservationFilter = null;
}
Set<User> users = getUserRestrictions();
for ( Iterator<Reservation> it = reservations.iterator();it.hasNext();)
{
Reservation event = it.next();
if ( !users.isEmpty() && !users.contains( event.getOwner() )) {
it.remove();
}
else if (reservationFilter != null && !ClassificationFilter.Util.matches( reservationFilter,event))
{
it.remove();
}
}
return reservations;
}
private Set<User> getUserRestrictions() {
User currentUser = getUser();
if ( currentUser != null && isOnlyCurrentUserSelected() || !m_facade.canReadReservationsFromOthers( currentUser))
{
return Collections.singleton( currentUser );
}
else if ( currentUser != null && currentUser.isAdmin())
{
return getSelected(User.TYPE);
}
else
{
return Collections.emptySet();
}
}
private boolean isNoAllocatableSelected()
{
for (RaplaObject obj :getSelectedObjects())
{
RaplaType raplaType = obj.getRaplaType();
if ( raplaType == Allocatable.TYPE)
{
return false;
}
else if (raplaType == DynamicType.TYPE)
{
DynamicType type = (DynamicType) obj;
String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
if ( annotation.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON ) || annotation.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE))
{
return false;
}
}
else if ( obj.equals(ALLOCATABLES_ROOT) )
{
return false;
}
}
return true;
}
@Override
public Allocatable[] getSelectedAllocatables() throws RaplaException {
Collection<Allocatable> result = getSelectedAllocatablesAsList();
return result.toArray(Allocatable.ALLOCATABLE_ARRAY);
}
protected Collection<Allocatable> getSelectedAllocatablesAsList()
throws RaplaException {
Collection<Allocatable> result = new HashSet<Allocatable>();
for(RaplaObject object:getSelectedObjectsAndChildren()) {
if ( object.getRaplaType() == Conflict.TYPE ) {
result.add( ((Conflict)object).getAllocatable() );
}
}
// We ignore the allocatable selection if there are conflicts selected
if ( result.isEmpty())
{
for(RaplaObject object:getSelectedObjectsAndChildren()) {
if ( object.getRaplaType() ==Allocatable.TYPE ) {
result.add( (Allocatable)object );
}
}
}
Collection<Allocatable> filteredAllocatables = getFilteredAllocatables();
result.retainAll( filteredAllocatables);
return result;
}
public Collection<Conflict> getSelectedConflicts() {
return getSelected(Conflict.TYPE);
}
public Set<DynamicType> getSelectedTypes(String classificationType) throws RaplaException {
Set<DynamicType> result = new HashSet<DynamicType>();
Iterator<RaplaObject> it = getSelectedObjectsAndChildren().iterator();
while (it.hasNext()) {
RaplaObject object = it.next();
if ( object.getRaplaType() == DynamicType.TYPE ) {
if (classificationType == null || (( DynamicType) object).getAnnotation( DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE).equals( classificationType))
{
result.add((DynamicType) object );
}
}
}
return result;
}
private <T extends RaplaObject<T>> Set<T> getSelected(RaplaType<T> type) {
Set<T> result = new HashSet<T>();
Iterator<RaplaObject> it = getSelectedObjects().iterator();
while (it.hasNext()) {
RaplaObject object = it.next();
if ( object.getRaplaType() == type ) {
@SuppressWarnings("unchecked")
T casted = (T)object;
result.add( casted );
}
}
return result;
}
protected I18nBundle getI18n() {
return i18n;
}
protected RaplaLocale getRaplaLocale() {
return raplaLocale;
}
@Override
public boolean isOnlyCurrentUserSelected() {
String option = getOption(CalendarModel.ONLY_MY_EVENTS );
if ( option != null && option.equalsIgnoreCase("TRUE"))
{
return true;
}
return false;
}
@Override
public void selectUser(User user) {
List<RaplaObject> selectedObjects = new ArrayList<RaplaObject>(getSelectedObjects());
for (Iterator<RaplaObject> it = selectedObjects.iterator();it.hasNext();) {
RaplaObject obj = it.next();
if (obj.getRaplaType() == User.TYPE ) {
it.remove();
}
}
if ( user != null)
{
selectedObjects.add( user );
}
setSelectedObjects(selectedObjects);
}
@Override
public String getOption( String name )
{
return optionMap.get( name );
}
@Override
public void setOption( String name, String string )
{
if ( string == null)
{
optionMap.remove( name);
}
else
{
optionMap.put( name, string);
}
}
@Override
public boolean isDefaultEventTypes()
{
return defaultEventTypes;
}
@Override
public boolean isDefaultResourceTypes()
{
return defaultResourceTypes;
}
@Override
public void save(final String filename) throws RaplaException,
EntityNotFoundException {
Preferences clone = createStorablePreferences(filename);
m_facade.store(clone);
}
public Preferences createStorablePreferences(final String filename) throws RaplaException, EntityNotFoundException {
final CalendarModelConfiguration conf = createConfiguration();
Preferences clone = m_facade.edit(m_facade.getPreferences(user));
if ( filename == null)
{
clone.putEntry( CalendarModelConfiguration.CONFIG_ENTRY, conf);
}
else
{
Map<String,CalendarModelConfiguration> exportMap= clone.getEntry(EXPORT_ENTRY);
Map<String,CalendarModelConfiguration> newMap;
if ( exportMap == null)
newMap = new TreeMap<String,CalendarModelConfiguration>();
else
newMap = new TreeMap<String,CalendarModelConfiguration>( exportMap);
newMap.put(filename, conf);
clone.putEntry( EXPORT_ENTRY, m_facade.newRaplaMap( newMap ));
}
return clone;
}
// Old defaultname behaviour. Duplication of language resource names. But the system has to be replaced anyway in the future, because it doesnt allow for multiple language outputs on the server.
private boolean isOldDefaultNameBehavoir(final String filename)
{
List<String> translations = new ArrayList<String>();
translations.add( getI18n().getString("default") );
translations.add( "default" );
translations.add( "Default" );
translations.add( "Standard" );
translations.add( "Standaard");
// special for polnish
if (filename.startsWith( "Domy") && filename.endsWith("lne"))
{
return true;
}
if (filename.startsWith( "Est") && filename.endsWith("ndar"))
{
return true;
}
return translations.contains(filename);
}
@Override
public void load(final String filename) throws RaplaException, EntityNotFoundException, CalendarNotFoundExeption {
final CalendarModelConfiguration modelConfig;
boolean createIfNotNull =false;
{
final Preferences preferences = m_facade.getPreferences(user, createIfNotNull);
modelConfig = getModelConfig(filename, preferences);
}
if ( modelConfig == null && filename != null )
{
throw new CalendarNotFoundExeption("Calendar with name " + filename + " not found.");
}
else
{
final boolean isDefault = filename == null ;
Map<String,String> alternativeOptions = new HashMap<String,String>();
if (modelConfig != null && modelConfig.getOptionMap() != null)
{
// All old default calendars have no selected date
if (isDefault && (modelConfig.getOptionMap().get( CalendarModel.SAVE_SELECTED_DATE) == null))
{
alternativeOptions.put(CalendarModel.SAVE_SELECTED_DATE , "false");
}
// All old calendars are exported
if ( !isDefault && modelConfig.getOptionMap().get(HTML_EXPORT_ENABLED) == null)
{
alternativeOptions.put(HTML_EXPORT_ENABLED,"true");
}
}
setConfiguration(modelConfig, alternativeOptions);
}
}
public CalendarModelConfiguration getModelConfig(final String filename,final Preferences preferences) {
final CalendarModelConfiguration modelConfig;
if (preferences != null)
{
final boolean isDefault = filename == null ;
if ( isDefault )
{
modelConfig = preferences.getEntry(CalendarModelConfiguration.CONFIG_ENTRY);
}
else if ( filename != null && !isDefault)
{
Map<String,CalendarModelConfiguration> exportMap= preferences.getEntry(EXPORT_ENTRY);
final CalendarModelConfiguration config;
if ( exportMap != null)
{
config = exportMap.get(filename);
}
else
{
config = null;
}
if ( config == null && isOldDefaultNameBehavoir(filename) )
{
modelConfig = preferences.getEntry(CalendarModelConfiguration.CONFIG_ENTRY);
}
else
{
modelConfig = config;
}
}
else
{
modelConfig = null;
}
}
else
{
modelConfig = null;
}
return modelConfig;
}
//Set<Appointment> conflictList = new HashSet<Appointment>();
// if ( selectedConflicts != null)
// {
// for (Conflict conflict: selectedConflicts)
// {
// if ( conflict.getAppointment1().equals( app.getId()))
// {
// conflictList.add(conflict.getAppointment2());
// }
// else if ( conflict.getAppointment2().equals( app.getId()))
// {
// conflictList.add(conflict.getAppointment1());
// }
// }
// }
@Override
public List<AppointmentBlock> getBlocks() throws RaplaException
{
List<AppointmentBlock> appointments = new ArrayList<AppointmentBlock>();
Set<Allocatable> selectedAllocatables = new HashSet<Allocatable>(Arrays.asList(getSelectedAllocatables()));
if ( isNoAllocatableSelected())
{
selectedAllocatables = null;
}
Collection<Conflict> selectedConflicts = getSelectedConflicts();
List<Reservation> reservations = m_facade.getReservations( selectedConflicts);
Map<Appointment,Set<Appointment>> conflictingAppointments = ConflictImpl.getMap(selectedConflicts,reservations);
for ( Reservation event:getReservations())
{
for (Appointment app: event.getAppointments())
{
//
Allocatable[] allocatablesFor = event.getAllocatablesFor(app);
if ( selectedAllocatables == null || containsOne(selectedAllocatables, allocatablesFor))
{
Collection<Appointment> conflictList = conflictingAppointments.get( app );
if ( conflictList == null || conflictList.isEmpty())
{
app.createBlocks(getStartDate(), getEndDate(), appointments);
}
else
{
List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
app.createBlocks(getStartDate(), getEndDate(), blocks);
Iterator<AppointmentBlock> it = blocks.iterator();
while ( it.hasNext())
{
AppointmentBlock block = it.next();
boolean found = false;
for ( Appointment conflictingApp:conflictList)
{
if (conflictingApp.overlaps( block ))
{
found = true;
break;
}
}
if ( !found)
{
it.remove();
}
}
appointments.addAll( blocks);
}
}
}
}
Collections.sort(appointments, new AppointmentBlockStartComparator());
return appointments;
}
private boolean containsOne(Set<Allocatable> allocatableSet,
Allocatable[] listOfAllocatablesToMatch) {
for ( Allocatable alloc: listOfAllocatablesToMatch)
{
if (allocatableSet.contains(alloc))
{
return true;
}
}
return false;
}
@Override
public DynamicType guessNewEventType() throws RaplaException {
Set<DynamicType> selectedTypes = getSelectedTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
DynamicType guessedType;
if (selectedTypes.size()>0)
{
guessedType = selectedTypes.iterator().next();
}
else
{
guessedType = m_facade.getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)[0];
}
ClassificationFilter[] reservationFilter = getReservationFilter();
DynamicType firstType = null;
boolean found = false;
// assure that the guessed type is in the filter selection list
for (ClassificationFilter filter : reservationFilter)
{
DynamicType type = filter.getType();
if ( firstType == null)
{
firstType = type;
}
if ( type.equals( guessedType))
{
found = true;
break;
}
}
if (!found && firstType != null)
{
guessedType = firstType;
}
return guessedType;
}
@Override
public Collection<TimeInterval> getMarkedIntervals()
{
return timeIntervals;
}
@Override
public void setMarkedIntervals(Collection<TimeInterval> timeIntervals)
{
if ( timeIntervals != null)
{
this.timeIntervals = Collections.unmodifiableCollection(timeIntervals);
}
else
{
this.timeIntervals = Collections.emptyList();
}
}
@Override
public void markInterval(Date start, Date end) {
TimeInterval timeInterval = new TimeInterval( start, end);
setMarkedIntervals( Collections.singletonList( timeInterval));
}
@Override
public Collection<Allocatable> getMarkedAllocatables() {
return markedAllocatables;
}
@Override
public void setMarkedAllocatables(Collection<Allocatable> allocatables) {
this.markedAllocatables = allocatables;
}
public Collection<Appointment> getAppointments(TimeInterval interval) throws RaplaException
{
Date startDate = interval.getStart();
Date endDate = interval.getEnd();
List<Reservation> reservations = getReservationsAsList(startDate, endDate);
Collection<Allocatable> allocatables =getSelectedAllocatablesAsList();
List<Appointment> result = RaplaBuilder.getAppointments(reservations, allocatables);
return result;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import org.rapla.ConnectInfo;
import org.rapla.components.util.Command;
import org.rapla.components.util.CommandScheduler;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.MultiLanguageName;
import org.rapla.entities.Ownable;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.entities.configuration.internal.RaplaMapImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.domain.RepeatingType;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.RaplaObjectAnnotations;
import org.rapla.entities.domain.ResourceAnnotations;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.domain.internal.AppointmentImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.entities.dynamictype.internal.DynamicTypeImpl;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.entities.internal.ModifiableTimestamp;
import org.rapla.entities.internal.UserImpl;
import org.rapla.entities.storage.ParentEntity;
import org.rapla.entities.storage.internal.SimpleEntity;
import org.rapla.facade.AllocationChangeEvent;
import org.rapla.facade.AllocationChangeListener;
import org.rapla.facade.CalendarOptions;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.Conflict;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.facade.PeriodModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.facade.UpdateErrorListener;
import org.rapla.framework.Configuration;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.internal.ContextTools;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.RaplaSecurityException;
import org.rapla.storage.StorageOperator;
import org.rapla.storage.StorageUpdateListener;
import org.rapla.storage.UpdateResult;
/**
* This is the default implementation of the necessary Client-Facade to the
* DB-Subsystem.
* <p>
* Sample configuration 1:
*
* <pre>
* <facade id="facade">
* <store>file</store>
* </facade>
* </pre>
*
* </p>
* <p>
* The store entry contains the id of a storage-component. Storage-Components
* are all components that implement the {@link StorageOperator} interface.
* </p>
*/
public class FacadeImpl implements ClientFacade,StorageUpdateListener {
protected CommandScheduler notifyQueue;
private String workingUserId = null;
private StorageOperator operator;
private Vector<ModificationListener> modificatonListenerList = new Vector<ModificationListener>();
private Vector<AllocationChangeListener> allocationListenerList = new Vector<AllocationChangeListener>();
private Vector<UpdateErrorListener> errorListenerList = new Vector<UpdateErrorListener>();
private I18nBundle i18n;
private PeriodModelImpl periodModel;
// private ConflictFinder conflictFinder;
private Vector<ModificationListener> directListenerList = new Vector<ModificationListener>();
public CommandHistory commandHistory = new CommandHistory();
Locale locale;
RaplaContext context;
Logger logger;
String templateName;
public FacadeImpl(RaplaContext context, Configuration config, Logger logger) throws RaplaException {
this( context, getOperator(context, config, logger), logger);
}
private static StorageOperator getOperator(RaplaContext context, Configuration config, Logger logger)
throws RaplaContextException {
String configEntry = config.getChild("store").getValue("*");
String storeSelector = ContextTools.resolveContext(configEntry, context ).toString();
logger.info("Using rapladatasource " +storeSelector);
try {
Container container = context.lookup(Container.class);
StorageOperator operator = container.lookup(StorageOperator.class, storeSelector);
return operator;
}
catch (RaplaContextException ex) {
throw new RaplaContextException("Store "
+ storeSelector
+ " is not found (or could not be initialized)", ex);
}
}
public static FacadeImpl create(RaplaContext context, StorageOperator operator, Logger logger) throws RaplaException
{
return new FacadeImpl(context, operator, logger);
}
private FacadeImpl(RaplaContext context, StorageOperator operator, Logger logger) throws RaplaException {
this.operator = operator;
this.logger = logger;
i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
locale = context.lookup(RaplaLocale.class).getLocale();
this.context = context;
operator.addStorageUpdateListener(this);
notifyQueue = context.lookup( CommandScheduler.class );
//org.rapla.components.util.CommandQueue.createCommandQueue();
}
public Logger getLogger()
{
return logger;
}
public StorageOperator getOperator() {
return operator;
}
// Implementation of StorageUpdateListener.
/**
* This method is called by the storage-operator, when stored objects have
* changed.
*
* <strong>Caution:</strong> You must not lock the storage operator during
* processing of this call, because it could have been locked by the store
* method, causing deadlocks
*/
public void objectsUpdated(UpdateResult evt) {
if (getLogger().isDebugEnabled())
getLogger().debug("Objects updated");
cacheValidString = null;
cachedReservations = null;
if (workingUserId != null)
{
if ( evt.isModified( User.TYPE))
{
if (operator.tryResolve( workingUserId, User.class) == null)
{
EntityNotFoundException ex = new EntityNotFoundException("User for id " + workingUserId + " not found. Maybe it was removed.");
fireUpdateError(ex);
}
}
}
fireUpdateEvent(evt);
}
public void updateError(RaplaException ex) {
getLogger().error(ex.getMessage(), ex);
fireUpdateError(ex);
}
public void storageDisconnected(String message) {
fireStorageDisconnected(message);
}
/******************************
* Update-module *
******************************/
public boolean isClientForServer() {
return operator.supportsActiveMonitoring();
}
public void refresh() throws RaplaException {
if (operator.supportsActiveMonitoring()) {
operator.refresh();
}
}
void setName(MultiLanguageName name, String to)
{
String currentLang = i18n.getLang();
name.setName("en", to);
try
{
// try to find a translation in the current locale
String translation = i18n.getString( to);
name.setName(currentLang, translation);
}
catch (Exception ex)
{
// go on, if non is found
}
}
public void addModificationListener(ModificationListener listener) {
modificatonListenerList.add(listener);
}
public void addDirectModificationListener(ModificationListener listener)
{
directListenerList.add(listener);
}
public void removeModificationListener(ModificationListener listener) {
directListenerList.remove(listener);
modificatonListenerList.remove(listener);
}
private Collection<ModificationListener> getModificationListeners() {
if (modificatonListenerList.size() == 0)
{
return Collections.emptyList();
}
synchronized (this) {
Collection<ModificationListener> list = new ArrayList<ModificationListener>(3);
if (periodModel != null) {
list.add(periodModel);
}
Iterator<ModificationListener> it = modificatonListenerList.iterator();
while (it.hasNext()) {
ModificationListener listener = it.next();
list.add(listener);
}
return list;
}
}
public void addAllocationChangedListener(AllocationChangeListener listener) {
if ( operator.supportsActiveMonitoring())
{
throw new IllegalStateException("You can't add an allocation listener to a client facade because reservation objects are not updated");
}
allocationListenerList.add(listener);
}
public void removeAllocationChangedListener(AllocationChangeListener listener) {
allocationListenerList.remove(listener);
}
private Collection<AllocationChangeListener> getAllocationChangeListeners() {
if (allocationListenerList.size() == 0)
{
return Collections.emptyList();
}
synchronized (this) {
Collection<AllocationChangeListener> list = new ArrayList<AllocationChangeListener>( 3);
Iterator<AllocationChangeListener> it = allocationListenerList.iterator();
while (it.hasNext()) {
AllocationChangeListener listener = it.next();
list.add(listener);
}
return list;
}
}
public AllocationChangeEvent[] createAllocationChangeEvents(UpdateResult evt) {
Logger logger = getLogger().getChildLogger("trigger.allocation");
List<AllocationChangeEvent> triggerEvents = AllocationChangeFinder.getTriggerEvents(evt, logger);
return triggerEvents.toArray( new AllocationChangeEvent[0]);
}
public void addUpdateErrorListener(UpdateErrorListener listener) {
errorListenerList.add(listener);
}
public void removeUpdateErrorListener(UpdateErrorListener listener) {
errorListenerList.remove(listener);
}
public UpdateErrorListener[] getUpdateErrorListeners() {
return errorListenerList.toArray(new UpdateErrorListener[] {});
}
protected void fireUpdateError(RaplaException ex) {
UpdateErrorListener[] listeners = getUpdateErrorListeners();
for (int i = 0; i < listeners.length; i++) {
listeners[i].updateError(ex);
}
}
protected void fireStorageDisconnected(String message) {
UpdateErrorListener[] listeners = getUpdateErrorListeners();
for (int i = 0; i < listeners.length; i++) {
listeners[i].disconnected(message);
}
}
final class UpdateCommandAllocation implements Runnable, Command {
Collection<AllocationChangeListener> listenerList;
AllocationChangeEvent[] allocationChangeEvents;
public UpdateCommandAllocation(Collection<AllocationChangeListener> allocationChangeListeners, UpdateResult evt) {
this.listenerList= new ArrayList<AllocationChangeListener>(allocationChangeListeners);
if ( allocationChangeListeners.size() > 0)
{
allocationChangeEvents = createAllocationChangeEvents(evt);
}
}
public void execute() {
run();
}
public void run() {
for (AllocationChangeListener listener: listenerList)
{
try {
if (isAborting())
return;
if (getLogger().isDebugEnabled())
getLogger().debug("Notifying " + listener);
if (allocationChangeEvents.length > 0) {
listener.changed(allocationChangeEvents);
}
} catch (Exception ex) {
getLogger().error("update-exception", ex);
}
}
}
}
final class UpdateCommandModification implements Runnable, Command {
Collection<ModificationListener> listenerList;
ModificationEvent modificationEvent;
public UpdateCommandModification(Collection<ModificationListener> modificationListeners, UpdateResult evt) {
this.listenerList = new ArrayList<ModificationListener>(modificationListeners);
this.modificationEvent = evt;
}
public void execute() {
run();
}
public void run() {
for (ModificationListener listener: listenerList) {
try {
if (isAborting())
return;
if (getLogger().isDebugEnabled())
getLogger().debug("Notifying " + listener);
listener.dataChanged(modificationEvent);
} catch (Exception ex) {
getLogger().error("update-exception", ex);
}
}
}
} /**
* fires update event asynchronous.
*/
protected void fireUpdateEvent(UpdateResult evt) {
if (periodModel != null) {
try {
periodModel.update();
} catch (RaplaException e) {
getLogger().error("Can't update Period Model", e);
}
}
{
Collection<ModificationListener> modificationListeners = directListenerList;
if (modificationListeners.size() > 0 ) {
new UpdateCommandModification(modificationListeners,evt).execute();
}
}
{
Collection<ModificationListener> modificationListeners = getModificationListeners();
if (modificationListeners.size() > 0 ) {
notifyQueue.schedule(new UpdateCommandModification(modificationListeners, evt),0);
}
Collection<AllocationChangeListener> allocationChangeListeners = getAllocationChangeListeners();
if (allocationChangeListeners.size() > 0) {
notifyQueue.schedule(new UpdateCommandAllocation(allocationChangeListeners, evt),0);
}
}
}
/******************************
* Query-module *
******************************/
private Collection<Allocatable> getVisibleAllocatables( ClassificationFilter[] filters) throws RaplaException {
User workingUser = getWorkingUser();
Collection<Allocatable> objects = operator.getAllocatables(filters);
Iterator<Allocatable> it = objects.iterator();
while (it.hasNext()) {
Allocatable allocatable = it.next();
if (workingUser == null || workingUser.isAdmin())
continue;
if (!allocatable.canRead(workingUser))
it.remove();
}
return objects;
}
int queryCounter = 0;
private Collection<Reservation> getVisibleReservations(User user, Allocatable[] allocatables, Date start, Date end, ClassificationFilter[] reservationFilters)
throws RaplaException {
if ( templateName != null)
{
Collection<Reservation> reservations = getTemplateReservations( templateName);
return reservations;
}
List<Allocatable> allocList;
if (allocatables != null)
{
if ( allocatables.length == 0 )
{
return Collections.emptyList();
}
allocList = Arrays.asList( allocatables);
}
else
{
allocList = Collections.emptyList();
}
Collection<Reservation> reservations =operator.getReservations(user,allocList, start, end, reservationFilters,null);
// Category can_see = getUserGroupsCategory().getCategory(
// Permission.GROUP_CAN_READ_EVENTS_FROM_OTHERS);
if (getLogger().isDebugEnabled())
{
getLogger().debug((++queryCounter)+". Query reservation called user=" + user + " start=" +start + " end=" + end);
}
return reservations;
}
public Allocatable[] getAllocatables() throws RaplaException {
return getAllocatables(null);
}
public Allocatable[] getAllocatables(ClassificationFilter[] filters) throws RaplaException {
return getVisibleAllocatables(filters).toArray( Allocatable.ALLOCATABLE_ARRAY);
}
public boolean canExchangeAllocatables(Reservation reservation) {
try {
Allocatable[] all = getAllocatables(null);
User user = getUser();
for (int i = 0; i < all.length; i++) {
if (all[i].canModify(user)) {
return true;
}
}
} catch (RaplaException ex) {
}
return false;
}
public Preferences getPreferences() throws RaplaException {
return getPreferences(getUser());
}
public Preferences getSystemPreferences() throws RaplaException
{
return operator.getPreferences(null, true);
}
public Preferences getPreferences(User user) throws RaplaException {
return operator.getPreferences(user, true);
}
public Preferences getPreferences(User user,boolean createIfNotNull) throws RaplaException {
return operator.getPreferences(user, createIfNotNull);
}
public Category getSuperCategory() {
return operator.getSuperCategory();
}
public Category getUserGroupsCategory() throws RaplaException {
Category userGroups = getSuperCategory().getCategory(
Permission.GROUP_CATEGORY_KEY);
if (userGroups == null) {
throw new RaplaException("No category '"+ Permission.GROUP_CATEGORY_KEY + "' available");
}
return userGroups;
}
public Collection<String> getTemplateNames() throws RaplaException
{
return operator.getTemplateNames();
}
public Collection<Reservation> getTemplateReservations(String name) throws RaplaException
{
User user = null;
Collection<Allocatable> allocList = null;
Date start = null;
Date end = null;
Map<String,String> annotationQuery = new LinkedHashMap<String,String>();
annotationQuery.put(RaplaObjectAnnotations.KEY_TEMPLATE, name);
Collection<Reservation> result = operator.getReservations(user,allocList, start, end,null, annotationQuery);
return result;
}
public Reservation[] getReservations(User user, Date start, Date end,ClassificationFilter[] filters) throws RaplaException {
return getVisibleReservations(user, null,start, end, filters).toArray(Reservation.RESERVATION_ARRAY);
}
private String cacheValidString;
private Reservation[] cachedReservations;
public Reservation[] getReservations(Allocatable[] allocatables,Date start, Date end) throws RaplaException {
String cacheKey = createCacheKey( allocatables, start, end);
if ( cacheValidString != null && cacheValidString.equals( cacheKey) && cachedReservations != null)
{
return cachedReservations;
}
Reservation[] reservationsForAllocatable = getReservationsForAllocatable(allocatables, start, end, null);
cachedReservations = reservationsForAllocatable;
cacheValidString = cacheKey;
return reservationsForAllocatable;
}
private String createCacheKey(Allocatable[] allocatables, Date start,
Date end) {
StringBuilder buf = new StringBuilder();
if ( allocatables != null)
{
for ( Allocatable alloc:allocatables)
{
buf.append(alloc.getId());
buf.append(";");
}
}
else
{
buf.append("all_reservations;");
}
if ( start != null)
{
buf.append(start.getTime() + ";");
}
if ( end != null)
{
buf.append(end.getTime() + ";");
}
return buf.toString();
}
public List<Reservation> getReservations(Collection<Conflict> conflicts) throws RaplaException
{
Collection<String> ids = new ArrayList<String>();
for ( Conflict conflict:conflicts)
{
ids.add(conflict.getReservation1());
ids.add(conflict.getReservation2());
}
Collection<Entity> values = operator.getFromId( ids, true).values();
@SuppressWarnings("unchecked")
ArrayList<Reservation> converted = new ArrayList(values);
return converted;
}
public Reservation[] getReservationsForAllocatable(Allocatable[] allocatables, Date start, Date end,ClassificationFilter[] reservationFilters) throws RaplaException {
//System.gc();
Collection<Reservation> reservations = getVisibleReservations(null, allocatables,start, end, reservationFilters);
return reservations.toArray(Reservation.RESERVATION_ARRAY);
}
public Period[] getPeriods() throws RaplaException {
Period[] result = getPeriodModel().getAllPeriods();
return result;
}
public PeriodModel getPeriodModel() throws RaplaException {
if (periodModel == null) {
periodModel = new PeriodModelImpl(this);
}
return periodModel;
}
public DynamicType[] getDynamicTypes(String classificationType)
throws RaplaException {
ArrayList<DynamicType> result = new ArrayList<DynamicType>();
Collection<DynamicType> collection = operator.getDynamicTypes();
for (DynamicType type: collection) {
String classificationTypeAnno = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
// ignore internal types for backward compatibility
if ((( DynamicTypeImpl)type).isInternal())
{
continue;
}
if ( classificationType == null || classificationType.equals(classificationTypeAnno)) {
result.add(type);
}
}
return result.toArray(DynamicType.DYNAMICTYPE_ARRAY);
}
public DynamicType getDynamicType(String elementKey) throws RaplaException {
DynamicType dynamicType = operator.getDynamicType(elementKey);
if ( dynamicType == null)
{
throw new EntityNotFoundException("No dynamictype with elementKey "
+ elementKey);
}
return dynamicType;
}
public User[] getUsers() throws RaplaException {
User[] result = operator.getUsers().toArray(User.USER_ARRAY);
return result;
}
public User getUser(String username) throws RaplaException {
User user = operator.getUser(username);
if (user == null)
throw new EntityNotFoundException("No User with username " + username);
return user;
}
public Conflict[] getConflicts(Reservation reservation) throws RaplaException {
Date today = operator.today();
if ( RaplaComponent.isTemplate( reservation))
{
return Conflict.CONFLICT_ARRAY;
}
Collection<Allocatable> allocatables = Arrays.asList(reservation.getAllocatables());
Collection<Appointment> appointments = Arrays.asList(reservation.getAppointments());
Collection<Reservation> ignoreList = Collections.singleton( reservation );
Map<Allocatable, Map<Appointment, Collection<Appointment>>> allocatableBindings = operator.getAllAllocatableBindings( allocatables, appointments, ignoreList);
ArrayList<Conflict> conflictList = new ArrayList<Conflict>();
for ( Map.Entry<Allocatable, Map<Appointment, Collection<Appointment>>> entry: allocatableBindings.entrySet() )
{
Allocatable allocatable= entry.getKey();
String annotation = allocatable.getAnnotation( ResourceAnnotations.KEY_CONFLICT_CREATION);
boolean holdBackConflicts = annotation != null && annotation.equals( ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE);
if ( holdBackConflicts)
{
continue;
}
Map<Appointment, Collection<Appointment>> appointmentMap = entry.getValue();
for (Map.Entry<Appointment, Collection<Appointment>> appointmentEntry: appointmentMap.entrySet())
{
Appointment appointment = appointmentEntry.getKey();
if ( reservation.hasAllocated( allocatable, appointment))
{
Collection<Appointment> conflictionAppointments = appointmentEntry.getValue();
if ( conflictionAppointments != null)
{
for ( Appointment conflictingAppointment: conflictionAppointments)
{
Appointment appointment1 = appointment;
Appointment appointment2 = conflictingAppointment;
if (ConflictImpl.isConflict(appointment1, appointment2, today))
{
ConflictImpl.addConflicts(conflictList, allocatable,appointment1, appointment2, today);
}
}
}
}
}
}
return conflictList.toArray(Conflict.CONFLICT_ARRAY);
}
public Conflict[] getConflicts() throws RaplaException {
final User user;
User workingUser = getWorkingUser();
if ( workingUser != null && !workingUser.isAdmin())
{
user = workingUser;
}
else
{
user = null;
}
Collection<Conflict> conflicts = operator.getConflicts( user);
if (getLogger().isDebugEnabled())
{
getLogger().debug("getConflits called. Returned " + conflicts.size() + " conflicts.");
}
return conflicts.toArray(new Conflict[] {});
}
public static boolean hasPermissionToAllocate( User user, Appointment appointment,Allocatable allocatable, Reservation original, Date today) {
if ( user.isAdmin()) {
return true;
}
Date start = appointment.getStart();
Date end = appointment.getMaxEnd();
Permission[] permissions = allocatable.getPermissions();
for ( int i = 0; i < permissions.length; i++)
{
Permission p = permissions[i];
int accessLevel = p.getAccessLevel();
if ( (!p.affectsUser( user )) || accessLevel< Permission.READ) {
continue;
}
if ( accessLevel == Permission.ADMIN)
{
// user has the right to allocate
return true;
}
if ( accessLevel >= Permission.ALLOCATE && p.covers( start, end, today ) )
{
return true;
}
if ( original == null )
{
continue;
}
// We must check if the changes of the existing appointment
// are in a permisable timeframe (That should be allowed)
// 1. check if appointment is old,
// 2. check if allocatable was already assigned to the appointment
Appointment originalAppointment = original.findAppointment( appointment );
if ( originalAppointment == null || !original.hasAllocated( allocatable, originalAppointment))
{
continue;
}
// 3. check if the appointment has changed during
// that time
if ( appointment.matches( originalAppointment ) )
{
return true;
}
if ( accessLevel >= Permission.ALLOCATE )
{
Date maxTime = DateTools.max(appointment.getMaxEnd(), originalAppointment.getMaxEnd());
if (maxTime == null)
{
maxTime = DateTools.addYears( today, 4);
}
Date minChange = appointment.getFirstDifference( originalAppointment, maxTime );
Date maxChange = appointment.getLastDifference( originalAppointment, maxTime );
//System.out.println ( "minChange: " + minChange + ", maxChange: " + maxChange );
if ( p.covers( minChange, maxChange, today ) ) {
return true;
}
}
}
return false;
}
public boolean canEditTemplats(User user) {
return hasGroupRights(user, Permission.GROUP_CAN_EDIT_TEMPLATES);
}
public boolean canReadReservationsFromOthers(User user) {
return hasGroupRights(user, Permission.GROUP_CAN_READ_EVENTS_FROM_OTHERS);
}
protected boolean hasGroupRights(User user, String groupKey) {
if (user == null) {
User workingUser;
try {
workingUser = getWorkingUser();
} catch (EntityNotFoundException e) {
return false;
}
return workingUser == null || workingUser.isAdmin();
}
if (user.isAdmin()) {
return true;
}
try {
Category group = getUserGroupsCategory().getCategory( groupKey);
if ( group == null)
{
return true;
}
return user.belongsTo(group);
} catch (Exception ex) {
getLogger().error("Can't get permissions!", ex);
}
return false;
}
public boolean canCreateReservations(User user) {
return hasGroupRights(user, Permission.GROUP_CAN_CREATE_EVENTS);
}
@Deprecated
public Allocatable[] getAllocatableBindings(Appointment forAppointment) throws RaplaException {
List<Allocatable> allocatableList = Arrays.asList(getAllocatables());
List<Allocatable> result = new ArrayList<Allocatable>();
Map<Allocatable, Collection<Appointment>> bindings = getAllocatableBindings( allocatableList, Collections.singletonList(forAppointment));
for (Map.Entry<Allocatable, Collection<Appointment>> entry: bindings.entrySet())
{
Collection<Appointment> appointments = entry.getValue();
if ( appointments.contains( forAppointment))
{
Allocatable alloc = entry.getKey();
result.add( alloc);
}
}
return result.toArray(Allocatable.ALLOCATABLE_ARRAY);
}
public Map<Allocatable,Collection<Appointment>> getAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments) throws RaplaException {
Collection<Reservation> ignoreList = new HashSet<Reservation>();
if ( appointments != null)
{
for (Appointment app: appointments)
{
Reservation r = app.getReservation();
if ( r != null)
{
ignoreList.add( r );
}
}
}
return operator.getFirstAllocatableBindings(allocatables, appointments, ignoreList);
}
public Date getNextAllocatableDate(Collection<Allocatable> allocatables, Appointment appointment, CalendarOptions options) throws RaplaException {
int worktimeStartMinutes = options.getWorktimeStartMinutes();
int worktimeEndMinutes = options.getWorktimeEndMinutes();
Integer[] excludeDays = options.getExcludeDays().toArray( new Integer[] {});
int rowsPerHour = options.getRowsPerHour();
Reservation reservation = appointment.getReservation();
Collection<Reservation> ignoreList;
if (reservation != null)
{
ignoreList = Collections.singleton( reservation);
}
else
{
ignoreList = Collections.emptyList();
}
return operator.getNextAllocatableDate(allocatables, appointment,ignoreList, worktimeStartMinutes, worktimeEndMinutes, excludeDays, rowsPerHour);
}
/******************************
* Login - Module *
******************************/
public User getUser() throws RaplaException {
if (this.workingUserId == null) {
throw new RaplaException("no user loged in");
}
return operator.resolve( workingUserId, User.class);
}
/** unlike getUser this can be null if working user not set*/
private User getWorkingUser() throws EntityNotFoundException {
if ( workingUserId == null)
{
return null;
}
return operator.resolve( workingUserId, User.class);
}
public boolean login(String username, char[] password)
throws RaplaException {
return login( new ConnectInfo(username, password));
}
public boolean login(ConnectInfo connectInfo)
throws RaplaException {
User user = null;
try {
if (!operator.isConnected()) {
user = operator.connect( connectInfo);
}
} catch (RaplaSecurityException ex) {
return false;
} finally {
// Clear password
// for (int i = 0; i < password.length; i++)
// password[i] = 0;
}
if ( user == null)
{
String username = connectInfo.getUsername();
if ( connectInfo.getConnectAs() != null)
{
username = connectInfo.getConnectAs();
}
user = operator.getUser(username);
}
if (user != null) {
this.workingUserId = user.getId();
getLogger().info("Login " + user.getUsername());
return true;
} else {
return false;
}
}
public boolean canChangePassword() {
try {
return operator.canChangePassword();
} catch (RaplaException e) {
return false;
}
}
public boolean isSessionActive() {
return (this.workingUserId != null);
}
private boolean aborting;
public void logout() throws RaplaException {
if (this.workingUserId == null )
return;
getLogger().info("Logout " + workingUserId);
aborting = true;
try
{
// now we can add it again
this.workingUserId = null;
// we need to remove the storage update listener, because the disconnect
// would trigger a restart otherwise
operator.removeStorageUpdateListener(this);
operator.disconnect();
operator.addStorageUpdateListener(this);
}
finally
{
aborting = false;
}
}
private boolean isAborting() {
return aborting || !operator.isConnected();
}
public void changePassword(User user, char[] oldPassword, char[] newPassword) throws RaplaException {
operator.changePassword( user, oldPassword, newPassword);
}
/******************************
* Modification-module *
******************************/
public String getTemplateName()
{
if ( templateName != null)
{
return templateName;
}
return null;
}
public void setTemplateName(String templateName)
{
this.templateName = templateName;
cachedReservations = null;
cacheValidString = null;
User workingUser;
try {
workingUser = getWorkingUser();
} catch (EntityNotFoundException e) {
// system user as change initiator won't hurt
workingUser = null;
getLogger().error(e.getMessage(),e);
}
UpdateResult updateResult = new UpdateResult( workingUser);
updateResult.setSwitchTemplateMode(true);
updateResult.setInvalidateInterval( new TimeInterval(null, null));
fireUpdateEvent( updateResult);
}
@SuppressWarnings("unchecked")
public <T> RaplaMap<T> newRaplaMap(Map<String, T> map) {
return (RaplaMap<T>) new RaplaMapImpl(map);
}
@SuppressWarnings("unchecked")
public <T> RaplaMap<T> newRaplaMap(Collection<T> col) {
return (RaplaMap<T>) new RaplaMapImpl(col);
}
public Appointment newAppointment(Date startDate, Date endDate) throws RaplaException {
User user = getUser();
return newAppointment(startDate, endDate, user);
}
public Reservation newReservation() throws RaplaException
{
Classification classification = getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)[0].newClassification();
return newReservation( classification );
}
public Reservation newReservation(Classification classification) throws RaplaException
{
User user = getUser();
return newReservation( classification,user );
}
public Reservation newReservation(Classification classification,User user) throws RaplaException
{
if (!canCreateReservations( user))
{
throw new RaplaException("User not allowed to create events");
}
Date now = operator.getCurrentTimestamp();
ReservationImpl reservation = new ReservationImpl(now ,now );
if ( templateName != null )
{
reservation.setAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE, templateName);
}
reservation.setClassification(classification);
setNew(reservation, user);
return reservation;
}
public Allocatable newAllocatable( Classification classification) throws RaplaException
{
return newAllocatable(classification, getUser());
}
public Allocatable newAllocatable( Classification classification, User user) throws RaplaException {
Date now = operator.getCurrentTimestamp();
AllocatableImpl allocatable = new AllocatableImpl(now, now);
DynamicTypeImpl type = (DynamicTypeImpl)classification.getType();
if ( type.getElementKey().equals(StorageOperator.PERIOD_TYPE))
{
Permission newPermission =allocatable.newPermission();
newPermission.setAccessLevel( Permission.READ);
allocatable.addPermission(newPermission);
}
if ( !type.isInternal())
{
allocatable.addPermission(allocatable.newPermission());
if (user != null && !user.isAdmin()) {
Permission permission = allocatable.newPermission();
permission.setUser(user);
permission.setAccessLevel(Permission.ADMIN);
allocatable.addPermission(permission);
}
}
allocatable.setClassification(classification);
setNew(allocatable, user);
return allocatable;
}
private Classification newClassification(String classificationType)
throws RaplaException {
DynamicType[] dynamicTypes = getDynamicTypes(classificationType);
DynamicType dynamicType = dynamicTypes[0];
Classification classification = dynamicType.newClassification();
return classification;
}
public Appointment newAppointment(Date startDate, Date endDate, User user) throws RaplaException {
AppointmentImpl appointment = new AppointmentImpl(startDate, endDate);
setNew(appointment, user);
return appointment;
}
public Appointment newAppointment(Date startDate, Date endDate, RepeatingType repeatingType, int repeatingDuration) throws RaplaException {
AppointmentImpl appointment = new AppointmentImpl(startDate, endDate, repeatingType, repeatingDuration);
User user = getUser();
setNew(appointment, user);
return appointment;
}
public Allocatable newResource() throws RaplaException {
User user = getUser();
Classification classification = newClassification(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE);
return newAllocatable(classification, user);
}
public Allocatable newPerson() throws RaplaException {
User user = getUser();
Classification classification = newClassification(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON);
return newAllocatable(classification, user);
}
public Allocatable newPeriod() throws RaplaException {
DynamicType periodType = getDynamicType(StorageOperator.PERIOD_TYPE);
Classification classification = periodType.newClassification();
classification.setValue("name", "");
Date today = today();
classification.setValue("start", DateTools.cutDate(today));
classification.setValue("end", DateTools.addDays(DateTools.fillDate(today),7));
Allocatable period = newAllocatable(classification);
setNew(period);
return period;
}
public Date today() {
return operator.today();
}
public Category newCategory() throws RaplaException {
Date now = operator.getCurrentTimestamp();
CategoryImpl category = new CategoryImpl(now, now);
setNew(category);
return category;
}
private Attribute createStringAttribute(String key, String name) throws RaplaException {
Attribute attribute = newAttribute(AttributeType.STRING);
attribute.setKey(key);
setName(attribute.getName(), name);
return attribute;
}
public DynamicType newDynamicType(String classificationType) throws RaplaException {
Date now = operator.getCurrentTimestamp();
DynamicTypeImpl dynamicType = new DynamicTypeImpl(now,now);
dynamicType.setAnnotation("classification-type", classificationType);
dynamicType.setKey(createDynamicTypeKey(classificationType));
setNew(dynamicType);
if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE)) {
dynamicType.addAttribute(createStringAttribute("name", "name"));
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}");
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS,"automatic");
} else if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)) {
dynamicType.addAttribute(createStringAttribute("name","eventname"));
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}");
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS, null);
} else if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON)) {
dynamicType.addAttribute(createStringAttribute("surname", "surname"));
dynamicType.addAttribute(createStringAttribute("firstname", "firstname"));
dynamicType.addAttribute(createStringAttribute("email", "email"));
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT, "{surname} {firstname}");
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS, null);
}
return dynamicType;
}
public Attribute newAttribute(AttributeType attributeType) throws RaplaException {
AttributeImpl attribute = new AttributeImpl(attributeType);
setNew(attribute);
return attribute;
}
public User newUser() throws RaplaException {
Date now = operator.getCurrentTimestamp();
UserImpl user = new UserImpl( now, now);
setNew(user);
String[] defaultGroups = new String[] {Permission.GROUP_MODIFY_PREFERENCES_KEY,Permission.GROUP_CAN_READ_EVENTS_FROM_OTHERS,Permission.GROUP_CAN_CREATE_EVENTS};
for ( String groupKey: defaultGroups)
{
Category group = getUserGroupsCategory().getCategory( groupKey);
if (group != null)
{
user.addGroup(group);
}
}
return user;
}
public CalendarSelectionModel newCalendarModel(User user) throws RaplaException{
User workingUser = getWorkingUser();
if ( workingUser != null && !workingUser.isAdmin() && !user.equals(workingUser))
{
throw new RaplaException("Can't create a calendar model for a different user.");
}
return new CalendarModelImpl( context, user, this);
}
private String createDynamicTypeKey(String classificationType)
throws RaplaException {
DynamicType[] dts = getDynamicTypes(classificationType);
int max = 1;
for (int i = 0; i < dts.length; i++) {
String key = dts[i].getKey();
int len = classificationType.length();
if (key.indexOf(classificationType) >= 0 && key.length() > len && Character.isDigit(key.charAt(len))) {
try {
int value = Integer.valueOf(key.substring(len)).intValue();
if (value >= max)
max = value + 1;
} catch (NumberFormatException ex) {
}
}
}
return classificationType + (max);
}
private void setNew(Entity entity) throws RaplaException {
setNew(entity, null);
}
private void setNew(Entity entity,User user) throws RaplaException {
setNew(Collections.singleton(entity), entity.getRaplaType(), user);
}
private <T extends Entity> void setNew(Collection<T> entities, RaplaType raplaType,User user)
throws RaplaException {
for ( T entity: entities)
{
if ((entity instanceof ParentEntity) && (((ParentEntity)entity).getSubEntities().iterator().hasNext()) && ! (entity instanceof Reservation) ) {
throw new RaplaException("The current Rapla Version doesnt support cloning entities with sub-entities. (Except reservations)");
}
}
String[] ids = operator.createIdentifier(raplaType, entities.size());
int i = 0;
for ( T uncasted: entities)
{
String id = ids[i++];
SimpleEntity entity = (SimpleEntity) uncasted;
entity.setId(id);
entity.setResolver(operator);
if (getLogger() != null && getLogger().isDebugEnabled()) {
getLogger().debug("new " + entity.getId());
}
if (entity instanceof Reservation) {
if (user == null)
throw new RaplaException("The reservation " + entity + " needs an owner but user specified is null ");
((Ownable) entity).setOwner(user);
}
}
}
public void checkReservation(Reservation reservation) throws RaplaException {
if (reservation.getAppointments().length == 0) {
throw new RaplaException(i18n.getString("error.no_appointment"));
}
Locale locale = i18n.getLocale();
String name = reservation.getName(locale);
if (name.trim().length() == 0) {
throw new RaplaException(i18n.getString("error.no_reservation_name"));
}
}
public <T extends Entity> T edit(T obj) throws RaplaException {
if (obj == null)
throw new NullPointerException("Can't edit null objects");
Set<T> singleton = Collections.singleton( obj);
Collection<T> edit = edit(singleton);
T result = edit.iterator().next();
return result;
}
public <T extends Entity> Collection<T> edit(Collection<T> list) throws RaplaException
{
List<Entity> castedList = new ArrayList<Entity>();
for ( Entity entity:list)
{
castedList.add( entity);
}
User workingUser = getWorkingUser();
Collection<Entity> result = operator.editObjects(castedList, workingUser);
List<T> castedResult = new ArrayList<T>();
for ( Entity entity:result)
{
@SuppressWarnings("unchecked")
T casted = (T) entity;
castedResult.add( casted);
}
return castedResult;
}
@SuppressWarnings("unchecked")
private <T extends Entity> T _clone(T obj) throws RaplaException {
T deepClone = (T) obj.clone();
T clone = deepClone;
RaplaType raplaType = clone.getRaplaType();
if (raplaType == Appointment.TYPE) {
// Hack for 1.6 compiler compatibility
Object temp = clone;
((AppointmentImpl) temp).removeParent();
}
if (raplaType == Category.TYPE) {
// Hack for 1.6 compiler compatibility
Object temp = clone;
((CategoryImpl) temp).removeParent();
}
User workingUser = getWorkingUser();
setNew((Entity) clone, workingUser);
return clone;
}
@SuppressWarnings("unchecked")
public <T extends Entity> T clone(T obj) throws RaplaException {
if (obj == null)
throw new NullPointerException("Can't clone null objects");
User workingUser = getWorkingUser();
T result;
RaplaType<T> raplaType = obj.getRaplaType();
// Hack for 1.6 compiler compatibility
if (((Object)raplaType) == Appointment.TYPE ){
T _clone = _clone(obj);
// Hack for 1.6 compiler compatibility
Object temp = _clone;
((AppointmentImpl) temp).setParent(null);
result = _clone;
// Hack for 1.6 compiler compatibility
} else if (((Object)raplaType) == Reservation.TYPE) {
// Hack for 1.6 compiler compatibility
Object temp = obj;
Reservation clonedReservation = cloneReservation((Reservation) temp);
// Hack for 1.6 compiler compatibility
Reservation r = clonedReservation;
if ( workingUser != null)
{
r.setOwner( workingUser );
}
if ( templateName != null )
{
r.setAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE, templateName);
}
else
{
String originalTemplate = r.getAnnotation( RaplaObjectAnnotations.KEY_TEMPLATE);
if (originalTemplate != null)
{
r.setAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE_COPYOF, originalTemplate);
}
r.setAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE, null);
}
// Hack for 1.6 compiler compatibility
Object r2 = r;
result = (T)r2;
}
else
{
try {
T _clone = _clone(obj);
result = _clone;
} catch (ClassCastException ex) {
throw new RaplaException("This entity can't be cloned ", ex);
} finally {
}
}
if (result instanceof ModifiableTimestamp) {
Date now = operator.getCurrentTimestamp();
((ModifiableTimestamp) result).setLastChanged(now);
if (workingUser != null) {
((ModifiableTimestamp) result).setLastChangedBy(workingUser);
}
}
return result;
}
/** Clones a reservation and sets new ids for all appointments and the reservation itsel
*/
private Reservation cloneReservation(Reservation obj) throws RaplaException {
User workingUser = getWorkingUser();
// first we do a reservation deep clone
Reservation clone = obj.clone();
HashMap<Allocatable, Appointment[]> restrictions = new HashMap<Allocatable, Appointment[]>();
Allocatable[] allocatables = clone.getAllocatables();
for (Allocatable allocatable:allocatables) {
restrictions.put(allocatable, clone.getRestriction(allocatable));
}
// then we set new ids for all appointments
Appointment[] clonedAppointments = clone.getAppointments();
setNew(Arrays.asList(clonedAppointments),Appointment.TYPE, workingUser);
for (Appointment clonedAppointment:clonedAppointments) {
clone.removeAppointment(clonedAppointment);
}
// and now a new id for the reservation
setNew( clone, workingUser);
for (Appointment clonedAppointment:clonedAppointments) {
clone.addAppointment(clonedAppointment);
}
for (Allocatable allocatable:allocatables) {
clone.addAllocatable( allocatable);
Appointment[] appointments = restrictions.get(allocatable);
if (appointments != null) {
clone.setRestriction(allocatable, appointments);
}
}
return clone;
}
public <T extends Entity> T getPersistant(T entity) throws RaplaException {
Set<T> persistantList = Collections.singleton( entity);
Map<T,T> map = getPersistant( persistantList);
T result = map.get( entity);
if ( result == null)
{
throw new EntityNotFoundException( "There is no persistant version of " + entity);
}
return result;
}
public <T extends Entity> Map<T,T> getPersistant(Collection<T> list) throws RaplaException {
Map<Entity,Entity> result = operator.getPersistant(list);
LinkedHashMap<T, T> castedResult = new LinkedHashMap<T, T>();
for ( Map.Entry<Entity,Entity> entry: result.entrySet())
{
@SuppressWarnings("unchecked")
T key = (T) entry.getKey();
@SuppressWarnings("unchecked")
T value = (T) entry.getValue();
castedResult.put( key, value);
}
return castedResult;
}
public void store(Entity<?> obj) throws RaplaException {
if (obj == null)
throw new NullPointerException("Can't store null objects");
storeObjects(new Entity[] { obj });
}
public void remove(Entity<?> obj) throws RaplaException {
if (obj == null)
throw new NullPointerException("Can't remove null objects");
removeObjects(new Entity[] { obj });
}
public void storeObjects(Entity<?>[] obj) throws RaplaException {
storeAndRemove(obj, Entity.ENTITY_ARRAY);
}
public void removeObjects(Entity<?>[] obj) throws RaplaException {
storeAndRemove(Entity.ENTITY_ARRAY, obj);
}
public void storeAndRemove(Entity<?>[] storeObjects, Entity<?>[] removedObjects) throws RaplaException {
if (storeObjects.length == 0 && removedObjects.length == 0)
return;
long time = System.currentTimeMillis();
for (int i = 0; i < storeObjects.length; i++) {
if (storeObjects[i] == null) {
throw new RaplaException("Stored Objects cant be null");
}
if (storeObjects[i].getRaplaType() == Reservation.TYPE) {
checkReservation((Reservation) storeObjects[i]);
}
}
for (int i = 0; i < removedObjects.length; i++) {
if (removedObjects[i] == null) {
throw new RaplaException("Removed Objects cant be null");
}
}
ArrayList<Entity>storeList = new ArrayList<Entity>();
ArrayList<Entity>removeList = new ArrayList<Entity>();
for (Entity toStore : storeObjects) {
storeList.add( toStore);
}
for (Entity<?> toRemove : removedObjects) {
removeList.add( toRemove);
}
User workingUser = getWorkingUser();
operator.storeAndRemove(storeList, removeList, workingUser);
if (getLogger().isDebugEnabled())
getLogger().debug("Storing took " + (System.currentTimeMillis() - time) + " ms.");
}
public CommandHistory getCommandHistory()
{
return commandHistory;
}
public void changeName(String title, String firstname, String surname) throws RaplaException
{
User user = getUser();
getOperator().changeName(user,title,firstname,surname);
}
public void changeEmail(String newEmail) throws RaplaException
{
User user = getUser();
getOperator().changeEmail(user, newEmail);
}
public void confirmEmail(String newEmail) throws RaplaException {
User user = getUser();
getOperator().confirmEmail(user, newEmail);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.AllocationChangeEvent;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.UpdateResult;
/** Converts updateResults into AllocationChangeEvents */
public class AllocationChangeFinder
{
ArrayList<AllocationChangeEvent> changeList = new ArrayList<AllocationChangeEvent>();
UpdateResult updateResult;
Logger logger;
private AllocationChangeFinder(Logger logger, UpdateResult updateResult) {
this.logger = logger;
if ( updateResult == null)
return;
User user = updateResult.getUser();
for (Iterator<UpdateResult.Add> it = updateResult.getOperations( UpdateResult.Add.class );it.hasNext();) {
UpdateResult.Add addOp = it.next();
added( addOp.getNew(), user );
}
for (Iterator<UpdateResult.Remove> it = updateResult.getOperations( UpdateResult.Remove.class );it.hasNext();) {
UpdateResult.Remove removeOp = it.next();
removed( removeOp.getCurrent(), user );
}
for (Iterator<UpdateResult.Change> it = updateResult.getOperations( UpdateResult.Change.class );it.hasNext();) {
UpdateResult.Change changeOp = it.next();
Entity old = changeOp.getOld();
Entity newObj = changeOp.getNew();
changed(old , newObj, user );
}
}
public Logger getLogger()
{
return logger;
}
static public List<AllocationChangeEvent> getTriggerEvents(UpdateResult result,Logger logger) {
AllocationChangeFinder finder = new AllocationChangeFinder(logger, result);
return finder.changeList;
}
private void added(RaplaObject entity, User user) {
RaplaType raplaType = entity.getRaplaType();
if ( raplaType == Reservation.TYPE ) {
Reservation newRes = (Reservation) entity;
addAppointmentAdd(
user
,newRes
,Arrays.asList(newRes.getAllocatables())
,Arrays.asList(newRes.getAppointments())
);
}
}
private void removed(RaplaObject entity,User user) {
RaplaType raplaType = entity.getRaplaType();
if ( raplaType == Reservation.TYPE ) {
if (getLogger().isDebugEnabled())
getLogger().debug("Reservation removed: " + entity);
Reservation oldRes = (Reservation) entity;
addAppointmentRemove(
user
,oldRes
,oldRes
,Arrays.asList(oldRes.getAllocatables())
,Arrays.asList(oldRes.getAppointments())
);
}
}
private void changed(Entity oldEntity,Entity newEntity, User user) {
RaplaType raplaType = oldEntity.getRaplaType();
if (raplaType == Reservation.TYPE ) {
if (getLogger().isDebugEnabled())
getLogger().debug("Reservation changed: " + oldEntity);
Reservation oldRes = (Reservation) oldEntity;
Reservation newRes = (Reservation) newEntity;
List<Allocatable> alloc1 = Arrays.asList(oldRes.getAllocatables());
List<Allocatable> alloc2 = Arrays.asList(newRes.getAllocatables());
List<Appointment> app1 = Arrays.asList(oldRes.getAppointments());
List<Appointment> app2 = Arrays.asList(newRes.getAppointments());
ArrayList<Allocatable> removeList = new ArrayList<Allocatable>(alloc1);
removeList.removeAll(alloc2);
// add removed allocations to the change list
addAppointmentRemove(user, oldRes,newRes, removeList, app1);
ArrayList<Allocatable> addList = new ArrayList<Allocatable>(alloc2);
addList.removeAll(alloc1);
// add new allocations to the change list
addAppointmentAdd(user, newRes, addList, app2);
ArrayList<Allocatable> changeList = new ArrayList<Allocatable>(alloc2);
changeList.retainAll(alloc1);
addAllocationDiff(user, changeList,oldRes,newRes);
}
if ( Appointment.TYPE == raplaType ) {
if (getLogger().isDebugEnabled())
getLogger().debug("Appointment changed: " + oldEntity + " to " + newEntity);
}
}
/*
private void printList(List list) {
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
*/
/**
* Calculates the allocations that have changed
*/
private void addAllocationDiff(User user,List<Allocatable> allocatableList,Reservation oldRes,Reservation newRes) {
List<Appointment> app1 = Arrays.asList(oldRes.getAppointments());
List<Appointment> app2 = Arrays.asList(newRes.getAppointments());
ArrayList<Appointment> removeList = new ArrayList<Appointment>(app1);
removeList.removeAll(app2);
addAppointmentRemove(user, oldRes,newRes,allocatableList,removeList);
ArrayList<Appointment> addList = new ArrayList<Appointment>(app2);
addList.removeAll(app1);
addAppointmentAdd(user, newRes,allocatableList,addList);
/*
System.out.println("OLD appointments");
printList(app1);
System.out.println("NEW appointments");
printList(app2);
*/
Set<Appointment> newList = new HashSet<Appointment>(app2);
newList.retainAll(app1);
ArrayList<Appointment> oldList = new ArrayList<Appointment>(app1);
oldList.retainAll(app2);
sort(oldList);
for (int i=0;i<oldList.size();i++) {
Appointment oldApp = oldList.get(i);
Appointment newApp = null;
for ( Appointment app:newList)
{
if ( app.equals( oldApp))
{
newApp = app;
}
}
if ( newApp == null)
{
// This should never happen as we call retainAll before
getLogger().error("Not found matching pair for " + oldApp);
continue;
}
for (Allocatable allocatable: allocatableList )
{
boolean oldAllocated = oldRes.hasAllocated(allocatable, oldApp);
boolean newAllocated = newRes.hasAllocated(allocatable, newApp);
if (!oldAllocated && !newAllocated) {
continue;
}
else if (!oldAllocated && newAllocated)
{
changeList.add(new AllocationChangeEvent(AllocationChangeEvent.ADD,user,newRes,allocatable,newApp));
}
else if (oldAllocated && !newAllocated)
{
changeList.add(new AllocationChangeEvent(AllocationChangeEvent.REMOVE,user,newRes,allocatable,newApp));
}
else if (!newApp.matches(oldApp))
{
getLogger().debug("\n" + newApp + " doesn't match \n" + oldApp);
changeList.add(new AllocationChangeEvent(user,newRes,allocatable,newApp,oldApp));
}
}
}
}
@SuppressWarnings("unchecked")
public void sort(ArrayList<Appointment> oldList) {
Collections.sort(oldList);
}
private void addAppointmentAdd(User user,Reservation newRes,List<Allocatable> allocatables,List<Appointment> appointments) {
for (Allocatable allocatable:allocatables)
{
for (Appointment appointment:appointments)
{
if (!newRes.hasAllocated(allocatable,appointment))
continue;
changeList.add(new AllocationChangeEvent(AllocationChangeEvent.ADD,user, newRes,allocatable,appointment));
}
}
}
private void addAppointmentRemove(User user,Reservation oldRes,Reservation newRes,List<Allocatable> allocatables,List<Appointment> appointments) {
for (Allocatable allocatable:allocatables)
{
for (Appointment appointment:appointments)
{
if (!oldRes.hasAllocated(allocatable,appointment))
continue;
changeList.add(new AllocationChangeEvent(AllocationChangeEvent.REMOVE,user, newRes,allocatable,appointment));
}
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade.internal;
import java.util.Calendar;
import java.util.LinkedHashSet;
import java.util.Set;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.facade.CalendarOptions;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
/** <strong>WARNING!!</strong> This class should not be public to the outside. Please use the interface */
public class CalendarOptionsImpl implements CalendarOptions {
public final static TypedComponentRole<RaplaConfiguration> CALENDAR_OPTIONS= new TypedComponentRole<RaplaConfiguration>("org.rapla.calendarview");
public final static TypedComponentRole<Boolean> SHOW_CONFLICT_WARNING = new TypedComponentRole<Boolean>("org.rapla.conflict.showWarning");
public static final String WORKTIME = "worktime";
public static final String EXCLUDE_DAYS = "exclude-days";
public static final String WEEKSTART = "exclude-days";
public static final String ROWS_PER_HOUR = "rows-per-hour";
public final static String EXCEPTIONS_VISIBLE="exceptions-visible";
public final static String COMPACT_COLUMNS="compact-columns";
public final static String COLOR_BLOCKS="color";
public final static String COLOR_RESOURCES="resources";
public final static String COLOR_EVENTS="reservations";
public final static String COLOR_EVENTS_AND_RESOURCES="reservations_and_resources";
public final static String COLOR_NONE="disabled";
public final static String DAYS_IN_WEEKVIEW = "days-in-weekview";
public final static String FIRST_DAY_OF_WEEK = "first-day-of-week";
public final static String MIN_BLOCK_WIDTH = "minimum-block-width";
/** The following fields will be replaced in version 1.7 as they don't refer to the calendar but to the creation of appointment. Please don't use*/
public final static String REPEATING="repeating";
public final static String NTIMES="repeating.ntimes";
public final static String CALNAME="calendar-name";
public final static String REPEATINGTYPE="repeatingtype";
public final static String NON_FILTERED_EVENTS= "non-filtered-events";
public final static String NON_FILTERED_EVENTS_TRANSPARENT= "transparent";
public final static String NON_FILTERED_EVENTS_HIDDEN= "not_visible";
int nTimes;
/** Ends here*/
Set<Integer> excludeDays = new LinkedHashSet<Integer>();
int maxtimeMinutes = -1;
int mintimeMinutes = -1;
int rowsPerHour = 4;
boolean exceptionsVisible;
boolean compactColumns = false; // use for strategy.setFixedSlotsEnabled
Configuration config;
String colorField;
boolean nonFilteredEventsVisible = false;
int daysInWeekview;
int firstDayOfWeek;
private int minBlockWidth;
public CalendarOptionsImpl(Configuration config ) throws RaplaException {
this.config = config;
Configuration worktime = config.getChild( WORKTIME );
String worktimesString = worktime.getValue("8-18");
int minusIndex = worktimesString.indexOf("-");
try {
if ( minusIndex >= 0)
{
String firstPart = worktimesString.substring(0,minusIndex);
String secondPart = worktimesString.substring(minusIndex+ 1);
mintimeMinutes = parseMinutes( firstPart );
maxtimeMinutes = parseMinutes( secondPart );
}
else
{
mintimeMinutes = parseMinutes( worktimesString);
}
} catch ( NumberFormatException e ) {
throw new RaplaException( "Invalid time in " + worktime + ". use the following format : 8-18 or 8:30-18:00!");
}
Configuration exclude = config.getChild( EXCLUDE_DAYS );
String excludeString = exclude.getValue("");
if ( excludeString.trim().length() > 0)
{
String[] tokens = excludeString.split(",");
for ( String token:tokens)
{
String normalizedToken = token.toLowerCase().trim();
try {
excludeDays.add( new Integer(normalizedToken) );
} catch ( NumberFormatException e ) {
throw new RaplaException("Invalid day in " + excludeDays + ". only numbers are allowed!");
}
} // end of while ()
}
int firstDayOfWeekDefault = Calendar.getInstance().getFirstDayOfWeek();
firstDayOfWeek = config.getChild(FIRST_DAY_OF_WEEK).getValueAsInteger(firstDayOfWeekDefault);
daysInWeekview = config.getChild(DAYS_IN_WEEKVIEW).getValueAsInteger( 7 );
rowsPerHour = config.getChild( ROWS_PER_HOUR ).getValueAsInteger( 4 );
exceptionsVisible = config.getChild(EXCEPTIONS_VISIBLE).getValueAsBoolean(false);
colorField = config.getChild( COLOR_BLOCKS ).getValue( COLOR_EVENTS_AND_RESOURCES );
minBlockWidth = config.getChild( MIN_BLOCK_WIDTH).getValueAsInteger(0);
nTimes = config.getChild( NTIMES ).getValueAsInteger( 1 );
nonFilteredEventsVisible = config.getChild( NON_FILTERED_EVENTS).getValue(NON_FILTERED_EVENTS_TRANSPARENT).equals( NON_FILTERED_EVENTS_TRANSPARENT);
}
private int parseMinutes(String string) {
String[] split = string.split(":");
int hour = Integer.parseInt(split[0].toLowerCase().trim());
int minute = 0;
if ( split.length > 1)
{
minute = Integer.parseInt(split[1].toLowerCase().trim());
}
int result = Math.max(0,Math.min(24 * 60,hour * 60 + minute));
return result;
}
public Configuration getConfig() {
return config;
}
public int getWorktimeStart() {
return mintimeMinutes / 60;
}
public int getRowsPerHour() {
return rowsPerHour;
}
public int getWorktimeEnd() {
return maxtimeMinutes / 60;
}
public Set<Integer> getExcludeDays() {
return excludeDays;
}
public boolean isNonFilteredEventsVisible()
{
return nonFilteredEventsVisible;
}
public void setNonFilteredEventsVisible(boolean nonFilteredEventsVisible)
{
this.nonFilteredEventsVisible = nonFilteredEventsVisible;
}
public boolean isExceptionsVisible() {
return exceptionsVisible;
}
public boolean isCompactColumns() {
return compactColumns;
}
public boolean isResourceColoring() {
return colorField.equals( COLOR_RESOURCES ) || colorField.equals( COLOR_EVENTS_AND_RESOURCES);
}
public boolean isEventColoring() {
return colorField.equals( COLOR_EVENTS ) || colorField.equals( COLOR_EVENTS_AND_RESOURCES);
}
public int getDaysInWeekview() {
return daysInWeekview;
}
public int getFirstDayOfWeek()
{
return firstDayOfWeek;
}
public int getMinBlockWidth()
{
return minBlockWidth;
}
public boolean isWorktimeOvernight() {
int worktimeS = getWorktimeStartMinutes();
int worktimeE = getWorktimeEndMinutes();
worktimeE = (worktimeE == 0)?24*60:worktimeE;
boolean overnight = worktimeS >= worktimeE|| worktimeE == 24*60;
return overnight;
}
public int getWorktimeStartMinutes() {
return mintimeMinutes;
}
public int getWorktimeEndMinutes() {
return maxtimeMinutes;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.rapla.components.util.DateTools;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.entities.storage.EntityResolver;
import org.rapla.entities.storage.internal.SimpleEntity;
import org.rapla.facade.Conflict;
import org.rapla.facade.RaplaComponent;
/**
* A conflict is the allocation of the same resource at the same time by different
* reservations. There's one conflict for each resource and each overlapping of
* two allocations. So if there are 3 reservations that allocate the same 2 resources
* on 2 days of the week, then we got ( 3 * 2 ) * 2 * 2 = 24 conflicts. Thats
* 3 reservations, each conflicting with two other 2 reservations on 2 days with 2 resources.
*
* @author Christopher Kohlhaas
*/
public class ConflictImpl extends SimpleEntity implements Conflict
{
Date startDate;
String reservation1Name;
String reservation2Name;
ConflictImpl() {
}
public ConflictImpl(
Allocatable allocatable,
Appointment app1,
Appointment app2,
Date today
)
{
this(allocatable,app1,app2, today,createId(allocatable.getId(), app1.getId(), app2.getId()));
}
public ConflictImpl(
Allocatable allocatable,
Appointment app1,
Appointment app2,
Date today,
String id
)
{
putEntity("allocatable", allocatable);
startDate = getStartDate_(today, app1, app2);
putEntity("appointment1", app1);
putEntity("appointment2", app2);
Reservation reservation1 = app1.getReservation();
Reservation reservation2 = app2.getReservation();
putEntity("reservation1", reservation1);
putEntity("reservation2", reservation2);
putEntity("owner1", reservation1.getOwner());
putEntity("owner2", reservation2.getOwner());
this.reservation1Name = reservation1.getName(Locale.getDefault());
this.reservation2Name = reservation2.getName(Locale.getDefault());
setResolver( ((AllocatableImpl)allocatable).getResolver());
setId( id);
}
public String getReservation1Name() {
return reservation1Name;
}
public String getReservation2Name() {
return reservation2Name;
}
public Date getStartDate()
{
return startDate;
}
@Override
public Iterable<ReferenceInfo> getReferenceInfo() {
return Collections.emptyList();
}
private Date getStartDate_(Date today,Appointment app1, Appointment app2) {
Date fromDate = today;
Date start1 = app1.getStart();
if ( start1.before( fromDate))
{
fromDate = start1;
}
Date start2 = app2.getStart();
if ( start2.before( fromDate))
{
fromDate = start2;
}
Date toDate = DateTools.addDays( today, 365 * 10);
Date date = getFirstConflictDate(fromDate, toDate, app1, app2);
return date;
}
static public String createId(String allocId, String id1, String id2)
{
StringBuilder buf = new StringBuilder();
//String id1 = getId("appointment1");
//String id2 = getId("appointment2");
if ( id1.equals( id2))
{
throw new IllegalStateException("ids of conflicting appointments are the same " + id1);
}
buf.append(allocId);
buf.append(';');
buf.append(id1.compareTo( id2) > 0 ? id1 : id2);
buf.append(';');
buf.append(id1.compareTo( id2) > 0 ? id2 : id1);
return buf.toString();
}
// public ConflictImpl(String id) throws RaplaException {
// String[] split = id.split(";");
// ReferenceHandler referenceHandler = getReferenceHandler();
// referenceHandler.putId("allocatable", LocalCache.getId(Allocatable.TYPE,split[0]));
// referenceHandler.putId("appointment1", LocalCache.getId(Appointment.TYPE,split[1]));
// referenceHandler.putId("appointment2", LocalCache.getId(Appointment.TYPE,split[2]));
// setId( id);
// }
// public static boolean isConflictId(String id) {
// if ( id == null)
// {
// return false;
// }
// String[] split = id.split(";");
// if ( split.length != 3)
// {
// return false;
// }
// try {
// LocalCache.getId(Allocatable.TYPE,split[0]);
// LocalCache.getId(Appointment.TYPE,split[1]);
// LocalCache.getId(Appointment.TYPE,split[2]);
// } catch (RaplaException e) {
// return false;
// }
// return true;
// }
/** @return the first Reservation, that is involed in the conflict.*/
// public Reservation getReservation1()
// {
// Appointment appointment1 = getAppointment1();
// if ( appointment1 == null)
// {
// throw new IllegalStateException("Appointment 1 is null resolve not called");
// }
// return appointment1.getReservation();
// }
/** The appointment of the first reservation, that causes the conflict. */
public String getAppointment1()
{
return getId("appointment1");
}
public String getReservation1()
{
return getId("reservation1");
}
public String getReservation2()
{
return getId("reservation2");
}
/** @return the allocatable, allocated for the same time by two different reservations. */
public Allocatable getAllocatable()
{
return getEntity("allocatable", Allocatable.class);
}
// /** @return the second Reservation, that is involed in the conflict.*/
// public Reservation getReservation2()
// {
// Appointment appointment2 = getAppointment2();
// if ( appointment2 == null)
// {
// throw new IllegalStateException("Appointment 2 is null resolve not called");
// }
// return appointment2.getReservation();
// }
// /** @return The User, who created the second Reservation.*/
// public User getUser2()
// {
// return getReservation2().getOwner();
// }
/** The appointment of the second reservation, that causes the conflict. */
public String getAppointment2()
{
return getId("appointment2");
}
public static final ConflictImpl[] CONFLICT_ARRAY= new ConflictImpl[] {};
/**
* @see org.rapla.entities.Named#getName(java.util.Locale)
*/
public String getName(Locale locale) {
return getAllocatable().getName( locale );
}
public boolean isOwner( User user)
{
User owner1 = getOwner1();
User owner2 = getOwner2();
if (user != null && !user.equals(owner1) && !user.equals(owner2)) {
return false;
}
return true;
}
// public Date getFirstConflictDate(final Date fromDate, Date toDate) {
// Appointment a1 =getAppointment1();
// Appointment a2 =getAppointment2();
// return getFirstConflictDate(fromDate, toDate, a1, a2);
//}
public User getOwner1() {
return getEntity("owner1", User.class);
}
public User getOwner2() {
return getEntity("owner2", User.class);
}
private boolean contains(String appointmentId) {
if ( appointmentId == null)
return false;
String app1 = getAppointment1();
String app2 = getAppointment2();
if ( app1 != null && app1.equals( appointmentId))
return true;
if ( app2 != null && app2.equals( appointmentId))
return true;
return false;
}
static public boolean equals( ConflictImpl firstConflict,Conflict secondConflict) {
if (secondConflict == null )
return false;
if (!firstConflict.contains( secondConflict.getAppointment1()))
return false;
if (!firstConflict.contains( secondConflict.getAppointment2()))
return false;
Allocatable allocatable = firstConflict.getAllocatable();
if ( allocatable != null && !allocatable.equals( secondConflict.getAllocatable())) {
return false;
}
return true;
}
private static boolean contains(ConflictImpl conflict,
Collection<Conflict> conflictList) {
for ( Conflict conf:conflictList)
{
if ( equals(conflict,conf))
{
return true;
}
}
return false;
}
public RaplaType<Conflict> getRaplaType()
{
return Conflict.TYPE;
}
public String toString()
{
Conflict conflict = this;
StringBuffer buf = new StringBuffer();
buf.append( "Conflict for");
buf.append( conflict.getAllocatable());
buf.append( " " );
buf.append( conflict.getAppointment1());
buf.append( " " );
buf.append( "with");
buf.append( " " );
buf.append( conflict.getAppointment2());
buf.append( " " );
return buf.toString();
}
static public Date getFirstConflictDate(final Date fromDate, Date toDate,
Appointment a1, Appointment a2) {
Date minEnd = a1.getMaxEnd();
if ( a1.getMaxEnd() != null && a2.getMaxEnd() != null && a2.getMaxEnd().before( a1.getMaxEnd())) {
minEnd = a2.getMaxEnd();
}
Date maxStart = a1.getStart();
if ( a2.getStart().after( a1.getStart())) {
maxStart = a2.getStart();
}
if ( fromDate != null && maxStart.before( fromDate))
{
maxStart = fromDate;
}
// look for 10 years in the future (520 weeks)
if ( minEnd == null)
minEnd = new Date(maxStart.getTime() + DateTools.MILLISECONDS_PER_DAY * 365 * 10 );
if ( toDate != null && minEnd.after( toDate))
{
minEnd = toDate;
}
List<AppointmentBlock> listA = new ArrayList<AppointmentBlock>();
a1.createBlocks(maxStart, minEnd, listA );
List<AppointmentBlock> listB = new ArrayList<AppointmentBlock>();
a2.createBlocks( maxStart, minEnd, listB );
for ( int i=0, j=0;i<listA.size() && j<listB.size();) {
long s1 = listA.get( i).getStart();
long s2 = listB.get( j).getStart();
long e1 = listA.get( i).getEnd();
long e2 = listB.get( j).getEnd();
if ( s1< e2 && s2 < e1) {
return new Date( Math.max( s1, s2));
}
if ( s1> s2)
j++;
else
i++;
}
return null;
}
public static void addConflicts(Collection<Conflict> conflictList, Allocatable allocatable,Appointment appointment1, Appointment appointment2,Date today)
{
final ConflictImpl conflict = new ConflictImpl(allocatable,appointment1, appointment2, today);
// Rapla 1.4: Don't add conflicts twice
if (!contains(conflict, conflictList) )
{
conflictList.add(conflict);
}
}
public static boolean endsBefore(Appointment appointment1,Appointment appointment2, Date date) {
Date maxEnd1 = appointment1.getMaxEnd();
Date maxEnd2 = appointment2.getMaxEnd();
if (maxEnd1 != null && maxEnd1.before( date))
{
return true;
}
if (maxEnd2 != null && maxEnd2.before( date))
{
return true;
}
return false;
}
public static boolean isConflict(Appointment appointment1,Appointment appointment2, Date today) {
// Don't add conflicts, when in the past
if (endsBefore(appointment1, appointment2, today))
{
return false;
}
if (appointment1.equals(appointment2))
return false;
if (RaplaComponent.isTemplate( appointment1))
{
return false;
}
if (RaplaComponent.isTemplate( appointment2))
{
return false;
}
boolean conflictTypes = checkForConflictTypes( appointment1, appointment2);
if ( !conflictTypes )
{
return false;
}
Date maxEnd1 = appointment1.getMaxEnd();
Date maxEnd2 = appointment2.getMaxEnd();
Date checkEnd = maxEnd1;
if ( maxEnd2 != null && checkEnd !=null && maxEnd2.before( checkEnd) )
{
checkEnd = maxEnd2;
}
if (checkEnd != null && ConflictImpl.getFirstConflictDate(today, checkEnd, appointment1, appointment2) == null)
{
return false;
}
return true;
}
public static boolean isConflictWithoutCheck(Appointment appointment1,Appointment appointment2, Date today) {
// Don't add conflicts, when in the past
if (appointment1.equals(appointment2))
return false;
boolean conflictTypes = checkForConflictTypes2( appointment1, appointment2);
if ( !conflictTypes )
{
return false;
}
Date maxEnd1 = appointment1.getMaxEnd();
Date maxEnd2 = appointment2.getMaxEnd();
Date checkEnd = maxEnd1;
if ( maxEnd2 != null && checkEnd !=null && maxEnd2.before( checkEnd) )
{
checkEnd = maxEnd2;
}
if (checkEnd != null && ConflictImpl.getFirstConflictDate(today, checkEnd, appointment1, appointment2) == null)
{
return false;
}
return true;
}
@SuppressWarnings("null")
private static boolean checkForConflictTypes(Appointment a1, Appointment a2) {
Reservation r1 = a1.getReservation();
DynamicType type1 = r1 != null ? r1.getClassification().getType() : null;
String annotation1 = getConflictAnnotation( type1);
if ( isNoConflicts( annotation1 ) )
{
return false;
}
Reservation r2 = a2.getReservation();
DynamicType type2 = r2 != null ? r2.getClassification().getType() : null;
String annotation2 = getConflictAnnotation( type2);
if ( isNoConflicts ( annotation2))
{
return false;
}
if ( annotation1 != null )
{
if ( annotation1.equals(DynamicTypeAnnotations.VALUE_CONFLICTS_WITH_OTHER_TYPES))
{
if (type2 != null)
{
if (type1.equals(type2))
{
return false;
}
}
}
}
return true;
}
@SuppressWarnings("null")
private static boolean checkForConflictTypes2(Appointment a1, Appointment a2) {
Reservation r1 = a1.getReservation();
DynamicType type1 = r1 != null ? r1.getClassification().getType() : null;
String annotation1 = getConflictAnnotation( type1);
Reservation r2 = a2.getReservation();
DynamicType type2 = r2 != null ? r2.getClassification().getType() : null;
if ( annotation1 != null )
{
if ( annotation1.equals(DynamicTypeAnnotations.VALUE_CONFLICTS_WITH_OTHER_TYPES))
{
if (type2 != null)
{
if (type1.equals(type2))
{
return false;
}
}
}
}
return true;
}
public static boolean isNoConflicts(String annotation) {
if ( annotation != null && annotation.equals(DynamicTypeAnnotations.VALUE_CONFLICTS_NONE))
{
return true;
}
return false;
}
public static String getConflictAnnotation( DynamicType type) {
if ( type == null)
{
return null;
}
return type.getAnnotation(DynamicTypeAnnotations.KEY_CONFLICTS);
}
public boolean hasAppointment(Appointment appointment)
{
boolean result = getAppointment1().equals( appointment) || getAppointment2().equals( appointment);
return result;
}
@Override
public Conflict clone()
{
ConflictImpl clone = new ConflictImpl();
super.deepClone( clone);
return clone;
}
static public boolean canModify(Conflict conflict,User user, EntityResolver resolver) {
Allocatable allocatable = conflict.getAllocatable();
if (user == null || user.isAdmin())
{
return true;
}
if (allocatable.canRead( user ))
{
Reservation reservation = resolver.tryResolve(conflict.getReservation1(), Reservation.class);
if ( reservation == null )
{
// reservation will be deleted, and conflict also so return
return false;
}
if (RaplaComponent.canModify(reservation, user) )
{
return true;
}
Reservation overlappingReservation = resolver.tryResolve(conflict.getReservation2(), Reservation.class);
if ( overlappingReservation == null )
{
return false;
}
if (RaplaComponent.canModify(overlappingReservation, user))
{
return true;
}
}
return false;
}
public static Map<Appointment, Set<Appointment>> getMap(Collection<Conflict> selectedConflicts,List<Reservation> reservations)
{
Map<Appointment, Set<Appointment>> result = new HashMap<Appointment,Set<Appointment>>();
Map<String, Appointment> map = new HashMap<String,Appointment>();
for ( Reservation reservation:reservations)
{
for (Appointment app:reservation.getAppointments())
{
map.put( app.getId(), app);
}
}
for ( Conflict conflict:selectedConflicts)
{
Appointment app1 = map.get(conflict.getAppointment1());
Appointment app2 = map.get(conflict.getAppointment2());
add(result, app1, app2);
add(result, app2, app1);
}
return result;
}
private static void add(Map<Appointment, Set<Appointment>> result,Appointment app1, Appointment app2) {
Set<Appointment> set = result.get( app1);
if ( set == null)
{
set = new HashSet<Appointment>();
result.put(app1,set);
}
set.add( app2);
}
}
| Java |
package org.rapla.facade;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
public interface CalendarModel extends Cloneable, ClassifiableFilter
{
public static final String SHOW_NAVIGATION_ENTRY = "org.rapla.plugin.abstractcalendar.show_navigation";
public static final String ONLY_ALLOCATION_INFO = "org.rapla.plugin.abstractcalendar.only_allocation_info";
public static final String SAVE_SELECTED_DATE = "org.rapla.plugin.abstractcalendar.save_selected_date";
public static final String ONLY_MY_EVENTS = "only_own_reservations";
public static final TypedComponentRole<Boolean> ONLY_MY_EVENTS_DEFAULT = new TypedComponentRole<Boolean>("org.rapla.plugin.abstractcalendar.only_own_reservations");
String getNonEmptyTitle();
User getUser();
Date getSelectedDate();
void setSelectedDate( Date date );
Date getStartDate();
void setStartDate( Date date );
Date getEndDate();
void setEndDate( Date date );
Collection<RaplaObject> getSelectedObjects();
/** Calendar View Plugins can use the calendar options to store their requiered optional parameters for a calendar view */
String getOption(String name);
Collection<RaplaObject> getSelectedObjectsAndChildren() throws RaplaException;
/** Convenience method to extract the allocatables from the selectedObjects and their children
* @see #getSelectedObjectsAndChildren */
Allocatable[] getSelectedAllocatables() throws RaplaException;
Reservation[] getReservations( Date startDate, Date endDate ) throws RaplaException;
Reservation[] getReservations() throws RaplaException;
CalendarModel clone();
List<AppointmentBlock> getBlocks() throws RaplaException;
DynamicType guessNewEventType() throws RaplaException;
/** returns the marked time intervals in the calendar. */
Collection<TimeInterval> getMarkedIntervals();
Collection<Allocatable> getMarkedAllocatables();
} | Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.Set;
/** This class contains the configuration options for the calendar views
like Worktimes and dates configuration is done in the calendar option menu.
Hours belonging to the worktime get a different color in the
weekview. This is also the minimum interval that will be used for
printing.<br>
Excluded Days are only visible, when there is an appointment to
display.<br>
*/
public interface CalendarOptions {
/** return the worktimeStart in hours
* @deprecated use {@link #getWorktimeStartMinutes()} instead*/
@Deprecated
int getWorktimeStart();
int getRowsPerHour();
/** return the worktimeEnd in hours
* @deprecated use {@link #getWorktimeEndMinutes()} instead*/
@Deprecated
int getWorktimeEnd();
Set<Integer> getExcludeDays();
int getDaysInWeekview();
int getFirstDayOfWeek();
boolean isExceptionsVisible();
boolean isCompactColumns();
boolean isResourceColoring();
boolean isEventColoring();
int getMinBlockWidth();
int getWorktimeStartMinutes();
int getWorktimeEndMinutes();
boolean isNonFilteredEventsVisible();
boolean isWorktimeOvernight();
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.HashMap;
import java.util.Map;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
public class AllocationChangeEvent
{
static Map<String,Type> TYPES = new HashMap<String,Type>();
public static class Type
{
private String type;
Type( String type )
{
TYPES.put( type, this );
this.type = type;
}
public String toString()
{
return type;
}
}
Type m_type;
public static Type CHANGE = new Type( "change" );
public static Type ADD = new Type( "add" );
public static Type REMOVE = new Type( "remove" );
User m_user;
Reservation m_newReservation;
Allocatable m_allocatable;
Appointment m_newAppointment;
Appointment m_oldAppointment;
public AllocationChangeEvent( Type type, User user, Reservation newReservation, Allocatable allocatable,
Appointment appointment )
{
m_user = user;
m_type = type;
m_allocatable = allocatable;
if ( type.equals( REMOVE ) )
m_oldAppointment = appointment;
m_newAppointment = appointment;
m_newReservation = newReservation;
}
public AllocationChangeEvent( User user, Reservation newReservation, Allocatable allocatable,
Appointment newAppointment, Appointment oldApp )
{
this( CHANGE, user, newReservation, allocatable, newAppointment );
m_oldAppointment = oldApp;
}
/** either Type.CHANGE,Type.REMOVE or Type.ADD */
public Type getType()
{
return m_type;
}
/** returns the user-object, of the user that made the change.
* <strong>Warning can be null</strong>
*/
public User getUser()
{
return m_user;
}
public Allocatable getAllocatable()
{
return m_allocatable;
}
public Appointment getNewAppointment()
{
return m_newAppointment;
}
public Reservation getNewReservation()
{
return m_newReservation;
}
/** only available if type is "change" */
public Appointment getOldAppointment()
{
return m_oldAppointment;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.EventListener;
/** After a store all registered ChangeListeners get notified by calling
* the trigger method. A list with all changes is passed.
* At the moment only AllocationChangeEvents are triggered.
* By this you can get notified, when any Reservation changes.
* The difference between the UpdateEvent and a ChangeEvent is,
* that the UpdateEvent contains the new Versions of all updated enties,
* while a ChangeEvent contains Information about a single change.
* That change can be calculated as with the AllocationChangeEvent, which
* represents a single allocation change for one allocatable object
* ,including information about the old allocation and the new one.
* @see AllocationChangeEvent
*/
public interface AllocationChangeListener extends EventListener
{
void changed(AllocationChangeEvent[] changeEvents);
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import org.rapla.storage.StorageOperator;
/** A collection of all module-interfaces
*/
public interface ClientFacade
extends
UserModule
,ModificationModule
,QueryModule
,UpdateModule
{
StorageOperator getOperator();
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
public interface UpdateModule
{
public final static TypedComponentRole<Integer> REFRESH_INTERVAL_ENTRY = new TypedComponentRole<Integer>("org.rapla.refreshInterval");
public final static TypedComponentRole<Integer> ARCHIVE_AGE = new TypedComponentRole<Integer>("org.rapla.archiveAge");
public static final int REFRESH_INTERVAL_DEFAULT = 30000;
/**
* Refreshes the data that is in the cache (or on the client)
and notifies all registered {@link ModificationListener ModificationListeners}
with an update-event.
There are two types of refreshs.
<ul>
<li>Incremental Refresh: Only the changes are propagated</li>
<li>Full Refresh: The complete data is reread. (Currently disabled in Rapla)</li>
</ul>
<p>
Incremental refreshs are the normal case if you have a client server basis.
(In a single user system no refreshs are necessary at all).
The refreshs are triggered in defined intervals if you use the webbased communication
and automaticaly if you use the old communication layer. You can change the refresh interval
via the admin options.
</p>
<p>
Of course you can call a refresh anytime you want to synchronize with the server, e.g. if
you want to ensure you are uptodate before editing. If you are on the server you dont need to refresh.
</p>
<strong>WARNING: When using full refresh on a local file storage
all information will be changed. So use it
only if you modify the data from external.
You better re-get and re-draw all
the information in the Frontend after a full refresh.
</strong>
*/
void refresh() throws RaplaException;
/** returns if the Facade is connected through a server (false if it has a local store)*/
boolean isClientForServer();
/**
* registers a new ModificationListener.
* A ModifictionEvent will be fired to every registered DateChangeListener
* when one or more entities have been added, removed or changed
* @see ModificationListener
* @see ModificationEvent
*/
void addModificationListener(ModificationListener listener);
void removeModificationListener(ModificationListener listener);
void addUpdateErrorListener(UpdateErrorListener listener);
void removeUpdateErrorListener(UpdateErrorListener listener);
void addAllocationChangedListener(AllocationChangeListener triggerListener);
void removeAllocationChangedListener(AllocationChangeListener triggerListener);
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import org.rapla.framework.RaplaException;
/** Classes implementing this interface will be notified when an update error
* occurred. The listener can be registered by calling
* <code>addUpdateErrorListener</code> of the <code>UpdateModule</code> <br>
* Don't forget to remove the listener by calling <code>removeUpdateErrorLister</code>
* when no longer need.
* @author Christopher Kohlhaas
* @see UpdateModule
*/
public interface UpdateErrorListener {
/** this notifies all listeners that the update of the data has
caused an error. A normal source for UpdateErrors is a broken
connection to the server.
*/
void updateError(RaplaException ex);
void disconnected(String message);
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.framework.RaplaException;
public interface ClassifiableFilter
{
ClassificationFilter[] getReservationFilter() throws RaplaException ;
ClassificationFilter[] getAllocatableFilter() throws RaplaException ;
boolean isDefaultEventTypes();
boolean isDefaultResourceTypes();
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import org.rapla.entities.Entity;
import org.rapla.entities.Named;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
/**
* A conflict is the allocation of the same resource at the same time by different
* reservations. There's one conflict for each resource and each overlapping of
* two allocations. So if there are 3 reservations that allocate the same 2 resources
* on 2 days of the week, then we got ( 3 * 2 ) * 2 * 2 = 24 conflicts. Thats
* 3 reservations, each conflicting with two other 2 reservations on 2 days with 2 resources.
*
* @version 1.0
* @author Christopher Kohlhaas
*/
public interface Conflict extends Named, Entity<Conflict>
{
static public final RaplaType<Conflict> TYPE = new RaplaType<Conflict>(Conflict.class,"conflict");
/** @return the allocatable, allocated for the same time by two different reservations. */
public Allocatable getAllocatable();
// /** @return the first Reservation, that is involved in the conflict.*/
// public Reservation getReservation1();
/** The appointment of the first reservation, that causes the conflict. */
public String getAppointment1();
// /** @return the second Reservation, that is involved in the conflict.*/
// public Reservation getReservation2();
// /** @return The User, who created the second Reservation.*/
// public User getUser2();
/** The appointment of the second reservation, that causes the conflict. */
public String getAppointment2();
String getReservation1();
String getReservation2();
String getReservation1Name();
String getReservation2Name();
///** Find the first occurance of a conflict in the specified interval or null when not in intervall*/
//public Date getFirstConflictDate(final Date fromDate, final Date toDate);
//public boolean canModify(User user);
public boolean isOwner( User user);
public static final Conflict[] CONFLICT_ARRAY= new Conflict[] {};
public class Util
{
public static Collection<Allocatable> getAllocatables(
Collection<Conflict> conflictsSelected) {
LinkedHashSet<Allocatable> allocatables = new LinkedHashSet<Allocatable>();
for ( Conflict conflict: conflictsSelected)
{
allocatables.add(conflict.getAllocatable());
}
return allocatables;
}
// static public List<Reservation> getReservations(Collection<Conflict> conflicts) {
// Collection<Reservation> reservations = new LinkedHashSet<Reservation>();
// for (Conflict conflict:conflicts)
// {
// reservations.add(conflict.getReservation1());
// reservations.add(conflict.getReservation2());
//
// }
// return new ArrayList<Reservation>( reservations);
// }
//
}
boolean hasAppointment(Appointment appointment);
//boolean endsBefore(Date date);
Date getStartDate();
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.components.xmlbundle.CompoundI18n;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.Annotatable;
import org.rapla.entities.Category;
import org.rapla.entities.Named;
import org.rapla.entities.Ownable;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.configuration.internal.PreferencesImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentFormater;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.RaplaObjectAnnotations;
import org.rapla.entities.domain.ReservationStartComparator;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.Classifiable;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ConstraintIds;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.facade.internal.CalendarOptionsImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.RaplaSynchronizationException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.framework.logger.ConsoleLogger;
import org.rapla.framework.logger.Logger;
/**
Base class for most components. Eases
access to frequently used services, e.g. {@link I18nBundle}.
*/
public class RaplaComponent
{
public static final TypedComponentRole<I18nBundle> RAPLA_RESOURCES = new TypedComponentRole<I18nBundle>("org.rapla.RaplaResources");
public static final TypedComponentRole<RaplaConfiguration> PLUGIN_CONFIG= new TypedComponentRole<RaplaConfiguration>("org.rapla.plugin");
private final ClientServiceManager serviceManager;
private TypedComponentRole<I18nBundle> childBundleName;
private Logger logger;
private RaplaContext context;
public RaplaComponent(RaplaContext context) {
try {
logger = context.lookup(Logger.class );
} catch (RaplaContextException e) {
logger = new ConsoleLogger();
}
this.context = context;
this.serviceManager = new ClientServiceManager();
}
protected void setLogger(Logger logger)
{
this.logger = logger;
}
final public TypedComponentRole<I18nBundle> getChildBundleName() {
return childBundleName;
}
final public void setChildBundleName(TypedComponentRole<I18nBundle> childBundleName) {
this.childBundleName = childBundleName;
}
final protected Container getContainer() throws RaplaContextException {
return getContext().lookup(Container.class);
}
/** returns if the session user is admin */
final public boolean isAdmin() {
try {
return getUser().isAdmin();
} catch (RaplaException ex) {
}
return false;
}
/** returns if the session user is a registerer */
final public boolean isRegisterer() {
if (isAdmin())
{
return true;
}
try {
Category registererGroup = getQuery().getUserGroupsCategory().getCategory(Permission.GROUP_REGISTERER_KEY);
return getUser().belongsTo(registererGroup);
} catch (RaplaException ex) {
}
return false;
}
final public boolean isModifyPreferencesAllowed() {
if (isAdmin())
{
return true;
}
try {
Category modifyPreferences = getQuery().getUserGroupsCategory().getCategory(Permission.GROUP_MODIFY_PREFERENCES_KEY);
if ( modifyPreferences == null ) {
return true;
}
return getUser().belongsTo(modifyPreferences);
} catch (RaplaException ex) {
}
return false;
}
/** returns if the user has allocation rights for one or more resource */
final public boolean canUserAllocateSomething(User user) throws RaplaException {
Allocatable[] allocatables =getQuery().getAllocatables();
if ( user.isAdmin() )
return true;
if (!canCreateReservation(user))
{
return false;
}
for ( int i=0;i<allocatables.length;i++) {
Permission[] permissions = allocatables[i].getPermissions();
for ( int j=0;j<permissions.length;j++) {
Permission p = permissions[j];
if (!p.affectsUser( user ))
{
continue;
}
if ( p.getAccessLevel() > Permission.READ)
{
return true;
}
}
}
return false;
}
final public boolean canCreateReservation(User user) {
boolean result = getQuery().canCreateReservations(user);
return result;
}
final public boolean canCreateReservation() {
try {
User user = getUser();
return canCreateReservation( user);
} catch (RaplaException ex) {
return false;
}
}
protected boolean canAllocate()
{
CalendarSelectionModel model = getService( CalendarSelectionModel.class);
//Date start, Date end,
Collection<Allocatable> allocatables = getService(CalendarSelectionModel.class).getMarkedAllocatables();
boolean canAllocate = true;
Date start = getStartDate( model);
Date end = getEndDate( model, start);
for (Allocatable allo:allocatables)
{
if (!canAllocate( start, end, allo))
{
canAllocate = false;
}
}
return canAllocate;
}
protected Date getStartDate(CalendarModel model) {
Collection<TimeInterval> markedIntervals = model.getMarkedIntervals();
Date startDate = null;
if ( markedIntervals.size() > 0)
{
TimeInterval first = markedIntervals.iterator().next();
startDate = first.getStart();
}
if ( startDate != null)
{
return startDate;
}
Date selectedDate = model.getSelectedDate();
if ( selectedDate == null)
{
selectedDate = getQuery().today();
}
Date time = new Date (DateTools.MILLISECONDS_PER_MINUTE * getCalendarOptions().getWorktimeStartMinutes());
startDate = getRaplaLocale().toDate(selectedDate,time);
return startDate;
}
protected Date getEndDate( CalendarModel model,Date startDate) {
Collection<TimeInterval> markedIntervals = model.getMarkedIntervals();
Date endDate = null;
if ( markedIntervals.size() > 0)
{
TimeInterval first = markedIntervals.iterator().next();
endDate = first.getEnd();
}
if ( endDate != null)
{
return endDate;
}
return new Date(startDate.getTime() + DateTools.MILLISECONDS_PER_HOUR);
}
protected boolean canAllocate(Date start, Date end, Allocatable allocatables) {
if ( allocatables == null) {
return true;
}
try {
User user = getUser();
Date today = getQuery().today();
return allocatables.canAllocate( user, start, end, today );
} catch (RaplaException ex) {
return false;
}
}
/** returns if the current user is allowed to modify the object. */
final public boolean canModify(Object object) {
try {
User user = getUser();
return canModify(object, user);
} catch (RaplaException ex) {
return false;
}
}
static public boolean canModify(Object object, User user) {
if (object == null || !(object instanceof RaplaObject))
{
return false;
}
if ( user == null)
{
return false;
}
if (user.isAdmin())
return true;
if (object instanceof Ownable) {
Ownable ownable = (Ownable) object;
User owner = ownable.getOwner();
if ( owner != null && user.equals(owner))
{
return true;
}
if (object instanceof Allocatable) {
Allocatable allocatable = (Allocatable) object;
if (allocatable.canModify( user ))
{
return true;
}
if ( owner == null)
{
Category[] groups = user.getGroups();
for ( Category group: groups)
{
if (group.getKey().equals(Permission.GROUP_REGISTERER_KEY))
{
return true;
}
}
}
}
}
if (checkClassifiableModifyPermissions(object, user))
{
return true;
}
return false;
}
public boolean canRead(Appointment appointment,User user)
{
Reservation reservation = appointment.getReservation();
boolean canReadReservationsFromOthers = getQuery().canReadReservationsFromOthers( user);
boolean result = canRead(reservation, user, canReadReservationsFromOthers);
return result;
}
static public boolean canRead(Reservation reservation,User user, boolean canReadReservationsFromOthers)
{
if ( user == null)
{
return true;
}
if ( canModify(reservation, user))
{
return true;
}
if ( !canReadReservationsFromOthers)
{
return false;
}
if (checkClassifiablerReadPermissions(reservation, user))
{
return true;
}
return false;
}
static public boolean canRead(Allocatable allocatable, User user) {
if ( canModify(allocatable, user))
{
return true;
}
if (checkClassifiablerReadPermissions(allocatable, user))
{
return true;
}
return false;
}
/** We check if an attribute with the permission_modify exists and look if the permission is set either globally (if boolean type is used) or for a specific user group (if category type is used)*/
public static boolean checkClassifiableModifyPermissions(Object object,
User user) {
return checkClassifiablePermissions(object, user, ReservationImpl.PERMISSION_MODIFY, false);
}
public static boolean checkClassifiablerReadPermissions(
Object object, User user) {
return checkClassifiablePermissions(object, user, ReservationImpl.PERMISSION_READ, true);
}
static Category dummyCategory = new CategoryImpl(new Date(), new Date());
// The dummy category is used if no permission attribute is found. Use permissionNotFoundReturns to set whether this means permssion granted or not
private static boolean checkClassifiablePermissions(Object object, User user, String permissionKey, boolean permssionNotFoundReturnsYesCategory) {
Collection<Category> cat = getPermissionGroups(object, dummyCategory,permissionKey, permssionNotFoundReturnsYesCategory);
if ( cat == null)
{
return false;
}
if ( cat.size() == 1 && cat.iterator().next() == dummyCategory)
{
return true;
}
for (Category c: cat)
{
if (user.belongsTo( c) )
{
return true;
}
}
return false;
}
/** returns the group that is has the requested permission on the object
**/
public static Collection<Category> getPermissionGroups(Object object, Category yesCategory, String permissionKey, boolean permssionNotFoundReturnsYesCategory)
{
if (object instanceof Classifiable ) {
final Classifiable classifiable = (Classifiable) object;
Classification classification = classifiable.getClassification();
if ( classification != null)
{
final DynamicType type = classification.getType();
final Attribute attribute = type.getAttribute(permissionKey);
if ( attribute != null)
{
return getPermissionGroups(classification, yesCategory, attribute);
}
else
{
if ( permssionNotFoundReturnsYesCategory && yesCategory != null)
{
return Collections.singleton(yesCategory);
}
else
{
return null;
}
}
}
}
return null;
}
private static Collection<Category> getPermissionGroups(Classification classification,
Category yesCategory, final Attribute attribute) {
final AttributeType type2 = attribute.getType();
if (type2 == AttributeType.BOOLEAN)
{
final Object value = classification.getValue( attribute);
if (Boolean.TRUE.equals(value))
{
return Collections.singleton(yesCategory);
}
else
{
return null;
}
}
if ( type2 == AttributeType.CATEGORY)
{
Collection<?> values = classification.getValues( attribute);
@SuppressWarnings("unchecked")
Collection<Category> cat = (Collection<Category>) values;
if ( cat == null || cat.size() == 0)
{
Category rootCat = (Category)attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY);
if ( rootCat.getCategories().length == 0)
{
cat = Collections.singleton(rootCat);
}
}
return cat;
}
return null;
}
public CalendarOptions getCalendarOptions() {
User user;
try
{
user = getUser();
}
catch (RaplaException ex) {
// Use system settings if an error occurs
user = null;
}
return getCalendarOptions( user);
}
protected CalendarOptions getCalendarOptions(User user) {
RaplaConfiguration conf = null;
try {
if ( user != null)
{
conf = getQuery().getPreferences( user ).getEntry(CalendarOptionsImpl.CALENDAR_OPTIONS);
}
if ( conf == null)
{
conf = getQuery().getPreferences( null ).getEntry(CalendarOptionsImpl.CALENDAR_OPTIONS);
}
if ( conf != null)
{
return new CalendarOptionsImpl( conf );
}
} catch (RaplaException ex) {
}
return getService( CalendarOptions.class);
}
protected User getUser() throws RaplaException {
return getUserModule().getUser();
}
protected Logger getLogger() {
return logger;
}
/** lookup the service in the serviceManager under the specified key:
serviceManager.lookup(role).
@throws IllegalStateException if GUIComponent wasn't serviced. No service method called
@throws UnsupportedOperationException if service not available.
*/
protected <T> T getService(Class<T> role) {
try {
return context.lookup( role);
} catch (RaplaContextException e) {
throw serviceExcption(role, e);
}
}
protected UnsupportedOperationException serviceExcption(Object role, RaplaContextException e) {
return new UnsupportedOperationException("Service not supported in this context: " + role, e);
}
protected <T> T getService(TypedComponentRole<T> role) {
try {
return context.lookup(role);
} catch (RaplaContextException e) {
throw serviceExcption(role, e);
}
}
protected RaplaContext getContext() {
return context;
}
/** lookup RaplaLocale from the context */
protected RaplaLocale getRaplaLocale() {
if (serviceManager.raplaLocale == null)
serviceManager.raplaLocale = getService(RaplaLocale.class);
return serviceManager.raplaLocale;
}
protected Locale getLocale() {
return getRaplaLocale().getLocale();
}
protected I18nBundle childBundle;
/** lookup I18nBundle from the serviceManager */
protected I18nBundle getI18n() {
TypedComponentRole<I18nBundle> childBundleName = getChildBundleName();
if ( childBundleName != null) {
if ( childBundle == null) {
I18nBundle pluginI18n = getService(childBundleName );
childBundle = new CompoundI18n(pluginI18n,getI18nDefault());
}
return childBundle;
}
return getI18nDefault();
}
private I18nBundle getI18nDefault() {
if (serviceManager.i18n == null)
serviceManager.i18n = getService(RaplaComponent.RAPLA_RESOURCES);
return serviceManager.i18n;
}
/** lookup AppointmentFormater from the serviceManager */
protected AppointmentFormater getAppointmentFormater() {
if (serviceManager.appointmentFormater == null)
serviceManager.appointmentFormater = getService(AppointmentFormater.class);
return serviceManager.appointmentFormater;
}
/** lookup PeriodModel from the serviceManager */
protected PeriodModel getPeriodModel() {
try {
return getQuery().getPeriodModel();
} catch (RaplaException ex) {
throw new UnsupportedOperationException("Service not supported in this context: " );
}
}
/** lookup QueryModule from the serviceManager */
protected QueryModule getQuery() {
return getClientFacade();
}
final protected ClientFacade getClientFacade() {
if (serviceManager.facade == null)
serviceManager.facade = getService( ClientFacade.class );
return serviceManager.facade;
}
/** lookup ModificationModule from the serviceManager */
protected ModificationModule getModification() {
return getClientFacade();
}
/** lookup UpdateModule from the serviceManager */
protected UpdateModule getUpdateModule() {
return getClientFacade();
}
/** lookup UserModule from the serviceManager */
protected UserModule getUserModule() {
return getClientFacade();
}
/** returns a translation for the object name into the selected language. If
a translation into the selected language is not possible an english translation will be tried next.
If theres no translation for the default language, the first available translation will be used. */
public String getName(Object object) {
if (object == null)
return "";
if (object instanceof Named) {
String name = ((Named) object).getName(getI18n().getLocale());
return (name != null) ? name : "";
}
return object.toString();
}
/** calls getI18n().getString(key) */
final public String getString(String key) {
return getI18n().getString(key);
}
/** calls "<html>" + getI18n().getString(key) + "</html>"*/
final public String getStringAsHTML(String key) {
return "<html>" + getI18n().getString(key) + "</html>";
}
private static class ClientServiceManager {
I18nBundle i18n;
ClientFacade facade;
RaplaLocale raplaLocale;
AppointmentFormater appointmentFormater;
}
final public Preferences newEditablePreferences() throws RaplaException {
Preferences preferences = getQuery().getPreferences();
ModificationModule modification = getModification();
return modification.edit(preferences);
}
/** @deprecated demand webservice in constructor instead*/
@Deprecated
final public <T> T getWebservice(Class<T> a) throws RaplaException
{
org.rapla.storage.dbrm.RemoteServiceCaller remote = getService( org.rapla.storage.dbrm.RemoteServiceCaller.class);
return remote.getRemoteMethod(a);
}
@Deprecated
public Configuration getPluginConfig(String pluginClassName) throws RaplaException
{
Preferences systemPreferences = getQuery().getSystemPreferences();
return ((PreferencesImpl)systemPreferences).getOldPluginConfig(pluginClassName);
}
public static boolean isTemplate(RaplaObject<?> obj)
{
if ( obj instanceof Appointment)
{
obj = ((Appointment) obj).getReservation();
}
if ( obj instanceof Annotatable)
{
String template = ((Annotatable)obj).getAnnotation( RaplaObjectAnnotations.KEY_TEMPLATE);
return template != null;
}
return false;
}
protected List<Reservation> copy(Collection<Reservation> toCopy, Date beginn) throws RaplaException
{
List<Reservation> sortedReservations = new ArrayList<Reservation>( toCopy);
Collections.sort( sortedReservations, new ReservationStartComparator(getLocale()));
List<Reservation> copies = new ArrayList<Reservation>();
Date firstStart = null;
for (Reservation reservation: sortedReservations) {
if ( firstStart == null )
{
firstStart = ReservationStartComparator.getStart( reservation);
}
Reservation copy = copy(reservation, beginn, firstStart);
copies.add( copy);
}
return copies;
}
public Reservation copyAppointment(Reservation reservation, Date beginn) throws RaplaException
{
Date firstStart = ReservationStartComparator.getStart( reservation);
Reservation copy = copy(reservation, beginn, firstStart);
return copy;
}
private Reservation copy(Reservation reservation, Date destStart,Date firstStart) throws RaplaException {
Reservation r = getModification().clone( reservation);
Appointment[] appointments = r.getAppointments();
for ( Appointment app :appointments) {
Repeating repeating = app.getRepeating();
Date oldStart = app.getStart();
// we need to calculate an offset so that the reservations will place themself relativ to the first reservation in the list
long offset = DateTools.countDays( firstStart, oldStart) * DateTools.MILLISECONDS_PER_DAY;
Date newStart ;
Date destWithOffset = new Date(destStart.getTime() + offset );
newStart = getRaplaLocale().toDate( destWithOffset , oldStart );
app.move( newStart) ;
if (repeating != null)
{
Date[] exceptions = repeating.getExceptions();
repeating.clearExceptions();
for (Date exc: exceptions)
{
long days = DateTools.countDays(oldStart, exc);
Date newDate = DateTools.addDays(newStart, days);
repeating.addException( newDate);
}
if ( !repeating.isFixedNumber())
{
Date oldEnd = repeating.getEnd();
if ( oldEnd != null)
{
// If we don't have and endig destination, just make the repeating to the original length
long days = DateTools.countDays(oldStart, oldEnd);
Date end = DateTools.addDays(newStart, days);
repeating.setEnd( end);
}
}
}
}
return r;
}
public static void unlock(Lock lock)
{
if ( lock != null)
{
lock.unlock();
}
}
public static Lock lock(Lock lock, int seconds) throws RaplaException {
try
{
if ( lock.tryLock())
{
return lock;
}
if (lock.tryLock(seconds, TimeUnit.SECONDS))
{
return lock;
}
else
{
throw new RaplaSynchronizationException("Someone is currently writing. Please try again! Can't acquire lock " + lock );
}
}
catch (InterruptedException ex)
{
throw new RaplaSynchronizationException( ex);
}
}
}
| Java |
package org.rapla.facade;
import java.util.Collection;
import java.util.Date;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.framework.RaplaException;
public interface CalendarSelectionModel extends CalendarModel{
String getTitle();
void setTitle(String title);
void setViewId(String viewId);
String getViewId();
void setSelectedObjects(Collection<? extends Object> selectedObjects);
void setOption( String name, String string );
void selectUser( User user );
/** If show only own reservations is selected. Thats if the current user is selected with select User*/
boolean isOnlyCurrentUserSelected();
void setReservationFilter(ClassificationFilter[] array);
void setAllocatableFilter(ClassificationFilter[] filters);
public void resetExports();
public void save(final String filename) throws RaplaException;
public void load(final String filename) throws RaplaException, EntityNotFoundException, CalendarNotFoundExeption;
CalendarSelectionModel clone();
void setMarkedIntervals(Collection<TimeInterval> timeIntervals);
/** calls setMarkedIntervals with a single interval from start to end*/
void markInterval(Date start, Date end);
void setMarkedAllocatables(Collection<Allocatable> allocatable);
/** CalendarModels do not update automatically but need to be notified on changes from the outside*/
void dataChanged(ModificationEvent evt) throws RaplaException;
} | Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.Date;
import java.util.List;
import org.rapla.entities.domain.Period;
/** ListModel that contains all periods. Updates the list automatically if a period is added, changed or deleted.
* */
public interface PeriodModel
{
/** returns the first matching period or null if no period matches.*/
public Period getPeriodFor(Date date);
public Period getNearestPeriodForDate(Date date);
public Period getNearestPeriodForStartDate(Date date);
public Period getNearestPeriodForStartDate(Date date, Date endDate);
public Period getNearestPeriodForEndDate(Date date);
/** return all matching periods.*/
public List<Period> getPeriodsFor(Date date);
public int getSize();
public Period[] getAllPeriods();
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.Set;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaType;
/** Encapsulate the changes that are made in the backend-store.*/
public interface ModificationEvent
{
/** returns if the objects has changed.*/
boolean hasChanged(Entity object);
/** returns if the objects was removed.*/
boolean isRemoved(Entity object);
/** returns if the objects has changed or was removed.*/
boolean isModified(Entity object);
/** returns if any object of the specified type has changed or was removed.*/
boolean isModified(RaplaType raplaType);
/** returns all removed objects .*/
Set<Entity> getRemoved();
/** returns all changed object .*/
Set<Entity> getChanged();
Set<Entity> getAddObjects();
TimeInterval getInvalidateInterval();
boolean isModified();
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.facade;
import java.util.EventListener;
import org.rapla.framework.RaplaException;
/** Classes implementing this interface will be notified when changes to
* reservations or resources occurred. The listener can be registered by calling
* <code>addModificationListener</code> of the <code>UpdateModule</code> <br>
* Don't forget to remove the listener by calling <code>removeModificationLister</code>
* when no longer needed.
* @author Christopher Kohlhaas
* @see UpdateModule
* @see ModificationEvent
*/
public interface ModificationListener extends EventListener {
/** this notifies all listeners that data in the rapla-backend has changed.
* The {@link ModificationEvent} describes these changes.
*/
void dataChanged(ModificationEvent evt) throws RaplaException;
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.rapla.components.util.CommandScheduler;
import org.rapla.components.util.IOUtil;
import org.rapla.components.util.xml.RaplaNonValidatedInput;
import org.rapla.components.xmlbundle.CompoundI18n;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.LocaleSelector;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.entities.domain.AppointmentFormater;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.facade.CalendarOptions;
import org.rapla.facade.RaplaComponent;
import org.rapla.facade.internal.CalendarOptionsImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.Provider;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaDefaultContext;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.ServiceListCreator;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.TypedComponentRole;
import org.rapla.framework.internal.ComponentInfo;
import org.rapla.framework.internal.ConfigTools;
import org.rapla.framework.internal.ContainerImpl;
import org.rapla.framework.internal.RaplaJDKLoggingAdapter;
import org.rapla.framework.internal.RaplaLocaleImpl;
import org.rapla.framework.internal.RaplaMetaConfigInfo;
import org.rapla.framework.logger.Logger;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.rest.gwtjsonrpc.common.ResultImpl;
import org.rapla.storage.dbrm.RaplaConnectException;
import org.rapla.storage.dbrm.RaplaHTTPConnector;
import org.rapla.storage.dbrm.RemoteConnectionInfo;
import org.rapla.storage.dbrm.RemoteMethodStub;
import org.rapla.storage.dbrm.RemoteServiceCaller;
import org.rapla.storage.dbrm.StatusUpdater;
import org.rapla.storage.dbrm.StatusUpdater.Status;
/**
The Rapla Main Container class for the basic container for Rapla specific services and the rapla plugin architecture.
The rapla container has only one instance at runtime. Configuration of the RaplaMainContainer is done in the rapla*.xconf
files. Typical configurations of the MainContainer are
<ol>
<li>Client: A ClientContainerService, one facade and a remote storage ( automaticaly pointing to the download server in webstart mode)</li>
<li>Server: A ServerContainerService (providing a facade) a messaging server for handling the connections with the clients, a storage (file or db) and an extra service for importing and exporting in the db</li>
<li>Standalone: A ClientContainerService (with preconfigured auto admin login) and a ServerContainerService that is directly connected to the client without http communication.</li>
<li>Embedded: Configuration example follows.</li>
</ol>
<p>
Configuration of the main container is usually done via the raplaserver.xconf
</p>
<p>
The Main Container provides the following Services to all RaplaComponents
<ul>
<li>I18nBundle</li>
<li>AppointmentFormater</li>
<li>RaplaLocale</li>
<li>LocaleSelector</li>
<li>RaplaMainContainer.PLUGIN_LIST (A list of all available plugins)</li>
</ul>
</p>
@see I18nBundle
@see RaplaLocale
@see AppointmentFormater
@see LocaleSelector
*/
final public class RaplaMainContainer extends ContainerImpl
{
public static final TypedComponentRole<Configuration> RAPLA_MAIN_CONFIGURATION = new TypedComponentRole<Configuration>("org.rapla.MainConfiguration");
public static final TypedComponentRole<String> DOWNLOAD_SERVER = new TypedComponentRole<String>("download-server");
public static final TypedComponentRole<URL> DOWNLOAD_URL = new TypedComponentRole<URL>("download-url");
public static final TypedComponentRole<String> ENV_RAPLADATASOURCE = new TypedComponentRole<String>("env.rapladatasource");
public static final TypedComponentRole<String> ENV_RAPLAFILE = new TypedComponentRole<String>("env.raplafile");
public static final TypedComponentRole<Object> ENV_RAPLADB= new TypedComponentRole<Object>("env.rapladb");
public static final TypedComponentRole<Object> ENV_RAPLAMAIL= new TypedComponentRole<Object>("env.raplamail");
public static final TypedComponentRole<Boolean> ENV_DEVELOPMENT = new TypedComponentRole<Boolean>("env.development");
public static final TypedComponentRole<Object> TIMESTAMP = new TypedComponentRole<Object>("timestamp");
public static final TypedComponentRole<String> CONTEXT_ROOT = new TypedComponentRole<String>("context-root");
public final static TypedComponentRole<Set<String>> PLUGIN_LIST = new TypedComponentRole<Set<String>>("plugin-list");
public final static TypedComponentRole<String> TITLE = new TypedComponentRole<String>("org.rapla.title");
public final static TypedComponentRole<String> TIMEZONE = new TypedComponentRole<String>("org.rapla.timezone");
Logger callLogger;
public RaplaMainContainer() throws Exception {
this(new RaplaStartupEnvironment());
}
public RaplaMainContainer(StartupEnvironment env) throws Exception {
this( env, new RaplaDefaultContext() );
}
public RaplaMainContainer( StartupEnvironment env, RaplaContext context) throws Exception
{
this( env,context,createRaplaLogger());
}
RemoteConnectionInfo globalConnectInfo;
CommandScheduler commandQueue;
public RaplaMainContainer( StartupEnvironment env, RaplaContext context,Logger logger) throws Exception{
super( context, env.getStartupConfiguration(),logger );
addContainerProvidedComponentInstance( StartupEnvironment.class, env);
addContainerProvidedComponentInstance( DOWNLOAD_SERVER, env.getDownloadURL().getHost());
addContainerProvidedComponentInstance( DOWNLOAD_URL, env.getDownloadURL());
commandQueue = createCommandQueue();
addContainerProvidedComponentInstance( CommandScheduler.class, commandQueue);
addContainerProvidedComponentInstance( RemoteServiceCaller.class, new RemoteServiceCaller() {
@Override
public <T> T getRemoteMethod(Class<T> a) throws RaplaContextException {
return RaplaMainContainer.this.getRemoteMethod(getContext(), a);
}
} );
if (env.getContextRootURL() != null)
{
File file = IOUtil.getFileFrom( env.getContextRootURL());
addContainerProvidedComponentInstance( CONTEXT_ROOT, file.getPath());
}
addContainerProvidedComponentInstance( TIMESTAMP, new Object() {
public String toString() {
DateFormat formatter = new SimpleDateFormat("yyyyMMdd-HHmmss");
String formatNow = formatter.format(new Date());
return formatNow;
}
});
initialize();
}
private static Logger createRaplaLogger()
{
Logger logger;
try {
RaplaMainContainer.class.getClassLoader().loadClass("org.slf4j.Logger");
@SuppressWarnings("unchecked")
Provider<Logger> logManager = (Provider<Logger>) RaplaMainContainer.class.getClassLoader().loadClass("org.rapla.framework.internal.Slf4jAdapter").newInstance();
logger = logManager.get();
logger.info("Logging via SLF4J API.");
} catch (Throwable e1) {
Provider<Logger> logManager = new RaplaJDKLoggingAdapter( );
logger = logManager.get();
logger.info("Logging via java.util.logging API. " + e1.toString());
}
return logger;
}
protected Map<String,ComponentInfo> getComponentInfos() {
return new RaplaMetaConfigInfo();
}
private void initialize() throws Exception {
Logger logger = getLogger();
int startupMode = getStartupEnvironment().getStartupMode();
logger.debug("----------- Rapla startup mode = " + startupMode);
RaplaLocaleImpl raplaLocale = new RaplaLocaleImpl(m_config.getChild("locale"), logger);
Configuration localeConfig = m_config.getChild("locale");
CalendarOptions calendarOptions = new CalendarOptionsImpl(localeConfig);
addContainerProvidedComponentInstance( CalendarOptions.class, calendarOptions );
addContainerProvidedComponentInstance( RAPLA_MAIN_CONFIGURATION, m_config );
addContainerProvidedComponent( RaplaNonValidatedInput.class, ConfigTools.RaplaReaderImpl.class);
// Startup mode= EMBEDDED = 0, CONSOLE = 1, WEBSTART = 2, APPLET = 3, SERVLET = 4
addContainerProvidedComponentInstance( RaplaLocale.class,raplaLocale);
addContainerProvidedComponentInstance( LocaleSelector.class,raplaLocale.getLocaleSelector());
m_config.getChildren("rapla-client");
String defaultBundleName = m_config.getChild("default-bundle").getValue( null);
// Override the intern Resource Bundle with user provided
Configuration parentConfig = I18nBundleImpl.createConfig( RaplaComponent.RAPLA_RESOURCES.getId() );
if ( defaultBundleName!=null) {
I18nBundleImpl i18n = new I18nBundleImpl( getContext(), I18nBundleImpl.createConfig( defaultBundleName ), logger);
String parentId = i18n.getParentId();
if ( parentId != null && parentId.equals(RaplaComponent.RAPLA_RESOURCES.getId()))
{
I18nBundleImpl parent = new I18nBundleImpl( getContext(), parentConfig, logger);
I18nBundle compound = new CompoundI18n( i18n, parent);
addContainerProvidedComponentInstance(RaplaComponent.RAPLA_RESOURCES, compound);
}
else
{
addContainerProvidedComponent(RaplaComponent.RAPLA_RESOURCES,I18nBundleImpl.class, parentConfig);
}
}
else
{
addContainerProvidedComponent(RaplaComponent.RAPLA_RESOURCES,I18nBundleImpl.class, parentConfig);
}
addContainerProvidedComponentInstance( AppointmentFormater.class, new AppointmentFormaterImpl( getContext()));
// Discover and register the plugins for Rapla
Set<String> pluginNames = new LinkedHashSet<String>();
boolean isDevelopment = getContext().has(RaplaMainContainer.ENV_DEVELOPMENT) && getContext().lookup( RaplaMainContainer.ENV_DEVELOPMENT);
Enumeration<URL> pluginEnum = ConfigTools.class.getClassLoader().getResources("META-INF/rapla-plugin.list");
if (!pluginEnum.hasMoreElements() || isDevelopment)
{
Collection<String> result = ServiceListCreator.findPluginClasses(logger);
pluginNames.addAll(result);
}
while ( pluginEnum.hasMoreElements() ) {
BufferedReader reader = new BufferedReader(new InputStreamReader((pluginEnum.nextElement()).openStream()));
while ( true ) {
String plugin = reader.readLine();
if ( plugin == null)
break;
pluginNames.add(plugin);
}
}
addContainerProvidedComponentInstance( PLUGIN_LIST, pluginNames);
logger.info("Config=" + getStartupEnvironment().getConfigURL());
I18nBundle i18n = getContext().lookup(RaplaComponent.RAPLA_RESOURCES);
String version = i18n.getString( "rapla.version" );
logger.info("Rapla.Version=" + version);
version = i18n.getString( "rapla.build" );
logger.info("Rapla.Build=" + version);
AttributeImpl.TRUE_TRANSLATION.setName(i18n.getLang(), i18n.getString("yes"));
AttributeImpl.FALSE_TRANSLATION.setName(i18n.getLang(), i18n.getString("no"));
try {
version = System.getProperty("java.version");
logger.info("Java.Version=" + version);
} catch (SecurityException ex) {
version = "-";
logger.warn("Permission to system property java.version is denied!");
}
callLogger =logger.getChildLogger("call");
}
public void dispose() {
getLogger().info("Shutting down rapla-container");
if ( commandQueue != null)
{
((DefaultScheduler)commandQueue).cancel();
}
super.dispose();
}
public <T> T getRemoteMethod(final RaplaContext context,final Class<T> a) throws RaplaContextException
{
if (context.has( RemoteMethodStub.class))
{
RemoteMethodStub server = context.lookup(RemoteMethodStub.class);
return server.getWebserviceLocalStub(a);
}
InvocationHandler proxy = new InvocationHandler()
{
RemoteConnectionInfo localConnectInfo;
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
if ( method.getName().equals("setConnectInfo") && method.getParameterTypes()[0].equals(RemoteConnectionInfo.class))
{
localConnectInfo = (RemoteConnectionInfo) args[0];
if ( globalConnectInfo == null)
{
globalConnectInfo =localConnectInfo;
}
return null;
}
RemoteConnectionInfo remoteConnectionInfo = localConnectInfo != null ? localConnectInfo : globalConnectInfo;
if ( remoteConnectionInfo == null)
{
throw new IllegalStateException("you need to call setConnectInfo first");
}
Class<?> returnType = method.getReturnType();
String methodName = method.getName();
final URL server;
try
{
server = new URL( remoteConnectionInfo.getServerURL());
}
catch (MalformedURLException e)
{
throw new RaplaContextException(e.getMessage());
}
StatusUpdater statusUpdater = remoteConnectionInfo.getStatusUpdater();
if ( statusUpdater != null)
{
statusUpdater.setStatus( Status.BUSY );
}
FutureResult result;
try
{
result = call(context,server, a, methodName, args, remoteConnectionInfo);
if (callLogger.isDebugEnabled())
{
callLogger.debug("Calling " + server + " " + a.getName() + "."+methodName);
}
}
finally
{
if ( statusUpdater != null)
{
statusUpdater.setStatus( Status.READY );
}
}
if ( !FutureResult.class.isAssignableFrom(returnType))
{
return result.get();
}
return result;
}
};
ClassLoader classLoader = a.getClassLoader();
@SuppressWarnings("unchecked")
Class<T>[] interfaces = new Class[] {a};
@SuppressWarnings("unchecked")
T proxyInstance = (T)Proxy.newProxyInstance(classLoader, interfaces, proxy);
return proxyInstance;
}
static private FutureResult call( RaplaContext context,URL server,Class<?> service, String methodName,Object[] args,RemoteConnectionInfo connectionInfo) {
RaplaHTTPConnector connector = new RaplaHTTPConnector();
try {
FutureResult result =connector.call(service, methodName, args, connectionInfo);
return result;
} catch (RaplaConnectException ex) {
return new ResultImpl(getConnectError(context,ex, server.toString()));
} catch (Exception ex) {
return new ResultImpl(ex);
}
}
static private RaplaConnectException getConnectError(RaplaContext context,RaplaConnectException ex2, String server) {
try
{
String message = context.lookup(RaplaComponent.RAPLA_RESOURCES).format("error.connect", server) + " " + ex2.getMessage();
return new RaplaConnectException(message);
}
catch (Exception ex)
{
return new RaplaConnectException("Connection error with server " + server + ": " + ex2.getMessage());
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.framework;
/** the base-class for all Rapla specific Exceptions */
public class RaplaException extends Exception {
private static final long serialVersionUID = 1L;
public RaplaException(String text) {
super(text);
}
public RaplaException(Throwable throwable) {
super(throwable.getMessage(),throwable);
}
public RaplaException(String text,Throwable ex) {
super(text,ex);
}
}
| Java |
package org.rapla.framework;
public interface Configuration {
String getName();
Configuration getChild(String name);
Configuration[] getChildren(String name);
Configuration[] getChildren();
String getValue() throws ConfigurationException;
String getValue(String defaultValue);
boolean getValueAsBoolean(boolean defaultValue);
long getValueAsLong(int defaultValue);
int getValueAsInteger(int defaultValue);
String getAttribute(String name) throws ConfigurationException;
String getAttribute(String name, String defaultValue);
boolean getAttributeAsBoolean(String string, boolean defaultValue);
String[] getAttributeNames();
public Configuration find( String localName);
public Configuration find( String attributeName, String attributeValue);
}
| Java |
package org.rapla.framework;
public class RaplaContextException
extends RaplaException
{
private static final long serialVersionUID = 1L;
public RaplaContextException( final String key ) {
super( "Unable to provide implementation for " + key + " " );
}
public RaplaContextException( final Class<?> clazz, final String message ) {
super("Unable to provide implementation for " + clazz.getName() + " " + message);
}
public RaplaContextException( final String message, final Throwable throwable )
{
super( message, throwable );
}
}
| Java |
package org.rapla.framework;
public interface Provider<T> {
T get();
}
| Java |
package org.rapla.framework.logger;
public class NullLogger extends AbstractLogger {
public NullLogger() {
super(LEVEL_FATAL);
}
public Logger getChildLogger(String childLoggerName) {
return this;
}
protected void write(int logLevel, String message, Throwable cause) {
}
}
| Java |
package org.rapla.framework.logger;
public abstract class AbstractLogger implements Logger{
protected int logLevel;
public static final int LEVEL_FATAL = 4;
public static final int LEVEL_ERROR = 3;
public static final int LEVEL_WARN = 2;
public static final int LEVEL_INFO = 1;
public static final int LEVEL_DEBUG = 0;
public AbstractLogger(int logLevel) {
this.logLevel = logLevel;
}
public void error(String message, Throwable cause) {
log( LEVEL_ERROR,message, cause);
}
private void log(int logLevel, String message) {
log( logLevel, message, null);
}
private void log(int logLevel, String message, Throwable cause)
{
if ( logLevel < this.logLevel)
{
return;
}
write( logLevel, message, cause);
}
protected abstract void write(int logLevel, String message, Throwable cause);
public void debug(String message) {
log( LEVEL_DEBUG,message);
}
public void info(String message) {
log( LEVEL_INFO,message);
}
public void warn(String message) {
log( LEVEL_WARN,message);
}
public void warn(String message, Throwable cause) {
log( LEVEL_WARN,message, cause);
}
public void error(String message) {
log( LEVEL_ERROR,message);
}
public void fatalError(String message) {
log( LEVEL_FATAL,message);
}
public void fatalError(String message, Throwable cause) {
log( LEVEL_FATAL,message, cause);
}
public boolean isDebugEnabled() {
return logLevel<= LEVEL_DEBUG;
}
}
| Java |
package org.rapla.framework.logger;
public interface Logger {
boolean isDebugEnabled();
void debug(String message);
void info(String message);
void warn(String message);
void warn(String message, Throwable cause);
void error(String message);
void error(String message, Throwable cause);
Logger getChildLogger(String childLoggerName);
}
| Java |
package org.rapla.framework.logger;
public class ConsoleLogger extends AbstractLogger {
String prefix;
public ConsoleLogger(int logLevel)
{
super(logLevel);
}
public ConsoleLogger(String prefix,int logLevel)
{
super(logLevel);
this.prefix = prefix;
}
public ConsoleLogger()
{
this(LEVEL_INFO);
}
public Logger getChildLogger(String prefix)
{
String newPrefix = prefix;
if ( this.prefix != null)
{
newPrefix = this.prefix + "." + prefix;
}
return new ConsoleLogger( newPrefix, logLevel);
}
String getLogLevelString(int logLevel)
{
switch (logLevel)
{
case LEVEL_DEBUG: return "DEBUG";
case LEVEL_INFO: return "INFO";
case LEVEL_WARN: return "WARN";
case LEVEL_ERROR: return "ERROR";
case LEVEL_FATAL: return "FATAL";
}
return "";
}
protected void write(int logLevel, String message, Throwable cause)
{
String logLevelString = getLogLevelString( logLevel );
StringBuffer buf = new StringBuffer();
buf.append( logLevelString );
buf.append( " " );
if ( prefix != null)
{
buf.append( prefix);
buf.append( ": " );
}
if ( message != null)
{
buf.append( message);
if ( cause != null)
{
buf.append( ": " );
}
}
while( cause!= null)
{
StackTraceElement[] stackTrace = cause.getStackTrace();
buf.append( cause.getMessage());
buf.append( "\n" );
for ( StackTraceElement element:stackTrace)
{
buf.append(" ");
buf.append( element.toString());
buf.append( "\n");
}
cause = cause.getCause();
if ( cause != null)
{
buf.append(" caused by ");
buf.append( cause.getMessage());
buf.append( " " );
}
}
System.out.println(buf.toString());
}
}
| Java |
package org.rapla.framework;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.rapla.components.util.SerializableDateTimeFormat;
/** This class contains all locale specific information for Rapla. Like
<ul>
<li>Selected language.</li>
<li>Selected country.</li>
<li>Available languages (if the user has the possibility to choose a language)</li>
<li>TimeZone for appointments (This is always GMT+0)</li>
</ul>
<p>
Also it provides basic formating information for the dates.
</p>
<p>
Configuration is done in the rapla.xconf:
<pre>
<locale>
<languages default="de">
<language>de</language>
<language>en</language>
</languages>
<country>US</country>
</locale>
</pre>
If languages default is not set, the system default wil be used.<br>
If country code is not set, the system default will be used.<br>
</p>
<p>
Rapla hasn't a support for different Timezones yet.
if you look into RaplaLocale you find
3 timzones in Rapla:
</p>
<ul>
<li>{@link RaplaLocale#getTimeZone}</li>
<li>{@link RaplaLocale#getSystemTimeZone}</li>
<li>{@link RaplaLocale#getImportExportTimeZone}</li>
</ul>
*/
public interface RaplaLocale
{
TypedComponentRole<String> LANGUAGE_ENTRY = new TypedComponentRole<String>("org.rapla.language");
String[] getAvailableLanguages();
/** creates a calendar initialized with the Rapla timezone ( that is always GMT+0 for Rapla ) and the selected locale*/
Calendar createCalendar();
String formatTime( Date date );
Date fromUTCTimestamp(Date timestamp);
/** sets time to 0:00:00 or 24:00:00 */
Date toDate( Date date, boolean fillDate );
/** sets time to 0:00:00
* Warning month is zero based so January is 0
* @deprecated use toRaplaDate*/
Date toDate( int year, int month, int date );
/**
* month is 1-12 January is 1
*/
Date toRaplaDate( int year, int month, int date );
/** sets date to 0:00:00 */
Date toTime( int hour, int minute, int second );
/** Uses the first date parameter for year, month, date information and
the second for hour, minutes, second, millisecond information.*/
Date toDate( Date date, Date time );
/** format long with the local NumberFormat */
String formatNumber( long number );
/** format without year */
String formatDateShort( Date date );
/** format with locale DateFormat.SHORT */
String formatDate( Date date );
/** format with locale DateFormat.MEDIUM */
String formatDateLong( Date date );
String formatTimestamp(Date timestamp);
@Deprecated
String formatTimestamp(Date timestamp, TimeZone timezone);
/** Abbreviation of locale weekday name of date. */
String getWeekday( Date date );
/** Monthname of date. */
String getMonth( Date date );
String getCharsetNonUtf();
/**
This method always returns GMT+0. This is used for all internal calls. All dates and times are stored internaly with this Timezone.
Rapla can't work with timezones but to use the Date api it needs a timezone, so GMT+0 is used, because it doesn't have DaylightSavingTimes which would confuse the conflict detection. This timezone (GMT+0) is only used internaly and never shown in Rapla. Rapla only displays the time e.g. 10:00am without the timezone.
*/
TimeZone getTimeZone();
/**
returns the timezone of the system where Rapla is running (java default)
this is used on the server for storing the dates in mysql. Prior to 1.7 Rapla always switched the system time to gmt for the mysql api. But now the dates are converted from GMT+0 to system time before storing.
Converted meens: 10:00am GMT+0 Raplatime is converted to 10:00am Europe/Berlin, if thats the system timezone. When loading 10:00am Europe/Berlin is converted back to 10:00am GMT+0.
This timezone is also used for the timestamps, so created-at and last-changed dates are always stored in system time.
Also the logging api uses this timezone and now logs are in system time.
@see RaplaLocale#toRaplaTime(TimeZone, long)
@deprecated only used internally by the storage api
*/
@Deprecated
TimeZone getSystemTimeZone();
/**
returns the timezone configured via main options, this is per default the system timezon. This timezone is used for ical/exchange import/export
If Rapla will support timezones in the future, than this will be the default timezone for all times. Now its only used on import and export. It works as with system time above. 10:00am GMT+0 is converted to 10:00am of the configured timezone on export and on import all times are converted to GMT+0.
@see RaplaLocale#toRaplaTime(TimeZone, long)
@deprecated moved to ImportExportLocale
*/
@Deprecated
TimeZone getImportExportTimeZone();
/**
@deprecated moved to TimeZoneConverter
*/
@Deprecated
long fromRaplaTime(TimeZone timeZone,long raplaTime);
/**
@deprecated moved to TimeZoneConverter
*/
@Deprecated
long toRaplaTime(TimeZone timeZone,long time);
/**
@deprecated moved to TimeZoneConverter
*/
@Deprecated
Date fromRaplaTime(TimeZone timeZone,Date raplaTime);
/**
* converts a common Date object into a Date object that
* assumes that the user (being in the given timezone) is in the
* UTC-timezone by adding the offset between UTC and the given timezone.
*
* <pre>
* Example: If you pass the Date "2013 Jan 15 11:00:00 UTC"
* and the TimeZone "GMT+1", this method will return a Date
* "2013 Jan 15 12:00:00 UTC" which is effectivly 11:00:00 GMT+1
* </pre>
*
* @param timeZone
* the orgin timezone
* @param time
* the Date object in the passed timezone
* @see RaplaLocale#fromRaplaTime
@deprecated moved to TimeZoneConverter
*/
Date toRaplaTime(TimeZone timeZone,Date time);
Locale getLocale();
SerializableDateTimeFormat getSerializableFormat();
} | Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.framework;
public interface PluginDescriptor<T extends Container>{
public void provideServices(T container, Configuration configuration) throws RaplaContextException;
}
| Java |
package org.rapla.framework;
public class SimpleProvider<T> implements Provider<T>
{
T value;
public T get() {
return value;
}
public void setValue(T value)
{
this.value = value;
}
} | Java |
package org.rapla.framework.internal;
import org.rapla.framework.ConfigurationException;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.TypedComponentRole;
public class ContextTools {
/** resolves a context value in the passed string.
If the string begins with <code>${</code> the method will lookup the String-Object in the context and returns it.
If it doesn't, the method returns the unmodified string.
Example:
<code>resolveContext("${download-server}")</code> returns the same as
context.get("download-server").toString();
@throws ConfigurationException when no contex-object was found for the given variable.
*/
public static String resolveContext( String s, RaplaContext context ) throws RaplaContextException
{
return ContextTools.resolveContextObject(s, context).toString();
}
public static Object resolveContextObject( String s, RaplaContext context ) throws RaplaContextException
{
StringBuffer value = new StringBuffer();
s = s.trim();
int startToken = s.indexOf( "${" );
if ( startToken < 0 )
return s;
int endToken = s.indexOf( "}", startToken );
String token = s.substring( startToken + 2, endToken );
String preToken = s.substring( 0, startToken );
String unresolvedRest = s.substring( endToken + 1 );
TypedComponentRole<Object> untypedIdentifier = new TypedComponentRole<Object>(token);
Object lookup = context.lookup( untypedIdentifier );
if ( preToken.length() == 0 && unresolvedRest.length() == 0 )
{
return lookup;
}
String contextObject = lookup.toString();
value.append( preToken );
String stringRep = contextObject.toString();
value.append( stringRep );
Object resolvedRest = resolveContext(unresolvedRest, context );
value.append( resolvedRest.toString());
return value.toString();
}
}
| Java |
package org.rapla.framework.internal;
import java.util.Date;
import java.util.TimeZone;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.framework.RaplaLocale;
public abstract class AbstractRaplaLocale implements RaplaLocale {
public String formatTimestamp( Date date )
{
Date raplaDate = fromUTCTimestamp(date);
StringBuffer buf = new StringBuffer();
{
String formatDate= formatDate( raplaDate );
buf.append( formatDate);
}
buf.append(" ");
{
String formatTime = formatTime( raplaDate );
buf.append( formatTime);
}
return buf.toString();
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#toDate(java.util.Date, boolean)
*/
public Date toDate( Date date, boolean fillDate ) {
Date result = DateTools.cutDate(DateTools.addDay(date));
return result;
//
// Calendar cal1 = createCalendar();
// cal1.setTime( date );
// if ( fillDate ) {
// cal1.add( Calendar.DATE, 1);
// }
// cal1.set( Calendar.HOUR_OF_DAY, 0 );
// cal1.set( Calendar.MINUTE, 0 );
// cal1.set( Calendar.SECOND, 0 );
// cal1.set( Calendar.MILLISECOND, 0 );
// return cal1.getTime();
}
@Deprecated
public Date toDate( int year,int month, int day ) {
Date result = toRaplaDate(year, month+1, day);
return result;
}
public Date toRaplaDate( int year,int month, int day ) {
Date result = new Date(DateTools.toDate(year, month, day));
return result;
}
public Date toTime( int hour,int minute, int second ) {
Date result = new Date(DateTools.toTime(hour, minute, second));
return result;
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#toDate(java.util.Date, java.util.Date)
*/
public Date toDate( Date date, Date time ) {
long millisTime = time.getTime() - DateTools.cutDate( time.getTime());
Date result = new Date( DateTools.cutDate(date.getTime()) + millisTime);
return result;
// Calendar cal1 = createCalendar();
// Calendar cal2 = createCalendar();
// cal1.setTime( date );
// cal2.setTime( time );
// cal1.set( Calendar.HOUR_OF_DAY, cal2.get(Calendar.HOUR_OF_DAY) );
// cal1.set( Calendar.MINUTE, cal2.get(Calendar.MINUTE) );
// cal1.set( Calendar.SECOND, cal2.get(Calendar.SECOND) );
// cal1.set( Calendar.MILLISECOND, cal2.get(Calendar.MILLISECOND) );
// return cal1.getTime();
}
public long fromRaplaTime(TimeZone timeZone,long raplaTime)
{
long offset = getOffset(timeZone, raplaTime);
return raplaTime - offset;
}
public long toRaplaTime(TimeZone timeZone,long time)
{
long offset = getOffset(timeZone,time);
return time + offset;
}
public Date fromRaplaTime(TimeZone timeZone,Date raplaTime)
{
return new Date( fromRaplaTime(timeZone, raplaTime.getTime()));
}
public Date toRaplaTime(TimeZone timeZone,Date time)
{
return new Date( toRaplaTime(timeZone, time.getTime()));
}
private long getOffset(TimeZone timeZone,long time) {
long offsetSystem;
long offsetRapla;
{
// Calendar cal =Calendar.getInstance( timeZone);
// cal.setTimeInMillis( time );
// int zoneOffset = cal.get(Calendar.ZONE_OFFSET);
// int dstOffset = cal.get(Calendar.DST_OFFSET);
offsetSystem = timeZone.getOffset(time);
}
{
TimeZone utc = getTimeZone();
// Calendar cal =Calendar.getInstance( utc);
// cal.setTimeInMillis( time );
// offsetRapla = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET);
offsetRapla = utc.getOffset(time);
}
return offsetSystem - offsetRapla;
}
public SerializableDateTimeFormat getSerializableFormat()
{
return new SerializableDateTimeFormat();
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.framework.internal;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import org.rapla.components.util.Assert;
import org.rapla.components.util.JNLPUtil;
import org.rapla.components.util.xml.RaplaContentHandler;
import org.rapla.components.util.xml.RaplaErrorHandler;
import org.rapla.components.util.xml.RaplaNonValidatedInput;
import org.rapla.components.util.xml.RaplaSAXHandler;
import org.rapla.components.util.xml.XMLReaderAdapter;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaException;
import org.rapla.framework.logger.Logger;
import org.rapla.framework.logger.NullLogger;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/** Tools for configuring the rapla-system. */
public abstract class ConfigTools
{
/** parse startup parameters. The parse format:
<pre>
[-?|-c PATH_TO_CONFIG_FILE] [ACTION]
</pre>
Possible map entries:
<ul>
<li>config: the config-file</li>
<li>action: the start action</li>
</ul>
@return a map with the parameter-entries or null if format is invalid or -? is used
*/
public static Map<String,String> parseParams( String[] args )
{
boolean bInvalid = false;
Map<String,String> map = new HashMap<String,String>();
String config = null;
String action = null;
// Investigate the passed arguments
for ( int i = 0; i < args.length; i++ )
{
if ( args[i].toLowerCase().equals( "-c" ) )
{
if ( i + 1 == args.length )
{
bInvalid = true;
break;
}
config = args[++i];
continue;
}
if ( args[i].toLowerCase().equals( "-?" ) )
{
bInvalid = true;
break;
}
if ( args[i].toLowerCase().substring( 0, 1 ).equals( "-" ) )
{
bInvalid = true;
break;
}
action = args[i].toLowerCase();
}
if ( bInvalid )
{
return null;
}
if ( config != null )
map.put( "config", config );
if ( action != null )
map.put( "action", action );
return map;
}
/** Creates a configuration from a URL.*/
public static Configuration createConfig( String configURL ) throws RaplaException
{
try
{
URLConnection conn = new URL( configURL).openConnection();
InputStreamReader stream = new InputStreamReader(conn.getInputStream());
StringBuilder builder = new StringBuilder();
//System.out.println( "File Content:");
int s= -1;
do {
s = stream.read();
// System.out.print( (char)s );
if ( s != -1)
{
builder.append( (char) s );
}
} while ( s != -1);
stream.close();
Assert.notNull( stream );
Logger logger = new NullLogger();
RaplaNonValidatedInput parser = new RaplaReaderImpl();
final SAXConfigurationHandler handler = new SAXConfigurationHandler();
String xml = builder.toString();
parser.read(xml, handler, logger);
Configuration config = handler.getConfiguration();
Assert.notNull( config );
return config;
}
catch ( EOFException ex )
{
throw new RaplaException( "Can't load configuration-file at " + configURL );
}
catch ( Exception ex )
{
throw new RaplaException( ex );
}
}
static public class RaplaReaderImpl implements RaplaNonValidatedInput
{
public void read(String xml, RaplaSAXHandler handler, Logger logger) throws RaplaException
{
InputSource source = new InputSource( new StringReader(xml));
try {
XMLReader reader = XMLReaderAdapter.createXMLReader(false);
reader.setContentHandler( new RaplaContentHandler(handler));
reader.parse(source );
reader.setErrorHandler( new RaplaErrorHandler( logger));
} catch (SAXException ex) {
Throwable cause = ex.getException();
if (cause instanceof SAXParseException) {
ex = (SAXParseException) cause;
cause = ex.getException();
}
if (ex instanceof SAXParseException) {
throw new RaplaException("Line: " + ((SAXParseException)ex).getLineNumber()
+ " Column: "+ ((SAXParseException)ex).getColumnNumber() + " "
+ ((cause != null) ? cause.getMessage() : ex.getMessage())
,(cause != null) ? cause : ex );
}
if (cause == null) {
throw new RaplaException( ex);
}
if (cause instanceof RaplaException)
throw (RaplaException) cause;
else
throw new RaplaException( cause);
} catch (IOException ex) {
throw new RaplaException( ex.getMessage(), ex);
}
}
}
/** Creates an configuration URL from a configuration path.
If path is null the URL of the defaultPropertiesFile
will be returned.
*/
public static URL configFileToURL( String path, String defaultPropertiesFile ) throws RaplaException
{
URL configURL = null;
try
{
if ( path != null )
{
File file = new File( path );
if ( file.exists() )
{
configURL = ( file.getCanonicalFile() ).toURI().toURL();
}
}
if ( configURL == null )
{
configURL = ConfigTools.class.getClassLoader().getResource( defaultPropertiesFile );
if ( configURL == null )
{
File file = new File( defaultPropertiesFile );
if ( !file.exists() )
{
file = new File( "war/WEB-INF/" + defaultPropertiesFile );
}
if ( !file.exists() )
{
file = new File( "war/webclient/" + defaultPropertiesFile );
}
if ( file.exists() )
{
configURL = file.getCanonicalFile().toURI().toURL();
}
}
}
}
catch ( MalformedURLException ex )
{
throw new RaplaException( "malformed config path" + path );
}
catch ( IOException ex )
{
throw new RaplaException( "Can't resolve config path" + path );
}
if ( configURL == null )
{
throw new RaplaException( defaultPropertiesFile
+ " not found on classpath and in working folder "
+ " Path config file with -c argument. "
+ " For more information start rapla -? or read the api-docs." );
}
return configURL;
}
/** Creates an configuration URL from a configuration filename and
the webstart codebae.
If filename is null the URL of the defaultPropertiesFile
will be returned.
*/
public static URL webstartConfigToURL( String defaultPropertiesFilename ) throws RaplaException
{
try
{
URL base = JNLPUtil.getCodeBase();
URL configURL = new URL( base, defaultPropertiesFilename );
return configURL;
}
catch ( Exception ex )
{
throw new RaplaException( "Can't get configuration file in webstart mode." );
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.framework.internal;
import org.rapla.framework.Provider;
import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
@SuppressWarnings("restriction")
public class Slf4jAdapter implements Provider<org.rapla.framework.logger.Logger> {
static ILoggerFactory logManager = LoggerFactory.getILoggerFactory();
static public org.rapla.framework.logger.Logger getLoggerForCategory(String categoryName) {
LocationAwareLogger loggerForCategory = (LocationAwareLogger)logManager.getLogger(categoryName);
return new Wrapper(loggerForCategory, categoryName);
}
public org.rapla.framework.logger.Logger get() {
return getLoggerForCategory( "rapla");
}
static class Wrapper implements org.rapla.framework.logger.Logger{
LocationAwareLogger logger;
String id;
public Wrapper( LocationAwareLogger loggerForCategory, String id) {
this.logger = loggerForCategory;
this.id = id;
}
public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
public void debug(String message) {
log(LocationAwareLogger.DEBUG_INT, message);
}
public void info(String message) {
log( LocationAwareLogger.INFO_INT, message);
}
private void log(int infoInt, String message) {
log( infoInt, message, null);
}
private void log( int level, String message,Throwable t) {
Object[] argArray = null;
String fqcn = Wrapper.class.getName();
logger.log(null, fqcn, level,message,argArray, t);
}
public void warn(String message) {
log( LocationAwareLogger.WARN_INT, message);
}
public void warn(String message, Throwable cause) {
log( LocationAwareLogger.WARN_INT, message, cause);
}
public void error(String message) {
log( LocationAwareLogger.ERROR_INT, message);
}
public void error(String message, Throwable cause) {
log( LocationAwareLogger.ERROR_INT, message, cause);
}
public org.rapla.framework.logger.Logger getChildLogger(String childLoggerName)
{
String childId = id + "." + childLoggerName;
return getLoggerForCategory( childId);
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.framework.internal;
import java.util.HashMap;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.internal.RaplaClientServiceImpl;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.internal.FacadeImpl;
import org.rapla.storage.CachableStorageOperator;
import org.rapla.storage.ImportExportManager;
import org.rapla.storage.StorageOperator;
import org.rapla.storage.dbrm.RemoteOperator;
public class RaplaMetaConfigInfo extends HashMap<String,ComponentInfo> {
private static final long serialVersionUID = 1L;
public RaplaMetaConfigInfo() {
put( "rapla-client", new ComponentInfo(RaplaClientServiceImpl.class.getName(),ClientServiceContainer.class.getName()));
put( "resource-bundle",new ComponentInfo(I18nBundleImpl.class.getName(),I18nBundle.class.getName()));
put( "facade",new ComponentInfo(FacadeImpl.class.getName(),ClientFacade.class.getName()));
put( "remote-storage",new ComponentInfo(RemoteOperator.class.getName(),new String[] {StorageOperator.class.getName(), CachableStorageOperator.class.getName()}));
// now the server configurations
put( "rapla-server", new ComponentInfo("org.rapla.server.internal.ServerServiceImpl",new String[]{"org.rapla.server.ServerServiceContainer"}));
put( "file-storage",new ComponentInfo("org.rapla.storage.dbfile.FileOperator",new String[] {StorageOperator.class.getName(), CachableStorageOperator.class.getName()}));
put( "db-storage",new ComponentInfo("org.rapla.storage.dbsql.DBOperator",new String[] {StorageOperator.class.getName(), CachableStorageOperator.class.getName()}));
put( "sql-storage",new ComponentInfo("org.rapla.storage.dbsql.DBOperator",new String[] {StorageOperator.class.getName(), CachableStorageOperator.class.getName()}));
put( "importexport", new ComponentInfo("org.rapla.storage.impl.server.ImportExportManagerImpl",ImportExportManager.class.getName()));
}
}
| Java |
package org.rapla.framework.internal;
import java.util.Map;
import java.util.Stack;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXHandler;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
public class SAXConfigurationHandler implements RaplaSAXHandler
{
final Stack<DefaultConfiguration> configStack = new Stack<DefaultConfiguration>();
Configuration parsedConfiguration;
public Configuration getConfiguration()
{
return parsedConfiguration;
}
public void startElement(String namespaceURI, String localName,
RaplaSAXAttributes atts) throws RaplaSAXParseException
{
DefaultConfiguration defaultConfiguration = new DefaultConfiguration(localName);
for ( Map.Entry<String,String> entry :atts.getMap().entrySet())
{
String name = entry.getKey();
String value = entry.getValue();
defaultConfiguration.setAttribute( name, value);
}
configStack.push( defaultConfiguration);
}
public void endElement(
String namespaceURI,
String localName
) throws RaplaSAXParseException
{
DefaultConfiguration current =configStack.pop();
if ( configStack.isEmpty())
{
parsedConfiguration = current;
}
else
{
DefaultConfiguration parent = configStack.peek();
parent.addChild( current);
}
}
public void characters(char[] ch, int start, int length) {
DefaultConfiguration peek = configStack.peek();
String value = peek.getValue(null);
StringBuffer buf = new StringBuffer();
if ( value != null)
{
buf.append( value);
}
buf.append( ch, start, length);
String string = buf.toString();
if ( string.trim().length() > 0)
{
peek.setValue( string);
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.framework.internal;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.rapla.components.util.DateTools;
import org.rapla.components.xmlbundle.LocaleSelector;
import org.rapla.components.xmlbundle.impl.LocaleSelectorImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.logger.Logger;
public class RaplaLocaleImpl extends AbstractRaplaLocale {
TimeZone zone;
TimeZone systemTimezone;
TimeZone importExportTimeZone;
LocaleSelector localeSelector = new LocaleSelectorImpl();
String[] availableLanguages;
String COUNTRY = "country";
String LANGUAGES = "languages";
String LANGUAGE = "language";
String CHARSET = "charset";
String charsetForHtml;
public RaplaLocaleImpl(Configuration config,Logger logger )
{
String selectedCountry = config.getChild( COUNTRY).getValue(Locale.getDefault().getCountry() );
Configuration languageConfig = config.getChild( LANGUAGES );
Configuration[] languages = languageConfig.getChildren( LANGUAGE );
charsetForHtml = config.getChild(CHARSET).getValue("iso-8859-15");
availableLanguages = new String[languages.length];
for ( int i=0;i<languages.length;i++ ) {
availableLanguages[i] = languages[i].getValue("en");
}
String selectedLanguage = languageConfig.getAttribute( "default", Locale.getDefault().getLanguage() );
if (selectedLanguage.trim().length() == 0)
selectedLanguage = Locale.getDefault().getLanguage();
localeSelector.setLocale( new Locale(selectedLanguage, selectedCountry) );
zone = DateTools.getTimeZone();
systemTimezone = TimeZone.getDefault();
importExportTimeZone = systemTimezone;
logger.info("Configured Locale= " + getLocaleSelector().getLocale().toString());
}
public TimeZone getSystemTimeZone() {
return systemTimezone;
}
public LocaleSelector getLocaleSelector() {
return localeSelector;
}
public Date fromUTCTimestamp(Date date)
{
Date raplaTime = toRaplaTime( importExportTimeZone,date );
return raplaTime;
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#getAvailableLanguages()
*/
public String[] getAvailableLanguages() {
return availableLanguages;
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#createCalendar()
*/
public Calendar createCalendar() {
return Calendar.getInstance( zone, getLocale() );
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#formatTime(java.util.Date)
*/
public String formatTime( Date date ) {
Locale locale = getLocale();
TimeZone timezone = getTimeZone();
DateFormat format = DateFormat.getTimeInstance( DateFormat.SHORT, locale );
format.setTimeZone( timezone );
String formatTime = format.format( date );
return formatTime;
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#formatNumber(long)
*/
public String formatNumber( long number ) {
Locale locale = getLocale();
return NumberFormat.getInstance( locale).format(number );
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#formatDateShort(java.util.Date)
*/
public String formatDateShort( Date date ) {
Locale locale = getLocale();
TimeZone timezone = zone;
StringBuffer buf = new StringBuffer();
FieldPosition fieldPosition = new FieldPosition( DateFormat.YEAR_FIELD );
DateFormat format = DateFormat.getDateInstance( DateFormat.SHORT, locale );
format.setTimeZone( timezone );
buf = format.format(date,
buf,
fieldPosition
);
if ( fieldPosition.getEndIndex()<buf.length() ) {
buf.delete( fieldPosition.getBeginIndex(), fieldPosition.getEndIndex()+1 );
} else if ( (fieldPosition.getBeginIndex()>=0) ) {
buf.delete( fieldPosition.getBeginIndex(), fieldPosition.getEndIndex() );
}
String result = buf.toString();
return result;
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#formatDate(java.util.Date)
*/
public String formatDate( Date date ) {
TimeZone timezone = zone;
Locale locale = getLocale();
DateFormat format = DateFormat.getDateInstance( DateFormat.SHORT, locale );
format.setTimeZone( timezone );
return format.format( date );
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#formatDateLong(java.util.Date)
*/
public String formatDateLong( Date date ) {
TimeZone timezone = zone;
Locale locale = getLocale();
DateFormat format = DateFormat.getDateInstance( DateFormat.MEDIUM, locale );
format.setTimeZone( timezone );
String dateFormat = format.format( date);
return dateFormat + " (" + getWeekday(date) + ")";
}
@Deprecated
public String formatTimestamp( Date date, TimeZone timezone )
{
Locale locale = getLocale();
StringBuffer buf = new StringBuffer();
{
DateFormat format = DateFormat.getDateInstance( DateFormat.SHORT, locale );
format.setTimeZone( timezone );
String formatDate= format.format( date );
buf.append( formatDate);
}
buf.append(" ");
{
DateFormat format = DateFormat.getTimeInstance( DateFormat.SHORT, locale );
format.setTimeZone( timezone );
String formatTime = format.format( date );
buf.append( formatTime);
}
return buf.toString();
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#getWeekday(java.util.Date)
*/
public String getWeekday( Date date ) {
TimeZone timeZone = getTimeZone();
Locale locale = getLocale();
SimpleDateFormat format = new SimpleDateFormat( "EE", locale );
format.setTimeZone( timeZone );
return format.format( date );
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#getMonth(java.util.Date)
*/
public String getMonth( Date date ) {
TimeZone timeZone = getTimeZone();
Locale locale = getLocale();
SimpleDateFormat format = new SimpleDateFormat( "MMMMM", locale );
format.setTimeZone( timeZone );
return format.format( date );
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#getTimeZone()
*/
public TimeZone getTimeZone() {
return zone;
}
public TimeZone getImportExportTimeZone() {
return importExportTimeZone;
}
public void setImportExportTimeZone(TimeZone importExportTimeZone) {
this.importExportTimeZone = importExportTimeZone;
}
/* (non-Javadoc)
* @see org.rapla.common.IRaplaLocale#getLocale()
*/
public Locale getLocale() {
return localeSelector.getLocale();
}
public String getCharsetNonUtf()
{
return charsetForHtml;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.framework.internal;
public class ComponentInfo {
String className;
String[] roles;
public ComponentInfo(String className) {
this( className, className );
}
public ComponentInfo(String className, String roleName) {
this( className, new String[] {roleName} );
}
public ComponentInfo(String className, String[] roleNames) {
this.className = className;
this.roles = roleNames;
}
public String[] getRoles() {
return roles;
}
public String getClassname() {
return className;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.framework.internal;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.rapla.framework.Provider;
public class RaplaJDKLoggingAdapter implements Provider<org.rapla.framework.logger.Logger> {
public org.rapla.framework.logger.Logger get() {
final Logger logger = getLogger( "rapla");
return new Wrapper(logger, "rapla");
}
static private java.util.logging.Logger getLogger(String categoryName)
{
Logger logger = Logger.getLogger(categoryName);
return logger;
}
static String WRAPPER_NAME = RaplaJDKLoggingAdapter.class.getName();
class Wrapper implements org.rapla.framework.logger.Logger{
java.util.logging.Logger logger;
String id;
public Wrapper( java.util.logging.Logger logger, String id) {
this.logger = logger;
this.id = id;
}
public boolean isDebugEnabled() {
return logger.isLoggable(Level.CONFIG);
}
public void debug(String message) {
log(Level.CONFIG, message);
}
public void info(String message) {
log(Level.INFO, message);
}
public void warn(String message) {
log(Level.WARNING,message);
}
public void warn(String message, Throwable cause) {
log(Level.WARNING,message, cause);
}
public void error(String message) {
log(Level.SEVERE, message);
}
public void error(String message, Throwable cause) {
log(Level.SEVERE, message, cause);
}
private void log(Level level,String message) {
log(level, message, null);
}
private void log(Level level,String message, Throwable cause) {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
String sourceClass = null;
String sourceMethod =null;
for (StackTraceElement element:stackTrace)
{
String classname = element.getClassName();
if ( !classname.startsWith(WRAPPER_NAME))
{
sourceClass=classname;
sourceMethod =element.getMethodName();
break;
}
}
logger.logp(level,sourceClass, sourceMethod,message, cause);
}
public org.rapla.framework.logger.Logger getChildLogger(String childLoggerName)
{
String childId = id+ "." + childLoggerName;
Logger childLogger = getLogger( childId);
return new Wrapper( childLogger, childId);
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.framework.internal;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.jws.WebService;
import org.rapla.components.util.Cancelable;
import org.rapla.components.util.Command;
import org.rapla.components.util.CommandScheduler;
import org.rapla.framework.Configuration;
import org.rapla.framework.ConfigurationException;
import org.rapla.framework.Container;
import org.rapla.framework.Disposable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaDefaultContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.TypedComponentRole;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.dbrm.RemoteServiceCaller;
/** Base class for the ComponentContainers in Rapla.
* Containers are the RaplaMainContainer, the Client- and the Server-Service
*/
public class ContainerImpl implements Container
{
protected Container m_parent;
protected RaplaDefaultContext m_context;
protected Configuration m_config;
protected List<ComponentHandler> m_componentHandler = Collections.synchronizedList(new ArrayList<ComponentHandler>());
protected Map<String,RoleEntry> m_roleMap = Collections.synchronizedMap(new LinkedHashMap<String,RoleEntry>());
Logger logger;
public ContainerImpl(RaplaContext parentContext, Configuration config, Logger logger) throws RaplaException {
m_config = config;
// if ( parentContext.has(Logger.class ) )
// {
// logger = parentContext.lookup( Logger.class);
// }
// else
// {
// logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
// }
this.logger = logger;
if ( parentContext.has(Container.class )) {
m_parent = parentContext.lookup( Container.class);
}
m_context = new RaplaDefaultContext(parentContext) {
@Override
protected Object lookup(String role) throws RaplaContextException {
ComponentHandler handler = getHandler( role );
if ( handler != null ) {
return handler.get();
}
return null;
}
@Override
protected boolean has(String role) {
if (getHandler( role ) != null)
return true;
return false;
}
};
addContainerProvidedComponentInstance(Logger.class,logger);
init( );
}
@SuppressWarnings("unchecked")
public <T> T lookup(Class<T> componentRole, String hint) throws RaplaContextException {
String key = componentRole.getName()+ "/" + hint;
ComponentHandler handler = getHandler( key );
if ( handler != null ) {
return (T) handler.get();
}
if ( m_parent != null)
{
return m_parent.lookup(componentRole, hint);
}
throw new RaplaContextException( key );
}
public Logger getLogger()
{
return logger;
}
protected void init() throws RaplaException {
configure( m_config );
addContainerProvidedComponentInstance( Container.class, this );
addContainerProvidedComponentInstance( Logger.class, getLogger());
}
public StartupEnvironment getStartupEnvironment() {
try
{
return getContext().lookup( StartupEnvironment.class);
}
catch ( RaplaContextException e )
{
throw new IllegalStateException(" Container not initialized with a startup environment");
}
}
protected void configure( final Configuration config )
throws RaplaException
{
Map<String,ComponentInfo> m_componentInfos = getComponentInfos();
final Configuration[] elements = config.getChildren();
for ( int i = 0; i < elements.length; i++ )
{
final Configuration element = elements[i];
final String id = element.getAttribute( "id", null );
if ( null == id )
{
// Only components with an id attribute are treated as components.
getLogger().debug( "Ignoring configuration for component, " + element.getName()
+ ", because the id attribute is missing." );
}
else
{
final String className;
final String[] roles;
if ( "component".equals( element.getName() ) )
{
try {
className = element.getAttribute( "class" );
Configuration[] roleConfigs = element.getChildren("roles");
roles = new String[ roleConfigs.length ];
for ( int j=0;j< roles.length;j++) {
roles[j] = roleConfigs[j].getValue();
}
} catch ( ConfigurationException ex) {
throw new RaplaException( ex);
}
}
else
{
String configName = element.getName();
final ComponentInfo roleEntry = m_componentInfos.get( configName );
if ( null == roleEntry )
{
final String message = "No class found matching configuration name " + "[name: " + element.getName() + "]";
getLogger().error( message );
continue;
}
roles = roleEntry.getRoles();
className = roleEntry.getClassname();
}
if ( getLogger().isDebugEnabled() )
{
getLogger().debug( "Configuration processed for: " + className );
}
Logger logger = this.logger.getChildLogger( id );
ComponentHandler handler =new ComponentHandler( element, className, logger);
for ( int j=0;j< roles.length;j++) {
String roleName = (roles[j]);
addHandler( roleName, id, handler );
}
}
}
}
protected Map<String,ComponentInfo> getComponentInfos() {
return Collections.emptyMap();
}
public <T, I extends T> void addContainerProvidedComponent(Class<T> roleInterface, Class<I> implementingClass) {
addContainerProvidedComponent(roleInterface, implementingClass, null, (Configuration)null);
}
public <T, I extends T> void addContainerProvidedComponent(Class<T> roleInterface, Class<I> implementingClass, Configuration config) {
addContainerProvidedComponent(roleInterface, implementingClass, null,config);
}
public <T, I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass) {
addContainerProvidedComponent(roleInterface, implementingClass, (Configuration) null);
}
public <T, I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass, Configuration config) {
addContainerProvidedComponent( roleInterface, implementingClass, null, config);
}
public <T, I extends T> void addContainerProvidedComponentInstance(TypedComponentRole<T> roleInterface, I implementingInstance) {
addContainerProvidedComponentInstance(roleInterface.getId(), implementingInstance, null);
}
public <T, I extends T> void addContainerProvidedComponentInstance(Class<T> roleInterface, I implementingInstance) {
addContainerProvidedComponentInstance(roleInterface, implementingInstance, implementingInstance.toString());
}
public <T> Collection< T> lookupServicesFor(TypedComponentRole<T> role) throws RaplaContextException {
Collection<T> list = new LinkedHashSet<T>();
for (T service: getAllServicesForThisContainer(role)) {
list.add(service);
}
if ( m_parent != null)
{
for (T service:m_parent.lookupServicesFor(role))
{
list.add( service);
}
}
return list;
}
public <T> Collection<T> lookupServicesFor(Class<T> role) throws RaplaContextException {
Collection<T> list = new LinkedHashSet<T>();
for (T service:getAllServicesForThisContainer(role)) {
list.add( service);
}
if ( m_parent != null)
{
for (T service:m_parent.lookupServicesFor(role))
{
list.add( service);
}
}
return list;
}
protected <T, I extends T> void addContainerProvidedComponentInstance(Class<T> roleInterface, I implementingInstance, String hint) {
addContainerProvidedComponentInstance(roleInterface.getName(), implementingInstance, hint);
}
protected <T, I extends T> void addContainerProvidedComponent(Class<T> roleInterface, Class<I> implementingClass, String hint, Configuration config) {
addContainerProvidedComponent( roleInterface.getName(), implementingClass.getName(), hint, config);
}
private <T, I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass, String hint, Configuration config)
{
addContainerProvidedComponent( roleInterface.getId(), implementingClass.getName(), hint, config);
}
synchronized private void addContainerProvidedComponent(String role,String classname, String hint,Configuration config) {
addContainerProvidedComponent( new String[] {role}, classname, hint, config);
}
synchronized private void addContainerProvidedComponentInstance(String role,Object componentInstance,String hint) {
addHandler( role, hint, new ComponentHandler(componentInstance));
}
synchronized private void addContainerProvidedComponent(String[] roles,String classname,String hint, Configuration config) {
ComponentHandler handler = new ComponentHandler( config, classname, getLogger() );
for ( int i=0;i<roles.length;i++) {
addHandler( roles[i], hint, handler);
}
}
protected <T> Collection<T> getAllServicesForThisContainer(TypedComponentRole<T> role) {
RoleEntry entry = m_roleMap.get( role.getId() );
return getAllServicesForThisContainer( entry);
}
protected <T> Collection<T> getAllServicesForThisContainer(Class<T> role) {
RoleEntry entry = m_roleMap.get( role.getName() );
return getAllServicesForThisContainer( entry);
}
private <T> Collection<T> getAllServicesForThisContainer(RoleEntry entry) {
if ( entry == null)
{
return Collections.emptyList();
}
List<T> result = new ArrayList<T>();
Set<String> hintSet = entry.getHintSet();
for (String hint: hintSet)
{
ComponentHandler handler = entry.getHandler(hint);
try
{
Object service = handler.get();
// we can safely cast here because the method is only called from checked methods
@SuppressWarnings("unchecked")
T casted = (T)service;
result.add(casted);
}
catch (Exception e)
{
Throwable ex = e;
while( ex.getCause() != null)
{
ex = ex.getCause();
}
getLogger().error("Could not initialize component " + handler + " due to " + ex.getMessage() + " removing from service list" , e);
entry.remove(hint);
}
}
return result;
}
/**
* @param roleName
* @param hint
* @param handler
*/
private void addHandler(String roleName, String hint, ComponentHandler handler) {
m_componentHandler.add( handler);
RoleEntry entry = m_roleMap.get( roleName );
if ( entry == null)
entry = new RoleEntry(roleName);
entry.put( hint , handler);
m_roleMap.put( roleName, entry);
}
ComponentHandler getHandler( String role) {
int hintSeperator = role.indexOf('/');
String roleName = role;
String hint = null;
if ( hintSeperator > 0 ) {
roleName = role.substring( 0, hintSeperator );
hint = role.substring( hintSeperator + 1 );
}
return getHandler( roleName, hint );
}
ComponentHandler getHandler( String role,Object hint) {
RoleEntry entry = m_roleMap.get( role );
if ( entry == null)
{
return null;
}
ComponentHandler handler = entry.getHandler( hint );
if ( handler != null)
{
return handler;
}
if ( hint == null || hint.equals("*" ) )
return entry.getFirstHandler();
// Try the first accessible handler
return null;
}
protected final class DefaultScheduler implements CommandScheduler {
private final ScheduledExecutorService executor;
private DefaultScheduler() {
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(5,new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
String name = thread.getName();
if ( name == null)
{
name = "";
}
thread.setName("raplascheduler-" + name.toLowerCase().replaceAll("thread", "").replaceAll("-|\\[|\\]", ""));
thread.setDaemon(true);
return thread;
}
});
this.executor = executor;
}
public Cancelable schedule(Command command, long delay)
{
Runnable task = createTask(command);
return schedule(task, delay);
}
public Cancelable schedule(Runnable task, long delay) {
if (executor.isShutdown())
{
RaplaException ex = new RaplaException("Can't schedule command because executer is already shutdown " + task.toString());
getLogger().error(ex.getMessage(), ex);
return createCancable( null);
}
TimeUnit unit = TimeUnit.MILLISECONDS;
ScheduledFuture<?> schedule = executor.schedule(task, delay, unit);
return createCancable( schedule);
}
private Cancelable createCancable(final ScheduledFuture<?> schedule) {
return new Cancelable() {
public void cancel() {
if ( schedule != null)
{
schedule.cancel(true);
}
}
};
}
public Cancelable schedule(Runnable task, long delay, long period) {
if (executor.isShutdown())
{
RaplaException ex = new RaplaException("Can't schedule command because executer is already shutdown " + task.toString());
getLogger().error(ex.getMessage(), ex);
return createCancable( null);
}
TimeUnit unit = TimeUnit.MILLISECONDS;
ScheduledFuture<?> schedule = executor.scheduleAtFixedRate(task, delay, period, unit);
return createCancable( schedule);
}
public Cancelable schedule(Command command, long delay, long period)
{
Runnable task = createTask(command);
return schedule(task, delay, period);
}
public void cancel() {
try{
getLogger().info("Stopping scheduler thread.");
List<Runnable> shutdownNow = executor.shutdownNow();
for ( Runnable task: shutdownNow)
{
long delay = -1;
if ( task instanceof ScheduledFuture)
{
ScheduledFuture scheduledFuture = (ScheduledFuture) task;
delay = scheduledFuture.getDelay( TimeUnit.SECONDS);
}
if ( delay <=0)
{
getLogger().warn("Interrupted active task " + task );
}
}
getLogger().info("Stopped scheduler thread.");
}
catch ( Throwable ex)
{
getLogger().warn(ex.getMessage());
}
// we give the update threads some time to execute
try
{
Thread.sleep( 50);
}
catch (InterruptedException e)
{
}
}
}
class RoleEntry {
Map<String,ComponentHandler> componentMap = Collections.synchronizedMap(new LinkedHashMap<String,ComponentHandler>());
ComponentHandler firstEntry;
int generatedHintCounter = 0;
String roleName;
RoleEntry(String roleName) {
this.roleName = roleName;
}
String generateHint()
{
return roleName + "_" +generatedHintCounter++;
}
void put( String hint, ComponentHandler handler ){
if ( hint == null)
{
hint = generateHint();
}
synchronized (this) {
componentMap.put( hint, handler);
}
if (firstEntry == null)
firstEntry = handler;
}
void remove(String hint)
{
componentMap.remove( hint);
}
Set<String> getHintSet() {
// we return a clone to avoid concurrent modification exception
synchronized (this) {
LinkedHashSet<String> result = new LinkedHashSet<String>(componentMap.keySet());
return result;
}
}
ComponentHandler getHandler(Object hint) {
return componentMap.get( hint );
}
ComponentHandler getFirstHandler() {
return firstEntry;
}
public String toString()
{
return componentMap.toString();
}
}
public RaplaContext getContext() {
return m_context;
}
boolean disposing;
public void dispose() {
// prevent reentrence in dispose
synchronized ( this)
{
if ( disposing)
{
getLogger().warn("Disposing is called twice",new RaplaException(""));
return;
}
disposing = true;
}
try
{
removeAllComponents();
}
finally
{
disposing = false;
}
}
protected void removeAllComponents() {
Iterator<ComponentHandler> it = new ArrayList<ComponentHandler>(m_componentHandler).iterator();
while ( it.hasNext() ) {
it.next().dispose();
}
m_componentHandler.clear();
m_roleMap.clear();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
Constructor findDependantConstructor(Class componentClass) {
Constructor[] constructors= componentClass.getConstructors();
TreeMap<Integer,Constructor> constructorMap = new TreeMap<Integer, Constructor>();
for (Constructor constructor:constructors) {
Class[] types = constructor.getParameterTypes();
boolean compatibleParameters = true;
for (int j=0; j< types.length; j++ ) {
Class type = types[j];
if (!( type.isAssignableFrom( RaplaContext.class) || type.isAssignableFrom( Configuration.class) || type.isAssignableFrom(Logger.class) || type.isAnnotationPresent(WebService.class) || getContext().has( type)))
{
compatibleParameters = false;
}
}
if ( compatibleParameters )
{
//return constructor;
constructorMap.put( types.length, constructor);
}
}
// return the constructor with the most paramters
if (!constructorMap.isEmpty())
{
return constructorMap.lastEntry().getValue();
}
return null;
}
/** Instantiates a class and passes the config, logger and the parent context to the object if needed by the constructor.
* This concept is taken form pico container.*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object instanciate( String componentClassName, Configuration config, Logger logger ) throws RaplaContextException
{
RaplaContext context = m_context;
Class componentClass;
try {
componentClass = Class.forName( componentClassName );
} catch (ClassNotFoundException e1) {
throw new RaplaContextException("Component class " + componentClassName + " not found." , e1);
}
Constructor c = findDependantConstructor( componentClass );
Object[] params = null;
if ( c != null) {
Class[] types = c.getParameterTypes();
params = new Object[ types.length ];
for (int i=0; i< types.length; i++ ) {
Class type = types[i];
Object p;
if ( type.isAssignableFrom( RaplaContext.class)) {
p = context;
} else if ( type.isAssignableFrom( Configuration.class)) {
p = config;
} else if ( type.isAssignableFrom( Logger.class)) {
p = logger;
} else if ( type.isAnnotationPresent(WebService.class)) {
RemoteServiceCaller lookup = context.lookup(RemoteServiceCaller.class);
p = lookup.getRemoteMethod( type);
} else {
Class guessedRole = type;
if ( context.has( guessedRole )) {
p = context.lookup( guessedRole );
} else {
throw new RaplaContextException(componentClass, "Can't statisfy constructor dependency " + type.getName() );
}
}
params[i] = p;
}
}
try {
final Object component;
if ( c!= null) {
component = c.newInstance( params);
} else {
component = componentClass.newInstance();
}
return component;
}
catch (Exception e)
{
throw new RaplaContextException(componentClassName + " could not be initialized due to " + e.getMessage(), e);
}
}
protected class ComponentHandler implements Disposable {
protected Configuration config;
protected Logger logger;
protected Object component;
protected String componentClassName;
boolean dispose = true;
protected ComponentHandler( Object component) {
this.component = component;
this.dispose = false;
}
protected ComponentHandler( Configuration config, String componentClass, Logger logger) {
this.config = config;
this.componentClassName = componentClass;
this.logger = logger;
}
Semaphore instanciating = new Semaphore(1);
Object get() throws RaplaContextException {
if ( component != null)
{
return component;
}
boolean acquired;
try {
acquired = instanciating.tryAcquire(60,TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RaplaContextException("Timeout while waiting for instanciation of " + componentClassName );
}
if ( !acquired)
{
throw new RaplaContextException("Instanciating component " + componentClassName + " twice. Possible a cyclic dependency.",new RaplaException(""));
}
else
{
try
{
// test again, maybe instanciated by another thread
if ( component != null)
{
return component;
}
component = instanciate( componentClassName, config, logger );
return component;
}
finally
{
instanciating.release();
}
}
}
boolean disposing;
public void dispose() {
// prevent reentrence in dispose
synchronized ( this)
{
if ( disposing)
{
getLogger().warn("Disposing is called twice",new RaplaException(""));
return;
}
disposing = true;
}
try
{
if (component instanceof Disposable)
{
if ( component == ContainerImpl.this)
{
return;
}
((Disposable) component).dispose();
}
} catch ( Exception ex) {
getLogger().error("Error disposing component ", ex );
}
finally
{
disposing = false;
}
}
public String toString()
{
if ( component != null)
{
return component.toString();
}
if ( componentClassName != null)
{
return componentClassName.toString();
}
return super.toString();
}
}
protected Runnable createTask(final Command command) {
Runnable timerTask = new Runnable() {
public void run() {
try {
command.execute();
} catch (Exception e) {
getLogger().error( e.getMessage(), e);
}
}
public String toString()
{
return command.toString();
}
};
return timerTask;
}
protected CommandScheduler createCommandQueue() {
CommandScheduler commandQueue = new DefaultScheduler();
return commandQueue;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.