code
stringlengths
3
1.18M
language
stringclasses
1 value
/*--------------------------------------------------------------------------* | 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.abstractcalendar; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.RepaintManager; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateChangeListener; import org.rapla.components.calendarview.CalendarView; import org.rapla.components.calendarview.swing.AbstractSwingCalendar; import org.rapla.components.calendarview.swing.ViewListener; import org.rapla.components.util.DateTools; import org.rapla.components.util.TimeInterval; import org.rapla.entities.NamedComparator; import org.rapla.entities.domain.Allocatable; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.SwingCalendarView; import org.rapla.gui.SwingViewFactory; import org.rapla.gui.VisibleTimeInterval; public abstract class AbstractRaplaSwingCalendar extends RaplaGUIComponent implements SwingCalendarView, DateChangeListener, MultiCalendarPrint, VisibleTimeInterval, Printable { protected final CalendarModel model; protected final AbstractSwingCalendar view; protected DateChooserPanel dateChooser; JComponent container; JLabel titleView; int units = 1; public AbstractRaplaSwingCalendar(RaplaContext sm,CalendarModel model, boolean editable) throws RaplaException { super( sm); this.model = model; boolean printable = isPrintContext(); view = createView( !printable); view.setEditable(editable); view.setLocale( getRaplaLocale().getLocale() ); view.setTimeZone(getRaplaLocale().getTimeZone()); if ( editable ) { view.addCalendarViewListener( createListener() ); } if ( !printable ) { container = view.getComponent(); } else { container = new JPanel(); container.setLayout( new BorderLayout()); container.setOpaque( false ); view.getComponent().setOpaque( false); titleView = new JLabel(); titleView.setFont(new Font("SansSerif", Font.BOLD, 14)); titleView.setOpaque(false); titleView.setForeground(Color.black); //titleView.setHorizontalAlignment(JLabel.CENTER); titleView.setBorder(BorderFactory.createEmptyBorder(0,11,12,11)); container.add( titleView, BorderLayout.NORTH); container.add( view.getComponent(), BorderLayout.CENTER); } dateChooser = new DateChooserPanel(getContext(), model); dateChooser.addDateChangeListener(this); dateChooser.setIncrementSize( getIncrementSize() ); update(); } protected boolean isPrintContext() { return getContext().has(SwingViewFactory.PRINT_CONTEXT) && getService( SwingViewFactory.PRINT_CONTEXT); } abstract protected AbstractSwingCalendar createView(boolean showScrollPane) throws RaplaException; abstract protected void configureView() throws RaplaException; abstract public int getIncrementSize(); /** * @throws RaplaException */ protected ViewListener createListener() throws RaplaException { return new RaplaCalendarViewListener(getContext(), model, view.getComponent()); } public JComponent getDateSelection() { return dateChooser.getComponent(); } public void dateChanged(DateChangeEvent evt) { try { // TODO why is that here //Date date = evt.getDate(); // model.setSelectedDate( date ); update(); } catch (RaplaException ex) { showException(ex, view.getComponent()); } } public void update( ) throws RaplaException { if ( titleView != null) { titleView.setText( model.getNonEmptyTitle()); } dateChooser.update(); if (!isPrintContext()) { int minBlockWidth = getCalendarOptions().getMinBlockWidth(); view.setMinBlockWidth( minBlockWidth); } configureView( ); Date startDate = getStartDate() ; Date endDate = getEndDate(); ensureViewTimeframeIsInModel(startDate, endDate); view.rebuild( createBuilder() ); if ( !view.isEditable()) { Dimension size = view.getComponent().getPreferredSize(); container.setBounds( 0,0, size.width, size.height + 40); } } protected Date getEndDate() { return view.getEndDate() ; } protected Date getStartDate() { return view.getStartDate(); } public TimeInterval getVisibleTimeInterval() { return new TimeInterval( getStartDate(),getEndDate()); } protected void ensureViewTimeframeIsInModel( Date startDate, Date endDate) { // Update start- and enddate of the model Date modelStart = model.getStartDate(); Date modelEnd = model.getEndDate(); if ( modelStart == null || modelStart.after( startDate)) { model.setStartDate( startDate); } if ( modelEnd == null || modelEnd.before( endDate)) { model.setEndDate( endDate); } } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = new SwingRaplaBuilder(getContext()); Date startDate = getStartDate() ; Date endDate = getEndDate(); builder.setFromModel( model, startDate, endDate ); builder.setRepeatingVisible( view.isEditable()); GroupAllocatablesStrategy strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ); boolean compactColumns = getCalendarOptions().isCompactColumns() || builder.getAllocatables().size() ==0 ; strategy.setFixedSlotsEnabled( !compactColumns); strategy.setResolveConflictsEnabled( true ); builder.setBuildStrategy( strategy ); return builder; } public JComponent getComponent() { return container; } public List<Allocatable> getSortedAllocatables() throws RaplaException { Allocatable[] selectedAllocatables = model.getSelectedAllocatables(); List<Allocatable> sortedAllocatables = new ArrayList<Allocatable>( Arrays.asList( selectedAllocatables)); Collections.sort(sortedAllocatables, new NamedComparator<Allocatable>( getLocale() )); return sortedAllocatables; } public void scrollToStart() { } public CalendarView getCalendarView() { return view; } //DateTools.addDays(new Date(), 100); Date currentPrintDate; Map<Date,Integer> pageStartMap = new HashMap<Date,Integer>(); Double scaleFactor = null; /** * @see java.awt.print.Printable#print(java.awt.Graphics, java.awt.print.PageFormat, int) */ public int print(Graphics g, PageFormat format, int page) throws PrinterException { /*JFrame frame = new JFrame(); frame.setSize(300,300); frame.getContentPane().add( container); frame.pack(); frame.setVisible(false);*/ final Date startDate = model.getStartDate(); final Date endDate = model.getEndDate(); final Date selectedDate = model.getSelectedDate(); int pages = getUnits(); Date targetDate; { Calendar cal = getRaplaLocale().createCalendar(); cal.setTime( selectedDate); cal.add(getIncrementSize(), pages-1); targetDate = cal.getTime(); } if ( page <= 0 ) { currentPrintDate = selectedDate; pageStartMap.clear(); scaleFactor = null; pageStartMap.put(currentPrintDate,page); } while (true) { int printOffset = (int)DateTools.countDays(selectedDate, currentPrintDate); model.setStartDate(DateTools.addDays(startDate, printOffset)); model.setEndDate(DateTools.addDays(endDate, printOffset)); model.setSelectedDate( DateTools.addDays(selectedDate, printOffset)); try { Graphics2D g2 = (Graphics2D) g; try { update(); } catch (RaplaException e) { throw new PrinterException(e.getMessage()); } double preferedHeight = view.getComponent().getPreferredSize().getHeight(); if ( scaleFactor == null) { scaleFactor = Math.min(1, 1/ Math.min(2.5,preferedHeight / format.getImageableHeight())); } double newWidth = format.getImageableWidth() / scaleFactor ; double scaledPreferedHeigth =preferedHeight * scaleFactor; Component component = container; view.updateSize( (int)newWidth ); container.setBounds( 0,0, (int)newWidth, (int)preferedHeight); try { update(); } catch (RaplaException e) { throw new PrinterException(e.getMessage()); } Integer pageStart = pageStartMap.get( currentPrintDate); if ( pageStart == null) { return NO_SUCH_PAGE; } int translatey = (int)((page-pageStart )* format.getImageableHeight()); if ( translatey > scaledPreferedHeigth-20) { if ( targetDate != null && currentPrintDate.before( targetDate)) { Calendar cal = getRaplaLocale().createCalendar(); cal.setTime( currentPrintDate); cal.add(getIncrementSize(), 1); currentPrintDate = cal.getTime(); pageStartMap.put(currentPrintDate,page); continue; } else { return NO_SUCH_PAGE; } } if ( translatey <0 && targetDate!= null) { Calendar cal = getRaplaLocale().createCalendar(); cal.setTime( currentPrintDate); cal.add(getIncrementSize(), -1); currentPrintDate = cal.getTime(); continue; } if ( targetDate != null && currentPrintDate.after( targetDate)) { return NO_SUCH_PAGE; } g2.translate(format.getImageableX(), format.getImageableY() - translatey ); g2.clipRect(0, translatey , (int)(format.getImageableWidth() ), (int)(format.getImageableHeight())); g2.scale(scaleFactor, scaleFactor); RepaintManager rm = RepaintManager.currentManager(component); boolean db= rm.isDoubleBufferingEnabled(); try { rm.setDoubleBufferingEnabled(false); component.printAll(g); return Printable.PAGE_EXISTS; } finally { rm.setDoubleBufferingEnabled(db); } } finally { model.setStartDate(startDate); model.setEndDate(endDate); model.setSelectedDate( selectedDate); } } } public String getCalendarUnit() { int incrementSize = getIncrementSize(); if ( incrementSize == Calendar.DAY_OF_YEAR) { return getString("days"); } else if ( incrementSize == Calendar.WEEK_OF_YEAR) { return getString("weeks"); } else if ( incrementSize == Calendar.MONTH) { return getString("months"); } else { return ""; } } public int getUnits() { return units; } public void setUnits(int units) { this.units = units; } }
Java
/** * */ package org.rapla.plugin.abstractcalendar; import java.awt.Component; import java.awt.Point; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.swing.JComponent; import javax.swing.JMenuItem; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.swing.ViewListener; import org.rapla.entities.NamedComparator; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarSelectionModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; import org.rapla.gui.MenuContext; import org.rapla.gui.MenuFactory; import org.rapla.gui.ObjectMenuFactory; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.ReservationEdit; import org.rapla.gui.internal.action.AppointmentAction; import org.rapla.gui.internal.common.RaplaClipboard; import org.rapla.gui.toolkit.MenuInterface; import org.rapla.gui.toolkit.RaplaMenu; import org.rapla.gui.toolkit.RaplaMenuItem; import org.rapla.gui.toolkit.RaplaPopupMenu; public class RaplaCalendarViewListener extends RaplaGUIComponent implements ViewListener { public static TypedComponentRole<Date> SELECTED_DATE = new TypedComponentRole<Date>( RaplaCalendarViewListener.class.getName()); protected boolean keepTime = false; protected JComponent calendarContainerComponent; CalendarModel model; public RaplaCalendarViewListener(RaplaContext context, CalendarModel model, JComponent calendarContainerComponent) { super( context); this.model = model; this.calendarContainerComponent = calendarContainerComponent; } protected CalendarModel getModel() { return model; } /** override this method if you want to implement a custom time selection */ public void selectionChanged(Date start,Date end) { // #TODO this cast need to be replaced without adding the setter methods to the readOnly interface CalendarModel CalendarSelectionModel castedModel = (CalendarSelectionModel)model; castedModel.markInterval( start, end); Collection<Allocatable> markedAllocatables = getMarkedAllocatables(); castedModel.setMarkedAllocatables( markedAllocatables); } /** * start, end and slotNr are not used because they are handled by selectionChanged method * @param start not used because handled by selectionChanged method * @param end not used because handled by selectionChanged method * @param slotNr not used because handled by selectionChanged method * */ public void selectionPopup(Component component,Point p,Date start,Date end, int slotNr) { selectionPopup(component, p); } public void selectionPopup(Component component,Point p) { try { RaplaPopupMenu menu= new RaplaPopupMenu(); Object focusedObject = null; MenuContext context = new MenuContext(getContext(), focusedObject); getService(MenuFactory.class).addReservationWizards(menu, context, null); if (canCreateReservation()) { // User user = getUser(); // Date today = getQuery().today(); // boolean canAllocate = false; // Collection<Allocatable> selectedAllocatables = getMarkedAllocatables(); // for ( Allocatable alloc: selectedAllocatables) { // if (alloc.canAllocate( user, start, end, today)) // canAllocate = true; // } // canAllocate || (selectedAllocatables.size() == 0 && if ( canUserAllocateSomething( getUser()) ) { ReservationEdit[] editWindows = getReservationController().getEditWindows(); if ( editWindows.length >0 ) { RaplaMenu addItem = new RaplaMenu("add_to"); addItem.setText(getString("add_to")); menu.add(addItem); for ( ReservationEdit reservationEdit: editWindows) { addAppointmentAction(addItem,component,p).setAddTo( reservationEdit); } } } else { JMenuItem cantAllocate = new JMenuItem(getString("permission.denied")); cantAllocate.setEnabled( false); menu.add( cantAllocate); } } // RaplaClipboard clipboard = getService(RaplaClipboard.class); Appointment appointment = clipboard.getAppointment(); if ( appointment != null ) { if (!clipboard.isWholeReservation()) { addAppointmentAction(menu,component,p).setPaste( keepTime ); } addAppointmentAction(menu,component,p).setPasteAsNew( keepTime ); } menu.show(component,p.x,p.y); } catch (RaplaException ex) { showException(ex, calendarContainerComponent); } } public void blockPopup(Block block,Point p) { SwingRaplaBlock b = (SwingRaplaBlock) block; if ( !b.getContext().isBlockSelected() ) { return; } showPopupMenu(b, p); } public void blockEdit(Block block,Point p) { // double click on block in view. SwingRaplaBlock b = (SwingRaplaBlock) block; if ( !b.getContext().isBlockSelected() ) { return; } try { if (!canModify(b.getReservation())) return; final AppointmentBlock appointmentBlock = b.getAppointmentBlock(); getReservationController().edit(appointmentBlock); } catch (RaplaException ex) { showException(ex,b.getView()); } } public void moved(Block block,Point p,Date newStart, int slotNr) { moved(block, p, newStart); } protected void moved(Block block, Point p, Date newStart) { SwingRaplaBlock b = (SwingRaplaBlock) block; try { long offset = newStart.getTime() - b.getStart().getTime(); Date newStartWithOffset = new Date(b.getAppointmentBlock().getStart() + offset); getReservationController().moveAppointment(b.getAppointmentBlock() ,newStartWithOffset ,calendarContainerComponent ,p, keepTime); } catch (RaplaException ex) { showException(ex,b.getView()); } } public boolean isKeepTime() { return keepTime; } public void setKeepTime(boolean keepTime) { this.keepTime = keepTime; } public void resized(Block block,Point p,Date newStart, Date newEnd, int slotNr) { SwingRaplaBlock b = (SwingRaplaBlock) block; try { getReservationController().resizeAppointment(b.getAppointmentBlock() ,newStart ,newEnd ,calendarContainerComponent ,p, keepTime); } catch (RaplaException ex) { showException(ex,b.getView()); } } public List<Allocatable> getSortedAllocatables() { try { Allocatable[] selectedAllocatables; selectedAllocatables = model.getSelectedAllocatables(); List<Allocatable> sortedAllocatables = new ArrayList<Allocatable>( Arrays.asList( selectedAllocatables)); Collections.sort(sortedAllocatables, new NamedComparator<Allocatable>( getLocale() )); return sortedAllocatables; } catch (RaplaException e) { getLogger().error(e.getMessage(), e); return Collections.emptyList(); } } /** override this method if you want to implement a custom allocatable marker */ protected Collection<Allocatable> getMarkedAllocatables() { List<Allocatable> selectedAllocatables = getSortedAllocatables(); if ( selectedAllocatables.size()== 1 ) { return Collections.singletonList(selectedAllocatables.get(0)); } return Collections.emptyList(); } protected void showPopupMenu(SwingRaplaBlock b,Point p) { Component component = b.getView(); AppointmentBlock appointmentBlock = b.getAppointmentBlock(); Appointment appointment = b.getAppointment(); Date start = b.getStart(); boolean isException = b.isException(); try { RaplaPopupMenu menu= new RaplaPopupMenu(); Allocatable groupAllocatable = b.getGroupAllocatable(); Collection<Allocatable> copyContextAllocatables; if (groupAllocatable != null) { copyContextAllocatables = Collections.singleton( groupAllocatable); } else { copyContextAllocatables = Collections.emptyList(); } addAppointmentAction( menu, component, p).setCopy(appointmentBlock,copyContextAllocatables); addAppointmentAction( menu, component, p ).setEdit(appointmentBlock); if ( !isException) { addAppointmentAction( menu, component, p).setDelete(appointmentBlock); } addAppointmentAction( menu, component, p).setView(appointmentBlock); Iterator<?> it = getContainer().lookupServicesFor( RaplaClientExtensionPoints.OBJECT_MENU_EXTENSION).iterator(); while (it.hasNext()) { ObjectMenuFactory objectMenuFact = (ObjectMenuFactory) it.next(); MenuContext menuContext = new MenuContext( getContext(), appointment); menuContext.put(SELECTED_DATE, start); RaplaMenuItem[] items = objectMenuFact.create( menuContext, appointment ); for ( int i =0;i<items.length;i++) { RaplaMenuItem item = items[i]; menu.add( item); } } menu.show(component,p.x,p.y); } catch (RaplaException ex) { showException(ex, calendarContainerComponent); } } public AppointmentAction addAppointmentAction(MenuInterface menu, Component parent, Point p) { AppointmentAction action = new AppointmentAction(getContext(),parent,p); menu.add(new JMenuItem(action)); return action; } }
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.plugin.abstractcalendar; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import org.rapla.components.calendarview.AbstractGroupStrategy; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.CalendarView; import org.rapla.entities.NamedComparator; import org.rapla.entities.domain.Allocatable; /** Tries to put reservations that allocate the same Resources in the same column.*/ public class GroupAllocatablesStrategy extends AbstractGroupStrategy { Comparator<Allocatable> allocatableComparator; Collection<Allocatable> allocatables = new ArrayList<Allocatable>(); public GroupAllocatablesStrategy(Locale locale) { allocatableComparator = new NamedComparator<Allocatable>( locale ); } public void setAllocatables( Collection<Allocatable> allocatables) { this.allocatables = allocatables; } @Override protected Map<Block, Integer> getBlockMap(CalendarView wv, List<Block> blocks) { return super.getBlockMap(wv, blocks); } protected Collection<List<Block>> group(List<Block> list) { HashMap<Allocatable,List<Block>> groups = new HashMap<Allocatable,List<Block>>(); for (Iterator<Allocatable> it = allocatables.iterator();it.hasNext(); ) { groups.put( it.next(), new ArrayList<Block>() ); } List<Block> noAllocatablesGroup = null; for (Iterator<Block> it = list.iterator();it.hasNext();) { AbstractRaplaBlock block = (AbstractRaplaBlock) it.next(); Allocatable allocatable = block.getContext().getGroupAllocatable(); if (allocatable == null) { if (noAllocatablesGroup == null) noAllocatablesGroup = new ArrayList<Block>(); noAllocatablesGroup.add(block); continue; } List<Block> col = groups.get( allocatable ); if (col == null) { col = new ArrayList<Block>(); groups.put( allocatable, col ); } col.add(block); } ArrayList<Allocatable> sortedAllocatables = new ArrayList<Allocatable>(groups.keySet()); Collections.sort(sortedAllocatables, allocatableComparator); ArrayList<List<Block>> sortedList = new ArrayList<List<Block>>(); for (Iterator<Allocatable> it = sortedAllocatables.iterator();it.hasNext();) { sortedList.add( groups.get(it.next()) ); } if (noAllocatablesGroup != null) sortedList.add(noAllocatablesGroup); return sortedList; } }
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.plugin.abstractcalendar; import java.util.Date; import java.util.LinkedHashSet; import java.util.List; import org.rapla.components.calendarview.Block; import org.rapla.components.util.DateTools; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.Named; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaLocale; import org.rapla.plugin.abstractcalendar.RaplaBuilder.BuildContext; public abstract class AbstractRaplaBlock implements Block { RaplaBuilder.RaplaBlockContext m_context; Date m_start; Date m_end; RaplaLocale m_raplaLocale; protected String timeStringSeperator = " -"; protected AbstractRaplaBlock() { } public void contextualize(RaplaBuilder.RaplaBlockContext context) { m_context = context; m_raplaLocale = getBuildContext().getRaplaLocale(); } public String getName(Named named) { return named.getName(m_raplaLocale.getLocale()); } public String getName() { return getReservation().getName( m_raplaLocale.getLocale()); } public Date getStart() { return m_start; } public Date getEnd() { return m_end; } protected I18nBundle getI18n() { return getBuildContext().getI18n(); } public void setStart(Date start) { m_start = start; } public void setEnd(Date end) { m_end = end; } public Appointment getAppointment() { return getContext().getAppointment(); } public Reservation getReservation() { return getAppointment().getReservation(); } public AppointmentBlock getAppointmentBlock() { return getContext().getAppointmentBlock(); } protected RaplaBuilder.RaplaBlockContext getContext() { return m_context; } public Allocatable getGroupAllocatable() { return getContext().getGroupAllocatable(); } public RaplaBuilder.BuildContext getBuildContext() { return getContext().getBuildContext(); } public boolean isMovable() { return getContext().isMovable() && !isException(); } public boolean startsAndEndsOnSameDay() { return DateTools.isSameDay( getAppointment().getStart().getTime() ,getAppointment().getEnd().getTime() -1 ) ; } protected String[] getColorsAsHex() { BuildContext buildContext = getBuildContext(); LinkedHashSet<String> colorList = new LinkedHashSet<String>(); if ( buildContext.isEventColoringEnabled()) { Reservation reservation = getReservation(); if (reservation != null) { String eventColor = RaplaBuilder.getColorForClassifiable( reservation ); if ( eventColor != null) { colorList.add( eventColor); } } } if ( buildContext.isResourceColoringEnabled()) { List<Allocatable> allocatables = getContext().getSelectedAllocatables(); for (Allocatable alloc:allocatables) { String lookupColorString = buildContext.lookupColorString(alloc); if ( lookupColorString != null) { colorList.add( lookupColorString); } } } if ( colorList.size() == 0) { colorList.add(buildContext.lookupColorString(null)); } return colorList.toArray(new String[] {}); } protected String getTimeString(boolean small) { RaplaLocale loc = getBuildContext().getRaplaLocale(); String timeString = null; if ( getBuildContext().isTimeVisible()) { timeString = ""; // Don't show startTime if its 00:00 /* TODO nicht sinnvoll auch 0:00 als Start und Endzeit anzuzeigen?*/ if ( !DateTools.isMidnight(getStart()) ) { timeString = loc.formatTime( getStart() ); } if ( !small && !DateTools.isMidnight(getEnd().getTime() + 1)) { timeString = timeString + timeStringSeperator; timeString = timeString + loc.formatTime( getEnd()); } } return timeString; } public boolean isException() { return getAppointment().getRepeating() != null && getAppointment().getRepeating().isException(getStart().getTime()); } public boolean isStartResizable() { return startsAndEndsOnSameDay() && !isException(); } public boolean isEndResizable() { return startsAndEndsOnSameDay() && !isException(); } }
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.abstractcalendar; import java.awt.Dimension; import java.awt.GridLayout; 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.Date; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.border.TitledBorder; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateChangeListener; import org.rapla.components.calendar.RaplaArrowButton; import org.rapla.components.calendar.RaplaCalendar; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.DateTools; import org.rapla.entities.domain.Period; import org.rapla.facade.CalendarModel; import org.rapla.facade.PeriodModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.internal.common.PeriodChooser; import org.rapla.gui.toolkit.RaplaButton; import org.rapla.gui.toolkit.RaplaWidget; public class IntervalChooserPanel extends RaplaGUIComponent implements RaplaWidget { Collection<DateChangeListener> listenerList = new ArrayList<DateChangeListener>(); PeriodChooser periodChooser; JPanel panel = new JPanel(); RaplaCalendar startDateSelection; RaplaCalendar endDateSelection; // BJO 00000042 JButton startTodayButton= new RaplaButton(getString("today"), RaplaButton.SMALL); JButton prevStartButton = new RaplaArrowButton('<', 20); JButton nextStartButton = new RaplaArrowButton('>', 20); { prevStartButton.setSize(30, 20); nextStartButton.setSize(30, 20); } JButton endTodayButton= new RaplaButton(getString("today"), RaplaButton.SMALL); JButton prevEndButton = new RaplaArrowButton('<', 20); JButton nextEndButton = new RaplaArrowButton('>', 20); { prevEndButton.setSize(30, 20); nextEndButton.setSize(30, 20); } int incrementSize = Calendar.WEEK_OF_YEAR; // BJO00000042 boolean listenersEnabled = true; CalendarModel model; Listener listener = new Listener(); JPanel periodPanel; public IntervalChooserPanel(RaplaContext sm, CalendarModel model) throws RaplaException { super(sm); this.model = model; periodChooser = new PeriodChooser(getContext(),PeriodChooser.START_AND_END); periodChooser.setWeekOfPeriodVisible( false ); startDateSelection = createRaplaCalendar(); endDateSelection = createRaplaCalendar(); //prevButton.setText("<"); //nextButton.setText(">"); double pre =TableLayout.PREFERRED; double[][] sizes = {{5,pre, 5, pre, 5,0.9,0.02} ,{pre}}; TableLayout tableLayout = new TableLayout(sizes); int todayWidth = (int)Math.max(40, startTodayButton.getPreferredSize().getWidth()); startTodayButton.setPreferredSize( new Dimension(todayWidth,20)); endTodayButton.setPreferredSize( new Dimension(todayWidth,20)); panel.setLayout(tableLayout); JPanel startPanel = new JPanel(); TitledBorder titleBorder = BorderFactory.createTitledBorder(getString("start_date")); startPanel.setBorder(titleBorder); startPanel.add(startDateSelection); // BJO 00000042 startPanel.add(startTodayButton); startPanel.add(prevStartButton); startPanel.add(nextStartButton); startTodayButton.addActionListener( listener ); prevStartButton.addActionListener( listener ); nextStartButton.addActionListener( listener ); // BJO 00000042 panel.add(startPanel,"1,0"); JPanel endPanel = new JPanel(); titleBorder = BorderFactory.createTitledBorder(getString("end_date")); endPanel.setBorder(titleBorder); endPanel.add(endDateSelection); // BJO 00000042 endPanel.add(endTodayButton); endPanel.add(prevEndButton); endPanel.add(nextEndButton); endTodayButton.addActionListener( listener ); prevEndButton.addActionListener( listener ); nextEndButton.addActionListener( listener ); // BJO 00000042 panel.add(endPanel,"3,0"); periodPanel = new JPanel(new GridLayout(1,1)); titleBorder = BorderFactory.createTitledBorder(getString("period")); periodPanel.setBorder(titleBorder); periodPanel.add(periodChooser); panel.add( periodPanel,"5,0"); periodChooser.addActionListener( listener ); startDateSelection.addDateChangeListener( listener ); endDateSelection.addDateChangeListener( listener ); update(); } public void update() { listenersEnabled = false; try { Date startDate = model.getStartDate(); startDateSelection.setDate( startDate); final PeriodModel periodModel = getPeriodModel(); periodChooser.setPeriodModel( periodModel); periodChooser.setDate( startDate ); Date endDate = model.getEndDate(); periodPanel.setVisible( periodModel.getSize() > 0); endDateSelection.setDate( DateTools.subDay(endDate)); } finally { listenersEnabled = true; } } // BJO00000042 /** possible values are Calendar.DATE, Calendar.WEEK_OF_YEAR, Calendar.MONTH and Calendar.YEAR. Default is Calendar.WEEK_OF_YEAR. */ public void setIncrementSize(int incrementSize) { this.incrementSize = incrementSize; } // BJO00000042 /** registers new DateChangeListener for this component. * An DateChangeEvent will be fired to every registered DateChangeListener * when the a different date is selected. * @see DateChangeListener * @see DateChangeEvent */ public void addDateChangeListener(DateChangeListener listener) { listenerList.add(listener); } /** removes a listener from this component.*/ public void removeDateChangeListener(DateChangeListener listener) { listenerList.remove(listener); } public DateChangeListener[] getDateChangeListeners() { return listenerList.toArray(new DateChangeListener[]{}); } /** An ActionEvent will be fired to every registered ActionListener * when a different date is selected. */ protected void fireDateChange(Date date) { if (listenerList.size() == 0) return; DateChangeListener[] listeners = getDateChangeListeners(); DateChangeEvent evt = new DateChangeEvent(this,date); for (int i = 0;i<listeners.length;i++) { listeners[i].dateChanged(evt); } } public JComponent getComponent() { return panel; } class Listener implements DateChangeListener, ActionListener { public void actionPerformed( ActionEvent e ) { if ( !listenersEnabled ) return; // BJO 00000042 Date date; Calendar calendar = getRaplaLocale().createCalendar(); if (e.getSource() == prevStartButton) { calendar.setTime(startDateSelection.getDate()); calendar.add(incrementSize,-1); date = calendar.getTime(); startDateSelection.setDate(date); } else if (e.getSource() == nextStartButton) { calendar.setTime(startDateSelection.getDate()); calendar.add(incrementSize,1); date = calendar.getTime(); startDateSelection.setDate(date); } else if (e.getSource() == prevEndButton) { calendar.setTime(endDateSelection.getDate()); calendar.add(incrementSize,-1); date = calendar.getTime(); endDateSelection.setDate(date); } else if (e.getSource() == nextEndButton) { calendar.setTime(endDateSelection.getDate()); calendar.add(incrementSize,1); date = calendar.getTime(); endDateSelection.setDate(date); } else if (e.getSource() == startTodayButton) { calendar.setTime(new Date()); date = calendar.getTime(); startDateSelection.setDate(date); } else if (e.getSource() == endTodayButton) { calendar.setTime(new Date()); date = calendar.getTime(); endDateSelection.setDate(date); } // BJO 00000042 Period period = periodChooser.getPeriod(); if ( period == null) { return; } updateDates( period.getStart(), period.getEnd()); fireDateChange( period.getStart()); } public void dateChanged(DateChangeEvent evt) { if ( !listenersEnabled ) return; if ( evt.getSource() == startDateSelection) { Date newStartDate = startDateSelection.getDate(); if (newStartDate.after( endDateSelection.getDate())) { Date endDate = DateTools.addDays(newStartDate, 1); endDateSelection.setDate( endDate); } } if ( evt.getSource() == endDateSelection) { Date newEndDate = endDateSelection.getDate(); if (newEndDate.before( startDateSelection.getDate())) { Date startDate = DateTools.addDays(newEndDate, -1); startDateSelection.setDate( startDate); } } updateDates( startDateSelection.getDate(), DateTools.addDay(endDateSelection.getDate())); fireDateChange(evt.getDate()); } private void updateDates(Date start, Date end) { try { listenersEnabled = false; model.setStartDate( start); model.setEndDate( end ); model.setSelectedDate( start ); // start startDateSelection.setDate( start); endDateSelection.setDate( end ); } finally { listenersEnabled = true; } } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.abstractcalendar.server; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.servletpages.RaplaPageGenerator; public interface HTMLViewFactory { public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) throws RaplaException; public String getViewId(); }
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.abstractcalendar.server; import java.util.Calendar; import java.util.Date; import org.rapla.components.calendarview.Block; import org.rapla.entities.User; import org.rapla.entities.domain.Appointment; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.RaplaBuilder; public class HTMLRaplaBuilder extends RaplaBuilder { static String COLOR_NO_RESOURCE = "#BBEEBB"; int m_rowsPerHour = 4; /** shared calendar instance. Only used for temporary stored values. */ String m_html; int index = 0; protected boolean onlyAllocationInfo; public HTMLRaplaBuilder(RaplaContext sm) { super(sm); } @Override public void setFromModel(CalendarModel model, Date startDate, Date endDate) throws RaplaException { super.setFromModel(model, startDate, endDate); { String option = model.getOption(CalendarModel.ONLY_ALLOCATION_INFO); if (option != null && option.equalsIgnoreCase("true")) { onlyAllocationInfo = true; } } } @Override protected boolean isAnonymous(User user, Appointment appointment) { if ( onlyAllocationInfo) { return true; } return super.isAnonymous(user, appointment); } @Override protected boolean isExceptionsExcluded() { return true; } @Override protected Block createBlock(RaplaBlockContext blockContext, Date start, Date end) { HTMLRaplaBlock block = createBlock(); block.setIndex( index ++ ); block.setStart(start); block.setEnd(end); block.contextualize(blockContext); Calendar calendar = getRaplaLocale().createCalendar(); calendar.setTime(start); int row = (int) ( calendar.get(Calendar.HOUR_OF_DAY)* m_rowsPerHour + Math.round((calendar.get(Calendar.MINUTE) * m_rowsPerHour)/60.0) ); block.setRow(row); block.setDay(calendar.get(Calendar.DAY_OF_WEEK)); calendar.setTime(block.getEnd()); int endRow = (int) ( calendar.get(Calendar.HOUR_OF_DAY)* m_rowsPerHour + Math.round((calendar.get(Calendar.MINUTE) * m_rowsPerHour)/60.0) ); int rowCount = endRow -row; block.setRowCount(rowCount); //System.out.println("Start " + start + " End " + end); //System.out.println("Block " + block.getReservation().getName(null) // + " Row: " + row + " Endrow: " + endRow + " Rowcount " + rowCount ); return block; } protected HTMLRaplaBlock createBlock() { HTMLRaplaBlock block = new HTMLRaplaBlock(); return block; } }
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.abstractcalendar.server; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import org.rapla.components.calendarview.html.HTMLBlock; import org.rapla.components.util.xml.XMLWriter; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.Attribute; import org.rapla.gui.internal.view.AppointmentInfoUI; import org.rapla.plugin.abstractcalendar.AbstractRaplaBlock; public class HTMLRaplaBlock extends AbstractRaplaBlock implements HTMLBlock { private int m_day; private int m_row; private int m_rowCount; private int index = 0; { timeStringSeperator ="&#160;-"; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public void setRowCount(int rows) { m_rowCount = rows; } public void setRow(int row) { m_row = row; } public int getRowCount() { return m_rowCount; } public int getRow() { return m_row; } public void setDay(int day) { m_day = day; } public int getDay() { return m_day; } public String getBackgroundColor() { return getColorsAsHex()[0]; } public String toString() { StringBuffer buf = new StringBuffer(); String label = XMLWriter.encode(getName( getReservation())); String timeString = getTimeString(false); if ( getContext().isAnonymous()) { String anonymous = "&#160;&#160;&#160;&#160;???"; if ( timeString != null) { return timeString + " " + anonymous; } else { return anonymous; } } if ( timeString != null) { List<Allocatable> resources = getContext().getAllocatables(); StringBuffer buffer = new StringBuffer() ; for (Allocatable resource: resources) { if ( getContext().isVisible( resource) && !resource.isPerson()) { if ( buffer.length() > 0) { buffer.append(", "); } buffer.append(XMLWriter.encode( getName(resource))); } } if ( !getBuildContext().isResourceVisible() && buffer.length() > 0) { timeString = timeString + " " + buffer.toString(); } label = timeString + "<br/>" + label; } AppointmentInfoUI reservationInfo = new AppointmentInfoUI(getContext().getBuildContext().getServiceManager()); URL url = null; Attribute[] attributes = getReservation().getClassification().getAttributes(); for ( int i=0;i<attributes.length;i++) { String value = getReservation().getClassification().getValueAsString( attributes[i],getBuildContext().getRaplaLocale().getLocale()); if ( value == null) continue; try{ int httpEnd = Math.max( value.indexOf(" ")-1, value.length()); url = new URL( value.substring(0,httpEnd)); break; } catch (MalformedURLException ex) { } } buf.append( "<a href=\""); if ( url != null) { buf.append( url ); } else { buf.append( "#" + index ); } buf.append( "\">" ); if ( url != null) { buf.append( "<span class=\"link\">"); } buf.append( label ); if ( url != null) { buf.append( "</span>"); } if (getBuildContext().isShowToolTips()) { buf.append( "<span class=\"tooltip\">"); buf.append(reservationInfo.getTooltip(getAppointment())); buf.append( "</span>"); } buf.append( "</a>" ); if (getBuildContext().isPersonVisible()) { List<Allocatable> persons = getContext().getAllocatables(); for ( Allocatable person:persons) { if ( !getContext().isVisible( person) || !person.isPerson()) continue; buf.append("<br>"); buf.append("<span class=\"person\">"); buf.append(XMLWriter.encode(getName(person))); buf.append("</span>"); } } else { List<Allocatable> persons = getContext().getAllocatables(); if ( persons.size() > 0) { buf.append("<br>"); buf.append("<span class=\"person\">"); boolean first = true; for ( Allocatable person:persons) { if ( !getContext().isVisible( person) || !person.isPerson()) continue; if ( !first) { buf.append(", "); } else { first = false; } buf.append( XMLWriter.encode(getName( person ))); } buf.append("</span>"); } } if (getBuildContext().isResourceVisible()) { Allocatable[] resources = getReservation().getResources(); for (int i=0; i<resources.length;i ++) { if (!getContext().isVisible(resources[i])) continue; buf.append("<br>"); buf.append("<span class=\"resource\">"); buf.append(XMLWriter.encode(getName(resources[i]))); buf.append("</span>"); } } return buf.toString(); } }
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.abstractcalendar.server; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.rapla.components.calendarview.html.AbstractHTMLView; import org.rapla.components.util.ParseDateException; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.entities.NamedComparator; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarOptions; 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.servletpages.RaplaPageGenerator; public abstract class AbstractHTMLCalendarPage extends RaplaComponent implements RaplaPageGenerator { protected AbstractHTMLView view; protected String calendarviewHTML; protected CalendarModel model = null; RaplaBuilder builder; public AbstractHTMLCalendarPage(RaplaContext context, CalendarModel calendarModel) { super( context); this.model = calendarModel.clone(); } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = new HTMLRaplaBuilder( getContext()); Date startDate = view.getStartDate(); Date endDate = view.getEndDate(); builder.setFromModel( model, startDate, endDate ); builder.setNonFilteredEventsVisible( false); return builder; } abstract protected AbstractHTMLView createCalendarView(); abstract protected int getIncrementSize(); public List<Allocatable> getSortedAllocatables() throws RaplaException { Allocatable[] selectedAllocatables = model.getSelectedAllocatables(); List<Allocatable> sortedAllocatables = new ArrayList<Allocatable>( Arrays.asList( selectedAllocatables)); Collections.sort(sortedAllocatables, new NamedComparator<Allocatable>( getLocale() )); return sortedAllocatables; } public String getCalendarHTML() { return calendarviewHTML; } public String getDateChooserHTML( Date date) { Calendar calendar = getRaplaLocale().createCalendar(); calendar.setTime( date ); return HTMLDateComponents.getDateSelection( "", calendar,getLocale()); } public Date getStartDate() { return view.getStartDate(); } public Date getEndDate() { return view.getEndDate(); } public String getTitle() { return model.getNonEmptyTitle(); } public int getDay( Date date) { Calendar calendarview = getRaplaLocale().createCalendar(); calendarview.setTime( date); return calendarview.get( Calendar.DATE); } public int getMonth( Date date) { Calendar calendarview = getRaplaLocale().createCalendar(); calendarview.setTime( date); return calendarview.get( Calendar.MONTH) + 1; } public int getYear( Date date) { Calendar calendarview = getRaplaLocale().createCalendar(); calendarview.setTime( date); return calendarview.get( Calendar.YEAR); } abstract protected void configureView() throws RaplaException; public void generatePage( ServletContext context,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=" + getRaplaLocale().getCharsetNonUtf() ); java.io.PrintWriter out = response.getWriter(); Calendar calendarview = getRaplaLocale().createCalendar(); calendarview.setTime( model.getSelectedDate() ); if ( request.getParameter("today") != null ) { Date today = getQuery().today(); calendarview.setTime( today ); } else if ( request.getParameter("day") != null ) { String dateString = request.getParameter("year") + "-" + request.getParameter("month") + "-" + request.getParameter("day"); try { SerializableDateTimeFormat format = getRaplaLocale().getSerializableFormat(); calendarview.setTime( format.parseDate( dateString, false ) ); } catch (ParseDateException ex) { out.close(); throw new ServletException( ex); } if ( request.getParameter("next") != null) calendarview.add( getIncrementSize(), 1); if ( request.getParameter("prev") != null) calendarview.add( getIncrementSize(), -1); } Date currentDate = calendarview.getTime(); model.setSelectedDate( currentDate ); view = createCalendarView(); try { configureView(); } catch (RaplaException ex) { getLogger().error("Can't configure view ", ex); throw new ServletException( ex ); } view.setLocale( getRaplaLocale().getLocale() ); view.setTimeZone(getRaplaLocale().getTimeZone()); view.setToDate(model.getSelectedDate()); model.setStartDate( view.getStartDate() ); model.setEndDate( view.getEndDate() ); try { builder = createBuilder(); } catch (RaplaException ex) { getLogger().error("Can't create builder ", ex); out.close(); throw new ServletException( ex ); } view.rebuild( builder); printPage(request, out, calendarview); } /** * @throws ServletException * @throws UnsupportedEncodingException */ protected void printPage(HttpServletRequest request, java.io.PrintWriter out, Calendar currentDate) throws ServletException, UnsupportedEncodingException { boolean navigationVisible = isNavigationVisible( request ); String linkPrefix = request.getPathTranslated() != null ? "../": ""; RaplaLocale raplaLocale= getRaplaLocale(); calendarviewHTML = view.getHtml(); out.println("<!DOCTYPE html>"); // we have HTML5 out.println("<html>"); out.println("<head>"); out.println(" <title>" + getTitle() + "</title>"); out.println(" <link REL=\"stylesheet\" href=\""+linkPrefix + "calendar.css\" type=\"text/css\">"); out.println(" <link REL=\"stylesheet\" href=\"" + linkPrefix + "default.css\" type=\"text/css\">"); // tell the html page where its favourite icon is stored out.println(" <link REL=\"shortcut icon\" type=\"image/x-icon\" href=\""+linkPrefix + "images/favicon.ico\">"); out.println(" <meta HTTP-EQUIV=\"Content-Type\" content=\"text/html; charset=" + raplaLocale.getCharsetNonUtf() + "\">"); out.println("</head>"); out.println("<body>"); if (request.getParameter("selected_allocatables") != null && request.getParameter("allocatable_id")==null) { try { Allocatable[] selectedAllocatables = model.getSelectedAllocatables(); printAllocatableList(request, out, getLocale(), selectedAllocatables); } catch (RaplaException e) { throw new ServletException(e); } } else { String allocatable_id = request.getParameter("allocatable_id"); // Start DateChooser if (navigationVisible) { out.println("<div class=\"datechooser\">"); out.println("<form action=\""+linkPrefix + "rapla\" method=\"get\">"); String keyParamter = request.getParameter("key"); if (keyParamter != null) { out.println(getHiddenField("key", keyParamter)); } else { out.println(getHiddenField("page", "calendar")); out.println(getHiddenField("user", model.getUser().getUsername())); String filename = getFilename( request ); if ( filename != null) { out.println(getHiddenField("file", filename)); } } if ( allocatable_id != null) { out.println(getHiddenField("allocatable_id", allocatable_id)); } // add the "previous" button including the css class="super button" out.println("<span class=\"button\"><input type=\"submit\" name=\"prev\" value=\"&lt;&lt;\"/></span> "); out.println("<span class=\"spacer\">&nbsp;</span> "); out.println(getDateChooserHTML(currentDate.getTime())); // add the "goto" button including the css class="super button" out.println("<span class=\"button\"><input type=\"submit\" name=\"goto\" value=\"" + getString("goto_date") + "\"/></span>"); out.println("<span class=\"spacer\">&nbsp;</span>"); out.println("<span class=\"spacer\">&nbsp;</span>"); // add the "today" button including the css class="super button" out.println("<span class=\"button\"><input type=\"submit\" name=\"today\" value=\"" + getString("today") + "\"/></span>"); out.println("<span class=\"spacer\">&nbsp;</span>"); // add the "next" button including the css class="super button" out.println("<span class=\"button\"><input type=\"submit\" name=\"next\" value=\"&gt;&gt;\"/></span>"); out.println("</form>"); out.println("</div>"); } // End DateChooser // Start weekview out.println("<h2 class=\"title\">"); out.println(getTitle()); out.println("</h2>"); out.println("<div id=\"calendar\">"); out.println(getCalendarHTML()); out.println("</div>"); // end weekview } out.println("</body>"); out.println("</html>"); } static public void printAllocatableList(HttpServletRequest request, java.io.PrintWriter out, Locale locale, Allocatable[] selectedAllocatables) throws UnsupportedEncodingException { out.println("<table>"); String base = request.getRequestURL().toString(); String queryPath = request.getQueryString(); queryPath = queryPath.replaceAll("&selected_allocatables[^&]*",""); List<Allocatable> sortedAllocatables = new ArrayList<Allocatable>(Arrays.asList(selectedAllocatables)); Collections.sort( sortedAllocatables, new NamedComparator<Allocatable>(locale) ); for (Allocatable alloc:sortedAllocatables) { out.print("<tr>"); out.print("<td>"); String name = alloc.getName(locale); out.print(name); out.print("</a>"); out.print("</td>"); out.print("<td>"); String link = base + "?" + queryPath + "&allocatable_id=" + URLEncoder.encode(alloc.getId(),"UTF-8"); out.print("<a href=\""+ link+ "\">"); out.print(link); out.print("</a>"); out.print("</td>"); out.print("</tr>"); } out.println("</table>"); } public String getFilename(HttpServletRequest request) { return request.getParameter("file"); } public boolean isNavigationVisible( HttpServletRequest request) { String config = model.getOption( CalendarModel.SHOW_NAVIGATION_ENTRY ); if ( config == null || config.equals( "true" )) { return true; } return !config.equals( "false" ) && request.getParameter("hide_nav") == null; } String getHiddenField( String fieldname, String value) { return "<input type=\"hidden\" name=\"" + fieldname + "\" value=\"" + value + "\"/>"; } String getHiddenField( String fieldname, int value) { return getHiddenField( fieldname, String.valueOf(value)); } /* public String getLegend() { if ( !getCalendarOptions().isResourceColoring()) { return ""; } Iterator it = view.getBlocks().iterator(); LinkedList coloredAllocatables = new LinkedList(); while (it.hasNext()) { List list = ((HTMLRaplaBlock)it.next()).getContext().getColoredAllocatables(); for (int i=0;i<list.size();i++) { Object obj = list.get(i); if (!coloredAllocatables.contains(obj)) coloredAllocatables.add(obj); } } if (coloredAllocatables.size() < 1) { return ""; } StringBuffer buf = new StringBuffer(); it = coloredAllocatables.iterator(); buf.append("<table>\n"); buf.append("<tr>\n"); buf.append("<td>"); buf.append( getI18n().getString("legend")); buf.append(":"); buf.append("</td>"); try { AllocatableInfoUI allocatableInfo = new AllocatableInfoUI(getContext()); while (it.hasNext()) { Allocatable allocatable = (Allocatable) it.next(); String color = (String) builder.getColorMap().get(allocatable); if (color == null) // (!color_map.containsKey(allocatable)) continue; buf.append("<td style=\"background-color:"); buf.append( color ); buf.append("\">"); buf.append("<a href=\"#\">"); buf.append( allocatable.getName(getRaplaLocale().getLocale()) ); buf.append("<span>"); buf.append( allocatableInfo.getTooltip( allocatable)); buf.append("</span>"); buf.append("</a>"); buf.append("</td>"); } } catch (RaplaException ex) { getLogger().error( "Error generating legend",ex); } buf.append("</tr>\n"); buf.append("</table>"); return buf.toString(); } */ public CalendarOptions getCalendarOptions() { User user = model.getUser(); return getCalendarOptions(user); } }
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.abstractcalendar.server; import java.util.Calendar; import java.util.Locale; public class HTMLDateComponents { static public String getDateSelection(String prefix,Calendar calendarview, Locale locale) { StringBuffer buf = new StringBuffer(); int day = calendarview.get(Calendar.DATE); int month = calendarview.get(Calendar.MONTH) +1; int year = calendarview.get(Calendar.YEAR); int minYear = 2003; int maxYear = 2020; buf.append( getDaySelection(prefix + "day",day)); buf.append( getMonthSelection(prefix + "month",month, locale)); buf.append( getYearSelection(prefix + "year", year,minYear, maxYear)); return buf.toString(); } static public String getDaySelection(String name, int selectedValue) { StringBuffer buf = new StringBuffer(); buf.append("<select name=\""); buf.append( name ); buf.append("\">\n"); for (int i=1;i<=31;i++) { buf.append("<option "); if ( i == selectedValue) { buf.append("selected"); } buf.append(">"); buf.append(i); buf.append("</option>"); buf.append("\n"); } buf.append("</select>"); return buf.toString(); } static public String getMonthSelection(String name, int selectedValue, Locale locale) { StringBuffer buf = new StringBuffer(); buf.append("<select name=\""); buf.append( name ); buf.append("\">\n"); Calendar calendar = Calendar.getInstance( locale ); java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("MMMMM", locale); calendar.set(Calendar.MONTH,Calendar.JANUARY); for (int i=1;i<=12;i++) { buf.append("<option "); buf.append("value=\""); buf.append(i); buf.append("\" "); if ( i == selectedValue ) { buf.append("selected"); } buf.append(">"); buf.append(format.format(calendar.getTime())); calendar.add(Calendar.MONTH,1); buf.append("</option>"); buf.append("\n"); } buf.append("</select>"); return buf.toString(); } static public String getYearSelection(String name, int selectedValue, int minYear, int maxYear) { StringBuffer buf = new StringBuffer(); buf.append("<select name=\""); buf.append( name ); buf.append("\">\n"); for (int i=minYear;i<=maxYear;i++) { buf.append("<option "); if ( i == selectedValue ) { buf.append("selected"); } buf.append(">"); buf.append(i); buf.append("</option>"); } buf.append("</select>"); return buf.toString(); } }
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.abstractcalendar; import java.awt.Dimension; import java.awt.GridLayout; 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.Date; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.border.TitledBorder; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateChangeListener; import org.rapla.components.calendar.RaplaArrowButton; import org.rapla.components.calendar.RaplaCalendar; import org.rapla.components.layout.TableLayout; import org.rapla.entities.domain.Period; import org.rapla.facade.CalendarModel; import org.rapla.facade.PeriodModel; import org.rapla.facade.QueryModule; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.internal.common.PeriodChooser; import org.rapla.gui.toolkit.RaplaButton; import org.rapla.gui.toolkit.RaplaWidget; public class DateChooserPanel extends RaplaGUIComponent implements Disposable ,RaplaWidget { Collection<DateChangeListener> listenerList = new ArrayList<DateChangeListener>(); JPanel panel = new JPanel(); JButton prevButton = new RaplaArrowButton('<', 20); RaplaCalendar dateSelection; PeriodChooser periodChooser; JButton nextButton = new RaplaArrowButton('>', 20); int incrementSize = Calendar.WEEK_OF_YEAR; CalendarModel model; Listener listener = new Listener(); JPanel periodPanel; JButton todayButton= new RaplaButton(getString("today"), RaplaButton.SMALL); public DateChooserPanel(RaplaContext sm, CalendarModel model) throws RaplaException { super( sm ); this.model = model; prevButton.setSize(30, 20); nextButton.setSize(30, 20); periodChooser = new PeriodChooser(getContext(),PeriodChooser.START_ONLY); dateSelection = createRaplaCalendar(); //prevButton.setText("<"); //nextButton.setText(">"); double pre =TableLayout.PREFERRED; double[][] sizes = {{5,pre,5,pre,2,pre,0.02,0.9,5,0.02} ,{/*0.5,*/pre/*,0.5*/}}; TableLayout tableLayout = new TableLayout(sizes); JPanel calendarPanel = new JPanel(); TitledBorder titleBorder = BorderFactory.createTitledBorder(getI18n().getString("date")); calendarPanel.setBorder(titleBorder); panel.setLayout(tableLayout); calendarPanel.add(dateSelection); calendarPanel.add(todayButton); int todayWidth = (int)Math.max(40, todayButton.getPreferredSize().getWidth()); todayButton.setPreferredSize( new Dimension(todayWidth,20)); calendarPanel.add(prevButton); calendarPanel.add(nextButton); panel.add(calendarPanel, "1, 0"); periodPanel = new JPanel(new GridLayout(1,1)); titleBorder = BorderFactory.createTitledBorder(getI18n().getString("period")); periodPanel.setBorder(titleBorder); periodPanel.add(periodChooser); panel.add(periodPanel,"7,0"); periodChooser.setDate(getQuery().today()); nextButton.addActionListener( listener ); prevButton.addActionListener( listener); dateSelection.addDateChangeListener( listener); periodChooser.addActionListener( listener); todayButton.addActionListener(listener); update(); } boolean listenersEnabled = true; public void update() { listenersEnabled = false; try { final PeriodModel periodModel = getPeriodModel(); periodChooser.setPeriodModel( periodModel); if ( model.getSelectedDate() == null) { QueryModule query = getQuery(); Date today = query.today(); model.setSelectedDate( today); } Date date = model.getSelectedDate(); periodChooser.setDate( date); dateSelection.setDate( date); periodPanel.setVisible( periodModel.getSize() > 0); } finally { listenersEnabled = true; } } public void dispose() { periodChooser.removeActionListener( listener ); periodChooser.dispose(); } public void setNavigationVisible( boolean enable) { nextButton.setVisible( enable); prevButton.setVisible( enable); } /** possible values are Calendar.DATE, Calendar.WEEK_OF_YEAR, Calendar.MONTH and Calendar.YEAR. Default is Calendar.WEEK_OF_YEAR. */ public void setIncrementSize(int incrementSize) { this.incrementSize = incrementSize; } /** registers new DateChangeListener for this component. * An DateChangeEvent will be fired to every registered DateChangeListener * when the a different date is selected. * @see DateChangeListener * @see DateChangeEvent */ public void addDateChangeListener(DateChangeListener listener) { listenerList.add(listener); } /** removes a listener from this component.*/ public void removeDateChangeListener(DateChangeListener listener) { listenerList.remove(listener); } public DateChangeListener[] getDateChangeListeners() { return listenerList.toArray(new DateChangeListener[]{}); } /** An ActionEvent will be fired to every registered ActionListener * when the a different date is selected. */ protected void fireDateChange(Date date) { if (listenerList.size() == 0) return; DateChangeListener[] listeners = getDateChangeListeners(); DateChangeEvent evt = new DateChangeEvent(this,date); for (int i = 0;i<listeners.length;i++) { listeners[i].dateChanged(evt); } } public JComponent getComponent() { return panel; } class Listener implements ActionListener, DateChangeListener { public void actionPerformed(ActionEvent evt) { if (!listenersEnabled) return; Date date; Calendar calendar = getRaplaLocale().createCalendar(); Date date2 = dateSelection.getDate(); calendar.setTime(date2); if (evt.getSource() == prevButton) { calendar.add(incrementSize,-1); } //eingefuegt: rku if (evt.getSource() == todayButton) { Date today = getQuery().today(); calendar.setTime(today); } if (evt.getSource() == nextButton) { calendar.add(incrementSize,1); } if (evt.getSource() == periodChooser) { date = periodChooser.getDate(); Period period = periodChooser.getPeriod(); model.setStartDate( period.getStart() ); model.setEndDate( period.getEnd() ); } else { date = calendar.getTime(); } updateDates( date ); fireDateChange( date); } public void dateChanged(DateChangeEvent evt) { if ( !listenersEnabled) return; try { listenersEnabled = false; } finally { listenersEnabled = true; } Date date = evt.getDate(); updateDates( date); fireDateChange(date); } private void updateDates(Date date) { try { listenersEnabled = false; model.setSelectedDate( date ); // EXCO: It seems not nice to me that the start date // is in the parameter and the end date is extracted // from the model. // But, with this way, I am certain that // nothing can get broken. Date endDate = model.getEndDate(); periodChooser.setDate( date, endDate ); dateSelection.setDate( date); } finally { listenersEnabled = true; } } } }
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). | *--------------------------------------------------------------------------*/ /** rapla-specific implementation of builder. * Splits the appointments into day-blocks. */ package org.rapla.plugin.abstractcalendar; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; 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.components.calendarview.Block; import org.rapla.components.calendarview.BuildStrategy; import org.rapla.components.calendarview.Builder; import org.rapla.components.calendarview.CalendarView; import org.rapla.components.util.Assert; import org.rapla.components.util.DateTools; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.Category; import org.rapla.entities.CategoryAnnotations; import org.rapla.entities.NamedComparator; 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.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarOptions; import org.rapla.facade.Conflict; import org.rapla.facade.Conflict.Util; import org.rapla.facade.RaplaComponent; import org.rapla.facade.internal.CalendarModelImpl; import org.rapla.facade.internal.ConflictImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.framework.TypedComponentRole; import org.rapla.framework.logger.Logger; import org.rapla.gui.toolkit.RaplaColors; public abstract class RaplaBuilder extends RaplaComponent implements Builder ,Cloneable { private Collection<Reservation> selectedReservations; private List<Allocatable> selectedAllocatables = new ArrayList<Allocatable>(); private boolean enabled= true; private boolean bExceptionsExcluded = false; private boolean bResourceVisible = true; private boolean bPersonVisible = true; private boolean bRepeatingVisible = true; private boolean bTimeVisible = true; //Shows time <from - till> in top of all HTML- and Swing-View Blocks private boolean splitByAllocatables = false; private HashMap<Allocatable,String> colors = new HashMap<Allocatable,String>(); //This currently only works with HashMap private User editingUser; private boolean isResourceColoring; private boolean isEventColoring; private boolean nonFilteredEventsVisible; /** default buildStrategy is {@link GroupAllocatablesStrategy}.*/ BuildStrategy buildStrategy; HashSet<Reservation> allReservationsForAllocatables = new HashSet<Reservation>(); int max =0; int min =0; List<AppointmentBlock> preparedBlocks = null; public static final TypedComponentRole<Boolean> SHOW_TOOLTIP_CONFIG_ENTRY = new TypedComponentRole<Boolean>("org.rapla.showTooltips"); Map<Appointment,Set<Appointment>> conflictingAppointments; public RaplaBuilder(RaplaContext sm) { super(sm); buildStrategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ); } public void setFromModel(CalendarModel model, Date startDate, Date endDate) throws RaplaException { Collection<Conflict> conflictsSelected = new ArrayList<Conflict>(); conflictingAppointments = null; conflictsSelected.clear(); conflictsSelected.addAll( ((CalendarModelImpl)model).getSelectedConflicts()); Collection<Allocatable> allocatables ; List<Reservation> filteredReservations; if ( !conflictsSelected.isEmpty() ) { allocatables = Util.getAllocatables( conflictsSelected ); } else { allocatables = Arrays.asList( model.getSelectedAllocatables()); } if ( startDate != null && !allocatables.isEmpty()) { List<Reservation> reservationsForAllocatables = Arrays.asList(getQuery().getReservations( allocatables.toArray(Allocatable.ALLOCATABLE_ARRAY), startDate, endDate)); allReservationsForAllocatables.addAll( reservationsForAllocatables); } if ( !conflictsSelected.isEmpty() ) { filteredReservations = getQuery().getReservations( conflictsSelected); conflictingAppointments = ConflictImpl.getMap( conflictsSelected, filteredReservations); } else { if ( allocatables.isEmpty() || startDate == null) { filteredReservations = Arrays.asList( model.getReservations( startDate, endDate )); } else { filteredReservations = ((CalendarModelImpl)model).restrictReservations( allReservationsForAllocatables); } } User user = model.getUser(); CalendarOptions calendarOptions = getCalendarOptions( user); nonFilteredEventsVisible = calendarOptions.isNonFilteredEventsVisible(); isResourceColoring =calendarOptions.isResourceColoring(); isEventColoring =calendarOptions.isEventColoring(); Collection<Reservation> reservations = new HashSet<Reservation>(filteredReservations); selectReservations( reservations ); setEditingUser( user); setExceptionsExcluded( !calendarOptions.isExceptionsVisible()); /* Uncomment this to color allocatables in the reservation view if ( allocatables.size() == 0) { allocatables = new ArrayList(); for (int i=0;i< reservations.size();i++) { Reservation r = (Reservation) reservations.get( i ); Allocatable[] a = r.getAllocatables(); for (int j=0;j<a.length;j++) { if ( !allocatables.contains( a[j] )) { allocatables.add( a[j]); } } } }*/ selectAllocatables( allocatables ); } public boolean isNonFilteredEventsVisible() { return nonFilteredEventsVisible; } public void setNonFilteredEventsVisible(boolean nonFilteredEventsVisible) { this.nonFilteredEventsVisible = nonFilteredEventsVisible; } public void setSmallBlocks( boolean isSmallView) { setTimeVisible( isSmallView ); setPersonVisible( !isSmallView ); setResourceVisible( !isSmallView ); } public void setSplitByAllocatables( boolean enable) { splitByAllocatables = enable; } public void setExceptionsExcluded( boolean exclude) { this.bExceptionsExcluded = exclude; } protected boolean isExceptionsExcluded() { return bExceptionsExcluded; } public void setEditingUser(User editingUser) { this.editingUser = editingUser; } public User getEditingUser() { return this.editingUser; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enable) { this.enabled = enable; } public void setBuildStrategy(BuildStrategy strategy) { this.buildStrategy = strategy; } public void setTimeVisible(boolean bTimeVisible) { this.bTimeVisible = bTimeVisible; } public boolean isTimeVisible() { return bTimeVisible; } private void setResourceVisible(boolean bVisible) { this.bResourceVisible = bVisible; } private void setPersonVisible(boolean bVisible) { this.bPersonVisible = bVisible; } public void setRepeatingVisible(boolean bVisible) { this.bRepeatingVisible = bVisible; } public List<Allocatable> getAllocatables() { return selectedAllocatables; } /** Map enthaelt die fuer die resourcen-darstellung benutzten farben mit resource-id (vom typ Integer) als schluessel. erst nach rebuild() verfuegbar. */ Map<Allocatable,String> getColorMap() { return colors; } private void createColorMap() { colors.clear(); List<Allocatable> arrayList = new ArrayList<Allocatable>(selectedAllocatables); Comparator<Allocatable> comp =new Comparator<Allocatable>() { public int compare(Allocatable o1, Allocatable o2) { if (o1.hashCode()>o2.hashCode()) return -1; if (o1.hashCode()<o2.hashCode()) return 1; return 0; } }; Collections.sort(arrayList,comp); Iterator<Allocatable> it = arrayList.iterator(); int i=0; while (it.hasNext()) { Allocatable allocatable = it.next(); DynamicType type = allocatable.getClassification().getType(); String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_COLORS); String color =null; if (annotation == null) { annotation = type.getAttribute("color") != null ? DynamicTypeAnnotations.VALUE_COLORS_COLOR_ATTRIBUTE: DynamicTypeAnnotations.VALUE_COLORS_AUTOMATED; } color = getColorForClassifiable( allocatable ); if ( color == null && annotation.equals(DynamicTypeAnnotations.VALUE_COLORS_AUTOMATED)) { color = RaplaColors.getResourceColor(i++); } else if ( annotation.equals(DynamicTypeAnnotations.VALUE_COLORS_DISABLED)) { color = null; } if ( color != null) { colors.put(allocatable, color); } } } static String getColorForClassifiable( Classifiable classifiable ) { Classification c = classifiable.getClassification(); Attribute colorAttribute = c.getAttribute("color"); String annotation = c.getType().getAnnotation(DynamicTypeAnnotations.KEY_COLORS); if ( annotation != null && annotation.equals( DynamicTypeAnnotations.VALUE_COLORS_DISABLED)) { return null; } String color = null; if ( colorAttribute != null) { Object hexValue = c.getValue( colorAttribute ); if ( hexValue != null) { if ( hexValue instanceof Category) { hexValue = ((Category) hexValue).getAnnotation( CategoryAnnotations.KEY_NAME_COLOR ); } if ( hexValue != null) { color = hexValue.toString(); } } } return color; } /** diese reservierungen werden vom WeekView angezeigt. */ public void selectReservations(Collection<Reservation> reservations) { this.selectedReservations= reservations; } /** nur diese resourcen werden angezeigt. */ public void selectAllocatables(Collection<Allocatable> allocatables) { selectedAllocatables.clear(); if (allocatables != null ) { selectedAllocatables.addAll(new HashSet<Allocatable>(allocatables)); Collections.sort( selectedAllocatables, new NamedComparator<Allocatable>( getRaplaLocale().getLocale() )); } createColorMap(); } public static List<Appointment> getAppointments( Reservation[] reservations, Allocatable[] allocatables) { return getAppointments( Arrays.asList( reservations), Arrays.asList( allocatables)); } public static List<Appointment> getAppointments( Collection<Reservation> reservations, Collection<Allocatable> allocatables) { List<Appointment> appointments = new ArrayList<Appointment>(); for (Reservation r:reservations) { for ( Appointment app:r.getAppointments()) { if (allocatables == null || allocatables.isEmpty()) { appointments.add( app); } else { // this flag is set true if one of the allocatables of a // reservation matches a selected allocatable. boolean allocatableMatched = false; for (Allocatable alloc:r.getAllocatablesFor(app)) { if (allocatables.contains(alloc)) { allocatableMatched = true; break; } } if ( allocatableMatched ) { appointments.add( app); } } } } return appointments; } static public class SplittedBlock extends AppointmentBlock { public SplittedBlock(AppointmentBlock original,long start, long end, Appointment appointment, boolean isException) { super(start, end, appointment, isException); this.original = original; } public AppointmentBlock getOriginal() { return original; } AppointmentBlock original; } static public List<AppointmentBlock> splitBlocks(Collection<AppointmentBlock> preparedBlocks, Date startDate, Date endDate) { List<AppointmentBlock> result = new ArrayList<AppointmentBlock>(); for (AppointmentBlock block:preparedBlocks) { long blockStart = block.getStart(); long blockEnd = block.getEnd(); Appointment appointment = block.getAppointment(); boolean isException = block.isException(); if (DateTools.isSameDay(blockStart, blockEnd)) { result.add( block); } else { long firstBlockDate = Math.max(blockStart, startDate.getTime()); long lastBlockDate = Math.min(blockEnd, endDate.getTime()); long currentBlockDate = firstBlockDate; while ( currentBlockDate >= blockStart && DateTools.cutDate( currentBlockDate ) < lastBlockDate) { long start; long end; if (DateTools.isSameDay(blockStart, currentBlockDate)) { start= blockStart; } else { start = DateTools.cutDate(currentBlockDate); } if (DateTools.isSameDay(blockEnd, currentBlockDate) && !DateTools.isMidnight(blockEnd)) { end = blockEnd; }else { end = DateTools.fillDate( currentBlockDate ) -1; } //System.out.println("Adding Block " + new Date(start) + " - " + new Date(end)); result.add ( new SplittedBlock(block,start, end, appointment,isException)); currentBlockDate+= DateTools.MILLISECONDS_PER_DAY; } } } return result; } /** selects all blocks that should be visible and calculates the max start- and end-time */ public void prepareBuild(Date start,Date end) { boolean excludeExceptions = isExceptionsExcluded(); HashSet<Reservation> allReservations = new HashSet<Reservation>( selectedReservations); allReservations.addAll( allReservationsForAllocatables); Collection<Appointment> appointments = getAppointments( selectedReservations, selectedAllocatables); // Add appointment to the blocks final List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>(); for (Appointment app:appointments) { app.createBlocks(start, end, blocks, excludeExceptions); } preparedBlocks = splitBlocks(blocks, start, end); // calculate new start and end times max =0; min =24*60; for (AppointmentBlock block:blocks) { int starthour = DateTools.getHourOfDay(block.getStart()); int startminute = DateTools.getMinuteOfHour(block.getStart()); int endhour = DateTools.getHourOfDay(block.getEnd()); int endminute = DateTools.getMinuteOfHour(block.getEnd()); if ((starthour != 0 || startminute != 0) && starthour*60 + startminute<min) min = starthour * 60 + startminute; if ((endhour >0 || endminute>0) && (endhour *60 + endminute)<min ) min = Math.max(0,endhour-1) * 60 + endminute; if ((endhour != 0 || endminute != 0) && (endhour != 23 && endminute!=59) && (endhour *60 + endminute)>max) max = Math.min(24*60 , endhour * 60 + endminute); if (starthour>=max) max = Math.min(24*60 , starthour *60 + startminute); } } public int getMinMinutes() { Assert.notNull(preparedBlocks, "call prepareBuild first"); return min; } public int getMaxMinutes() { Assert.notNull(preparedBlocks, "call prepareBuild first"); return max; } protected abstract Block createBlock(RaplaBlockContext blockContext, Date start, Date end); public void build(CalendarView wv) { ArrayList<Block> blocks = new ArrayList<Block>(); BuildContext buildContext = new BuildContext(this, blocks); Assert.notNull(preparedBlocks, "call prepareBuild first"); for (AppointmentBlock block:preparedBlocks) { Date start = new Date( block.getStart() ); Date end = new Date( block.getEnd() ); RaplaBlockContext[] blockContext = getBlocksForAppointment( block, buildContext ); for ( int j=0;j< blockContext.length; j++) { blocks.add( createBlock(blockContext[j], start, end)); } } buildStrategy.build(wv, blocks); } private RaplaBlockContext[] getBlocksForAppointment(AppointmentBlock block, BuildContext buildContext) { Appointment appointment = block.getAppointment(); boolean isBlockSelected = selectedReservations.contains( appointment.getReservation()); boolean isConflictsSelected = isConflictsSelected(); if ( !isBlockSelected && (!nonFilteredEventsVisible && !isConflictsSelected)) { return new RaplaBlockContext[] {}; } if ( isConflictsSelected) { boolean found = false; Collection<Appointment> collection = conflictingAppointments.get(appointment); if ( collection != null) { for (Appointment conflictingApp:collection) { if ( conflictingApp.overlaps( block)) { found = true; break; } } } if ( !found) { isBlockSelected = false; } } boolean isAnonymous = isAnonymous(buildContext.user, appointment); RaplaBlockContext firstContext = new RaplaBlockContext( block, this, buildContext, null, isBlockSelected, isAnonymous ); List<Allocatable> selectedAllocatables = firstContext.getSelectedAllocatables(); if ( !splitByAllocatables || selectedAllocatables.size() < 2) { return new RaplaBlockContext[] { firstContext }; } RaplaBlockContext[] context = new RaplaBlockContext[ selectedAllocatables.size() ]; for ( int i= 0;i<context.length;i ++) { context[i] = new RaplaBlockContext( block, this, buildContext, selectedAllocatables.get( i ), isBlockSelected, isAnonymous); } return context; } protected boolean isAnonymous(User user,Appointment appointment) { return !canRead(appointment, user); } private boolean isMovable(Reservation reservation) { return selectedReservations.contains( reservation ) && canModify(reservation, editingUser); } public boolean isConflictsSelected() { return conflictingAppointments != null; } /** This context contains the shared information for all RaplaBlocks.*/ public static class BuildContext { boolean bResourceVisible = true; boolean bPersonVisible = true; boolean bRepeatingVisible = true; boolean bTimeVisible = false; boolean conflictsSelected = false; Map<Allocatable,String> colors; I18nBundle i18n; RaplaLocale raplaLocale; RaplaContext serviceManager; Logger logger; User user; List<Block> blocks; private boolean isResourceColoring; private boolean isEventColoring; private boolean showTooltips; @SuppressWarnings("unchecked") public BuildContext(RaplaBuilder builder, List<Block> blocks) { this.blocks = blocks; this.raplaLocale = builder.getRaplaLocale(); this.bResourceVisible = builder.bResourceVisible; this.bPersonVisible= builder.bPersonVisible; this.bTimeVisible= builder.isTimeVisible(); this.bRepeatingVisible= builder.bRepeatingVisible; this.colors = (Map<Allocatable,String>) builder.colors.clone(); this.i18n =builder.getI18n(); this.serviceManager = builder.getContext(); this.logger = builder.getLogger(); this.user = builder.editingUser; this.conflictsSelected = builder.isConflictsSelected(); this.isResourceColoring = builder.isResourceColoring; this.isEventColoring = builder.isEventColoring; try { this.showTooltips = builder.getClientFacade().getPreferences(user).getEntryAsBoolean(RaplaBuilder.SHOW_TOOLTIP_CONFIG_ENTRY, true); } catch (RaplaException e) { this.showTooltips = true; getLogger().error(e.getMessage(), e); } } public RaplaLocale getRaplaLocale() { return raplaLocale; } public RaplaContext getServiceManager() { return serviceManager; } public List<Block> getBlocks() { return blocks; } public I18nBundle getI18n() { return i18n; } public boolean isTimeVisible() { return bTimeVisible; } public boolean isPersonVisible() { return bPersonVisible; } public boolean isRepeatingVisible() { return bRepeatingVisible; } public boolean isResourceVisible() { return bResourceVisible; } public String lookupColorString(Allocatable allocatable) { if (allocatable == null) return RaplaColors.DEFAULT_COLOR_AS_STRING; return colors.get(allocatable); } public boolean isConflictSelected() { return conflictsSelected; } public boolean isResourceColoringEnabled() { return isResourceColoring; } public boolean isEventColoringEnabled() { return isEventColoring; } public Logger getLogger() { return logger; } public boolean isShowToolTips() { return showTooltips; } } /** This context contains the shared information for one particular RaplaBlock.*/ public static class RaplaBlockContext { ArrayList<Allocatable> selectedMatchingAllocatables = new ArrayList<Allocatable>(3); ArrayList<Allocatable> matchingAllocatables = new ArrayList<Allocatable>(3); AppointmentBlock appointmentBlock; boolean movable; BuildContext buildContext; boolean isBlockSelected; boolean isAnonymous; public RaplaBlockContext(AppointmentBlock appointmentBlock,RaplaBuilder builder,BuildContext buildContext, Allocatable selectedAllocatable, boolean isBlockSelected, boolean isAnonymous) { this.buildContext = buildContext; this.isAnonymous = isAnonymous; if ( appointmentBlock instanceof SplittedBlock) { this.appointmentBlock = ((SplittedBlock)appointmentBlock).getOriginal(); } else { this.appointmentBlock = appointmentBlock; } Appointment appointment =appointmentBlock.getAppointment(); this.isBlockSelected = isBlockSelected; Reservation reservation = appointment.getReservation(); if(isBlockSelected) this.movable = builder.isMovable( reservation ); // Prefer resources when grouping addAllocatables(builder, reservation.getResources(), selectedAllocatable); addAllocatables(builder, reservation.getPersons(), selectedAllocatable); } private void addAllocatables(RaplaBuilder builder, Allocatable[] allocatables,Allocatable selectedAllocatable) { Appointment appointment =appointmentBlock.getAppointment(); Reservation reservation = appointment.getReservation(); for (int i=0; i<allocatables.length; i++) { if ( !reservation.hasAllocated( allocatables[i], appointment ) ) { continue; } matchingAllocatables.add(allocatables[i]); if ( builder.selectedAllocatables.contains(allocatables[i])) { if ( selectedAllocatable == null || selectedAllocatable.equals( allocatables[i]) ) { selectedMatchingAllocatables.add(allocatables[i]); } } } } public boolean isMovable() { return movable;// && !isAnonymous; } public AppointmentBlock getAppointmentBlock() { return appointmentBlock; } public Appointment getAppointment() { Appointment appointment =appointmentBlock.getAppointment(); return appointment; } public List<Allocatable> getSelectedAllocatables() { return selectedMatchingAllocatables; } public List<Allocatable> getAllocatables() { return matchingAllocatables; } public boolean isVisible(Allocatable allocatable) { User user = buildContext.user; if ( user != null && !allocatable.canReadOnlyInformation( user) ) { return false; } return matchingAllocatables.contains(allocatable); } public BuildContext getBuildContext() { return buildContext; } /** * @return null if no allocatables found */ public Allocatable getGroupAllocatable() { // Look if block belongs to a group according to the selected allocatables List<Allocatable> allocatables = getSelectedAllocatables(); // Look if block belongs to a group according to its reserved allocatables if ( allocatables.size() == 0) allocatables = getAllocatables(); if ( allocatables.size() == 0) return null; return allocatables.get( 0 ); } public boolean isBlockSelected() { return isBlockSelected; } public boolean isAnonymous() { return isAnonymous; } } }
Java
package org.rapla.plugin.abstractcalendar; public interface MultiCalendarPrint { String getCalendarUnit(); void setUnits(int units); int getUnits(); }
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.abstractcalendar; import java.util.Date; import org.rapla.components.calendarview.Block; import org.rapla.framework.RaplaContext; public class SwingRaplaBuilder extends RaplaBuilder { public SwingRaplaBuilder(RaplaContext sm) { super(sm); } /** * @see org.rapla.plugin.abstractcalendar.RaplaBuilder#createBlock(calendar.RaplaBuilder.RaplaBlockContext, java.util.Date, java.util.Date) */ protected Block createBlock(RaplaBlockContext blockContext, Date start, Date end) { SwingRaplaBlock block = new SwingRaplaBlock(); block.contextualize(blockContext); block.setStart(start); block.setEnd(end); return block; } }
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.AppointmentBlock; public interface AppointmentTableColumn extends RaplaTableColumn<AppointmentBlock> { }
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
/** * */ package org.rapla.plugin.tableview; import java.awt.Component; import java.util.Date; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import org.rapla.components.util.DateTools; import org.rapla.framework.RaplaLocale; final public class DateCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 1L; RaplaLocale raplaLocale; private boolean substractDayWhenFullDay; public DateCellRenderer(RaplaLocale raplaLocale) { this.raplaLocale = raplaLocale; } public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column ) { final Date date = (Date) value; if ( date == null) { value = ""; } else { // don't append time when 0 or 24 boolean appendTime = !raplaLocale.toDate(date, false ).equals( date); if ( appendTime ) { value = raplaLocale.formatDateLong( date) + " " + raplaLocale.formatTime( date ) ; } else { if ( substractDayWhenFullDay ) { value = raplaLocale.formatDateLong( DateTools.addDays(date, -1)); } else { value = raplaLocale.formatDateLong( date); } } } //setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT ); return super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); } public boolean isSubstractDayWhenFullDay() { return substractDayWhenFullDay; } public void setSubstractDayWhenFullDay(boolean substractDayWhenFullDay) { this.substractDayWhenFullDay = substractDayWhenFullDay; } }
Java
package org.rapla.plugin.tableview.internal; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.StringTokenizer; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.TableModel; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateChangeListener; import org.rapla.components.tablesorter.TableSorter; import org.rapla.components.util.TimeInterval; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Reservation; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarSelectionModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.MenuContext; import org.rapla.gui.MenuFactory; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.SwingCalendarView; import org.rapla.gui.VisibleTimeInterval; import org.rapla.gui.internal.common.InternMenus; import org.rapla.gui.internal.common.RaplaClipboard; import org.rapla.gui.toolkit.MenuInterface; import org.rapla.gui.toolkit.RaplaMenu; import org.rapla.gui.toolkit.RaplaPopupMenu; import org.rapla.plugin.abstractcalendar.IntervalChooserPanel; import org.rapla.plugin.tableview.RaplaTableColumn; import org.rapla.plugin.tableview.ReservationTableColumn; import org.rapla.plugin.tableview.TableViewExtensionPoints; public class SwingReservationTableView extends RaplaGUIComponent implements SwingCalendarView, Printable, VisibleTimeInterval { ReservationTableModel reservationTableModel; JTable table; CalendarModel model; IntervalChooserPanel dateChooser; JScrollPane scrollpane; JComponent container; TableSorter sorter; ActionListener copyListener = new ActionListener() { public void actionPerformed(ActionEvent evt) { List<Reservation> selectedEvents = getSelectedEvents(); List<Reservation> clones = new ArrayList<Reservation>(); try { for (Reservation r:selectedEvents) { Reservation copyReservation = getModification().clone(r); clones.add( copyReservation); } } catch (RaplaException e) { showException( e, getComponent()); } Collection<Allocatable> markedAllocatables = model.getMarkedAllocatables(); getClipboard().setReservation( clones, markedAllocatables); copy(table, evt); } private RaplaClipboard getClipboard() { return getService(RaplaClipboard.class); } }; public SwingReservationTableView( RaplaContext context, final CalendarModel model, final boolean editable ) throws RaplaException { super( context ); table = new JTable() { private static final long serialVersionUID = 1L; public String getToolTipText(MouseEvent e) { if (!editable) return null; int rowIndex = rowAtPoint( e.getPoint() ); Reservation reservation = reservationTableModel.getReservationAt( sorter.modelIndex( rowIndex )); return getInfoFactory().getToolTip( reservation ); } }; scrollpane = new JScrollPane( table); if ( editable ) { container = new JPanel(); container.setLayout( new BorderLayout()); container.add( scrollpane, BorderLayout.CENTER); JPanel extensionPanel = new JPanel(); extensionPanel.setLayout( new BoxLayout(extensionPanel, BoxLayout.X_AXIS)); container.add( extensionPanel, BorderLayout.SOUTH); scrollpane.setPreferredSize( new Dimension(600,800)); PopupTableHandler popupHandler = new PopupTableHandler(); scrollpane.addMouseListener( popupHandler); table.addMouseListener( popupHandler ); Collection< ? extends SummaryExtension> reservationSummaryExtensions = getContainer().lookupServicesFor(TableViewExtensionPoints.RESERVATION_TABLE_SUMMARY); for ( SummaryExtension summary:reservationSummaryExtensions) { summary.init(table, extensionPanel); } } else { Dimension size = table.getPreferredSize(); scrollpane.setBounds( 0,0,600, (int)size.getHeight()); container = scrollpane; } this.model = model; //Map<?,?> map = getContainer().lookupServicesFor(RaplaExtensionPoints.APPOINTMENT_STATUS); //Collection<AppointmentStatusFactory> appointmentStatusFactories = (Collection<AppointmentStatusFactory>) map.values(); List< ? extends ReservationTableColumn> reservationColumnPlugins = new ArrayList<ReservationTableColumn>(getContainer().lookupServicesFor(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN)); reservationTableModel = new ReservationTableModel( getLocale(),getI18n(), reservationColumnPlugins ); ReservationTableModel tableModel = reservationTableModel; sorter = createAndSetSorter(model, table, TableViewPlugin.EVENTS_SORTING_STRING_OPTION, tableModel); int column = 0; for (RaplaTableColumn<?> col: reservationColumnPlugins) { col.init(table.getColumnModel().getColumn(column )); column++; } table.setColumnSelectionAllowed( true ); table.setRowSelectionAllowed( true); table.getTableHeader().setReorderingAllowed(false); table.registerKeyboardAction(copyListener,getString("copy"),COPY_STROKE,JComponent.WHEN_FOCUSED); dateChooser = new IntervalChooserPanel( context, model); dateChooser.addDateChangeListener( new DateChangeListener() { public void dateChanged( DateChangeEvent evt ) { try { update( ); } catch (RaplaException ex ){ showException( ex, getComponent()); } } }); reservationTableModel.setReservations( model.getReservations() ); Listener listener = new Listener(); table.getSelectionModel().addListSelectionListener( listener); table.addFocusListener( listener); } class Listener implements ListSelectionListener, FocusListener { public void valueChanged(ListSelectionEvent e) { updateEditMenu(); } public void focusGained(FocusEvent e) { updateEditMenu(); } public void focusLost(FocusEvent e) { } } public static TableSorter createAndSetSorter(final CalendarModel model, final JTable table, final String sortingStringOptionName, TableModel tableModel) { final TableSorter sorter = new TableSorter( tableModel, table.getTableHeader()); String sorting = model.getOption(sortingStringOptionName); if ( sorting != null) { Enumeration<Object> e = new StringTokenizer( sorting,";", false); for (Object stringToCast:Collections.list(e)) { String string = (String) stringToCast; int length = string.length(); int column = Integer.parseInt(string.substring(0,length-1)); char order = string.charAt( length-1); if ( column < tableModel.getColumnCount()) { sorter.setSortingStatus( column, order == '-' ? TableSorter.DESCENDING : TableSorter.ASCENDING); } } } sorter.addTableModelListener(new TableModelListener() { public void tableChanged(TableModelEvent e) { StringBuffer buf = new StringBuffer(); for ( int i=0;i<table.getColumnCount();i++) { int sortingStatus = sorter.getSortingStatus( i); if (sortingStatus == TableSorter.ASCENDING) { buf.append(i + "+;"); } if (sortingStatus == TableSorter.DESCENDING) { buf.append(i + "-;"); } } String sortingString = buf.toString(); ((CalendarSelectionModel)model).setOption(sortingStringOptionName, sortingString.length() > 0 ? sortingString : null); } }); table.setModel( sorter ); return sorter; } protected void updateEditMenu() { List<Reservation> selectedEvents = getSelectedEvents(); if ( selectedEvents.size() == 0 ) { return; } RaplaMenu editMenu = getService(InternMenus.EDIT_MENU_ROLE); RaplaMenu newMenu = getService(InternMenus.NEW_MENU_ROLE); editMenu.removeAllBetween("EDIT_BEGIN", "EDIT_END"); newMenu.removeAll(); Point p = null; try { updateMenu(editMenu,newMenu, p); boolean canUserAllocateSomething = canUserAllocateSomething(getUser()); boolean enableNewMenu = newMenu.getMenuComponentCount() > 0 && canUserAllocateSomething; newMenu.setEnabled(enableNewMenu); editMenu.setEnabled(canUserAllocateSomething(getUser())); } catch (RaplaException ex) { showException (ex,getComponent()); } } public void update() throws RaplaException { reservationTableModel.setReservations( model.getReservations() ); dateChooser.update(); } public JComponent getDateSelection() { return dateChooser.getComponent(); } public void scrollToStart() { } public JComponent getComponent() { return container; } protected void updateMenu(MenuInterface editMenu,MenuInterface newMenu, Point p) throws RaplaException { List<Reservation> selectedEvents = getSelectedEvents(); Reservation focusedObject = null; if ( selectedEvents.size() == 1) { focusedObject = selectedEvents.get( 0); } MenuContext menuContext = new MenuContext( getContext(), focusedObject,getComponent(),p); menuContext.setSelectedObjects( selectedEvents); // add the new reservations wizards MenuFactory menuFactory = getService(MenuFactory.class); menuFactory.addReservationWizards( newMenu, menuContext, null); // add the edit methods if ( selectedEvents.size() != 0) { final JMenuItem copyItem = new JMenuItem(); copyItem.addActionListener( copyListener); copyItem.setText(getString("copy")); copyItem.setIcon( getIcon("icon.copy")); editMenu.insertAfterId(copyItem, "EDIT_BEGIN"); menuFactory.addObjectMenu( editMenu, menuContext, "EDIT_BEGIN"); } } List<Reservation> getSelectedEvents() { int[] rows = table.getSelectedRows(); List<Reservation> selectedEvents = new ArrayList<Reservation>(); for (int i=0;i<rows.length;i++) { Reservation reservation =reservationTableModel.getReservationAt( sorter.modelIndex(rows[i]) ); selectedEvents.add( reservation); } return selectedEvents; } class PopupTableHandler extends MouseAdapter { void showPopup(MouseEvent me) { try { RaplaPopupMenu menu= new RaplaPopupMenu(); Point p = new Point(me.getX(), me.getY()); RaplaMenu newMenu = new RaplaMenu("EDIT_BEGIN"); newMenu.setText(getString("new")); menu.add(newMenu); boolean canUserAllocateSomething = canUserAllocateSomething(getUser()); updateMenu(menu,newMenu, p); boolean enableNewMenu = newMenu.getMenuComponentCount() > 0 && canUserAllocateSomething; newMenu.setEnabled(enableNewMenu); menu.show( table, p.x, p.y); } catch (RaplaException ex) { showException (ex,getComponent()); } } /** Implementation-specific. Should be private.*/ public void mousePressed(MouseEvent me) { if (me.isPopupTrigger()) showPopup(me); } /** Implementation-specific. Should be private.*/ public void mouseReleased(MouseEvent me) { if (me.isPopupTrigger()) showPopup(me); } /** we want to edit the reservation on double click*/ public void mouseClicked(MouseEvent me) { List<Reservation> selectedEvents = getSelectedEvents(); if (me.getClickCount() > 1 && selectedEvents.size() == 1 ) { Reservation reservation = selectedEvents.get( 0); if (!canModify( reservation )) { return; } try { getReservationController().edit( reservation ); } catch (RaplaException ex) { showException (ex,getComponent()); } } } } Printable printable = null; /** * @see java.awt.print.Printable#print(java.awt.Graphics, java.awt.print.PageFormat, int) */ public int print(Graphics graphics, PageFormat format, int page) throws PrinterException { MessageFormat f1 = new MessageFormat( model.getNonEmptyTitle()); Printable printable = table.getPrintable( JTable.PrintMode.FIT_WIDTH,f1, null ); return printable.print( graphics, format, page); } public TimeInterval getVisibleTimeInterval() { return new TimeInterval(model.getStartDate(), model.getEndDate()); } }
Java
package org.rapla.plugin.tableview.internal; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateChangeListener; import org.rapla.components.tablesorter.TableSorter; import org.rapla.components.util.TimeInterval; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.Reservation; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaException; import org.rapla.gui.MenuContext; import org.rapla.gui.MenuFactory; import org.rapla.gui.ObjectMenuFactory; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.SwingCalendarView; import org.rapla.gui.VisibleTimeInterval; import org.rapla.gui.internal.action.AppointmentAction; import org.rapla.gui.internal.common.InternMenus; import org.rapla.gui.toolkit.MenuInterface; import org.rapla.gui.toolkit.RaplaMenu; import org.rapla.gui.toolkit.RaplaMenuItem; import org.rapla.gui.toolkit.RaplaPopupMenu; import org.rapla.plugin.abstractcalendar.IntervalChooserPanel; import org.rapla.plugin.abstractcalendar.RaplaCalendarViewListener; import org.rapla.plugin.tableview.AppointmentTableColumn; import org.rapla.plugin.tableview.TableViewExtensionPoints; public class SwingAppointmentTableView extends RaplaGUIComponent implements SwingCalendarView, Printable, VisibleTimeInterval { AppointmentTableModel appointmentTableModel; JTable table; CalendarModel model; IntervalChooserPanel dateChooser; JComponent scrollpane; TableSorter sorter; ActionListener copyListener = new ActionListener() { public void actionPerformed(ActionEvent evt) { List<AppointmentBlock> selectedEvents = getSelectedEvents(); if ( selectedEvents.size() == 1) { AppointmentBlock appointmentBlock = selectedEvents.get( 0); try { Component sourceComponent = table; Point p = null; Collection<Allocatable> contextAllocatables = Collections.emptyList(); getReservationController().copyAppointment(appointmentBlock,sourceComponent,p, contextAllocatables); } catch (RaplaException e) { showException( e, getComponent()); } } copy(table, evt); } }; private JComponent container; public SwingAppointmentTableView( RaplaContext context, CalendarModel model, final boolean editable ) throws RaplaException { super( context ); table = new JTable() { private static final long serialVersionUID = 1L; public String getToolTipText(MouseEvent e) { if (!editable) return null; int rowIndex = rowAtPoint( e.getPoint() ); AppointmentBlock app = appointmentTableModel.getAppointmentAt( sorter.modelIndex( rowIndex )); Reservation reservation = app.getAppointment().getReservation(); return getInfoFactory().getToolTip( reservation ); } }; scrollpane = new JScrollPane( table); if ( editable ) { scrollpane.setPreferredSize( new Dimension(600,800)); PopupTableHandler popupHandler = new PopupTableHandler(); scrollpane.addMouseListener( popupHandler); table.addMouseListener( popupHandler ); container = new JPanel(); container.setLayout( new BorderLayout()); container.add( scrollpane, BorderLayout.CENTER); JPanel extensionPanel = new JPanel(); extensionPanel.setLayout( new BoxLayout(extensionPanel, BoxLayout.X_AXIS)); container.add( extensionPanel, BorderLayout.SOUTH); Collection< ? extends SummaryExtension> reservationSummaryExtensions = getContainer().lookupServicesFor(TableViewExtensionPoints.APPOINTMENT_TABLE_SUMMARY); for ( SummaryExtension summary:reservationSummaryExtensions) { summary.init(table, extensionPanel); } } else { Dimension size = table.getPreferredSize(); scrollpane.setBounds( 0,0,600, (int)size.getHeight()); container = scrollpane; } this.model = model; Collection< ? extends AppointmentTableColumn> columnPlugins = getContainer().lookupServicesFor(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN); appointmentTableModel = new AppointmentTableModel( getLocale(),getI18n(), columnPlugins ); sorter = SwingReservationTableView.createAndSetSorter(model, table, TableViewPlugin.BLOCKS_SORTING_STRING_OPTION, appointmentTableModel); int column = 0; for (AppointmentTableColumn col: columnPlugins) { col.init(table.getColumnModel().getColumn(column )); column++; } table.setColumnSelectionAllowed( true ); table.setRowSelectionAllowed( true); table.getTableHeader().setReorderingAllowed(false); table.registerKeyboardAction(copyListener,getString("copy"),COPY_STROKE,JComponent.WHEN_FOCUSED); dateChooser = new IntervalChooserPanel( context, model); dateChooser.addDateChangeListener( new DateChangeListener() { public void dateChanged( DateChangeEvent evt ) { try { update( ); } catch (RaplaException ex ){ showException( ex, getComponent()); } } }); update(model); table.getSelectionModel().addListSelectionListener( new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { updateEditMenu(); } }); } protected void update(CalendarModel model) throws RaplaException { List<AppointmentBlock> blocks = model.getBlocks(); appointmentTableModel.setAppointments(blocks); } public void update() throws RaplaException { update(model); dateChooser.update(); } public JComponent getDateSelection() { return dateChooser.getComponent(); } public void scrollToStart() { } public JComponent getComponent() { return container; } List<AppointmentBlock> getSelectedEvents() { int[] rows = table.getSelectedRows(); List<AppointmentBlock> selectedEvents = new ArrayList<AppointmentBlock>(); for (int i=0;i<rows.length;i++) { AppointmentBlock reservation =appointmentTableModel.getAppointmentAt( sorter.modelIndex(rows[i]) ); selectedEvents.add( reservation); } return selectedEvents; } protected void updateEditMenu() { List<AppointmentBlock> selectedEvents = getSelectedEvents(); if ( selectedEvents.size() == 0 ) { return; } RaplaMenu editMenu = getService(InternMenus.EDIT_MENU_ROLE); RaplaMenu newMenu = getService(InternMenus.NEW_MENU_ROLE); editMenu.removeAllBetween("EDIT_BEGIN", "EDIT_END"); newMenu.removeAll(); Point p = null; try { updateMenu(editMenu,newMenu, p); newMenu.setEnabled(newMenu.getMenuComponentCount() > 0 && canUserAllocateSomething(getUser())); editMenu.setEnabled(canUserAllocateSomething(getUser())); } catch (RaplaException ex) { showException (ex,getComponent()); } } class PopupTableHandler extends MouseAdapter { void showPopup(MouseEvent me) { Point p = new Point(me.getX(), me.getY()); RaplaPopupMenu menu= new RaplaPopupMenu(); try { RaplaMenu newMenu = new RaplaMenu("EDIT_BEGIN"); newMenu.setText(getString("new")); menu.add( newMenu ); updateMenu( menu, newMenu, p); newMenu.setEnabled(newMenu.getMenuComponentCount() > 0 && canUserAllocateSomething(getUser())); menu.show( table, p.x, p.y); } catch (RaplaException ex) { showException (ex,getComponent()); } } /** Implementation-specific. Should be private.*/ public void mousePressed(MouseEvent me) { if (me.isPopupTrigger()) showPopup(me); } /** Implementation-specific. Should be private.*/ public void mouseReleased(MouseEvent me) { if (me.isPopupTrigger()) showPopup(me); } /** we want to edit the reservation on double click*/ public void mouseClicked(MouseEvent me) { List<AppointmentBlock> selectedEvents = getSelectedEvents(); if (me.getClickCount() > 1 && selectedEvents.size() == 1 ) { AppointmentBlock block = selectedEvents.get( 0); Appointment appointment = block.getAppointment(); Reservation reservation = appointment.getReservation(); if (!canModify( reservation )) { return; } try { getReservationController().edit( block); } catch (RaplaException ex) { showException (ex,getComponent()); } } } } protected void updateMenu(MenuInterface editMenu,MenuInterface newMenu,Point p) throws RaplaException, RaplaContextException { List<AppointmentBlock> selectedEvents = getSelectedEvents(); AppointmentBlock focusedObject = null; if ( selectedEvents.size() == 1) { focusedObject = selectedEvents.get( 0); } MenuContext menuContext = new MenuContext( getContext(), focusedObject,getComponent(), p); menuContext.put(RaplaCalendarViewListener.SELECTED_DATE, focusedObject != null ? new Date(focusedObject.getStart()): new Date()); { menuContext.setSelectedObjects( selectedEvents); } // add the new reservations wizards { MenuFactory menuFactory = getService(MenuFactory.class); menuFactory.addReservationWizards( newMenu, menuContext, null); } if ( selectedEvents.size() != 0) { final JMenuItem copyItem = new JMenuItem(); copyItem.addActionListener( copyListener); copyItem.setIcon( getIcon("icon.copy")); copyItem.setText(getString("copy")); editMenu.insertAfterId(copyItem, "EDIT_BEGIN"); addObjectMenu(editMenu, menuContext, "EDIT_BEGIN"); } } Printable printable = null; /** * @see java.awt.print.Printable#print(java.awt.Graphics, java.awt.print.PageFormat, int) */ public int print(Graphics graphics, PageFormat format, int page) throws PrinterException { MessageFormat f1 = new MessageFormat( model.getNonEmptyTitle()); MessageFormat f2 = new MessageFormat("- {0} -"); Printable printable = table.getPrintable( JTable.PrintMode.FIT_WIDTH,f1, f2 ); return printable.print( graphics, format, page); } private MenuInterface addObjectMenu( MenuInterface menu, MenuContext context, String afterId ) throws RaplaException { Component parent = getComponent(); AppointmentBlock appointmentBlock = (AppointmentBlock) context.getFocusedObject(); Point p = context.getPoint(); @SuppressWarnings("unchecked") Collection<AppointmentBlock> selection = (Collection<AppointmentBlock>)context.getSelectedObjects(); if ( appointmentBlock != null) { { AppointmentAction action = new AppointmentAction(getContext(),parent,p); action.setDelete(appointmentBlock); menu.insertAfterId(new JMenuItem(action), afterId); } { AppointmentAction action = new AppointmentAction(getContext(),parent,p); action.setView(appointmentBlock); menu.insertAfterId(new JMenuItem(action), afterId); } { AppointmentAction action = new AppointmentAction(getContext(),parent,p); action.setEdit(appointmentBlock); menu.insertAfterId(new JMenuItem(action), afterId); } } else if ( selection != null && selection.size() > 0) { AppointmentAction action = new AppointmentAction(getContext(),parent,p); action.setDeleteSelection(selection); menu.insertAfterId(new JMenuItem(action), afterId); } Iterator<?> it = getContainer().lookupServicesFor( RaplaClientExtensionPoints.OBJECT_MENU_EXTENSION).iterator(); while (it.hasNext()) { ObjectMenuFactory objectMenuFact = (ObjectMenuFactory) it.next(); Appointment appointment = appointmentBlock != null ? appointmentBlock.getAppointment(): null; RaplaMenuItem[] items = objectMenuFact.create( context, appointment); for ( int i =0;i<items.length;i++) { RaplaMenuItem item = items[i]; menu.insertAfterId( item, afterId); } } return menu; } public TimeInterval getVisibleTimeInterval() { return new TimeInterval(model.getStartDate(), model.getEndDate()); } }
Java
package org.rapla.plugin.tableview.internal; import javax.swing.table.TableColumn; import org.rapla.components.util.xml.XMLWriter; import org.rapla.entities.domain.Reservation; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.plugin.tableview.ReservationTableColumn; public final class ReservationNameColumn extends RaplaComponent implements ReservationTableColumn{ public ReservationNameColumn(RaplaContext context) { super(context); } public void init(TableColumn column) { } public Object getValue(Reservation reservation) { // getLocale(). return reservation.getName(getLocale()); } public String getColumnName() { return getString("name"); } public Class<?> getColumnClass() { return String.class; } public String getHtmlValue(Reservation event) { String value = getValue(event).toString(); return XMLWriter.encode(value); } }
Java
package org.rapla.plugin.tableview.internal; import org.rapla.entities.domain.Allocatable; import org.rapla.framework.RaplaContext; public final class ResourceColumn extends AllocatableListColumn { public ResourceColumn(RaplaContext context) { super(context); } @Override protected boolean contains(Allocatable alloc) { return !alloc.isPerson(); } public String getColumnName() { return getString("resources"); } }
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.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.internal; import java.util.Date; import javax.swing.table.TableColumn; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaLocale; import org.rapla.plugin.tableview.AppointmentTableColumn; import org.rapla.plugin.tableview.DateCellRenderer; public final class AppointmentStartDate extends RaplaComponent implements AppointmentTableColumn { public AppointmentStartDate(RaplaContext context) { super(context); } public void init(TableColumn column) { column.setCellRenderer( new DateCellRenderer( getRaplaLocale())); column.setMaxWidth( 175 ); column.setPreferredWidth( 175 ); } public Object getValue(AppointmentBlock block) { return new Date(block.getStart()); } public String getColumnName() { return getString("start_date"); } public Class<?> getColumnClass() { return Date.class; } public String getHtmlValue(AppointmentBlock block) { RaplaLocale raplaLocale = getRaplaLocale(); final Date date = new Date(block.getStart()); if ( block.getAppointment().isWholeDaysSet()) { String dateString= raplaLocale.formatDateLong(date); return dateString; } else { String dateString= raplaLocale.formatDateLong(date) + " " + raplaLocale.formatTime( date); return dateString; } } }
Java
package org.rapla.plugin.tableview.internal; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.swing.table.DefaultTableModel; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.plugin.tableview.AppointmentTableColumn; public class AppointmentTableModel extends DefaultTableModel { private static final long serialVersionUID = 1L; List<AppointmentBlock> appointments= new ArrayList<AppointmentBlock>(); Locale locale; I18nBundle i18n; Map<Integer,AppointmentTableColumn> columns = new LinkedHashMap<Integer, AppointmentTableColumn>(); //String[] columns; public AppointmentTableModel(Locale locale, I18nBundle i18n, Collection<? extends AppointmentTableColumn> columnPlugins) { this.locale = locale; this.i18n = i18n; List<String> columnNames = new ArrayList<String>(); int column = 0; for (AppointmentTableColumn col: columnPlugins) { columnNames.add( col.getColumnName()); columns.put( column, col); column++; } this.setColumnIdentifiers( columnNames.toArray()); } public void setAppointments(List<AppointmentBlock> appointments2) { this.appointments = appointments2; super.fireTableDataChanged(); } public AppointmentBlock getAppointmentAt(int row) { return this.appointments.get(row); } public boolean isCellEditable(int row, int column) { return false; } public int getRowCount() { if ( appointments != null) return appointments.size(); else return 0; } public Object getValueAt( int rowIndex, int columnIndex ) { AppointmentBlock event = getAppointmentAt(rowIndex); AppointmentTableColumn tableColumn = columns.get( columnIndex); return tableColumn.getValue(event); } public Class<?> getColumnClass(int columnIndex) { AppointmentTableColumn tableColumn = columns.get( columnIndex); return tableColumn.getColumnClass(); } }
Java
package org.rapla.plugin.tableview.internal; import java.util.Date; import javax.swing.table.TableColumn; import org.rapla.entities.domain.Reservation; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaLocale; import org.rapla.plugin.tableview.DateCellRenderer; import org.rapla.plugin.tableview.ReservationTableColumn; public class ReservationStartColumn extends RaplaComponent implements ReservationTableColumn { public ReservationStartColumn(RaplaContext context) { super(context); } public void init(TableColumn column) { column.setCellRenderer( new DateCellRenderer( getRaplaLocale())); column.setMaxWidth( 130 ); column.setPreferredWidth( 130 ); } public Object getValue(Reservation reservation) { return reservation.getFirstDate(); } public String getColumnName() { return getString("start_date"); } public Class<?> getColumnClass() { return Date.class; } public String getHtmlValue(Reservation reservation) { RaplaLocale raplaLocale = getRaplaLocale(); final Date firstDate = reservation.getFirstDate(); String string= raplaLocale.formatDateLong(firstDate) + " " + raplaLocale.formatTime( firstDate); return string; } }
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.tableview.internal; import java.awt.Component; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import javax.swing.JMenuItem; import javax.swing.SwingUtilities; import org.rapla.RaplaMainContainer; import org.rapla.components.iolayer.IOInterface; import org.rapla.facade.CalendarSelectionModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.IdentifiableMenuEntry; import org.rapla.plugin.tableview.RaplaTableColumn; import org.rapla.plugin.tableview.TableViewExtensionPoints; public class CSVExportMenu extends RaplaGUIComponent implements IdentifiableMenuEntry, ActionListener { JMenuItem exportEntry; String idString = "csv"; public CSVExportMenu( RaplaContext context ) { super( context ); exportEntry = new JMenuItem(getString("csv.export")); exportEntry.setIcon( getIcon("icon.export") ); exportEntry.addActionListener(this); } public void actionPerformed(ActionEvent evt) { try { CalendarSelectionModel model = getService(CalendarSelectionModel.class); export( model); } catch (Exception ex) { showException( ex, getMainComponent() ); } } public String getId() { return idString; } public JMenuItem getMenuElement() { return exportEntry; } private static final String LINE_BREAK = "\n"; private static final String CELL_BREAK = ";"; @SuppressWarnings({ "unchecked", "rawtypes" }) public void export(final CalendarSelectionModel model) throws Exception { // generates a text file from all filtered events; StringBuffer buf = new StringBuffer(); Collection< ? extends RaplaTableColumn<?>> columns; List<Object> objects = new ArrayList<Object>(); if (model.getViewId().equals(ReservationTableViewFactory.TABLE_VIEW)) { columns = getContainer().lookupServicesFor(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN); objects.addAll(Arrays.asList( model.getReservations())); } else { columns = getContainer().lookupServicesFor(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN); objects.addAll( model.getBlocks()); } for (RaplaTableColumn column: columns) { buf.append( column.getColumnName()); buf.append(CELL_BREAK); } for (Object row: objects) { buf.append(LINE_BREAK); for (RaplaTableColumn column: columns) { Object value = column.getValue( row); Class columnClass = column.getColumnClass(); boolean isDate = columnClass.isAssignableFrom( java.util.Date.class); String formated = ""; if(value != null) { if ( isDate) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); format.setTimeZone( getRaplaLocale().getTimeZone()); String timestamp = format.format( (java.util.Date)value); formated = timestamp; } else { String escaped = escape(value); formated = escaped; } } buf.append( formated ); buf.append(CELL_BREAK); } } byte[] bytes = buf.toString().getBytes(); DateFormat sdfyyyyMMdd = new SimpleDateFormat("yyyyMMdd"); final String calendarName = getQuery().getSystemPreferences().getEntryAsString(RaplaMainContainer.TITLE, getString("rapla.title")); String filename = calendarName + "-" + sdfyyyyMMdd.format( model.getStartDate() ) + "-" + sdfyyyyMMdd.format( model.getEndDate() ) + ".csv"; if (saveFile( bytes, filename,"csv")) { exportFinished(getMainComponent()); } } protected boolean exportFinished(Component topLevel) { try { DialogUI dlg = DialogUI.create( getContext() ,topLevel ,true ,getString("export") ,getString("file_saved") ,new String[] { getString("ok")} ); dlg.setIcon(getIcon("icon.export")); dlg.setDefault(0); dlg.start(); return (dlg.getSelectedIndex() == 0); } catch (RaplaException e) { return true; } } private String escape(Object cell) { return cell.toString().replace(LINE_BREAK, " ").replace(CELL_BREAK, " "); } public boolean saveFile(byte[] content,String filename, String extension) throws RaplaException { final Frame frame = (Frame) SwingUtilities.getRoot(getMainComponent()); IOInterface io = getService( IOInterface.class); try { String file = io.saveFile( frame, null, new String[] {extension}, filename, content); return file != null; } catch (IOException e) { throw new RaplaException(e.getMessage(), e); } } }
Java
package org.rapla.plugin.tableview.internal; import org.rapla.entities.domain.Allocatable; import org.rapla.framework.RaplaContext; public final class PersonColumn extends AllocatableListColumn { public PersonColumn(RaplaContext context) { super(context); } @Override protected boolean contains(Allocatable alloc) { return alloc.isPerson(); } public String getColumnName() { return getString("persons"); } }
Java
package org.rapla.plugin.tableview.internal; import javax.swing.table.TableColumn; import org.rapla.components.util.xml.XMLWriter; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.Reservation; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.plugin.tableview.AppointmentTableColumn; public class AllocatableListColumn extends RaplaComponent implements AppointmentTableColumn { public AllocatableListColumn(RaplaContext context) { super(context); } public void init(TableColumn column) { column.setMaxWidth( 130 ); column.setPreferredWidth( 130 ); } public Object getValue(AppointmentBlock block) { Appointment appointment = block.getAppointment(); Reservation reservation = appointment.getReservation(); Allocatable[] allocatablesFor = reservation.getAllocatablesFor(appointment); StringBuilder buf = new StringBuilder(); boolean first = true; for (Allocatable alloc: allocatablesFor) { if ( !contains( alloc)) { continue; } if (!first) { buf.append(", "); } first = false; String name = alloc.getName( getLocale()); buf.append( name); } return buf.toString(); } /** * @param alloc */ protected boolean contains(Allocatable alloc) { return true; } public String getColumnName() { return getString("resources"); } public Class<?> getColumnClass() { return String.class; } public String getHtmlValue(AppointmentBlock block) { String names = getValue(block).toString(); return XMLWriter.encode(names); } }
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.tableview.internal; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.framework.Configuration; import org.rapla.framework.Container; import org.rapla.framework.PluginDescriptor; import org.rapla.plugin.tableview.TableViewExtensionPoints; public class TableViewPlugin implements PluginDescriptor<ClientServiceContainer> { public static final String PLUGIN_CLASS = TableViewPlugin.class.getName(); public static final String EVENTS_SORTING_STRING_OPTION = "org.rapla.plugin.tableview.events.sortingstring"; public static final String BLOCKS_SORTING_STRING_OPTION = "org.rapla.plugin.tableview.blocks.sortingstring"; public final static boolean ENABLE_BY_DEFAULT = true; public void provideServices(final ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent( RaplaClientExtensionPoints.EXPORT_MENU_EXTENSION_POINT, CSVExportMenu.class); container.addContainerProvidedComponent( RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,ReservationTableViewFactory.class); container.addContainerProvidedComponent( RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,AppointmentTableViewFactory.class); addReservationTableColumns(container); addAppointmentTableColumns(container); //Summary rows container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_SUMMARY, EventCounter.class); container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_SUMMARY, AppointmentCounter.class); } protected void addAppointmentTableColumns(final Container container) { container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, AppointmentNameColumn.class); container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, AppointmentStartDate.class); container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, AppointmentEndDate.class); container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, ResourceColumn.class); container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, PersonColumn.class); } protected void addReservationTableColumns(final Container container) { container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, ReservationNameColumn.class); container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, ReservationStartColumn.class); container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, ReservationLastChangedColumn.class); } }
Java
package org.rapla.plugin.tableview.internal; import java.util.Date; import javax.swing.table.TableColumn; import org.rapla.entities.domain.Reservation; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaLocale; import org.rapla.plugin.tableview.DateCellRenderer; import org.rapla.plugin.tableview.ReservationTableColumn; public class ReservationLastChangedColumn extends RaplaComponent implements ReservationTableColumn { public ReservationLastChangedColumn(RaplaContext context) { super(context); } public void init(TableColumn column) { column.setCellRenderer( new DateCellRenderer( getRaplaLocale())); column.setMaxWidth( 130 ); column.setPreferredWidth( 130 ); } public Object getValue(Reservation reservation) { return reservation.getLastChanged(); } public String getColumnName() { return getString("last_changed"); } public Class<?> getColumnClass() { return Date.class; } public String getHtmlValue(Reservation reservation) { RaplaLocale raplaLocale = getRaplaLocale(); final Date lastChangeTime = reservation.getLastChanged(); String lastChanged= raplaLocale.formatDateLong(lastChangeTime); return lastChanged; } }
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.internal.server; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import org.rapla.entities.domain.Reservation; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.tableview.RaplaTableColumn; import org.rapla.plugin.tableview.TableViewExtensionPoints; import org.rapla.plugin.tableview.internal.TableViewPlugin; public class ReservationTableViewPage extends TableViewPage<Reservation> { public ReservationTableViewPage( RaplaContext context, CalendarModel calendarModel ) { super( context, calendarModel ); } String getCalendarHTML() throws RaplaException { final Date startDate = model.getStartDate(); final Date endDate = model.getEndDate(); final List<Reservation> reservations = Arrays.asList(model.getReservations(startDate, endDate)); List< RaplaTableColumn<Reservation>> columPluigns = new ArrayList<RaplaTableColumn<Reservation>>(getContainer().lookupServicesFor(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN)); return getCalendarHTML( columPluigns, reservations,TableViewPlugin.EVENTS_SORTING_STRING_OPTION ); } @Override int compareTo(Reservation r1, Reservation r2) { if ( r1.equals( r2)) { return 0; } int compareTo = r1.getFirstDate().compareTo( r2.getFirstDate()); return compareTo; } }
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.tableview.internal.server; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory; import org.rapla.servletpages.RaplaPageGenerator; public class AppointmentHTMLTableViewFactory extends RaplaComponent implements HTMLViewFactory { public AppointmentHTMLTableViewFactory( RaplaContext context ) { super( context ); } public final static String TABLE_VIEW = "table_appointments"; public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) { return new AppointmentTableViewPage( context, model); } public String getViewId() { return TABLE_VIEW; } public String getName() { return getString("appointments"); } }
Java
package org.rapla.plugin.tableview.internal.server; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.StringTokenizer; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.rapla.entities.domain.Allocatable; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.plugin.abstractcalendar.server.AbstractHTMLCalendarPage; import org.rapla.plugin.tableview.RaplaTableColumn; import org.rapla.servletpages.RaplaPageGenerator; abstract public class TableViewPage<T> extends RaplaComponent implements RaplaPageGenerator { protected CalendarModel model; public TableViewPage(RaplaContext context, CalendarModel model) { super(context); this.model = model; } public String getTitle() { return model.getNonEmptyTitle(); } public void generatePage(ServletContext context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=" + getRaplaLocale().getCharsetNonUtf() ); java.io.PrintWriter out = response.getWriter(); RaplaLocale raplaLocale= getRaplaLocale(); String linkPrefix = request.getPathTranslated() != null ? "../": ""; out.println("<html>"); out.println("<head>"); out.println(" <title>" + getTitle() + "</title>"); out.println(" <link REL=\"stylesheet\" href=\""+linkPrefix + "calendar.css\" type=\"text/css\">"); out.println(" <link REL=\"stylesheet\" href=\""+linkPrefix + "default.css\" type=\"text/css\">"); // tell the html page where its favourite icon is stored out.println(" <link REL=\"shortcut icon\" type=\"image/x-icon\" href=\"/images/favicon.ico\">"); out.println(" <meta HTTP-EQUIV=\"Content-Type\" content=\"text/html; charset=" + raplaLocale.getCharsetNonUtf() + "\">"); out.println("</head>"); out.println("<body>"); if (request.getParameter("selected_allocatables") != null && request.getParameter("allocatable_id")==null) { try { Allocatable[] selectedAllocatables = model.getSelectedAllocatables(); AbstractHTMLCalendarPage.printAllocatableList(request, out, getLocale(), selectedAllocatables); } catch (RaplaException e) { throw new ServletException(e); } } else { out.println("<h2 class=\"title\">"); out.println(getTitle()); out.println("</h2>"); out.println("<div id=\"calendar\">"); try { final String calendarHTML = getCalendarHTML(); out.println(calendarHTML); } catch (RaplaException e) { out.close(); throw new ServletException( e); } out.println("</div>"); } // end weekview out.println("</body>"); out.println("</html>"); out.close(); } class TableRow implements Comparable<TableRow> { T object; @SuppressWarnings("rawtypes") RaplaTableColumn reservationColumnPlugins; int direction; TableRow(T originalObject, RaplaTableColumn<T> reservationColumnPlugins, int sortDirection) { this.object = originalObject; this.reservationColumnPlugins = reservationColumnPlugins; this.direction = sortDirection; } @SuppressWarnings({ "rawtypes", "unchecked" }) public int compareTo(TableRow o) { if (o.equals( this)) { return 0; } if ( reservationColumnPlugins != null) { Object v1 = reservationColumnPlugins.getValue( object ); Object v2 = o.reservationColumnPlugins.getValue( o.object); if ( v1 != null && v2 != null) { Class<?> columnClass = reservationColumnPlugins.getColumnClass(); if ( columnClass.equals( String.class)) { return String.CASE_INSENSITIVE_ORDER.compare( v1.toString(), v2.toString()) * direction; } else if (columnClass.isAssignableFrom(Comparable.class)) { return ((Comparable)v1).compareTo( v2) * direction; } } } T object1 = object; T object2 = o.object; return TableViewPage.this.compareTo(object1,object2); } } public String getCalendarHTML(List< RaplaTableColumn<T>> columPluigns, List<T> rowObjects,String sortingStringOption) { RaplaTableColumn<T> columPlugin = null; int sortDirection =1; String sorting = model.getOption(sortingStringOption); if ( sorting != null) { Enumeration<Object> e = new StringTokenizer( sorting,";", false); for (Object stringToCast:Collections.list(e)) { String string = (String) stringToCast; int length = string.length(); int column = Integer.parseInt(string.substring(0,length-1)); char order = string.charAt( length-1); if ( columPluigns.size() > column) { columPlugin = columPluigns.get( column ); sortDirection= order == '+' ? 1: -1; } } } List<TableRow> rows = new ArrayList<TableRow>(); for (T r :rowObjects) { rows.add( new TableRow( r, columPlugin, sortDirection)); } Collections.sort( rows); StringBuffer buf = new StringBuffer(); buf.append("<table class='eventtable'>"); for (RaplaTableColumn<?> col: columPluigns) { buf.append("<th>"); buf.append(col.getColumnName()); buf.append("</th>"); } for (TableRow row :rows) { buf.append("<tr>"); for (RaplaTableColumn<T> col: columPluigns) { buf.append("<td>"); T rowObject = row.object; buf.append(col.getHtmlValue(rowObject)); buf.append("</td>"); } buf.append("</tr>"); } buf.append("</table>"); final String result = buf.toString(); return result; } abstract String getCalendarHTML() throws RaplaException; abstract int compareTo(T object1, T object2); }
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.internal.server; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.tableview.AppointmentTableColumn; import org.rapla.plugin.tableview.RaplaTableColumn; import org.rapla.plugin.tableview.TableViewExtensionPoints; import org.rapla.plugin.tableview.internal.TableViewPlugin; public class AppointmentTableViewPage extends TableViewPage<AppointmentBlock> { public AppointmentTableViewPage( RaplaContext context, CalendarModel calendarModel ) { super( context,calendarModel ); } public String getCalendarHTML() throws RaplaException { final List<AppointmentBlock> blocks = model.getBlocks(); Collection<AppointmentTableColumn> map2 = getContainer().lookupServicesFor(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN); List<RaplaTableColumn<AppointmentBlock>> appointmentColumnPlugins = new ArrayList<RaplaTableColumn<AppointmentBlock>>(map2); return getCalendarHTML(appointmentColumnPlugins, blocks, TableViewPlugin.BLOCKS_SORTING_STRING_OPTION); } int compareTo(AppointmentBlock object1, AppointmentBlock object2) { return object1.compareTo( object2); } }
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.tableview.internal.server; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory; import org.rapla.servletpages.RaplaPageGenerator; public class ReservationHTMLTableViewFactory extends RaplaComponent implements HTMLViewFactory { public ReservationHTMLTableViewFactory( RaplaContext context ) { super( context ); } public final static String TABLE_VIEW = "table"; public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) throws RaplaException { return new ReservationTableViewPage( context, model); } public String getViewId() { return TABLE_VIEW; } public String getName() { return getString("reservations"); } }
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.tableview.internal.server; import org.rapla.framework.Configuration; import org.rapla.framework.Container; import org.rapla.framework.PluginDescriptor; import org.rapla.plugin.tableview.TableViewExtensionPoints; import org.rapla.plugin.tableview.internal.AppointmentCounter; import org.rapla.plugin.tableview.internal.AppointmentEndDate; import org.rapla.plugin.tableview.internal.AppointmentNameColumn; import org.rapla.plugin.tableview.internal.AppointmentStartDate; import org.rapla.plugin.tableview.internal.EventCounter; import org.rapla.plugin.tableview.internal.PersonColumn; import org.rapla.plugin.tableview.internal.ReservationLastChangedColumn; import org.rapla.plugin.tableview.internal.ReservationNameColumn; import org.rapla.plugin.tableview.internal.ReservationStartColumn; import org.rapla.plugin.tableview.internal.ResourceColumn; import org.rapla.plugin.tableview.internal.TableViewPlugin; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.server.ServerServiceContainer; public class TableViewServerPlugin implements PluginDescriptor<ServerServiceContainer> { public void provideServices(final ServerServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", TableViewPlugin.ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent( RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,ReservationHTMLTableViewFactory.class); container.addContainerProvidedComponent( RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,AppointmentHTMLTableViewFactory.class); addReservationTableColumns(container); addAppointmentTableColumns(container); //Summary rows container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_SUMMARY, EventCounter.class); container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_SUMMARY, AppointmentCounter.class); } protected void addAppointmentTableColumns(final Container container) { container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, AppointmentNameColumn.class); container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, AppointmentStartDate.class); container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, AppointmentEndDate.class); container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, ResourceColumn.class); container.addContainerProvidedComponent(TableViewExtensionPoints.APPOINTMENT_TABLE_COLUMN, PersonColumn.class); } protected void addReservationTableColumns(final Container container) { container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, ReservationNameColumn.class); container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, ReservationStartColumn.class); container.addContainerProvidedComponent(TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, ReservationLastChangedColumn.class); } }
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.tableview.internal; import javax.swing.Icon; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.SwingCalendarView; import org.rapla.gui.SwingViewFactory; import org.rapla.gui.images.Images; public class ReservationTableViewFactory extends RaplaComponent implements SwingViewFactory { public ReservationTableViewFactory( RaplaContext context ) { super( context ); } public final static String TABLE_VIEW = "table"; public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException { return new SwingReservationTableView( context, model, editable); } public String getViewId() { return TABLE_VIEW; } public String getName() { return getString("reservations"); } Icon icon; public Icon getIcon() { if ( icon == null) { icon = Images.getIcon("/org/rapla/plugin/tableview/images/eventlist.png"); } return icon; } public String getMenuSortKey() { return "0"; } }
Java
package org.rapla.plugin.tableview.internal; import javax.swing.JPanel; import javax.swing.JTable; public interface SummaryExtension { void init(JTable table, JPanel summaryRow); }
Java
package org.rapla.plugin.tableview.internal; import java.util.Date; import javax.swing.table.TableColumn; import org.rapla.components.util.DateTools; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaLocale; import org.rapla.plugin.tableview.AppointmentTableColumn; import org.rapla.plugin.tableview.DateCellRenderer; public final class AppointmentEndDate extends RaplaComponent implements AppointmentTableColumn { public AppointmentEndDate(RaplaContext context) { super(context); } public void init(TableColumn column) { DateCellRenderer cellRenderer = new DateCellRenderer( getRaplaLocale()); cellRenderer.setSubstractDayWhenFullDay(true); column.setCellRenderer( cellRenderer); column.setMaxWidth( 175 ); column.setPreferredWidth( 175 ); } public Object getValue(AppointmentBlock block) { return new Date(block.getEnd()); } public String getColumnName() { return getString("end_date"); } public Class<?> getColumnClass() { return Date.class; } public String getHtmlValue(AppointmentBlock block) { RaplaLocale raplaLocale = getRaplaLocale(); final Date date = new Date(block.getEnd()); if ( block.getAppointment().isWholeDaysSet()) { String dateString= raplaLocale.formatDateLong(DateTools.addDays(date,-1)); return dateString; } else { String dateString= raplaLocale.formatDateLong(date) + " " + raplaLocale.formatTime( date ); return dateString; } } }
Java
package org.rapla.plugin.tableview.internal; import javax.swing.table.TableColumn; import org.rapla.components.util.xml.XMLWriter; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.Reservation; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.plugin.tableview.AppointmentTableColumn; public final class AppointmentNameColumn extends RaplaComponent implements AppointmentTableColumn { public AppointmentNameColumn(RaplaContext context) { super(context); } public void init(TableColumn column) { } public Object getValue(AppointmentBlock block) { // getLocale(). Appointment appointment = block.getAppointment(); Reservation reservation = appointment.getReservation(); return reservation.getName(getLocale()); } public String getColumnName() { return getString("name"); } public Class<?> getColumnClass() { return String.class; } public String getHtmlValue(AppointmentBlock block) { String value = getValue(block).toString(); return XMLWriter.encode(value); } }
Java
package org.rapla.plugin.tableview.internal; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.swing.table.DefaultTableModel; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.domain.Reservation; import org.rapla.plugin.tableview.RaplaTableColumn; import org.rapla.plugin.tableview.ReservationTableColumn; public class ReservationTableModel extends DefaultTableModel { private static final long serialVersionUID = 1L; Reservation[] reservations = new Reservation[] {}; Locale locale; I18nBundle i18n; Map<Integer,ReservationTableColumn> columns = new LinkedHashMap<Integer, ReservationTableColumn>(); //String[] columns; public ReservationTableModel(Locale locale, I18nBundle i18n, Collection<? extends ReservationTableColumn> reservationColumnPlugins) { this.locale = locale; this.i18n = i18n; List<String> columnNames = new ArrayList<String>(); int column = 0; for (ReservationTableColumn col: reservationColumnPlugins) { columnNames.add( col.getColumnName()); columns.put( column, col); column++; } this.setColumnIdentifiers( columnNames.toArray()); } public void setReservations(Reservation[] events) { this.reservations = events; super.fireTableDataChanged(); } public Reservation getReservationAt(int row) { return this.reservations[row]; } public boolean isCellEditable(int row, int column) { return false; } public int getRowCount() { if ( reservations != null) return reservations.length; else return 0; } public Object getValueAt( int rowIndex, int columnIndex ) { Reservation event = reservations[rowIndex]; RaplaTableColumn<Reservation> tableColumn = columns.get( columnIndex); return tableColumn.getValue(event); } public Class<?> getColumnClass(int columnIndex) { RaplaTableColumn<Reservation> tableColumn = columns.get( columnIndex); return tableColumn.getColumnClass(); } }
Java
package org.rapla.plugin.tableview.internal; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; public final class EventCounter extends RaplaComponent implements SummaryExtension { public EventCounter(RaplaContext context) { super(context); } public void init(final JTable table, JPanel summaryRow) { final JLabel counter = new JLabel(); summaryRow.add( counter); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { int count = table.getSelectedRows().length; counter.setText( count+ " " + (count == 1 ? getString("reservation") : getString("reservations")) + " " ); } }); } }
Java
package org.rapla.plugin.tableview.internal; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; public final class AppointmentCounter extends RaplaComponent implements SummaryExtension { public AppointmentCounter(RaplaContext context) { super(context); } public void init(final JTable table, JPanel summaryRow) { final JLabel counter = new JLabel(); summaryRow.add( counter); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { int count = table.getSelectedRows().length; counter.setText( count+ " " + (count == 1 ? getString("appointment") : getString("appointments")) + " "); } }); } }
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
/*--------------------------------------------------------------------------* | 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.compactweekview; import java.awt.Font; import java.awt.Point; import java.text.MessageFormat; 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.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.swing.AbstractSwingCalendar; import org.rapla.components.calendarview.swing.SwingCompactWeekView; import org.rapla.components.calendarview.swing.ViewListener; import org.rapla.components.util.DateTools; 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.GroupAllocatablesStrategy; import org.rapla.plugin.abstractcalendar.RaplaBuilder; import org.rapla.plugin.abstractcalendar.RaplaCalendarViewListener; public class SwingCompactWeekCalendar extends AbstractRaplaSwingCalendar { public SwingCompactWeekCalendar(RaplaContext sm,CalendarModel settings, boolean editable) throws RaplaException { super( sm, settings, editable); } protected AbstractSwingCalendar createView(boolean showScrollPane) { 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 renderingInfo = dateRenderer.getRenderingInfo( date); if ( renderingInfo.getBackgroundColor() != null) { component.setBackground(renderingInfo.getBackgroundColor()); } if ( renderingInfo.getForegroundColor() != null) { component.setForeground(renderingInfo.getForegroundColor()); } component.setToolTipText(renderingInfo.getTooltipText()); } } else { String calendarWeek = MessageFormat.format(getString("calendarweek.abbreviation"), getStartDate()); component.setText( calendarWeek); } return component; } protected int getColumnCount() { return getDaysInView(); } }; return compactWeekView; } protected ViewListener createListener() throws RaplaException { RaplaCalendarViewListener listener = new RaplaCalendarViewListener(getContext(), model, view.getComponent()) { @Override public void selectionChanged(Date start, Date end) { if ( end.getTime()- start.getTime() == DateTools.MILLISECONDS_PER_DAY ) { Calendar cal = getRaplaLocale().createCalendar(); cal.setTime ( start ); int worktimeStartMinutes = getCalendarOptions().getWorktimeStartMinutes(); cal.set( Calendar.HOUR_OF_DAY, worktimeStartMinutes / 60); cal.set( Calendar.MINUTE, worktimeStartMinutes%60); start = cal.getTime(); end = new Date ( start.getTime() + 30 * DateTools.MILLISECONDS_PER_MINUTE ); } super.selectionChanged(start, end); } @Override protected Collection<Allocatable> getMarkedAllocatables() { final List<Allocatable> selectedAllocatables = getSortedAllocatables(); Set<Allocatable> allSelected = new HashSet<Allocatable>(); if ( selectedAllocatables.size() == 1 ) { allSelected.add(selectedAllocatables.get(0)); } int i= 0; int daysInView = view.getDaysInView(); for ( Allocatable alloc:selectedAllocatables) { boolean add = false; for (int slot = i*daysInView;slot< (i+1)*daysInView;slot++) { if ( view.isSelected(slot)) { add = true; } } if ( add ) { allSelected.add(alloc); } i++; } return allSelected; } @Override public void moved(Block block, Point p, Date newStart, int slotNr) { int index= slotNr / view.getDaysInView();//getIndex( selectedAllocatables, block ); if ( index < 0) { return; } try { final List<Allocatable> selectedAllocatables = getSortedAllocatables(); Allocatable newAlloc = selectedAllocatables.get(index); AbstractRaplaBlock raplaBlock = (AbstractRaplaBlock)block; Allocatable oldAlloc = raplaBlock.getGroupAllocatable(); if ( newAlloc != null && oldAlloc != null && !newAlloc.equals(oldAlloc)) { AppointmentBlock appointmentBlock = raplaBlock.getAppointmentBlock(); getReservationController().exchangeAllocatable(appointmentBlock, oldAlloc,newAlloc, newStart,getMainComponent(),p); } else { super.moved(block, p, newStart, slotNr); } } catch (RaplaException ex) { showException(ex, getMainComponent()); } } }; listener.setKeepTime( true); return listener; } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = super.createBuilder(); builder.setSmallBlocks( true ); String[] slotNames; final List<Allocatable> allocatables = getSortedAllocatables(); GroupAllocatablesStrategy strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ); strategy.setFixedSlotsEnabled( true); strategy.setResolveConflictsEnabled( false ); strategy.setAllocatables(allocatables) ; builder.setBuildStrategy( strategy ); slotNames = new String[ allocatables.size() ]; for (int i = 0; i <allocatables.size(); i++ ) { slotNames[i] = allocatables.get(i).getName( getRaplaLocale().getLocale() ); } builder.setSplitByAllocatables( true ); ((SwingCompactWeekView)view).setLeftColumnSize( 150); ((SwingCompactWeekView)view).setSlots( slotNames ); return builder; } 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()); // if ( !view.isEditable() ) { // view.setSlotSize( model.getSize()); // } else { // view.setSlotSize( 200 ); // } } public 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.compactweekview; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; public class CompactWeekViewPlugin implements PluginDescriptor<ClientServiceContainer> { public final static 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,CompactWeekViewFactory.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.compactweekview.server; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.plugin.compactweekview.CompactWeekViewPlugin; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.server.ServerServiceContainer; public class CompactWeekViewServerPlugin implements PluginDescriptor<ServerServiceContainer> { public void provideServices(ServerServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", CompactWeekViewPlugin.ENABLE_BY_DEFAULT)) return; container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,CompactHTMLWeekViewFactory.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.compactweekview.server; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.List; import java.util.Set; import org.rapla.components.calendarview.Block; 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.GroupAllocatablesStrategy; import org.rapla.plugin.abstractcalendar.RaplaBuilder; import org.rapla.plugin.abstractcalendar.server.AbstractHTMLCalendarPage; public class HTMLCompactWeekViewPage extends AbstractHTMLCalendarPage { public HTMLCompactWeekViewPage( 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(); } }; 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 { RaplaBuilder builder = super.createBuilder(); builder.setSmallBlocks( true ); builder.setSplitByAllocatables( true ); GroupAllocatablesStrategy strategy; if ( builder.getAllocatables().size() > 0) { strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ); strategy.setAllocatables( builder.getAllocatables() ) ; } else { // put all Allocatables in the same group strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ) { protected Collection<List<Block>> group(List<Block> blockList) { ArrayList<List<Block>> list = new ArrayList<List<Block>>(); list.add( blockList ); return list; } }; } strategy.setFixedSlotsEnabled( true ); builder.setBuildStrategy( strategy ); List<Allocatable> allocatables = builder.getAllocatables(); String[] slotNames = new String[ allocatables.size() ]; for (int i = 0; i < slotNames.length; i++ ) { Allocatable allocatable = allocatables.get( i ); String slotName = allocatable.getName( getRaplaLocale().getLocale() ); slotNames[i] = XMLWriter.encode( slotName ); } ((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.compactweekview.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 CompactHTMLWeekViewFactory extends RaplaComponent implements HTMLViewFactory { public final static String COMPACT_WEEK_VIEW = "week_compact"; public CompactHTMLWeekViewFactory( RaplaContext context ) { super( context ); } public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) { return new HTMLCompactWeekViewPage( context, model); } public String getViewId() { return COMPACT_WEEK_VIEW; } public String getName() { return getString(COMPACT_WEEK_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.compactweekview; 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 COMPACT_WEEK_VIEW = "week_compact"; public CompactWeekViewFactory( RaplaContext context ) { super( context ); } public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException { return new SwingCompactWeekCalendar( context, model, editable); } public String getViewId() { return COMPACT_WEEK_VIEW; } public String getName() { return getString(COMPACT_WEEK_VIEW); } 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 "B1"; } }
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.weekview; 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 WeekViewFactory extends RaplaComponent implements SwingViewFactory { public WeekViewFactory( RaplaContext context ) { super( context ); } public final static String WEEK_VIEW = "week"; public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException { return new SwingWeekCalendar( context, model, editable); } public String getViewId() { return WEEK_VIEW; } public String getName() { return getString(WEEK_VIEW); } Icon icon; public Icon getIcon() { if ( icon == null) { icon = Images.getIcon("/org/rapla/plugin/weekview/images/week.png"); } return icon; } public String getMenuSortKey() { return "B"; } }
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.weekview; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; public class WeekViewPlugin 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,WeekViewFactory.class); container.addContainerProvidedComponent(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,DayViewFactory.class); } }
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.weekview; import java.util.Calendar; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarOptions; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class SwingDayCalendar extends SwingWeekCalendar { public SwingDayCalendar( RaplaContext sm, CalendarModel model, boolean editable ) throws RaplaException { super( sm, model, editable ); } @Override protected int getDays( CalendarOptions calendarOptions) { return 1; } 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.weekview; 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 DayViewFactory extends RaplaComponent implements SwingViewFactory { public DayViewFactory( RaplaContext context ) { super( context ); } public final static String DAY_VIEW = "day"; public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException { return new SwingDayCalendar( context, model, editable); } public String getViewId() { return DAY_VIEW; } public String getName() { return getString(DAY_VIEW); } Icon icon; public Icon getIcon() { if ( icon == null) { icon = Images.getIcon("/org/rapla/plugin/weekview/images/day.png"); } return icon; } public String getMenuSortKey() { return "A"; } }
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.weekview.server; import java.util.Calendar; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarOptions; import org.rapla.framework.RaplaContext; public class HTMLDayViewPage extends HTMLWeekViewPage { public HTMLDayViewPage( RaplaContext context, CalendarModel calendarModel ) { super( context, calendarModel ); } @Override protected int getDays(CalendarOptions calendarOptions) { return 1; } 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.weekview.server; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.server.ServerServiceContainer; public class WeekViewServerPlugin implements PluginDescriptor<ServerServiceContainer> { static boolean ENABLE_BY_DEFAULT = true; public String toString() { return "Week View"; } public void provideServices(ServerServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,HTMLWeekViewFactory.class); container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,HTMLDayViewFactory.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.weekview.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 HTMLDayViewFactory extends RaplaComponent implements HTMLViewFactory { public HTMLDayViewFactory( RaplaContext context ) { super( context ); } public final static String DAY_VIEW = "day"; public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) { return new HTMLDayViewPage( context, model); } public String getViewId() { return DAY_VIEW; } public String getName() { return getString(DAY_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.weekview.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 HTMLWeekViewFactory extends RaplaComponent implements HTMLViewFactory { public HTMLWeekViewFactory( RaplaContext context ) { super( context ); } public final static String WEEK_VIEW = "week"; public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) throws RaplaException { return new HTMLWeekViewPage( context, model); } public String getViewId() { return WEEK_VIEW; } public String getName() { return getString(WEEK_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.weekview.server; import java.text.MessageFormat; import java.util.Calendar; import java.util.HashSet; import java.util.Set; import org.rapla.components.calendarview.html.AbstractHTMLView; import org.rapla.components.calendarview.html.HTMLWeekView; 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.GroupAllocatablesStrategy; import org.rapla.plugin.abstractcalendar.RaplaBuilder; import org.rapla.plugin.abstractcalendar.server.AbstractHTMLCalendarPage; public class HTMLWeekViewPage extends AbstractHTMLCalendarPage { public HTMLWeekViewPage( RaplaContext context, CalendarModel calendarModel ) { super( context, calendarModel ); } protected AbstractHTMLView createCalendarView() { HTMLWeekView weekView = new HTMLWeekView() { public void rebuild() { setWeeknumber(MessageFormat.format(getString("calendarweek.abbreviation"), getStartDate())); super.rebuild(); } }; return weekView; } protected void configureView() { HTMLWeekView weekView = (HTMLWeekView) view; CalendarOptions opt = getCalendarOptions(); weekView.setRowsPerHour( opt.getRowsPerHour() ); weekView.setWorktimeMinutes(opt.getWorktimeStartMinutes(), opt.getWorktimeEndMinutes() ); weekView.setFirstWeekday( opt.getFirstDayOfWeek()); int days = getDays(opt); weekView.setDaysInView( days); Set<Integer> excludeDays = opt.getExcludeDays(); if ( days <3) { excludeDays = new HashSet<Integer>(); } weekView.setExcludeDays( excludeDays ); } /** overide this for daily views*/ protected int getDays(CalendarOptions calendarOptions) { return calendarOptions.getDaysInWeekview(); } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = super.createBuilder(); GroupAllocatablesStrategy strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ); boolean compactColumns = getCalendarOptions().isCompactColumns() || builder.getAllocatables().size() ==0 ; strategy.setFixedSlotsEnabled( !compactColumns); strategy.setResolveConflictsEnabled( true ); builder.setBuildStrategy( strategy ); return builder; } public int getIncrementSize() { return Calendar.WEEK_OF_YEAR; } }
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.weekview; import java.awt.Font; import java.text.MessageFormat; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.swing.JComponent; import javax.swing.JLabel; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateRenderer; import org.rapla.components.calendar.DateRenderer.RenderingInfo; import org.rapla.components.calendar.DateRendererAdapter; import org.rapla.components.calendarview.swing.AbstractSwingCalendar; import org.rapla.components.calendarview.swing.SwingWeekView; 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; public class SwingWeekCalendar extends AbstractRaplaSwingCalendar { public SwingWeekCalendar( RaplaContext context, CalendarModel model, boolean editable ) throws RaplaException { super( context, model, editable ); } protected AbstractSwingCalendar createView(boolean showScrollPane) { final DateRenderer dateRenderer; final DateRendererAdapter dateRendererAdapter; dateRenderer = getService(DateRenderer.class); dateRendererAdapter = new DateRendererAdapter(dateRenderer, getRaplaLocale().getTimeZone(), getRaplaLocale().getLocale()); final SwingWeekView wv = new SwingWeekView( showScrollPane ) { protected JComponent createSlotHeader(Integer column) { JLabel component = (JLabel) super.createSlotHeader(column); 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 = dateRendererAdapter.getRenderingInfo(date); if (info.getBackgroundColor() != null) { component.setBackground(info.getBackgroundColor()); } if (info.getForegroundColor() != null) { component.setForeground(info.getForegroundColor()); } if (info.getTooltipText() != null) { component.setToolTipText(info.getTooltipText()); } } return component; } @Override public void rebuild() { // update week weekTitle.setText(MessageFormat.format(getString("calendarweek.abbreviation"), getStartDate())); super.rebuild(); } }; return wv; } public void dateChanged(DateChangeEvent evt) { super.dateChanged( evt ); ((SwingWeekView)view).scrollDateVisible( evt.getDate()); } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = super.createBuilder(); return builder; } @Override protected void configureView() { SwingWeekView view = (SwingWeekView) this.view; CalendarOptions calendarOptions = getCalendarOptions(); int rowsPerHour = calendarOptions.getRowsPerHour(); int startMinutes = calendarOptions.getWorktimeStartMinutes(); int endMinutes = calendarOptions.getWorktimeEndMinutes(); int hours = Math.max(1, (endMinutes - startMinutes) / 60); view.setRowsPerHour( rowsPerHour ); if ( rowsPerHour == 1 ) { if ( hours < 10) { view.setRowSize( 80); } else if ( hours < 15) { view.setRowSize( 60); } else { view.setRowSize( 30); } } else if ( rowsPerHour == 2 ) { if ( hours < 10) { view.setRowSize( 40); } else { view.setRowSize( 20); } } else if ( rowsPerHour >= 4 ) { view.setRowSize( 15); } view.setWorktimeMinutes(startMinutes, endMinutes); int days = getDays( calendarOptions); view.setDaysInView( days); Set<Integer> excludeDays = calendarOptions.getExcludeDays(); if ( days <3) { excludeDays = new HashSet<Integer>(); } view.setExcludeDays( excludeDays ); view.setFirstWeekday( calendarOptions.getFirstDayOfWeek()); view.setToDate(model.getSelectedDate()); // if ( !view.isEditable() ) { // view.setSlotSize( model.getSize()); // } else { // view.setSlotSize( 135 ); // } } /** overide this for dayly views*/ protected int getDays(CalendarOptions calendarOptions) { return calendarOptions.getDaysInWeekview(); } public void scrollToStart() { ((SwingWeekView)view).scrollToStart(); } public int getIncrementSize() { return Calendar.WEEK_OF_YEAR; } }
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.dayresource; import java.awt.Point; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.JComponent; import javax.swing.JLabel; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.CalendarView; import org.rapla.components.calendarview.swing.AbstractSwingCalendar; import org.rapla.components.calendarview.swing.SelectionHandler.SelectionStrategy; import org.rapla.components.calendarview.swing.SwingWeekView; import org.rapla.components.calendarview.swing.ViewListener; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.AbstractRaplaBlock; import org.rapla.plugin.abstractcalendar.GroupAllocatablesStrategy; import org.rapla.plugin.abstractcalendar.RaplaBuilder; import org.rapla.plugin.abstractcalendar.RaplaCalendarViewListener; import org.rapla.plugin.weekview.SwingDayCalendar; public class SwingDayResourceCalendar extends SwingDayCalendar { public SwingDayResourceCalendar( RaplaContext sm, CalendarModel model, boolean editable ) throws RaplaException { super( sm, model, editable ); } protected AbstractSwingCalendar createView(boolean showScrollPane) { /** renderer for dates in weekview */ SwingWeekView wv = new SwingWeekView( showScrollPane ) { { selectionHandler.setSelectionStrategy(SelectionStrategy.BLOCK); } @Override protected JComponent createSlotHeader(Integer column) { JLabel component = (JLabel) super.createSlotHeader(column); try { List<Allocatable> sortedAllocatables = getSortedAllocatables(); Allocatable allocatable = sortedAllocatables.get(column); String name = allocatable.getName( getLocale()); component.setText( name); component.setToolTipText(name); } catch (RaplaException e) { } return component; } @Override protected int getColumnCount() { try { Allocatable[] selectedAllocatables =model.getSelectedAllocatables(); return selectedAllocatables.length; } catch (RaplaException e) { return 0; } } @Override public void rebuild() { super.rebuild(); String dateText = getRaplaLocale().formatDateShort(getStartDate()); weekTitle.setText( dateText); } }; return wv; } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = super.createBuilder(); builder.setSplitByAllocatables( true ); final List<Allocatable> allocatables = getSortedAllocatables(); builder.selectAllocatables(allocatables); GroupAllocatablesStrategy strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ) { @Override protected Map<Block, Integer> getBlockMap(CalendarView wv, List<Block> blocks) { if (allocatables != null) { Map<Block,Integer> map = new LinkedHashMap<Block, Integer>(); for (Block block:blocks) { int index = getIndex(allocatables, block); if ( index >= 0 ) { map.put( block, index ); } } return map; } else { return super.getBlockMap(wv, blocks); } } }; strategy.setResolveConflictsEnabled( true ); builder.setBuildStrategy( strategy ); return builder; } protected ViewListener createListener() throws RaplaException { return new RaplaCalendarViewListener(getContext(), model, view.getComponent()) { @Override protected Collection<Allocatable> getMarkedAllocatables() { final List<Allocatable> selectedAllocatables = getSortedAllocatables(); Set<Allocatable> allSelected = new HashSet<Allocatable>(); if ( selectedAllocatables.size() == 1 ) { allSelected.add(selectedAllocatables.get(0)); } for ( int i =0 ;i< selectedAllocatables.size();i++) { if ( view.isSelected(i)) { allSelected.add(selectedAllocatables.get(i)); } } return allSelected; } @Override public void moved(Block block, Point p, Date newStart, int slotNr) { int column= slotNr;//getIndex( selectedAllocatables, block ); if ( column < 0) { return; } try { final List<Allocatable> selectedAllocatables = getSortedAllocatables(); Allocatable newAlloc = selectedAllocatables.get(column); AbstractRaplaBlock raplaBlock = (AbstractRaplaBlock)block; Allocatable oldAlloc = raplaBlock.getGroupAllocatable(); if ( newAlloc != null && oldAlloc != null && !newAlloc.equals(oldAlloc)) { AppointmentBlock appointmentBlock= raplaBlock.getAppointmentBlock(); getReservationController().exchangeAllocatable(appointmentBlock, oldAlloc,newAlloc,newStart, getMainComponent(),p); } else { super.moved(block, p, newStart, slotNr); } } catch (RaplaException ex) { showException(ex, getMainComponent()); } } }; } private int getIndex(final List<Allocatable> allocatables, Block block) { AbstractRaplaBlock b = (AbstractRaplaBlock)block; Allocatable a = b.getGroupAllocatable(); int index = a != null ? allocatables.indexOf( a ) : -1; return index; } }
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.dayresource; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; public class DayResourceViewPlugin implements PluginDescriptor<ClientServiceContainer> { final public static boolean ENABLE_BY_DEFAULT = true; public void provideServices(ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,DayResourceViewFactory.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.dayresource; 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 DayResourceViewFactory extends RaplaComponent implements SwingViewFactory { public DayResourceViewFactory( RaplaContext context ) { super( context ); } public final static String DAY_RESOURCE_VIEW = "day_resource"; public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException { return new SwingDayResourceCalendar( context, model, editable); } public String getViewId() { return DAY_RESOURCE_VIEW; } public String getName() { return getString(DAY_RESOURCE_VIEW); } Icon icon; public Icon getIcon() { if ( icon == null) { icon = Images.getIcon("/org/rapla/plugin/dayresource/images/day_resource.png"); } return icon; } public String getMenuSortKey() { return "A"; } }
Java
package org.rapla.plugin.dayresource.server; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.CalendarView; import org.rapla.components.calendarview.html.AbstractHTMLView; import org.rapla.components.calendarview.html.HTMLWeekView; import org.rapla.entities.domain.Allocatable; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.AbstractRaplaBlock; import org.rapla.plugin.abstractcalendar.GroupAllocatablesStrategy; import org.rapla.plugin.abstractcalendar.RaplaBuilder; import org.rapla.plugin.weekview.server.HTMLDayViewPage; public class HTMLDayResourcePage extends HTMLDayViewPage { public HTMLDayResourcePage(RaplaContext context, CalendarModel calendarModel) { super(context, calendarModel); } protected AbstractHTMLView createCalendarView() { HTMLWeekView weekView = new HTMLWeekView(){ @Override protected String createColumnHeader(int i) { try { Allocatable allocatable = getSortedAllocatables().get(i); return allocatable.getName( getLocale()); } catch (RaplaException e) { return ""; } } @Override protected int getColumnCount() { try { Allocatable[] selectedAllocatables =model.getSelectedAllocatables(); return selectedAllocatables.length; } catch (RaplaException e) { return 0; } } public void rebuild() { setWeeknumber(getRaplaLocale().formatDateShort(getStartDate())); super.rebuild(); } }; return weekView; } private int getIndex(final List<Allocatable> allocatables, Block block) { AbstractRaplaBlock b = (AbstractRaplaBlock)block; Allocatable a = b.getGroupAllocatable(); int index = a != null ? allocatables.indexOf( a ) : -1; return index; } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = super.createBuilder(); final List<Allocatable> allocatables = getSortedAllocatables(); builder.setSplitByAllocatables( true ); builder.selectAllocatables(allocatables); GroupAllocatablesStrategy strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ) { @Override protected Map<Block, Integer> getBlockMap(CalendarView wv, List<Block> blocks) { if (allocatables != null) { Map<Block,Integer> map = new LinkedHashMap<Block, Integer>(); for (Block block:blocks) { int index = getIndex(allocatables, block); if ( index >= 0 ) { map.put( block, index ); } } return map; } else { return super.getBlockMap(wv, blocks); } } }; strategy.setResolveConflictsEnabled( true ); builder.setBuildStrategy( strategy ); return builder; } }
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.dayresource.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 DayResourceHTMLViewFactory extends RaplaComponent implements HTMLViewFactory { public DayResourceHTMLViewFactory( RaplaContext context ) { super( context ); } public final static String DAY_RESOURCE_VIEW = "day_resource"; public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) throws RaplaException { return new HTMLDayResourcePage( context, model); } public String getViewId() { return DAY_RESOURCE_VIEW; } public String getName() { return getString(DAY_RESOURCE_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.dayresource.server; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.plugin.dayresource.DayResourceViewPlugin; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.server.ServerServiceContainer; public class DayResourceViewServerPlugin implements PluginDescriptor<ServerServiceContainer> { public void provideServices(ServerServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", DayResourceViewPlugin.ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,DayResourceHTMLViewFactory.class); } }
Java
package org.rapla.plugin.rightsreport; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeModel; import org.rapla.entities.Category; import org.rapla.entities.User; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.TreeFactory; import org.rapla.gui.toolkit.RaplaTree; public class RaplaRightsReport extends RaplaGUIComponent implements ItemListener, TreeSelectionListener, DocumentListener { final Category rootCategory = getQuery().getUserGroupsCategory(); // definition of different panels JPanel mainPanel; JPanel northPanel; JPanel centerPanel; JComboBox cbView; View view = View.USERGROUPS; // hierarchical tree RaplaTree selectionTreeTable; // list for the presentation of the assigned elements DefaultListModel assignedElementsListModel; JList assignedElementsList; JScrollPane assignedElementsScrollPane; // text field for filter JTextField filterTextField; Collection<Object> notAllList = new HashSet<Object>(); public RaplaRightsReport(RaplaContext context) throws RaplaException { super(context); // creation of different panels mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); northPanel = new JPanel(); northPanel.setLayout(new GridLayout(0, 1)); centerPanel = new JPanel(); centerPanel.setLayout(new GridLayout(0, 2)); // add northPanel and centerPanel to the mainPanel - using BoarderLayout mainPanel.add(northPanel, BorderLayout.NORTH); mainPanel.add(centerPanel, BorderLayout.CENTER); // creation of the ComboBox to choose one of the views // adding the ComboBox to the northPanel @SuppressWarnings("unchecked") JComboBox jComboBox = new JComboBox(new String[] {getString("groups"), getString("users")}); cbView = jComboBox; cbView.addItemListener(this); northPanel.add(cbView); // creation of the filter-text field and adding this object (this) as // DocumentListener // note: DocumentListener registers all changes filterTextField = new JTextField(); filterTextField.getDocument().addDocumentListener(this); northPanel.add(filterTextField); // creation of the tree selectionTreeTable = new RaplaTree(); selectionTreeTable.setMultiSelect( true); selectionTreeTable.getTree().setCellRenderer(getTreeFactory().createRenderer()); selectionTreeTable.getTree().addTreeSelectionListener(this); // including the tree in ScrollPane and adding this to the GUI centerPanel.add(selectionTreeTable); // creation of the list for the assigned elements assignedElementsList = new JList(); assignedElementsListModel = new DefaultListModel(); setRenderer(); // including the list in ScrollPaneListe and adding this to the GUI assignedElementsScrollPane = new JScrollPane(assignedElementsList); centerPanel.add(assignedElementsScrollPane); } @SuppressWarnings("unchecked") private void setRenderer() { assignedElementsList.setCellRenderer(new CategoryListCellRenderer()); } public JComponent getComponent() { return mainPanel; } public void show() { // set default values view = View.USERGROUPS; filterTextField.setText(""); loadView(); } // provides a TreeFactory -> interface for facade, provides the tree // (groups/users) private TreeFactory getTreeFactory() { return getService(TreeFactory.class); } // change of the ComboBox -> new view has been chosen public void itemStateChanged(ItemEvent e) { JComboBox cbViewSelection = (JComboBox) e.getSource(); // definition of the internal variable for storing the view if (cbViewSelection.getSelectedIndex() == 0) view = View.USERGROUPS; else if (cbViewSelection.getSelectedIndex() == 1) view = View.USERS; // build of the screen according to the view loadView(); } // selection of one or more elements in the tree @SuppressWarnings("unchecked") public void valueChanged(TreeSelectionEvent event) { try { assignedElementsListModel.clear(); List<Object> selectedElements = selectionTreeTable.getSelectedElements(); Set<Object> commonElements = new TreeSet<Object>(); notAllList.clear(); User[] allUsers = getQuery().getUsers(); boolean first = true; for ( Object sel:selectedElements) { List<Object> elementsToAdd = new ArrayList<Object>(); if ( sel instanceof User) { User user= (User) sel; for ( Category cat:user.getGroups()) { elementsToAdd.add( cat); } } if ( sel instanceof Category) { Category category = (Category) sel; for (User user : allUsers) { if (user.belongsTo(category)) elementsToAdd.add(user); } } for ( Object toAdd: elementsToAdd) { if (!first && !commonElements.contains(toAdd)) { notAllList.add( toAdd); } commonElements.add( toAdd); } first = false; } for (Object element : commonElements) { assignedElementsListModel.addElement(element); } assignedElementsList.setModel(assignedElementsListModel); } catch (RaplaException ex) { showException(ex, getMainComponent()); } } // this method builds the current screen (GUI) according to the variable // "view" private void loadView() { // reset the filter filterTextField.setText(""); filter(); } // search categories with specified pattern in categoryname (only child of // rootCategory) private List<Category> searchCategoryName(Category rootCategory, String pattern) { List<Category> categories = new ArrayList<Category>(); Locale locale = getLocale(); // loop all child of rootCategory for (Category category : rootCategory.getCategories()) { // is category a leaf? if (category.getCategories().length == 0) { // does the specified pattern matches with the the categoryname? if (Pattern.matches(pattern.toLowerCase(locale), category.getName(locale).toLowerCase(locale))) categories.add(category); } else { // get all child with a matching name (recursive) categories.addAll(searchCategoryName(category, pattern)); } } sortCategories(categories); return categories; } @SuppressWarnings("unchecked") public void sortCategories(List<Category> categories) { Collections.sort(categories); } // search users with specified pattern in username private List<User> searchUserName(String pattern) throws RaplaException { List<User> users = new ArrayList<User>(); Locale locale = getLocale(); // get all users for (User user : getQuery().getUsers()) { // does the specified pattern matches with the the username? if (Pattern.matches(pattern.toLowerCase(locale), user.getUsername() .toLowerCase(locale))) users.add(user); } sort(users); return users; } @SuppressWarnings("unchecked") public void sort(List<User> users) { Collections.sort(users); } private void filter() { // add regular expressions to filter pattern String pattern = ".*" + filterTextField.getText() + ".*"; try { selectionTreeTable.getTree().clearSelection(); TreeModel selectionModel = null; switch (view) { case USERGROUPS: // search all categories for the specified pattern and add // them to the list List<Category> categoriesToMatch = searchCategoryName(rootCategory,pattern); selectionModel = getTreeFactory().createModel(categoriesToMatch, false); break; case USERS: User[] users =searchUserName(pattern).toArray( User.USER_ARRAY); selectionModel = getTreeFactory().createModelFlat( users); // change the name of the root node in "user" ((DefaultMutableTreeNode) (selectionModel.getRoot())).setUserObject(getString("users")); break; } selectionTreeTable.getTree().setModel(selectionModel); assignedElementsListModel.clear(); } catch (RaplaException ex) { showException(ex, getMainComponent()); } } public void changedUpdate(DocumentEvent e) { } public void insertUpdate(DocumentEvent e) { // filter elements filter(); } public void removeUpdate(DocumentEvent e) { // filter elements filter(); } public enum View { USERS, USERGROUPS; } // ListCellRenderer to display the right name of categories based on locale class CategoryListCellRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 1L; public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Object userObject = value; if (value != null && value instanceof Category) { // if element in cell is a category: set the name of the // category value = ((Category) value).getName(getLocale()); } Component component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); Font f; if (notAllList.contains( userObject)) { f =component.getFont().deriveFont(Font.ITALIC); } else { f =component.getFont().deriveFont(Font.BOLD); } component.setFont(f); return component; } } }
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.rightsreport; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.TypedComponentRole; import org.rapla.plugin.periodcopy.PeriodCopyPlugin; public class RightsReportPlugin 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( RaplaClientExtensionPoints.ADMIN_MENU_EXTENSION_POINT, RightsReportMenu.class); } }
Java
package org.rapla.plugin.rightsreport; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Icon; import javax.swing.MenuElement; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.IdentifiableMenuEntry; import org.rapla.gui.toolkit.RaplaMenuItem; public class RightsReportMenu extends RaplaGUIComponent implements IdentifiableMenuEntry, ActionListener{ private RaplaMenuItem report; final String name = getString("user") +"/"+ getString("groups") + " "+getString("report") ; public RightsReportMenu(RaplaContext context) { super(context); report = new RaplaMenuItem("report"); report.getMenuElement().setText( name); final Icon icon = getIcon("icon.info_small"); report.getMenuElement().setIcon( icon); report.addActionListener( this); } public String getId() { return "report"; } @Override public MenuElement getMenuElement() { return report; } public void actionPerformed( ActionEvent e ) { try { RaplaRightsReport report = new RaplaRightsReport( getContext()); DialogUI dialog = DialogUI.create( getContext(),getMainComponent(),true, report.getComponent(), new String[] {getString("ok")}); dialog.setTitle( name); dialog.setSize( 650, 550); report.show(); dialog.startNoPack(); } catch (RaplaException ex) { showException( ex, getMainComponent()); } } }
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) 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
/*--------------------------------------------------------------------------* | 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
/*--------------------------------------------------------------------------* | 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
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) 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; 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.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.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.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; 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
package org.rapla.bootstrap; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; @SuppressWarnings({ "rawtypes", "unchecked" }) public class CustomJettyStarter { public static final String USAGE = new String ( "Usage : \n" + "[-?|-c PATH_TO_CONFIG_FILE] [ACTION]\n" + "Possible actions:\n" + " standalone : Starts the rapla-gui with embedded server (this is the default)\n" + " server : Starts the rapla-server \n" + " client : Starts the rapla-client \n" + " import : Import from file into the database\n" + " export : Export from database into file\n" + "the config file is jetty.xml generally located in etc/jetty.xml" ); public static void main(final String[] args) throws Exception { String property = System.getProperty("org.rapla.disableHostChecking"); if ( Boolean.parseBoolean( property)) { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); } new CustomJettyStarter().start( args); } Class ServerC ; Class ConfigurationC; Class ConnectorC; Class ResourceC; Class EnvEntryC; Class LifeCyleC; Class LifeCyleListenerC; // Class DeploymentManagerC; // Class ContextHandlerC; // Class WebAppContextC; // Class AppC; // Class AppProviderC; // Class ServletHandlerC; // Class ServletHolderC; ClassLoader loader; Method stopMethod; Logger logger = Logger.getLogger(getClass().getName()); String startupMode; String startupUser; /** 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++ ) { String arg = args[i].toLowerCase(); if ( arg.equals( "-c" ) ) { if ( i + 1 == args.length ) { bInvalid = true; break; } config = args[++i]; continue; } if ( arg.equals( "-?" ) ) { bInvalid = true; break; } if ( arg.substring( 0, 1 ).equals( "-" ) ) { bInvalid = true; break; } if (action == null) { action = arg; } } if ( bInvalid ) { return null; } if ( config != null ) map.put( "config", config ); if ( action != null ) map.put( "action", action ); return map; } public void start(final String[] arguments) throws Exception { Map<String, String> parseParams = parseParams(arguments); String configFiles = parseParams.get("config"); if ( configFiles == null) { configFiles = "etc/jetty.xml"; String property = System.getProperty("jetty.home"); if (property != null) { if ( !property.endsWith("/")) { property += "/"; } configFiles = property + configFiles; } } startupMode =System.getProperty("org.rapla.startupMode"); if (startupMode == null) { startupMode = parseParams.get("action"); } if (startupMode == null) { startupMode = "standalone"; } startupUser =System.getProperty("org.rapla.startupUser"); boolean isServer = startupMode.equals("server"); final boolean removeConnectors = !isServer; if ( isServer) { System.setProperty( "java.awt.headless", "true" ); } loader = Thread.currentThread().getContextClassLoader(); Class<?> LoadingProgressC= null; final Object progressBar; if ( startupMode.equals("standalone" ) || startupMode.equals("client" )) { LoadingProgressC = loader.loadClass("org.rapla.bootstrap.LoadingProgress"); progressBar = LoadingProgressC.getMethod("getInstance").invoke(null); LoadingProgressC.getMethod("start", int.class, int.class).invoke( progressBar, 1,4); } else { progressBar = null; } final String contextPath = System.getProperty("org.rapla.context",null); final String downloadUrl = System.getProperty("org.rapla.serverUrl",null); final String[] jettyArgs = configFiles.split(","); final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); AccessController.doPrivileged(new PrivilegedAction<Object>() { boolean started; boolean shutdownShouldRun; public Object run() { try { Properties properties = new Properties(); // Add System Properties Enumeration<?> ensysprop = System.getProperties().propertyNames(); while (ensysprop.hasMoreElements()) { String name = (String)ensysprop.nextElement(); properties.put(name,System.getProperty(name)); } //loader.loadClass("org.rapla.bootstrap.JNDIInit").newInstance(); ServerC =loader.loadClass("org.eclipse.jetty.server.Server"); stopMethod = ServerC.getMethod("stop"); ConfigurationC =loader.loadClass("org.eclipse.jetty.xml.XmlConfiguration"); ConnectorC = loader.loadClass("org.eclipse.jetty.server.Connector"); ResourceC = loader.loadClass("org.eclipse.jetty.util.resource.Resource"); EnvEntryC = loader.loadClass("org.eclipse.jetty.plus.jndi.EnvEntry"); LifeCyleC = loader.loadClass( "org.eclipse.jetty.util.component.LifeCycle"); LifeCyleListenerC = loader.loadClass( "org.eclipse.jetty.util.component.LifeCycle$Listener"); // DeploymentManagerC = loader.loadClass("org.eclipse.jetty.deploy.DeploymentManager"); // ContextHandlerC = loader.loadClass("org.eclipse.jetty.server.handler.ContextHandler"); // WebAppContextC = loader.loadClass("org.eclipse.jetty.webapp.WebAppContext"); // AppC = loader.loadClass("org.eclipse.jetty.deploy.App"); // AppProviderC = loader.loadClass("org.eclipse.jetty.deploy.AppProvider"); // ServletHandlerC = loader.loadClass("org.eclipse.jetty.servlet.ServletHandler"); // ServletHolderC = loader.loadClass("org.eclipse.jetty.servlet.ServletHolder"); // For all arguments, load properties or parse XMLs Object last = null; Object[] obj = new Object[jettyArgs.length]; for (int i = 0; i < jettyArgs.length; i++) { String configFile = jettyArgs[i]; Object newResource = ResourceC.getMethod("newResource",String.class).invoke(null,configFile); if (configFile.toLowerCase(Locale.ENGLISH).endsWith(".properties")) { properties.load((InputStream)ResourceC.getMethod("getInputStream").invoke(newResource)); } else { URL url = (URL)ResourceC.getMethod("getURL").invoke(newResource); Object configuration = ConfigurationC.getConstructor(URL.class).newInstance(url); if (last != null) ((Map)ConfigurationC.getMethod("getIdMap").invoke(configuration)).putAll((Map)ConfigurationC.getMethod("getIdMap").invoke(last)); if (properties.size() > 0) { Map<String, String> props = new HashMap<String, String>(); for (Object key : properties.keySet()) { props.put(key.toString(),String.valueOf(properties.get(key))); } ((Map)ConfigurationC.getMethod("getProperties").invoke( configuration)).putAll( props); } Object configuredObject = ConfigurationC.getMethod("configure").invoke(configuration); Integer port = null; if ( ServerC.isInstance(configuredObject)) { final Object server = configuredObject; Object[] connectors = (Object[]) ServerC.getMethod("getConnectors").invoke(server); for (Object c: connectors) { port = (Integer) ConnectorC.getMethod("getPort").invoke(c); if ( removeConnectors) { ServerC.getMethod("removeConnector", ConnectorC).invoke(server, c); } } final Method shutdownMethod = ServerC.getMethod("stop"); InvocationHandler proxy = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); if ( name.toLowerCase(Locale.ENGLISH).indexOf("started")>=0) { if ( shutdownShouldRun) { shutdownMethod.invoke( server); } else { started = true; } } return null; } }; Class<?>[] interfaces = new Class[] {LifeCyleListenerC}; Object proxyInstance = Proxy.newProxyInstance(loader, interfaces, proxy); ServerC.getMethod("addLifeCycleListener", LifeCyleListenerC).invoke(server, proxyInstance); Constructor newJndi = EnvEntryC.getConstructor(String.class,Object.class); Method addBean = ServerC.getMethod("addBean", Object.class); if ( !startupMode.equals("server")) { addBean.invoke(server, newJndi.newInstance("rapla_startup_user", startupUser)); addBean.invoke(server, newJndi.newInstance("rapla_startup_mode", startupMode)); addBean.invoke(server, newJndi.newInstance("rapla_download_url", downloadUrl)); addBean.invoke(server, newJndi.newInstance("rapla_instance_counter", new ArrayList<String>())); if ( contextPath != null) { addBean.invoke(server, newJndi.newInstance("rapla_startup_context", contextPath)); } } addBean.invoke(server, newJndi.newInstance("rapla_startup_port", port)); { Runnable shutdownCommand = new Runnable() { public void run() { if ( started) { try { shutdownMethod.invoke(server); } catch (Exception ex) { logger.log(Level.SEVERE,ex.getMessage(),ex); } } else { shutdownShouldRun = true; } } }; addBean.invoke(server, newJndi.newInstance("rapla_shutdown_command", shutdownCommand)); } } obj[i] = configuredObject; last = configuration; } } // For all objects created by XmlConfigurations, start them if they are lifecycles. for (int i = 0; i < obj.length; i++) { if (LifeCyleC.isInstance(obj[i])) { Object o =obj[i]; if ( !(Boolean)LifeCyleC.getMethod("isStarted").invoke(o)) { LifeCyleC.getMethod("start").invoke(o); } } } } catch (Exception e) { exception.set(e); } return null; } }); if ( progressBar != null && LoadingProgressC != null) { LoadingProgressC.getMethod("close").invoke( progressBar); } Throwable th = exception.get(); if (th != null) { if (th instanceof RuntimeException) throw (RuntimeException)th; else if (th instanceof Exception) throw (Exception)th; else if (th instanceof Error) throw (Error)th; throw new Error(th); } } // void doStart(final Object server, String passedContext) // { // try // { // Object bean = ServerC.getMethod("getBean", Class.class).invoke(server, DeploymentManagerC); // Map<String, Object> raplaServletMap = new LinkedHashMap<String, Object>(); // Collection<?> apps = (Collection<?>) DeploymentManagerC.getMethod("getApps").invoke(bean); // for (Object handler:apps) // { // // Object context_ = AppC.getMethod("getContextHandler").invoke(handler); // String contextPath = (String) ContextHandlerC.getMethod("getContextPath").invoke(context_); // Object[] servlets = (Object[]) ContextHandlerC.getMethod("getChildHandlersByClass", Class.class).invoke(context_, ServletHandlerC); // for ( Object childHandler : servlets) // { // Object servlet = ServletHandlerC.getMethod("getServlet",String.class).invoke( childHandler,"RaplaServer"); // if ( servlet != null) // { // raplaServletMap.put(contextPath, servlet); // } // } // } // // Set<String> keySet = raplaServletMap.keySet(); // if ( keySet.size() == 0) // { // logger.log(Level.SEVERE,"No rapla context found in jetty container."); // stopMethod.invoke(server); // } // else if ( keySet.size() > 1 && passedContext == null) // { // logger.log(Level.SEVERE,"Multiple context found in jetty container " + keySet +" Please specify one via -Dorg.rapla.context=REPLACE_WITH_CONTEXT"); // stopMethod.invoke(server); // } // else // { // //Class MainServletC = loader.loadClass("org.rapla.MainServlet"); // Object servletHolder = passedContext == null ? raplaServletMap.values().iterator().next(): raplaServletMap.get( passedContext); // if ( servletHolder != null) // { // // Object servlet = ServletHolderC.getMethod("getServlet").invoke( servletHolder); // PropertyChangeListener castedHack = (PropertyChangeListener)servlet; // castedHack.propertyChange( new PropertyChangeEvent(server, startupMode, null, shutdownCommand)); // } // else // { // logger.log(Level.SEVERE,"Rapla context ' " + passedContext +"' not found."); // stopMethod.invoke(server); // } // } // } // catch (Exception ex) // { // logger.log(Level.SEVERE,ex.getMessage(),ex); // try { // stopMethod.invoke(server); // } catch (Exception e) { // logger.log(Level.SEVERE,e.getMessage(),e); // } // } // } }
Java
package org.rapla.bootstrap; import java.io.File; import java.io.IOException; public class RaplaJettyLoader { public static void main(String[] args) throws IOException { String baseDir = System.getProperty("jetty.home"); if ( baseDir == null) { baseDir = "."; System.setProperty( "jetty.home", new File(baseDir ).getCanonicalPath() ); } for ( String arg:args) { if ( arg != null && arg.toLowerCase().equals("server")) { System.setProperty( "java.awt.headless", "true" ); } } String dirList = "lib,lib/logging,lib/ext,resources"; String classname = "org.rapla.bootstrap.CustomJettyStarter"; String methodName = "main"; //System.setProperty( "java.awt.headless", "true" ); String test = "Starting rapla from " + System.getProperty("jetty.home"); System.out.println(test ); RaplaLoader.start( baseDir,dirList, classname,methodName, new Object[] {args }); } }
Java
package org.rapla.bootstrap; import java.io.IOException; public class RaplaClientLoader { public static void main(String[] args) throws IOException { RaplaJettyLoader.main(new String[] {"client"}); } }
Java
package org.rapla.bootstrap; import java.io.IOException; public class RaplaServerLoader { public static void main(String[] args) throws IOException { System.setProperty( "java.awt.headless", "true" ); RaplaJettyLoader.main(new String[] {"server"}); } }
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.bootstrap; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker; import java.awt.Toolkit; import java.awt.image.ImageObserver; import java.net.URL; import javax.swing.JProgressBar; final public class LoadingProgress { static LoadingProgress instance; JProgressBar progressBar; Frame frame; ImageObserver observer; Image image; Component canvas; int maxValue; static public LoadingProgress getInstance() { if ( instance == null) { instance = new LoadingProgress(); } return instance; } public boolean isStarted() { return frame != null; } /** this method creates the progress bar */ public void start(int startValue, int maxValue) { this.maxValue = maxValue; frame = new Frame() { private static final long serialVersionUID = 1L; public void paint(Graphics g) { super.paint(g); g.drawRect(0, 0, getWidth() - 1, getHeight() - 1); } }; observer = new ImageObserver() { public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h) { if ((flags & ALLBITS) != 0) { canvas.repaint(); } return (flags & (ALLBITS | ABORT | ERROR)) == 0; } }; frame.setBackground(new Color(255, 255, 204)); canvas = new Component() { private static final long serialVersionUID = 1L; public void paint(Graphics g) { g.drawImage(image, 0, 0, observer); } }; Toolkit toolkit = Toolkit.getDefaultToolkit(); URL url = LoadingProgress.class.getResource("/org/rapla/bootstrap/tafel.png"); // Variables (integer pixels) for... // ... the width of the border around the picture int borderwidth = 4; // ... the height of the border around the picture int borderheight = 4; // ... the width of the picture within the frame int picturewidth = 356; // ... the height of the picture within the frame int pictureheight = 182; // ... calculating the frame width int framewidth = borderwidth + borderheight + picturewidth; // ... calculating the frame height int frameheight = borderwidth + borderheight + pictureheight; // ... width of the loading progress bar int progresswidth = 150; // ... height of the loading progress bar int progressheight = 15; image = toolkit.createImage(url); frame.setResizable(false); frame.setLayout(null); progressBar = new JProgressBar(0, maxValue); progressBar.setValue(startValue); // set the bounds to position the progressbar and set width and height progressBar.setBounds(158, 130, progresswidth, progressheight); progressBar.repaint(); // we have to add the progressbar first to get it infront of the picture frame.add(progressBar); frame.add(canvas); // width and height of the canvas equal to those of the picture inside // but here we need the borderwidth as X and the borderheight as Y value canvas.setBounds(borderwidth, borderheight, picturewidth, pictureheight); try { // If run on jdk < 1.4 this will throw a MethodNotFoundException // frame.setUndecorated(true); Frame.class.getMethod("setUndecorated", new Class[] { boolean.class }).invoke(frame, new Object[] { new Boolean(true) }); } catch (Exception ex) { } // we grab the actual size of the screen Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // to make sure the starting dialog is positioned in the middle of // the screen and has the width and height we specified for the frame frame.setBounds((screenSize.width / 2) - (picturewidth / 2), (screenSize.height / 2) - (pictureheight / 2), framewidth, frameheight); frame.validate(); frame.setVisible(true); frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); MediaTracker mt = new MediaTracker(frame); mt.addImage(image, 0); try { mt.waitForID(0); } catch (InterruptedException e) { } } public void advance() { if ( frame == null) { return; } int oldValue = progressBar.getValue(); if (oldValue < maxValue) progressBar.setValue(oldValue + 1); progressBar.repaint(); } public void close() { if ( frame != null) { frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); frame.dispose(); frame = null; } } }
Java
package org.rapla.bootstrap; import java.io.File; import java.io.IOException; public class RaplaServerAsServiceLoader { public static void main(String[] args) throws IOException { System.setProperty( "java.awt.headless", "true" ); String baseDir = System.getProperty("jetty.home"); if ( baseDir == null) { baseDir = "../.."; System.setProperty( "jetty.home", new File(baseDir ).getCanonicalPath() ); } RaplaServerLoader.main( args); } }
Java
package org.rapla.bootstrap; import java.io.IOException; public class RaplaStandaloneLoader { public static void main(String[] args) throws IOException { // This is for backwards compatibility if ( args.length > 0 && args[0].equals( "client")) { RaplaJettyLoader.main(new String[] {"client"}); } else { RaplaJettyLoader.main(new String[] {"standalone"}); } } }
Java
package org.rapla.bootstrap; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.StringTokenizer; /** Puts all jar-files from the libdirs into the classpath and start the mainClass. Usage: <code> Syntax: baseDir libdir1,libdir2,... mainClass arg1 arg2 ... Will put all jar-files from the libdirs into the classpath and start the mainClass baseDir: replace with the path, from wich you want the lib-dirs to resolve. libdir[1-n]: Lib-Directories relativ to the base jars."); mainClass: The Java-Class you want to start after loading the jars. arg[1-n]: Example: ./lib common,client org.rapla.Main rapla loads the jars in lib/common and lib/client and starts org.rapla.Main with the argument rapla </code> */ public class RaplaLoader { /** returns all *.jar files in the directories passed in dirList relative to the baseDir */ public static File[] getJarFilesAndClassesFolder(String baseDir,String dirList) throws IOException { ArrayList<File> completeList = new ArrayList<File>(); StringTokenizer tokenizer = new StringTokenizer(dirList,","); while (tokenizer.hasMoreTokens()) { File jarDir = new File(baseDir,tokenizer.nextToken()); if (jarDir.exists() && jarDir.isDirectory()) { File[] jarFiles = jarDir.listFiles(); for (int i = 0; i < jarFiles.length; i++) { if ( jarFiles[i].getAbsolutePath().endsWith(".jar") ) { completeList.add(jarFiles[i].getCanonicalFile()); } } completeList.add( jarDir.getCanonicalFile() ); } } return completeList.toArray(new File[] {}); } private static void printUsage() { System.out.println("Syntax: baseDir libdir1,libdir2,... mainClass arg1 arg2 ..."); System.out.println(); System.out.println("Will put all jar-files from the libdirs into the classpath and start the mainClass"); System.out.println(); System.out.println(" baseDir: replace with the path, from wich you want the lib-dirs to resolve."); System.out.println(" libdir[1-n]: Lib-Directories relativ to the base jars."); System.out.println(" mainClass: The Java-Class you want to start after loading the jars."); System.out.println(" arg[1-n]: "); System.out.println(); System.out.println(" Example: ./lib common,client org.rapla.Main rapla "); System.out.println("loads the jars in lib/common and lib/client and "); System.out.println(" starts org.rapla.Main with the argument rapla"); } public static void main(String[] args) { String baseDir; String dirList; String classname; String[] applicationArgs; if (args.length <3) { printUsage(); System.exit(1); } baseDir=args[0]; dirList=args[1]; classname=args[2]; applicationArgs = new String[args.length-3]; for (int i=0;i<applicationArgs.length;i++) { applicationArgs[i] = args[i+3]; } start( baseDir, dirList, classname, "main",new Object[] {applicationArgs} ); } public static void start( String baseDir, String dirList, String classname, String methodName,Object[] applicationArgs ) { try{ ClassLoader classLoader = getJarClassloader(baseDir, dirList); Thread.currentThread().setContextClassLoader(classLoader); startMain(classLoader,classname,methodName,applicationArgs); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } } private static ClassLoader getJarClassloader(String baseDir, String dirList) throws IOException, MalformedURLException { File[] jarFiles = getJarFilesAndClassesFolder(baseDir,dirList); URL[] urls = new URL[jarFiles.length]; for (int i = 0; i < jarFiles.length; i++) { urls[i] = jarFiles[i].toURI().toURL(); //System.out.println(urls[i]); } ClassLoader classLoader = new URLClassLoader ( urls ,RaplaLoader.class.getClassLoader() ); return classLoader; } private static void startMain(ClassLoader classLoader,String classname, String methodName,Object[] args) throws Exception { Class<?> startClass = classLoader.loadClass(classname); Class<?>[] argTypes = new Class[args.length]; for ( int i=0;i<args.length;i++) { argTypes[i] = args[i].getClass(); } Method mainMethod = startClass.getMethod(methodName,argTypes); mainMethod.invoke(null, args); } // public static void startFromWar( String baseDir, String dirList,String warfile, String classname, String methodName,Object[] applicationArgs ) // { // try{ // ClassLoader loader = getJarClassloader(baseDir, dirList); // Thread.currentThread().setContextClassLoader(loader); // Class<?> forName = loader.loadClass("org.slf4j.bridge.SLF4JBridgeHandler"); // forName.getMethod("removeHandlersForRootLogger", new Class[] {}).invoke(null, new Object[] {}); // forName.getMethod("install", new Class[] {}).invoke(null, new Object[] {}); // loader.loadClass("org.rapla.bootstrap.JNDIInit").newInstance(); // // File file = new File(baseDir, warfile); // ClassLoader classLoader; // if (file.exists()) // { // Class<?> webappContextClass = loader.loadClass("org.eclipse.jetty.webapp.WebAppContext"); // //org.eclipse.jetty.webapp.WebAppContext context = new org.eclipse.jetty.webapp.WebAppContext("webapps/rapla.war","/"); // Constructor<?> const1 = webappContextClass.getConstructor(String.class, String.class); // Object context = const1.newInstance(new Object[] {file.getPath(),"/"}); // Class<?> webappClassLoaderClass = loader.loadClass("org.eclipse.jetty.webapp.WebAppClassLoader"); // Class<?> contextClass = loader.loadClass("org.eclipse.jetty.webapp.WebAppClassLoader$Context"); // //org.eclipse.jetty.webapp.WebAppClassLoader classLoader = new org.eclipse.jetty.webapp.WebAppClassLoader(parentClassLoader, context); // Constructor<?> const2 = webappClassLoaderClass.getConstructor(ClassLoader.class, contextClass); // classLoader = (ClassLoader) const2.newInstance(loader, context); // webappContextClass.getMethod("setClassLoader", ClassLoader.class).invoke( context,classLoader); // Class<?> configurationClass = loader.loadClass("org.eclipse.jetty.webapp.WebInfConfiguration"); // Object config = configurationClass.newInstance(); // configurationClass.getMethod("preConfigure", webappContextClass).invoke(config, context); // configurationClass.getMethod("configure", webappContextClass).invoke(config, context); // } // else // { // classLoader = loader; // System.err.println("War " + warfile + " not found. Using original classpath."); // } // startMain(classLoader,classname,methodName,applicationArgs); // } catch (Exception ex) { // ex.printStackTrace(); // System.exit(1); // } // } }
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 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 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.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
/** * */ 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