code
stringlengths
3
1.18M
language
stringclasses
1 value
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.iolayer; import java.awt.Frame; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.Transferable; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.io.IOException; import java.io.OutputStream; import java.net.URL; /** The IO layer is an abstraction from the io differences in webstart or desktop mode */ public interface IOInterface { String saveAsFileShowDialog( String toDir ,Printable printable ,PageFormat format ,boolean askFormat ,java.awt.Component owner ,boolean pdf ) throws IOException,UnsupportedOperationException; void saveAsFile( Printable printable ,PageFormat format ,OutputStream out ,boolean pdf ) throws IOException,UnsupportedOperationException; boolean print( Printable printable ,PageFormat format ,boolean askFormat ) throws PrinterException,UnsupportedOperationException; PageFormat defaultPage() throws UnsupportedOperationException; PageFormat showFormatDialog(PageFormat format) throws UnsupportedOperationException; void setContents(Transferable transferable, ClipboardOwner owner); Transferable getContents( ClipboardOwner owner); public String saveFile(Frame frame,String dir, String[] fileExtensions,String path, byte[] content) throws IOException; public FileContent openFile(Frame frame,String dir, String[] fileExtensions) throws IOException; public boolean openUrl(final URL url) throws IOException; boolean supportsPostscriptExport(); public double INCH_TO_MM = 25.40006; public double MM_TO_INCH = 1.0 / INCH_TO_MM; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | 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.components.calendarview; import java.util.Date; public interface Builder { /** Calculate the blocks that should be displayed in the weekview. * This method should not be called manually. * It is called by the CalendarView during the build process. * @see #build * @param start * @param end */ void prepareBuild(Date start, Date end); /** The maximal ending-time of all blocks that should be displayed. Call prepareBuild first to calculate the blocks.*/ int getMaxMinutes(); /** The minimal starting-time of all blocks that should be displayed. Call prepareBuild first to calculate the blocks.*/ int getMinMinutes(); /** Build the calculated blocks into the weekview. This method should not be called manually. * It is called by the CalendarView during the build process. * @see #prepareBuild */ void build(CalendarView cv); void setEnabled(boolean enable); boolean isEnabled(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender | | | | 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.components.calendarview; import java.util.Date; /** implementierung von block koennen in ein slot eingefuegt werden. Sie dienen als modell fuer beliebige grafische komponenten. mit getStart() und getEnd() wird anfangs- und endzeit des blocks definiert (nur uhrzeit ist fuer positionierung in slots relevant). */ public interface Block { Date getStart(); Date getEnd(); String getName(); }
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.components.calendarview; import java.util.Collection; import java.util.Date; import java.util.TimeZone; public interface CalendarView { public TimeZone getTimeZone(); /** returns the first Date that will be displayed in the calendar */ public Date getStartDate(); /** returns the last Date that will be displayed in the calendar */ public Date getEndDate(); /** sets the calendarview to the selected date*/ public void setToDate(Date weekDate); /** This method removes all existing blocks first. * Then it calls the build method of all added builders, so that they can add blocks into the CalendarView again. * After all blocks are added the Calendarthat repaints the screen. */ public void rebuild(); /** Adds a block. You can optionaly specify a slot, if the day-view supports multiple slots (like in the weekview). * If the selected slot does not exist it will be created. This method is usually called by the builders. */ public void addBlock(Block bl, int column,int slot); /** returns a collection of all the added blocks * @see #addBlock*/ Collection<Block> getBlocks(); }
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.components.calendarview.swing; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Rectangle; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import javax.swing.JComponent; import org.rapla.components.calendarview.AbstractCalendar; /** A vertical scale displaying the hours of day. Uses am/pm notation * in the appropriate locale. */ public class TimeScale extends JComponent { private static final long serialVersionUID = 1L; private int pixelPerHour = 60; private int mintime; private int maxtime; private boolean useAM_PM = false; private Font fontLarge= new Font("SansSerif", Font.PLAIN, 14); private Font fontSmall= new Font("SansSerif", Font.PLAIN, 9); private FontMetrics fm1 = getFontMetrics(fontLarge); private FontMetrics fm2 = getFontMetrics(fontSmall); String[] hours; private int SCALE_WIDTH = 35; private boolean smallSize = false; private int repeat = 1; private String days[] ; public TimeScale() { useAM_PM = AbstractCalendar.isAmPmFormat(Locale.getDefault()); createHours(Locale.getDefault()); } public void setLocale(Locale locale) { if (locale == null) return; useAM_PM = AbstractCalendar.isAmPmFormat(locale); createHours(locale); } /** mintime und maxtime definieren das zeitintevall in vollen stunden. die skalen-einteilung wird um vgap pixel nach unten verschoben (um ggf. zu justieren). */ public void setTimeIntervall(int minHour, int maxHour, int pixelPerHour) { removeAll(); this.mintime = minHour; this.maxtime = maxHour; this.pixelPerHour = pixelPerHour; //setBackground(Color.yellow); //super(JSeparator.VERTICAL); setLayout(null); setPreferredSize(new Dimension( SCALE_WIDTH, (maxHour-minHour + 1) * pixelPerHour * repeat)); } private void createHours(Locale locale) { hours = new String[24]; Calendar cal = Calendar.getInstance(locale); SimpleDateFormat format = new SimpleDateFormat(useAM_PM ? "h" : "H",locale); for (int i=0;i<24;i++) { cal.set(Calendar.HOUR_OF_DAY,i); hours[i] = format.format(cal.getTime()); } } public void setSmallSize(boolean smallSize) { this.smallSize = smallSize; } public void setRepeat(int repeat, String[] days) { this.repeat = repeat; this.days = days; } public void paint(Graphics g) { super.paint(g); int indent[]; int heightHour = (int) fm1.getLineMetrics("12",g).getHeight() ; int heightEnding = (int) fm2.getLineMetrics("12",g).getHeight() ; int current_y ; // Compute indentations FontMetrics fm; String[] indent_string = new String[3] ; if ( days != null ) { indent_string[0] = "M"; indent_string[1] = "M2"; indent_string[2] = "M22"; } else { indent_string[0] = ""; indent_string[1] = "2"; indent_string[2] = "22"; } if ( smallSize ) { fm = fm2; } else { fm = fm1; } indent = new int[3]; for(int i=0; i<3; i++) { indent[i] = fm.stringWidth(indent_string[i]) ; } Rectangle rect = g.getClipBounds(); //System.out.println(mintime + " - " + maxtime); int height = (maxtime - mintime) * pixelPerHour + 1 ; if ( days != null ) { g.drawLine(indent[0]+1,0,indent[0]+1,repeat*height); } for (int r=0; r<repeat; r++) { current_y = height * r; g.drawLine(0,current_y-1,SCALE_WIDTH ,current_y-1); int pad = 0; if ( days != null ) { pad = (maxtime - mintime - days[r].length())/2 ; if ( pad < 0 ) { pad = 0; } } for (int i=mintime; i<maxtime; i++) { int y = current_y + (i - mintime) * pixelPerHour; int hour; String ending; String prefix; if (useAM_PM) { hour = (i == 0) ? 12 : ((i-1)%12 + 1); ending = (i<=11) ? "AM" : "PM"; } else { hour = i; ending = "00"; } if ( days != null && i - mintime < days[r].length() + pad && i - mintime >= pad ) { prefix = days[r].substring(i-mintime-pad,i-mintime+1-pad); } else { prefix = null; } if (y >= rect.y && y <= (rect.y + rect.height)) { g.drawLine(i == mintime ? 0:indent[0]+1,y,SCALE_WIDTH ,y); } // Uncommenting this draws the last line // if (y >= rect.y && y <= (rect.y + rect.height) && i == maxtime-1) { // g.drawLine(0,y+pixelPerHour,SCALE_WIDTH ,y+pixelPerHour); // } if (y >= rect.y -heightHour && y <= (rect.y + rect.height) + heightHour ) { if ( smallSize ) { g.setFont(fontSmall); } else { g.setFont(fontLarge); } if ( prefix != null ) { g.drawString(prefix, (indent[0]-fm.stringWidth(prefix)+1)/2,y + heightEnding); } g.drawString(hours[i],(hour < 10) ? indent[1]+2:indent[0]+2,y + ( smallSize ? heightEnding : heightHour)); if ( !smallSize ) { g.setFont(fontSmall); } g.drawString(ending, indent[2]+2,y + heightEnding); } } } } }
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.components.calendarview.swing; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JViewport; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.border.EtchedBorder; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.CalendarView; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.TimeInterval; public abstract class AbstractSwingCalendar extends AbstractCalendar implements CalendarView { static Border SLOTHEADER_BORDER = new EtchedBorder(); int slotSize = 100; boolean bEditable = true; protected int minBlockWidth = 3; ArrayList<ViewListener> listenerList = new ArrayList<ViewListener>(); JScrollPane scrollPane = new JScrollPane(); JPanel jHeader = new JPanel(); BoxLayout boxLayout1 = new BoxLayout(jHeader, BoxLayout.X_AXIS); JPanel jCenter = new JPanel(); protected JPanel jTitlePanel = new JPanel(); protected JPanel component = new JPanel(); AbstractSwingCalendar(boolean showScrollPane) { jHeader.setLayout(boxLayout1); jHeader.setOpaque( false ); jCenter.setOpaque( false ); jTitlePanel.setOpaque( false); jTitlePanel.setLayout( new BorderLayout()); jTitlePanel.add(jHeader,BorderLayout.CENTER); if (showScrollPane) { component.setLayout(new BorderLayout()); component.add(scrollPane,BorderLayout.CENTER); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); scrollPane.setViewportView(jCenter); scrollPane.setColumnHeaderView(jTitlePanel); scrollPane.getVerticalScrollBar().setUnitIncrement(10); scrollPane.getHorizontalScrollBar().setUnitIncrement(10); scrollPane.setBorder(null); } else { component.setLayout(new TableLayout(new double[][] { {TableLayout.PREFERRED,TableLayout.FILL} ,{TableLayout.PREFERRED,TableLayout.FILL} })); component.add(jTitlePanel,"1,0"); component.add(jCenter,"1,1"); } this.timeZone = TimeZone.getDefault(); setLocale( Locale.getDefault() ); if ( showScrollPane) { component.addComponentListener( new ComponentListener() { private boolean resizing = false; public void componentShown(ComponentEvent e) { } public void componentResized(ComponentEvent e) { if ( resizing) { return; } resizing = true; if ( isEditable() ) { int width = component.getSize().width; updateSize(width); } SwingUtilities.invokeLater(new Runnable() { public void run() { resizing = false; } }); } public void componentMoved(ComponentEvent e) { } public void componentHidden(ComponentEvent e) { } }); } } abstract public void updateSize(int width); public JComponent getComponent() { return component; } void checkBlock( Block bl ) { if ( !bl.getStart().before(this.getEndDate())) { throw new IllegalStateException("Start-date " +bl.getStart() + " must be before calendar end at " +this.getEndDate()); } } public boolean isEditable() { return bEditable; } public void setEditable( boolean editable ) { bEditable = editable; } /** Width of a single slot in pixel. */ public void setSlotSize(int slotSize) { this.slotSize = slotSize; } public int getSlotSize() { return slotSize; } /** the minimum width of a block in pixel */ public int getMinBlockWidth() { return minBlockWidth; } /** the minimum width of a block in pixel */ public void setMinBlockWidth(int minBlockWidth) { this.minBlockWidth = Math.max(3,minBlockWidth); } public void setBackground(Color color) { component.setBackground(color); if (scrollPane != null) scrollPane.setBackground(color); if (jCenter != null) jCenter.setBackground(color); if (jHeader != null) jHeader.setBackground(color); } public void addCalendarViewListener(ViewListener listener) { listenerList.add(listener); } public void removeCalendarViewListener(ViewListener listener) { listenerList.remove(listener); } JScrollPane getScrollPane() { return scrollPane; } void scrollTo(int x, int y) { JViewport viewport = scrollPane.getViewport(); Rectangle rect = viewport.getViewRect(); int leftBound = rect.x; int upperBound = rect.y; int lowerBound = rect.y + rect.height; int rightBound = rect.x + rect.width; int maxX = viewport.getView().getWidth(); int maxY = viewport.getView().getHeight(); JScrollBar scrollBar = scrollPane.getVerticalScrollBar(); if ( y > lowerBound && lowerBound < maxY) { scrollBar.setValue(scrollBar.getValue() + 20); } if ( y < upperBound && upperBound >0) { scrollBar.setValue(scrollBar.getValue() - 20); } scrollBar = scrollPane.getHorizontalScrollBar(); if ( x > rightBound && rightBound < maxX) { scrollBar.setValue(scrollBar.getValue() + 20); } if ( x < leftBound && leftBound >0) { scrollBar.setValue(scrollBar.getValue() - 20); } } public ViewListener[] getWeekViewListeners() { return listenerList.toArray(new ViewListener[]{}); } final void fireSelectionChanged(Date start, Date end) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].selectionChanged(start,end); } } final void fireSelectionPopup(Component slot, Point p, Date start, Date end, int slotNr) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].selectionPopup(slot,p,start,end, slotNr); } } final void fireMoved(SwingBlock block, Point p, Date newTime, int slotNr) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].moved(block,p,newTime, slotNr); } } final void fireResized(SwingBlock block, Point p, Date newStart, Date newEnd, int slotNr) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].resized(block,p,newStart,newEnd, slotNr); } } void fireResized(SwingBlock block, Point p, Date newTime, int slotNr) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].moved(block,p,newTime, slotNr); } } void fireBlockPopup(SwingBlock block, Point p) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].blockPopup(block,p); } } void fireBlockEdit(SwingBlock block, Point p) { // Fire the popup event ViewListener[] listeners = getWeekViewListeners(); for (int i=0;i<listeners.length;i++) { listeners[i].blockEdit(block,p); } } abstract int getDayCount(); abstract DaySlot getSlot(int num); abstract public boolean isSelected(int nr); abstract int calcSlotNr( int x, int y); abstract int getSlotNr( DaySlot slot); abstract int getRowsPerDay(); abstract Date createDate( DaySlot slot, int row, boolean startOfRow); public TimeInterval normalizeBlockIntervall(SwingBlock block) { return new TimeInterval(block.getStart(), block.getEnd()); } }
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.components.calendarview.swing; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.SwingConstants; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.calendarview.swing.SelectionHandler.SelectionStrategy; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.DateTools; /** Graphical component for displaying a calendar like weekview. * This view doesn't show the times and arranges the different slots * Vertically. */ public class SwingCompactWeekView extends AbstractSwingCalendar { private SmallDaySlot[] slots = new SmallDaySlot[0]; private List<List<Block>> rows = new ArrayList<List<Block>>(); DraggingHandler draggingHandler = new DraggingHandler(this, false); SelectionHandler selectionHandler = new SelectionHandler(this); String[] rowNames = new String[] {}; int leftColumnSize = 100; Map<Block, Integer> columnMap = new HashMap<Block, Integer>(); public SwingCompactWeekView() { this(true); } public SwingCompactWeekView(boolean showScrollPane) { super( showScrollPane ); selectionHandler.setSelectionStrategy(SelectionStrategy.BLOCK); } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.length;i++) { list.addAll(slots[i].getBlocks()); } return Collections.unmodifiableCollection( list ); } public void setEditable(boolean b) { super.setEditable( b); if ( slots == null ) return; // Hide the rest for (int i= 0;i<slots.length;i++) { SmallDaySlot slot = slots[i]; if (slot == null) continue; slot.setEditable(b); } } public void setSlots(String[] slotNames) { this.rowNames = slotNames; } TableLayout tableLayout; public void rebuild() { rows.clear(); columnMap.clear(); for ( int i=0; i<rowNames.length; i++ ) { addRow(); } // calculate the blocks Iterator<Builder> it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(getStartDate(), getEndDate()); } // clear everything jHeader.removeAll(); jCenter.removeAll(); // build Blocks it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } tableLayout= new TableLayout(); jCenter.setLayout(tableLayout); Calendar calendar = createCalendar(); calendar.setTime(getStartDate()); int firstDayOfWeek = getFirstWeekday(); calendar.set( Calendar.DAY_OF_WEEK, firstDayOfWeek); if ( rowNames.length > 0) { tableLayout.insertColumn(0, leftColumnSize); jHeader.add( createColumnHeader( null ), "0,0,l,t" ); } else { tableLayout.insertColumn(0, 0); } int columns = getColumnCount(); // add headers for (int column=0;column<columns;column++) { if ( !isExcluded(column) ) { tableLayout.insertColumn(column + 1, slotSize ); jHeader.add( createColumnHeader( column ) ); } else { tableLayout.insertColumn(column + 1, 0.); } } int rowsize = rows.size(); slots = new SmallDaySlot[rowsize * columns]; for (int row=0;row<rowsize;row++) { tableLayout.insertRow(row, TableLayout.PREFERRED ); jCenter.add(createRowLabel( row ), "" + 0 + "," + row + ",f,t"); for (int column=0;column < columns; column++) { int fieldNumber = row * columns + column; SmallDaySlot field = createField( ); for (Block block:getBlocksForColumn(rows.get( row ), column)) { field.putBlock( (SwingBlock ) block); } slots[fieldNumber] = field; if ( !isExcluded( column ) ) { jCenter.add(slots[fieldNumber], "" + (column + 1) + "," + row); } } } selectionHandler.clearSelection(); jCenter.validate(); jHeader.validate(); if ( isEditable()) { updateSize(component.getSize().width); } component.revalidate(); component.repaint(); } protected int getColumnCount() { return getDaysInView(); } public int getLeftColumnSize() { return leftColumnSize; } public void setLeftColumnSize(int leftColumnSize) { this.leftColumnSize = leftColumnSize; } protected JComponent createRowLabel(int row) { JLabel label = new JLabel(); if ( row < rowNames.length ) { label.setText( rowNames[ row ] ); label.setToolTipText(rowNames[ row ]); } return label; } public boolean isSelected(int nr) { SmallDaySlot slot = getSlot(nr); if ( slot == null) { return false; } return slot.isSelected(); } /** override this method, if you want to create your own slot header. */ protected JComponent createColumnHeader(Integer column) { JLabel jLabel = new JLabel(); jLabel.setFont(new Font("SansSerif", Font.PLAIN, 13)); jLabel.setHorizontalAlignment(JLabel.CENTER); jLabel.setOpaque(false); jLabel.setForeground(Color.black); Dimension dim; if (column != null ) { Date date = getDateFromColumn(column); jLabel.setText(AbstractCalendar.formatDayOfWeekDateMonth(date,locale,getTimeZone())); jLabel.setBorder(isEditable() ? SLOTHEADER_BORDER : null); dim = new Dimension(this.slotSize,20); } else { dim = new Dimension(this.leftColumnSize,20); jLabel.setFont(jLabel.getFont().deriveFont((float)11.)); jLabel.setHorizontalAlignment(SwingConstants.LEFT); } jLabel.setPreferredSize( dim); jLabel.setMinimumSize( dim ); jLabel.setMaximumSize( dim ); return jLabel; } private SmallDaySlot createField( ) { SmallDaySlot c= new SmallDaySlot("",slotSize, Color.BLACK, null); c.setEditable(isEditable()); c.setDraggingHandler(draggingHandler); c.addMouseListener(selectionHandler); c.addMouseMotionListener(selectionHandler); return c; } protected List<Block> getBlocksForColumn(List<Block> blocks,int column) { List<Block> result = new ArrayList<Block>(); //Date startDate = getDateFromColumn(column); if ( blocks != null) { Iterator<Block> it = blocks.iterator(); while (it.hasNext()){ Block block = it.next(); if (columnMap.get( block) == column) { // if ( DateTools.cutDate( block.getStart()).equals( startDate)) { result.add( block); } } } return result; } protected Date getDateFromColumn(int column) { Date startDate = getStartDate(); return DateTools.addDays( startDate, column); } public void addBlock(Block block, int column,int slot) { if ( rows.size() <= slot) { return; } checkBlock( block ); List<Block> blocks = rows.get( slot ); blocks.add( block ); columnMap.put(block, column); } private void addRow() { rows.add( rows.size(), new ArrayList<Block>()); } public int getSlotNr( DaySlot slot) { for (int i=0;i<slots.length;i++) if (slots[i] == slot) return i; throw new IllegalStateException("Slot not found in List"); } int getRowsPerDay() { return 1; } SmallDaySlot getSlot(int nr) { if ( nr >=0 && nr< slots.length) return slots[nr]; else return null; } int getDayCount() { return slots.length; } int calcSlotNr(int x, int y) { for (int i=0;i<slots.length;i++) { if (slots[i] == null) continue; Point p = slots[i].getLocation(); if ((p.x <= x) && (x <= p.x + slots[i].getWidth()) && (p.y <= y) && (y <= p.y + slots[i].getHeight()) ) { return i; } } return -1; } SmallDaySlot calcSlot(int x,int y) { int nr = calcSlotNr(x, y); if (nr == -1) { return null; } else { return slots[nr]; } } Date createDate(DaySlot slot, int row, boolean startOfRow) { Calendar calendar = createCalendar(); Date startDate = getStartDate(); calendar.setTime( startDate ); calendar.set( Calendar.DAY_OF_WEEK, getFirstWeekday() ); calendar.add( Calendar.DATE , getSlotNr( slot ) % getDaysInView() ); //calendar.set( Calendar.DAY_OF_WEEK, getDayOfWeek(slot) ); if ( !startOfRow ) { calendar.add( Calendar.DATE , 1 ); } calendar.set( Calendar.HOUR_OF_DAY, 0 ); calendar.set( Calendar.MINUTE, 0 ); calendar.set( Calendar.SECOND, 0 ); calendar.set( Calendar.MILLISECOND, 0 ); return calendar.getTime(); } /** must be called after the slots are filled*/ protected boolean isEmpty(int column) { for (Integer value: columnMap.values()) { if ( value.equals( column)) { return false; } } return true; } @Override public void updateSize(int width) { int columnSize = tableLayout.getNumColumn(); int realColumns= columnSize; for ( int i=1;i< columnSize;i++) { if( isExcluded(i)) { realColumns--; } } int newWidth = Math.max( minBlockWidth ,(width - leftColumnSize -20 - realColumns) / (Math.max(1,realColumns-1))); for (SmallDaySlot slot: this.slots) { if ( slot != null) { slot.updateSize(newWidth); } } setSlotSize(newWidth); for ( int i=1;i< columnSize;i++) { if( !isExcluded(i-1)) { tableLayout.setColumn(i, newWidth); } } boolean first = true; for (Component comp:jHeader.getComponents()) { if ( first) { first = false; continue; } double height = comp.getPreferredSize().getHeight(); Dimension dim = new Dimension( newWidth,(int) height); comp.setPreferredSize(dim); comp.setMaximumSize(dim); comp.setMinimumSize( dim); comp.invalidate(); } jCenter.invalidate(); jCenter.repaint(); } }
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.components.calendarview.swing; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.HashMap; import java.util.Map; import javax.swing.JPanel; import javax.swing.UIManager; abstract class AbstractDaySlot extends JPanel implements DaySlot { private static final long serialVersionUID = 1L; private boolean bEditable = true; boolean paintDraggingGrid; int draggingSlot; int draggingY; SwingBlock draggingView; int draggingHeight; protected Map<Object,SwingBlock> blockViewMapper = new HashMap<Object,SwingBlock>(); // BJO 00000076 // protected Method getButtonMethod = null; // BJO 00000076 AbstractDaySlot() { /* // BJO 00000076 try { //is only available sind 1.4 getButtonMethod = MouseEvent.class.getMethod("getButton", new Class[] {}); } catch (Exception ex) { } // BJO 00000076 */ } public void setEditable(boolean b) { bEditable = b; } public boolean isEditable() { return bEditable; } SwingBlock getBlockFor(Object component) { return blockViewMapper.get(component); } protected void showPopup(MouseEvent evt) { Point p = new Point(evt.getX(),evt.getY()); SwingBlock block = getBlockFor(evt.getSource()); if (block != null) draggingHandler.blockPopup(block,p); } protected Color getSelectionColor() { return UIManager.getColor("Table.selectionBackground"); } public void paintDraggingGrid(int slot,int y, int height,SwingBlock draggingView,int oldY,int oldHeight,boolean bPaint) { this.paintDraggingGrid = bPaint; this.draggingSlot = slot; this.draggingY = y; this.draggingHeight = height; this.draggingView = draggingView; this.invalidateDragging(); } public int getX(Component component) { return component.getParent().getLocation().x; } void invalidateDragging() { repaint(); } void setDraggingHandler(DraggingHandler draggingHandler) { this.draggingHandler = draggingHandler; } private DraggingHandler draggingHandler; /** BlockListener handles the dragging events and the Block * Context Menu (right click). */ class BlockListener extends MouseAdapter { boolean preventDragging = false; public void mouseClicked(MouseEvent evt) { if (evt.isPopupTrigger()) { showPopup(evt); } else { if (evt.getClickCount()>1) blockEdit(evt); } //draggingPointOffset = evt.getY(); } private int calcResizeDirection( MouseEvent evt ) { if ( !draggingHandler.supportsResizing()) return 0; int height = ((Component)evt.getSource()).getHeight(); int diff = height- evt.getY() ; if ( diff <= 5 && diff >=0 ) return 1; if (evt.getY() >=0 && evt.getY() < 5) return -1; return 0; } public void mousePressed(MouseEvent evt) { if (evt.isPopupTrigger()) { showPopup(evt); } preventDragging = false; /* // BJO 00000076 //System.out.println ("Button:" +evt.getButton() ); if ( getButtonMethod != null) { try { Integer button = (Integer) getButtonMethod.invoke( evt, new Object [] {}); preventDragging = button.intValue() != 1; } catch (Exception ex) { } } */ preventDragging = evt.getButton() != 1; // BJO 00000076 if ( preventDragging ) return; SwingBlock block = getBlockFor(evt.getSource()); int resizeDirection = calcResizeDirection( evt ); if ( resizeDirection != 0) { draggingHandler.blockBorderPressed( AbstractDaySlot.this,block, evt, resizeDirection ); } } public void mouseReleased(MouseEvent evt) { if (evt.isPopupTrigger()) { showPopup(evt); } preventDragging = false; SwingBlock block = getBlockFor(evt.getSource()); draggingHandler.mouseReleased( AbstractDaySlot.this, block, evt); } public void mouseEntered(MouseEvent evt) { } public void mouseExited(MouseEvent evt) { if ( draggingHandler.isDragging()) return; setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } public void mouseMoved(MouseEvent evt) { if ( draggingHandler.isDragging()) { return; } SwingBlock block = getBlockFor(evt.getSource()); // BJO 00000137 if(!block.isMovable()) return; // BJO 00000137 if ( calcResizeDirection( evt ) == 1 && block.isEndResizable()) { setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); } else if (calcResizeDirection( evt ) == -1 && block.isStartResizable()){ setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR)); } else { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } public void mouseDragged(MouseEvent evt) { if ( preventDragging || !isEditable()) return; SwingBlock block = getBlockFor(evt.getSource()); draggingHandler.mouseDragged( AbstractDaySlot.this, block, evt); } private void blockEdit(MouseEvent evt) { SwingBlock block = getBlockFor(evt.getSource()); draggingHandler.blockEdit(block,new Point(evt.getX(),evt.getY())); } } protected void paintDraggingGrid(Graphics g, int x, int y, int width, int height) { /* Rectangle rect = g.getClipBounds(); int startx = draggingView.getView().getX(); int starty = draggingView.getView().getY(); g.setColor(Color.gray); for (int y1=10;y1<height-5; y1+=11) for (int x1=10;x1<width-5; x1+=11) { int x2 = startx + x1; int y2 = starty + y1; if ( x2 >= rect.x && x2 <= rect.x + rect.width && y2 >= rect.y && y2 <= rect.y + rect.height ) g.drawRect(x2,y2,2,2); } */ g.translate( x-1, y-1); if ( draggingView != null) { draggingView.paintDragging( g, width , height +1 ); } g.translate( -(x-1), -(y-1)); } static int count = 0; }
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.components.calendarview.swing; import java.awt.Color; import java.awt.Font; import java.awt.Point; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.Locale; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JScrollPane; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.calendarview.swing.scaling.IRowScale; import org.rapla.components.calendarview.swing.scaling.LinearRowScale; import org.rapla.components.calendarview.swing.scaling.VariableRowScale; import org.rapla.components.util.DateTools; /** Graphical component for displaying a calendar like weekview. */ public class SwingWeekView extends AbstractSwingCalendar { public final static int SLOT_GAP= 5; LargeDaySlot[] daySlots = new LargeDaySlot[] {}; private int startMinutes= 0; private int endMinutes= 24 * 60; BoxLayout boxLayout2= new BoxLayout(jCenter, BoxLayout.X_AXIS); TimeScale timeScale = new TimeScale(); IRowScale rowScale = new LinearRowScale(); protected JLabel weekTitle; protected SelectionHandler selectionHandler ; public SwingWeekView() { this(true); } public SwingWeekView(boolean showScrollPane) { super(showScrollPane); weekTitle = new JLabel(); weekTitle.setHorizontalAlignment( JLabel.CENTER); weekTitle.setFont(weekTitle.getFont().deriveFont((float)11.)); jCenter.setLayout(boxLayout2); jCenter.setAlignmentY(JComponent.TOP_ALIGNMENT); jCenter.setAlignmentX(JComponent.LEFT_ALIGNMENT); if ( showScrollPane ) { scrollPane.setRowHeaderView(timeScale); scrollPane.setCorner( JScrollPane.UPPER_LEFT_CORNER, weekTitle); } else { component.add(weekTitle, "0,0"); component.add(timeScale,"0,1"); } selectionHandler = new SelectionHandler(this); } public void updateSize(int width) { int slotCount = 0; int columnCount = 0; for (int i=0; i<daySlots.length; i++) { LargeDaySlot largeDaySlot = daySlots[i]; if ( isExcluded(i) ) { continue; } if ( largeDaySlot != null) { slotCount += largeDaySlot.getSlotCount(); columnCount++; } } int newWidth = Math.round(((width - timeScale.getWidth() - 10- columnCount* (16 + SLOT_GAP)) / (Math.max(1,slotCount)))-2); newWidth = Math.max( newWidth , minBlockWidth); for (LargeDaySlot slot: daySlots) { if ( slot != null) { slot.updateSize(newWidth); } } setSlotSize(newWidth); } public void setWorktime(int startHour, int endHour) { this.startMinutes = startHour * 60; this.endMinutes = endHour * 60; } public void setWorktimeMinutes(int startMinutes, int endMinutes) { this.startMinutes = startMinutes; this.endMinutes = endMinutes; if (getStartDate() != null) calcMinMaxDates( getStartDate() ); } public void setLocale(Locale locale) { super.setLocale( locale ); if ( timeScale != null ) timeScale.setLocale( locale ); } public void scrollDateVisible(Date date) { LargeDaySlot slot = getSlot(date); if ( slot == null) { return; } if (!jCenter.isAncestorOf( slot) ) { return; } LargeDaySlot scrollSlot = slot; Rectangle viewRect = scrollPane.getViewport().getViewRect(); Rectangle slotRect = scrollSlot.getBounds(); // test if already visible if (slotRect.x>=viewRect.x && (slotRect.x + slotRect.width)< (viewRect.x + viewRect.width ) ) { return; } scrollSlot.scrollRectToVisible(new Rectangle(0 ,viewRect.y ,scrollSlot.getWidth() ,10)); } public void scrollToStart() { int y = rowScale.getStartWorktimePixel(); int x = 0; scrollPane.getViewport().setViewPosition(new Point(x,y)); } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<getDaysInView();i++) { list.addAll(daySlots[i].getBlocks()); } return Collections.unmodifiableCollection( list ); } /** The granularity of the selection rows. * <ul> * <li>1: 1 rows per hour = 1 Hour</li> * <li>2: 2 rows per hour = 1/2 Hour</li> * <li>3: 3 rows per hour = 20 Minutes</li> * <li>4: 4 rows per hour = 15 Minutes</li> * <li>6: 6 rows per hour = 10 Minutes</li> * <li>12: 12 rows per hour = 5 Minutes</li> * </ul> * Default is 4. */ public void setRowsPerHour(int rowsPerHour) { if ( rowScale instanceof LinearRowScale) ((LinearRowScale)rowScale).setRowsPerHour(rowsPerHour); } /** @see #setRowsPerHour */ public int getRowsPerHour() { if ( rowScale instanceof LinearRowScale) return ((LinearRowScale)rowScale).getRowsPerHour(); return 0; } /** The size of each row (in pixel). Default is 15.*/ public void setRowSize(int rowSize) { if ( rowScale instanceof LinearRowScale) ((LinearRowScale)rowScale).setRowSize(rowSize); } public int getRowSize() { if ( rowScale instanceof LinearRowScale) return ((LinearRowScale)rowScale).getRowSize(); return 0; } public void setBackground(Color color) { super.setBackground(color); if (timeScale != null) timeScale.setBackground(color); } public void setEditable(boolean b) { super.setEditable( b ); // Hide the rest for (int i= 0;i<daySlots.length;i++) { LargeDaySlot slot = daySlots[i]; if (slot == null) continue; slot.setEditable(b); slot.getHeader().setBorder(b ? SLOTHEADER_BORDER : null); } } /** must be called after the slots are filled*/ protected boolean isEmpty(int column) { return daySlots[column].isEmpty(); } public void rebuild() { daySlots= new LargeDaySlot[getColumnCount()]; selectionHandler.clearSelection(); // clear everything jHeader.removeAll(); jCenter.removeAll(); int start = startMinutes ; int end = endMinutes ; // calculate the blocks Iterator<Builder> it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(getStartDate(),getEndDate()); if (! bEditable) { start = Math.min(b.getMinMinutes(),start); end = Math.max(b.getMaxMinutes(),end); if (start<0) throw new IllegalStateException("builder.getMin() is smaller than 0"); if (end>24*60) throw new IllegalStateException("builder.getMax() is greater than 24"); } } //rowScale = new VariableRowScale(); if ( rowScale instanceof LinearRowScale) { LinearRowScale linearScale = (LinearRowScale) rowScale; int pixelPerHour = linearScale.getRowsPerHour() * linearScale.getRowSize(); timeScale.setBackground(component.getBackground()); linearScale.setTimeZone( timeZone ); if ( isEditable()) { timeScale.setTimeIntervall(0, 24, pixelPerHour); linearScale.setTimeIntervall( 0, 24 * 60); } else { timeScale.setTimeIntervall(start / 60, end / 60, pixelPerHour); linearScale.setTimeIntervall( (start /60) * 60, Math.min( 24 * 60, ((end / 60) + ((end%60 != 0) ? 1 : 0)) * 60 )); } linearScale.setWorktimeMinutes( this.startMinutes, this.endMinutes); } else { timeScale.setBackground(component.getBackground()); timeScale.setTimeIntervall(0, 24, 60); VariableRowScale periodScale = (VariableRowScale) rowScale; periodScale.setTimeZone( timeZone ); } // create Slots DraggingHandler draggingHandler = new DraggingHandler(this, rowScale,true); for (int i=0; i<getColumnCount(); i++) { createMultiSlot(i, i, draggingHandler, selectionHandler); } // build Blocks it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } // add Slots for (int i=0; i<daySlots.length; i++) { if ( isExcluded(i) ) { continue; } addToWeekView(daySlots[i]); } jHeader.add(Box.createGlue()); jHeader.validate(); jCenter.validate(); if ( isEditable()) { updateSize(component.getSize().width); } component.revalidate(); component.repaint(); } private void createMultiSlot(int pos, int column, DraggingHandler draggingHandler, SelectionHandler selectionHandler) { JComponent header = createSlotHeader(column); LargeDaySlot c= new LargeDaySlot(slotSize,rowScale, header); c.setEditable(isEditable()); c.setTimeIntervall(); c.setDraggingHandler(draggingHandler); c.addMouseListener(selectionHandler); c.addMouseMotionListener(selectionHandler); daySlots[pos]= c; } protected Date getDateFromColumn(int column) { return DateTools.addDays( getStartDate(), column); } /** override this method, if you want to create your own slot header. */ protected JComponent createSlotHeader(Integer column) { JLabel jLabel = new JLabel(); jLabel.setBorder(isEditable() ? SLOTHEADER_BORDER : null); Date date = getDateFromColumn(column); jLabel.setText(AbstractCalendar.formatDayOfWeekDateMonth(date,locale,getTimeZone())); jLabel.setFont(new Font("SansSerif", Font.PLAIN, 13)); jLabel.setHorizontalAlignment(JLabel.CENTER); jLabel.setOpaque(false); jLabel.setForeground(Color.black); return jLabel; } protected int getColumnCount() { return getDaysInView(); } public void addBlock(Block bl, int col,int slot) { checkBlock( bl ); LargeDaySlot dslot = daySlots[col]; dslot.putBlock((SwingBlock)bl, slot); } private LargeDaySlot getSlot(Date start) { long countDays = DateTools.countDays(DateTools.cutDate(getStartDate()), start); int slotNr = (int) countDays; if ( daySlots.length ==0) { return null; } int min = Math.min(daySlots.length-1,slotNr); return daySlots[min]; } private void addToWeekView(LargeDaySlot slot) { jHeader.add(slot.getHeader()); jHeader.add(Box.createHorizontalStrut(SLOT_GAP)); jCenter.add(slot); jCenter.add(Box.createHorizontalStrut(SLOT_GAP)); } public int getSlotNr(DaySlot slot) { for (int i=0;i<daySlots.length;i++) { if (daySlots[i] == slot) { return i; } } throw new IllegalStateException("Slot not found in List"); } int getRowsPerDay() { return rowScale.getRowsPerDay(); } LargeDaySlot getSlot( int nr ) { if ( nr >=0 && nr< daySlots.length) return daySlots[nr]; else return null; } public boolean isSelected(int slotNr) { LargeDaySlot slot = getSlot(slotNr); if ( slot == null) { return false; } return slot.isSelected(); } int getDayCount() { return daySlots.length; } int calcSlotNr(int x, int y) { for (int i=0;i<daySlots.length;i++) { if (getSlot(i) == null) continue; Point p = getSlot(i).getLocation(); if (p.x <= x && x <= p.x + daySlots[i].getWidth() && p.y <= y && y <= p.y + daySlots[i].getHeight() ) return i; } return -1; } public LargeDaySlot calcSlot(int x, int y) { int nr = calcSlotNr(x, y); if (nr == -1) return null; else return daySlots[nr]; } protected Date createDate(DaySlot slot,int index, boolean startOfRow) { Calendar calendar = createCalendar(); calendar.setTime( getStartDate() ); calendar.set( Calendar.DAY_OF_WEEK, getFirstWeekday() ); calendar.add( Calendar.DATE , getSlotNr( slot ) %getDaysInView()); if (!startOfRow) index++; calendar.set(Calendar.HOUR_OF_DAY,rowScale.calcHour(index)); calendar.set(Calendar.MINUTE,rowScale.calcMinute(index)); calendar.set(Calendar.SECOND,0); calendar.set(Calendar.MILLISECOND,0); return calendar.getTime(); } }
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.components.calendarview.swing; import java.awt.Component; import java.awt.Graphics; import org.rapla.components.calendarview.Block; public interface SwingBlock extends Block { Component getView(); public void paintDragging(Graphics g, int width, int height); boolean isMovable(); boolean isStartResizable(); boolean isEndResizable(); }
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.components.calendarview.swing; import java.awt.Component; import java.awt.Cursor; import java.awt.Point; public interface DaySlot { void paintDraggingGrid(int x,int y, int height,SwingBlock block, int oldY,int oldHeight,boolean bPaint); Point getLocation(); void unselectAll(); int calcRow(int y); int calcSlot(int x); int getX(Component component); void select(int startRow,int endRow); void setCursor(Cursor cursor); }
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.components.calendarview.swing; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import javax.swing.JComponent; import javax.swing.JLabel; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.DateTools; /** Graphical component for displaying a calendar like monthview. * */ public class SwingMonthView extends AbstractSwingCalendar { public final static int ROWS = 6; //without the header row public final static int COLUMNS = 7; private SmallDaySlot[] slots; DraggingHandler draggingHandler = new DraggingHandler(this, false); SelectionHandler selectionHandler = new SelectionHandler(this); JLabel monthTitle = new JLabel(); public SwingMonthView() { this(true); } public SwingMonthView(boolean showScrollPane) { super( showScrollPane ); monthTitle.setOpaque( false); jTitlePanel.add(monthTitle, BorderLayout.NORTH); monthTitle.setHorizontalAlignment( JLabel.CENTER); monthTitle.setFont(monthTitle.getFont().deriveFont(Font.BOLD)); } protected boolean isEmpty(int column) { for ( int i=column;i < slots.length;i+=7 ) { if (!slots[i].isEmpty() ) { return false; } } return true; } public Collection<Block> getBlocks(int dayOfMonth) { int index = dayOfMonth-1; return Collections.unmodifiableCollection(slots[ index ].getBlocks()); } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.length;i++) { list.addAll(slots[i].getBlocks()); } return Collections.unmodifiableCollection( list ); } public void setEditable(boolean b) { super.setEditable( b); if ( slots == null ) return; // Hide the rest for (int i= 0;i<slots.length;i++) { SmallDaySlot slot = slots[i]; if (slot == null) continue; slot.setEditable(b); } } TableLayout tableLayout; public void rebuild() { // we need to clone the calendar, because we modify the calendar object in the getExclude() method Calendar counter = createCalendar(); Iterator<Builder> it= builders.iterator(); Date startDate = getStartDate(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(startDate,getEndDate() ); } // create fields slots = new SmallDaySlot[daysInMonth]; counter.setTime(startDate); int year = counter.get(Calendar.YEAR); SimpleDateFormat format = new SimpleDateFormat("MMMMMM",locale); String monthname = format.format(counter.getTime()); // calculate the blocks for (int i=0; i<daysInMonth; i++) { createField(i, counter.getTime()); counter.add(Calendar.DATE,1); } // clear everything jHeader.removeAll(); jCenter.removeAll(); monthTitle.setText( monthname + " " + year); // build Blocks it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } tableLayout= new TableLayout(); jCenter.setLayout(tableLayout); counter.setTime(startDate); int firstDayOfWeek = getFirstWeekday(); if ( counter.get(Calendar.DAY_OF_WEEK) != firstDayOfWeek) { counter.set(Calendar.DAY_OF_WEEK, firstDayOfWeek); if ( counter.getTime().after( startDate)) { counter.add(Calendar.DATE, -7); } } // add headers int offset = (int) DateTools.countDays(counter.getTime(),startDate); for (int i=0;i<COLUMNS;i++) { int weekday = counter.get(Calendar.DAY_OF_WEEK); if ( !isExcluded(i) ) { tableLayout.insertColumn(i, slotSize ); jHeader.add( createSlotHeader( weekday ) ); } else { tableLayout.insertColumn(i, 0); } counter.add(Calendar.DATE,1); } for (int i=0;i<ROWS;i++) { tableLayout.insertRow(i, TableLayout.PREFERRED ); } // add Fields counter.setTime(startDate); for (int i=0; i<daysInMonth; i++) { int column = (offset + i) % 7; int row = (counter.get(Calendar.DATE) + 6 - column ) / 7; if ( !isExcluded( column ) ) { jCenter.add( slots[i] , "" + column + "," + row); } counter.add(Calendar.DATE,1); } selectionHandler.clearSelection(); jHeader.validate(); jCenter.validate(); if ( isEditable()) { updateSize(component.getSize().width); } component.revalidate(); component.repaint(); } private void createField(int pos, Date date) { slots[pos]= createSmallslot(pos, date); } protected SmallDaySlot createSmallslot(int pos, Date date) { String headerText = "" + (pos + 1); Color headerColor = getNumberColor( date); Color headerBackground = null; return createSmallslot(headerText, headerColor,headerBackground); } protected SmallDaySlot createSmallslot(String headerText, Color headerColor, Color headerBackground) { return createSmallslot(headerText, slotSize,headerColor,headerBackground); } protected SmallDaySlot createSmallslot(String headerText, int width, Color headerColor, Color headerBackground ) { SmallDaySlot c= new SmallDaySlot(headerText, width, headerColor, headerBackground); c.setEditable(isEditable()); c.setDraggingHandler(draggingHandler); c.addMouseListener(selectionHandler); c.addMouseMotionListener(selectionHandler); return c; } public static Color DATE_NUMBER_COLOR = Color.gray; /** * @param date */ protected Color getNumberColor( Date date) { return DATE_NUMBER_COLOR; } /** override this method, if you want to create your own header. */ protected JComponent createSlotHeader(int weekday) { JLabel jLabel = new JLabel(); jLabel.setBorder(isEditable() ? SLOTHEADER_BORDER : null); jLabel.setText( getWeekdayName(weekday) ); jLabel.setFont(new Font("SansSerif", Font.PLAIN, 13)); jLabel.setHorizontalAlignment(JLabel.CENTER); jLabel.setOpaque(false); jLabel.setForeground(Color.black); Dimension dim = new Dimension(this.slotSize,20); jLabel.setPreferredSize( dim); jLabel.setMinimumSize( dim ); jLabel.setMaximumSize( dim ); return jLabel; } public void addBlock(Block bl, int col,int slot) { checkBlock( bl ); // System.out.println("Put " + bl.getStart() + " into field " + (date -1)); slots[col].putBlock((SwingBlock)bl); } public int getSlotNr( DaySlot slot) { for (int i=0;i<slots.length;i++) if (slots[i] == slot) return i; throw new IllegalStateException("Slot not found in List"); } public boolean isSelected(int nr) { SmallDaySlot slot = getSlot(nr); if ( slot == null) { return false; } return slot.isSelected(); } int getRowsPerDay() { return 1; } SmallDaySlot getSlot(int nr) { if ( nr >=0 && nr< slots.length) return slots[nr]; else return null; } int getDayCount() { return slots.length; } int calcSlotNr(int x, int y) { for (int i=0;i<slots.length;i++) { if (slots[i] == null) continue; Point p = slots[i].getLocation(); if ((p.x <= x) && (x <= p.x + slots[i].getWidth()) && (p.y <= y) && (y <= p.y + slots[i].getHeight()) ) { return i; } } return -1; } SmallDaySlot calcSlot(int x,int y) { int nr = calcSlotNr(x, y); if (nr == -1) { return null; } else { return slots[nr]; } } Date createDate(DaySlot slot, int row, boolean startOfRow) { Calendar calendar = createCalendar(); calendar.setTime( getStartDate() ); int dayOfMonth = getSlotNr( slot ) +1; calendar.set( Calendar.DAY_OF_MONTH, dayOfMonth); if ( !startOfRow ) { calendar.add( Calendar.DATE , 1 ); } calendar.set( Calendar.HOUR_OF_DAY, 0 ); calendar.set( Calendar.MINUTE, 0 ); calendar.set( Calendar.SECOND, 0 ); calendar.set( Calendar.MILLISECOND, 0 ); return calendar.getTime(); } @Override public void updateSize(int width) { int columnSize = tableLayout.getNumColumn(); int newWidth = Math.max( minBlockWidth , (width - 10 ) / (Math.max(1,columnSize))); for (SmallDaySlot slot: this.slots) { if ( slot != null) { slot.updateSize(newWidth); } } setSlotSize(newWidth); for ( int i=0;i< columnSize;i++) { tableLayout.setColumn(i, newWidth); } for (Component comp:jHeader.getComponents()) { double height = comp.getPreferredSize().getHeight(); Dimension dim = new Dimension( newWidth,(int) height); comp.setPreferredSize(dim); comp.setMaximumSize(dim); comp.setMinimumSize( dim); comp.invalidate(); } jCenter.invalidate(); jCenter.repaint(); } }
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.components.calendarview.swing; import java.awt.Cursor; import java.awt.Point; import java.awt.event.MouseEvent; import java.util.Date; import org.rapla.components.calendarview.swing.scaling.IRowScaleSmall; import org.rapla.components.calendarview.swing.scaling.OneRowScale; import org.rapla.components.util.TimeInterval; /** DraggingHandler coordinates the drag events from the Block-Components * between the different MultiSlots of a weekview. */ class DraggingHandler { int draggingPointOffset = 0; DaySlot oldSlot; int oldY = 0; int oldHeight = 0; AbstractSwingCalendar m_cv; Date start = null; Date newStart = null; Date end = null; Date newEnd = null; int resizeDirection; boolean bMoving; boolean bResizing; boolean supportsResizing; IRowScaleSmall rowScale; public DraggingHandler(AbstractSwingCalendar wv,IRowScaleSmall rowScale, boolean supportsResizing) { this.supportsResizing = supportsResizing; this.rowScale = rowScale; m_cv = wv; } public DraggingHandler(AbstractSwingCalendar wv, boolean supportsResizing) { this ( wv, new OneRowScale(), supportsResizing ); } public boolean supportsResizing() { return supportsResizing; } public void blockPopup(SwingBlock block,Point p) { m_cv.fireBlockPopup(block,p); } public void blockEdit(SwingBlock block,Point p) { m_cv.fireBlockEdit(block,p); } public void mouseReleased(DaySlot slot, SwingBlock block, MouseEvent evt) { if ( isDragging() ) stopDragging(slot, block, evt); } public void blockBorderPressed(DaySlot slot,SwingBlock block,MouseEvent evt, int direction) { if (!bResizing && supportsResizing ) { this.resizeDirection = direction; startResize( slot, block, evt); } } public boolean isDragging() { return bResizing || bMoving; } public void mouseDragged(DaySlot slot,SwingBlock block,MouseEvent evt) { if ( bResizing ) startResize( slot, block, evt ); else startMoving( slot, block, evt ); } private void dragging(DaySlot slot,SwingBlock block,int _x,int _y,boolean bDragging) { // 1. Calculate slot DaySlot newSlot = null; if ( bResizing ) { newSlot = slot; } else { int slotNr = m_cv.calcSlotNr( slot.getLocation().x + _x , slot.getLocation().y + _y); newSlot = m_cv.getSlot( slotNr ); if (newSlot == null) return; } // 2. Calculate new x relative to slot int y = _y; int xslot = 0; int height = block.getView().getHeight(); xslot = newSlot.calcSlot( slot.getLocation().x + _x - newSlot.getLocation().x ); if ( bResizing ) { if ( resizeDirection == 1) { y = block.getView().getLocation().y; // we must trim the endRow int endrow = newSlot.calcRow(_y ) + 1; endrow = Math.max( newSlot.calcRow(y) + 2, endrow); height = rowScale.getYCoordForRow(endrow) - y; if ( bDragging ) { start = block.getStart(); end = m_cv.createDate( newSlot, endrow, true); //System.out.println ( "Resizeing@end: start=" + start + ", end=" + end) ; } } else if (resizeDirection == -1){ // we must trim y y = rowScale.trim( y ); int row = newSlot.calcRow( y ) ; int rowSize = rowScale.getRowSizeForRow( row ); y = Math.min ( block.getView().getLocation().y + block.getView().getHeight() - rowSize, y ); height = block.getView().getLocation().y + block.getView().getHeight() - y; if ( bDragging ) { row = newSlot.calcRow( y ); if(y==0) start = m_cv.createDate( newSlot, row, true); else start = m_cv.createDate( newSlot, row, false); end = block.getEnd(); //System.out.println ( "Resizeing@start: start=" + start + ", end=" + end) ; } } } else if (bMoving){ // we must trim y //y = rowScale.trim( y); if ( bDragging ) { int newRow = newSlot.calcRow( y ); start = m_cv.createDate( newSlot, newRow, true); y = rowScale.trim( y ); //System.out.println ( "Moving: start=" + start + ", end=" + end +" row: " + row) ; } } if (oldSlot != null && oldSlot != newSlot) oldSlot.paintDraggingGrid(xslot, y, height, block, oldY, oldHeight, false); newSlot.paintDraggingGrid(xslot, y, height, block, oldY, oldHeight, bDragging); oldSlot = newSlot; oldY = y; oldHeight = height; } private void startMoving(DaySlot slot,SwingBlock block,MouseEvent evt) { if (!bMoving) { draggingPointOffset = evt.getY(); if (block.isMovable()) { bMoving = true; slot.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } else { bMoving = false; slot.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); return; } } if ( block == null) return; int x = evt.getX() + slot.getX(block.getView()); int y = evt.getY() + block.getView().getLocation().y; scrollTo( slot, x, y); // Correct y with the draggingPointOffset y = evt.getY() - draggingPointOffset + block.getView().getLocation().y ; y += rowScale.getDraggingCorrection(y ) ; dragging( slot, block, x, y, bMoving); } private void startResize(DaySlot slot,SwingBlock block, MouseEvent evt) { if ( block == null) return; int x = evt.getX() + slot.getX(block.getView()); int y = evt.getY() + block.getView().getLocation().y; if (!bResizing) { if (block.isMovable() && ( ( resizeDirection == -1 && block.isStartResizable() ) || ( resizeDirection == 1 && block.isEndResizable()))) { bResizing = true; } else { bResizing = false; return; } } scrollTo( slot, x, y); dragging( slot, block, x, y, bResizing); } private void stopDragging(DaySlot slot, SwingBlock block,MouseEvent evt) { slot.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); if ( block == null) { return ; } if (!m_cv.isEditable()) return; try { int x = evt.getX() + slot.getX( block.getView() ); int y = evt.getY() - draggingPointOffset + block.getView().getLocation().y ; y += rowScale.getDraggingCorrection(y ); dragging(slot,block,x,y,false); Point upperLeft = m_cv.getScrollPane().getViewport().getViewPosition(); Point newPoint = new Point(slot.getLocation().x + x -upperLeft.x ,y-upperLeft.y); int slotNr = m_cv.getSlotNr(oldSlot); TimeInterval normalizedInterval = m_cv.normalizeBlockIntervall(block); Date blockStart = normalizedInterval.getStart(); Date blockEnd = normalizedInterval.getEnd(); if ( bMoving ) { // Has the block moved //System.out.println("Moved to " + newStart + " - " + newEnd); if ( !start.equals( blockStart ) || oldSlot!= slot) { m_cv.fireMoved(block, newPoint, start, slotNr); } } if ( bResizing ) { // System.out.println("Resized to " + start + " - " + end); if ( !( start.equals( blockStart ) && end.equals( blockEnd) )) { m_cv.fireResized(block, newPoint, start, end, slotNr); } } } finally { bResizing = false; bMoving = false; start = null; end = null; } } // Begin scrolling when hitting the upper or lower border while // dragging or selecting. private void scrollTo(DaySlot slot,int x,int y) { // 1. Transfer p.x relative to jCenter m_cv.scrollTo(slot.getLocation().x + x, slot.getLocation().y + y); } }
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.components.calendarview.swing; import java.awt.Component; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Date; import javax.swing.SwingUtilities; /** SelectionHandler handles the selection events and the Slot * Context Menu (right click). * This is internally used by the weekview to communicate with its slots. */ public class SelectionHandler extends MouseAdapter { Date start; Date end; boolean bPopupClicked = false; boolean bSelecting = false; public int selectionStart = -1; public int selectionEnd = -1; private int oldIndex = -1; private int oldSlotNr = -1; private int startSlot = -1; private int endSlot = -1; private int draggingSlot = -1; private int draggingIndex = -1; AbstractSwingCalendar m_wv; public enum SelectionStrategy { FLOW,BLOCK; } SelectionStrategy selectionStrategy = SelectionStrategy.FLOW; public SelectionHandler(AbstractSwingCalendar wv) { m_wv = wv; } public void mouseClicked(MouseEvent evt) { if (evt.isPopupTrigger()) { bPopupClicked = true; slotPopup(evt); } else { /* We don't check click here if (SwingUtilities.isLeftMouseButton(evt)) move(evt); */ } } public void mousePressed(MouseEvent evt) { if (evt.isPopupTrigger()) { bPopupClicked = true; move(evt, true); slotPopup(evt); } else { if (SwingUtilities.isLeftMouseButton(evt)) move(evt,false); } } public void mouseReleased(MouseEvent evt) { if (evt.isPopupTrigger()) { bPopupClicked = true; move(evt, true); slotPopup(evt); } if (SwingUtilities.isLeftMouseButton(evt) && !bPopupClicked) move(evt, false); bPopupClicked = false; bSelecting = false; } public void mouseDragged(MouseEvent evt) { if (SwingUtilities.isLeftMouseButton(evt) && !bPopupClicked) move(evt, false); } public void mouseMoved(MouseEvent evt) { } public void setSelectionStrategy(SelectionStrategy strategy) { selectionStrategy = strategy; } public void clearSelection() { for (int i=0;i<m_wv.getDayCount();i++) { if (m_wv.getSlot(i) != null) { m_wv.getSlot(i).unselectAll(); } } selectionStart = -1; selectionEnd = -1; oldIndex = -1; oldSlotNr = -1; startSlot = -1; endSlot = -1; draggingSlot = -1; draggingIndex = -1; } public void slotPopup(MouseEvent evt) { Point p = new Point(evt.getX(),evt.getY()); DaySlot slot= (DaySlot)evt.getSource(); if (start == null || end == null) { int index = slot.calcRow( evt.getY() ); start = m_wv.createDate(slot, index, true); end = m_wv.createDate(slot, index, false); clearSelection(); slot.select(index,index); } m_wv.fireSelectionPopup((Component)slot,p,start,end,m_wv.getSlotNr( slot )); } public void move(MouseEvent evt, boolean contextPopup) { if (!m_wv.isEditable()) return; DaySlot source = (DaySlot) evt.getSource(); int slotNr; { Point location = source.getLocation(); slotNr = m_wv.calcSlotNr( location.x + evt.getX() ,location.y + evt.getY() ); } if (slotNr == -1) return; int selectedIndex = source.calcRow(evt.getY()); if ( contextPopup && inCurrentSelection(slotNr,selectedIndex)) { return; } if (!bSelecting) { clearSelection(); bSelecting = true; selectionStart = selectedIndex; selectionEnd = selectedIndex; draggingSlot =slotNr; draggingIndex = selectedIndex; startSlot = slotNr; endSlot = slotNr; } else { if (slotNr == draggingSlot) { startSlot = endSlot = slotNr; if ( selectedIndex > draggingIndex ) { selectionStart = draggingIndex; selectionEnd = selectedIndex; } else if (selectedIndex < draggingIndex ){ selectionStart = selectedIndex; selectionEnd = draggingIndex; } } else if (slotNr > draggingSlot) { startSlot = draggingSlot; selectionStart = draggingIndex; endSlot = slotNr; selectionEnd = selectedIndex; } else if (slotNr < draggingSlot) { startSlot = slotNr; selectionStart = selectedIndex; endSlot = draggingSlot; selectionEnd = draggingIndex; } if (selectedIndex == oldIndex && slotNr == oldSlotNr) { return; } int rowsPerDay = m_wv.getRowsPerDay(); if (selectedIndex >= rowsPerDay-1) { selectedIndex = rowsPerDay-1; } } oldSlotNr = slotNr; oldIndex = selectedIndex; switch ( selectionStrategy) { case BLOCK: setSelectionBlock();break; case FLOW: setSelectionFlow();break; } { Point location = m_wv.getSlot(slotNr).getLocation(); m_wv.scrollTo( location.x + evt.getX() ,location.y + evt.getY() ); } } private boolean inCurrentSelection(int slotNr, int selectedIndex) { if ( slotNr < startSlot || slotNr > endSlot) { return false; } if (slotNr == startSlot && selectedIndex < selectionStart) { return false; } if (slotNr == endSlot && selectedIndex > selectionEnd) { return false; } return true; } protected void setSelectionFlow() { int startRow = selectionStart; int endRow = m_wv.getRowsPerDay() -1; for (int i=0;i<startSlot;i++) { DaySlot daySlot = m_wv.getSlot(i); if (daySlot != null) { daySlot.unselectAll(); } } int dayCount = m_wv.getDayCount(); for (int i=startSlot;i<=endSlot;i++) { if (i > startSlot) { startRow = 0; } if (i == endSlot) { endRow = selectionEnd; } DaySlot slot = m_wv.getSlot(i); if (slot != null) { slot.select(startRow,endRow); } } startRow = selectionStart ; endRow = selectionEnd ; for (int i=endSlot+1;i<dayCount;i++) { DaySlot slot = m_wv.getSlot(i); if (slot != null) { slot.unselectAll(); } } start = m_wv.createDate(m_wv.getSlot(startSlot),startRow, true); end = m_wv.createDate(m_wv.getSlot(endSlot),endRow, false); m_wv.fireSelectionChanged(start,end); } protected void setSelectionBlock() { int startRow = selectionStart; int endRow = selectionEnd; Point endSlotLocation = m_wv.getSlot(endSlot).getLocation(); Point startSlotLocation = m_wv.getSlot(startSlot).getLocation(); int min_y = Math.min(startSlotLocation.y, endSlotLocation.y); int min_x = Math.min(startSlotLocation.x, endSlotLocation.x); int max_y = Math.max(startSlotLocation.y, endSlotLocation.y); int max_x = Math.max(startSlotLocation.x, endSlotLocation.x); int dayCount = m_wv.getDayCount(); for (int i=0;i<dayCount;i++) { DaySlot slot = m_wv.getSlot(i); if (slot != null) { Point location = slot.getLocation(); if ( location.x >= min_x && location.x <= max_x && location.y >= min_y && location.y <= max_y) { slot.select(startRow,endRow); } else { slot.unselectAll(); } } } start = m_wv.createDate(m_wv.getSlot(startSlot),startRow, true); end = m_wv.createDate(m_wv.getSlot(endSlot),endRow, false); m_wv.fireSelectionChanged(start,end); } }
Java
package org.rapla.components.calendarview.swing.scaling; import java.util.Date; public interface IRowScale extends IRowScaleSmall { int calcHour( int index ); int calcMinute( int index ); int getSizeInPixel(); int getMaxRows(); int getRowsPerDay(); int getYCoord( Date time ); int getStartWorktimePixel(); int getEndWorktimePixel(); int getSizeInPixelBetween( int startRow, int endRow ); boolean isPaintRowThick( int row ); }
Java
package org.rapla.components.calendarview.swing.scaling; public interface IRowScaleSmall { int getYCoordForRow( int row ); int getRowSizeForRow( int row ); int calcRow( int y ); int trim( int y ); int getDraggingCorrection(int y); }
Java
package org.rapla.components.calendarview.swing.scaling; public class OneRowScale implements IRowScaleSmall { public int getYCoordForRow( int row ) { return 0; } public int getRowSizeForRow( int row ) { return 15; } public int calcRow( int y ) { return 0; } public int trim( int y ) { return 0; } public int getDraggingCorrection( int y) { return 15 / 2; } }
Java
package org.rapla.components.calendarview.swing.scaling; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class LinearRowScale implements IRowScale { private int rowSize = 15; private int rowsPerHour = 4; final private static int MINUTES_PER_HOUR= 60; private TimeZone timeZone = TimeZone.getDefault(); private int mintime; private int maxtime; private int workstartMinutes; private int workendMinutes; public LinearRowScale() { } public void setTimeZone( TimeZone timeZone) { this.timeZone = timeZone; } public int getRowsPerDay() { return rowsPerHour * 24; } public void setRowSize( int rowSize ) { this.rowSize = rowSize; } public int getRowSize() { return rowSize; } public int getRowsPerHour() { return rowsPerHour; } public void setRowsPerHour( int rowsPerHour ) { this.rowsPerHour = rowsPerHour; } public int calcHour(int index) { return index / rowsPerHour; } public int calcMinute(int index) { double minutesPerRow = 60. / rowsPerHour; long minute = Math.round((index % rowsPerHour) * (minutesPerRow)); return (int)minute; } public int getSizeInPixel() { return rowSize * getMaxRows(); } public int getMaxRows() { int max; max = (rowsPerHour * (maxtime - mintime)) / 60 ; return max; } private int getMinuteOfDay(Date time) { Calendar cal = getCalendar(); cal.setTime(time); return (cal.get(Calendar.HOUR_OF_DAY )) * MINUTES_PER_HOUR + cal.get(Calendar.MINUTE); } public int getYCoord(Date time) { int diff = getMinuteOfDay(time) - mintime ; int pixelPerHour= rowSize * rowsPerHour; return (diff * pixelPerHour) / MINUTES_PER_HOUR; } public int getStartWorktimePixel() { int pixelPerHour= rowSize * rowsPerHour; int starty = (int) (pixelPerHour * workstartMinutes / 60.); return starty; } public int getEndWorktimePixel() { int pixelPerHour= rowSize * rowsPerHour; int endy = (int) (pixelPerHour * workendMinutes / 60.); return endy; } private Calendar calendar = null; private Calendar getCalendar() { // Lazy creation of the calendar if (calendar == null) calendar = Calendar.getInstance(timeZone); return calendar; } public boolean isPaintRowThick( int row ) { return row % rowsPerHour == 0; } public void setTimeIntervall( int startMinutes, int endMinutes ) { mintime = startMinutes; maxtime = endMinutes; } public void setWorktimeMinutes( int workstartMinutes, int workendMinutes ) { this.workstartMinutes = workstartMinutes; this.workendMinutes = workendMinutes; } public int getYCoordForRow( int row ) { return row * rowSize; } public int getSizeInPixelBetween( int startRow, int endRow ) { return (endRow - startRow) * rowSize; } public int getRowSizeForRow( int row ) { return rowSize; } public int calcRow(int y) { int rowsPerDay = getRowsPerDay(); int row = (y-3) / rowSize; return Math.min(Math.max(0, row), rowsPerDay -1); } public int trim(int y ) { return (y / rowSize) * rowSize; } public int getDraggingCorrection( int y) { return rowSize / 2; } }
Java
package org.rapla.components.calendarview.swing.scaling; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class VariableRowScale implements IRowScale { PeriodRow[] periodRows; private int hourSize = 60; final private static int MINUTES_PER_HOUR= 60; private TimeZone timeZone = TimeZone.getDefault(); private int mintime =0 ; /* private int maxtime = 24; private int workstart = 0; private int workend = 24; */ class PeriodRow { int minutes; int ypos; int startMinute; PeriodRow( int minutes ) { this.minutes = minutes; } public int getRowSize() { return (minutes * hourSize) / 60; } } public VariableRowScale() { periodRows = new PeriodRow[] { new PeriodRow( 60 * 8 ), new PeriodRow( 45 ), new PeriodRow( 60 ), new PeriodRow( 10 ), new PeriodRow( 110 ), new PeriodRow( 60 + 15), new PeriodRow( 60 * 3 ), new PeriodRow( 60 * 8 ) }; for ( int i=0;i< periodRows.length-1;i++) { periodRows[i+1].ypos = periodRows[i].ypos + periodRows[i].getRowSize(); periodRows[i+1].startMinute = periodRows[i].startMinute + periodRows[i].minutes; } } public void setTimeZone( TimeZone timeZone) { this.timeZone = timeZone; } public int getRowsPerDay() { return periodRows.length; } public int getSizeInPixel() { PeriodRow lastRow = getLastRow(); return lastRow.ypos + lastRow.getRowSize(); } public int getMaxRows() { return periodRows.length; } private int getMinuteOfDay(Date time) { Calendar cal = getCalendar(); cal.setTime(time); return (cal.get(Calendar.HOUR_OF_DAY )) * MINUTES_PER_HOUR + cal.get(Calendar.MINUTE); } public int calcHour(int index) { return periodRows[index].startMinute / MINUTES_PER_HOUR; } public int calcMinute(int index) { return periodRows[index].startMinute % MINUTES_PER_HOUR; } public int getYCoord(Date time) { int diff = getMinuteOfDay(time) - mintime * MINUTES_PER_HOUR ; return (diff * hourSize) / MINUTES_PER_HOUR; } public int getStartWorktimePixel() { return periodRows[0].getRowSize(); } public int getEndWorktimePixel() { PeriodRow lastRow = getLastRow(); return lastRow.ypos; } private PeriodRow getLastRow() { PeriodRow lastRow = periodRows[periodRows.length-1]; return lastRow; } private Calendar calendar = null; private Calendar getCalendar() { // Lazy creation of the calendar if (calendar == null) calendar = Calendar.getInstance(timeZone); return calendar; } public boolean isPaintRowThick( int row ) { return true; } /* public void setTimeIntervall( int startHour, int endHour ) { mintime = startHour; maxtime = endHour; } public void setWorktime( int startHour, int endHour ) { workstart = startHour; workend = endHour; } */ public int getYCoordForRow( int row ) { if ( row < 0 || row >= periodRows.length) { return row* 400; } return periodRows[row].ypos; } public int getSizeInPixelBetween( int startRow, int endRow ) { if ( startRow < 0 || endRow < 0 || startRow >= periodRows.length || endRow >=periodRows.length) { return (endRow - startRow) * 400; } return periodRows[endRow].ypos - periodRows[startRow].ypos; } public int getRowSizeForRow( int row ) { /* if ( row < 0 || row >= periodRows.length) { return 60; } */ return periodRows[row].getRowSize(); } public int calcRow(int y) { for ( int i=0;i< periodRows.length;i++) { PeriodRow row =periodRows[i]; if (row.ypos + row.getRowSize() >=y) return i; } return 0; } public int trim(int y ) { int row = calcRow( y ); int rowSize = getRowSizeForRow( row); return (y / rowSize) * rowSize; } public int getDraggingCorrection(int y) { return 0; } }
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.components.calendarview.swing; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.swing.scaling.IRowScale; /** Komponente, welche eine beliebige anzahl von Slot-komponenten zusammenfasst. * die slots koennen zur laufzeit hinzugefuegt oder auch dynamisch bei bedarf *erzeugt werden. sie werden horizontal nebeneinander angeordnet. */ class LargeDaySlot extends AbstractDaySlot { private static final long serialVersionUID = 1L; public static Color THICK_LINE_COLOR = Color.black; public static Color LINE_COLOR = new Color(0xaa, 0xaa, 0xaa); public static Color WORKTIME_BACKGROUND = Color.white; public static Color NON_WORKTIME_BACKGROUND = new Color(0xcc, 0xcc, 0xcc); private List<Slot> slots= new ArrayList<Slot>(); private int slotxsize; private int selectionStart = -1; private int selectionEnd = -1; private int oldSelectionStart = -1; private int oldSelectionEnd = -1; BoxLayout boxLayout1 = new BoxLayout(this, BoxLayout.X_AXIS); int right_gap = 8; int left_gap = 5; int slot_space = 3; JComponent header; IRowScale rowScale; private BlockListener blockListener = new BlockListener(); /** es muss auch noch setTimeIntervall() aufgerufen werden, um die initialisierung fertig zu stellen (wie beim konstruktor von Slot). slotxsize ist die breite der einzelnen slots. "date" legt das Datum fest, fuer welches das Slot anzeigt (Uhrzeit bleibt unberuecksichtigt) */ public LargeDaySlot( int slotxsize ,IRowScale rowScale ,JComponent header) { this.slotxsize= slotxsize; this.rowScale = rowScale; this.header = header; setLayout(boxLayout1); this.add(Box.createHorizontalStrut(left_gap)); addSlot(); setBackground(getBackground()); setAlignmentX(0); setAlignmentY(TOP_ALIGNMENT); this.setBackground(Color.white); } public boolean isBorderVisible() { return true; // return getBackground() != Color.white; } public int getSlotCount() { return slots.size(); } public boolean isSelected() { return selectionStart >=0 ; } public void setVisible(boolean b) { super.setVisible(b); header.setVisible(b); } public JComponent getHeader() { return header; } public int calcSlot(int x) { int slot = ((x - left_gap) / (slotxsize + slot_space)); //System.out.println ( x + " slot " + slot); if (slot<0) slot = 0; if (slot >= slots.size()) slot = slots.size() -1; return slot; } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.size();i++) list.addAll(slots.get(i).getBlocks()); return list; } public void select(int start,int end) { if (start == selectionStart && end == selectionEnd) return; selectionStart = start; selectionEnd = end; invalidateSelection(); } public void unselectAll() { if (selectionStart == -1 || selectionEnd == -1) return; selectionStart = -1; selectionEnd = -1; invalidateSelection(); } public void setTimeIntervall() { Iterator<Slot> it= slots.iterator(); while (it.hasNext()) { Slot slot = it.next(); slot.setTimeIntervall(); } } private int addSlot() { Slot slot= new Slot(); slot.setTimeIntervall(); slots.add(slot); this.add(slot); this.add(Box.createHorizontalStrut(slot_space)); updateHeaderSize(); return slots.size()-1; } public void updateHeaderSize() { Dimension size = header.getPreferredSize(); Dimension newSize = new Dimension(slotxsize * slots.size() //Slotwidth and border + slot_space * slots.size() //Space between Slots + left_gap + right_gap // left and right gap , (int)size.getHeight()); header.setPreferredSize(newSize); header.setMaximumSize(newSize); header.invalidate(); } /** fuegt einen block im gewuenschten slot ein (konflikte werden ignoriert). */ public void putBlock(SwingBlock bl, int slotnr) { while (slotnr >= slots.size()) { addSlot(); } slots.get(slotnr).putBlock(bl); // The blockListener can be shared among all blocks, // as long es we can only click on one block simultanously bl.getView().addMouseListener(blockListener); bl.getView().addMouseMotionListener(blockListener); blockViewMapper.put(bl.getView(),bl); } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); } Insets insets = new Insets(0,0,0, right_gap); Insets slotInsets = new Insets(0,0,0,0); public Insets getInsets() { return insets; } SwingBlock getBlockFor(Object component) { return blockViewMapper.get(component); } int getBlockCount() { int count = 0; Iterator<Slot> it = slots.iterator(); while (it.hasNext()) count += it.next().getBlockCount(); return count; } boolean isEmpty() { return getBlockCount() == 0; } protected void invalidateDragging(Point oldPoint) { int width = getSize().width; int startRow = Math.min(calcRow(draggingY),calcRow(oldPoint.y )); int endRow = Math.max(calcRow(draggingY),calcRow(oldPoint.y )) + 1; repaint(0 , rowScale.getYCoordForRow(startRow) -10 , width , rowScale.getSizeInPixelBetween(startRow, endRow) + draggingHeight + 20 ); } private void invalidateSelection() { int width = getSize().width; int startRow = Math.min(selectionStart,oldSelectionStart); int endRow = Math.max(selectionEnd,oldSelectionEnd) + 1; repaint(0,rowScale.getYCoordForRow(startRow ), width, rowScale.getSizeInPixelBetween(startRow, endRow )); // Update the values after calling repaint, because paint needs the old values. oldSelectionStart = selectionStart; oldSelectionEnd = selectionEnd; } public void paint(Graphics g) { Dimension dim = getSize(); Rectangle rect = g.getClipBounds(); if (!isEditable()) { g.setColor(Color.white); g.fillRect(rect.x ,rect.y ,rect.width ,rect.height); } else { int starty = rowScale.getStartWorktimePixel(); int endy = rowScale.getEndWorktimePixel(); int height = rowScale.getSizeInPixel(); Color firstColor = NON_WORKTIME_BACKGROUND; Color secondColor = WORKTIME_BACKGROUND; if ( starty >= endy) { int c = starty; starty = endy; endy = c; secondColor = NON_WORKTIME_BACKGROUND; firstColor = WORKTIME_BACKGROUND; } if (rect.y - rect.height <= starty) { g.setColor( firstColor ); g.fillRect(rect.x ,Math.max(rect.y,0) ,rect.width ,Math.min(rect.height,starty)); } if (rect.y + rect.height >= starty && rect.y <= endy ) { g.setColor( secondColor ); g.fillRect(rect.x ,Math.max(rect.y,starty) ,rect.width ,Math.min(rect.height,endy - starty)); } if (rect.y + rect.height >= endy) { g.setColor( firstColor ); g.fillRect(rect.x ,Math.max(rect.y,endy) ,rect.width ,Math.min(rect.height, height - endy)); } } if (isBorderVisible()) { g.setColor(LINE_COLOR); g.drawLine(0,rect.y,0,rect.y + rect.height); g.drawLine(dim.width - 1,rect.y,dim.width - 1 ,rect.y + rect.height); } int max = rowScale.getMaxRows() ; // Paint selection for (int i=0; i < max ; i++) { int rowSize = rowScale.getRowSizeForRow( i); int y = rowScale.getYCoordForRow( i); if ((y + rowSize) >= rect.y && y < (rect.y + rect.height)) { if (i>= selectionStart && i<=selectionEnd) { g.setColor(getSelectionColor()); g.fillRect(Math.max (rect.x,1) , y , Math.min (rect.width,dim.width - Math.max (rect.x,1) - 1) , rowSize); } boolean bPaintRowThick = (rowScale.isPaintRowThick(i)); g.setColor((bPaintRowThick) ? THICK_LINE_COLOR : LINE_COLOR); if (isEditable() || (bPaintRowThick && (i<max || isBorderVisible()))) g.drawLine(rect.x,y ,rect.x + rect.width , y); if ( i == max -1 ) { g.setColor( THICK_LINE_COLOR ); g.drawLine(rect.x,y+rowSize ,rect.x + rect.width , y+rowSize); } } } super.paintChildren(g); if ( paintDraggingGrid ) { int x = draggingSlot * (slotxsize + slot_space) + left_gap; paintDraggingGrid(g, x , draggingY, slotxsize -1, draggingHeight); } } /** grafische komponente, in die implementierungen von Block (genauer deren zugehoerige BlockViews) eingefuegt werden koennen. * entsprechend start- und end-zeit des blocks wird der view * im slot dargestellt. die views werden dabei vertikal angeordnet. */ class Slot extends JPanel { private static final long serialVersionUID = 1L; private Collection<Block> blocks= new ArrayList<Block>(); public Slot() { setLayout(null); setBackground(Color.white); setOpaque(false); } /** legt fest, fuer welches zeitintervall das slot gelten soll. (Beispiel 8:00 - 13:00) min und max sind uhrzeiten in vollen stunden. zur initialisierung der komponente muss diese methode mindestens einmal aufgerufen werden. */ public void setTimeIntervall() { int ysize= rowScale.getSizeInPixel() + 1; setSize(slotxsize, ysize); Dimension preferredSize = new Dimension(slotxsize, ysize ); setPreferredSize(preferredSize ); setMinimumSize(preferredSize ); } /** fuegt b in den Slot ein. */ public void putBlock(SwingBlock b) { blocks.add(b); add(b.getView()); updateBounds(b); } public void updateBounds(SwingBlock b) { //update bounds int y1= rowScale.getYCoord(b.getStart()); final int minimumSize = 15; int y2= Math.max( y1+minimumSize,rowScale.getYCoord(b.getEnd())); if ( y1 < 0) y1 = 0; if ( y2 > getMaximumSize().height) y2 = getMaximumSize().height; b.getView().setBounds(0, y1, slotxsize, y2 - y1 + 1); } public int getBlockCount() { return blocks.size(); } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); } public Insets getInsets() { return slotInsets; } public Collection<Block> getBlocks() { return blocks; } } void updateSize(int slotsize) { this.slotxsize = slotsize; for ( Slot slot:slots) { slot.setTimeIntervall(); for (Block block:slot.getBlocks()) { slot.updateBounds((SwingBlock)block); } } updateHeaderSize(); } public int calcRow( int y ) { return rowScale.calcRow( y); } }
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.components.calendarview.swing; import java.awt.Component; import java.awt.Point; import java.util.Date; import org.rapla.components.calendarview.Block; /** Listeners for user-changes in the weekview.*/ public interface ViewListener { /** Invoked when the user invokes the slot-contex (right-clicks on slot). The selected area and suggested coordinates at which the popup menu can be shown are passed.*/ void selectionPopup(Component slotComponent,Point p,Date start,Date end, int slotNr); /** Invoked when the selection has changed.*/ void selectionChanged(Date start,Date end); /** Invoked when the user invokes a block-context (right-clicks on a block). The suggested coordinates at which the popup menu can be shown are passed.*/ void blockPopup(Block block,Point p); /** Invoked when the user invokes a block-edit (double-clicks on a block). The suggested coordinates at which the popup menu can be shown are passed.*/ void blockEdit(Block block,Point p); /** Invoked when the user has dragged/moved a block */ void moved(Block block,Point p,Date newStart, int slotNr); /** Invoked when the user has resized a block */ void resized(Block block,Point p,Date newStart, Date newEnd, int slotNr); }
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.components.calendarview.swing; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.rapla.components.calendarview.Block; public class SmallDaySlot extends AbstractDaySlot { private static final long serialVersionUID = 1L; public static int BLOCK_HEIGHT = 32 +20; public static int START_GAP = 10; public static Color THICK_LINE_COLOR = Color.black; public static Color LINE_COLOR = new Color(0xaa, 0xaa, 0xaa); public static Color WORKTIME_BACKGROUND = Color.white; private List<Block> blocks = new LinkedList<Block>(); private int slotxsize; private Color headerColor; private Color headerBackground; private int rowSize = 15; private boolean selected; int slot_space = 3; private BlockListener blockListener = new BlockListener(); private String headerText; public SmallDaySlot(String headerText,int slotxsize,Color headerColor, Color headerBackground ) { this.headerColor = headerColor; this.headerBackground = headerBackground; this.slotxsize= slotxsize; this.headerText = headerText; setLayout( null ); setAlignmentX(0); setAlignmentY(TOP_ALIGNMENT); Dimension newSize = new Dimension(slotxsize, 10); setPreferredSize(newSize); this.setBackground(Color.white); } public boolean isBorderVisible() { return true; } public Collection<Block> getBlocks() { return blocks; } public void select(int startRow, int endRow) { boolean selected = (startRow >=0 || endRow>=0); if (this.selected == selected) return; this.selected = selected; invalidateSelection(); } public void unselectAll() { if (!selected ) return; selected = false; invalidateSelection(); } private void invalidateSelection() { repaint(); // Update the values after calling repaint, because paint needs the old values. } /** fuegt einen block im gewuenschten slot ein (konflikte werden ignoriert). */ public void putBlock(SwingBlock bl) { add( bl.getView() ); blocks.add( bl ); // The blockListener can be shared among all blocks, // as long as we can only click on one block simultaneously bl.getView().addMouseListener( blockListener ); bl.getView().addMouseMotionListener( blockListener ); blockViewMapper.put( bl.getView(), bl ); updateSize(); } public void updateSize() { int blockHeight = 0; for ( Block b:blocks) { blockHeight += getHeight( b); } int height = Math.max( 25, blockHeight + START_GAP ); Dimension newSize = new Dimension( slotxsize, height ); setPreferredSize( newSize ); updateBounds(); } private void updateBounds() { int y= START_GAP; for (int i=0;i< blocks.size();i++) { SwingBlock bl = (SwingBlock) blocks.get(i); int blockHeight = getHeight(bl); bl.getView().setBounds( 1 ,y, slotxsize -1, blockHeight-1); y+= blockHeight; } } /** * @param bl */ private int getHeight(Block bl) { int blockHeight = BLOCK_HEIGHT; // Special Solution for doubling the block height // if (DateTools.countMinutes(bl.getStart(), bl.getEnd()) >= 60) // { // blockHeight*= 2; // } return blockHeight; } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return getPreferredSize(); } Insets insets = new Insets(0,0,0, 0); public Insets getInsets() { return insets; } int getBlockCount() { return blocks.size(); } public boolean isEmpty() { return getBlockCount() == 0; } public int calcRow(int y) { return 0; } public int calcSlot(int x) { return 0; } public int getX(Component component) { return component.getLocation().x; } int max; public void paint(Graphics g) { Dimension dim = getSize(); Rectangle rect = g.getClipBounds(); g.setColor(getForeground()); if (selected) { g.setColor(getSelectionColor()); } else { g.setColor(getBackground()); } g.fillRect(rect.x , rect.y , rect.x + rect.width , rect.y + rect.height); if (isBorderVisible()) { g.setColor(LINE_COLOR); g.drawLine(0, rect.y, 0, rect.y + rect.height); g.drawLine(dim.width - 1, rect.y, dim.width - 1, rect.y + rect.height); g.drawLine(rect.x, 0, rect.x + rect.width, 0); g.drawLine(rect.x, dim.height - 1, rect.x + rect.width, dim.height - 1); } if ( headerText != null) { FontMetrics fontMetrics = g.getFontMetrics(); int headerWidth = fontMetrics.stringWidth(headerText); int headerHeight = 10;//fontMetrics.stringWidth(headerText); int x = Math.max(10, dim.width - headerWidth - 3); int y = Math.max(START_GAP, headerHeight); if ( headerBackground != null) { g.setColor(headerBackground); g.fillRect(1, y-headerHeight+1, dim.width -2, headerHeight); } g.setColor(headerColor); g.drawString(headerText, x, y); g.setColor(getForeground()); } super.paintChildren(g); if (paintDraggingGrid) { int height = draggingView.getView().getHeight() - 1; int x = 0; int y = draggingView.getView().getBounds().y; if (y + height + 2 > getHeight()) { y = getHeight() - height - 2; } paintDraggingGrid(g, x, y, slotxsize - 1, height); } } public int getRowSize() { return rowSize; } public boolean isSelected() { return selected ; } public void updateSize(int newWidth) { this.slotxsize = newWidth; updateSize(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann | | | | 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.components.calendarview; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; /** maps weekday names to Calendar.DAY_OF_WEEK. Example: <pre> WeekdayMapper mapper = new WeekdayMapper(); // print name of Sunday System.out.println(mapper.getName(Calendar.SUNDAY)); // Create a weekday ComboBox JComboBox comboBox = new JComboBox(); comboBox.setModel(new DefaultComboBoxModel(mapper.getNames())); // select sunday comboBox.setSelectedIndex(mapper.getIndexForDay(Calendar.SUNDAY)); // weekday == Calendar.SUNDAY int weekday = mapper.getDayForIndex(comboBox.getSelectedIndex()); </pre> */ public class WeekdayMapper { String[] weekdayNames; int[] weekday2index; int[] index2weekday; Map<Integer,String> map = new LinkedHashMap<Integer,String>(); public WeekdayMapper() { this(Locale.getDefault()); } public WeekdayMapper(Locale locale) { int days = 7; weekdayNames = new String[days]; weekday2index = new int[days+1]; index2weekday = new int[days+1]; SimpleDateFormat format = new SimpleDateFormat("EEEEEE",locale); Calendar calendar = Calendar.getInstance(locale); calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek()); for (int i=0;i<days;i++) { int weekday = calendar.get(Calendar.DAY_OF_WEEK); weekday2index[weekday] = i; index2weekday[i] = weekday; String weekdayName = format.format(calendar.getTime()); weekdayNames[i] = weekdayName; calendar.add(Calendar.DATE,1); map.put(weekday, weekdayName); } } public String[] getNames() { return weekdayNames; } public String getName(int weekday) { return map.get( weekday); } public int dayForIndex(int index) { return index2weekday[index]; } public int indexForDay(int weekday) { return weekday2index[weekday]; } }
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.components.calendarview; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.rapla.components.util.DateTools; import org.rapla.entities.domain.Allocatable; import org.rapla.plugin.abstractcalendar.AbstractRaplaBlock; /** Tries to put reservations that allocate the same Ressources in the same column.*/ public class GroupStartTimesStrategy extends AbstractGroupStrategy { List<Allocatable> allocatables; List<Integer> startTimes = new ArrayList<Integer>(); { for ( int i=0;i<=23;i++) { startTimes.add(i*60); } } @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) { AbstractRaplaBlock b = (AbstractRaplaBlock)block; for (Allocatable a:b.getReservation().getAllocatablesFor(b.getAppointment())) { int index = allocatables.indexOf( a ); if ( index >= 0 ) { map.put( block, index ); } } } return map; } else { return super.getBlockMap(wv, blocks); } } @Override protected List<List<Block>> getSortedSlots(List<Block> list) { TreeMap<Integer,List<Block>> groups = new TreeMap<Integer,List<Block>>(); for (Iterator<Block> it = list.iterator();it.hasNext();) { Block block = it.next(); long startTime = block.getStart().getTime(); int minuteOfDay = DateTools.getMinuteOfDay(startTime); int rowNumber = -1 ; for ( Integer start: startTimes) { if ( start <= minuteOfDay) { rowNumber++; } else { break; } } if ( rowNumber <0) { rowNumber = 0; } List<Block> col = groups.get( rowNumber ); if (col == null) { col = new ArrayList<Block>(); groups.put( rowNumber, col ); } col.add(block); } List<List<Block>> slots = new ArrayList<List<Block>>(); for (int row =0 ;row<startTimes.size();row++) { List<Block> oneRow = groups.get( row ); if ( oneRow == null) { oneRow = new ArrayList<Block>(); } else { Collections.sort( oneRow, blockComparator); } slots.add(oneRow); } return slots; } @Override protected Collection<List<Block>> group(List<Block> blockList) { List<List<Block>> singleGroup = new ArrayList<List<Block>>(); singleGroup.add(blockList); return singleGroup; } public List<Allocatable> getAllocatables() { return allocatables; } public void setAllocatables(List<Allocatable> allocatables) { this.allocatables = allocatables; } public List<Integer> getStartTimes() { return startTimes; } public void setStartTimes(List<Integer> startTimes) { this.startTimes = startTimes; } }
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.components.calendarview; import java.util.Comparator; /** Compares to blocks by the starting time. block1<block2 if * it block1.getStart()< block2.getStart(). */ public class BlockComparator implements Comparator<Block> { public static BlockComparator COMPARATOR = new BlockComparator(); public int compare(Block b1,Block b2) { int result = b1.getStart().compareTo(b2.getStart()); if (result != 0) return result; else return b1.getName().compareTo(b2.getName()); } }
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.components.calendarview; import java.util.List; public interface BuildStrategy { public void build(CalendarView wv,List<Block> blocks); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann | | | | 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.components.calendarview; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; /** maps weekday names to Calendar.DAY_OF_WEEK. Example: <pre> WeekdayMapper mapper = new WeekdayMapper(); // print name of Sunday System.out.println(mapper.getName(Calendar.SUNDAY)); // Create a weekday ComboBox JComboBox comboBox = new JComboBox(); comboBox.setModel(new DefaultComboBoxModel(mapper.getNames())); // select sunday comboBox.setSelectedIndex(mapper.getIndexForDay(Calendar.SUNDAY)); // weekday == Calendar.SUNDAY int weekday = mapper.getDayForIndex(comboBox.getSelectedIndex()); </pre> */ public class MonthMapper { String[] monthNames; public MonthMapper() { this(Locale.getDefault()); } public MonthMapper(Locale locale) { monthNames = new String[12]; SimpleDateFormat format = new SimpleDateFormat("MMMMMM",locale); Calendar calendar = Calendar.getInstance(locale); for (int i=0;i<12;i++) { calendar.set(Calendar.MONTH,i); monthNames[i] = format.format(calendar.getTime()); } } public String[] getNames() { return monthNames; } /** month are 0 based */ public String getName(int month) { return getNames()[month]; } }
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.components.calendarview; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** This strategy groups all blocks in a single group */ public class BestFitStrategy extends AbstractGroupStrategy { protected Collection<List<Block>> group(List<Block> blockList) { List<List<Block>> singleGroup = new ArrayList<List<Block>>(); singleGroup.add(blockList); return singleGroup; } }
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.components.calendarview; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.rapla.components.util.DateTools; /** Arranges blocks into groups, and tries to place one group into one slot. The subclass must overide the group method to perform the grouping on a given list of blocks. */ public abstract class AbstractGroupStrategy implements BuildStrategy { boolean m_sortSlotsBySize; public static long MILLISECONDS_PER_DAY = 24 * 3600 * 1000; private boolean m_fixedSlots; private boolean m_conflictResolving; protected Comparator<Block> blockComparator = new BlockComparator(); protected Comparator<List<Block>> slotComparator = new Comparator<List<Block>>() { public int compare(List<Block> s1,List<Block> s2) { if (s1.size() == 0 || s2.size() ==0) { if (s1.size() == s2.size()) return 0; else return s1.size() < s2.size() ? -1 : 1; } Block b1 = s1.get(0); Block b2 = s2.get(0); return b1.getStart().compareTo(b2.getStart()); } }; public void build(CalendarView wv, List<Block> blocks) { LinkedHashMap<Integer,List<Block>> days = new LinkedHashMap<Integer,List<Block>>(); Map<Block, Integer> blockMap = getBlockMap(wv, blocks); for (Block b:blockMap.keySet()) { Integer index = blockMap.get(b); List<Block> list = days.get(index); if (list == null) { list = new ArrayList<Block>(); days.put(index, list); } list.add(b); } for (Integer day: days.keySet()) { List<Block> list = days.get(day); Collections.sort(list, blockComparator); if (list == null) continue; insertDay( wv, day,list ); } } protected Map<Block,Integer> getBlockMap(CalendarView wv, List<Block> blocks) { Map<Block,Integer> map = new LinkedHashMap<Block, Integer>(); Date startDate = wv.getStartDate(); for (Block block:blocks) { int days = (int)DateTools.countDays(startDate, block.getStart()); map.put(block, days); } return map; } protected void insertDay(CalendarView wv, int column,List<Block> blockList) { Iterator<List<Block>> it = getSortedSlots(blockList).iterator(); int slotCount= 0; while (it.hasNext()) { List<Block> slot = it.next(); if (slot == null) { continue; } for (int i=0;i<slot.size();i++) { wv.addBlock(slot.get(i),column,slotCount); } slotCount ++; } } /** You can split the blockList into different groups. * This method returns a collection of lists. * Each list represents a group * of blocks. * @return a collection of List-objects * @see List * @see Collection */ abstract protected Collection<List<Block>> group(List<Block> blockList); public boolean isSortSlotsBySize() { return m_sortSlotsBySize; } public void setSortSlotsBySize(boolean enable) { m_sortSlotsBySize = enable; } /** takes a block list and returns a sorted slotList */ protected List<List<Block>> getSortedSlots(List<Block> blockList) { Collection<List<Block>> group = group(blockList); List<List<Block>> slots = new ArrayList<List<Block>>(group); if ( isResolveConflictsEnabled()) { resolveConflicts(slots); } if ( !isFixedSlotsEnabled() ) { mergeSlots(slots); } if (isSortSlotsBySize()) Collections.sort(slots, slotComparator); return slots; } protected boolean isCollision(Block b1, Block b2) { final long start1 = b1.getStart().getTime(); long minimumLength = DateTools.MILLISECONDS_PER_MINUTE * 5; final long end1 = Math.max(start1+ minimumLength,b1.getEnd().getTime()); final long start2 = b2.getStart().getTime(); final long end2 = Math.max(start2 + minimumLength,b2.getEnd().getTime()); boolean result = start1 < end2 && start2 <end1 ; return result; } private void resolveConflicts(List<List<Block>> groups) { int pos = 0; while (pos < groups.size()) { List<Block> group = groups.get(pos++ ); List<Block> newSlot = null; int i = 0; while (i< group.size()) { Block element1 = group.get( i++ ); int j = i; while (j< group.size()) { Block element2 = group.get( j ++); if ( isCollision( element1, element2 ) ) { group.remove( element2 ); j --; if (newSlot == null) { newSlot = new ArrayList<Block>(); groups.add(pos, newSlot); } newSlot.add( element2); } } } } } /** the lists must be sorted */ private boolean canMerge(List<Block> slot1,List<Block> slot2) { int size1 = slot1.size(); int size2 = slot2.size(); int i = 0; int j = 0; while (i<size1 && j < size2) { Block b1 = slot1.get(i); Block b2 = slot2.get(j); if (isCollision( b1, b2)) return false; if ( b1.getStart().before( b2.getStart() )) i ++; else j ++; } return true; } /** merge two slots */ private void mergeSlots(List<List<Block>> slots) { // We use a (sub-optimal) greedy algorithm for merging slots int pos = 0; while (pos < slots.size()) { List<Block> slot1 = slots.get(pos ++); for (int i= pos; i<slots.size(); i++) { List<Block> slot2 = slots.get(i); if (canMerge(slot1, slot2)) { slot1.addAll(slot2); Collections.sort(slot1, blockComparator); slots.remove(slot2); pos --; break; } } } } public void setFixedSlotsEnabled( boolean enable) { m_fixedSlots = enable; } public boolean isFixedSlotsEnabled() { return m_fixedSlots; } /** enables or disables conflict resolving. If turned on and 2 blocks ocupy the same slot, * a new slot will be inserted dynamicly * @param enable */ public void setResolveConflictsEnabled( boolean enable) { m_conflictResolving = enable; } public boolean isResolveConflictsEnabled() { return m_conflictResolving; } public Comparator<Block> getBlockComparator() { return blockComparator; } public void setBlockComparator(Comparator<Block> blockComparator) { this.blockComparator = blockComparator; } }
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.components.calendarview.html; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.BlockComparator; import org.rapla.components.calendarview.CalendarView; public abstract class AbstractHTMLView extends AbstractCalendar implements CalendarView { public static String COLOR_NO_RESOURCE = "#BBEEBB"; String m_html; abstract public Collection<Block> getBlocks(); void checkBlock( Block bl ) { Date endDate = getEndDate(); if ( !bl.getStart().before(endDate)) { throw new IllegalStateException("Start-date " +bl.getStart() + " must be before calendar end at " +endDate); } } public String getHtml() { return m_html; } protected class HTMLSmallDaySlot extends ArrayList<Block> { private static final long serialVersionUID = 1L; private String date; private Date startTime; public HTMLSmallDaySlot(String date) { super(2); this.date = date; } public void putBlock(Block block) { add( block ); } public void sort() { Collections.sort( this, BlockComparator.COMPARATOR); } public void paint(StringBuffer out) { out.append("<div valign=\"top\" align=\"right\">"); out.append( date ); out.append("</div>\n"); for ( int i=0;i<size();i++) { Block block = get(i); out.append("<div valign=\"top\" class=\"month_block\""); if ( block instanceof HTMLBlock ) { out.append(" style=\"background-color:" + ((HTMLBlock)block).getBackgroundColor() + ";\""); } out.append(">"); out.append(block.toString()); out.append("</div>\n"); } } public void setStart(Date date) { startTime = date; } public Date getStart() { return startTime; } } }
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.components.calendarview.html; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.util.DateTools; public class HTMLCompactWeekView extends AbstractHTMLView { public final static int ROWS = 6; //without the header row /** shared calendar instance. Only used for temporary stored values. */ HTMLSmallDaySlot[] slots = {}; String[] slotNames = {}; private ArrayList<List<Block>> rows = new ArrayList<List<Block>>(); Map<Block, Integer> columnMap = new HashMap<Block, Integer>(); private double leftColumnSize = 0.1; String weeknumber = ""; public String getWeeknumber() { return weeknumber; } public void setWeeknumber(String weeknumber) { this.weeknumber = weeknumber; } public void setLeftColumnSize(double leftColumnSize) { this.leftColumnSize = leftColumnSize; } public void setSlots( String[] slotNames ) { this.slotNames = slotNames; } public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.length;i++) { list.addAll(slots[i]); } return Collections.unmodifiableCollection( list ); } /** must be called after the slots are filled*/ protected boolean isEmpty( int column) { HTMLSmallDaySlot slot = slots[column]; return slot.isEmpty(); } public void rebuild() { List<String> headerNames; int columns = getColumnCount(); headerNames = getHeaderNames(); columnMap.clear(); rows.clear(); for ( int i=0; i<slotNames.length; i++ ) { addRow(); } // calculate the blocks Iterator<Builder> it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(getStartDate(),getEndDate()); } // build Blocks it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } Calendar calendar = createCalendar(); calendar.setTime(getStartDate()); calendar.set( Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek()); // resource header // add headers StringBuffer result = new StringBuffer(); result.append("<table class=\"month_table\">\n"); result.append("<tr>\n"); result.append("<td class=\"week_number\" width=\"" + Math.round(getLeftColumnSize() * 100) + "%\">"); result.append(weeknumber); result.append("</td>"); String percentage = "" + Math.round(columns); int rowsize = rows.size(); slots = new HTMLSmallDaySlot[rowsize * columns]; for (int row=0;row<rowsize;row++) { for (int column=0;column < columns; column++) { List<Block> blocks = rows.get( row ); int fieldNumber = row * columns + column; slots[fieldNumber] = createField( blocks, column ); } } for (int i=0;i<columns;i++) { if (isExcluded(i)) { continue; } result.append("<td class=\"month_header\" width=\""+percentage + "%\">"); result.append("<nobr>"); result.append(headerNames.get(i)); result.append("</nobr>"); result.append("</td>"); } result.append("\n</tr>"); for (int row=0;row<rowsize;row++) { result.append("<tr>\n"); result.append("<td class=\"month_cell\" valign=\"top\" height=\"40\">\n"); if ( slotNames.length > row ) { result.append( slotNames[ row ] ); } result.append("</td>\n"); for (int column=0;column < columns; column++) { int fieldNumber = row * columns + column; if ( !isExcluded( column ) ) { result.append("<td class=\"month_cell\" valign=\"top\" height=\"40\">\n"); slots[fieldNumber].paint( result ); result.append("</td>\n"); } } result.append("</tr>\n"); } result.append("</table>"); m_html = result.toString(); } protected List<String> getHeaderNames() { List<String> headerNames = new ArrayList<String>(); blockCalendar.setTime(getStartDate()); int columnCount = getColumnCount(); for (int i=0;i<columnCount;i++) { headerNames.add (AbstractCalendar.formatDayOfWeekDateMonth (blockCalendar.getTime() ,locale ,timeZone )); blockCalendar.add(Calendar.DATE, 1); } return headerNames; } public double getLeftColumnSize() { return leftColumnSize ; } protected int getColumnCount() { return getDaysInView(); } private HTMLSmallDaySlot createField(List<Block> blocks, int column) { HTMLSmallDaySlot c = new HTMLSmallDaySlot(""); c.setStart(DateTools.addDays( getStartDate(), column)); if ( blocks != null) { Iterator<Block> it = blocks.iterator(); while (it.hasNext()){ HTMLBlock block = (HTMLBlock)it.next(); if (columnMap.get( block) == column) { c.putBlock( block ); } } } c.sort(); return c; } public void addBlock(Block block, int column,int slot) { checkBlock( block ); while ( rows.size() <= slot ) { addRow(); } List<Block> blocks = rows.get( slot ); blocks.add( block ); columnMap.put(block, column); } private void addRow() { rows.add( rows.size(), new ArrayList<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.components.calendarview.html; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import org.rapla.components.calendarview.AbstractCalendar; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; public class HTMLWeekView extends AbstractHTMLView { private int endMinutes; private int minMinute; private int maxMinute; private int startMinutes; int m_rowsPerHour = 2; HTMLDaySlot[] multSlots ; ArrayList<Block> blocks = new ArrayList<Block>(); //ArrayList<Integer> blockStart = new ArrayList<Integer>(); //ArrayList<Integer> blockSize = new ArrayList<Integer>(); String weeknumber; /** The granularity of the selection rows. * <ul> * <li>1: 1 rows per hour = 1 Hour</li> * <li>2: 2 rows per hour = 1/2 Hour</li> * <li>3: 3 rows per hour = 20 Minutes</li> * <li>4: 4 rows per hour = 15 Minutes</li> * <li>6: 6 rows per hour = 10 Minutes</li> * <li>12: 12 rows per hour = 5 Minutes</li> * </ul> * Default is 2. */ public void setRowsPerHour(int rows) { m_rowsPerHour = rows; } public int getRowsPerHour() { return m_rowsPerHour; } public void setWorktime(int startHour, int endHour) { this.startMinutes = startHour * 60; this.endMinutes = endHour * 60; } public void setWorktimeMinutes(int startMinutes, int endMinutes) { this.startMinutes = startMinutes; this.endMinutes = endMinutes; } public void setToDate(Date weekDate) { calcMinMaxDates( weekDate ); } public Collection<Block> getBlocks() { return blocks; } /** must be called after the slots are filled*/ protected boolean isEmpty( int column) { return multSlots[column].isEmpty(); } protected int getColumnCount() { return getDaysInView(); } public void rebuild() { int columns = getColumnCount(); blocks.clear(); multSlots = new HTMLDaySlot[columns]; String[] headerNames = new String[columns]; for (int i=0;i<columns;i++) { String headerName = createColumnHeader(i); headerNames[i] = headerName; } // calculate the blocks int start = startMinutes; int end = endMinutes; minuteBlock.clear(); Iterator<Builder> it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(getStartDate(),getEndDate()); start = Math.min(b.getMinMinutes(),start); end = Math.max(b.getMaxMinutes(),end); if (start<0) throw new IllegalStateException("builder.getMin() is smaller than 0"); if (end>24*60) throw new IllegalStateException("builder.getMax() is greater than 24"); } minMinute = start ; maxMinute = end ; for (int i=0;i<multSlots.length;i++) { multSlots[i] = new HTMLDaySlot(2); } it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } StringBuffer result = new StringBuffer(); result.append("<table class=\"week_table\">\n"); result.append("<tbody>"); result.append("<tr>\n"); result.append("<th class=\"week_number\">"+weeknumber+"</th>"); for (int i=0;i<multSlots.length;i++) { if ( isExcluded ( i ) ) continue; result.append("<td class=\"week_header\" colspan=\""+ (Math.max(1,multSlots[i].size()) * 2 + 1) + "\">"); result.append("<nobr>"); result.append(headerNames[i]); result.append("</nobr>"); result.append("</td>"); } result.append("\n</tr>"); result.append("<tr></tr>"); boolean useAM_PM = org.rapla.components.calendarview.AbstractCalendar.isAmPmFormat( locale ); int firstEventMarkerId = 7; boolean firstEventMarkerSet = false; for (int minuteOfDay = minMinute;minuteOfDay<maxMinute;minuteOfDay++) { boolean isLine = (minuteOfDay ) % (60 / m_rowsPerHour) == 0; if ( isLine || minuteOfDay == minMinute) { minuteBlock.add( minuteOfDay); } } for (Integer minuteOfDay:minuteBlock) { if ( minuteBlock.last().equals( minuteOfDay)) { break; } //System.out.println("Start row " + row / m_rowsPerHour + ":" + row % m_rowsPerHour +" " + timeString ); result.append("<tr>\n"); boolean fullHour = (minuteOfDay) % 60 == 0; boolean isLine = (minuteOfDay ) % (60 / m_rowsPerHour) == 0; if ( fullHour || minuteOfDay == minMinute) { int rowspan = calcRowspan(minuteOfDay, ((minuteOfDay / 60) + 1) * 60); String timeString = formatTime(minuteOfDay, useAM_PM); result.append("<th class=\"week_times\" rowspan=\""+ rowspan +"\"><nobr>"); result.append(timeString); result.append("</nobr>"); result.append(" &#160;</th>\n"); } for (int day=0;day<columns;day++) { if (isExcluded(day)) continue; if (multSlots[day].size() == 0) { // Rapla 1.4: Make line for full hours darker than others if (fullHour ) { result.append("<td class=\"week_smallseparatorcell_black\">&nbsp;</td>"); result.append("<td class=\"week_emptycell_black\">&nbsp;</td>\n"); } else if (isLine) { result.append("<td class=\"week_smallseparatorcell\">&nbsp;</td>"); result.append("<td class=\"week_emptycell\">&nbsp;</td>\n"); } else { result.append("<td class=\"week_smallseparatornolinecell\">&nbsp;</td>"); result.append("<td class=\"week_emptynolinecell\">&nbsp;</td>\n"); } } else if ( firstEventMarkerSet) { firstEventMarkerId = day; } for (int slotnr = 0; slotnr < multSlots[day].size(); slotnr++) { // Rapla 1.4: Make line for full hours darker than others if (fullHour) { result.append("<td class=\"week_smallseparatorcell_black\">&nbsp;</td>"); } else if (isLine) { result.append("<td class=\"week_smallseparatorcell\">&nbsp;</td>"); } else { result.append("<td class=\"week_smallseparatornolinecell\"></td>"); } Slot slot = multSlots[day].getSlotAt(slotnr); Block block = slot.getBlock(minuteOfDay); if ( block != null) { blockCalendar.setTime( block.getEnd()); int endMinute = Math.min(maxMinute,blockCalendar.get(Calendar.HOUR_OF_DAY) * 60 + blockCalendar.get(Calendar.MINUTE)); int rowspan = calcRowspan(minuteOfDay, endMinute); result.append("<td valign=\"top\" class=\"week_block\""); result.append(" rowspan=\"" + rowspan + "\"" ); if (block instanceof HTMLBlock) result.append(" style=\"background-color:" + ((HTMLBlock) block).getBackgroundColor() + "\""); result.append(">"); printBlock(result, firstEventMarkerId, block); result.append("</td>"); slot.setLastEnd( endMinute); } else { // skip ? if (slot.getLastEnd() > minuteOfDay) { // Do nothing } else { // Rapla 1.4: Make line for full hours darker than others if (fullHour )//|| (!slot.isEmpty(row-1) && (row-minRow) > 0)) { result.append("<td class=\"week_emptycell_black\">&nbsp;</td>\n"); } else if (isLine) { result.append("<td class=\"week_emptycell\">&nbsp;</td>\n"); } else { result.append("<td class=\"week_emptynolinecell\"></td>\n"); } } } } // Rapla 1.4: Make line for full hours darker than others if (fullHour) { result.append("<td class=\"week_separatorcell_black\">&nbsp;</td>"); } else if ( isLine) { result.append("<td class=\"week_separatorcell\">&nbsp;</td>"); } else { result.append("<td class=\"week_separatornolinecell\"></td>\n"); } } result.append("\n</tr>\n"); } result.append("</tbody>"); result.append("</table>\n"); m_html = result.toString(); } private int calcRowspan(int start, int end) { if ( start == end) { return 0; } SortedSet<Integer> tailSet = minuteBlock.tailSet( start); int col = 0; for (Integer minute:tailSet) { if ( minute< end) { col++; } else { break; } } return col; } public String getWeeknumber() { return weeknumber; } public void setWeeknumber(String weeknumber) { this.weeknumber = weeknumber; } protected void printBlock(StringBuffer result, @SuppressWarnings("unused") int firstEventMarkerId, Block block) { String string = block.toString(); result.append(string); } protected String createColumnHeader(int i) { blockCalendar.setTime(getStartDate()); blockCalendar.add(Calendar.DATE, i); String headerName = AbstractCalendar.formatDayOfWeekDateMonth (blockCalendar.getTime() ,locale ,timeZone ); return headerName; } SortedSet<Integer> minuteBlock = new TreeSet<Integer>(); public void addBlock(Block block,int column,int slot) { checkBlock ( block ); HTMLDaySlot multiSlot =multSlots[column]; blockCalendar.setTime( block.getStart()); int startMinute = Math.max(minMinute,( blockCalendar.get(Calendar.HOUR_OF_DAY)* 60 + blockCalendar.get(Calendar.MINUTE) )); blockCalendar.setTime(block.getEnd()); int endMinute = (Math.min(maxMinute, blockCalendar.get(Calendar.HOUR_OF_DAY)* 60 + blockCalendar.get(Calendar.MINUTE) )); blocks.add(block); // startBlock.add( startMinute); // endBlock.add( endMinute); minuteBlock.add( startMinute); minuteBlock.add( endMinute); multiSlot.putBlock( block, slot, startMinute); } private String formatTime(int minuteOfDay,boolean useAM_PM) { blockCalendar.set(Calendar.MINUTE, minuteOfDay%60); int hour = minuteOfDay/60; blockCalendar.set(Calendar.HOUR_OF_DAY, hour); SimpleDateFormat format = new SimpleDateFormat(useAM_PM ? "h:mm" : "H:mm", locale); format.setTimeZone(blockCalendar.getTimeZone()); if (useAM_PM && hour == 12 && minuteOfDay%60 == 0) { return format.format(blockCalendar.getTime()) + " PM"; } else { return format.format(blockCalendar.getTime()); } } protected class HTMLDaySlot extends ArrayList<Slot> { private static final long serialVersionUID = 1L; private boolean empty = true; public HTMLDaySlot(int size) { super(size); } public void putBlock(Block block,int slotnr, int startMinute) { while (slotnr >= size()) { addSlot(); } getSlotAt(slotnr).putBlock( block, startMinute); empty = false; } public int addSlot() { Slot slot = new Slot(); add(slot); return size(); } public Slot getSlotAt(int index) { return get(index); } public boolean isEmpty() { return empty; } } protected class Slot { // int[] EMPTY = new int[]{-2}; // int[] SKIP = new int[]{-1}; int lastEnd = 0; HashMap<Integer, Block> map = new HashMap<Integer, Block>(); public Slot() { } public void putBlock( Block block, int startMinute) { map.put( startMinute, block); } Block getBlock(Integer startMinute) { return map.get( startMinute); } public int getLastEnd() { return lastEnd; } public void setLastEnd(int lastEnd) { this.lastEnd = lastEnd; } } }
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.components.calendarview.html; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.Builder; import org.rapla.components.util.DateTools; public class HTMLMonthView extends AbstractHTMLView { public final static int ROWS = 6; //without the header row public final static int COLUMNS = 7; HTMLSmallDaySlot[] slots; public Collection<Block> getBlocks() { ArrayList<Block> list = new ArrayList<Block>(); for (int i=0;i<slots.length;i++) { list.addAll(slots[i]); } return Collections.unmodifiableCollection( list ); } protected boolean isEmpty(int column) { for ( int i=column;i < slots.length;i+=7 ) { if (!slots[i].isEmpty() ) { return false; } } return true; } public void rebuild() { // we need to clone the calendar, because we modify the calendar object int the getExclude() method Calendar counter = (Calendar) blockCalendar.clone(); // calculate the blocks Iterator<Builder> it= builders.iterator(); final Date startDate = getStartDate(); while (it.hasNext()) { Builder b= it.next(); b.prepareBuild(startDate,getEndDate()); } slots = new HTMLSmallDaySlot[ daysInMonth ]; for (int i=0;i<slots.length;i++) { slots[i] = new HTMLSmallDaySlot(String.valueOf( i + 1)); } it= builders.iterator(); while (it.hasNext()) { Builder b= it.next(); if (b.isEnabled()) { b.build(this); } } int lastRow = 0; HTMLSmallDaySlot[][] table = new HTMLSmallDaySlot[ROWS][COLUMNS]; counter.setTime(startDate); int firstDayOfWeek = getFirstWeekday(); if ( counter.get(Calendar.DAY_OF_WEEK) != firstDayOfWeek) { counter.set(Calendar.DAY_OF_WEEK, firstDayOfWeek); if ( counter.getTime().after( startDate)) { counter.add(Calendar.DATE, -7); } } Date time = counter.getTime(); int offset = (int) DateTools.countDays(counter.getTime(),startDate); // add headers counter.setTime(startDate); for (int i=0; i<daysInMonth; i++) { int column = (offset + i) % 7; int row = (counter.get(Calendar.DATE) + 6 - column ) / 7; table[row][column] = slots[i]; lastRow = row; slots[i].sort(); counter.add(Calendar.DATE,1); } StringBuffer result = new StringBuffer(); // Rapla 1.4: Show month and year in monthview SimpleDateFormat monthYearFormat = new SimpleDateFormat("MMMMM yyyy", locale); result.append("<h2 class=\"title\">" + monthYearFormat.format(startDate) + "</h2>\n"); result.append("<table class=\"month_table\">\n"); result.append("<tr>\n"); counter.setTime( time ); for (int i=0;i<COLUMNS;i++) { if (isExcluded(i)) { counter.add(Calendar.DATE, 1); continue; } int weekday = counter.get(Calendar.DAY_OF_WEEK); if ( counter.getTime().equals( startDate)) { offset = i; } result.append("<td class=\"month_header\" width=\"14%\">"); result.append("<nobr>"); String name = getWeekdayName(weekday); result.append(name); result.append("</nobr>"); result.append("</td>"); counter.add(Calendar.DATE, 1); } result.append("\n</tr>"); for (int row=0; row<=lastRow; row++) { boolean excludeRow = true; // calculate if we can exclude the row for (int column = 0; column<COLUMNS; column ++) { if ( table[row][column] != null && !isExcluded( column )) { excludeRow = false; } } if ( excludeRow ) continue; result.append("<tr>\n"); for (int column = 0; column<COLUMNS; column ++) { if ( isExcluded( column )) { continue; } HTMLSmallDaySlot slot = table[row][column]; if ( slot == null ) { result.append("<td class=\"month_cell\" height=\"40\"></td>\n"); } else { result.append("<td class=\"month_cell\" valign=\"top\" height=\"40\">\n"); slot.paint( result ); result.append("</td>\n"); } } result.append("</tr>\n"); } result.append("</table>"); m_html = result.toString(); } public void addBlock(Block block,int col,int slot) { checkBlock( block ); blockCalendar.setTime(block.getStart()); int day = blockCalendar.get(Calendar.DATE); slots[day-1].putBlock( block ); } }
Java
package org.rapla.components.calendarview.html; import org.rapla.components.calendarview.Block; public interface HTMLBlock extends Block { String getBackgroundColor(); String toString(); }
Java
package org.rapla.components.calendarview; import java.text.DateFormat; import java.text.FieldPosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.Locale; import java.util.TimeZone; import org.rapla.components.util.DateTools; public abstract class AbstractCalendar { private int daysInView = 7; private int firstWeekday = Calendar.getInstance().getFirstDayOfWeek(); /** shared calendar instance. Only used for temporary stored values. */ protected Calendar blockCalendar; protected Collection<Integer> excludeDays = Collections.emptySet(); private Date startDate; private Date endDate; protected Locale locale; protected TimeZone timeZone; protected int daysInMonth; protected Collection<Builder> builders = new ArrayList<Builder>(); public int getDaysInView() { return daysInView; } public void setDaysInView(int daysInView) { this.daysInView = daysInView; } public int getFirstWeekday() { return firstWeekday; } public void setFirstWeekday(int firstDayOfWeek) { this.firstWeekday = firstDayOfWeek; } public String getWeekdayName(int weekday) { SimpleDateFormat format = new SimpleDateFormat("EEEEEE",locale); Calendar calendar = createCalendar(); calendar.set(Calendar.DAY_OF_WEEK, weekday); String weekdayName = format.format(calendar.getTime()); return weekdayName; } protected boolean isExcluded(int column) { if ( daysInView == 1) { return false; } blockCalendar.set(Calendar.DAY_OF_WEEK, getFirstWeekday()); blockCalendar.add(Calendar.DATE, column); int weekday = blockCalendar.get(Calendar.DAY_OF_WEEK); if ( !excludeDays.contains(new Integer( weekday )) ) { return false; } boolean empty = isEmpty(column); return empty; } abstract protected boolean isEmpty(int column); public void setTimeZone(TimeZone timeZone) { this.timeZone = timeZone; blockCalendar = createCalendar(); } protected Calendar createCalendar() { return Calendar.getInstance(getTimeZone(),locale); } public TimeZone getTimeZone() { return timeZone; } public void setLocale(Locale locale) { this.locale = locale; // Constructor called? if (timeZone != null) { setTimeZone( timeZone ); blockCalendar = createCalendar(); } } public void setToDate(Date date) { calcMinMaxDates( date ); } public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } protected void setStartDate(Date date) { this.startDate = date; } protected void setEndDate(Date date) { this.endDate = date; } public void setExcludeDays(Collection<Integer> excludeDays) { this.excludeDays = excludeDays; if (getStartDate() != null) calcMinMaxDates( getStartDate() ); } public void rebuild(Builder builder) { try { addBuilder( builder); rebuild(); } finally { removeBuilder( builder ); } } public void calcMinMaxDates(Date date) { Calendar blockCalendar = createCalendar(); blockCalendar.setTime( date ); blockCalendar.set(Calendar.HOUR_OF_DAY,0); blockCalendar.set(Calendar.MINUTE,0); blockCalendar.set(Calendar.SECOND,0); blockCalendar.set(Calendar.MILLISECOND,0); this.daysInMonth = blockCalendar.getActualMaximum( Calendar.DAY_OF_MONTH ) ; if ( daysInView > 14) { blockCalendar.set(Calendar.DAY_OF_MONTH, 1); this.startDate = blockCalendar.getTime(); blockCalendar.set(Calendar.MILLISECOND,1); blockCalendar.set(Calendar.MILLISECOND,0); blockCalendar.add(Calendar.DATE, this.daysInMonth); this.endDate = blockCalendar.getTime(); firstWeekday = blockCalendar.getFirstDayOfWeek(); } else { if ( daysInView >= 3) { int firstWeekday2 = getFirstWeekday(); blockCalendar.set(Calendar.DAY_OF_WEEK, firstWeekday2); if ( blockCalendar.getTime().after( date)) { blockCalendar.add(Calendar.DATE, -7); } } else { firstWeekday = blockCalendar.get( Calendar.DAY_OF_WEEK); } startDate = blockCalendar.getTime(); endDate =DateTools.addDays(startDate, daysInView); } } public abstract void rebuild(); public Iterator<Builder> getBuilders() { return builders.iterator(); } public void addBuilder(Builder b) { builders.add(b); } public void removeBuilder(Builder b) { builders.remove(b); } /** formats the date and month in the selected locale and timeZone*/ public static String formatDateMonth(Date date, Locale locale, TimeZone timeZone) { FieldPosition fieldPosition = new FieldPosition( DateFormat.YEAR_FIELD ); StringBuffer buf = new StringBuffer(); DateFormat format = DateFormat.getDateInstance( DateFormat.SHORT, locale); format.setTimeZone( timeZone ); buf = format.format(date, buf, fieldPosition ); if ( fieldPosition.getEndIndex()<buf.length() ) { buf.delete( fieldPosition.getBeginIndex(), fieldPosition.getEndIndex()+1 ); } else if ( (fieldPosition.getBeginIndex()>=0) ) { buf.delete( fieldPosition.getBeginIndex(), fieldPosition.getEndIndex() ); } char lastChar = buf.charAt(buf.length()-1); if (lastChar == '/' || lastChar == '-' ) { String result = buf.substring(0,buf.length()-1); return result; } else { String result = buf.toString(); return result; } } /** formats the day of week, date and month in the selected locale and timeZone*/ public static String formatDayOfWeekDateMonth(Date date, Locale locale, TimeZone timeZone) { SimpleDateFormat format = new SimpleDateFormat("EEE", locale); format.setTimeZone(timeZone); String datePart = format.format(date); String dateOfMonthPart = AbstractCalendar.formatDateMonth( date,locale,timeZone ); return datePart + " " + dateOfMonthPart ; } public static boolean isAmPmFormat(Locale locale) { // Determines if am-pm-format should be used. DateFormat format= DateFormat.getTimeInstance(DateFormat.SHORT, locale); FieldPosition amPmPos = new FieldPosition(DateFormat.AM_PM_FIELD); format.format(new Date(), new StringBuffer(),amPmPos); return (amPmPos.getEndIndex()>0); } }
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.components.util; import java.util.Comparator; /** * * Reverts the Original Comparator * -1 -> 1 * 1 -> -1 * 0 -> 0 */ public class InverseComparator<T> implements Comparator<T> { Comparator<T> original; public InverseComparator( Comparator<T> original) { this.original = original; } public int compare( T arg0, T arg1 ) { return -1 * original.compare( arg0, arg1); } }
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.components.util; /** Creates a new thread that successively executes the queued command objects * @see Command */ public interface CommandScheduler { public Cancelable schedule(Command object, long delay); public Cancelable schedule(Command object, long delay, long period); }
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.components.util; import java.lang.reflect.Method; import java.net.URL; /** returns the codebase in an webstart application */ abstract public class JNLPUtil { final static String basicService = "javax.jnlp.BasicService"; final public static URL getCodeBase() throws Exception { try { Class<?> serviceManagerC = Class.forName("javax.jnlp.ServiceManager"); Class<?> basicServiceC = Class.forName( basicService ); //Class unavailableServiceException = Class.forName("javax.jnlp.UnavailableServiceException"); Method lookup = serviceManagerC.getMethod("lookup", new Class[] {String.class}); Method getCodeBase = basicServiceC.getMethod("getCodeBase", new Class[] {}); Object service = lookup.invoke( null, new Object[] { basicService }); return (URL) getCodeBase.invoke( service, new Object[] {}); } catch (ClassNotFoundException ex ) { throw new Exception( "Webstart not available :" + ex.getMessage()); } } }
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.components.util; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; /** miscellaneous util methods.*/ public abstract class Tools { /** same as new Object[0].*/ public static final Object[] EMPTY_ARRAY = new Object[0]; public static final Class<?>[] EMPTY_CLASS_ARRAY = new Class[0]; public static final String[] EMPTY_STRING_ARRAY = new String[0]; /** test if 2 char arrays match. */ public static boolean match(char[] p1, char[] p2) { boolean bMatch = true; if (p1.length == p2.length) { for (int i = 0; i<p1.length; i++) { if (p1[i] != p2[i]) { bMatch = false; break; } } } else { bMatch = false; } return bMatch; } private static boolean validStart(char c) { return (c == '_' || c =='-' || Character.isLetter(c)) ? true : false; } private static boolean validLetter(char c) { return (validStart(c) || Character.isDigit(c)); } /** Rudimentary tests if the string is a valid xml-tag.*/ public static boolean isKey(String key) { // A tag name must start with a letter (a-z, A-Z) or an underscore (_) and can contain letters, digits 0-9, the period (.), the underscore (_) or the hyphen (-). char[] c = key.toCharArray(); if (c.length == 0) return false; if (!validStart(c[0])) return false; for (int i=0;i<c.length;i++) { if (!validLetter(c[i])) return false; } return true; } /** same as substring(0,width-1) except that it will not not throw an <code>ArrayIndexOutOfBoundsException</code> if string.length()&lt;width. */ public static String left(String string,int width) { return string.substring(0, Math.min(string.length(), width -1)); } /** Convert a byte array into a printable format containing aString of hexadecimal digit characters (two per byte). * This method is taken form the apache jakarata * tomcat project. */ public static String convert(byte bytes[]) { StringBuffer sb = new StringBuffer(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { sb.append(convertDigit(bytes[i] >> 4)); sb.append(convertDigit(bytes[i] & 0x0f)); } return (sb.toString()); } /** Convert the specified value (0-15) to the corresponding hexadecimal digit. * This method is taken form the apache jakarata tomcat project. */ public static char convertDigit(int value) { value &= 0x0f; if (value >= 10) return ((char) (value - 10 + 'a')); else return ((char) (value + '0')); } public static boolean equalsOrBothNull(Object o1, Object o2) { if (o1 == null) { if (o2 != null) { return false; } } else if ( o2 == null) { return false; } else if (!o1.equals( o2 ) ) { return false; } return true; } /** 1.3 compatibility method */ public static String[] split(String stringToSplit, char delimiter) { List<String> keys = new ArrayList<String>(); int lastIndex = 0; while( true ) { int index = stringToSplit.indexOf( delimiter,lastIndex); if ( index < 0) { String token = stringToSplit.substring( lastIndex ); if ( token.length() >= 0) { keys.add( token ); } break; } String token = stringToSplit.substring( lastIndex , index ); keys.add( token ); lastIndex = index + 1; } return keys.toArray( new String[] {}); } // /** 1.3 compatibility method */ // public static String replaceAll( String string, String stringToReplace, String newString ) { // if ( stringToReplace.equals( newString)) // return string; // int length = stringToReplace.length(); // int oldPos = 0; // while ( true ) { // int pos = string.indexOf( stringToReplace,oldPos); // if ( pos < 0 ) // return string; // // string = string.substring(0, pos) + newString + string.substring( pos + length); // oldPos = pos + 1; // if ( oldPos >= string.length() ) // return string; // // } // } /** reads a table from a csv file. You can specify a minimum number of columns */ public static String[][] csvRead(Reader reader, int expectedColumns) throws IOException { return csvRead(reader, ';', expectedColumns); } /** reads a table from a csv file. You can specify the seperator and a minimum number of columns */ public static String[][] csvRead(Reader reader, char seperator,int expectedColumns) throws IOException { //System.out.println( "Using Encoding " + reader.getEncoding() ); StringBuffer buf = new StringBuffer(); while (true) { int c = reader.read(); if ( c == -1 ) break; buf.append( (char) c ); } String[] lines = buf.toString().split(System.getProperty("line.separator")); //BJO //String[] lines = split( buf.toString(),'\n'); String[][] lineEntries = new String[ lines.length ][]; for ( int i=0;i<lines.length; i++ ) { String stringToSplit = lines[i]; //String firstIterator =stringToSplit.replaceAll("\"\"", "DOUBLEQUOTEQUOTE"); lineEntries[i] = split( stringToSplit,seperator); if ( lineEntries[i].length < expectedColumns ) { throw new IOException("Can't parse line " + i + ":" + stringToSplit + "Expected " + expectedColumns + " Entries. Found " + lineEntries[i].length); // BJO } } return lineEntries; } }
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.components.util; public class AssertionError extends RuntimeException { private static final long serialVersionUID = 1L; String text = ""; public AssertionError() { } public AssertionError(String text) { this.text = text; } public String toString() { return text; } }
Java
package org.rapla.components.util; import java.io.Serializable; import java.util.Date; public final class TimeInterval implements Serializable { private static final long serialVersionUID = -8387919392038291664L; Date start; Date end; TimeInterval() { } public TimeInterval(Date start, Date end) { this.start = start; this.end = end; } public Date getStart() { return start; } public void setStart(Date start) { this.start = start; } public Date getEnd() { return end; } public void setEnd(Date end) { this.end = end; } public String toString() { return start + " - " + end; } public boolean equals(Object obj) { if (obj == null || !(obj instanceof TimeInterval) ) { return false; } TimeInterval other = (TimeInterval) obj; Date start2 = other.getStart(); Date end2 = other.getEnd(); if ( start == null ) { if (start != start2) { return false; } } else { if ( start2 == null || !start.equals(start2)) { return false; } } if ( end == null ) { if (end != end2) { return false; } } else { if ( end2 == null || !end.equals(end2)) { return false; } } return true; } @Override public int hashCode() { int hashCode; if ( start!=null ) { hashCode = start.hashCode(); if ( end!=null ) { hashCode *= end.hashCode(); } } else if ( end!=null ) { hashCode = end.hashCode(); } else { hashCode =super.hashCode(); } return hashCode; } public boolean overlaps(TimeInterval other) { Date start2 = other.getStart(); Date end2 = other.getEnd(); if ( start != null) { if ( end2 != null) { if ( !start.before(end2)) { return false; } } } if ( end != null) { if ( start2 != null) { if ( !start2.before(end)) { return false; } } } return true; } public TimeInterval union(TimeInterval interval) { Date start = getStart(); Date end = getEnd(); if ( interval == null ) { interval = new TimeInterval(start, end); } if ( start == null || (interval.getStart() != null && interval.getStart().after( start))) { interval = new TimeInterval( start, interval.getEnd()); } if ( end == null || ( interval.getEnd() != null && end.after( interval.getEnd()))) { interval = new TimeInterval( interval.getStart(), end); } return interval; } }
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.components.util; public interface Command { public void execute() throws Exception; }
Java
package org.rapla.components.util; public class ParseDateException extends Exception { private static final long serialVersionUID = 1L; public ParseDateException(String message) { super(message); } }
Java
package org.rapla.components.util; import java.util.Date; import org.rapla.components.util.DateTools.TimeWithoutTimezone; import org.rapla.components.util.iterator.IntIterator; /** Provides methods for parsing and formating dates and times in the following format: <br> <code>2002-25-05</code> for dates and <code>13:00:00</code> for times. This is according to the xschema specification for dates and time and ISO8601 */ public class SerializableDateTimeFormat { public static SerializableDateTimeFormat INSTANCE = new SerializableDateTimeFormat(); // we ommit T private final static char DATE_TIME_SEPERATOR = 'T'; //private final static char DATE_TIME_SEPERATOR = ' '; private Date parseDate( String date, String time, boolean fillDate ) throws ParseDateException { if( date == null || date.length()==0 ) throwParseDateException("empty" ); long millis = parseDate_(date, fillDate); if ( time != null ) { long timeMillis = parseTime_(time); millis+= timeMillis; } // logger.log( "parsed to " + calendar.getTime() ); return new Date( millis); } private long parseTime_(String time) throws ParseDateException { int length = time.length(); if ( length <1) { throwParseTimeException( time ); } if ( time.charAt( length-1) == 'Z') { time = time.substring(0,length-1); } IntIterator it = new IntIterator( time, new char[]{':','.',','} ); if ( !it.hasNext() ) throwParseTimeException( time ); int hour = it.next(); if ( !it.hasNext() ) throwParseTimeException( time ); int minute = it.next(); int second; if ( it.hasNext() ) { second = it.next(); } else { second = 0; } int millisecond; if ( it.hasNext() ) { millisecond = it.next(); } else { millisecond = 0; } long result = DateTools.toTime( hour, minute,second, millisecond); return result; } private long parseDate_(String date, boolean fillDate) throws ParseDateException { int indexOfSeperator = indexOfSeperator(date); if ( indexOfSeperator > 0) { date = date.substring(0, indexOfSeperator); } IntIterator it = new IntIterator(date,'-'); if ( !it.hasNext() ) throwParseDateException( date ); int year = it.next(); if ( !it.hasNext() ) throwParseDateException( date); int month = it.next(); if ( !it.hasNext() ) throwParseDateException( date); int day = it.next(); if (fillDate ) { day+=1; } return DateTools.toDate( year, month, day); } private int indexOfSeperator(String date) { // First try the new ISO8601 int indexOfSeperator = date.indexOf( 'T' ); if ( indexOfSeperator<0) { //then search for a space indexOfSeperator = date.indexOf( ' ' ); } return indexOfSeperator; } private void throwParseDateException( String date) throws ParseDateException { throw new ParseDateException( "No valid date format: " + date); } private void throwParseTimeException( String time) throws ParseDateException { throw new ParseDateException( "No valid time format: " + time); } /** The date-string must be in the following format <strong>2001-10-21</strong>. The format of the time-string is <strong>18:00:00</strong>. @return The parsed date @throws ParseDateException when the date cannot be parsed. */ public Date parseDateTime( String date, String time) throws ParseDateException { return parseDate( date, time, false); } /** The format of the time-string is <strong>18:00:00</strong>. @return The parsed time @throws ParseDateException when the date cannot be parsed. */ public Date parseTime( String time) throws ParseDateException { if( time == null || time.length()==0 ) throwParseDateException("empty"); long millis = parseTime_( time); Date result = new Date( millis); return result; } /** The date-string must be in the following format <strong>2001-10-21</strong>. * @param fillDate if this flag is set the time will be 24:00 instead of 0:00 <strong> When this flag is set the time parameter should be null</strong> @return The parsed date @throws ParseDateException when the date cannot be parsed. */ public Date parseDate( String date, boolean fillDate ) throws ParseDateException { return parseDate( date, null, fillDate); } public Date parseTimestamp(String timestamp) throws ParseDateException { boolean fillDate = false; timestamp = timestamp.trim(); long millisDate = parseDate_(timestamp, fillDate); int indexOfSeperator = indexOfSeperator(timestamp); if ( timestamp.indexOf(':') >= indexOfSeperator && indexOfSeperator > 0) { String timeString = timestamp.substring( indexOfSeperator + 1); if ( timeString.length() > 0) { long time = parseTime_( timeString); millisDate+= time; } } Date result = new Date( millisDate); return result; } /** returns the time object in the following format: <strong>13:00:00</strong>. <br> */ public String formatTime( Date date ) { return formatTime(date, false); } private String formatTime(Date date, boolean includeMilliseconds) { StringBuilder buf = new StringBuilder(); if ( date == null) { date = new Date(); } TimeWithoutTimezone time = DateTools.toTime( date.getTime()); append( buf, time.hour, 2 ); buf.append( ':' ); append( buf, time.minute, 2 ); buf.append( ':' ); append( buf, time.second, 2 ); if ( includeMilliseconds) { buf.append('.'); append( buf, time.milliseconds, 4 ); } //buf.append( 'Z'); return buf.toString(); } /** returns the date object in the following format: <strong>2001-10-21</strong>. <br> @param adaptDay if the flag is set 2001-10-21 will be stored as 2001-10-20. This is usefull for end-dates: 2001-10-21 00:00 is then interpreted as 2001-10-20 24:00. */ public String formatDate( Date date, boolean adaptDay ) { StringBuilder buf = new StringBuilder(); DateTools.DateWithoutTimezone splitDate; splitDate = DateTools.toDate( date.getTime() - (adaptDay ? DateTools.MILLISECONDS_PER_DAY : 0)); append( buf, splitDate.year, 4 ); buf.append( '-' ); append( buf, splitDate.month, 2 ); buf.append( '-' ); append( buf, splitDate.day, 2 ); return buf.toString(); } public String formatTimestamp( Date date ) { StringBuilder builder = new StringBuilder(); builder.append(formatDate( date, false)); builder.append( DATE_TIME_SEPERATOR); builder.append( formatTime( date , true)); builder.append( 'Z'); String timestamp = builder.toString();; return timestamp; } /** same as formatDate(date, false). @see #formatDate(Date,boolean) */ public String formatDate( Date date ) { return formatDate( date, false ); } private void append( StringBuilder buf, int number, int minLength ) { int limit = 1; for ( int i=0;i<minLength-1;i++ ) { limit *= 10; if ( number<limit ) buf.append( '0' ); } buf.append( number ); } }
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.components.util.iterator; import java.util.Iterator; import java.util.NoSuchElementException; /**Successivly iterates over the elements specified in the nested Iterators. Example of an recursive traversal of an Entity Tree: <pre> class RecursiveEntityIterator extends NestedIterator { public RecursiveEntityIterator(Iterator it) { super(it); } public Iterator getNestedIterator(Object obj) { return new RecursiveEntityIterator(((Entity)obj).getSubEntities()); } } </pre> */ public abstract class NestedIterator<T,S> implements Iterator<T>, Iterable<T> { protected Iterator<S> outerIt; protected Iterator<T> innerIt; T nextElement; boolean isInitialized; public NestedIterator(Iterable<S> outerIt) { this.outerIt = outerIt.iterator(); } private T nextElement() { while (outerIt.hasNext() || (innerIt != null && innerIt.hasNext())) { if (innerIt != null && innerIt.hasNext()) return innerIt.next(); innerIt = getNestedIterator(outerIt.next()).iterator(); } return null; } public abstract Iterable<T> getNestedIterator(S obj); public boolean hasNext() { if (!isInitialized) { nextElement = nextElement(); isInitialized = true; } return nextElement != null; } public void remove() { throw new UnsupportedOperationException(); } public T next() { if (!hasNext()) throw new NoSuchElementException(); T result = nextElement; nextElement = nextElement(); return result; } public Iterator<T> iterator() { return this; } }
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.components.util.iterator; import java.util.Iterator; import java.util.NoSuchElementException; /** Filters the objects of an Iterator by overiding the isInIterator method*/ public abstract class FilterIterator<T> implements Iterator<T>, Iterable<T> { Iterator<? extends Object> it; Object obj; public FilterIterator(Iterable<? extends Object> it) { this.it = it.iterator(); obj = getNextObject(); } public boolean hasNext() { return obj != null; } protected abstract boolean isInIterator(Object obj); public void remove() { throw new UnsupportedOperationException(); } private Object getNextObject() { Object o; do { if ( !it.hasNext() ) { return null; } o = it.next(); } while (!isInIterator( o)); return o; } @SuppressWarnings("unchecked") public T next() { if ( obj == null) throw new NoSuchElementException(); Object result = obj; obj = getNextObject(); return (T)result; } public Iterator<T> iterator() { return this; } }
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.components.util.iterator; import java.util.Iterator; import java.util.NoSuchElementException; /** concatenates two Iterators */ public class IteratorChain<T> implements Iterator<T>, Iterable<T> { protected Iterator<T> firstIt; protected Iterator<T> secondIt; protected Iterator<T> thirdIt; public IteratorChain(Iterable<T> firstIt, Iterable<T> secondIt) { this( firstIt.iterator(), secondIt.iterator()); } public IteratorChain(Iterable<T> firstIt, Iterable<T> secondIt, Iterable<T> thirdIt) { this( firstIt.iterator(), secondIt.iterator(), thirdIt.iterator()); } public IteratorChain(Iterator<T> firstIt, Iterator<T> secondIt) { this.firstIt = firstIt; this.secondIt = secondIt; } public IteratorChain(Iterator<T> firstIt, Iterator<T> secondIt, Iterator<T> thirdIt) { this.firstIt = firstIt; this.secondIt = secondIt; this.thirdIt = thirdIt; } public boolean hasNext() { return (firstIt!=null && firstIt.hasNext()) || (secondIt != null && secondIt.hasNext()) || (thirdIt != null && thirdIt.hasNext()); } public void remove() { throw new UnsupportedOperationException(); } public T next() { if (firstIt!=null && !firstIt.hasNext()) { firstIt = null; } else if (secondIt!=null && !secondIt.hasNext()) { secondIt = null; } // else if (thirdIt!=null && !thirdIt.hasNext()) // { // thirdIt = null; // } if ( firstIt != null ) return firstIt.next(); else if ( secondIt != null) return secondIt.next(); else if (thirdIt != null) return thirdIt.next(); else throw new NoSuchElementException(); } public Iterator<T> iterator() { return this; } }
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.components.util.iterator; import java.util.NoSuchElementException; /** This class can iterate over a string containing a list of integers. Its tuned for performance, so it will return int instead of Integer */ public class IntIterator { int parsePosition = 0; String text; char[] delimiter; int len; int next; boolean hasNext=false; char endingDelimiter; public IntIterator(String text,char delimiter) { this(text,new char[] {delimiter}); } public IntIterator(String text,char[] delimiter) { this.text = text; len = text.length(); this.delimiter = delimiter; parsePosition = 0; parseNext(); } public boolean hasNext() { return hasNext; } public int next() { if (!hasNext()) throw new NoSuchElementException(); int result = next; parseNext(); return result; } private void parseNext() { boolean isNegative = false; int relativePos = 0; next = 0; if (parsePosition == len) { hasNext = false; return; } while (parsePosition< len) { char c = text.charAt(parsePosition ); if (relativePos == 0 && c=='-') { isNegative = true; parsePosition++; continue; } boolean delimiterFound = false; for ( char d:delimiter) { if (c == d ) { parsePosition++; delimiterFound = true; break; } } if (delimiterFound || c == endingDelimiter ) { break; } int digit = c-'0'; if (digit<0 || digit>9) { hasNext = false; return; } next *= 10; next += digit; parsePosition++; relativePos++; } if (isNegative) next *= -1; hasNext = parsePosition > 0; } public int getPos() { return parsePosition; } }
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.components.util; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** Tools for manipulating dates. * At the moment of writing rapla internaly stores all appointments * in the GMT timezone. */ public abstract class DateTools { public static final int DAYS_PER_WEEK= 7; public static final long MILLISECONDS_PER_MINUTE = 1000 * 60; public static final long MILLISECONDS_PER_HOUR = MILLISECONDS_PER_MINUTE * 60; public static final long MILLISECONDS_PER_DAY = 24 * MILLISECONDS_PER_HOUR; public static final long MILLISECONDS_PER_WEEK = 7 * MILLISECONDS_PER_DAY; public static final int SUNDAY = 1, MONDAY = 2, TUESDAY = 3, WEDNESDAY = 4, THURSDAY = 5, FRIDAY = 6, SATURDAY = 7; public static int getHourOfDay(long date) { return (int) ((date % MILLISECONDS_PER_DAY)/ MILLISECONDS_PER_HOUR); } public static int getMinuteOfHour(long date) { return (int) ((date % MILLISECONDS_PER_HOUR)/ MILLISECONDS_PER_MINUTE); } public static int getMinuteOfDay(long date) { return (int) ((date % MILLISECONDS_PER_DAY)/ MILLISECONDS_PER_MINUTE); } public static String formatDate(Date date) { SerializableDateTimeFormat format = new SerializableDateTimeFormat(); String string = format.formatDate( date); return string; } public static String formatDate(Date date, @SuppressWarnings("unused") Locale locale) { // FIXME has to be replaced with locale implementation // DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT,locale); // format.setTimeZone(DateTools.getTimeZone()); // String string = format.format( date); // return string; return formatDate(date); } public static String formatTime(Date date) { SerializableDateTimeFormat format = new SerializableDateTimeFormat(); String string = format.formatTime( date); return string; } public static String formatDateTime(Date date) { SerializableDateTimeFormat format = new SerializableDateTimeFormat(); String dateString = format.formatDate( date); String timeString = format.formatTime( date); String string = dateString + " " + timeString; return string; } public static int getDaysInMonth(int year, int month) { int _month = month+1; if ( _month == 2) { if ( isLeapYear(year)) { return 29; } return 28; } else if ( _month == 4 || _month == 6 || _month == 9 || _month == 11 ) { return 30; } else { return 31; } } public static boolean isLeapYear(int year) { return year % 4 == 0 && ((year % 100) != 0 || (year % 400) == 0); } /** sets time of day to 0:00. @see #cutDate(Date) */ public static long cutDate(long date) { long dateModMillis = date % MILLISECONDS_PER_DAY; if ( dateModMillis == 0) { return date; } if ( date >= 0) { return (date - dateModMillis); } else { return (date - (MILLISECONDS_PER_DAY + dateModMillis)); } } public static boolean isMidnight(long date) { return cutDate( date ) == date ; } public static boolean isMidnight(Date date) { return isMidnight( date.getTime()); } /** sets time of day to 0:00. */ public static Date cutDate(Date date) { long time = date.getTime(); if ( time %MILLISECONDS_PER_DAY == 0) { return date; } return new Date(cutDate(time)); } private static TimeZone timeZone =TimeZone.getTimeZone("GMT"); /** same as TimeZone.getTimeZone("GMT"). */ public static TimeZone getTimeZone() { return timeZone; } /** sets time of day to 0:00 and increases day. @see #fillDate(Date) */ public static long fillDate(long date) { // cut date long cuttedDate = (date - (date % MILLISECONDS_PER_DAY)); return cuttedDate + MILLISECONDS_PER_DAY; } public static Date fillDate(Date date) { return new Date(fillDate(date.getTime())); } /** Monday 24:00 = tuesday 0:00. But the first means end of monday and the second start of tuesday. The default DateFormat always displays tuesday. If you want to edit the first interpretation in calendar components. call addDay() to add 1 day to the given date before displaying and subDay() for mapping a day back after editing. @see #subDay @see #addDays */ public static Date addDay(Date date) { return addDays( date, 1); } public static Date addYear(Date date) { return addYears(date, 1); } public static Date addWeeks(Date date, int weeks) { Date result = new Date(date.getTime() + MILLISECONDS_PER_WEEK * weeks); return result; } public static Date addYears(Date date, int yearModifier) { int monthModifier = 0; return modifyDate(date, yearModifier, monthModifier); } public static Date addMonth(Date startDate) { return addMonths(startDate, 1); } public static Date addMonths(Date startDate, int monthModifier) { int yearModifier = 0; return modifyDate(startDate, yearModifier, monthModifier); } private static Date modifyDate(Date startDate, int yearModifier, int monthModifier) { long original = startDate.getTime(); long millis = original - DateTools.cutDate( original ); DateWithoutTimezone date = toDate( original); int year = date.year + yearModifier; int month = date.month + monthModifier; if ( month < 1 ) { year += month/ 12 -1 ; month = ((month +11) % 12) + 1; } if ( month >12 ) { year += month/ 12; month = ((month -1) % 12) + 1; } int day = date.day ; long newDate = toDate(year, month, day); Date result = new Date( newDate + millis); return result; } /** see #addDay*/ public static Date addDays(Date date,long days) { return new Date(date.getTime() + MILLISECONDS_PER_DAY * days); } /** @see #addDay @see #subDays */ public static Date subDay(Date date) { return new Date(date.getTime() - MILLISECONDS_PER_DAY); } /** @see #addDay */ public static Date subDays(Date date,int days) { return new Date(date.getTime() - MILLISECONDS_PER_DAY * days); } /** returns if the two dates are one the same date. * Dates must be in GMT */ static public boolean isSameDay( Date d1, Date d2) { return cutDate( d1 ).equals( cutDate ( d2 )); } /** returns if the two dates are one the same date. * Dates must be in GMT */ static public boolean isSameDay( long d1, long d2) { return cutDate( d1 ) == cutDate ( d2 ); } /** returns the day of week SUNDAY = 1, MONDAY = 2, TUESDAY = 3, WEDNESDAY = 4, THURSDAY = 5, FRIDAY = 6, SATURDAY = 7 */ public static int getWeekday(Date date) { long days = countDays(0,date.getTime()); int weekday_zero = THURSDAY; int alt = (int) days%7; int weekday = weekday_zero + alt; if ( weekday > 7) { weekday -=7; } else if ( weekday <=0 ) { weekday += 7 ; } return weekday; } public static int getDayOfWeekInMonth(Date date) { DateWithoutTimezone date2 = toDate( date.getTime()); int day = date2.day; int occurances = (day-1) / 7 + 1; return occurances; } // public static int getWeekOfYear(Date date) // { // // 1970/1/1 is a thursday // long millis = date.getTime(); // long daysSince1970 = millis >= 0 ? millis/ MILLISECONDS_PER_DAY : ((millis + MILLISECONDS_PER_DAY - 1)/ MILLISECONDS_PER_DAY + 1) ; // int weekday = daysSince1970 + 4; // // } public static int getDayOfMonth(Date date) { DateWithoutTimezone date2 = toDate( date.getTime()); int result = date2.day; return result; } // /** uses the calendar-object for date comparison. // * Use this for non GMT Dates*/ // static public boolean isSameDay( Calendar calendar, Date d1, Date d2 ) { // calendar.setTime( d1 ); // int era1 = calendar.get( Calendar.ERA ); // int year1 = calendar.get( Calendar.YEAR ); // int day_of_year1 = calendar.get( Calendar.DAY_OF_YEAR ); // calendar.setTime( d2 ); // int era2 = calendar.get( Calendar.ERA ); // int year2 = calendar.get( Calendar.YEAR ); // int day_of_year2 = calendar.get( Calendar.DAY_OF_YEAR ); // return ( era1 == era2 && year1 == year2 && day_of_year1 == day_of_year2 ); // } static public long countDays(Date start,Date end) { return countDays(start.getTime(), end.getTime()); } static public long countDays(long start,long end) { return (cutDate(end) - cutDate(start)) / MILLISECONDS_PER_DAY; } static public long countMinutes(Date start, Date end) { return (end.getTime()- start.getTime())/ MILLISECONDS_PER_MINUTE; } static public long countMinutes(long start, long end){ return (end-start)/ MILLISECONDS_PER_MINUTE; } // static public Calendar createGMTCalendar() // { // return Calendar.getInstance( GMT); // } static int date_1970_1_1 = calculateJulianDayNumberAtNoon(1970, 1, 1); /** Return a the whole number, with no fraction. The JD at noon is 1 more than the JD at midnight. */ private static int calculateJulianDayNumberAtNoon(int y, int m, int d) { //http://www.hermetic.ch/cal_stud/jdn.htm int result = (1461 * (y + 4800 + (m - 14) / 12)) / 4 + (367 * (m - 2 - 12 * ((m - 14) / 12))) / 12 - (3 * ((y + 4900 + (m - 14) / 12) / 100)) / 4 + d - 32075; return result; } /** * * @param year * @param month ranges from 1-12 * @param day * @return */ public static long toDate(int year, int month, int day ) { int days = calculateJulianDayNumberAtNoon(year, month, day); int diff = days - date_1970_1_1; long millis = diff * MILLISECONDS_PER_DAY; return millis; } public static class DateWithoutTimezone { public int year; public int month; public int day; public String toString() { return year+"-" +month + "-" + day; } } public static class TimeWithoutTimezone { public int hour; public int minute; public int second; public int milliseconds; public String toString() { return hour+":" +minute + ":" + second + "." + milliseconds; } } public static TimeWithoutTimezone toTime(long millis) { long millisInDay = millis - DateTools.cutDate( millis); TimeWithoutTimezone result = new TimeWithoutTimezone(); result.hour = (int) (millisInDay / MILLISECONDS_PER_HOUR); result.minute = (int) ((millisInDay % MILLISECONDS_PER_HOUR) / MILLISECONDS_PER_MINUTE); result.second = (int) ((millisInDay % MILLISECONDS_PER_MINUTE) / 1000); result.milliseconds = (int) (millisInDay % 1000 ); return result; } public static long toTime(int hour, int minute, int second) { return toTime(hour, minute, second, 0); } public static long toTime(int hour, int minute, int second, int millisecond) { long millis = hour * MILLISECONDS_PER_HOUR; millis += minute * MILLISECONDS_PER_MINUTE; millis += second * 1000; millis += millisecond; return millis; } public static DateWithoutTimezone toDate(long millis) { // special case for negative milliseconds as day rounding needs to get the lower day int day = millis >= 0 ? (int) (millis/ MILLISECONDS_PER_DAY) : (int) (( millis + MILLISECONDS_PER_DAY -1) / MILLISECONDS_PER_DAY); int julianDateAtNoon = day + date_1970_1_1; DateWithoutTimezone result = fromJulianDayNumberAtNoon( julianDateAtNoon); return result; } private static DateWithoutTimezone fromJulianDayNumberAtNoon(int julianDateAtNoon) { //http://www.hermetic.ch/cal_stud/jdn.htm int l = julianDateAtNoon + 68569; int n = (4 * l) / 146097; l = l - (146097 * n + 3) / 4; int i = (4000 * (l + 1)) / 1461001; l = l - (1461 * i) / 4 + 31; int j = (80 * l) / 2447; int d = l - (2447 * j) / 80; l = j / 11; int m = j + 2 - (12 * l); int y = 100 * (n - 49) + i + l; DateWithoutTimezone dt = new DateWithoutTimezone(); dt.year = y; dt.month = m; dt.day = d; return dt; } /** returns the largest date null dates count as postive infinity*/ public static Date max(Date... param) { Date max = null; boolean set = false; for (Date d:param) { if ( !set) { max = d; set = true; } else if ( max != null ) { if ( d == null || max.before( d)) { max = d; } } } return max; } }
Java
package org.rapla.components.util; public interface Cancelable { public void cancel(); }
Java
package org.rapla.components.util; public interface Predicate<T> { boolean apply(T t); }
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.components.util; /** Some of the assert functionality of 1.4 for 1.3 versions of Rapla*/ public class Assert { static String NOT_NULL_ASSERTION = "notNull-Assertion"; static String IS_TRUE_ASSERTION = "isTrue-Assertion"; static String ASSERTION_FAIL = "Assertion fail"; static boolean _bActivate = true; public static void notNull(Object obj,String text) { if ( obj == null && isActivated()) { doAssert(getText(NOT_NULL_ASSERTION,text)); } } public static void notNull(Object obj) { if ( obj == null && isActivated()) { doAssert(getText(NOT_NULL_ASSERTION,"")); } } public static void isTrue(boolean condition,String text) { if ( !condition && isActivated()) { doAssert(getText(IS_TRUE_ASSERTION,text)); } // end of if () } public static void isTrue(boolean condition) { if ( !condition && isActivated()) { doAssert(getText(IS_TRUE_ASSERTION,"")); } // end of if () } public static void fail() throws AssertionError { doAssert(getText(ASSERTION_FAIL,"")); } public static void fail(String text) throws AssertionError { doAssert(getText(ASSERTION_FAIL,text)); } private static void doAssert(String text) throws AssertionError { System.err.println(text); throw new AssertionError(text); } static boolean isActivated() { return _bActivate; } static void setActivated(boolean bActivate) { _bActivate = bActivate; } static String getText(String type, String text) { return ( type + " failed '" + text + "'"); } }
Java
package org.rapla.components.util.undo; import java.util.EventListener; public interface CommandHistoryChangedListener extends EventListener { public void historyChanged(); }
Java
package org.rapla.components.util.undo; import java.util.ArrayList; import java.util.List; import java.util.Vector; /** * This is where all the committed actions are saved. * A list will be initialized, every action is an item of this list. * There is a list for the calendar view, and one for the edit view. * @author Jens Fritz * */ //Erstellt von Dominick Krickl-Vorreiter public class CommandHistory { private List<CommandUndo<?>> history = new ArrayList<CommandUndo<?>>(); private int current = -1; private int maxSize = 100; private Vector<CommandHistoryChangedListener> listenerList = new Vector<CommandHistoryChangedListener>(); private void fireChangeEvent() { for (CommandHistoryChangedListener listener: listenerList.toArray(new CommandHistoryChangedListener[] {})) { listener.historyChanged(); } } public <T extends Exception> boolean storeAndExecute(CommandUndo<T> cmd) throws T { while (!history.isEmpty() && (current < history.size() - 1)) { history.remove(history.size() - 1); } while (history.size() >= maxSize) { history.remove(0); current--; } if (cmd.execute()) { history.add(cmd); current++; fireChangeEvent(); return true; } else { return false; } } public void undo() throws Exception { if (!history.isEmpty() && (current >= 0)) { if (history.get(current).undo()) { current--; } fireChangeEvent(); } } public void redo() throws Exception { if (!history.isEmpty() && (current < history.size() - 1)) { if (history.get(current + 1).execute()) { current++; } fireChangeEvent(); } } public void clear() { history.clear(); current = -1; fireChangeEvent(); } public int size() { return history.size(); } public int getCurrent() { return current; } public int getMaxSize() { return maxSize; } public void setMaxSize(int maxSize) { if (maxSize > 0) { this.maxSize = maxSize; } } public boolean canUndo() { return current >= 0; } public boolean canRedo() { return current < history.size() - 1; } public String getRedoText() { if ( !canRedo()) { return ""; } else { return history.get(current + 1).getCommandoName(); } } public String getUndoText() { if ( !canUndo()) { return ""; } else { return history.get(current ).getCommandoName(); } } public void addCommandHistoryChangedListener(CommandHistoryChangedListener actionListener) { this.listenerList.add( actionListener); } public void removeCommandHistoryChangedListener(CommandHistoryChangedListener actionListener) { this.listenerList.remove( actionListener); } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Undo=["); for (int i=current;i>0;i--) { CommandUndo<?> command = history.get(i); builder.append(command.getCommandoName()); if ( i > 0) { builder.append(", "); } } builder.append("]"); builder.append(", "); builder.append("Redo=["); for (int i=current+1;i<history.size();i++) { CommandUndo<?> command = history.get(i); builder.append(command.getCommandoName()); if ( i < history.size() -1) { builder.append(", "); } } builder.append("]"); return builder.toString(); } }
Java
package org.rapla.components.util.undo; //Erstellt von Dominick Krickl-Vorreiter public interface CommandUndo<T extends Exception> { // Der Rückgabewert signalisiert, ob alles korrekt ausgeführt wurde public boolean execute() throws T; public boolean undo() throws T; public String getCommandoName(); }
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.components.util; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Enumeration; import java.util.StringTokenizer; /** Some IOHelper methods. */ abstract public class IOUtil { /** returns the path of the url without the last path component */ public static URL getBase(URL url) { try { String file = url.getPath(); String separator = "/"; if (url.getProtocol().equals("file") && file.indexOf(File.separator)>0) { separator = File.separator; } int index = file.lastIndexOf(separator); String dir = (index<0) ? file: file.substring(0,index + 1); return new URL(url.getProtocol() ,url.getHost() ,url.getPort() ,dir); } catch ( MalformedURLException e) { // This should not happen e.printStackTrace(); throw new RuntimeException("Unknown error while getting the base of the url!"); } // end of try-catch } /** reads the content form an url into a ByteArray*/ public static byte[] readBytes(URL url) throws IOException { InputStream in = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); try { in = url.openStream(); byte[] buffer = new byte[1024]; int count = 0; do { out.write(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); return out.toByteArray(); } finally { if ( in != null) { in.close(); } // end of if () } } /** same as {@link URLDecoder#decode}. * But calls the deprecated method under 1.3. */ public static String decode(String s,String enc) throws UnsupportedEncodingException { return callEncodeDecode(URLDecoder.class,"decode",s,enc); } /** same as {@link URLEncoder#encode}. * But calls the deprecated method under 1.3. */ public static String encode(String s,String enc) throws UnsupportedEncodingException { return callEncodeDecode(URLEncoder.class,"encode",s,enc); } private static String callEncodeDecode(Class<?> clazz,String methodName,String s,String enc) throws UnsupportedEncodingException { Assert.notNull(s); Assert.notNull(enc); try { Method method = clazz.getMethod(methodName ,new Class[] { String.class ,String.class } ); return (String) method.invoke(null,new Object[] {s,enc}); } catch (NoSuchMethodException ex) { try { Method method = URLDecoder.class.getMethod(methodName ,new Class[] {String.class} ); return (String) method.invoke(null,new Object[] {s}); } catch (Exception ex2) { ex2.printStackTrace(); throw new IllegalStateException("Should not happen" + ex2.getMessage()); } } catch (InvocationTargetException ex) { throw (UnsupportedEncodingException) ex.getTargetException(); } catch (IllegalAccessException ex) { ex.printStackTrace(); throw new IllegalStateException("Should not happen" + ex.getMessage()); } } /** returns a BufferedInputStream from the url. If the url-protocol is "file" no url connection will be opened. */ public static InputStream getInputStream(URL url) throws IOException { if (url.getProtocol().equals("file")) { String path = decode(url.getPath(),"UTF-8"); return new BufferedInputStream(new FileInputStream(path)); } else { return new BufferedInputStream(url.openStream()); } // end of else } public static File getFileFrom(URL url) throws IOException { String path = decode(url.getPath(),"UTF-8"); return new File( path ); } /** copies a file. * @param srcPath the source-path. Thats the path of the file that should be copied. * @param destPath the destination-path */ public static void copy( String srcPath, String destPath) throws IOException{ copy( srcPath, destPath, false); } /** copies a file. * @param srcPath the source-path. Thats the path of the file that should be copied. * @param destPath the destination-path */ public static void copy( String srcPath, String destPath,boolean onlyOverwriteIfNewer ) throws IOException{ copy ( new File( srcPath ) , new File( destPath ), onlyOverwriteIfNewer ); } /** copies a file. */ public static void copy(File srcFile, File destFile, boolean onlyOverwriteIfNewer) throws IOException { if ( ! srcFile.exists() ) { throw new IOException( srcFile.getPath() + " doesn't exist!!"); } if ( destFile.exists() && destFile.lastModified() >= srcFile.lastModified() && onlyOverwriteIfNewer) { return; } FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream( srcFile ); out = new FileOutputStream( destFile); copyStreams ( in, out ); } finally { if ( in != null ) in.close(); if ( out != null ) out.close(); } } /** copies the contents of the input stream to the output stream. * @param in * @param out * @throws IOException */ public static void copyStreams( InputStream in, OutputStream out ) throws IOException { byte[] buf = new byte[ 32000 ]; int n = 0; while ( n != -1 ) { out.write( buf, 0, n ); n = in.read(buf, 0, buf.length ); } return; } public static void deleteAll(File f) { if (f.isDirectory()) { File[] files = f.listFiles(); for (File file:files) { deleteAll(file); } } f.delete(); } /** returns the relative path of file to base. * @throws IOException if position of file is not relative to base */ public static String getRelativePath(File base,File file) throws IOException { String filePath = file.getAbsoluteFile().getCanonicalPath(); String basePath = base.getAbsoluteFile().getCanonicalPath(); int start = filePath.indexOf(basePath); if (start != 0) throw new IOException(basePath + " not ancestor of " + filePath); return filePath.substring(basePath.length()); } /** returns the relative path of file to base. * same as {@link #getRelativePath(File, File)} but replaces windows-plattform-specific * file separator <code>\</code> with <code>/</code> * @throws IOException if position of file is not relative to base */ public static String getRelativeURL(File base,File file) throws IOException { StringBuffer result= new StringBuffer(getRelativePath(base,file)); for (int i=0;i<result.length();i++) { if (result.charAt(i) == '\\') result.setCharAt(i, '/'); } return result.toString(); } public static File[] getJarFiles(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()); } } } } return completeList.toArray(new File[] {}); } public static String getStackTraceAsString(Throwable ex) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(bytes,true); writer.println("<h2>" + ex.getMessage() +"</h2><br/>"); ex.printStackTrace(writer); while (true) { ex = ex.getCause(); if (ex != null) { writer.println("<br/><h2>Caused by: "+ ex.getMessage() + "</h2><br/>"); ex.printStackTrace(writer); } else { break; } } return bytes.toString(); } public static boolean isSigned() { try { final ClassLoader classLoader = IOUtil.class.getClassLoader(); { final Enumeration<URL> resources = classLoader.getResources("META-INF/RAPLA.SF"); if (resources.hasMoreElements() ) return true; } { final Enumeration<URL> resources = classLoader.getResources("META-INF/RAPLA.DSA"); if (resources.hasMoreElements() ) return true; } } catch ( IOException ex) { } return false; } }
Java
package org.rapla.components.util.xml; import java.util.Collections; import java.util.Map; public class RaplaSAXAttributes { final Map<String,String> attributeMap; public RaplaSAXAttributes(Map<String,String> map) { this.attributeMap = map; } public String getValue(@SuppressWarnings("unused") String uri,String key) { return getValue( key); } public String getValue(String key) { return attributeMap.get( key); } public Map<String, String> getMap() { return Collections.unmodifiableMap( attributeMap); } }
Java
package org.rapla.components.util.xml; public interface RaplaSAXHandler { public void startElement(String namespaceURI, String localName, RaplaSAXAttributes atts) throws RaplaSAXParseException; public void endElement( String namespaceURI, String localName ) throws RaplaSAXParseException; public void characters( char[] ch, int start, int length ); }
Java
/*---------------------------------------------------------------------------* | (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.components.util.xml; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; final public class XMLReaderAdapter { static SAXParserFactory spfvalidating; static SAXParserFactory spfnonvalidating; static private SAXParserFactory getFactory( boolean validating) { if ( validating && spfvalidating != null) { return spfvalidating; } if ( !validating && spfnonvalidating != null) { return spfnonvalidating; } SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(validating); if ( validating) { spfvalidating = spf; } else { spfnonvalidating = spf; } return spf; } public static XMLReader createXMLReader(boolean validating) throws SAXException { try { SAXParserFactory spf = getFactory(validating); return spf.newSAXParser().getXMLReader(); } catch (Exception ex2) { throw new SAXException("Couldn't create XMLReader " + ex2.getMessage(), ex2); } } }
Java
package org.rapla.components.util.xml; import org.rapla.framework.logger.Logger; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class RaplaErrorHandler implements ErrorHandler { Logger logger; public RaplaErrorHandler(Logger logger) { this.logger = logger; } public void error(SAXParseException exception) throws SAXException { throw exception; } public void fatalError(SAXParseException exception) throws SAXException { throw exception; } public void warning(SAXParseException exception) throws SAXException { if (logger != null) logger.error("Warning: " + getString(exception)); } public String getString(SAXParseException exception) { // return "Line " + exception.getLineNumber() // + "\t Col " + exception.getColumnNumber() // + "\t " + return exception.getMessage(); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util.xml; import java.io.IOException; import java.util.Map; /** Provides some basic functionality for xml-file creation. This * is the SAX like alternative to the creation of a DOM Tree.*/ public class XMLWriter { Appendable appendable; //BufferedWriter writer; boolean xmlSQL = false; public void setWriter(Appendable writer) { this.appendable = writer; } public Appendable getWriter() { return this.appendable; } int level = 0; private void indent() throws IOException { if( !xmlSQL) //BJO do not indent for sql db, XML_VALUE column will be too small for (int i = 0; i < level * 3; i++) write(' '); } protected void increaseIndentLevel() { level ++; } protected void decreaseIndentLevel() { if (level > 0) level --; } public int getIndentLevel() { return level; } public void setIndentLevel(int level) { this.level = level; } public static String encode(String text) { boolean needsEncoding = false; int size = text.length(); for ( int i= 0; i<size && !needsEncoding; i++) { char c = text.charAt(i); switch ( c) { case '<': case '>': case '&': case '"': needsEncoding = true; break; } } if ( !needsEncoding ) return text; StringBuilder buf = new StringBuilder(); for ( int i= 0; i<size; i++) { char c = text.charAt(i); switch ( c) { case '<': buf.append("&lt;"); break; case '>': buf.append("&gt;"); break; case '&': buf.append("&amp;"); break; case '"': buf.append("&quot;"); break; default: buf.append(c); break; } // end of switch () } // end of for () return buf.toString(); } protected void printEncode(String text) throws IOException { if (text == null) return; write( encode(text) ); } protected void openTag(String start) throws IOException { indent(); write('<'); write(start); level++; } protected void openElement(String start) throws IOException { indent(); write('<'); write(start); write('>');newLine(); level++; } protected void openElementOnLine(String start) throws IOException { indent(); write('<'); write(start); write('>'); level++; } protected void att(Map<String,String> attributes) throws IOException{ for (Map.Entry<String, String> entry: attributes.entrySet()) { att(entry.getKey(),entry.getValue()); } } protected void att(String attribute,String value) throws IOException { write(' '); write(attribute); write('='); write('"'); printEncode(value); write('"'); } protected void closeTag() throws IOException { write('>');newLine(); } protected void closeTagOnLine() throws IOException{ write('>'); } protected void closeElementOnLine(String element) throws IOException { level--; write('<'); write('/'); write(element); write('>'); } protected void closeElement(String element) throws IOException { level--; indent(); write('<'); write('/'); write(element); write('>');newLine(); } protected void closeElementTag() throws IOException { level--; write('/'); write('>');newLine(); } /** writes the line to the specified PrintWriter */ public void println(String text) throws IOException { indent(); write(text);newLine(); } protected void newLine() throws IOException { appendable.append("\n"); } protected void write(String text) throws IOException { appendable.append( text); } protected void write(char c) throws IOException { appendable.append( c ); } /** writes the text to the specified PrintWriter */ public void print(String text) throws IOException { write(text); } /** writes the line to the specified PrintWriter */ public void println() throws IOException { newLine(); } public void setSQL(boolean sql) { this.xmlSQL = sql; } }
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.components.util.xml; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; public class RaplaContentHandler extends DefaultHandler { Locator locator; RaplaSAXHandler handler; public RaplaContentHandler(RaplaSAXHandler handler) { this.handler = handler; } public void setDocumentLocator( Locator locator ) { this.locator = locator; } final public void startElement( String namespaceURI, String localName, String qName, Attributes atts ) throws SAXException { try { Map<String,String> attributeMap; if ( atts != null) { int length = atts.getLength(); if ( length == 0) { attributeMap = Collections.emptyMap(); } else if ( length == 1) { String key = atts.getLocalName( 0); String value = atts.getValue( 0); attributeMap = Collections.singletonMap(key, value); } else { attributeMap = new LinkedHashMap<String, String>(); for ( int i=0;i<length;i++) { String key = atts.getLocalName( i); String value = atts.getValue( i); attributeMap.put( key, value); } } } else { attributeMap = Collections.emptyMap(); } handler.startElement( namespaceURI, localName, new RaplaSAXAttributes(attributeMap) ); } catch (RaplaSAXParseException ex) { throw new SAXParseException(ex.getMessage(), locator, ex); } catch (Exception ex) { throw new SAXException( ex ); } } final public void endElement( String namespaceURI, String localName, String qName ) throws SAXException { try { handler.endElement( namespaceURI, localName); } catch ( RaplaSAXParseException ex) { throw new SAXParseException(ex.getMessage(), locator, ex); } } final public void characters( char[] ch, int start, int length ) throws SAXException { handler.characters( ch, start, length ); } }
Java
package org.rapla.components.util.xml; import org.rapla.framework.RaplaException; public class RaplaSAXParseException extends RaplaException{ public RaplaSAXParseException(String text, Throwable cause) { super(text, cause); } /** * */ private static final long serialVersionUID = 1L; }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org . | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.components.util.xml; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; /** Reads the data in xml format from an InputSource into the LocalCache and converts it to a newer version if necessary. */ public interface RaplaNonValidatedInput { public void read(String xml, RaplaSAXHandler handler, Logger logger) throws RaplaException; }
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.components.util; import java.util.Vector; /** Creates a new thread that successively executes the queued command objects * @see Command * @deprecated use CommandScheduler instead */ @Deprecated public class CommandQueue { private Vector<Command> v = new Vector<Command>(); public synchronized void enqueue(Command object) { v.addElement( object ); } public synchronized Command dequeue() { if ( v.size() == 0) return null; Object firstElement =v.firstElement(); if ( firstElement != null) { v.removeElementAt( 0 ); } return (Command) firstElement; } public void dequeueAll() { while ( dequeue() != null){} } /** Creates a new Queue for Command Object. The commands will be executed in succession in a seperate Daemonthread. @see Command */ public static CommandQueue createCommandQueue() { CommandQueue commandQueue = new CommandQueue(); Thread eventThread= new MyEventThread(commandQueue); eventThread.setDaemon(true); eventThread.start(); return commandQueue; } static class MyEventThread extends Thread { CommandQueue commandQueue; MyEventThread(CommandQueue commandQueue) { this.commandQueue = commandQueue; } public void run() { try { while (true) { Command command = commandQueue.dequeue(); if (command == null) { sleep(100); continue; } try { command.execute(); } catch (Exception ex) { ex.printStackTrace(); } } } catch (InterruptedException ex) { } } } }
Java
package org.rapla; import java.util.Arrays; /** Object that encapsulates the login information. * For admin users it is possible to connect as an other user. */ public class ConnectInfo { String username; char[] password; String connectAs; public ConnectInfo(String username, char[] password, String connectAs) { this.username = username; this.password = password; this.connectAs = connectAs; } public ConnectInfo(String username, char[] password) { this( username, password, null); } public String getUsername() { return username; } public char[] getPassword() { return password; } public String getConnectAs() { return connectAs; } @Override public String toString() { return "ReconnectInfo [username=" + username + ", password=" + Arrays.toString(password) + ", connectAs=" + connectAs + "]"; } }
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.server; import org.rapla.facade.ClientFacade; import org.rapla.framework.RaplaContext; /** Encapsulates a StorageOperator. This service is responsible for <ul> <li>synchronizing update and remove request from clients and passing them to the storage-operator</li> <li>authentification of the clients</li> <li>notifying subscribed clients when the stored-data has changed</li> </ul> */ public interface ServerService { ClientFacade getFacade(); RaplaContext getContext(); }
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.server; import org.rapla.entities.User; import org.rapla.framework.RaplaContextException; import org.rapla.framework.logger.Logger; /** An interface to access the SessionInformation. An implementation of * RemoteSession gets passed to the creation RaplaRemoteService.*/ public interface RemoteSession { boolean isAuthentified(); User getUser() throws RaplaContextException; Logger getLogger(); //String getAccessToken(); }
Java
package org.rapla.server.internal; import java.util.Date; import java.util.TimeZone; import org.rapla.components.util.DateTools; import org.rapla.server.TimeZoneConverter; public class TimeZoneConverterImpl implements TimeZoneConverter { TimeZone zone; TimeZone importExportTimeZone; public TimeZoneConverterImpl() { zone = DateTools.getTimeZone(); TimeZone systemTimezone = TimeZone.getDefault(); importExportTimeZone = systemTimezone; } public TimeZone getImportExportTimeZone() { return importExportTimeZone; } public void setImportExportTimeZone(TimeZone importExportTimeZone) { this.importExportTimeZone = importExportTimeZone; } public long fromRaplaTime(TimeZone timeZone,long raplaTime) { long offset = TimeZoneConverterImpl.getOffset(zone,timeZone, raplaTime); return raplaTime - offset; } public long toRaplaTime(TimeZone timeZone,long time) { long offset = TimeZoneConverterImpl.getOffset(zone,timeZone,time); return time + offset; } public Date fromRaplaTime(TimeZone timeZone,Date raplaTime) { return new Date( fromRaplaTime(timeZone, raplaTime.getTime())); } public Date toRaplaTime(TimeZone timeZone,Date time) { return new Date( toRaplaTime(timeZone, time.getTime())); } public static int getOffset(TimeZone zone1,TimeZone zone2,long time) { int offsetRapla = zone1.getOffset(time); int offsetSystem = zone2.getOffset(time); return offsetSystem - offsetRapla; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.server.internal; import java.lang.reflect.Method; 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 java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.servlet.http.HttpServletRequest; import net.fortuna.ical4j.model.TimeZoneRegistry; import net.fortuna.ical4j.model.TimeZoneRegistryFactory; import org.rapla.ConnectInfo; import org.rapla.RaplaMainContainer; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.entities.domain.Permission; import org.rapla.entities.internal.UserImpl; import org.rapla.facade.ClientFacade; import org.rapla.facade.RaplaComponent; import org.rapla.facade.internal.FacadeImpl; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.framework.internal.ComponentInfo; import org.rapla.framework.internal.ContainerImpl; import org.rapla.framework.internal.RaplaLocaleImpl; import org.rapla.framework.internal.RaplaMetaConfigInfo; import org.rapla.framework.logger.Logger; import org.rapla.plugin.export2ical.Export2iCalPlugin; import org.rapla.rest.gwtjsonrpc.common.FutureResult; import org.rapla.rest.gwtjsonrpc.common.ResultImpl; import org.rapla.rest.gwtjsonrpc.common.VoidResult; import org.rapla.rest.gwtjsonrpc.server.SignedToken; import org.rapla.rest.gwtjsonrpc.server.ValidToken; import org.rapla.rest.gwtjsonrpc.server.XsrfException; import org.rapla.rest.server.RaplaAPIPage; import org.rapla.rest.server.RaplaAuthRestPage; import org.rapla.rest.server.RaplaDynamicTypesRestPage; import org.rapla.rest.server.RaplaEventsRestPage; import org.rapla.rest.server.RaplaResourcesRestPage; import org.rapla.server.AuthenticationStore; import org.rapla.server.RaplaKeyStorage; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.server.RemoteMethodFactory; import org.rapla.server.RemoteSession; import org.rapla.server.ServerService; import org.rapla.server.ServerServiceContainer; import org.rapla.server.TimeZoneConverter; import org.rapla.servletpages.DefaultHTMLMenuEntry; import org.rapla.servletpages.RaplaAppletPageGenerator; import org.rapla.servletpages.RaplaIndexPageGenerator; import org.rapla.servletpages.RaplaJNLPPageGenerator; import org.rapla.servletpages.RaplaPageGenerator; import org.rapla.servletpages.RaplaStatusPageGenerator; import org.rapla.servletpages.RaplaStorePage; import org.rapla.storage.CachableStorageOperator; import org.rapla.storage.RaplaSecurityException; import org.rapla.storage.StorageOperator; import org.rapla.storage.StorageUpdateListener; import org.rapla.storage.UpdateResult; import org.rapla.storage.dbrm.LoginCredentials; import org.rapla.storage.dbrm.LoginTokens; import org.rapla.storage.dbrm.RemoteConnectionInfo; import org.rapla.storage.dbrm.RemoteMethodStub; import org.rapla.storage.dbrm.RemoteServer; import org.rapla.storage.dbrm.RemoteStorage; import org.rapla.storage.impl.server.LocalAbstractCachableOperator; /** Default implementation of StorageService. * <p>Sample configuration 1: <pre> &lt;storage id="storage" > &lt;store>file&lt;/store> &lt;/storage> </pre> * The store value contains the id of a storage-component. * Storage-Components are all components that implement the * <code>CachableStorageOperator<code> interface. * * </p> @see ServerService */ public class ServerServiceImpl extends ContainerImpl implements StorageUpdateListener, ServerServiceContainer, ServerService, ShutdownService, RemoteMethodFactory<RemoteServer>,RemoteMethodStub { @SuppressWarnings("rawtypes") public static Class<RemoteMethodFactory> REMOTE_METHOD_FACTORY = RemoteMethodFactory.class; static Class<RaplaPageGenerator> SERVLET_PAGE_EXTENSION = RaplaPageGenerator.class; protected CachableStorageOperator operator; protected I18nBundle i18n; List<PluginDescriptor<ServerServiceContainer>> pluginList; ClientFacade facade; private AuthenticationStore authenticationStore; SignedToken accessTokenSigner; SignedToken refreshTokenSigner; RemoteSessionImpl standaloneSession; ShutdownService shutdownService; // 5 Hours until the token expires int accessTokenValiditySeconds = 300 * 60; public ServerServiceImpl( RaplaContext parentContext, Configuration config, Logger logger) throws RaplaException { super( parentContext, config, logger ); addContainerProvidedComponent( TimeZoneConverter.class, TimeZoneConverterImpl.class); i18n = parentContext.lookup( RaplaComponent.RAPLA_RESOURCES ); Configuration login = config.getChild( "login" ); String username = login.getChild( "username" ).getValue( null ); String password = login.getChild( "password" ).getValue( "" ); RaplaContext context = getContext(); if ( config.getChildren("facade").length >0 ) { facade = m_context.lookup(ClientFacade.class); } else { // for old raplaserver.xconf facade = new FacadeImpl( context, config, getLogger().getChildLogger("serverfacade") ); } operator = (CachableStorageOperator) facade.getOperator(); addContainerProvidedComponentInstance( ServerService.class, this); addContainerProvidedComponentInstance( ShutdownService.class, this); addContainerProvidedComponentInstance( ServerServiceContainer.class, this); addContainerProvidedComponentInstance( CachableStorageOperator.class, operator ); addContainerProvidedComponentInstance( StorageOperator.class, operator ); addContainerProvidedComponentInstance( ClientFacade.class, facade ); addContainerProvidedComponent( SecurityManager.class, SecurityManager.class ); addRemoteMethodFactory(RemoteStorage.class,RemoteStorageImpl.class, null); addContainerProvidedComponentInstance( REMOTE_METHOD_FACTORY, this, RemoteServer.class.getName() ); // adds 5 basic pages to the webapplication addWebpage( "server",RaplaStatusPageGenerator.class); addWebpage( "json",RaplaAPIPage.class); addWebpage( "resources",RaplaResourcesRestPage.class); addWebpage( "events",RaplaEventsRestPage.class); addWebpage( "dynamictypes",RaplaDynamicTypesRestPage.class); addWebpage( "auth",RaplaAuthRestPage.class); addWebpage( "index",RaplaIndexPageGenerator.class ); addWebpage( "raplaclient.jnlp",RaplaJNLPPageGenerator.class ); addWebpage( "raplaclient",RaplaJNLPPageGenerator.class ); addWebpage( "raplaapplet",RaplaAppletPageGenerator.class ); addWebpage( "store",RaplaStorePage.class); addWebpage( "raplaclient.xconf",RaplaConfPageGenerator.class ); addWebpage( "raplaclient.xconf",RaplaConfPageGenerator.class); I18nBundle i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES); // Index page menu addContainerProvidedComponentInstance( RaplaServerExtensionPoints.HTML_MAIN_MENU_EXTENSION_POINT, new DefaultHTMLMenuEntry(context,i18n.getString( "start_rapla_with_webstart" ),"rapla/raplaclient.jnlp") ); addContainerProvidedComponentInstance( RaplaServerExtensionPoints.HTML_MAIN_MENU_EXTENSION_POINT, new DefaultHTMLMenuEntry(context,i18n.getString( "start_rapla_with_applet" ),"rapla?page=raplaapplet") ); addContainerProvidedComponentInstance( RaplaServerExtensionPoints.HTML_MAIN_MENU_EXTENSION_POINT, new DefaultHTMLMenuEntry(context,i18n.getString( "server_status" ),"rapla?page=server") ); standaloneSession = new RemoteSessionImpl(getContext(), "session"); operator.addStorageUpdateListener( this ); if ( username != null ) operator.connect( new ConnectInfo(username, password.toCharArray())); else operator.connect(); Set<String> pluginNames; //List<PluginDescriptor<ClientServiceContainer>> pluginList; try { pluginNames = context.lookup( RaplaMainContainer.PLUGIN_LIST); } catch (RaplaContextException ex) { throw new RaplaException (ex ); } pluginList = new ArrayList<PluginDescriptor<ServerServiceContainer>>( ); Logger pluginLogger = getLogger().getChildLogger("plugin"); for ( String plugin:pluginNames) { try { boolean found = false; try { Class<?> componentClass = ServerServiceImpl.class.getClassLoader().loadClass( plugin ); Method[] methods = componentClass.getMethods(); for ( Method method:methods) { if ( method.getName().equals("provideServices")) { Class<?> type = method.getParameterTypes()[0]; if (ServerServiceContainer.class.isAssignableFrom(type)) { found = true; } } } } catch (ClassNotFoundException e1) { } catch (Exception e1) { getLogger().warn(e1.getMessage()); continue; } if ( found ) { @SuppressWarnings("unchecked") PluginDescriptor<ServerServiceContainer> descriptor = (PluginDescriptor<ServerServiceContainer>) instanciate(plugin, null, logger); pluginList.add(descriptor); pluginLogger.info("Installed plugin "+plugin); } } catch (RaplaContextException e) { if (e.getCause() instanceof ClassNotFoundException) { pluginLogger.error("Could not instanciate plugin "+ plugin, e); } } } addContainerProvidedComponent(RaplaKeyStorage.class, RaplaKeyStorageImpl.class); try { RaplaKeyStorage keyStorage = getContext().lookup( RaplaKeyStorage.class); String secretKey = keyStorage.getRootKeyBase64(); accessTokenSigner = new SignedToken(accessTokenValiditySeconds , secretKey); refreshTokenSigner = new SignedToken(-1 , secretKey); } catch (Exception e) { throw new RaplaException( e.getMessage(), e); } Preferences preferences = operator.getPreferences( null, true ); //RaplaConfiguration encryptionConfig = preferences.getEntry(EncryptionService.CONFIG); //addRemoteMethodFactory( EncryptionService.class, EncryptionServiceFactory.class); RaplaConfiguration entry = preferences.getEntry(RaplaComponent.PLUGIN_CONFIG); String importExportTimeZone = TimeZone.getDefault().getID(); if ( entry != null) { Configuration find = entry.find("class", Export2iCalPlugin.PLUGIN_CLASS); if ( find != null) { String timeZone = find.getChild("TIMEZONE").getValue( null); if ( timeZone != null && !timeZone.equals("Etc/UTC")) { importExportTimeZone = timeZone; } } } String timezoneId = preferences.getEntryAsString(RaplaMainContainer.TIMEZONE, importExportTimeZone); RaplaLocale raplaLocale = context.lookup(RaplaLocale.class); TimeZoneConverter importExportLocale = context.lookup(TimeZoneConverter.class); try { TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry(); TimeZone timeZone = registry.getTimeZone(timezoneId); ((RaplaLocaleImpl) raplaLocale).setImportExportTimeZone( timeZone); ((TimeZoneConverterImpl) importExportLocale).setImportExportTimeZone( timeZone); if ( operator instanceof LocalAbstractCachableOperator) { ((LocalAbstractCachableOperator) operator).setTimeZone( timeZone); } } catch (Exception rc) { getLogger().error("Timezone " + timezoneId + " not found. " + rc.getMessage() + " Using system timezone " + importExportLocale.getImportExportTimeZone()); } initializePlugins( pluginList, preferences ); if ( context.has( AuthenticationStore.class ) ) { try { authenticationStore = context.lookup( AuthenticationStore.class ); getLogger().info( "Using AuthenticationStore " + authenticationStore.getName() ); } catch ( RaplaException ex) { getLogger().error( "Can't initialize configured authentication store. Using default authentication." , ex); } } // Provider<EntityStore> storeProvider = new Provider<EntityStore>() // { // public EntityStore get() { // return new EntityStore(operator, operator.getSuperCategory()); // } // // }; } @Override protected Map<String,ComponentInfo> getComponentInfos() { return new RaplaMetaConfigInfo(); } public <T> void addRemoteMethodFactory(Class<T> role, Class<? extends RemoteMethodFactory<T>> factory) { addRemoteMethodFactory(role, factory, null); } public <T> void addRemoteMethodFactory(Class<T> role, Class<? extends RemoteMethodFactory<T>> factory, Configuration configuration) { addContainerProvidedComponent(REMOTE_METHOD_FACTORY,factory, role.getName(), configuration); } protected RemoteMethodFactory<?> getRemoteMethod(String interfaceName) throws RaplaContextException { RemoteMethodFactory<?> factory = lookup( REMOTE_METHOD_FACTORY ,interfaceName); return factory; } public <T extends RaplaPageGenerator> void addWebpage(String pagename, Class<T> pageClass) { addWebpage(pagename, pageClass, null); } public <T extends RaplaPageGenerator> void addWebpage(String pagename, Class<T> pageClass, Configuration configuration) { String lowerCase = pagename.toLowerCase(); addContainerProvidedComponent(SERVLET_PAGE_EXTENSION,pageClass, lowerCase, configuration); } public RaplaPageGenerator getWebpage(String page) { try { String lowerCase = page.toLowerCase(); RaplaPageGenerator factory = lookup( SERVLET_PAGE_EXTENSION ,lowerCase); return factory; } catch (RaplaContextException ex) { Throwable cause = ex.getCause(); if ( cause != null) { getLogger().error(cause.getMessage(),cause); } return null; } } public void updateError( RaplaException ex ) { if ( getLogger() != null ) getLogger().error( ex.getMessage(), ex ); try { stop(); } catch ( Exception e ) { if ( getLogger() != null ) getLogger().error( e.getMessage() ); } } public void objectsUpdated(UpdateResult evt) { } /** * @see org.rapla.server.ServerService#getFacade() */ public ClientFacade getFacade() { return facade; } protected void initializePlugins( List<PluginDescriptor<ServerServiceContainer>> pluginList, Preferences preferences ) throws RaplaException { RaplaConfiguration raplaConfig = preferences.getEntry( RaplaComponent.PLUGIN_CONFIG); // Add plugin configs for ( Iterator<PluginDescriptor<ServerServiceContainer>> it = pluginList.iterator(); it.hasNext(); ) { PluginDescriptor<ServerServiceContainer> pluginDescriptor = it.next(); String pluginClassname = pluginDescriptor.getClass().getName(); Configuration pluginConfig = null; if ( raplaConfig != null ) { // TODO should be replaced with a more desciptve approach instead of looking for the config by guessing from the package name pluginConfig = raplaConfig.find( "class", pluginClassname ); // If no plugin config for server is found look for plugin config for client plugin if ( pluginConfig == null ) { pluginClassname = pluginClassname.replaceAll("ServerPlugin", "Plugin"); pluginClassname = pluginClassname.replaceAll(".server.", ".client."); pluginConfig = raplaConfig.find( "class", pluginClassname ); if ( pluginConfig == null) { pluginClassname = pluginClassname.replaceAll(".client.", "."); pluginConfig = raplaConfig.find( "class", pluginClassname ); } } } if ( pluginConfig == null ) { pluginConfig = new DefaultConfiguration( "plugin" ); } pluginDescriptor.provideServices( this, pluginConfig ); } lookupServicesFor(RaplaServerExtensionPoints.SERVER_EXTENSION ); } private void stop() { boolean wasConnected = operator.isConnected(); operator.removeStorageUpdateListener( this ); Logger logger = getLogger(); try { operator.disconnect(); } catch (RaplaException e) { logger.error( "Could not disconnect operator " , e); } finally { } if ( wasConnected ) { logger.info( "Storage service stopped" ); } } public void dispose() { stop(); super.dispose(); } public StorageOperator getOperator() { return operator; } public void storageDisconnected(String message) { try { stop(); } catch ( Exception e ) { if ( getLogger() != null ) getLogger().error( e.getMessage() ); } } // public byte[] dispatch(RemoteSession remoteSession, String methodName, Map<String,String> args ) throws Exception // { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // int indexRole = methodName.indexOf( "/" ); // String interfaceName = RemoteStorage.class.getName(); // if ( indexRole > 0 ) // { // interfaceName = methodName.substring( 0, indexRole ); // methodName = methodName.substring( indexRole + 1 ); // } // try // { // final Object serviceUncasted; // { // Logger debugLogger = getLogger().getChildLogger(interfaceName+"."+ methodName + ".arguments" ); // if ( debugLogger.isDebugEnabled()) // { // debugLogger.debug(args.toString()); // } // } // RemoteMethodFactory<?> factory = getRemoteMethod(interfaceName); // Class<?> interfaceClass = Class.forName( interfaceName); // // serviceUncasted = factory.createService( remoteSession); // Method method = findMethod( interfaceClass, methodName, args); // if ( method == null) // { // throw new RaplaException("Can't find method with name " + methodName); // } // Class<?>[] parameterTypes = method.getParameterTypes(); // Object[] convertedArgs = remoteMethodService.deserializeArguments(parameterTypes,args); // Object result = null; // try // { // result = method.invoke( serviceUncasted, convertedArgs); // } // catch (InvocationTargetException ex) // { // Throwable cause = ex.getCause(); // if (cause instanceof RaplaException) // { // throw (RaplaException)cause; // } // else // { // throw new RaplaException( cause.getMessage(), cause ); // } // } // User user = remoteSession.isAuthentified() ? remoteSession.getUser() : null; // // if ( result != null) // { // BufferedWriter outWriter = new BufferedWriter( new OutputStreamWriter( out,"utf-8")); // Appendable appendable = outWriter; // // we don't trasmit password settings in the general preference entry when the user is not an admin // remoteMethodService.serializeReturnValue(user, result, appendable); // outWriter.flush(); // } // else // { //// BufferedWriter outWriter = new BufferedWriter( new OutputStreamWriter( out,"utf-8")); //// outWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); //// outWriter.write("/n"); //// outWriter.write("<data/>"); //// outWriter.flush(); // } // out.flush(); // } // catch (EntityNotFoundException ex) // { // throw ex; // } // catch (DependencyException ex) // { // throw ex; // } // catch (RaplaNewVersionException ex) // { // throw ex; // } // catch (RaplaSecurityException ex) // { // getLogger().getChildLogger( interfaceName + "." + methodName).warn( ex.getMessage()); // throw ex; // } // catch ( Exception ex ) // { // getLogger().getChildLogger( interfaceName + "." + methodName).error( ex.getMessage(), ex ); // throw ex; // } // out.close(); // return out.toByteArray(); // } // private Method findMethod( Class inter,String methodName,Map<String,String> args) // { // Method[] methods = inter.getMethods(); // for ( Method method: methods) // { // if ( method.getName().equals( methodName) ) // { // Class<?>[] parameterTypes = method.getParameterTypes(); // Annotation[][] parameterAnnotations = method.getParameterAnnotations(); // int length = parameterTypes.length; // // Map // //for ( int i=0;) // if (parameterTypes.length == args.size()) // return method; // } // } // return null; // } public RemoteServer createService(final RemoteSession session) { return new RemoteServer() { public Logger getLogger() { if ( session != null) { return session.getLogger(); } else { return ServerServiceImpl.this.getLogger(); } } @Override public void setConnectInfo(RemoteConnectionInfo info) { } @Override public FutureResult<VoidResult> logout() { try { if ( session != null) { if ( session.isAuthentified()) { User user = session.getUser(); if ( user != null) { getLogger().getChildLogger("login").info( "Request Logout " + user.getUsername()); } ((RemoteSessionImpl)session).logout(); } } } catch (RaplaException ex) { return new ResultImpl<VoidResult>(ex); } return ResultImpl.VOID; } @Override public FutureResult<LoginTokens> login( String username, String password, String connectAs ) { LoginCredentials loginCredentials = new LoginCredentials(username,password,connectAs); return auth(loginCredentials); } @Override public FutureResult<LoginTokens> auth( LoginCredentials credentials ) { try { User user; String username = credentials.getUsername(); String password = credentials.getPassword(); String connectAs = credentials.getConnectAs(); boolean isStandalone = getContext().has( RemoteMethodStub.class); if ( isStandalone) { String toConnect = connectAs != null && !connectAs.isEmpty() ? connectAs : username; // don't check passwords in standalone version user = operator.getUser( toConnect); if ( user == null) { throw new RaplaSecurityException(i18n.getString("error.login")); } standaloneSession.setUser( user); } else { Logger logger = getLogger().getChildLogger("login"); user = authenticate(username, password, connectAs, logger); ((RemoteSessionImpl)session).setUser( user); } if ( connectAs != null && connectAs.length()> 0) { if (!operator.getUser( username).isAdmin()) { throw new SecurityException("Non admin user is requesting change user permission!"); } } FutureResult<LoginTokens> generateAccessToken = generateAccessToken(user); return generateAccessToken; } catch (RaplaException ex) { return new ResultImpl<LoginTokens>(ex); } } private FutureResult<LoginTokens> generateAccessToken(User user) throws RaplaException { try { String userId = user.getId(); Date now = operator.getCurrentTimestamp(); Date validUntil = new Date(now.getTime() + 1000 * accessTokenValiditySeconds); String signedToken = accessTokenSigner.newToken( userId, now); return new ResultImpl<LoginTokens>(new LoginTokens( signedToken, validUntil)); } catch (Exception e) { throw new RaplaException(e.getMessage()); } } @Override public FutureResult<String> getRefreshToken() { try { User user = getValidUser(session); RaplaKeyStorage keyStore = getContext().lookup(RaplaKeyStorage.class); Collection<String> apiKeys = keyStore.getAPIKeys(user); String refreshToken; if ( apiKeys.size() == 0) { refreshToken = null; } else { refreshToken = apiKeys.iterator().next(); } return new ResultImpl<String>(refreshToken); } catch (RaplaException ex) { return new ResultImpl<String>(ex); } } @Override public FutureResult<String> regenerateRefreshToken() { try { User user = getValidUser(session); RaplaKeyStorage keyStore = getContext().lookup(RaplaKeyStorage.class); Date now = operator.getCurrentTimestamp(); String generatedAPIKey = refreshTokenSigner.newToken(user.getId(), now); keyStore.storeAPIKey(user, "refreshToken",generatedAPIKey); return new ResultImpl<String>(generatedAPIKey); } catch (Exception ex) { return new ResultImpl<String>(ex); } } @Override public FutureResult<LoginTokens> refresh(String refreshToken) { try { User user = getUser(refreshToken, refreshTokenSigner); RaplaKeyStorage keyStore = getContext().lookup(RaplaKeyStorage.class); Collection<String> apiKeys = keyStore.getAPIKeys(user); if ( !apiKeys.contains( refreshToken)) { throw new RaplaSecurityException("refreshToken not valid"); } FutureResult<LoginTokens> generateAccessToken = generateAccessToken(user); return generateAccessToken; } catch (RaplaException ex) { return new ResultImpl<LoginTokens>(ex); } } public User getValidUser(final RemoteSession session) throws RaplaContextException, RaplaSecurityException { User user = session.getUser(); if ( user == null) { throw new RaplaSecurityException(i18n.getString("error.login")); } return user; } }; } public User authenticate(String username, String password,String connectAs, Logger logger) throws RaplaException,RaplaSecurityException { User user; String toConnect = connectAs != null && !connectAs.isEmpty() ? connectAs : username; logger.info( "User '" + username + "' is requesting login." ); if ( authenticationStore != null ) { logger.info("Checking external authentifiction for user " + username); boolean authenticateExternal; try { authenticateExternal = authenticationStore.authenticate( username, password ); } catch (RaplaException ex) { authenticateExternal= false; getLogger().error(ex.getMessage(), ex); } if (authenticateExternal) { logger.info("Successfull for " + username); //@SuppressWarnings("unchecked") user = operator.getUser( username ); if ( user == null ) { logger.info("User not found in localstore. Creating new Rapla user " + username); Date now = operator.getCurrentTimestamp(); UserImpl newUser = new UserImpl(now,now); newUser.setId( operator.createIdentifier( User.TYPE,1 )[0] ); user = newUser; } else { Set<Entity>singleton = Collections.singleton((Entity)user); Collection<Entity> editList = operator.editObjects( singleton, null ); user = (User)editList.iterator().next(); } boolean initUser ; try { Category groupCategory = operator.getSuperCategory().getCategory( Permission.GROUP_CATEGORY_KEY ); logger.info("Looking for update for rapla user '" + username + "' from external source."); initUser = authenticationStore.initUser( (User) user, username, password, groupCategory ); } catch (RaplaSecurityException ex){ throw new RaplaSecurityException(i18n.getString("error.login")); } if ( initUser ) { logger.info("Udating rapla user '" + username + "' from external source."); List<Entity>storeList = new ArrayList<Entity>(1); storeList.add( user); List<Entity>removeList = Collections.emptyList(); operator.storeAndRemove( storeList, removeList, null ); } else { logger.info("User '" + username + "' already up to date"); } } else { logger.info("Now trying to authenticate with local store '" + username + "'"); operator.authenticate( username, password ); } // do nothing } // if the authenticationStore can't authenticate the user is checked against the local database else { logger.info("Check password for " + username); operator.authenticate( username, password ); } if ( connectAs != null && connectAs.length() > 0) { logger.info("Successfull login for '" + username +"' acts as user '" + connectAs + "'"); } else { logger.info("Successfull login for '" + username + "'"); } user = operator.getUser(toConnect); if ( user == null) { throw new RaplaException("User with username '" + toConnect + "' not found"); } return user; } public void setShutdownService(ShutdownService shutdownService) { this.shutdownService = shutdownService; } public <T> T getWebserviceLocalStub(final Class<T> a) throws RaplaContextException { @SuppressWarnings("unchecked") RemoteMethodFactory<T> factory =lookup( REMOTE_METHOD_FACTORY ,a.getName()); T service = factory.createService( standaloneSession); return service; } public void shutdown(boolean restart) { if ( shutdownService != null) { shutdownService.shutdown(restart); } else { getLogger().error("Shutdown service not set"); } } public RemoteSession getRemoteSession(HttpServletRequest request) throws RaplaException { User user = getUser(request); RemoteSessionImpl remoteSession = new RemoteSessionImpl(getContext(), user != null ? user.getUsername() : "anonymous"); remoteSession.setUser( (User) user); // remoteSession.setAccessToken( token ); return remoteSession; } public User getUser(HttpServletRequest request) throws RaplaException { String token = request.getHeader("Authorization"); if ( token != null) { String bearerStr = "bearer"; int bearer = token.toLowerCase().indexOf(bearerStr); if ( bearer >= 0) { token = token.substring( bearer + bearerStr.length()).trim(); } } else { token = request.getParameter("access_token"); } User user = null; if ( token == null) { String username = request.getParameter("username"); if ( username != null) { user = getUserWithoutPassword(username); } } if ( user == null) { user = getUser( token, accessTokenSigner); } return user; } @SuppressWarnings("unchecked") @Override public <T> T createWebservice(Class<T> role, HttpServletRequest request) throws RaplaException { RemoteMethodFactory<T> remoteMethod = (RemoteMethodFactory<T>) getRemoteMethod( role.getName()); RemoteSession remoteSession = getRemoteSession(request); return remoteMethod.createService(remoteSession); } @Override public boolean hasWebservice(String interfaceName) { try { lookup( REMOTE_METHOD_FACTORY ,interfaceName); } catch (RaplaContextException e) { return false; } return true; } private User getUserWithoutPassword(String username) throws RaplaException { String connectAs = null; User user = authenticate(username, "", connectAs, getLogger()); return user; } private User getUser(String tokenString,SignedToken tokenSigner) throws RaplaException { if ( tokenString == null) { return null; } final int s = tokenString.indexOf('$'); if (s <= 0) { return null; } final String recvText = tokenString.substring(s + 1); try { Date now = operator.getCurrentTimestamp(); ValidToken checkToken = tokenSigner.checkToken(tokenString, recvText, now); if ( checkToken == null) { throw new RaplaSecurityException(RemoteStorage.USER_WAS_NOT_AUTHENTIFIED + " InvalidToken " + tokenString); } } catch (XsrfException e) { throw new RaplaSecurityException(e.getMessage(), e); } String userId = recvText; User user = operator.resolve( userId, User.class); return user; } }
Java
package org.rapla.server.internal; import org.rapla.entities.User; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.logger.Logger; import org.rapla.server.RemoteSession; /** Implementation of RemoteStorage as a RemoteService * @see org.rapla.storage.dbrm.RemoteStorage */ public class RemoteSessionImpl extends RaplaComponent implements RemoteSession { /** * */ User user; Logger logger; // private String accessToken; public RemoteSessionImpl(RaplaContext context, String clientName) { super( context ); logger = super.getLogger().getChildLogger(clientName); } public Logger getLogger() { return logger; } @Override public User getUser() throws RaplaContextException { if (user == null) throw new RaplaContextException("No user found in session."); return user; } @Override public boolean isAuthentified() { return user != null; } public void setUser( User user) { this.user = user; } // public void setAccessToken( String token) // { // this.accessToken = token; // } // // @Override // public String getAccessToken() { // return accessToken; // } public void logout() { this.setUser( null); } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Praktikum Gruppe2?, 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.server.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.Ownable; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentFormater; import org.rapla.entities.domain.Permission; import org.rapla.entities.domain.Reservation; import org.rapla.facade.ClientFacade; import org.rapla.facade.Conflict; import org.rapla.facade.RaplaComponent; import org.rapla.facade.internal.FacadeImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; import org.rapla.storage.CachableStorageOperator; import org.rapla.storage.PreferencePatch; import org.rapla.storage.RaplaSecurityException; /** checks if the client can store or delete an entity */ public class SecurityManager { I18nBundle i18n; AppointmentFormater appointmentFormater; CachableStorageOperator operator; RaplaContext context; Logger logger; public SecurityManager(RaplaContext context) throws RaplaException { logger = context.lookup( Logger.class); operator = context.lookup( CachableStorageOperator.class); i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES); appointmentFormater = context.lookup(AppointmentFormater.class); this.context = context; } void checkWritePermissions(User user,Entity entity) throws RaplaSecurityException { if (user.isAdmin()) return; Object id = entity.getId(); if (id == null) throw new RaplaSecurityException("No id set"); boolean permitted = false; @SuppressWarnings("unchecked") Class<Entity> typeClass = entity.getRaplaType().getTypeClass(); Entity original = operator.tryResolve( entity.getId(), typeClass); // flag indicates if a user only exchanges allocatables (needs to have admin-access on the allocatable) boolean canExchange = false; boolean ownable = entity instanceof Ownable; if (ownable || entity instanceof Appointment) { User entityOwner; if ( ownable) { entityOwner = ((Ownable) entity).getOwner(); } else { entityOwner = ((Appointment) entity).getOwner(); } if (original == null) { permitted = entityOwner != null && user.isIdentical(entityOwner); if (getLogger().isDebugEnabled()) getLogger().debug("Permissions for new object " + entity + "\nUser check: " + user + " = " + entityOwner); } else { User originalOwner; if ( ownable) { originalOwner = ((Ownable) original).getOwner(); } else { originalOwner = ((Appointment) original).getOwner(); } if (getLogger().isDebugEnabled()) getLogger().debug("Permissions for existing object " + entity + "\nUser check: " + user + " = " + entityOwner + " = " + originalOwner); permitted = (originalOwner != null) && originalOwner.isIdentical(user) && originalOwner.isIdentical(entityOwner); if ( !permitted ) { canExchange = canExchange( user, entity, original ); permitted = canExchange; } } } if ( !permitted && entity instanceof Allocatable ){ if ( original == null ) { permitted = isRegisterer(user); } else { permitted = ((Allocatable)original).canModify( user ); } } if ( !permitted && original != null) { permitted = RaplaComponent.checkClassifiableModifyPermissions(original, user); } if (!permitted && entity instanceof Appointment) { final Reservation reservation = ((Appointment)entity).getReservation(); Reservation originalReservation = operator.tryResolve(reservation.getId(), Reservation.class); if ( originalReservation != null) { permitted = RaplaComponent.checkClassifiableModifyPermissions(originalReservation, user); } } if (!permitted) throw new RaplaSecurityException(i18n.format("error.modify_not_allowed", new Object []{ user.toString(),entity.toString()})); // Check if the user can change the reservation if ( Reservation.TYPE ==entity.getRaplaType() ) { Reservation reservation = (Reservation) entity ; Reservation originalReservation = (Reservation)original; Allocatable[] all = reservation.getAllocatables(); if ( originalReservation != null && canExchange ) { List<Allocatable> newAllocatabes = new ArrayList<Allocatable>( Arrays.asList(reservation.getAllocatables() ) ); newAllocatabes.removeAll( Arrays.asList( originalReservation.getAllocatables())); all = newAllocatabes.toArray( Allocatable.ALLOCATABLE_ARRAY); } if ( originalReservation == null) { Category group = getUserGroupsCategory().getCategory( Permission.GROUP_CAN_CREATE_EVENTS); if (group != null && !user.belongsTo(group)) { throw new RaplaSecurityException(i18n.format("error.create_not_allowed", new Object []{ user.toString(),entity.toString()})); } } checkPermissions( user, reservation, originalReservation , all); } } private Logger getLogger() { return logger; } protected boolean isRegisterer(User user) throws RaplaSecurityException { try { Category registererGroup = getUserGroupsCategory().getCategory(Permission.GROUP_REGISTERER_KEY); return user.belongsTo(registererGroup); } catch (RaplaException ex) { throw new RaplaSecurityException(ex ); } } public Category getUserGroupsCategory() throws RaplaSecurityException { Category userGroups = operator.getSuperCategory().getCategory(Permission.GROUP_CATEGORY_KEY); if ( userGroups == null) { throw new RaplaSecurityException("No category '" + Permission.GROUP_CATEGORY_KEY + "' available"); } return userGroups; } /** checks if the user just exchanges one allocatable or removes one. The user needs admin-access on the * removed allocatable and the newly inserted allocatable */ private boolean canExchange(User user,Entity entity,Entity original) { if ( Appointment.TYPE.equals( entity.getRaplaType() )) { return ((Appointment) entity).matches( (Appointment) original ); } if ( Reservation.TYPE.equals( entity.getRaplaType() )) { Reservation newReservation = (Reservation) entity; Reservation oldReservation = (Reservation) original; // We only need to check the length because we compare the appointments above. if ( newReservation.getAppointments().length != oldReservation.getAppointments().length ) { return false; } List<Allocatable> oldAllocatables = Arrays.asList(oldReservation.getAllocatables()); List<Allocatable> newAllocatables = Arrays.asList(newReservation.getAllocatables()); List<Allocatable> inserted = new ArrayList<Allocatable>(newAllocatables); List<Allocatable> removed = new ArrayList<Allocatable>(oldAllocatables); List<Allocatable> overlap = new ArrayList<Allocatable>(oldAllocatables); inserted.removeAll( oldAllocatables ); removed.removeAll( newAllocatables ); overlap.retainAll( inserted ); if ( inserted.size() == 0 && removed.size() == 0) { return false; } // he must have admin rights on all inserted resources Iterator<Allocatable> it = inserted.iterator(); while (it.hasNext()) { if (!canAllocateForOthers(it.next(),user)) { return false; } } // and he must have admin rights on all the removed resources it = removed.iterator(); while (it.hasNext()) { if (!canAllocateForOthers(it.next(),user)) { return false; } } // He can't change appointments, only exchange allocatables he has admin-priviliges for it = overlap.iterator(); while (it.hasNext()) { Allocatable all = it.next(); Appointment[] r1 = newReservation.getRestriction( all ); Appointment[] r2 = oldReservation.getRestriction( all ); boolean changed = false; if ( r1.length != r2.length ) { changed = true; } else { for ( int i=0; i< r1.length; i++ ) { if ( !r1[i].matches(r2[i]) ) { changed = true; } } } if ( changed && !canAllocateForOthers( all, user )) { return false; } } return true; } return false; } /** for Thierry, we can make this configurable in the next version */ private boolean canAllocateForOthers(Allocatable allocatable, User user) { // only admins, current behaviour return allocatable.canModify( user); // everyone who can allocate the resource anytime //return allocatable.canAllocate( user, null, null, operator.today()); // everyone //return true; } private void checkConflictsAllowed(User user, Allocatable allocatable, Conflict[] conflictsBefore, Conflict[] conflictsAfter) throws RaplaSecurityException { int nConflictsBefore = 0; int nConflictsAfter = 0; if ( allocatable.canCreateConflicts( user ) ) { return; } if ( conflictsBefore != null ) { for ( int i = 0; i < conflictsBefore.length; i++ ) { if ( conflictsBefore[i].getAllocatable().equals ( allocatable ) ) { nConflictsBefore ++; } } } for ( int i = 0; i < conflictsAfter.length; i++ ) { if ( conflictsAfter[i].getAllocatable().equals ( allocatable ) ) { nConflictsAfter ++; } } if ( nConflictsAfter > nConflictsBefore ) { String all = allocatable.getName( i18n.getLocale() ); throw new RaplaSecurityException( i18n.format("warning.no_conflict_permission", all ) ); } } private void checkPermissions( User user, Reservation r, Reservation original, Allocatable[] allocatables ) throws RaplaSecurityException { ClientFacade facade; try { facade = context.lookup(ClientFacade.class); } catch (RaplaContextException e) { throw new RaplaSecurityException(e.getMessage(), e); } Conflict[] conflictsBefore = null; Conflict[] conflictsAfter = null; try { conflictsAfter = facade.getConflicts( r ); if ( original != null ) { conflictsBefore = facade.getConflicts( original ); } } catch ( RaplaException ex ) { throw new RaplaSecurityException(" Can't check permissions due to:" + ex.getMessage(), ex ); } Appointment[] appointments = r.getAppointments(); // ceck if the user has the permisson to add allocations in the given time for (int i = 0; i < allocatables.length; i++ ) { Allocatable allocatable = allocatables[i]; checkConflictsAllowed( user, allocatable, conflictsBefore, conflictsAfter ); for (int j = 0; j < appointments.length; j++ ) { Appointment appointment = appointments[j]; Date today = operator.today(); if ( r.hasAllocated( allocatable, appointment ) && !FacadeImpl.hasPermissionToAllocate( user, appointment, allocatable, original,today ) ) { String all = allocatable.getName( i18n.getLocale() ); String app = appointmentFormater.getSummary( appointment ); String error = i18n.format("warning.no_reserve_permission" ,all ,app); throw new RaplaSecurityException( error ); } } } if (original == null ) return; Date today = operator.today(); // 1. calculate the deleted assignments from allocatable to appointments // 2. check if they were allowed to change in the specified time appointments = original.getAppointments(); allocatables = original.getAllocatables(); for (int i = 0; i < allocatables.length; i++ ) { Allocatable allocatable = allocatables[i]; for (int j = 0; j < appointments.length; j++ ) { Appointment appointment = appointments[j]; if ( original.hasAllocated( allocatable, appointment ) && !r.hasAllocated( allocatable, appointment ) ) { Date start = appointment.getStart(); Date end = appointment.getMaxEnd(); if ( !allocatable.canAllocate( user, start, end, today ) ) { String all = allocatable.getName( i18n.getLocale() ); String app = appointmentFormater.getSummary( appointment ); String error = i18n.format("warning.no_reserve_permission" ,all ,app); throw new RaplaSecurityException( error ); } } } } } public void checkRead(User user,Entity entity) throws RaplaSecurityException, RaplaException { RaplaType<?> raplaType = entity.getRaplaType(); if ( raplaType == Allocatable.TYPE) { Allocatable allocatable = (Allocatable) entity; if ( !allocatable.canReadOnlyInformation( user)) { throw new RaplaSecurityException(i18n.format("error.read_not_allowed",user, allocatable.getName( null))); } } if ( raplaType == Preferences.TYPE) { Ownable ownable = (Preferences) entity; User owner = ownable.getOwner(); if ( user != null && !user.isAdmin() && (owner == null || !user.equals( owner))) { throw new RaplaSecurityException(i18n.format("error.read_not_allowed", user, entity)); } } } public void checkWritePermissions(User user, PreferencePatch patch) throws RaplaSecurityException { String ownerId = patch.getUserId(); if ( user != null && !user.isAdmin() && (ownerId == null || !user.getId().equals( ownerId))) { throw new RaplaSecurityException("User " + user + " can't modify preferences " + ownerId); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.server.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TimeZone; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import org.rapla.RaplaMainContainer; import org.rapla.components.util.DateTools; import org.rapla.components.util.ParseDateException; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.components.util.TimeInterval; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.Category; import org.rapla.entities.DependencyException; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Permission; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.internal.AppointmentImpl; import org.rapla.entities.domain.internal.ReservationImpl; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.DynamicTypeImpl; import org.rapla.entities.storage.EntityReferencer; import org.rapla.facade.ClientFacade; import org.rapla.facade.Conflict; import org.rapla.facade.RaplaComponent; import org.rapla.facade.internal.ConflictImpl; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.framework.TypedComponentRole; import org.rapla.framework.logger.Logger; import org.rapla.plugin.mail.MailPlugin; import org.rapla.plugin.mail.server.MailInterface; import org.rapla.rest.gwtjsonrpc.common.FutureResult; import org.rapla.rest.gwtjsonrpc.common.ResultImpl; import org.rapla.rest.gwtjsonrpc.common.VoidResult; import org.rapla.server.AuthenticationStore; import org.rapla.server.RemoteMethodFactory; import org.rapla.server.RemoteSession; import org.rapla.storage.CachableStorageOperator; import org.rapla.storage.PreferencePatch; import org.rapla.storage.RaplaNewVersionException; import org.rapla.storage.RaplaSecurityException; import org.rapla.storage.StorageOperator; import org.rapla.storage.StorageUpdateListener; import org.rapla.storage.UpdateEvent; import org.rapla.storage.UpdateResult; import org.rapla.storage.UpdateResult.Change; import org.rapla.storage.UpdateResult.Remove; import org.rapla.storage.dbrm.RemoteConnectionInfo; import org.rapla.storage.dbrm.RemoteStorage; import org.rapla.storage.impl.EntityStore; /** Provides an adapter for each client-session to their shared storage operator * Handles security and synchronizing aspects. */ public class RemoteStorageImpl implements RemoteMethodFactory<RemoteStorage>, StorageUpdateListener, Disposable { CachableStorageOperator operator; protected SecurityManager security; RaplaContext context; int cleanupPointVersion = 0; protected AuthenticationStore authenticationStore; Logger logger; ClientFacade facade; RaplaLocale raplaLocale; //private Map<String,Long> updateMap = new HashMap<String,Long>(); //private Map<String,Long> removeMap = new HashMap<String,Long>(); public RemoteStorageImpl(RaplaContext context) throws RaplaException { this.context = context; this.logger = context.lookup( Logger.class); facade = context.lookup( ClientFacade.class); raplaLocale = context.lookup( RaplaLocale.class); operator = (CachableStorageOperator)facade.getOperator(); operator.addStorageUpdateListener( this); security = context.lookup( SecurityManager.class); if ( context.has( AuthenticationStore.class ) ) { try { authenticationStore = context.lookup( AuthenticationStore.class ); getLogger().info( "Using AuthenticationStore " + authenticationStore.getName() ); } catch ( RaplaException ex) { getLogger().error( "Can't initialize configured authentication store. Using default authentication." , ex); } } Long repositoryVersion = operator.getCurrentTimestamp().getTime(); // Invalidate all clients for ( User user:operator.getUsers()) { String userId = user.getId(); needResourceRefresh.put( userId, repositoryVersion); needConflictRefresh.put( userId, repositoryVersion); } synchronized (invalidateMap) { invalidateMap.put( repositoryVersion, new TimeInterval( null, null)); } } public Logger getLogger() { return logger; } public I18nBundle getI18n() throws RaplaException { return context.lookup(RaplaComponent.RAPLA_RESOURCES); } static UpdateEvent createTransactionSafeUpdateEvent( UpdateResult updateResult ) { User user = updateResult.getUser(); UpdateEvent saveEvent = new UpdateEvent(); if ( user != null ) { saveEvent.setUserId( user.getId() ); } { Iterator<UpdateResult.Add> it = updateResult.getOperations( UpdateResult.Add.class ); while ( it.hasNext() ) { Entity newEntity = (Entity) ( it.next() ).getNew(); saveEvent.putStore( newEntity ); } } { Iterator<UpdateResult.Change> it = updateResult.getOperations( UpdateResult.Change.class ); while ( it.hasNext() ) { Entity newEntity = (Entity) ( it.next() ).getNew(); saveEvent.putStore( newEntity ); } } { Iterator<UpdateResult.Remove> it = updateResult.getOperations( UpdateResult.Remove.class ); while ( it.hasNext() ) { Entity removeEntity = (Entity) (it.next() ).getCurrent(); saveEvent.putRemove( removeEntity ); } } return saveEvent; } private Map<String,Long> needConflictRefresh = new ConcurrentHashMap<String,Long>(); private Map<String,Long> needResourceRefresh = new ConcurrentHashMap<String,Long>(); private SortedMap<Long, TimeInterval> invalidateMap = Collections.synchronizedSortedMap(new TreeMap<Long,TimeInterval>()); // Implementation of StorageUpdateListener public void objectsUpdated( UpdateResult evt ) { long repositoryVersion = operator.getCurrentTimestamp().getTime(); // notify the client for changes TimeInterval invalidateInterval = evt.calulateInvalidateInterval(); if ( invalidateInterval != null) { long oneHourAgo = repositoryVersion - DateTools.MILLISECONDS_PER_HOUR; // clear the entries that are older than one hour and replace them with a clear_all // that is set one hour in the past, to refresh all clients that have not been connected in the past hour on the next connect synchronized ( invalidateMap) { SortedMap<Long, TimeInterval> headMap = invalidateMap.headMap( oneHourAgo); if ( !headMap.isEmpty()) { Set<Long> toDelete = new TreeSet<Long>(headMap.keySet()); for ( Long key:toDelete) { invalidateMap.remove(key); } invalidateMap.put(oneHourAgo, new TimeInterval( null, null)); } invalidateMap.put(repositoryVersion, invalidateInterval); } } UpdateEvent safeResultEvent = createTransactionSafeUpdateEvent( evt ); if ( getLogger().isDebugEnabled() ) getLogger().debug( "Storage was modified. Calling notify." ); boolean addAllUsersToConflictRefresh = false; for ( Iterator<Entity>it = safeResultEvent.getStoreObjects().iterator(); it.hasNext(); ) { Entity obj = it.next(); if (!isTransferedToClient(obj)) { continue; } if ( obj instanceof Conflict) { addAllUsersToConflictRefresh = true; } if ( obj instanceof DynamicType) { addAllUsersToConflictRefresh = true; } // RaplaType<?> raplaType = obj.getRaplaType(); // if (raplaType == Conflict.TYPE) // { // String id = obj.getId(); // updateMap.remove( id ); // removeMap.remove( id ); // updateMap.put( id, new Long( repositoryVersion ) ); // } } // now we check if a the resources have changed in a way that a user needs to refresh all resources. That is the case, when // someone changes the permissions on one or more resource and that affects the visibility of that resource to a user, // so its either pushed to the client or removed from it. Set<Permission> invalidatePermissions = new HashSet<Permission>(); boolean addAllUsersToResourceRefresh = false; { Iterator<Remove> operations = evt.getOperations(UpdateResult.Remove.class); while ( operations.hasNext()) { Remove operation = operations.next(); Entity obj = operation.getCurrent(); if ( obj instanceof User) { String userId = obj.getId(); needConflictRefresh.remove( userId); needResourceRefresh.remove( userId); } if (!isTransferedToClient(obj)) { continue; } if ( obj instanceof Allocatable) { Permission[] oldPermissions = ((Allocatable)obj).getPermissions(); invalidatePermissions.addAll( Arrays.asList( oldPermissions)); } if ( obj instanceof DynamicType) { addAllUsersToResourceRefresh = true; addAllUsersToConflictRefresh = true; } if ( obj instanceof Conflict) { addAllUsersToConflictRefresh = true; } // if ( obj instanceof Conflict) // { // String id = obj.getId(); // updateMap.remove( id ); // removeMap.remove( id ); // removeMap.put( id, new Long( repositoryVersion ) ); // } } } if (addAllUsersToResourceRefresh || addAllUsersToConflictRefresh) { invalidateAll(repositoryVersion, addAllUsersToResourceRefresh,addAllUsersToConflictRefresh); } else { invalidate(evt, repositoryVersion, invalidatePermissions); } } private void invalidateAll(long repositoryVersion, boolean resourceRefreh, boolean conflictRefresh) { Collection<String> allUserIds = new ArrayList<String>(); try { Collection<User> allUsers = operator.getUsers(); for ( User user:allUsers) { String id = user.getId(); allUserIds.add( id); } } catch (RaplaException ex) { getLogger().error( ex.getMessage(), ex); // we stay with the old list. // keySet iterator from concurrent hashmap is thread safe Iterator<String> iterator = needResourceRefresh.keySet().iterator(); while ( iterator.hasNext()) { String id = iterator.next(); allUserIds.add( id); } } for ( String userId :allUserIds) { if (resourceRefreh ) { needResourceRefresh.put( userId, repositoryVersion); } if ( conflictRefresh) { needConflictRefresh.put( userId, repositoryVersion); } } } private void invalidate(UpdateResult evt, long repositoryVersion, Set<Permission> invalidatePermissions) { Collection<User> allUsers; try { allUsers = operator.getUsers(); } catch (RaplaException e) { // we need to invalidate all on an exception invalidateAll(repositoryVersion, true, true); return; } // We also check if a permission on a reservation has changed, so that it is no longer or new in the conflict list of a certain user. // If that is the case we trigger an invalidate of the conflicts for a user Set<User> usersResourceRefresh = new HashSet<User>(); Category superCategory = operator.getSuperCategory(); Set<Category> groupsConflictRefresh = new HashSet<Category>(); Set<User> usersConflictRefresh = new HashSet<User>(); Iterator<Change> operations = evt.getOperations(UpdateResult.Change.class); while ( operations.hasNext()) { Change operation = operations.next(); Entity newObject = operation.getNew(); if ( newObject.getRaplaType().is( Allocatable.TYPE) && isTransferedToClient(newObject)) { Allocatable newAlloc = (Allocatable) newObject; Allocatable current = (Allocatable) operation.getOld(); Permission[] oldPermissions = current.getPermissions(); Permission[] newPermissions = newAlloc.getPermissions(); // we leave this condition for a faster equals check if (oldPermissions.length == newPermissions.length) { for (int i=0;i<oldPermissions.length;i++) { Permission oldPermission = oldPermissions[i]; Permission newPermission = newPermissions[i]; if (!oldPermission.equals(newPermission)) { invalidatePermissions.add( oldPermission); invalidatePermissions.add( newPermission); } } } else { HashSet<Permission> newSet = new HashSet<Permission>(Arrays.asList(newPermissions)); HashSet<Permission> oldSet = new HashSet<Permission>(Arrays.asList(oldPermissions)); { HashSet<Permission> changed = new HashSet<Permission>( newSet); changed.removeAll( oldSet); invalidatePermissions.addAll(changed); } { HashSet<Permission> changed = new HashSet<Permission>(oldSet); changed.removeAll( newSet); invalidatePermissions.addAll(changed); } } } if ( newObject.getRaplaType().is( User.TYPE)) { User newUser = (User) newObject; User oldUser = (User) operation.getOld(); HashSet<Category> newGroups = new HashSet<Category>(Arrays.asList(newUser.getGroups())); HashSet<Category> oldGroups = new HashSet<Category>(Arrays.asList(oldUser.getGroups())); if ( !newGroups.equals( oldGroups) || newUser.isAdmin() != oldUser.isAdmin()) { usersResourceRefresh.add( newUser); } } if ( newObject.getRaplaType().is( Reservation.TYPE)) { Reservation newEvent = (Reservation) newObject; Reservation oldEvent = (Reservation) operation.getOld(); User newOwner = newEvent.getOwner(); User oldOwner = oldEvent.getOwner(); if ( newOwner != null && oldOwner != null && (newOwner.equals( oldOwner)) ) { usersConflictRefresh.add( newOwner); usersConflictRefresh.add( oldOwner); } Collection<Category> newGroup = RaplaComponent.getPermissionGroups( newEvent, superCategory, ReservationImpl.PERMISSION_MODIFY, false); Collection<Category> oldGroup = RaplaComponent.getPermissionGroups( oldEvent, superCategory, ReservationImpl.PERMISSION_MODIFY, false); if (newGroup != null && (oldGroup == null || !oldGroup.equals(newGroup))) { groupsConflictRefresh.addAll( newGroup); } if (oldGroup != null && (newGroup == null || !oldGroup.equals(newGroup))) { groupsConflictRefresh.addAll( oldGroup); } } } boolean addAllUsersToConflictRefresh = groupsConflictRefresh.contains( superCategory); Set<Category> groupsResourceRefrsesh = new HashSet<Category>(); if ( !invalidatePermissions.isEmpty() || ! addAllUsersToConflictRefresh || !! groupsConflictRefresh.isEmpty()) { for ( Permission permission:invalidatePermissions) { User user = permission.getUser(); if ( user != null) { usersResourceRefresh.add( user); } Category group = permission.getGroup(); if ( group != null) { groupsResourceRefrsesh.add( group); } if ( user == null && group == null) { usersResourceRefresh.addAll( allUsers); break; } } for ( User user:allUsers) { if ( usersResourceRefresh.contains( user)) { continue; } for (Category group:user.getGroups()) { if ( groupsResourceRefrsesh.contains( group)) { usersResourceRefresh.add( user); break; } if ( addAllUsersToConflictRefresh || groupsConflictRefresh.contains( group)) { usersConflictRefresh.add( user); break; } } } } for ( User user:usersResourceRefresh) { String userId = user.getId(); needResourceRefresh.put( userId, repositoryVersion); needConflictRefresh.put( userId, repositoryVersion); } for ( User user:usersConflictRefresh) { String userId = user.getId(); needConflictRefresh.put( userId, repositoryVersion); } } private boolean isTransferedToClient(RaplaObject obj) { RaplaType<?> raplaType = obj.getRaplaType(); if (raplaType == Appointment.TYPE || raplaType == Reservation.TYPE) { return false; } if ( obj instanceof DynamicType) { if (!DynamicTypeImpl.isTransferedToClient(( DynamicType) obj)) { return false; } } if ( obj instanceof Classifiable) { if (!DynamicTypeImpl.isTransferedToClient(( Classifiable) obj)) { return false; } } return true; } @Override public void dispose() { } public void updateError(RaplaException ex) { } public void storageDisconnected(String disconnectionMessage) { } public Class<RemoteStorage> getServiceClass() { return RemoteStorage.class; } @Override public RemoteStorage createService(final RemoteSession session) { return new RemoteStorage() { @Override public void setConnectInfo(RemoteConnectionInfo info) { // do nothing here } public FutureResult<UpdateEvent> getResources() { try { checkAuthentified(); User user = getSessionUser(); getLogger().debug ("A RemoteServer wants to get all resource-objects."); Date serverTime = operator.getCurrentTimestamp(); Collection<Entity> visibleEntities = operator.getVisibleEntities(user); UpdateEvent evt = new UpdateEvent(); evt.setUserId( user.getId()); for ( Entity entity: visibleEntities) { if ( isTransferedToClient(entity)) { if ( entity instanceof Preferences) { Preferences preferences = (Preferences)entity; User owner = preferences.getOwner(); if ( owner == null && !user.isAdmin()) { entity = removeServerOnlyPreferences(preferences); } } evt.putStore(entity); } } evt.setLastValidated(serverTime); return new ResultImpl<UpdateEvent>( evt); } catch (RaplaException ex ) { return new ResultImpl<UpdateEvent>(ex ); } } private Preferences removeServerOnlyPreferences(Preferences preferences) { Preferences clone = preferences.clone(); { //removeOldPluginConfigs(preferences, clone); for (String role :((PreferencesImpl)preferences).getPreferenceEntries()) { if ( role.contains(".server.")) { clone.removeEntry(role); } } } return clone; } // private void removeOldPluginConfigs(Preferences preferences, Preferences clone) { // List<String> adminOnlyPreferences = new ArrayList<String>(); // adminOnlyPreferences.add(MailPlugin.class.getCanonicalName()); // adminOnlyPreferences.add(JNDIPlugin.class.getCanonicalName()); // // RaplaConfiguration entry = preferences.getEntry(RaplaComponent.PLUGIN_CONFIG); // if ( entry != null) // { // RaplaConfiguration newConfig = entry.clone(); // for ( String className: adminOnlyPreferences) // { // DefaultConfiguration pluginConfig = (DefaultConfiguration)newConfig.find("class", className); // if ( pluginConfig != null) // { // newConfig.removeChild( pluginConfig); // boolean enabled = pluginConfig.getAttributeAsBoolean("enabled", false); // RaplaConfiguration newPluginConfig = new RaplaConfiguration(pluginConfig.getName()); // newPluginConfig.setAttribute("enabled", enabled); // newPluginConfig.setAttribute("class", className); // newConfig.addChild( newPluginConfig); // } // } // clone.putEntry(RaplaComponent.PLUGIN_CONFIG, newConfig); // } // } public FutureResult<List<String>> getTemplateNames() { try { checkAuthentified(); Collection<String> templateNames = operator.getTemplateNames(); return new ResultImpl<List<String>>(new ArrayList<String>(templateNames)); } catch (RaplaException ex ) { return new ResultImpl<List<String>>(ex); } } public FutureResult<UpdateEvent> getEntityRecursive(String... ids) { //synchronized (operator.getLock()) try { checkAuthentified(); Date repositoryVersion = operator.getCurrentTimestamp(); User sessionUser = getSessionUser(); ArrayList<Entity>completeList = new ArrayList<Entity>(); for ( String id:ids) { Entity entity = operator.resolve(id); if ( entity instanceof Classifiable) { if (!DynamicTypeImpl.isTransferedToClient(( Classifiable) entity)) { throw new RaplaSecurityException("Entity for id " + id + " is not transferable to the client"); } } if ( entity instanceof DynamicType) { if (!DynamicTypeImpl.isTransferedToClient(( DynamicType) entity)) { throw new RaplaSecurityException("Entity for id " + id + " is not transferable to the client"); } } if ( entity instanceof Reservation) { entity = checkAndMakeReservationsAnonymous(sessionUser, entity); } if ( entity instanceof Preferences) { entity = removeServerOnlyPreferences((Preferences)entity); } security.checkRead(sessionUser, entity); completeList.add( entity ); getLogger().debug("Get entity " + entity); } UpdateEvent evt = new UpdateEvent(); evt.setLastValidated(repositoryVersion); for ( Entity entity: completeList) { evt.putStore(entity); } return new ResultImpl<UpdateEvent>( evt); } catch (RaplaException ex ) { return new ResultImpl<UpdateEvent>(ex ); } } public FutureResult<List<ReservationImpl>> getReservations(String[] allocatableIds,Date start,Date end,Map<String,String> annotationQuery) { getLogger().debug ("A RemoteServer wants to reservations from ." + start + " to " + end); try { checkAuthentified(); User sessionUser = getSessionUser(); User user = null; // Reservations and appointments ArrayList<ReservationImpl> list = new ArrayList<ReservationImpl>(); List<Allocatable> allocatables = new ArrayList<Allocatable>(); if ( allocatableIds != null ) { for ( String id:allocatableIds) { Allocatable allocatable = operator.resolve(id, Allocatable.class); security.checkRead(sessionUser, allocatable); allocatables.add( allocatable); } } ClassificationFilter[] classificationFilters = null; Collection<Reservation> reservations = operator.getReservations(user,allocatables, start, end, classificationFilters,annotationQuery ); for (Reservation res:reservations) { if (isAllocatablesVisible(sessionUser, res)) { ReservationImpl safeRes = checkAndMakeReservationsAnonymous(sessionUser, res); list.add( safeRes); } } // for (Reservation r:reservations) // { // Iterable<Entity>subEntities = ((ParentEntity)r).getSubEntities(); // for (Entity appointments:subEntities) // { // completeList.add( appointments); // } getLogger().debug("Get reservations " + start + " " + end + ": " + reservations.size() + "," + list.size()); return new ResultImpl<List<ReservationImpl>>(list); } catch (RaplaException ex ) { return new ResultImpl<List<ReservationImpl>>(ex ); } } private ReservationImpl checkAndMakeReservationsAnonymous(User sessionUser,Entity entity) { ReservationImpl reservation =(ReservationImpl) entity; boolean canReadFromOthers = facade.canReadReservationsFromOthers(sessionUser); boolean reservationVisible = RaplaComponent.canRead( reservation, sessionUser, canReadFromOthers); // check if the user is allowed to read the reservation info if ( !reservationVisible ) { ReservationImpl clone = reservation.clone(); // we can safely change the reservation info here because we cloned it in transaction safe before DynamicType anonymousReservationType = operator.getDynamicType( StorageOperator.ANONYMOUSEVENT_TYPE); clone.setClassification( anonymousReservationType.newClassification()); clone.setReadOnly(); return clone; } else { return reservation; } } protected boolean isAllocatablesVisible(User sessionUser, Reservation res) { User owner = res.getOwner(); if (sessionUser.isAdmin() || owner == null || owner.equals(sessionUser) ) { return true; } for (Allocatable allocatable: res.getAllocatables()) { if (allocatable.canRead(sessionUser)) { return true; } } return true; } public FutureResult<VoidResult> restartServer() { try { checkAuthentified(); if (!getSessionUser().isAdmin()) throw new RaplaSecurityException("Only admins can restart the server"); context.lookup(ShutdownService.class).shutdown( true); return ResultImpl.VOID; } catch (RaplaException ex ) { return new ResultImpl<VoidResult>(ex ); } } public FutureResult<UpdateEvent> dispatch(UpdateEvent event) { try { Date currentTimestamp = operator.getCurrentTimestamp(); Date lastSynced = event.getLastValidated(); if ( lastSynced == null) { throw new RaplaException("client sync time is missing"); } if ( lastSynced.after( currentTimestamp)) { long diff = lastSynced.getTime() - currentTimestamp.getTime(); getLogger().warn("Timestamp of client " +diff + " ms after server "); lastSynced = currentTimestamp; } // LocalCache cache = operator.getCache(); // UpdateEvent event = createUpdateEvent( context,xml, cache ); User sessionUser = getSessionUser(); getLogger().info("Dispatching change for user " + sessionUser); if ( sessionUser != null) { event.setUserId(sessionUser.getId()); } dispatch_( event); getLogger().info("Change for user " + sessionUser + " dispatched."); UpdateEvent result = createUpdateEvent( lastSynced ); return new ResultImpl<UpdateEvent>(result ); } catch (RaplaException ex ) { return new ResultImpl<UpdateEvent>(ex ); } } public FutureResult<String> canChangePassword() { try { checkAuthentified(); Boolean result = operator.canChangePassword(); return new ResultImpl<String>( result.toString()); } catch (RaplaException ex ) { return new ResultImpl<String>(ex ); } } public FutureResult<VoidResult> changePassword(String username ,String oldPassword ,String newPassword ) { try { checkAuthentified(); User sessionUser = getSessionUser(); if (!sessionUser.isAdmin()) { if ( authenticationStore != null ) { throw new RaplaSecurityException("Rapla can't change your password. Authentication handled by ldap plugin." ); } operator.authenticate(username,new String(oldPassword)); } User user = operator.getUser(username); operator.changePassword(user,oldPassword.toCharArray(),newPassword.toCharArray()); return ResultImpl.VOID; } catch (RaplaException ex ) { return new ResultImpl<VoidResult>(ex ); } } public FutureResult<VoidResult> changeName(String username,String newTitle, String newSurename, String newLastname) { try { User changingUser = getSessionUser(); User user = operator.getUser(username); if ( changingUser.isAdmin() || user.equals( changingUser) ) { operator.changeName(user,newTitle,newSurename,newLastname); } else { throw new RaplaSecurityException("Not allowed to change email from other users"); } return ResultImpl.VOID; } catch (RaplaException ex ) { return new ResultImpl<VoidResult>(ex ); } } public FutureResult<VoidResult> changeEmail(String username,String newEmail) { try { User changingUser = getSessionUser(); User user = operator.getUser(username); if ( changingUser.isAdmin() || user.equals( changingUser) ) { operator.changeEmail(user,newEmail); } else { throw new RaplaSecurityException("Not allowed to change email from other users"); } return ResultImpl.VOID; } catch (RaplaException ex ) { return new ResultImpl<VoidResult>(ex ); } } public FutureResult<VoidResult> confirmEmail(String username,String newEmail) { try { User changingUser = getSessionUser(); User user = operator.getUser(username); if ( changingUser.isAdmin() || user.equals( changingUser) ) { String subject = getString("security_code"); Preferences prefs = operator.getPreferences( null, true ); String mailbody = "" + getString("send_code_mail_body_1") + user.getUsername() + ",\n\n" + getString("send_code_mail_body_2") + "\n\n" + getString("security_code") + Math.abs(user.getEmail().hashCode()) + "\n\n" + getString("send_code_mail_body_3") + "\n\n" + "-----------------------------------------------------------------------------------" + "\n\n" + getString("send_code_mail_body_4") + prefs.getEntryAsString(RaplaMainContainer.TITLE, getString("rapla.title")) + " " + getString("send_code_mail_body_5"); final MailInterface mail = context.lookup(MailInterface.class); final String defaultSender = prefs.getEntryAsString( MailPlugin.DEFAULT_SENDER_ENTRY, ""); mail.sendMail( defaultSender, newEmail,subject, "" + mailbody); } else { throw new RaplaSecurityException("Not allowed to change email from other users"); } return ResultImpl.VOID; } catch (RaplaException ex ) { return new ResultImpl<VoidResult>(ex ); } } private String getString(String key) throws RaplaException { return getI18n().getString( key); } public FutureResult<List<String>> createIdentifier(String type, int count) { try { RaplaType raplaType = RaplaType.find( type); checkAuthentified(); //User user = getSessionUser(); //check if authenified String[] result =operator.createIdentifier(raplaType, count); return new ResultImpl<List<String>>( Arrays.asList(result)); } catch (RaplaException ex ) { return new ResultImpl<List<String>>(ex ); } } public FutureResult<UpdateEvent> refresh(String lastSyncedTime) { try { checkAuthentified(); Date clientRepoVersion = SerializableDateTimeFormat.INSTANCE.parseTimestamp(lastSyncedTime); UpdateEvent event = createUpdateEvent(clientRepoVersion); return new ResultImpl<UpdateEvent>( event); } catch (RaplaException ex ) { return new ResultImpl<UpdateEvent>(ex ); } catch (ParseDateException e) { return new ResultImpl<UpdateEvent>(new RaplaException( e.getMessage()) ); } } public Logger getLogger() { return session.getLogger(); } private void checkAuthentified() throws RaplaSecurityException { if (!session.isAuthentified()) { throw new RaplaSecurityException(RemoteStorage.USER_WAS_NOT_AUTHENTIFIED); } } private User getSessionUser() throws RaplaException { return session.getUser(); } private void dispatch_(UpdateEvent evt) throws RaplaException { checkAuthentified(); try { User user; if ( evt.getUserId() != null) { user = operator.resolve(evt.getUserId(), User.class); } else { user = session.getUser(); } Collection<Entity>storeObjects = evt.getStoreObjects(); EntityStore store = new EntityStore(operator, operator.getSuperCategory()); store.addAll(storeObjects); for (EntityReferencer references:evt.getEntityReferences( true)) { references.setResolver( store); } for (Entity entity:storeObjects) { security.checkWritePermissions(user,entity); } List<PreferencePatch> preferencePatches = evt.getPreferencePatches(); for (PreferencePatch patch:preferencePatches) { security.checkWritePermissions(user,patch); } Collection<Entity>removeObjects = evt.getRemoveObjects(); for ( Entity entity:removeObjects) { security.checkWritePermissions(user,entity); } if (this.getLogger().isDebugEnabled()) this.getLogger().debug("Dispatching changes to " + operator.getClass()); operator.dispatch(evt); if (this.getLogger().isDebugEnabled()) this.getLogger().debug("Changes dispatched returning result."); } catch (DependencyException ex) { throw ex; } catch (RaplaNewVersionException ex) { throw ex; } catch (RaplaSecurityException ex) { this.getLogger().warn(ex.getMessage()); throw ex; } catch (RaplaException ex) { this.getLogger().error(ex.getMessage(),ex); throw ex; } catch (Exception ex) { this.getLogger().error(ex.getMessage(),ex); throw new RaplaException(ex); } catch (Error ex) { this.getLogger().error(ex.getMessage(),ex); throw ex; } } private UpdateEvent createUpdateEvent( Date lastSynced ) throws RaplaException { Date currentTimestamp = operator.getCurrentTimestamp(); if ( lastSynced.after( currentTimestamp)) { long diff = lastSynced.getTime() - currentTimestamp.getTime(); getLogger().warn("Timestamp of client " +diff + " ms after server "); lastSynced = currentTimestamp; } User user = getSessionUser(); UpdateEvent safeResultEvent = new UpdateEvent(); safeResultEvent.setLastValidated( currentTimestamp); TimeZone systemTimeZone = operator.getTimeZone(); int timezoneOffset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, currentTimestamp.getTime()); safeResultEvent.setTimezoneOffset( timezoneOffset ); //if ( lastSynced.before( currentTimestamp )) { String userId = user.getId(); TimeInterval invalidateInterval; { Long lastVersion = needConflictRefresh.get( userId ); if ( lastVersion != null && lastVersion > lastSynced.getTime()) { invalidateInterval = new TimeInterval( null, null); } else { invalidateInterval = getInvalidateInterval( lastSynced.getTime() ); } } boolean resourceRefresh; { Long lastVersion = needResourceRefresh.get( userId); resourceRefresh = ( lastVersion != null && lastVersion > lastSynced.getTime()); } safeResultEvent.setNeedResourcesRefresh( resourceRefresh); safeResultEvent.setInvalidateInterval( invalidateInterval); } if ( !safeResultEvent.isNeedResourcesRefresh()) { Collection<Entity> updatedEntities = operator.getUpdatedEntities(lastSynced ); for ( Entity obj: updatedEntities ) { processClientReadable( user, safeResultEvent, obj, false); } } return safeResultEvent; } protected void processClientReadable(User user,UpdateEvent safeResultEvent, Entity obj, boolean remove) { if ( !isTransferedToClient(obj)) { return; } boolean clientStore = true; if (user != null ) { // we don't transmit preferences for other users if ( obj instanceof Preferences) { Preferences preferences = (Preferences) obj; User owner = preferences.getOwner(); if ( owner != null && !owner.equals( user)) { clientStore = false; } else { obj = removeServerOnlyPreferences(preferences); } } else if ( obj instanceof Allocatable) { Allocatable alloc = (Allocatable) obj; if ( !alloc.canReadOnlyInformation(user)) { clientStore = false; } } else if ( obj instanceof Conflict) { Conflict conflict = (Conflict) obj; if ( !ConflictImpl.canModify( conflict, user, operator) ) { clientStore = false; } } } if ( clientStore) { if ( remove) { safeResultEvent.putRemove( obj ); } else { safeResultEvent.putStore( obj ); } } } // protected List<Entity>getDependentObjects( // Appointment appointment) { // List<Entity> toAdd = new ArrayList<Entity>(); // toAdd.add( (Entity)appointment); // @SuppressWarnings("unchecked") // ReservationImpl reservation = (ReservationImpl)appointment.getReservation(); // { // toAdd.add(reservation); // String id = reservation.getId(); // Entity inCache; // try { // inCache = operator.resolve( id); // } catch (EntityNotFoundException e) { // inCache = null; // } // if ( inCache != null && ((RefEntity)inCache).getVersion() > reservation.getVersion()) // { // getLogger().error("Try to send an older version of the reservation to the client " + reservation.getName( raplaLocale.getLocale())); // } // for (Entity ref:reservation.getSubEntities()) // { // toAdd.add( ref ); // } // } // if (!toAdd.contains(appointment)) // { // getLogger().error(appointment.toString() + " at " + raplaLocale.formatDate(appointment.getStart()) + " does refer to reservation " + reservation.getName( raplaLocale.getLocale()) + " but the reservation does not refer back."); // } // return toAdd; // } // private TimeInterval getInvalidateInterval( long clientRepositoryVersion) { TimeInterval interval = null; synchronized (invalidateMap) { for ( TimeInterval current:invalidateMap.tailMap( clientRepositoryVersion).values()) { if ( current != null) { interval = current.union( interval); } } return interval; } } public FutureResult<List<ConflictImpl>> getConflicts() { try { Set<Entity>completeList = new HashSet<Entity> (); User sessionUser = getSessionUser(); Collection<Conflict> conflicts = operator.getConflicts( sessionUser); List<ConflictImpl> result = new ArrayList<ConflictImpl>(); for ( Conflict conflict:conflicts) { result.add( (ConflictImpl) conflict); Entity conflictRef = (Entity)conflict; completeList.add(conflictRef); //completeList.addAll( getDependentObjects(conflict.getAppointment1())); //completeList.addAll( getDependentObjects(conflict.getAppointment2())); } //EntityList list = createList( completeList, repositoryVersion ); return new ResultImpl<List<ConflictImpl>>( result); } catch (RaplaException ex ) { return new ResultImpl<List<ConflictImpl>>(ex ); } } @Override public FutureResult<Date> getNextAllocatableDate( String[] allocatableIds, AppointmentImpl appointment,String[] reservationIds, Integer worktimestartMinutes, Integer worktimeendMinutes, Integer[] excludedDays, Integer rowsPerHour) { try { checkAuthentified(); List<Allocatable> allocatables = resolveAllocatables(allocatableIds); Collection<Reservation> ignoreList = resolveReservations(reservationIds); Date result = operator.getNextAllocatableDate(allocatables, appointment, ignoreList, worktimestartMinutes, worktimeendMinutes, excludedDays, rowsPerHour); return new ResultImpl<Date>( result); } catch (RaplaException ex ) { return new ResultImpl<Date>(ex ); } } @Override public FutureResult<BindingMap> getFirstAllocatableBindings(String[] allocatableIds, List<AppointmentImpl> appointments, String[] reservationIds) { try { checkAuthentified(); //Integer[][] result = new Integer[allocatableIds.length][]; List<Allocatable> allocatables = resolveAllocatables(allocatableIds); Collection<Reservation> ignoreList = resolveReservations(reservationIds); List<Appointment> asList = cast(appointments); Map<Allocatable, Collection<Appointment>> bindings = operator.getFirstAllocatableBindings(allocatables, asList, ignoreList); Map<String,List<String>> result = new LinkedHashMap<String,List<String>>(); for ( Allocatable alloc:bindings.keySet()) { Collection<Appointment> apps = bindings.get(alloc); if ( apps == null) { apps = Collections.emptyList(); } ArrayList<String> indexArray = new ArrayList<String>(apps.size()); for ( Appointment app: apps) { for (Appointment app2:appointments) { if (app2.equals(app )) { indexArray.add ( app.getId()); } } } result.put(alloc.getId(), indexArray); } return new ResultImpl<BindingMap>(new BindingMap(result)); } catch (RaplaException ex ) { return new ResultImpl<BindingMap>(ex); } } private List<Appointment> cast(List<AppointmentImpl> appointments) { List<Appointment> result = new ArrayList<Appointment>(appointments.size()); for (Appointment app:appointments) { result.add( app); } return result; } public FutureResult<List<ReservationImpl>> getAllAllocatableBindings(String[] allocatableIds, List<AppointmentImpl> appointments, String[] reservationIds) { try { Set<ReservationImpl> result = new HashSet<ReservationImpl>(); checkAuthentified(); List<Allocatable> allocatables = resolveAllocatables(allocatableIds); Collection<Reservation> ignoreList = resolveReservations(reservationIds); List<Appointment> asList = cast(appointments); Map<Allocatable, Map<Appointment, Collection<Appointment>>> bindings = operator.getAllAllocatableBindings(allocatables, asList, ignoreList); for (Allocatable alloc:bindings.keySet()) { Map<Appointment,Collection<Appointment>> appointmentBindings = bindings.get( alloc); for (Appointment app: appointmentBindings.keySet()) { Collection<Appointment> bound = appointmentBindings.get( app); if ( bound != null) { for ( Appointment appointment: bound) { ReservationImpl reservation = (ReservationImpl) appointment.getReservation(); if ( reservation != null) { result.add( reservation); } } } } } return new ResultImpl<List<ReservationImpl>>(new ArrayList<ReservationImpl>(result)); } catch (RaplaException ex) { return new ResultImpl<List<ReservationImpl>>(ex); } } private List<Allocatable> resolveAllocatables(String[] allocatableIds) throws RaplaException,EntityNotFoundException, RaplaSecurityException { List<Allocatable> allocatables = new ArrayList<Allocatable>(); User sessionUser = getSessionUser(); for ( String id:allocatableIds) { Allocatable entity = operator.resolve(id, Allocatable.class); allocatables.add( entity); security.checkRead(sessionUser, entity); } return allocatables; } private Collection<Reservation> resolveReservations(String[] ignoreList) { Set<Reservation> ignoreConflictsWith = new HashSet<Reservation>(); for (String reservationId: ignoreList) { try { Reservation entity = operator.resolve(reservationId, Reservation.class); ignoreConflictsWith.add( entity); } catch (EntityNotFoundException ex) { // Do nothing reservation not found and assumed new } } return ignoreConflictsWith; } // public void logEntityNotFound(String logMessage,String... referencedIds) // { // StringBuilder buf = new StringBuilder(); // buf.append("{"); // for (String id: referencedIds) // { // buf.append("{ id="); // if ( id != null) // { // buf.append(id.toString()); // buf.append(": "); // Entity refEntity = operator.tryResolve(id); // if ( refEntity != null ) // { // buf.append( refEntity.toString()); // } // else // { // buf.append("NOT FOUND"); // } // } // else // { // buf.append( "is null"); // } // // buf.append("}, "); // } // buf.append("}"); // getLogger().error("EntityNotFoundFoundExceptionOnClient "+ logMessage + " " + buf.toString()); // //return ResultImpl.VOID; // } }; } static public void convertToNewPluginConfig(RaplaContext context, String className, TypedComponentRole<RaplaConfiguration> newConfKey) throws RaplaContextException { ClientFacade facade = context.lookup( ClientFacade.class); // { // RaplaConfiguration entry = facade.getPreferences().getEntry(RaplaComponent.PLUGIN_CONFIG,null); // if ( entry == null ) // { // return; // } // DefaultConfiguration pluginConfig = (DefaultConfiguration)entry.find("class", className); // if ( pluginConfig == null) // { // return; // } // // only class and getEnabled // // } try { PreferencesImpl clone = (PreferencesImpl) facade.edit( facade.getSystemPreferences()); RaplaConfiguration entry = clone.getEntry(RaplaComponent.PLUGIN_CONFIG,null); RaplaConfiguration newPluginConfigEntry = entry.clone(); DefaultConfiguration pluginConfig = (DefaultConfiguration)newPluginConfigEntry.find("class", className); // we split the config entry in the plugin config and the new config entry; if ( pluginConfig != null) { context.lookup(Logger.class).info("Converting plugin conf " + className + " to preference entry " + newConfKey); newPluginConfigEntry.removeChild( pluginConfig); boolean enabled = pluginConfig.getAttributeAsBoolean("enabled", false); RaplaConfiguration newPluginConfig = new RaplaConfiguration(pluginConfig.getName()); newPluginConfig.setAttribute("enabled", enabled); newPluginConfig.setAttribute("class", className); newPluginConfigEntry.addChild( newPluginConfig); RaplaConfiguration newConfigEntry = new RaplaConfiguration( pluginConfig); newConfigEntry.setAttribute("enabled", null); newConfigEntry.setAttribute("class", null); clone.putEntry(newConfKey, newConfigEntry); clone.putEntry(RaplaComponent.PLUGIN_CONFIG, newPluginConfigEntry); facade.store( clone); } } catch (RaplaException ex) { if ( ex instanceof RaplaContextException) { throw (RaplaContextException)ex; } throw new RaplaContextException(ex.getMessage(),ex); } } }
Java
package org.rapla.server.internal; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Collection; import java.util.Collections; import org.apache.commons.codec.binary.Base64; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; import org.rapla.server.RaplaKeyStorage; public class RaplaKeyStorageImpl extends RaplaComponent implements RaplaKeyStorage { //private static final String USER_KEYSTORE = "keystore"; private static final String ASYMMETRIC_ALGO = "RSA"; private static final TypedComponentRole<String> PUBLIC_KEY = new TypedComponentRole<String>("org.rapla.crypto.publicKey"); private static final TypedComponentRole<String> APIKEY = new TypedComponentRole<String>("org.rapla.crypto.server.refreshToken"); private static final TypedComponentRole<String> PRIVATE_KEY = new TypedComponentRole<String>("org.rapla.crypto.server.privateKey"); private String rootKey; private String rootPublicKey; private Base64 base64; CryptoHandler cryptoHandler; public String getRootKeyBase64() { return rootKey; } /** * Initializes the Url encryption plugin. * Checks whether an encryption key exists or not, reads an existing one from the configuration file * or generates a new one. The decryption and encryption ciphers are also initialized here. * * @param context * @param config * @throws RaplaException */ public RaplaKeyStorageImpl(RaplaContext context) throws RaplaException { super(context); byte[] linebreake = {}; // we use an url safe encoder for the keys this.base64 = new Base64(64, linebreake, true); rootKey = getQuery().getSystemPreferences().getEntryAsString(PRIVATE_KEY, null); rootPublicKey = getQuery().getSystemPreferences().getEntryAsString(PUBLIC_KEY, null); if ( rootKey == null || rootPublicKey == null) { try { generateRootKeyStorage(); } catch (NoSuchAlgorithmException e) { throw new RaplaException( e.getMessage()); } } cryptoHandler = new CryptoHandler( context,rootKey); } public LoginInfo decrypt(String encrypted) throws RaplaException { LoginInfo loginInfo = new LoginInfo(); String decrypt = cryptoHandler.decrypt(encrypted); String[] split = decrypt.split(":",2); loginInfo.login = split[0]; loginInfo.secret = split[1]; return loginInfo; } @Override public void storeAPIKey(User user,String clientId, String newApiKey) throws RaplaException { Preferences preferences = getQuery().getPreferences(user); Preferences edit = getModification().edit( preferences); edit.putEntry(APIKEY, newApiKey); getModification().store( edit); } @Override public Collection<String> getAPIKeys(User user) throws RaplaException { String annotation = getQuery().getPreferences(user).getEntryAsString(APIKEY, null); if (annotation == null) { return Collections.emptyList(); } Collection<String> keyList = Collections.singleton( annotation ); return keyList; } @Override public void removeAPIKey(User user, String apikey) throws RaplaException { throw new UnsupportedOperationException(); // Allocatable key= getAllocatable(user); // if ( key != null ) // { // Collection<String> keyList = parseList(key.getAnnotation(APIKEY)); // if (keyList == null || !keyList.contains(apikey)) // { // return; // } // key = getModification().edit( key ); // keyList.remove( apikey); // if ( keyList.size() > 0) // { // key.setAnnotation(APIKEY, null); // } // else // { // key.setAnnotation(APIKEY, serialize(keyList)); // } // // remove when no more annotations set // if (key.getAnnotationKeys().length == 0) // { // getModification().remove( key); // } // else // { // getModification().store( key); // } // } } @Override public LoginInfo getSecrets(User user, TypedComponentRole<String> tagName) throws RaplaException { String annotation = getQuery().getPreferences(user).getEntryAsString(tagName, null); if ( annotation == null) { return null; } return decrypt(annotation); } @Override public void storeLoginInfo(User user,TypedComponentRole<String> tagName,String login,String secret) throws RaplaException { Preferences preferences = getQuery().getPreferences(user); Preferences edit = getModification().edit( preferences); String loginPair = login +":" + secret; String encrypted = cryptoHandler.encrypt( loginPair); edit.putEntry(tagName, encrypted); getModification().store( edit); } // public Allocatable getOrCreate(User user) throws RaplaException { // Allocatable key= getAllocatable(user); // if ( key == null) // { // DynamicType dynamicType = getQuery().getDynamicType( StorageOperator.CRYPTO_TYPE); // Classification classification = dynamicType.newClassification(); // key = getModification().newAllocatable(classification, null ); // if ( user != null) // { // key.setOwner( user); // } // key.setClassification( classification); // } // else // { // key = getModification().edit( key); // } // return key; // } public void removeLoginInfo(User user, TypedComponentRole<String> tagName) throws RaplaException { Preferences preferences = getQuery().getPreferences(user); Preferences edit = getModification().edit( preferences); edit.putEntry(tagName, null); getModification().store( edit); } // // Allocatable getAllocatable(User user) throws RaplaException // { // Collection<Allocatable> store = getAllocatables(); // if ( store.size() > 0) // { // for ( Allocatable all:store) // { // User owner = all.getOwner(); // if ( user == null) // { // if ( owner == null ) // { // return all; // } // } // else // { // if ( owner != null && user.equals( owner)) // { // return all; // } // } // } // } // return null; // } // public Collection<Allocatable> getAllocatables() throws RaplaException // { // StorageOperator operator = getClientFacade().getOperator(); // DynamicType dynamicType = operator.getDynamicType( StorageOperator.CRYPTO_TYPE); // ClassificationFilter newClassificationFilter = dynamicType.newClassificationFilter(); // ClassificationFilter[] array = newClassificationFilter.toArray(); // Collection<Allocatable> store = operator.getAllocatables( array); // return store; // } private void generateRootKeyStorage() throws NoSuchAlgorithmException, RaplaException { getLogger().info("Generating new root key. This can take a while."); //Classification newClassification = dynamicType.newClassification(); //newClassification.setValue("name", "root"); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance( ASYMMETRIC_ALGO ); keyPairGen.initialize( 2048); KeyPair keyPair = keyPairGen.generateKeyPair(); getLogger().info("Root key generated"); PrivateKey privateKeyObj = keyPair.getPrivate(); this.rootKey = base64.encodeAsString(privateKeyObj.getEncoded()); PublicKey publicKeyObj = keyPair.getPublic(); this.rootPublicKey =base64.encodeAsString(publicKeyObj.getEncoded()); Preferences systemPreferences = getQuery().getSystemPreferences(); Preferences edit = getModification().edit( systemPreferences); edit.putEntry(PRIVATE_KEY, rootKey); edit.putEntry(PUBLIC_KEY, rootPublicKey); getModification().store( edit); } }
Java
package org.rapla.server.internal; import java.io.BufferedWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.LinkedHashMap; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.rapla.RaplaMainContainer; import org.rapla.facade.RaplaComponent; import org.rapla.framework.Configuration; import org.rapla.framework.RaplaContext; import org.rapla.servletpages.RaplaPageGenerator; public class RaplaConfPageGenerator extends RaplaComponent implements RaplaPageGenerator{ public RaplaConfPageGenerator(RaplaContext context) { super(context); } public void generatePage( ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws IOException { java.io.PrintWriter out = response.getWriter(); response.setContentType("application/xml;charset=utf-8"); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<rapla-config>"); Configuration conf = getService(RaplaMainContainer.RAPLA_MAIN_CONFIGURATION); //<!-- Use this to customize the rapla resources //<default-bundle>org.rapla.MyResources</default-bundle> //--> Configuration localeConf = conf.getChild("locale"); if ( localeConf != null) { printConfiguration( out, localeConf); } Configuration[] bundles = conf.getChildren("default-bundle"); for ( Configuration bundle: bundles) { printConfiguration( out, bundle); } String remoteId = null; Configuration[] clients = conf.getChildren("rapla-client"); for ( Configuration client: clients) { if ( client.getAttribute("id", "").equals( "client")) { remoteId = client.getChild("facade").getChild("store").getValue( "remote"); printConfiguration( out, client); break; } } if ( remoteId != null) { Configuration[] storages = conf.getChildren("remote-storage"); for ( Configuration storage: storages) { if ( storage.getAttribute("id", "").equals( remoteId)) { printConfiguration( out, storage); } } } else { // Config not found use default out.println("<rapla-client id=\"client\">"); out.println(" <facade id=\"facade\">"); out.println(" <store>remote</store>"); out.println(" </facade>"); out.println("</rapla-client>"); out.println(" "); out.println("<remote-storage id=\"remote\">"); out.println(" <server>${download-url}</server>"); out.println("</remote-storage>"); } out.println(" "); out.println("</rapla-config>"); out.close(); } private void printConfiguration(PrintWriter out, Configuration conf) throws IOException { ConfigurationWriter configurationWriter = new ConfigurationWriter(); BufferedWriter writer = new BufferedWriter( out); configurationWriter.setWriter( writer); configurationWriter.printConfiguration( conf); writer.flush(); } class ConfigurationWriter extends org.rapla.components.util.xml.XMLWriter { private void printConfiguration(Configuration element) throws IOException { LinkedHashMap<String, String> attr = new LinkedHashMap<String, String>(); String[] attrNames = element.getAttributeNames(); if( null != attrNames ) { for( int i = 0; i < attrNames.length; i++ ) { String key = attrNames[ i ]; String value = element.getAttribute( attrNames[ i ], "" ); attr.put(key,value); } } String qName = element.getName(); openTag(qName); att(attr); Configuration[] children = element.getChildren(); if (children.length > 0) { closeTag(); for( int i = 0; i < children.length; i++ ) { printConfiguration( children[ i ] ); } closeElement(qName); } else { String value = element.getValue( null ); if (null == value) { closeElementTag(); } else { closeTagOnLine(); print(value); closeElementOnLine(qName); println(); } } } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.server.internal; public interface ShutdownService { void shutdown( boolean restart); }
Java
package org.rapla.server.internal; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.Key; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class CryptoHandler extends RaplaComponent { String syncEncryptionAlg = "AES/ECB/PKCS5Padding"; private Cipher encryptionCipher; private Cipher decryptionCipher; private Base64 base64; private static final String ENCODING = "UTF-8"; public CryptoHandler( RaplaContext context,String pepper) throws RaplaException { super( context); try { byte[] linebreake = {}; this.base64 = new Base64(64, linebreake, true); initializeCiphers( pepper); } catch (Exception e) { throw new RaplaException( e.getMessage(),e); } } private void initializeCiphers(String pepper) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException { byte[] key = pepper.getBytes("UTF-8"); MessageDigest sha = MessageDigest.getInstance("SHA-1"); key = sha.digest(key); key = Arrays.copyOf(key, 16); // use only first 128 bit Key specKey = new SecretKeySpec(key, "AES"); this.encryptionCipher = Cipher.getInstance(syncEncryptionAlg); this.encryptionCipher.init(Cipher.ENCRYPT_MODE, specKey); this.decryptionCipher = Cipher.getInstance(syncEncryptionAlg); this.decryptionCipher.init(Cipher.DECRYPT_MODE, specKey); } public String encrypt(String toBeEncrypted) throws RaplaException{ try { return base64.encodeToString(this.encryptionCipher.doFinal(toBeEncrypted.getBytes(ENCODING))); } catch (Exception e) { throw new RaplaException(e.getMessage(), e); } } public String decrypt(String toBeDecryptedBase64) throws RaplaException{ try { return new String(this.decryptionCipher.doFinal(base64.decode(toBeDecryptedBase64.getBytes(ENCODING)))); } catch (Exception e) { throw new RaplaException(e.getMessage(), e); } } }
Java
package org.rapla.server; import org.rapla.framework.RaplaContextException; public interface RemoteMethodFactory<T> { public T createService(final RemoteSession remoteSession) throws RaplaContextException; }
Java
package org.rapla.server; import java.util.Date; import java.util.TimeZone; public interface TimeZoneConverter { /** returns the timezone configured via main options, this is per default the system timezon. This timezone is used for ical/exchange import/export If Rapla will support timezones in the future, than this will be the default timezone for all times. Now its only used on import and export. It works as with system time above. 10:00am GMT+0 is converted to 10:00am of the configured timezone on export and on import all times are converted to GMT+0. @see TimeZoneConverter#toRaplaTime(TimeZone, long) */ TimeZone getImportExportTimeZone(); long fromRaplaTime(TimeZone timeZone,long raplaTime); long toRaplaTime(TimeZone timeZone,long time); Date fromRaplaTime(TimeZone timeZone,Date raplaTime); /** * converts a common Date object into a Date object that * assumes that the user (being in the given timezone) is in the * UTC-timezone by adding the offset between UTC and the given timezone. * * <pre> * Example: If you pass the Date "2013 Jan 15 11:00:00 UTC" * and the TimeZone "GMT+1", this method will return a Date * "2013 Jan 15 12:00:00 UTC" which is effectivly 11:00:00 GMT+1 * </pre> * * @param timeZone * the orgin timezone * @param time * the Date object in the passed timezone * @see fromRaplaTime */ Date toRaplaTime(TimeZone timeZone,Date time); }
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.server; import org.rapla.entities.Category; import org.rapla.entities.User; import org.rapla.framework.RaplaException; public interface AuthenticationStore { /** returns, if the user can be authenticated. */ boolean authenticate(String username, String password) throws RaplaException; /** returns the name of the store */ String getName(); /** Initializes a user entity with the values provided by the authentication store. * @return <code>true</code> if the new user-object attributes (such as email, name, or groups) differ from the values stored before the method was executed, <code>false</code> otherwise. */ boolean initUser( User user, String username, String password, Category groupRootCategory) throws RaplaException; }
Java
package org.rapla.server; import java.util.Collection; import org.rapla.entities.User; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; public interface RaplaKeyStorage { public String getRootKeyBase64(); public LoginInfo getSecrets(User user, TypedComponentRole<String> tagName) throws RaplaException; public void storeLoginInfo(User user,TypedComponentRole<String> tagName,String login,String secret) throws RaplaException; public void removeLoginInfo(User user, TypedComponentRole<String> tagName) throws RaplaException; public void storeAPIKey(User user,String clientId,String apiKey) throws RaplaException; public Collection<String> getAPIKeys(User user) throws RaplaException; public void removeAPIKey(User user,String key) throws RaplaException; public class LoginInfo { public String login; public String secret; } }
Java
package org.rapla.server; import javax.servlet.http.HttpServletRequest; import org.rapla.entities.User; import org.rapla.framework.Configuration; import org.rapla.framework.Container; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaException; import org.rapla.servletpages.RaplaPageGenerator; public interface ServerServiceContainer extends Container { <T> void addRemoteMethodFactory( Class<T> service, Class<? extends RemoteMethodFactory<T>> factory); <T> void addRemoteMethodFactory( Class<T> service, Class<? extends RemoteMethodFactory<T>> factory, Configuration config); /** * You can add arbitrary serlvet pages to your rapla webapp. * * Example that adds a page with the name "my-page-name" and the class * "org.rapla.plugin.myplugin.MyPageGenerator". You can call this page with <code>rapla?page=my-page-name</code> * <p/> * In the provideService Method of your PluginDescriptor do the following <pre> container.addContainerProvidedComponent( RaplaExtensionPoints.SERVLET_PAGE_EXTENSION, "org.rapla.plugin.myplugin.MyPageGenerator", "my-page-name", config); </pre> *@see org.rapla.servletpages.RaplaPageGenerator */ <T extends RaplaPageGenerator> void addWebpage(String pagename, Class<T> pageClass); <T extends RaplaPageGenerator> void addWebpage(String pagename, Class<T> pageClass, Configuration config); /** @return null when the server doesn't have the webpage * @throws RaplaContextException */ RaplaPageGenerator getWebpage(String page); public User getUser(HttpServletRequest request) throws RaplaException; <T> T createWebservice(Class<T> role,HttpServletRequest request ) throws RaplaException; boolean hasWebservice(String interfaceName); }
Java
package org.rapla.server; /** * a class implementing server extension is started automatically when the server is up and running and connected to a data store. * */ public interface ServerExtension { }
Java
package org.rapla.server; import org.rapla.framework.TypedComponentRole; import org.rapla.gui.SwingViewFactory; import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory; import org.rapla.servletpages.RaplaMenuGenerator; import org.rapla.servletpages.ServletRequestPreprocessor; /** Constant Pool of basic extension points of the Rapla server. * You can add your extension in the provideService Method of your PluginDescriptor * <pre> * container.addContainerProvidedComponent( REPLACE_WITH_EXTENSION_POINT_NAME, REPLACE_WITH_CLASS_IMPLEMENTING_EXTENSION, config); * </pre> * @see org.rapla.framework.PluginDescriptor */ public class RaplaServerExtensionPoints { /** add your own views to Rapla, by providing a org.rapla.gui.ViewFactory * @see SwingViewFactory * */ public static final Class<HTMLViewFactory> HTML_CALENDAR_VIEW_EXTENSION = HTMLViewFactory.class; /** A server extension is started automaticaly when the server is up and running and connected to a data store. A class added as service doesn't need to implement a specific interface and is instanciated automaticaly after server start. You can add a RaplaContext parameter to your constructor to get access to the services of rapla. * */ public static final Class<ServerExtension> SERVER_EXTENSION = ServerExtension.class; /** you can add servlet pre processer to manipulate request and response before standard processing is * done by rapla */ public static final Class<ServletRequestPreprocessor> SERVLET_REQUEST_RESPONSE_PREPROCESSING_POINT = ServletRequestPreprocessor.class; /** you can add your own entries on the index page Just add a HTMLMenuEntry to the list @see RaplaMenuGenerator * */ public static final TypedComponentRole<RaplaMenuGenerator> HTML_MAIN_MENU_EXTENSION_POINT = new TypedComponentRole<RaplaMenuGenerator>("org.rapla.servletpages"); //public final static TypedComponentRole<List<PluginDescriptor<ServerServiceContainer>>> SERVER_PLUGIN_LIST = new TypedComponentRole<List<PluginDescriptor<ServerServiceContainer>>>("server-plugin-list"); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.server; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.naming.Context; import javax.naming.InitialContext; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.rapla.ConnectInfo; import org.rapla.RaplaMainContainer; import org.rapla.RaplaStartupEnvironment; import org.rapla.client.ClientService; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientListenerAdapter; import org.rapla.components.util.IOUtil; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.User; import org.rapla.facade.RaplaComponent; import org.rapla.framework.Container; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaDefaultContext; import org.rapla.framework.RaplaException; import org.rapla.framework.ServiceListCreator; import org.rapla.framework.StartupEnvironment; import org.rapla.framework.internal.ContainerImpl; import org.rapla.framework.internal.RaplaJDKLoggingAdapter; import org.rapla.framework.logger.Logger; import org.rapla.server.internal.ServerServiceImpl; import org.rapla.server.internal.ShutdownService; import org.rapla.servletpages.RaplaPageGenerator; import org.rapla.servletpages.ServletRequestPreprocessor; import org.rapla.storage.ImportExportManager; import org.rapla.storage.StorageOperator; import org.rapla.storage.dbrm.RemoteMethodStub; import org.rapla.storage.dbrm.WrongRaplaVersionException; public class MainServlet extends HttpServlet { private static final String RAPLA_RPC_PATH = "/rapla/rpc/"; private static final long serialVersionUID = 1L; /** The default config filename is raplaserver.xconf*/ private ContainerImpl raplaContainer; public final static String DEFAULT_CONFIG_NAME = "raplaserver.xconf"; private Logger logger = null; private String startupMode =null; private String startupUser = null; private Integer port; private String contextPath; private String env_rapladatasource; private String env_raplafile; private Object env_rapladb; private Object env_raplamail; private Boolean env_development; private String downloadUrl; private String serverVersion; private ServerServiceImpl server; private Runnable shutdownCommand; private Collection<ServletRequestPreprocessor> processors; private ReadWriteLock restartLock = new ReentrantReadWriteLock(); // the following variables are only for non server startup private Semaphore guiMutex = new Semaphore(1); private ConnectInfo reconnect; private URL getConfigFile(String entryName, String defaultName) throws ServletException,IOException { String configName = getServletConfig().getInitParameter(entryName); if (configName == null) configName = defaultName; if (configName == null) throw new ServletException("Must specify " + entryName + " entry in web.xml !"); String realPath = getServletConfig().getServletContext().getRealPath("/WEB-INF/" + configName); if (realPath != null) { File configFile = new File(realPath); if (configFile.exists()) { URL configURL = configFile.toURI().toURL(); return configURL; } } URL configURL = getClass().getResource("/raplaserver.xconf"); if ( configURL == null) { String message = "ERROR: Config file not found " + configName; throw new ServletException(message); } else { return configURL; } } /** * Initializes Servlet and creates a <code>RaplaMainContainer</code> instance * * @exception ServletException if an error occurs */ synchronized public void init() throws ServletException { getLogger().info("Init RaplaServlet"); Collection<String> instanceCounter = null; String selectedContextPath = null; Context env; try { Context initContext = new InitialContext(); Context envContext = (Context)initContext.lookup("java:comp"); env = (Context)envContext.lookup("env"); } catch (Exception e) { env = null; getLogger().warn("No JNDI Enivronment found under java:comp or java:/comp"); } if ( env != null) { env_rapladatasource = lookupEnvString(env, "rapladatasource", true); env_raplafile = lookupEnvString(env,"raplafile", true); env_rapladb = lookupResource(env, "jdbc/rapladb", true); getLogger().info("Passed JNDI Environment rapladatasource=" + env_rapladatasource + " env_rapladb="+env_rapladb + " env_raplafile="+ env_raplafile); if ( env_rapladatasource == null || env_rapladatasource.trim().length() == 0 || env_rapladatasource.startsWith( "${")) { if ( env_rapladb != null) { env_rapladatasource = "rapladb"; } else if ( env_raplafile != null) { env_rapladatasource = "raplafile"; } else { getLogger().warn("Neither file nor database setup configured."); } } env_raplamail = lookupResource(env, "mail/Session", false); startupMode = lookupEnvString(env,"rapla_startup_mode", false); env_development = (Boolean) lookupEnvVariable(env, "rapla_development", false); @SuppressWarnings("unchecked") Collection<String> instanceCounterLookup = (Collection<String>) lookup(env,"rapla_instance_counter", false); instanceCounter = instanceCounterLookup; selectedContextPath = lookupEnvString(env,"rapla_startup_context", false); startupUser = lookupEnvString( env, "rapla_startup_user", false); shutdownCommand = (Runnable) lookup(env,"rapla_shutdown_command", false); port = (Integer) lookup(env,"rapla_startup_port", false); downloadUrl = (String) lookup(env,"rapla_download_url", false); } if ( startupMode == null) { startupMode = "server"; } contextPath = getServletContext().getContextPath(); if ( !contextPath.startsWith("/")) { contextPath = "/" + contextPath; } // don't startup server if contextPath is not selected if ( selectedContextPath != null) { if( !contextPath.equals(selectedContextPath)) return; } else if ( instanceCounter != null) { instanceCounter.add( contextPath); if ( instanceCounter.size() > 1) { String msg = ("Ignoring webapp ["+ contextPath +"]. Multiple context found in jetty container " + instanceCounter + " You can specify one via -Dorg.rapla.context=REPLACE_WITH_CONTEXT"); getLogger().error(msg); return; } } startServer(startupMode); if ( startupMode.equals("standalone") || startupMode.equals("client")) { try { guiMutex.acquire(); } catch (InterruptedException e) { } try { startGUI(startupMode); } catch (Exception ex) { exit(); throw new ServletException(ex); } } } private Object lookupResource(Context env, String lookupname, boolean log) { String newLookupname = getServletContext().getInitParameter(lookupname); if (newLookupname != null && newLookupname.length() > 0) { lookupname = newLookupname; } Object result = lookup(env,lookupname, log); return result; } private String lookupEnvString(Context env, String lookupname, boolean log) { Object result = lookupEnvVariable(env, lookupname, log); return (String) result; } private Object lookupEnvVariable(Context env, String lookupname, boolean log) { String newEnvname = getServletContext().getInitParameter(lookupname); if ( newEnvname != null) { getLogger().info("Using contextparam for " + lookupname + ": " + newEnvname); } if (newEnvname != null && newEnvname.length() > 0 ) { return newEnvname; } else { Object result = lookup(env,lookupname, log); return result; } } private Object lookup(Context env, String string, boolean warn) { try { Object result = env.lookup( string); if ( result == null && warn) { getLogger().warn("JNDI Entry "+ string + " not found"); } return result; } catch (Exception e) { if ( warn ) { getLogger().warn("JNDI Entry "+ string + " not found"); } return null; } } private void startGUI(final String startupMode) throws ServletException { ConnectInfo connectInfo = null; if (startupMode.equals("standalone")) { try { String username = startupUser; if ( username == null ) { username = getFirstAdmin(); } if ( username != null) { connectInfo = new ConnectInfo(username, "".toCharArray()); } } catch (RaplaException ex) { getLogger().error(ex.getMessage(),ex); } } startGUI( startupMode, connectInfo); if ( startupMode.equals("standalone") || startupMode.equals("client")) { try { guiMutex.acquire(); while ( reconnect != null ) { raplaContainer.dispose(); try { if ( startupMode.equals("client")) { initContainer(startupMode); } else if ( startupMode.equals("standalone")) { startServer("standalone"); } if ( startupMode.equals("standalone") && reconnect.getUsername() == null) { String username = getFirstAdmin(); if ( username != null) { reconnect= new ConnectInfo(username, "".toCharArray()); } } startGUI(startupMode, reconnect); guiMutex.acquire(); } catch (Exception ex) { getLogger().error("Error restarting client",ex); exit(); return; } } } catch (InterruptedException e) { } } } protected String getFirstAdmin() throws RaplaContextException, RaplaException { String username = null; StorageOperator operator = server.getContext().lookup(StorageOperator.class); for (User u:operator.getUsers()) { if ( u.isAdmin()) { username = u.getUsername(); break; } } return username; } public void startGUI( final String startupMode, ConnectInfo connectInfo) throws ServletException { try { if ( startupMode.equals("standalone") || startupMode.equals("client")) { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( ClassLoader.getSystemClassLoader()); ClientServiceContainer clientContainer = raplaContainer.getContext().lookup(ClientServiceContainer.class ); ClientService client = clientContainer.getContext().lookup( ClientService.class); client.addRaplaClientListener(new RaplaClientListenerAdapter() { public void clientClosed(ConnectInfo reconnect) { MainServlet.this.reconnect = reconnect; if ( reconnect != null) { guiMutex.release(); } else { exit(); } } public void clientAborted() { exit(); } }); clientContainer.start(connectInfo); } finally { Thread.currentThread().setContextClassLoader( contextClassLoader); } } else if (!startupMode.equals("server")) { exit(); } } catch( Exception e ) { getLogger().error("Could not start server", e); if ( raplaContainer != null) { raplaContainer.dispose(); } throw new ServletException( "Error during initialization see logs for details: " + e.getMessage(), e ); } // log("Rapla Servlet started"); } protected void startServer(final String startupMode) throws ServletException { try { initContainer(startupMode); if ( startupMode.equals("import")) { ImportExportManager manager = raplaContainer.getContext().lookup(ImportExportManager.class); manager.doImport(); exit(); } else if (startupMode.equals("export")) { ImportExportManager manager = raplaContainer.getContext().lookup(ImportExportManager.class); manager.doExport(); exit(); } else if ( startupMode.equals("server") || startupMode.equals("standalone") ) { String hint = serverContainerHint != null ? serverContainerHint :"*"; // Start the server via lookup // We start the standalone server before the client to prevent jndi lookup failures server = (ServerServiceImpl) raplaContainer.lookup( ServerServiceContainer.class, hint); processors = server.lookupServicesFor(RaplaServerExtensionPoints.SERVLET_REQUEST_RESPONSE_PREPROCESSING_POINT); final Logger logger = getLogger(); logger.info("Rapla server started"); if ( startupMode.equals("server")) { // if setShutdownService(startupMode); } else { raplaContainer.addContainerProvidedComponentInstance(RemoteMethodStub.class, server); } } } catch( Exception e ) { getLogger().error(e.getMessage(), e); String message = "Error during initialization see logs for details: " + e.getMessage(); if ( raplaContainer != null) { raplaContainer.dispose(); } if ( shutdownCommand != null) { shutdownCommand.run(); } throw new ServletException( message,e); } } protected void setShutdownService(final String startupMode) { server.setShutdownService( new ShutdownService() { public void shutdown(final boolean restart) { Lock writeLock; try { try { RaplaComponent.unlock( restartLock.readLock()); } catch (IllegalMonitorStateException ex) { getLogger().error("Error unlocking read for restart " + ex.getMessage()); } writeLock = RaplaComponent.lock( restartLock.writeLock(), 60); } catch (RaplaException ex) { getLogger().error("Can't restart server " + ex.getMessage()); return; } try { //acquired = requestCount.tryAcquire(maxRequests -1,10, TimeUnit.SECONDS); logger.info( "Stopping Server"); stopServer(); if ( restart) { try { logger.info( "Restarting Server"); MainServlet.this.startServer(startupMode); } catch (Exception e) { logger.error( "Error while restarting Server", e ); } } } finally { RaplaComponent.unlock(writeLock); } } }); } protected void initContainer(String startupMode) throws ServletException, IOException, MalformedURLException, Exception, RaplaContextException { URL configURL = getConfigFile("config-file",DEFAULT_CONFIG_NAME); //URL logConfigURL = getConfigFile("log-config-file","raplaserver.xlog").toURI().toURL(); RaplaStartupEnvironment env = new RaplaStartupEnvironment(); env.setStartupMode( StartupEnvironment.CONSOLE); env.setConfigURL( configURL ); if ( startupMode.equals( "client")) { if ( port != null) { String url = downloadUrl; if ( url == null) { url = "http://localhost:" + port+ contextPath; if (! url.endsWith("/")) { url += "/"; } } env.setDownloadURL( new URL(url)); } } // env.setContextRootURL( contextRootURL ); //env.setLogConfigURL( logConfigURL ); RaplaDefaultContext context = new RaplaDefaultContext(); if ( env_rapladatasource != null) { context.put(RaplaMainContainer.ENV_RAPLADATASOURCE, env_rapladatasource); } if ( env_raplafile != null) { context.put(RaplaMainContainer.ENV_RAPLAFILE, env_raplafile); } if ( env_rapladb != null) { context.put(RaplaMainContainer.ENV_RAPLADB, env_rapladb); } if ( env_raplamail != null) { context.put(RaplaMainContainer.ENV_RAPLAMAIL, env_raplamail); getLogger().info("Configured mail service via JNDI"); } if ( env_development != null && env_development) { context.put(RaplaMainContainer.ENV_DEVELOPMENT, Boolean.TRUE); } raplaContainer = new RaplaMainContainer( env, context ); logger = raplaContainer.getContext().lookup(Logger.class); if ( env_development != null && env_development) { addDevelopmentWarFolders(); } serverVersion = raplaContainer.getContext().lookup(RaplaComponent.RAPLA_RESOURCES).getString("rapla.version"); } // add the war folders of the plugins to jetty resource handler so that the files inside the war // folders can be served from within jetty, even when they are not located in the same folder. // The method will search the class path for plugin classes and then add the look for a war folder entry in the file hierarchy // so a plugin allways needs a plugin class for this to work @SuppressWarnings("unchecked") private void addDevelopmentWarFolders() { Thread currentThread = Thread.currentThread(); ClassLoader classLoader = currentThread.getContextClassLoader(); ClassLoader parent = null; try { Collection<File> webappFolders = ServiceListCreator.findPluginWebappfolders(logger); if ( webappFolders.size() < 1) { return; } parent = classLoader.getParent(); if ( parent != null) { currentThread.setContextClassLoader( parent); } // first we need to access the necessary classes via reflection (are all loaded, because webapplication is already initialized) final Class WebAppClassLoaderC = Class.forName("org.eclipse.jetty.webapp.WebAppClassLoader",false, parent); final Class WebAppContextC = Class.forName("org.eclipse.jetty.webapp.WebAppContext",false, parent); final Class ResourceCollectionC = Class.forName("org.eclipse.jetty.util.resource.ResourceCollection",false, parent); final Class FileResourceC = Class.forName("org.eclipse.jetty.util.resource.FileResource",false, parent); final Object webappContext = WebAppClassLoaderC.getMethod("getContext").invoke(classLoader); if (webappContext == null) { return; } final Object baseResource = WebAppContextC.getMethod("getBaseResource").invoke( webappContext); if ( baseResource != null && ResourceCollectionC.isInstance( baseResource) ) { //Resource[] resources = ((ResourceCollection) baseResource).getResources(); final Object[] resources = (Object[])ResourceCollectionC.getMethod("getResources").invoke( baseResource); Set list = new HashSet( Arrays.asList( resources)); for (File folder:webappFolders) { Object fileResource = FileResourceC.getConstructor( URL.class).newInstance( folder.toURI().toURL()); if ( !list.contains( fileResource)) { list.add( fileResource); getLogger().info("Adding " + fileResource + " to webapp folder"); } } Object[] array = list.toArray( resources); //((ResourceCollection) baseResource).setResources( array); ResourceCollectionC.getMethod("setResources", resources.getClass()).invoke( baseResource, new Object[] {array}); //ResourceCollectionC.getMethod(", parameterTypes) } } catch (ClassNotFoundException ex) { getLogger().info("Development mode not in jetty so war finder will be disabled"); } catch (Exception ex) { getLogger().error(ex.getMessage(), ex); } finally { if ( parent != null) { currentThread.setContextClassLoader( classLoader); } } } private void exit() { MainServlet.this.reconnect = null; guiMutex.release(); if ( shutdownCommand != null) { shutdownCommand.run(); } } public void service( HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException { RaplaPageGenerator servletPage; Lock readLock = null; try { try { readLock = RaplaComponent.lock( restartLock.readLock(), 25); RaplaContext context = server.getContext(); for (ServletRequestPreprocessor preprocessor: processors) { final HttpServletRequest newRequest = preprocessor.handleRequest(context, getServletContext(), request, response); if (newRequest != null) request = newRequest; if (response.isCommitted()) return; } } catch (RaplaException e) { java.io.PrintWriter out = null; try { response.setStatus( 500 ); out = response.getWriter(); out.println(IOUtil.getStackTraceAsString( e)); } catch (Exception ex) { getLogger().error("Error writing exception back to client " + e.getMessage()); } finally { if ( out != null) { out.close(); } } return; } String page = request.getParameter("page"); String requestURI =request.getRequestURI(); if ( page == null) { String raplaPrefix = "rapla/"; String contextPath = request.getContextPath(); String toParse; if (requestURI.startsWith( contextPath)) { toParse = requestURI.substring( contextPath.length()); } else { toParse = requestURI; } int pageContextIndex = toParse.lastIndexOf(raplaPrefix); if ( pageContextIndex>= 0) { page = toParse.substring( pageContextIndex + raplaPrefix.length()); int firstSeparator = page.indexOf('/'); if ( firstSeparator>1) { page = page.substring(0,firstSeparator ); } } } //String servletPath = request.getServletPath(); if ( requestURI.indexOf(RAPLA_RPC_PATH) >= 0) { handleOldRPCCall( request, response ); return; } // if ( requestURI.indexOf(RAPLA_JSON_PATH)>= 0) { // handleJSONCall( request, response, requestURI ); // return; // } if ( page == null || page.trim().length() == 0) { page = "index"; } servletPage = server.getWebpage( page); if ( servletPage == null) { response.setStatus( 404 ); java.io.PrintWriter out = null; try { out = response.getWriter(); String message = "404: Page " + page + " not found in Rapla context"; out.print(message); getLogger().getChildLogger("server.html.404").warn( message); } finally { if ( out != null) { out.close(); } } return; } ServletContext servletContext = getServletContext(); servletPage.generatePage( servletContext, request, response); } finally { try { RaplaComponent.unlock( readLock ); } catch (IllegalMonitorStateException ex) { // Released by the restarter } try { ServletOutputStream outputStream = response.getOutputStream(); outputStream.close(); } catch (Exception ex) { } } } /** serverContainerHint is useful when you have multiple server configurations in one config file e.g. in a test environment*/ public static String serverContainerHint = null; private void stopServer() { if ( raplaContainer == null) { return; } try { raplaContainer.dispose(); } catch (Exception ex) { String message = "Error while stopping server "; getLogger().error(message + ex.getMessage()); } } /** * Disposes of container manager and container instance. */ public void destroy() { stopServer(); } public RaplaContext getContext() { return raplaContainer.getContext(); } public Container getContainer() { return raplaContainer; } public void doImport() throws RaplaException { ImportExportManager manager = raplaContainer.getContext().lookup(ImportExportManager.class); manager.doImport(); } public void doExport() throws RaplaException { ImportExportManager manager = raplaContainer.getContext().lookup(ImportExportManager.class); manager.doExport(); } public Logger getLogger() { if ( logger == null) { return new RaplaJDKLoggingAdapter().get(); } return logger; } // only for old rapla versions, will be removed in 2.0 private void handleOldRPCCall( HttpServletRequest request, HttpServletResponse response ) throws IOException { String clientVersion = request.getParameter("v"); if ( clientVersion != null ) { String message = getVersionErrorText(request, clientVersion); response.addHeader("X-Error-Classname", WrongRaplaVersionException.class.getName()); response.addHeader("X-Error-Stacktrace", message ); response.setStatus( 500); } else { //if ( !serverVersion.equals( clientVersion ) ) String message = getVersionErrorText(request, ""); response.addHeader("X-Error-Stacktrace", message ); RaplaException e1= new RaplaException( message ); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); ObjectOutputStream exout = new ObjectOutputStream( outStream); exout.writeObject( e1); exout.flush(); exout.close(); byte[] out = outStream.toByteArray(); ServletOutputStream outputStream = null; try { outputStream = response.getOutputStream(); outputStream.write( out ); } catch (Exception ex) { getLogger().error( " Error writing exception back to client " + ex.getMessage()); } finally { if (outputStream != null) { outputStream.close(); } } response.setStatus( 500); } } // only for old rapla versions, will be removed in 2.0 private String getVersionErrorText(HttpServletRequest request,String clientVersion) { String requestUrl = request.getRequestURL().toString(); int indexOf = requestUrl.indexOf( "rpc/"); if (indexOf>=0 ) { requestUrl = requestUrl.substring( 0, indexOf) ; } String message; try { I18nBundle i18n = getContext().lookup(RaplaComponent.RAPLA_RESOURCES); message = i18n.format("error.wrong_rapla_version", clientVersion, serverVersion, requestUrl); } catch (Exception e) { message = "Update client from " + clientVersion + " to " + serverVersion + " on " + requestUrl + ". Click on the webstart or applet to update."; } return message; } // private void handleRPCCall( HttpServletRequest request, HttpServletResponse response, String requestURI ) // { // boolean dispatcherExceptionThrown = false; // try // { // handleLogin(request, response, requestURI); // final Map<String,String[]> originalMap = request.getParameterMap(); // final Map<String,String> parameterMap = makeSinglesAndRemoveVersion(originalMap); // final ServerServiceContainer serverContainer = getServer(); // RemoteServiceDispatcher serviceDispater=serverContainer.getContext().lookup( RemoteServiceDispatcher.class); // byte[] out; // try // { // out =null; // //out = serviceDispater.dispatch(remoteSession, methodName, parameterMap); // } // catch (Exception ex) // { // dispatcherExceptionThrown = true; // throw ex; // } // //String test = new String( out); // response.setContentType( "text/html; charset=utf-8"); // try // { // response.getOutputStream().write( out); // response.flushBuffer(); // response.getOutputStream().close(); // } // catch (Exception ex) // { // getLogger().error( " Error writing exception back to client " + ex.getMessage()); // } // } // catch (Exception e) // { // if ( !dispatcherExceptionThrown) // { // getLogger().error(e.getMessage(), e); // } // try // { // String message = e.getMessage(); // String name = e.getClass().getName(); // if ( message == null ) // { // message = name; // } // response.addHeader("X-Error-Stacktrace", message ); // response.addHeader("X-Error-Classname", name); //// String param = RemoteMethodSerialization.serializeExceptionParam( e); //// if ( param != null) //// { //// response.addHeader("X-Error-Param", param); //// } // response.setStatus( 500); // } // catch (Exception ex) // { // getLogger().error( " Error writing exception back to client " + e.getMessage(), ex); // } // } // } // private boolean isClientVersionSupported(String clientVersion) { // // add/remove supported client versions here // return clientVersion.equals(serverVersion) || clientVersion.equals("@doc.version@") ; // } // // private Map<String,String> makeSinglesAndRemoveVersion( Map<String, String[]> parameterMap ) // { // TreeMap<String,String> singlesMap = new TreeMap<String,String>(); // for (Iterator<String> it = parameterMap.keySet().iterator();it.hasNext();) // { // String key = it.next(); // if ( key.toLowerCase().equals("v")) // { // continue; // } // String[] values = parameterMap.get( key); // if ( values != null && values.length > 0 ) // { // singlesMap.put( key,values[0]); // } // else // { // singlesMap.put( key,null); // } // } // // return singlesMap; // // } }
Java
package org.rapla.server; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; public class HTTPMethodOverrideFilter implements Filter { Collection<String> VALID_METHODS = Arrays.asList(new String[] {"GET","POST","DELETE","PUT","PATCH"}); @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { MethodOverrideWrapper wrapper = new MethodOverrideWrapper( (HttpServletRequest) request); chain.doFilter(wrapper, response); HttpServletResponse hresponse = (HttpServletResponse) response; hresponse.addHeader("Vary", "X-HTTP-Method-Override"); } private class MethodOverrideWrapper extends HttpServletRequestWrapper { public MethodOverrideWrapper(HttpServletRequest request) { super(request); } @Override public String getMethod() { String method = super.getMethod(); String newMethod = getHeader("X-HTTP-Method-Override"); if ("POST".equals(method) && newMethod != null && VALID_METHODS.contains(newMethod)) { method = newMethod; } return method; } } }
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.entities; import java.text.Collator; import java.util.Comparator; import java.util.Locale; import org.rapla.components.util.Assert; public class NamedComparator<T extends Named> implements Comparator<T> { Locale locale; Collator collator; public NamedComparator(Locale locale) { this.locale = locale; Assert.notNull( locale ); collator = Collator.getInstance(locale); } public int compare(Named o1,Named o2) { if ( o1.equals(o2)) return 0; Named r1 = o1; Named r2 = o2; int result = collator.compare( r1.getName(locale) ,r2.getName(locale) ); if ( result !=0 ) return result; else return (o1.hashCode() < o2.hashCode()) ? -1 : 1; } }
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.entities; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; /** Some entities (especially dynamic-types and attributes) can have multiple names to allow easier reuse of created schemas or support for multi-language-environments. @see MultiLanguageNamed */ public class MultiLanguageName implements java.io.Serializable { // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; Map<String,String> mapLocales = new TreeMap<String,String>(); transient private boolean readOnly; public MultiLanguageName(String language,String translation) { setName(language,translation); } public MultiLanguageName(String[][] data) { for (int i=0;i<data.length;i++) setName(data[i][0],data[i][1]); } public MultiLanguageName() { } public void setReadOnly() { this.readOnly = true; } public boolean isReadOnly() { return this.readOnly; } public String getName(String language) { if ( language == null) { language = "en"; } String result = mapLocales.get(language); if (result == null) { result = mapLocales.get("en"); } if (result == null) { Iterator<String> it = mapLocales.values().iterator(); if (it.hasNext()) result = it.next(); } if (result == null) { result = ""; } return result; } public void setName(String language,String translation) { checkWritable(); setNameWithoutReadCheck(language, translation); } private void checkWritable() { if ( isReadOnly() ) throw new ReadOnlyException("Can't modify this multilanguage name."); } public void setTo(MultiLanguageName newName) { checkWritable(); mapLocales = new TreeMap<String,String>(newName.mapLocales); } public Collection<String> getAvailableLanguages() { return mapLocales.keySet(); } public Object clone() { MultiLanguageName newName= new MultiLanguageName(); newName.mapLocales.putAll(mapLocales); return newName; } public String toString() { return getName("en"); } @Deprecated public void setNameWithoutReadCheck(String language, String translation) { if (translation != null && !translation.trim().equals("")) { mapLocales.put(language,translation.trim()); } else { mapLocales.remove(language); } } }
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.entities.internal; import java.util.Collection; import java.util.Date; import java.util.Locale; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.framework.RaplaException; public class UserImpl extends SimpleEntity implements User, ModifiableTimestamp { private String username = ""; private String email = ""; private String name = ""; private boolean admin = false; private Date lastChanged; private Date createDate; // The resolved references transient private Category[] groups; final public RaplaType<User> getRaplaType() {return TYPE;} UserImpl() { this(null,null); } public UserImpl(Date createDate,Date lastChanged) { this.createDate = createDate; this.lastChanged = lastChanged; } public Date getLastChanged() { return lastChanged; } @Deprecated public Date getLastChangeTime() { return lastChanged; } public Date getCreateTime() { return createDate; } public void setLastChanged(Date date) { checkWritable(); lastChanged = date; } public boolean isAdmin() {return admin;} public String getName() { final Allocatable person = getPerson(); if ( person != null) { return person.getName( null ); } return name; } public String getEmail() { final Allocatable person = getPerson(); if ( person != null) { final Classification classification = person.getClassification(); final Attribute attribute = classification.getAttribute("email"); return attribute != null ? (String)classification.getValue(attribute) : null; } return email; } public String getUsername() { return username; } public String toString() { return getUsername(); } public void setName(String name) { checkWritable(); this.name = name; } public void setEmail(String email) { checkWritable(); this.email = email; } public void setUsername(String username) { checkWritable(); this.username = username; } public void setAdmin(boolean bAdmin) { checkWritable(); this.admin=bAdmin; } public String getName(Locale locale) { final Allocatable person = getPerson(); if ( person != null) { return person.getName(locale); } final String name = getName(); if ( name == null || name.length() == 0) { return getUsername(); } else { return name; } } public void addGroup(Category group) { checkWritable(); if ( isRefering("groups", group.getId())) { return; } groups = null; add("groups",group); } public boolean removeGroup(Category group) { checkWritable(); return removeId(group.getId()); } public Category[] getGroups() { updateGroupArray(); return groups; } public boolean belongsTo( Category group ) { for (Category uGroup:getGroups()) { if (group.equals( uGroup) || group.isAncestorOf( uGroup)) { return true; } } return false; } private void updateGroupArray() { if (groups != null) return; synchronized ( this ) { Collection<Category> groupList = getList("groups", Category.class); groups = groupList.toArray(Category.CATEGORY_ARRAY); } } public User clone() { UserImpl clone = new UserImpl(); super.deepClone(clone); clone.groups = null; clone.username = username; clone.name = name; clone.email = email; clone.admin = admin; clone.lastChanged = lastChanged; clone.createDate = createDate; return clone; } public int compareTo(User o) { int result = toString().compareTo( o.toString()); if (result != 0) { return result; } else { return super.compareTo( o); } } public void setPerson(Allocatable person) throws RaplaException { checkWritable(); if ( person == null) { putEntity("person", null); return; } final Classification classification = person.getClassification(); final Attribute attribute = classification.getAttribute("email"); final String email = attribute != null ? (String)classification.getValue(attribute) : null; if ( email == null || email.length() == 0) { throw new RaplaException("Email of " + person + " not set. Linking to user needs an email "); } else { this.email = email; putEntity("person", (Entity) person); setName(person.getClassification().getName(null)); } } public Allocatable getPerson() { final Allocatable person = getEntity("person", Allocatable.class); return person; } }
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.entities.internal; import java.util.Date; import org.rapla.entities.Timestamp; import org.rapla.entities.User; public interface ModifiableTimestamp extends Timestamp { /** updates the last-changed timestamp */ void setLastChanged(Date date); void setLastChangedBy( User user); }
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.entities.internal; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.rapla.components.util.Assert; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.IllegalAnnotationException; import org.rapla.entities.MultiLanguageName; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.ParentEntity; import org.rapla.entities.storage.internal.SimpleEntity; final public class CategoryImpl extends SimpleEntity implements Category, ParentEntity, ModifiableTimestamp { private MultiLanguageName name = new MultiLanguageName(); private String key; Set<CategoryImpl> childs = new LinkedHashSet<CategoryImpl>(); private Date lastChanged; private Date createDate; private Map<String,String> annotations = new LinkedHashMap<String,String>(); private transient Category parent; CategoryImpl() { } public CategoryImpl(Date createDate, Date lastChanged) { this.createDate = createDate; this.lastChanged = lastChanged; } @Override public void setResolver(EntityResolver resolver) { super.setResolver(resolver); for (CategoryImpl child:childs) { child.setParent( this); } } @Override public void addEntity(Entity entity) { childs.add( (CategoryImpl) entity); } public Date getLastChanged() { return lastChanged; } @Deprecated public Date getLastChangeTime() { return lastChanged; } public Date getCreateTime() { return createDate; } public void setLastChanged(Date date) { checkWritable(); lastChanged = date; for ( CategoryImpl child:childs) { child.setLastChanged( date); } } public RaplaType<Category> getRaplaType() {return TYPE;} void setParent(CategoryImpl parent) { putEntity("parent", parent); this.parent = parent; } public void removeParent() { removeWithKey("parent"); this.parent = null; } public Category getParent() { if ( parent == null) { parent = getEntity("parent", Category.class); } return parent; } public Category[] getCategories() { return childs.toArray(Category.CATEGORY_ARRAY); } @SuppressWarnings("unchecked") public Collection<CategoryImpl> getSubEntities() { return childs; } public boolean isAncestorOf(Category category) { if (category == null) return false; if (category.getParent() == null) return false; if (category.getParent().equals(this)) return true; else return isAncestorOf(category.getParent()); } public Category getCategory(String key) { for (Entity ref: getSubEntities()) { Category cat = (Category) ref; if (cat.getKey().equals(key)) return cat; } return null; } public boolean hasCategory(Category category) { return childs.contains(category); } public void addCategory(Category category) { checkWritable(); Assert.isTrue(category.getParent() == null || category.getParent().equals(this) ,"Category is already attached to a parent"); CategoryImpl categoryImpl = (CategoryImpl)category; if ( resolver != null) { Assert.isTrue( !categoryImpl.isAncestorOf( this), "Can't add a parent category to one of its ancestors."); } addEntity( (Entity) category); categoryImpl.setParent(this); } public int getRootPathLength() { Category parent = getParent(); if ( parent == null) { return 0; } else { int parentDepth = parent.getRootPathLength(); return parentDepth + 1; } } public int getDepth() { int max = 0; Category[] categories = getCategories(); for (int i=0;i<categories.length;i++) { int depth = categories[i].getDepth(); if (depth > max) max = depth; } return max + 1; } public void removeCategory(Category category) { checkWritable(); if ( findCategory( category ) == null) return; childs.remove(category); //if (category.getParent().equals(this)) ((CategoryImpl)category).setParent(null); } public Category findCategory(Category copy) { return (Category) super.findEntity((Entity)copy); } public MultiLanguageName getName() { return name; } public void setReadOnly() { super.setReadOnly( ); name.setReadOnly( ); } public String getName(Locale locale) { if ( locale == null) { locale = Locale.getDefault(); } return name.getName(locale.getLanguage()); } public String getKey() { return key; } public void setKey(String key) { checkWritable(); this.key = key; } public String getPath(Category rootCategory,Locale locale) { StringBuffer buf = new StringBuffer(); if (rootCategory != null && this.equals(rootCategory)) return ""; if (this.getParent() != null) { String path = this.getParent().getPath(rootCategory,locale); buf.append(path); if (path.length()>0) buf.append('/'); } buf.append(this.getName(locale)); return buf.toString(); } public List<String> getKeyPath(Category rootCategory) { LinkedList<String> result = new LinkedList<String>(); if (rootCategory != null && this.equals(rootCategory)) return result; Category cat = this; while (cat.getParent() != null) { Category parent = cat.getParent(); result.addFirst( parent.getKey()); cat = parent; if ( parent == this) { throw new IllegalStateException("Parent added as own child"); } } result.add( getKey()); return result; } public String toString() { MultiLanguageName name = getName(); if (name != null) { return name.toString() + " ID='" + getId() + "'"; } else { return getKey() + " " + getId(); } } public String getPathForCategory(Category searchCategory) throws EntityNotFoundException { List<String> keyPath = getPathForCategory(searchCategory, true); return getKeyPathString(keyPath); } public static String getKeyPathString(List<String> keyPath) { StringBuffer buf = new StringBuffer(); for (String category:keyPath) { buf.append('/'); buf.append(category); } if ( buf.length() > 0) { buf.deleteCharAt(0); } String pathForCategory = buf.toString(); return pathForCategory ; } public List<String> getPathForCategory(Category searchCategory, boolean fail) throws EntityNotFoundException { LinkedList<String> result = new LinkedList<String>(); Category category = searchCategory; Category parent = category.getParent(); if (category == this) return result; if (parent == null) throw new EntityNotFoundException("Category has no parents!"); while (true) { String entry ="category[key='" + category.getKey() + "']"; result.addFirst(entry); parent = category.getParent(); category = parent; if (parent == null) { if ( fail) { throw new EntityNotFoundException("Category not found!" + searchCategory); } return null; } if (parent.equals(this)) break; } return result; } public Category getCategoryFromPath(String path) throws EntityNotFoundException { int start = 0; int end = 0; int pos = 0; Category category = this; while (category != null) { start = path.indexOf("'",pos) + 1; if (start==0) break; end = path.indexOf("'",start); if (end < 0) throw new EntityNotFoundException("Invalid xpath expression: " + path); String key = path.substring(start,end); category = category.getCategory(key); pos = end + 1; } if (category == null) throw new EntityNotFoundException("could not resolve category xpath expression: " + path); return category; } public Category findCategory(Object copy) { return (Category) super.findEntity((Entity)copy); } public String getAnnotation(String key) { return annotations.get(key); } public String getAnnotation(String key, String defaultValue) { String annotation = getAnnotation( key ); return annotation != null ? annotation : defaultValue; } public void setAnnotation(String key,String annotation) throws IllegalAnnotationException { checkWritable(); if (annotation == null) { annotations.remove(key); return; } annotations.put(key,annotation); } public String[] getAnnotationKeys() { return annotations.keySet().toArray(RaplaObject.EMPTY_STRING_ARRAY); } @SuppressWarnings("unchecked") public Category clone() { CategoryImpl clone = new CategoryImpl(); super.deepClone(clone); clone.name = (MultiLanguageName) name.clone(); clone.parent = parent; clone.annotations = (HashMap<String,String>) ((HashMap<String,String>)annotations).clone(); clone.key = key; clone.lastChanged = lastChanged; clone.createDate = createDate; for (Entity ref:clone.getSubEntities()) { ((CategoryImpl)ref).setParent(clone); } return clone; } public int compareTo(Object o) { if ( o == this ) { return 0; } if ( equals( o )) { return 0; } Category c1= this; Category c2= (Category) o; if ( c1.isAncestorOf( c2)) { return -1; } if ( c2.isAncestorOf( c1)) { return 1; } while ( c1.getRootPathLength() > c2.getRootPathLength()) { c1 = c1.getParent(); } while ( c2.getRootPathLength() > c2.getRootPathLength()) { c2 = c2.getParent(); } while ( c1.getParent() != null && c2.getParent() != null && (!c1.getParent().equals( c2.getParent()))) { c1 = c1.getParent(); c2 = c2.getParent(); } //now the two categories have the same parent if ( c1.getParent() == null || c2.getParent() == null) { return super.compareTo( o); } Category parent = c1.getParent(); // We look who is first in the list Category[] categories = parent.getCategories(); for ( Category category: categories) { if ( category.equals( c1)) { return -1; } if ( category.equals( c2)) { return 1; } } return super.compareTo( o); } public void replace(Category category) { String id = category.getId(); CategoryImpl existingEntity = (CategoryImpl) findEntityForId(id); if ( existingEntity != null) { LinkedHashSet<CategoryImpl> newChilds = new LinkedHashSet<CategoryImpl>(); for ( CategoryImpl child: childs) { newChilds.add( ( child != existingEntity) ? child: (CategoryImpl)category); } childs = newChilds; } } }
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.entities; /**This interface is a marker to distinct the different rapla classes * like Reservation, Allocatable and Category. * It is something like the java instanceof keyword. But it must be unique for each * class. This type-information is for examle used for mapping the correct storage-, * editing- mechanism to the class. */ public interface RaplaObject<T> extends Cloneable { public static final String[] EMPTY_STRING_ARRAY = new String[0]; RaplaType<T> getRaplaType(); T clone(); }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas, Frithjof Kurtz | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.entities.configuration.internal; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.rapla.components.util.iterator.NestedIterator; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.internal.ClassificationFilterImpl; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityResolver; public abstract class AbstractClassifiableFilter implements EntityReferencer, DynamicTypeDependant, Serializable { private static final long serialVersionUID = 1L; List<ClassificationFilterImpl> classificationFilters; protected transient EntityResolver resolver; AbstractClassifiableFilter() { classificationFilters = new ArrayList<ClassificationFilterImpl>(); } public void setResolver( EntityResolver resolver) { this.resolver = resolver; for (ClassificationFilterImpl filter:classificationFilters) { filter.setResolver( resolver ); } } @Override public Iterable<ReferenceInfo> getReferenceInfo() { Iterable<ClassificationFilterImpl> classificatonFilterIterator = classificationFilters; return new NestedIterator<ReferenceInfo,ClassificationFilterImpl>(classificatonFilterIterator) { public Iterable<ReferenceInfo> getNestedIterator(ClassificationFilterImpl obj) { return obj.getReferenceInfo(); } }; } public void setClassificationFilter(List<ClassificationFilterImpl> classificationFilters) { if ( classificationFilters != null) this.classificationFilters = classificationFilters; else this.classificationFilters = Collections.emptyList(); } public boolean needsChange(DynamicType type) { for (ClassificationFilterImpl filter:classificationFilters) { if (filter.needsChange(type)) return true; } return false; } public void commitChange(DynamicType type) { for (ClassificationFilterImpl filter:classificationFilters) { if (filter.getType().equals(type)) filter.commitChange(type); } } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { boolean removed = false; List<ClassificationFilterImpl> newFilter = new ArrayList<ClassificationFilterImpl>( classificationFilters); for (Iterator<ClassificationFilterImpl> f=newFilter.iterator();f.hasNext();) { ClassificationFilterImpl filter = f.next(); if (filter.getType().equals(type)) { removed = true; f.remove(); } } if ( removed) { classificationFilters = newFilter; } } public ClassificationFilter[] getFilter() { return classificationFilters.toArray( ClassificationFilter.CLASSIFICATIONFILTER_ARRAY); } public String toString() { return classificationFilters.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.entities.configuration.internal; import java.util.Date; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Set; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.entities.configuration.RaplaMap; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.internal.ModifiableTimestamp; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.internal.SimpleEntity; import org.rapla.facade.RaplaComponent; import org.rapla.framework.Configuration; import org.rapla.framework.TypedComponentRole; import org.rapla.storage.PreferencePatch; public class PreferencesImpl extends SimpleEntity implements Preferences ,ModifiableTimestamp , DynamicTypeDependant { private Date lastChanged; private Date createDate; RaplaMapImpl map = new RaplaMapImpl(); Set<String> removedKeys = new LinkedHashSet<String>(); final public RaplaType<Preferences> getRaplaType() {return TYPE;} private transient PreferencePatch patch = new PreferencePatch(); PreferencesImpl() { this(null,null); } public PreferencesImpl(Date createDate,Date lastChanged ) { super(); this.createDate = createDate; this.lastChanged = lastChanged; } public Date getLastChanged() { return lastChanged; } @Deprecated public Date getLastChangeTime() { return lastChanged; } public Date getCreateTime() { return createDate; } public void setLastChanged(Date date) { checkWritable(); lastChanged = date; } @Override public void putEntry(TypedComponentRole<CalendarModelConfiguration> role, CalendarModelConfiguration entry) { putEntryPrivate(role.getId(), entry); } @Override public void putEntry(TypedComponentRole<RaplaConfiguration> role, RaplaConfiguration entry) { putEntryPrivate(role.getId(), entry); } @Override public <T> void putEntry(TypedComponentRole<RaplaMap<T>> role, RaplaMap<T> entry) { putEntryPrivate(role.getId(), entry); } public void putEntryPrivate(String role,RaplaObject entry) { updateMap(role, entry); } private void updateMap(String role, Object entry) { checkWritable(); map.putPrivate(role, entry); patch.putPrivate( role, entry); if ( entry == null) { patch.addRemove( role); } } public void putEntryPrivate(String role,String entry) { updateMap(role, entry); } public void setResolver( EntityResolver resolver) { super.setResolver(resolver); map.setResolver(resolver); patch.setResolver(resolver); } public <T> T getEntry(String role) { return getEntry(role, null); } public <T> T getEntry(String role, T defaultValue) { try { @SuppressWarnings("unchecked") T result = (T) map.get( role ); if ( result == null) { return defaultValue; } return result; } catch ( ClassCastException ex) { throw new ClassCastException( "Stored entry is not of requested Type: " + ex.getMessage()); } } private String getEntryAsString(String role) { return (String) map.get( role ); } public String getEntryAsString(TypedComponentRole<String> role, String defaultValue) { String value = getEntryAsString( role.getId()); if ( value != null) return value; return defaultValue; } public Iterable<String> getPreferenceEntries() { return map.keySet(); } public void removeEntry(String role) { updateMap(role, null); } @Override public Iterable<ReferenceInfo> getReferenceInfo() { Iterable<ReferenceInfo> parentReferences = super.getReferenceInfo(); Iterable<ReferenceInfo> mapReferences = map.getReferenceInfo(); IteratorChain<ReferenceInfo> iteratorChain = new IteratorChain<ReferenceInfo>(parentReferences,mapReferences); return iteratorChain; } public boolean isEmpty() { return map.isEmpty(); } public PreferencesImpl clone() { PreferencesImpl clone = new PreferencesImpl(); super.deepClone(clone); clone.map = map.deepClone(); clone.createDate = createDate; clone.lastChanged = lastChanged; // we clear the patch on a clone clone.patch = new PreferencePatch(); clone.patch.setUserId( getOwnerId()); return clone; } @Override public void setOwner(User owner) { super.setOwner(owner); patch.setUserId( getOwnerId()); } public PreferencePatch getPatch() { return patch; } /** * @see org.rapla.entities.Named#getName(java.util.Locale) */ public String getName(Locale locale) { StringBuffer buf = new StringBuffer(); if ( getOwner() != null) { buf.append( "Preferences of "); buf.append( getOwner().getName( locale)); } else { buf.append( "Rapla Preferences!"); } return buf.toString(); } /* (non-Javadoc) * @see org.rapla.entities.configuration.Preferences#getEntryAsBoolean(java.lang.String, boolean) */ public Boolean getEntryAsBoolean(TypedComponentRole<Boolean> role, boolean defaultValue) { String entry = getEntryAsString( role.getId()); if ( entry == null) return defaultValue; return Boolean.valueOf(entry).booleanValue(); } /* (non-Javadoc) * @see org.rapla.entities.configuration.Preferences#getEntryAsInteger(java.lang.String, int) */ public Integer getEntryAsInteger(TypedComponentRole<Integer> role, int defaultValue) { String entry = getEntryAsString( role.getId()); if ( entry == null) return defaultValue; return Integer.parseInt(entry); } public boolean needsChange(DynamicType type) { return map.needsChange(type); } public void commitChange(DynamicType type) { map.commitChange(type); patch.commitChange(type); } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { map.commitRemove(type); patch.commitRemove(type); } public String toString() { return super.toString() + " " + map.toString(); } public <T extends RaplaObject> void putEntry(TypedComponentRole<T> role,T entry) { putEntryPrivate( role.getId(), entry); } public void applyPatch(PreferencePatch patch) { checkWritable(); Set<String> removedEntries = patch.getRemovedEntries(); for (String key:patch.keySet()) { Object value = patch.get( key); updateMap(key, value); } for ( String remove:removedEntries) { updateMap(remove, null); } } public <T extends RaplaObject> T getEntry(TypedComponentRole<T> role) { return getEntry( role, null); } public <T extends RaplaObject> T getEntry(TypedComponentRole<T> role, T defaultValue) { return getEntry( role.getId(), defaultValue); } public boolean hasEntry(TypedComponentRole<?> role) { return map.get( role.getId() ) != null; } public void putEntry(TypedComponentRole<Boolean> role, Boolean entry) { putEntry_(role, entry != null ? entry.toString(): null); } public void putEntry(TypedComponentRole<Integer> role, Integer entry) { putEntry_(role, entry != null ? entry.toString() : null); } public void putEntry(TypedComponentRole<String> role, String entry) { putEntry_(role, entry); } protected void putEntry_(TypedComponentRole<?> role, Object entry) { checkWritable(); String key = role.getId(); updateMap(key, entry); // if ( entry == null) // { // map.remove( id); // } // else // { // map.put( id ,entry.toString()); // } } public static String getPreferenceIdFromUser(String userId) { String preferenceId = (userId != null ) ? Preferences.ID_PREFIX + userId : SYSTEM_PREFERENCES_ID; return preferenceId.intern(); } @Deprecated public Configuration getOldPluginConfig(String pluginClassName) { RaplaConfiguration raplaConfig = getEntry(RaplaComponent.PLUGIN_CONFIG); Configuration pluginConfig = null; if ( raplaConfig != null) { pluginConfig = raplaConfig.find("class", pluginClassName); } if ( pluginConfig == null) { pluginConfig = new RaplaConfiguration("plugin"); } return pluginConfig; } // public static boolean isServerEntry(String configRole) { // if ( configRole == null) // { // return false; // } // if ( configRole.startsWith("server.") || configRole.contains(".server.")) // { // return true; // } // return false; // } }
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.entities.configuration.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.entities.Entity; import org.rapla.entities.RaplaType; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.entities.dynamictype.internal.ClassificationFilterImpl; import org.rapla.entities.storage.EntityResolver; import org.rapla.framework.RaplaException; public class CalendarModelConfigurationImpl extends AbstractClassifiableFilter implements CalendarModelConfiguration { // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; List<String> selected; List<String> typeList; String title; Date startDate; Date endDate; Date selectedDate; String view; Map<String,String> optionMap; boolean defaultEventTypes; boolean defaultResourceTypes; boolean resourceRootSelected; public CalendarModelConfigurationImpl( Collection<String> selected,Collection<RaplaType> idTypeList,boolean resourceRootSelected, ClassificationFilter[] filter, boolean defaultResourceTypes, boolean defaultEventTypes,String title, Date startDate, Date endDate, Date selectedDate,String view,Map<String,String> extensionMap) { if (selected != null) { this.selected = Collections.unmodifiableList(new ArrayList<String>(selected)); typeList = new ArrayList<String>(); for ( RaplaType type:idTypeList) { typeList.add(type.getLocalName()); } } else { this.selected = Collections.emptyList(); typeList = Collections.emptyList(); } this.view = view; this.resourceRootSelected = resourceRootSelected; this.defaultEventTypes = defaultEventTypes; this.defaultResourceTypes = defaultResourceTypes; this.title = title; this.startDate = startDate; this.endDate = endDate; this.selectedDate = selectedDate; List<ClassificationFilterImpl> filterList = new ArrayList<ClassificationFilterImpl>(); if ( filter != null) { for ( ClassificationFilter f:filter) { filterList.add((ClassificationFilterImpl)f); } } super.setClassificationFilter( filterList ); Map<String,String> map= new LinkedHashMap<String,String>(); if ( extensionMap != null) { map.putAll(extensionMap); } this.optionMap = Collections.unmodifiableMap( map); } CalendarModelConfigurationImpl() { } @Override public boolean isResourceRootSelected() { return resourceRootSelected; } public void setResolver( EntityResolver resolver) { super.setResolver( resolver ); } public RaplaType<CalendarModelConfiguration> getRaplaType() { return TYPE; } public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } public Date getSelectedDate() { return selectedDate; } public String getTitle() { return title; } public String getView() { return view; } public Collection<Entity> getSelected() { ArrayList<Entity> result = new ArrayList<Entity>(); for ( String id: selected) { Entity entity = resolver.tryResolve(id); if ( entity != null) { result.add( entity); } } return result; } @Override public Iterable<ReferenceInfo> getReferenceInfo() { Iterable<ReferenceInfo> references = super.getReferenceInfo(); List<ReferenceInfo> selectedInfo = new ArrayList<ReferenceInfo>(); int size = selected.size(); for ( int i = 0;i<size;i++) { String id = selected.get(0); String localname = typeList.get(0); Class<? extends Entity> type = null; RaplaType raplaType; try { raplaType = RaplaType.find(localname); Class typeClass = raplaType.getTypeClass(); if ( Entity.class.isAssignableFrom(typeClass )) { @SuppressWarnings("unchecked") Class<? extends Entity> casted = (Class<? extends Entity>)typeClass; type = casted; } } catch (RaplaException e) { } ReferenceInfo referenceInfo = new ReferenceInfo(id, type); selectedInfo.add( referenceInfo); } return new IteratorChain<ReferenceInfo>(references, selectedInfo); } public Map<String,String> getOptionMap() { return optionMap; } public boolean isDefaultEventTypes() { return defaultEventTypes; } public boolean isDefaultResourceTypes() { return defaultResourceTypes; } @SuppressWarnings("unchecked") static private void copy(CalendarModelConfigurationImpl source,CalendarModelConfigurationImpl dest) { dest.view = source.view; dest.defaultEventTypes = source.defaultEventTypes; dest.defaultResourceTypes = source.defaultResourceTypes; dest.title = source.title; dest.startDate = source.startDate; dest.endDate = source.endDate; dest.selectedDate = source.selectedDate; dest.resourceRootSelected = source.resourceRootSelected; dest.setResolver( source.resolver); List<ClassificationFilterImpl> newFilter = new ArrayList<ClassificationFilterImpl>(); for ( ClassificationFilterImpl f: source.classificationFilters) { ClassificationFilterImpl clone = f.clone(); newFilter.add( clone); } dest.setClassificationFilter(newFilter ); dest.selected = (List<String>)((ArrayList<String>)source.selected).clone(); LinkedHashMap<String, String> optionMap = new LinkedHashMap<String,String>(); optionMap.putAll(source.optionMap); dest.optionMap = Collections.unmodifiableMap(optionMap); } public void copy(CalendarModelConfiguration obj) { copy((CalendarModelConfigurationImpl)obj, this); } public CalendarModelConfiguration deepClone() { CalendarModelConfigurationImpl clone = new CalendarModelConfigurationImpl(); copy(this,clone); return clone; } public CalendarModelConfiguration clone() { return deepClone(); } public List<String> getSelectedIds() { return selected; } public String toString() { return super.toString() + ",selected=" + selected; } @Override public CalendarModelConfiguration cloneWithNewOptions(Map<String, String> newMap) { CalendarModelConfigurationImpl clone = (CalendarModelConfigurationImpl) deepClone(); clone.optionMap = Collections.unmodifiableMap( newMap); return clone; } }
Java
/*--------------------------------------------------------------------------* | C o//pyright (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.entities.configuration.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.rapla.components.util.iterator.FilterIterator; import org.rapla.components.util.iterator.IteratorChain; import org.rapla.components.util.iterator.NestedIterator; import org.rapla.entities.Category; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.ReadOnlyException; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.entities.configuration.RaplaMap; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.storage.CannotExistWithoutTypeException; import org.rapla.entities.storage.DynamicTypeDependant; import org.rapla.entities.storage.EntityReferencer; import org.rapla.entities.storage.EntityResolver; import org.rapla.entities.storage.internal.ReferenceHandler; /** Maps can only support one type value at a time. Especially a mixture out of references and other values is not supported*/ public class RaplaMapImpl implements EntityReferencer, DynamicTypeDependant, RaplaObject, RaplaMap { //this map stores all objects in the map private Map<String,String> constants; private Map<String,RaplaConfiguration> configurations; private Map<String,RaplaMapImpl> maps; private Map<String,CalendarModelConfigurationImpl> calendars; protected LinkReferenceHandler links; transient protected Map<String,Object> map; transient EntityResolver resolver; static private RaplaType[] SUPPORTED_TYPES = new RaplaType[] { Allocatable.TYPE, Category.TYPE, DynamicType.TYPE}; // this map only stores the references // this map only stores the child objects (not the references) public RaplaMapImpl() { } public <T> RaplaMapImpl( Collection<T> list) { this( makeMap(list) ); } public RaplaType getRaplaType() { return RaplaMap.TYPE; } private static <T> Map<String,T> makeMap(Collection<T> list) { Map<String,T> map = new TreeMap<String,T>(); int key = 0; for ( Iterator<T> it = list.iterator();it.hasNext();) { T next = it.next(); if ( next == null) { System.err.println("Adding null value in list" ); } map.put( new String( String.valueOf(key++)), next); } return map; } public RaplaMapImpl( Map<String,?> map) { for ( Iterator<String> it = map.keySet().iterator();it.hasNext();) { String key = it.next(); Object o = map.get(key ); putPrivate(key, o); } } /** This method is only used in storage operations, please dont use it from outside, as it skips type protection and resolving*/ public void putPrivate(String key, Object value) { cachedEntries = null; if ( value == null) { if (links != null) { links.removeWithKey(key); } if ( maps != null) { maps.remove( key); } if ( map != null) { map.remove( key); } if ( configurations != null) { configurations.remove(key); } if ( maps != null) { maps.remove(key); } if ( calendars != null) { calendars.remove(key); } if ( constants != null) { constants.remove(key); } return; } // if ( ! (value instanceof RaplaObject ) && !(value instanceof String) ) // { // } if ( value instanceof Entity) { Entity entity = (Entity) value; String id = entity.getId(); RaplaType raplaType = entity.getRaplaType(); if ( !isTypeSupportedAsLink( raplaType)) { throw new IllegalArgumentException("RaplaType " + raplaType + " cannot be stored as link in map"); } putIdPrivate(key, id, raplaType); } else if ( value instanceof RaplaConfiguration) { if ( configurations == null) { configurations = new LinkedHashMap<String,RaplaConfiguration>(); } configurations.put( key, (RaplaConfiguration) value); getMap().put(key, value); } else if ( value instanceof RaplaMap) { if ( maps == null) { maps = new LinkedHashMap<String,RaplaMapImpl>(); } maps.put( key, (RaplaMapImpl) value); getMap().put(key, value); } else if ( value instanceof CalendarModelConfiguration) { if ( calendars == null) { calendars = new LinkedHashMap<String,CalendarModelConfigurationImpl>(); } calendars.put( key, (CalendarModelConfigurationImpl) value); getMap().put(key, value); } else if ( value instanceof String) { if ( constants == null) { constants = new LinkedHashMap<String,String>(); } constants.put( key , (String) value); getMap().put(key, value); } else { throw new IllegalArgumentException("Map type not supported only category, dynamictype, allocatable, raplamap, raplaconfiguration or String."); } } private Map<String, Object> getMap() { if (links != null) { Map<String, ?> linkMap = links.getLinkMap(); @SuppressWarnings("unchecked") Map<String,Object> casted = (Map<String,Object>)linkMap; return casted; } if ( maps == null && configurations == null && constants == null && calendars == null) { return Collections.emptyMap(); } if ( map == null) { map = new LinkedHashMap<String,Object>(); fillMap(maps); fillMap(configurations); fillMap(constants); fillMap(calendars); } return map; } private void fillMap(Map<String, ?> map) { if ( map == null) { return; } this.map.putAll( map); } public void putIdPrivate(String key, String id, RaplaType raplaType) { cachedEntries = null; if ( links == null) { links = new LinkReferenceHandler(); links.setLinkType( raplaType.getLocalName()); if ( resolver != null) { links.setResolver( resolver); } } links.putId( key,id); map = null; } @Override public Iterable<ReferenceInfo> getReferenceInfo() { NestedIterator<ReferenceInfo,EntityReferencer> refIt = new NestedIterator<ReferenceInfo,EntityReferencer>( getEntityReferencers()) { public Iterable<ReferenceInfo> getNestedIterator(EntityReferencer obj) { Iterable<ReferenceInfo> referencedIds = obj.getReferenceInfo(); return referencedIds; } }; if ( links == null) { return refIt; } Iterable<ReferenceInfo> referencedLinks = links.getReferenceInfo(); return new IteratorChain<ReferenceInfo>( refIt, referencedLinks); } private Iterable<EntityReferencer> getEntityReferencers() { return new FilterIterator<EntityReferencer>( getMap().values()) { protected boolean isInIterator(Object obj) { return obj instanceof EntityReferencer; } }; } /* public Iterator getReferences() { return getReferenceHandler().getReferences(); } public boolean isRefering(Entity entity) { return getReferenceHandler().isRefering( entity); }*/ public void setResolver( EntityResolver resolver) { this.resolver = resolver; if ( links != null) { links.setResolver( resolver ); } setResolver( calendars); setResolver( maps ); map = null; } private void setResolver(Map<String,? extends EntityReferencer> map) { if ( map == null) { return; } for (EntityReferencer ref:map.values()) { ref.setResolver( resolver); } } public Object get(Object key) { if (links != null) { return links.getEntity((String)key); } return getMap().get(key); } /** * @see java.util.Map#clear() */ public void clear() { throw createReadOnlyException(); } protected ReadOnlyException createReadOnlyException() { return new ReadOnlyException("RaplaMap is readonly you must create a new Object"); } /** * @see java.util.Map#size() */ public int size() { return getMap().size(); } /** * @see java.util.Map#isEmpty() */ public boolean isEmpty() { return getMap().isEmpty(); } /** * @see java.util.Map#containsKey(java.lang.Object) */ public boolean containsKey(Object key) { return getMap().containsKey( key); } /** * @see java.util.Map#containsValue(java.lang.Object) */ public boolean containsValue(Object key) { return getMap().containsValue( key); } /** * @see java.util.Map#keySet() */ public Set<String> keySet() { return getMap().keySet(); } public boolean needsChange(DynamicType type) { for (Iterator it = getMap().values().iterator();it.hasNext();) { Object obj = it.next(); if ( obj instanceof DynamicTypeDependant) { if (((DynamicTypeDependant) obj).needsChange( type )) return true; } } return false; } public void commitChange(DynamicType type) { for (Object obj:getMap().values()) { if ( obj instanceof DynamicTypeDependant) { ((DynamicTypeDependant) obj).commitChange( type ); } } } public void commitRemove(DynamicType type) throws CannotExistWithoutTypeException { for (Object obj:getMap().values()) { if ( obj instanceof DynamicTypeDependant) { ((DynamicTypeDependant) obj).commitRemove( type ); } } } /** Clones the entity and all subentities*/ public RaplaMapImpl deepClone() { RaplaMapImpl clone = new RaplaMapImpl(getMap()); clone.setResolver( resolver ); return clone; } // public Collection<RaplaObject> getLinkValues() // { // ArrayList<RaplaObject> result = new ArrayList<RaplaObject>(); // EntityResolver resolver = getReferenceHandler().getResolver(); // for (String id: getReferencedIds()) // { // result.add( resolver.tryResolve( id)); // } // return result; // // } /** Clones the entity while preserving the references to the subentities*/ public Object clone() { return deepClone(); } /** * @see java.util.Map#put(java.lang.Object, java.lang.Object) */ public Object put(Object key, Object value) { throw createReadOnlyException(); } public Object remove(Object arg0) { throw createReadOnlyException(); } /** * @see java.util.Map#putAll(java.util.Map) */ public void putAll(Map m) { throw createReadOnlyException(); } /** * @see java.util.Map#values() */ public Collection values() { if ( links == null) { return getMap().values(); } else { List<Entity> result = new ArrayList<Entity>(); Iterable<String> values = links.getReferencedIds(); for (String id: values) { Entity resolved = links.getResolver().tryResolve( id); result.add( resolved); } return result; } } public static final class LinkReferenceHandler extends ReferenceHandler { protected String linkType; transient private Class<? extends Entity> linkClass; protected Class<? extends Entity> getInfoClass(String key) { return getLinkClass(); } public Iterable<String> getReferencedIds() { Set<String> result = new HashSet<String>(); if (links != null) { for (List<String> entries:links.values()) { for ( String id: entries) { result.add(id); } } } return result; } public Entity getEntity(String key) { Class<? extends Entity> linkClass = getLinkClass(); return getEntity(key, linkClass); } private Class<? extends Entity> getLinkClass() { if ( linkClass != null) { return linkClass; } if ( linkType != null ) { for ( RaplaType type: SUPPORTED_TYPES ) { if (linkType.equals( type.getLocalName())) { @SuppressWarnings("unchecked") Class<? extends Entity> casted = type.getTypeClass(); this.linkClass = casted; return linkClass; } } } return null; } public void setLinkType(String type) { this.linkType = type; linkClass = null; } } class Entry implements Map.Entry<String, Object> { String key; String id; Entry(String key,String id) { this.key = key; this.id = id; if ( id == null) { throw new IllegalArgumentException("Empty id added"); } } public String getKey() { return key; } public Object getValue() { if ( id == null) { return null; } Entity resolve = links.getResolver().tryResolve( id ); return resolve; } public Object setValue(Object value) { throw new UnsupportedOperationException(); } public int hashCode() { return key.hashCode(); } @Override public boolean equals(Object obj) { return key.equals( ((Entry) obj).key); } public String toString() { Entity value = links.getResolver().tryResolve( id ); return key + "=" + ((value != null) ? value : "unresolvable_" + id); } } transient Set<Map.Entry<String, Object>> cachedEntries; public Set<Map.Entry<String, Object>> entrySet() { if ( links != null) { if ( cachedEntries == null) { cachedEntries = new HashSet<Map.Entry<String, Object>>(); for (String key:links.getReferenceKeys()) { String id = links.getId( key); if ( id == null) { System.err.println("Empty id " + id); } cachedEntries.add(new Entry( key, id)); } } return cachedEntries; } else { if ( cachedEntries == null) { cachedEntries = new HashSet<Map.Entry<String, Object>>(); for (Map.Entry<String,Object> entry:getMap().entrySet()) { if ( entry.getValue() == null) { System.err.println("Empty value for " + entry.getKey()); } cachedEntries.add((Map.Entry<String, Object>) entry); } } return cachedEntries; } } public String toString() { return entrySet().toString(); } public boolean isTypeSupportedAsLink(RaplaType raplaType) { for ( RaplaType type: SUPPORTED_TYPES ) { if ( type == raplaType) { return true; } } return false; } }
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.entities.configuration; import java.io.Serializable; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; /** * This class adds just the get Type method to the DefaultConfiguration so that the config can be stored in a preference object * @author ckohlhaas * @version 1.00.00 * @since 2.03.00 */ public class RaplaConfiguration extends DefaultConfiguration implements RaplaObject, Serializable{ // Don't forget to increase the serialVersionUID when you change the fields private static final long serialVersionUID = 1; public static final RaplaType<RaplaConfiguration> TYPE = new RaplaType<RaplaConfiguration>(RaplaConfiguration.class, "config"); public RaplaConfiguration() { super(); } /** Creates a RaplaConfinguration with one element of the specified name * @param name the element name * @param content The content of the element. Can be null. */ public RaplaConfiguration( String name, String content) { super(name, content); } public RaplaConfiguration(String localName) { super(localName); } public RaplaConfiguration(Configuration configuration) { super( configuration); } public RaplaType getRaplaType() { return TYPE; } public RaplaConfiguration replace( Configuration oldChild, Configuration newChild) { return (RaplaConfiguration) super.replace( oldChild, newChild); } @Override protected RaplaConfiguration newConfiguration(String localName) { return new RaplaConfiguration( localName); } public RaplaConfiguration clone() { return new RaplaConfiguration( this); } }
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.entities.configuration; import org.rapla.entities.Entity; import org.rapla.entities.Named; import org.rapla.entities.Ownable; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.Timestamp; import org.rapla.framework.TypedComponentRole; /** Preferences store user-specific Information. You can store arbitrary configuration objects under unique role names. Each role can contain 1-n configuration entries. @see org.rapla.entities.User */ public interface Preferences extends Entity<Preferences>,Ownable,Timestamp, Named { final RaplaType<Preferences> TYPE = new RaplaType<Preferences>(Preferences.class, "preferences"); final String ID_PREFIX = TYPE.getLocalName() + "_"; final String SYSTEM_PREFERENCES_ID = ID_PREFIX + "0"; /** returns if there are any preference-entries */ boolean isEmpty(); boolean hasEntry(TypedComponentRole<?> role); <T extends RaplaObject> T getEntry(TypedComponentRole<T> role); <T extends RaplaObject> T getEntry(TypedComponentRole<T> role, T defaultEntry); String getEntryAsString(TypedComponentRole<String> role, String defaultValue); Boolean getEntryAsBoolean(TypedComponentRole<Boolean> role, boolean defaultValue); Integer getEntryAsInteger(TypedComponentRole<Integer> role, int defaultValue); /** puts a new configuration entry to the role.*/ void putEntry(TypedComponentRole<Boolean> role,Boolean entry); void putEntry(TypedComponentRole<Integer> role,Integer entry); void putEntry(TypedComponentRole<String> role,String entry); void putEntry(TypedComponentRole<CalendarModelConfiguration> role,CalendarModelConfiguration entry); <T> void putEntry(TypedComponentRole<RaplaMap<T>> role,RaplaMap<T> entry); void putEntry(TypedComponentRole<RaplaConfiguration> role,RaplaConfiguration entry); void removeEntry(String role); }
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.entities.configuration; import java.util.Collection; import java.util.Date; import java.util.Map; import org.rapla.entities.Entity; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.dynamictype.ClassificationFilter; import org.rapla.framework.TypedComponentRole; /** * * @author ckohlhaas * @version 1.00.00 * @since 2.03.00 */ public interface CalendarModelConfiguration extends RaplaObject<CalendarModelConfiguration> { public static final RaplaType<CalendarModelConfiguration> TYPE = new RaplaType<CalendarModelConfiguration>(CalendarModelConfiguration.class, "calendar"); public static final TypedComponentRole<CalendarModelConfiguration> CONFIG_ENTRY = new TypedComponentRole<CalendarModelConfiguration>("org.rapla.DefaultSelection"); public static final TypedComponentRole<RaplaMap<CalendarModelConfiguration>> EXPORT_ENTRY = new TypedComponentRole<RaplaMap<CalendarModelConfiguration>>("org.rapla.plugin.autoexport"); public Date getStartDate(); public Date getEndDate(); public Date getSelectedDate(); public String getTitle(); public String getView(); public Collection<Entity> getSelected(); public Map<String,String> getOptionMap(); //public Configuration get public ClassificationFilter[] getFilter(); public boolean isDefaultEventTypes(); public boolean isDefaultResourceTypes(); public boolean isResourceRootSelected(); public CalendarModelConfiguration cloneWithNewOptions(Map<String, String> newMap); }
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.entities.configuration; import java.util.Map; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; /** * This Map can hold only Objects of type RaplaObject and String * (It cannot hold references to appointments or attributes) * @see RaplaObject */ public interface RaplaMap<T> extends RaplaObject, Map<String,T> { public static final RaplaType<RaplaMap> TYPE = new RaplaType<RaplaMap>(RaplaMap.class, "map"); }
Java