code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Component; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; public class RaplaPopupMenu extends JPopupMenu implements MenuInterface { private static final long serialVersionUID = 1L; public RaplaPopupMenu() { super(); } private int getIndexOfEntryWithId(String id) { int size = getComponentCount(); for ( int i=0;i< size;i++) { Component component = getComponent( i ); if ( component instanceof IdentifiableMenuEntry) { IdentifiableMenuEntry comp = (IdentifiableMenuEntry) component; if ( id != null && id.equals( comp.getId() ) ) { return i; } } } return -1; } public void removeAllBetween(String startId, String endId) { int startIndex = getIndexOfEntryWithId( startId ); int endIndex = getIndexOfEntryWithId( endId); if ( startIndex < 0 || endIndex < 0 ) return; for ( int i= startIndex + 1; i< endIndex ;i++) { remove( startIndex ); } } public void insertAfterId(Component component,String id) { if ( id == null) { add ( component ); } else { int index = getIndexOfEntryWithId( id ) ; insert( component, index +1); } } public void insertBeforeId(JComponent component,String id) { int index = getIndexOfEntryWithId( id ); insert( component, index); } public void remove( JMenuItem item ) { super.remove( item ); } }
04900db4-rob
src/org/rapla/gui/toolkit/RaplaPopupMenu.java
Java
gpl3
2,642
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.gui.toolkit; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JPanel; import org.rapla.components.layout.TableLayout; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; /** displays a wizard dialog with four buttons and a HTML help. */ public class WizardDialog extends DialogUI { private static final long serialVersionUID = 1L; protected WizardPanel wizardPanel; protected HTMLView helpView; static public String[] options = new String[] { WizardPanel.ABORT ,WizardPanel.PREV ,WizardPanel.NEXT ,WizardPanel.FINISH }; public static WizardDialog createWizard(RaplaContext sm,Component owner,boolean modal) throws RaplaException { WizardDialog dlg; Component topLevel = getOwnerWindow(owner); if (topLevel instanceof Dialog) dlg = new WizardDialog(sm,(Dialog)topLevel); else dlg = new WizardDialog(sm,(Frame)topLevel); dlg.init(modal); return dlg; } protected WizardDialog(RaplaContext sm,Dialog owner) throws RaplaException { super(sm,owner); } protected WizardDialog(RaplaContext sm,Frame owner) throws RaplaException { super(sm,owner); } private void init(boolean modal) { super.init(modal, new JPanel(), options); content.setLayout(new BorderLayout()); helpView = new HTMLView(); helpView.setBorder( BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(0,0,3,0) , BorderFactory.createCompoundBorder( BorderFactory.createEtchedBorder() ,BorderFactory.createEmptyBorder(4,4,4,4) ) ) ); helpView.setOpaque(true); content.add(helpView,BorderLayout.WEST); helpView.setPreferredSize(new Dimension(220,300)); packFrame=false; } protected JComponent createButtonPanel() { TableLayout tableLayout = new TableLayout(new double[][] { {10,0.2,10,0.2,5,0.4,10,0.2,10} ,{5,TableLayout.PREFERRED,5} }); JPanel jPanelButtons = new JPanel(); jPanelButtons.setLayout(tableLayout); jPanelButtons.add(buttons[0],"1,1,l,c"); jPanelButtons.add(buttons[1],"3,1,r,c"); jPanelButtons.add(buttons[2],"5,1,l,c"); jPanelButtons.add(buttons[3],"7,1"); return jPanelButtons; } public WizardPanel getActivePanel() { return wizardPanel; } public void start(WizardPanel newPanel) { if (!isVisible()) start(); if (wizardPanel != null) content.remove(wizardPanel.getComponent()); wizardPanel = newPanel; if (wizardPanel == null) close(); content.add(wizardPanel.getComponent(),BorderLayout.CENTER); wizardPanel.getComponent().setBorder(BorderFactory.createEmptyBorder(0,4,0,4)); if (wizardPanel.getHelp() != null) helpView.setBody(wizardPanel.getHelp()); String defaultAction = wizardPanel.getDefaultAction(); content.revalidate(); content.repaint(); // set actions ActionMap actionMap = wizardPanel.getActionMap(); getButton(0).setAction(actionMap.get(WizardPanel.ABORT)); getButton(0).setActionCommand(WizardPanel.ABORT); if (defaultAction.equals(WizardPanel.ABORT)) setDefault(0); getButton(1).setAction(actionMap.get(WizardPanel.PREV)); getButton(1).setActionCommand(WizardPanel.PREV); if (defaultAction.equals(WizardPanel.PREV)) setDefault(1); getButton(2).setAction(actionMap.get(WizardPanel.NEXT)); getButton(2).setActionCommand(WizardPanel.NEXT); if (defaultAction.equals(WizardPanel.NEXT)) setDefault(2); getButton(3).setAction(actionMap.get(WizardPanel.FINISH)); getButton(3).setActionCommand(WizardPanel.FINISH); if (defaultAction.equals(WizardPanel.FINISH)) setDefault(3); } }
04900db4-rob
src/org/rapla/gui/toolkit/WizardDialog.java
Java
gpl3
5,416
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Color; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Stack; import javax.swing.BorderFactory; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.rapla.components.util.Tools; /** Encapsulates the complex tree class and provides some basic functionality like * life model exchanging while keeping the Tree state or the integration of the popup listener. */ final public class RaplaTree extends JScrollPane { private static final long serialVersionUID = 1L; ArrayList<PopupListener> m_popupListeners = new ArrayList<PopupListener>(); ArrayList<ActionListener> m_doubleclickListeners = new ArrayList<ActionListener>(); ArrayList<ChangeListener> m_changeListeners = new ArrayList<ChangeListener>(); JTree jTree = new JTree() { private static final long serialVersionUID = 1L; public String getToolTipText(MouseEvent evt) { if (toolTipRenderer == null) { return super.getToolTipText(evt); } int row = getRowForLocation(evt.getX(),evt.getY()); if (row >=0) { return toolTipRenderer.getToolTipText(this,row); } return super.getToolTipText(evt); } public Point getToolTipLocation(MouseEvent evt) { return new Point(getWidth(), 0); } /** * Overwrite the standard method for performance reasons. * * @see javax.swing.JTree#getExpandedDescendants(javax.swing.tree.TreePath) */ // @Override // public Enumeration getExpandedDescendants(final TreePath parent) { // return null; // } }; Listener listener = new Listener(); private boolean treeSelectionListenerBlocked = false; private boolean bMultiSelect = false; TreePath selectedPath = null; TreeToolTipRenderer toolTipRenderer; public RaplaTree() { jTree.setBorder( BorderFactory.createEtchedBorder(Color.white,new Color(178, 178, 178))); jTree.setRootVisible(false); jTree.setShowsRootHandles(true); //jTree.putClientProperty("JTree.lineStyle", "None"); getViewport().add(jTree, null); jTree.addTreeSelectionListener( listener ); jTree.addMouseListener( listener ); setMultiSelect(bMultiSelect); } public void setToolTipRenderer(TreeToolTipRenderer renderer) { toolTipRenderer = renderer; } public void addChangeListener(ChangeListener listener) { m_changeListeners.add(listener); } public void removeChangeListener(ChangeListener listener) { m_changeListeners.remove(listener); } /** An ChangeEvent will be fired to every registered ChangeListener * when the selection has changed. */ protected void fireValueChanged() { if (m_changeListeners.size() == 0) return; ChangeListener[] listeners = getChangeListeners(); ChangeEvent evt = new ChangeEvent(this); for (int i = 0;i<listeners.length;i++) { listeners[i].stateChanged(evt); } } public ChangeListener[] getChangeListeners() { return m_changeListeners.toArray(new ChangeListener[]{}); } public TreeToolTipRenderer getToolTipRenderer() { return toolTipRenderer; } public void addDoubleclickListeners(ActionListener listener) { m_doubleclickListeners.add(listener); } public void removeDoubleclickListeners(ActionListener listener) { m_doubleclickListeners.remove(listener); } public ActionListener[] getDoubleclickListeners() { return m_doubleclickListeners.toArray(new ActionListener[]{}); } public void addPopupListener(PopupListener listener) { m_popupListeners.add(listener); } public void removePopupListener(PopupListener listener) { m_popupListeners.remove(listener); } public PopupListener[] getPopupListeners() { return m_popupListeners.toArray(new PopupListener[]{}); } /** An PopupEvent will be fired to every registered PopupListener * when the popup is selected */ protected void firePopup(MouseEvent me) { Point p = new Point(me.getX(), me.getY()); if (m_popupListeners.size() == 0) return; PopupListener[] listeners = getPopupListeners(); Object selectedObject = null; TreePath path = getTree().getPathForLocation(p.x,p.y); if (path != null) { Object node = path.getLastPathComponent(); if (node != null) { if (node instanceof DefaultMutableTreeNode) selectedObject = ((DefaultMutableTreeNode)node).getUserObject(); } } Point upperLeft = getViewport().getViewPosition(); Point newPoint = new Point(p.x - upperLeft.x + 10 ,p.y-upperLeft.y); PopupEvent evt = new PopupEvent(this, selectedObject, newPoint); for (int i = 0;i<listeners.length;i++) { listeners[i].showPopup(evt); } } protected void fireEdit(MouseEvent me) { Point p = new Point(me.getX(), me.getY()); if (m_doubleclickListeners.size() == 0) return; ActionListener[] listeners = getDoubleclickListeners(); Object selectedObject = null; TreePath path = getTree().getPathForLocation(p.x,p.y); if (path != null) { Object node = path.getLastPathComponent(); if (node != null) { if (node instanceof DefaultMutableTreeNode) { selectedObject = ((DefaultMutableTreeNode)node).getUserObject(); } } } if (selectedObject != null) { ActionEvent evt = new ActionEvent( selectedObject, ActionEvent.ACTION_PERFORMED, ""); for (int i = 0;i<listeners.length;i++) { listeners[i].actionPerformed(evt); } } } public JTree getTree() { return jTree; } class Listener implements MouseListener,TreeSelectionListener { public void valueChanged(TreeSelectionEvent event) { if ( event.getSource() == jTree && ! treeSelectionListenerBlocked) { selectedPath = event.getNewLeadSelectionPath(); fireValueChanged(); } } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public void mousePressed(MouseEvent me) { if (me.isPopupTrigger()) firePopup(me); } public void mouseReleased(MouseEvent me) { if (me.isPopupTrigger()) firePopup(me); } public void mouseClicked(MouseEvent me) { TreePath selectionPath = jTree.getSelectionPath(); if (me.getClickCount() == 2 && selectionPath != null ) { final Object lastPathComponent = selectionPath.getLastPathComponent(); if ( lastPathComponent instanceof TreeNode) { if (( (TreeNode) lastPathComponent).isLeaf()) { fireEdit(me); } } // System.out.println("mouse Clicked > 1"); // System.out.println("Button= " + me.getButton() + "Cliks= " + me.getClickCount() + " " + me.getComponent().getClass().getName()); } } } public void setEnabled(boolean enabled) { jTree.setEnabled(enabled); } private Object getFromNode(TreeNode node) { if (node == null) return null; return getObject(node); } private Object getLastSelectedElement() { if (selectedPath != null) { TreeNode node = (TreeNode) selectedPath.getLastPathComponent(); return getFromNode(node); } else { return null; } } private static Object getObject(Object treeNode) { try { if (treeNode == null) return null; if (treeNode instanceof DefaultMutableTreeNode) return ((DefaultMutableTreeNode) treeNode).getUserObject(); return treeNode.getClass().getMethod("getUserObject",Tools.EMPTY_CLASS_ARRAY).invoke(treeNode, Tools.EMPTY_ARRAY); } catch (Exception ex) { return null; } } public void exchangeTreeModel(TreeModel model) { boolean notifySelection; try { treeSelectionListenerBlocked = true; notifySelection = exchangeTreeModel( model, jTree ) ; } finally { treeSelectionListenerBlocked = false; } if ( notifySelection ) { this.fireValueChanged(); } } public void exchangeTreeModel2(TreeModel model) { try { treeSelectionListenerBlocked = true; jTree.setModel(model); } finally { treeSelectionListenerBlocked = false; } } /** Exchanges the tree-model while trying to preserve the selection an expansion state. * Returns if the selection has been affected by the excahnge.*/ public static boolean exchangeTreeModel(TreeModel model,JTree tree) { Collection<Object> expanded = new LinkedHashSet<Object>(); Collection<Object> selected = new LinkedHashSet<Object>(); int rowCount = tree.getRowCount(); for (int i=0;i<rowCount;i++) { if (tree.isExpanded(i)) { Object obj = getObject( tree.getPathForRow(i).getLastPathComponent() ); if (obj != null ) expanded.add( obj ); } if (tree.isRowSelected(i)) { Object obj = getObject( tree.getPathForRow(i).getLastPathComponent() ); if (obj != null ) selected.add( obj ); } } tree.setModel(model); if ( model instanceof DefaultTreeModel ) { ((DefaultTreeModel)model).reload(); } if (expanded.size() ==0 && selected.size() == 0) { TreeNode root = (TreeNode)model.getRoot(); if (root.getChildCount()<2) { tree.expandRow(0); } } ArrayList<TreePath> selectedList = new ArrayList<TreePath>(); for (int i=0;i<rowCount;i++) { TreePath treePath = tree.getPathForRow(i); if (treePath != null) { Object obj = getObject( treePath.getLastPathComponent() ); if (obj == null) continue; if (expanded.contains( obj )) { expanded.remove( obj ); tree.expandRow(i); } if (selected.contains( obj )) { selected.remove( obj ); selectedList.add(treePath); } } } tree.setSelectionPaths(selectedList.toArray(new TreePath[selectedList.size()])); return selectedList.size() != selected.size(); } public void setMultiSelect(boolean bMultiSelect) { this.bMultiSelect = bMultiSelect; if ( bMultiSelect) { jTree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); } else { jTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); } // end of else } public static class TreeIterator implements Iterator<TreeNode> { Stack<TreeNode> nodeStack = new Stack<TreeNode>(); public TreeIterator(TreeNode node) { nodeStack.push(node); } public boolean hasNext() { return !nodeStack.isEmpty(); } public TreeNode next() { TreeNode node = nodeStack.pop(); int count = node.getChildCount(); for (int i=count-1;i>=0;i--) { nodeStack.push(node.getChildAt(i)); } return node; } public void remove() { throw new UnsupportedOperationException(); } } private TreePath getPath(TreeNode node) { if (node.getParent() == null) return new TreePath(node); else return getPath(node.getParent()).pathByAddingChild(node); } public void select(Collection<Object> selectedObjects) { Collection<TreeNode> selectedNodes = new ArrayList<TreeNode>(); Collection<Object> selectedToRemove = new LinkedHashSet<Object>( ); selectedToRemove.addAll( selectedObjects); Iterator<TreeNode> it = new TreeIterator((TreeNode)jTree.getModel().getRoot()); while (it.hasNext()) { TreeNode node = it.next(); Object object = getObject(node); if (node != null && selectedToRemove.contains( object )) { selectedNodes.add(node); selectedToRemove.remove( object); } } TreePath[] path = new TreePath[selectedNodes.size()]; int i=0; it = selectedNodes.iterator(); while (it.hasNext()) { path[i] = getPath(it.next()); jTree.expandPath(path[i]); i++; } jTree.setSelectionPaths(path); } public Object getSelectedElement() { Collection<Object> col = getSelectedElements(); if ( col.size()>0) { return col.iterator().next(); } else { return null; } // end of else } public List<Object> getSelectedElements() { return getSelectedElements( false); } public List<Object> getSelectedElements(boolean includeChilds) { TreePath[] path = jTree.getSelectionPaths(); List<Object> list = new LinkedList<Object>(); if ( path == null) { return list; } for (TreePath p:path) { TreeNode node = (TreeNode) p.getLastPathComponent(); Object obj = getFromNode(node); if (obj != null) list.add(obj); if ( includeChilds ) { addChildNodeObjects(list, node); } } return list; } protected void addChildNodeObjects(List<Object> list, TreeNode node) { int childCount = node.getChildCount(); for ( int i = 0;i<childCount;i++) { TreeNode child = node.getChildAt( i); Object obj = getFromNode(child); if (obj != null) list.add(obj); addChildNodeObjects(list, child); } } public Object getInfoElement() { if ( bMultiSelect) { return getLastSelectedElement(); } else { return getSelectedElement(); } // end of else } public void unselectAll() { jTree.setSelectionInterval(-1,-1); } public void requestFocus() { jTree.requestFocus(); } public void expandAll() { int i = 0; while (i<jTree.getRowCount()) { jTree.expandRow(i); i++; } } }
04900db4-rob
src/org/rapla/gui/toolkit/RaplaTree.java
Java
gpl3
16,946
package org.rapla.gui.toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import org.rapla.framework.Disposable; /** Disposes an object on window close. Must be added as a WindowListener to the target window*/ final public class DisposingTool extends WindowAdapter { Disposable m_objectToDispose; public DisposingTool(Disposable objectToDispose) { m_objectToDispose = objectToDispose; } public void windowClosed(WindowEvent e) { m_objectToDispose.dispose(); } }
04900db4-rob
src/org/rapla/gui/toolkit/DisposingTool.java
Java
gpl3
531
package org.rapla.gui.toolkit; import javax.swing.JComboBox; import org.rapla.entities.Named; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaLocale; import org.rapla.gui.internal.common.NamedListCellRenderer; public final class RaplaListComboBox extends JComboBox { private static final long serialVersionUID = 1L; // copied the coe from tree table String cachedSearchKey = ""; RaplaContext context; public RaplaListComboBox(RaplaContext context) { init(context); } @SuppressWarnings("unchecked") public RaplaListComboBox(RaplaContext context,Object[] named) { super(named); init(context); } @SuppressWarnings("unchecked") public void init(RaplaContext context) { this.context = context; try { setRenderer(new NamedListCellRenderer(context.lookup(RaplaLocale.class).getLocale())); } catch (RaplaContextException e) { throw new IllegalStateException(e); } } protected boolean processKeyBinding(javax.swing.KeyStroke ks, java.awt.event.KeyEvent e, int condition, boolean pressed) { // live search in current parent node if ((Character.isLetterOrDigit(e.getKeyChar())) && ks.isOnKeyRelease()) { char keyChar = e.getKeyChar(); // search term String search = ("" + keyChar).toLowerCase(); // try to find node with matching searchterm plus the search before int nextIndexMatching = getNextIndexMatching(cachedSearchKey + search); // if we did not find anything, try to find search term only: restart! if (nextIndexMatching <0 ) { nextIndexMatching = getNextIndexMatching(search); cachedSearchKey = ""; } // if we found a node, select it, make it visible and return true if (nextIndexMatching >=0 ) { // store found treepath cachedSearchKey = cachedSearchKey + search; setSelectedIndex(nextIndexMatching); return true; } cachedSearchKey = ""; return true; } return super.processKeyBinding(ks,e,condition,pressed); } private int getNextIndexMatching(String string) { int i = 0; while ( i< getItemCount()) { Object item = getItemAt( i ); String toString; if ( item instanceof Named) { toString = ((Named) item).getName( getLocale()); } else if ( item != null) { toString = item.toString(); } else { toString = null; } if ( toString != null && toString.toLowerCase().startsWith( string.toLowerCase())) { return i; } i++; } return -1; } }
04900db4-rob
src/org/rapla/gui/toolkit/RaplaListComboBox.java
Java
gpl3
3,054
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import javax.swing.JMenuItem; public class RaplaMenuItem extends JMenuItem implements IdentifiableMenuEntry { private static final long serialVersionUID = 1L; String id; public RaplaMenuItem(String id) { super(); this.id = id; } public String getId() { return id; } public static RaplaMenuItem[] EMPTY_ARRAY = new RaplaMenuItem[] {}; public JMenuItem getMenuElement() { return this; } }
04900db4-rob
src/org/rapla/gui/toolkit/RaplaMenuItem.java
Java
gpl3
1,428
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Insets; import javax.swing.Action; import javax.swing.JButton; public class RaplaButton extends JButton { private static final long serialVersionUID = 1L; public static int SMALL= -1; public static int LARGE = 1; public static int DEFAULT = 0; private static Insets smallInsets = new Insets(0,0,0,0); private static Insets largeInsets = new Insets(5,10,5,10); public RaplaButton(String text,int style) { this(style); setText(text); } public RaplaButton(int style) { if (style == SMALL) { setMargin(smallInsets); } else if (style == LARGE) { setMargin(largeInsets); } else { setMargin(null); } } public void setAction(Action action) { String oldText = null; if (action.getValue(Action.NAME) == null) oldText = getText(); super.setAction(action); if (oldText != null) setText(oldText); } public RaplaButton() { } }
04900db4-rob
src/org/rapla/gui/toolkit/RaplaButton.java
Java
gpl3
2,010
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import javax.swing.ActionMap; public interface WizardPanel extends RaplaWidget { String NEXT = "next"; String ABORT = "abort"; String PREV = "prev"; String FINISH = "finish"; public ActionMap getActionMap(); public String getHelp(); public String getDefaultAction(); }
04900db4-rob
src/org/rapla/gui/toolkit/WizardPanel.java
Java
gpl3
1,269
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Cursor; /** All classes implementing this Interface must call FrameControllerList.addFrameController(this) on initialization FrameControllerList.removeFrameController(this) on close This Class is used for automated close of all Frames on Logout. */ public interface FrameController { void close(); // must call FrameControllerList.remove(this); void setCursor(Cursor cursor); }
04900db4-rob
src/org/rapla/gui/toolkit/FrameController.java
Java
gpl3
1,391
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import javax.swing.JTree; public interface TreeToolTipRenderer { public String getToolTipText(JTree table, int row); }
04900db4-rob
src/org/rapla/gui/toolkit/TreeToolTipRenderer.java
Java
gpl3
1,091
/** * */ package org.rapla.gui.toolkit; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Insets; import javax.swing.border.Border; public class EmptyLineBorder implements Border { Insets insets = new Insets(0,0,0,0); Color COLOR = Color.LIGHT_GRAY; public void paintBorder( Component c, Graphics g, int x, int y, int width, int height ) { g.setColor( COLOR ); g.drawLine(30,8, c.getWidth(), 8); } public Insets getBorderInsets( Component c ) { return insets; } public boolean isBorderOpaque() { return true; } }
04900db4-rob
src/org/rapla/gui/toolkit/EmptyLineBorder.java
Java
gpl3
639
/*--------------------------------------------------------------------------* | 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.gui.toolkit; import java.awt.Dimension; import java.awt.FontMetrics; import javax.swing.JEditorPane; /** #BUGFIX * This is a workaround for a bug in the Sun JDK * that don't calculate the correct size of an JEditorPane. * The first version of this workaround caused a NullPointerException * on JDK 1.2.2 sometimes, so this is a workaround for a workaround: * A zero-sized component is added to the StartFrame- Window * This component will be used to calculate the size of * the JEditorPane Components. */ final class JEditorPaneWorkaround { static public void packText(JEditorPane jText,String text,int width) { int height; if (width <=0 ) return; try { jText.setSize(new Dimension(width,100)); jText.setText(text); height = jText.getPreferredScrollableViewportSize().height; } catch ( NullPointerException e) { jText.setSize(new Dimension(width,100)); jText.setText(text); FontMetrics fm = jText.getFontMetrics(jText.getFont()); height = fm.stringWidth(text)/width * fm.getHeight() + 50; } // end of try-catch jText.setSize(new Dimension(width,height)); jText.setPreferredSize(new Dimension(width,height)); } }
04900db4-rob
src/org/rapla/gui/toolkit/JEditorPaneWorkaround.java
Java
gpl3
2,220
/*--------------------------------------------------------------------------* | 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.gui.toolkit; public interface PopupListener { public void showPopup(PopupEvent evt); }
04900db4-rob
src/org/rapla/gui/toolkit/PopupListener.java
Java
gpl3
1,047
/*--------------------------------------------------------------------------* | 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.gui; import org.rapla.entities.Named; import org.rapla.entities.configuration.Preferences; import org.rapla.framework.RaplaException; import org.rapla.gui.toolkit.RaplaWidget; public interface OptionPanel extends RaplaWidget, Named { void setPreferences(Preferences preferences); /** commits the changes in the option Dialog.*/ void commit() throws RaplaException; /** called when the option Panel is selected for displaying.*/ void show() throws RaplaException; }
04900db4-rob
src/org/rapla/gui/OptionPanel.java
Java
gpl3
1,451
package org.rapla.gui; import java.awt.Component; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaException; /** performs a check, if the reservation is entered correctly. An example of a reservation check is the conflict checker*/ public interface ReservationCheck { /** @param sourceComponent * @return true if the reservation check is successful and false if the save dialog should be aborted*/ boolean check(Reservation reservation, Component sourceComponent) throws RaplaException; }
04900db4-rob
src/org/rapla/gui/ReservationCheck.java
Java
gpl3
552
/*--------------------------------------------------------------------------* | 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.gui; import javax.swing.event.ChangeListener; import org.rapla.gui.toolkit.RaplaWidget; /** Base class for most rapla edit fields. Provides some mapping functionality such as reflection invocation of getters/setters. A fieldName "username" will result in a getUsername() and setUsername() method. */ public interface EditField extends RaplaWidget { public String getFieldName(); /** registers new ChangeListener for this component. * An ChangeEvent will be fired to every registered ChangeListener * when the component info changes. * @see javax.swing.event.ChangeListener * @see javax.swing.event.ChangeEvent */ public void addChangeListener(ChangeListener listener); /** removes a listener from this component.*/ public void removeChangeListener(ChangeListener listener); }
04900db4-rob
src/org/rapla/gui/EditField.java
Java
gpl3
1,793
<body> This is the base package of the GUI-client. Communication through the backend is done through the modules of <code>org.rapla.facade</code> package. The gui-client is normally started through the <code>RaplaClientService</code>. You can also plug-in your own components into the gui. </body>
04900db4-rob
src/org/rapla/gui/package.html
HTML
gpl3
301
package org.rapla.gui; import java.awt.Component; import org.rapla.entities.Entity; import org.rapla.framework.RaplaException; public interface EditController { <T extends Entity> EditComponent<T> createUI( T obj ) throws RaplaException; <T extends Entity> void edit( T obj, Component owner ) throws RaplaException; <T extends Entity> void editNew( T obj, Component owner ) throws RaplaException; <T extends Entity> void edit( T obj, String title, Component owner ) throws RaplaException; // neue Methoden zur Bearbeitung von mehreren gleichartigen Elementen (Entities-Array) // orientieren sich an den oberen beiden Methoden zur Bearbeitung von einem Element <T extends Entity> void edit( T[] obj, Component owner ) throws RaplaException; <T extends Entity> void edit( T[] obj, String title, Component owner ) throws RaplaException; }
04900db4-rob
src/org/rapla/gui/EditController.java
Java
gpl3
872
/*--------------------------------------------------------------------------* | 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.gui; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.swing.Action; import org.rapla.framework.RaplaContext; public abstract class RaplaAction extends RaplaGUIComponent implements Action { private Map<String,Object> values = new HashMap<String,Object>(); private ArrayList<PropertyChangeListener> listenerList = new ArrayList<PropertyChangeListener>(); public RaplaAction(RaplaContext sm) { super( sm ); setEnabled(true); } public Object getValue(String key) { return values.get(key); } public void putValue(String key,Object value) { Object oldValue = getValue(key); values.put(key,value); firePropertyChange(key,oldValue,value); } public void addPropertyChangeListener(PropertyChangeListener listener) { listenerList.add(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { listenerList.remove(listener); } protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { if (listenerList.size() == 0) return; if (oldValue == newValue) return; // if (oldValue != null && newValue != null && oldValue.equals(newValue)) //return; PropertyChangeEvent evt = new PropertyChangeEvent(this,propertyName,oldValue,newValue); PropertyChangeListener[] listeners = getPropertyChangeListeners(); for (int i = 0;i<listeners.length; i++) { listeners[i].propertyChange(evt); } } public PropertyChangeListener[] getPropertyChangeListeners() { return listenerList.toArray(new PropertyChangeListener[]{}); } public void setEnabled(boolean enabled) { putValue("enabled", new Boolean(enabled)); } public boolean isEnabled() { Boolean enabled = (Boolean)getValue("enabled"); return (enabled != null && enabled.booleanValue()); } }
04900db4-rob
src/org/rapla/gui/RaplaAction.java
Java
gpl3
3,047
package org.rapla.gui; import javax.swing.JPanel; import javax.swing.JTextField; import org.rapla.plugin.autoexport.AutoExportPlugin; public interface PublishExtension { JPanel getPanel(); /** can return null if no url status should be displayed */ JTextField getURLField(); void mapOptionTo(); /** returns if getAddress can be used to generate an address */ boolean hasAddressCreationStrategy(); /** returns the generated address */ String getAddress( String filename, String generator); /** returns the generator (pagename) for the file. * * For the htmlexport plugin for example is this AutoExportPlugin.CALENDAR_GENERATOR * @see AutoExportPlugin **/ String getGenerator(); }
04900db4-rob
src/org/rapla/gui/PublishExtension.java
Java
gpl3
730
/*--------------------------------------------------------------------------* | 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.gui; import java.util.List; import org.rapla.framework.RaplaException; import org.rapla.gui.toolkit.RaplaWidget; public interface EditComponent<T> extends RaplaWidget { /** maps all fields back to the current object.*/ public void mapToObjects() throws RaplaException; public List<T> getObjects(); public void setObjects(List<T> o) throws RaplaException; }
04900db4-rob
src/org/rapla/gui/EditComponent.java
Java
gpl3
1,331
package org.rapla.gui; import org.rapla.entities.RaplaObject; import org.rapla.gui.toolkit.RaplaMenuItem; public interface ObjectMenuFactory { RaplaMenuItem[] create(MenuContext menuContext,RaplaObject focusedObject); }
04900db4-rob
src/org/rapla/gui/ObjectMenuFactory.java
Java
gpl3
226
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla; import java.net.MalformedURLException; import java.net.URL; import org.rapla.components.util.IOUtil; import org.rapla.components.util.JNLPUtil; import org.rapla.framework.Configuration; import org.rapla.framework.RaplaException; import org.rapla.framework.StartupEnvironment; import org.rapla.framework.internal.ConfigTools; import org.rapla.framework.logger.ConsoleLogger; import org.rapla.framework.logger.Logger; final public class RaplaStartupEnvironment implements StartupEnvironment { private int startupMode = CONSOLE; //private LoadingProgress progressbar; private Logger bootstrapLogger = new ConsoleLogger( ConsoleLogger.LEVEL_WARN ); private URL configURL; private URL contextRootURL; private URL downloadURL; public Configuration getStartupConfiguration() throws RaplaException { return ConfigTools.createConfig( getConfigURL().toExternalForm() ); } public URL getConfigURL() throws RaplaException { if ( configURL != null ) { return configURL; } else { return ConfigTools.configFileToURL( null, "rapla.xconf" ); } } public Logger getBootstrapLogger() { return bootstrapLogger; } public void setStartupMode( int startupMode ) { this.startupMode = startupMode; } /* (non-Javadoc) * @see org.rapla.framework.IStartupEnvironment#getStartupMode() */ public int getStartupMode() { return startupMode; } public void setBootstrapLogger( Logger logger ) { bootstrapLogger = logger; } public void setConfigURL( URL configURL ) { this.configURL = configURL; } public URL getContextRootURL() throws RaplaException { if ( contextRootURL != null ) return contextRootURL; return IOUtil.getBase( getConfigURL() ); } public void setContextRootURL(URL contextRootURL) { this.contextRootURL = contextRootURL; } public URL getDownloadURL() throws RaplaException { if ( downloadURL != null ) { return downloadURL; } if ( startupMode == WEBSTART ) { try { return JNLPUtil.getCodeBase(); } catch ( Exception e ) { throw new RaplaException( e ); } } else { URL base = IOUtil.getBase( getConfigURL() ); if ( base != null) { return base; } try { return new URL( "http://localhost:8051" ); } catch ( MalformedURLException e ) { throw new RaplaException( "Invalid URL" ); } } } public void setDownloadURL( URL downloadURL ) { this.downloadURL = downloadURL; } }
04900db4-rob
src/org/rapla/RaplaStartupEnvironment.java
Java
gpl3
3,889
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.tempatewizard; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.TreeSet; import javax.swing.MenuElement; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Reservation; import org.rapla.facade.CalendarModel; import org.rapla.facade.ModificationEvent; import org.rapla.facade.ModificationListener; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.internal.edit.SaveUndo; import org.rapla.gui.toolkit.IdentifiableMenuEntry; import org.rapla.gui.toolkit.MenuScroller; import org.rapla.gui.toolkit.RaplaMenu; import org.rapla.gui.toolkit.RaplaMenuItem; /** This ReservationWizard displays no wizard and directly opens a ReservationEdit Window */ public class TemplateWizard extends RaplaGUIComponent implements IdentifiableMenuEntry, ActionListener, ModificationListener { Map<Component,String> componentMap = new HashMap<Component, String>(); Collection<String> templateNames; public TemplateWizard(RaplaContext context) throws RaplaException{ super(context); getUpdateModule().addModificationListener( this); updateTemplateNames(); } public String getId() { return "020_templateWizard"; } @Override public void dataChanged(ModificationEvent evt) throws RaplaException { if ( evt.getInvalidateInterval() != null) { updateTemplateNames(); } } private Collection<String> updateTemplateNames() throws RaplaException { return templateNames = getQuery().getTemplateNames(); } public MenuElement getMenuElement() { componentMap.clear(); boolean canCreateReservation = canCreateReservation(); MenuElement element; if (templateNames.size() == 0) { return null; } if ( templateNames.size() == 1) { RaplaMenuItem item = new RaplaMenuItem( getId()); item.setEnabled( canAllocate() && canCreateReservation); item.setText(getString("new_reservations_from_template")); item.setIcon( getIcon("icon.new")); item.addActionListener( this); String template = templateNames.iterator().next(); componentMap.put( item, template); element = item; } else { RaplaMenu item = new RaplaMenu( getId()); item.setEnabled( canAllocate() && canCreateReservation); item.setText(getString("new_reservations_from_template")); item.setIcon( getIcon("icon.new")); Set<String> templateSet = new TreeSet<String>(templateNames); SortedMap<String, Set<String>> keyGroup = new TreeMap<String, Set<String>>(); if ( templateSet.size() > 10) { for ( String string:templateSet) { if (string.length() == 0) { continue; } String firstChar = string.substring( 0,1); Set<String> group = keyGroup.get( firstChar); if ( group == null) { group = new TreeSet<String>(); keyGroup.put( firstChar, group); } group.add(string); } SortedMap<String, Set<String>> merged = merge( keyGroup); for ( String subMenuName: merged.keySet()) { RaplaMenu subMenu = new RaplaMenu( getId()); item.setIcon( getIcon("icon.new")); subMenu.setText( subMenuName); Set<String> set = merged.get( subMenuName); int maxItems = 20; if ( set.size() >= maxItems) { int millisToScroll = 40; MenuScroller.setScrollerFor( subMenu, maxItems , millisToScroll); } addTemplates(subMenu, set); item.add( subMenu); } } else { addTemplates( item, templateSet); } element = item; } return element; } public void addTemplates(RaplaMenu item, Set<String> templateSet) { for ( String templateName:templateSet) { RaplaMenuItem newItem = new RaplaMenuItem(templateName); componentMap.put( newItem, templateName); newItem.setText( templateName ); item.add( newItem); newItem.addActionListener( this); } } private SortedMap<String, Set<String>> merge( SortedMap<String, Set<String>> keyGroup) { SortedMap<String,Set<String>> result = new TreeMap<String, Set<String>>(); String beginnChar = null; String currentChar = null; Set<String> currentSet = null; for ( String key: keyGroup.keySet() ) { Set<String> set = keyGroup.get( key); if ( currentSet == null) { currentSet = new TreeSet<String>(); beginnChar = key; currentChar = key; } if ( !key.equals( currentChar)) { if ( set.size() + currentSet.size() > 10) { String storeKey; if ( beginnChar != null && !beginnChar.equals(currentChar)) { storeKey = beginnChar + "-" + currentChar; } else { storeKey = currentChar; } result.put( storeKey, currentSet); currentSet = new TreeSet<String>(); beginnChar = key; currentChar = key; } else { currentChar = key; } } currentSet.addAll( set); } String storeKey; if ( beginnChar != null) { if ( !beginnChar.equals(currentChar)) { storeKey = beginnChar + "-" + currentChar; } else { storeKey = currentChar; } result.put( storeKey, currentSet); } return result; } public void actionPerformed(ActionEvent e) { try { CalendarModel model = getService(CalendarModel.class); Date beginn = getStartDate( model); Object source = e.getSource(); String templateName = componentMap.get( source); List<Reservation> newReservations; Collection<Reservation> reservations = getQuery().getTemplateReservations(templateName); if (reservations.size() > 0) { newReservations = copy( reservations, beginn); Collection<Allocatable> markedAllocatables = model.getMarkedAllocatables(); if (markedAllocatables != null ) { for (Reservation event: newReservations) { if ( event.getAllocatables().length == 0) { for ( Allocatable alloc:markedAllocatables) { if (!event.hasAllocated(alloc)) { event.addAllocatable( alloc); } } } } } } else { showException(new EntityNotFoundException("Template " + templateName + " not found"), getMainComponent()); return; } if ( newReservations.size() == 1) { Reservation next = newReservations.iterator().next(); getReservationController().edit( next); } else { Collection<Reservation> list = new ArrayList<Reservation>(); for ( Reservation reservation:newReservations) { Reservation cast = reservation; User lastChangedBy = cast.getLastChangedBy(); if ( lastChangedBy != null && !lastChangedBy.equals(getUser())) { throw new RaplaException("Reservation " + cast + " has wrong user " + lastChangedBy); } list.add( cast); } SaveUndo<Reservation> saveUndo = new SaveUndo<Reservation>(getContext(), list, null); getModification().getCommandHistory().storeAndExecute( saveUndo); } } catch (RaplaException ex) { showException( ex, getMainComponent()); } } }
04900db4-rob
src/org/rapla/plugin/tempatewizard/TemplateWizard.java
Java
gpl3
8,599
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.tempatewizard; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; public class TempateWizardPlugin implements PluginDescriptor<ClientServiceContainer> { public static final String PLUGIN_CLASS = TempateWizardPlugin.class.getName(); public static boolean ENABLE_BY_DEFAULT = true; public void provideServices(ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent( RaplaClientExtensionPoints.RESERVATION_WIZARD_EXTENSION, TemplateWizard.class); } }
04900db4-rob
src/org/rapla/plugin/tempatewizard/TempateWizardPlugin.java
Java
gpl3
1,711
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.setowner; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.components.xmlbundle.impl.I18nBundleImpl; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.TypedComponentRole; public class SetOwnerPlugin implements PluginDescriptor<ClientServiceContainer> { public final static boolean ENABLE_BY_DEFAULT = false; public static final TypedComponentRole<I18nBundle> RESOURCE_FILE = new TypedComponentRole<I18nBundle>(SetOwnerPlugin.class.getPackage().getName() + ".SetOwnerResources"); public String toString() { return "Set Owner"; } public void provideServices(ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent( RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig( RESOURCE_FILE.getId() ) ); container.addContainerProvidedComponent( RaplaClientExtensionPoints.OBJECT_MENU_EXTENSION, SetOwnerMenuFactory.class); } }
04900db4-rob
src/org/rapla/plugin/setowner/SetOwnerPlugin.java
Java
gpl3
2,173
package org.rapla.plugin.setowner; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.TreeSet; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import org.rapla.entities.Entity; import org.rapla.entities.Named; import org.rapla.entities.NamedComparator; import org.rapla.entities.Ownable; import org.rapla.entities.RaplaObject; import org.rapla.entities.RaplaType; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.MenuContext; import org.rapla.gui.ObjectMenuFactory; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.TreeFactory; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.RaplaMenuItem; import org.rapla.gui.toolkit.RaplaTree; public class SetOwnerMenuFactory extends RaplaGUIComponent implements ObjectMenuFactory { public SetOwnerMenuFactory( RaplaContext context) { super( context ); setChildBundleName( SetOwnerPlugin.RESOURCE_FILE); } public RaplaMenuItem[] create( final MenuContext menuContext, final RaplaObject focusedObject ) { if (!isAdmin()) { return RaplaMenuItem.EMPTY_ARRAY; } Collection<Object> selectedObjects = new HashSet<Object>(); Collection<?> selected = menuContext.getSelectedObjects(); if ( selected.size() != 0) { selectedObjects.addAll( selected); } if ( focusedObject != null) { selectedObjects.add( focusedObject); } final Collection<Entity<? extends Entity>> ownables = new HashSet<Entity<? extends Entity>>(); for ( Object obj: selectedObjects) { final Entity<? extends Entity> ownable; if ( obj instanceof AppointmentBlock) { ownable = ((AppointmentBlock) obj).getAppointment().getReservation(); } else if ( obj instanceof Entity ) { RaplaType raplaType = ((RaplaObject)obj).getRaplaType(); if ( raplaType == Appointment.TYPE ) { Appointment appointment = (Appointment) obj; ownable = appointment.getReservation(); } else if ( raplaType == Reservation.TYPE) { ownable = (Reservation) obj; } else if ( raplaType == Allocatable.TYPE) { ownable = (Allocatable) obj; } else { ownable = null; } } else { ownable = null; } if ( ownable != null) { ownables.add( ownable); } } if ( ownables.size() == 0 ) { return RaplaMenuItem.EMPTY_ARRAY; } // create the menu entry final RaplaMenuItem setOwnerItem = new RaplaMenuItem("SETOWNER"); setOwnerItem.setText(getI18n().getString("changeowner")); setOwnerItem.setIcon(getI18n().getIcon("icon.tree.persons")); setOwnerItem.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { User newOwner = showAddDialog(); if(newOwner != null) { ArrayList<Entity<?>> toStore = new ArrayList<Entity<?>>(); for ( Entity<? extends Entity> ownable: ownables) { Entity<?> editableOwnables = getClientFacade().edit( ownable); Ownable casted = (Ownable)editableOwnables; casted.setOwner(newOwner); toStore.add( editableOwnables); } //((SimpleEntity) editableEvent).setLastChangedBy(newOwner); getClientFacade().storeObjects( toStore.toArray( Entity.ENTITY_ARRAY) ); } } catch (RaplaException ex ) { showException( ex, menuContext.getComponent()); } } }); return new RaplaMenuItem[] {setOwnerItem }; } final private TreeFactory getTreeFactory() { return getService(TreeFactory.class); } private User showAddDialog() throws RaplaException { final DialogUI dialog; RaplaTree treeSelection = new RaplaTree(); treeSelection.setMultiSelect(true); treeSelection.getTree().setCellRenderer(getTreeFactory().createRenderer()); DefaultMutableTreeNode userRoot = new DefaultMutableTreeNode("ROOT"); //DefaultMutableTreeNode userRoot = TypeNode(User.TYPE, getString("users")); User[] userList = getQuery().getUsers(); for (final User user: sorted(userList)) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(); node.setUserObject( user ); userRoot.add(node); } treeSelection.exchangeTreeModel(new DefaultTreeModel(userRoot)); treeSelection.setMinimumSize(new java.awt.Dimension(300, 200)); treeSelection.setPreferredSize(new java.awt.Dimension(400, 260)); dialog = DialogUI.create( getContext() ,getMainComponent() ,true ,treeSelection ,new String[] { getString("apply"),getString("cancel")}); dialog.setTitle(getI18n().getString("changeownerto")); dialog.getButton(0).setEnabled(false); final JTree tree = treeSelection.getTree(); tree.addMouseListener(new MouseAdapter() { // End dialog when a leaf is double clicked public void mousePressed(MouseEvent e) { TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); if (selPath != null && e.getClickCount() == 2) { final Object lastPathComponent = selPath.getLastPathComponent(); if (((TreeNode) lastPathComponent).isLeaf() ) { dialog.getButton(0).doClick(); return; } } else if (selPath != null && e.getClickCount() == 1) { final Object lastPathComponent = selPath.getLastPathComponent(); if (((TreeNode) lastPathComponent).isLeaf() ) { dialog.getButton(0).setEnabled(true); return; } } tree.removeSelectionPath(selPath); } }); dialog.start(); if (dialog.getSelectedIndex() == 1) { return null; } return (User) treeSelection.getSelectedElement(); } private <T extends Named> Collection<T> sorted(T[] allocatables) { TreeSet<T> sortedList = new TreeSet<T>(new NamedComparator<T>(getLocale())); sortedList.addAll(Arrays.asList(allocatables)); return sortedList; } }
04900db4-rob
src/org/rapla/plugin/setowner/SetOwnerMenuFactory.java
Java
gpl3
7,505
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.dayresource; import java.awt.Point; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.JComponent; import javax.swing.JLabel; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.CalendarView; import org.rapla.components.calendarview.swing.AbstractSwingCalendar; import org.rapla.components.calendarview.swing.SelectionHandler.SelectionStrategy; import org.rapla.components.calendarview.swing.SwingWeekView; import org.rapla.components.calendarview.swing.ViewListener; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.AbstractRaplaBlock; import org.rapla.plugin.abstractcalendar.GroupAllocatablesStrategy; import org.rapla.plugin.abstractcalendar.RaplaBuilder; import org.rapla.plugin.abstractcalendar.RaplaCalendarViewListener; import org.rapla.plugin.weekview.SwingDayCalendar; public class SwingDayResourceCalendar extends SwingDayCalendar { public SwingDayResourceCalendar( RaplaContext sm, CalendarModel model, boolean editable ) throws RaplaException { super( sm, model, editable ); } protected AbstractSwingCalendar createView(boolean showScrollPane) { /** renderer for dates in weekview */ SwingWeekView wv = new SwingWeekView( showScrollPane ) { { selectionHandler.setSelectionStrategy(SelectionStrategy.BLOCK); } @Override protected JComponent createSlotHeader(Integer column) { JLabel component = (JLabel) super.createSlotHeader(column); try { List<Allocatable> sortedAllocatables = getSortedAllocatables(); Allocatable allocatable = sortedAllocatables.get(column); String name = allocatable.getName( getLocale()); component.setText( name); component.setToolTipText(name); } catch (RaplaException e) { } return component; } @Override protected int getColumnCount() { try { Allocatable[] selectedAllocatables =model.getSelectedAllocatables(); return selectedAllocatables.length; } catch (RaplaException e) { return 0; } } @Override public void rebuild() { super.rebuild(); String dateText = getRaplaLocale().formatDateShort(getStartDate()); weekTitle.setText( dateText); } }; return wv; } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = super.createBuilder(); builder.setSplitByAllocatables( true ); final List<Allocatable> allocatables = getSortedAllocatables(); builder.selectAllocatables(allocatables); GroupAllocatablesStrategy strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ) { @Override protected Map<Block, Integer> getBlockMap(CalendarView wv, List<Block> blocks) { if (allocatables != null) { Map<Block,Integer> map = new LinkedHashMap<Block, Integer>(); for (Block block:blocks) { int index = getIndex(allocatables, block); if ( index >= 0 ) { map.put( block, index ); } } return map; } else { return super.getBlockMap(wv, blocks); } } }; strategy.setResolveConflictsEnabled( true ); builder.setBuildStrategy( strategy ); return builder; } protected ViewListener createListener() throws RaplaException { return new RaplaCalendarViewListener(getContext(), model, view.getComponent()) { @Override protected Collection<Allocatable> getMarkedAllocatables() { final List<Allocatable> selectedAllocatables = getSortedAllocatables(); Set<Allocatable> allSelected = new HashSet<Allocatable>(); if ( selectedAllocatables.size() == 1 ) { allSelected.add(selectedAllocatables.get(0)); } for ( int i =0 ;i< selectedAllocatables.size();i++) { if ( view.isSelected(i)) { allSelected.add(selectedAllocatables.get(i)); } } return allSelected; } @Override public void moved(Block block, Point p, Date newStart, int slotNr) { int column= slotNr;//getIndex( selectedAllocatables, block ); if ( column < 0) { return; } try { final List<Allocatable> selectedAllocatables = getSortedAllocatables(); Allocatable newAlloc = selectedAllocatables.get(column); AbstractRaplaBlock raplaBlock = (AbstractRaplaBlock)block; Allocatable oldAlloc = raplaBlock.getGroupAllocatable(); if ( newAlloc != null && oldAlloc != null && !newAlloc.equals(oldAlloc)) { AppointmentBlock appointmentBlock= raplaBlock.getAppointmentBlock(); getReservationController().exchangeAllocatable(appointmentBlock, oldAlloc,newAlloc,newStart, getMainComponent(),p); } else { super.moved(block, p, newStart, slotNr); } } catch (RaplaException ex) { showException(ex, getMainComponent()); } } }; } private int getIndex(final List<Allocatable> allocatables, Block block) { AbstractRaplaBlock b = (AbstractRaplaBlock)block; Allocatable a = b.getGroupAllocatable(); int index = a != null ? allocatables.indexOf( a ) : -1; return index; } }
04900db4-rob
src/org/rapla/plugin/dayresource/SwingDayResourceCalendar.java
Java
gpl3
7,137
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.dayresource; import javax.swing.Icon; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.SwingCalendarView; import org.rapla.gui.SwingViewFactory; import org.rapla.gui.images.Images; public class DayResourceViewFactory extends RaplaComponent implements SwingViewFactory { public DayResourceViewFactory( RaplaContext context ) { super( context ); } public final static String DAY_RESOURCE_VIEW = "day_resource"; public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException { return new SwingDayResourceCalendar( context, model, editable); } public String getViewId() { return DAY_RESOURCE_VIEW; } public String getName() { return getString(DAY_RESOURCE_VIEW); } Icon icon; public Icon getIcon() { if ( icon == null) { icon = Images.getIcon("/org/rapla/plugin/dayresource/images/day_resource.png"); } return icon; } public String getMenuSortKey() { return "A"; } }
04900db4-rob
src/org/rapla/plugin/dayresource/DayResourceViewFactory.java
Java
gpl3
2,186
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.dayresource; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; public class DayResourceViewPlugin implements PluginDescriptor<ClientServiceContainer> { final public static boolean ENABLE_BY_DEFAULT = true; public void provideServices(ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,DayResourceViewFactory.class); } }
04900db4-rob
src/org/rapla/plugin/dayresource/DayResourceViewPlugin.java
Java
gpl3
1,637
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.dayresource.server; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory; import org.rapla.servletpages.RaplaPageGenerator; public class DayResourceHTMLViewFactory extends RaplaComponent implements HTMLViewFactory { public DayResourceHTMLViewFactory( RaplaContext context ) { super( context ); } public final static String DAY_RESOURCE_VIEW = "day_resource"; public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) throws RaplaException { return new HTMLDayResourcePage( context, model); } public String getViewId() { return DAY_RESOURCE_VIEW; } public String getName() { return getString(DAY_RESOURCE_VIEW); } }
04900db4-rob
src/org/rapla/plugin/dayresource/server/DayResourceHTMLViewFactory.java
Java
gpl3
1,872
package org.rapla.plugin.dayresource.server; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.CalendarView; import org.rapla.components.calendarview.html.AbstractHTMLView; import org.rapla.components.calendarview.html.HTMLWeekView; import org.rapla.entities.domain.Allocatable; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.AbstractRaplaBlock; import org.rapla.plugin.abstractcalendar.GroupAllocatablesStrategy; import org.rapla.plugin.abstractcalendar.RaplaBuilder; import org.rapla.plugin.weekview.server.HTMLDayViewPage; public class HTMLDayResourcePage extends HTMLDayViewPage { public HTMLDayResourcePage(RaplaContext context, CalendarModel calendarModel) { super(context, calendarModel); } protected AbstractHTMLView createCalendarView() { HTMLWeekView weekView = new HTMLWeekView(){ @Override protected String createColumnHeader(int i) { try { Allocatable allocatable = getSortedAllocatables().get(i); return allocatable.getName( getLocale()); } catch (RaplaException e) { return ""; } } @Override protected int getColumnCount() { try { Allocatable[] selectedAllocatables =model.getSelectedAllocatables(); return selectedAllocatables.length; } catch (RaplaException e) { return 0; } } public void rebuild() { setWeeknumber(getRaplaLocale().formatDateShort(getStartDate())); super.rebuild(); } }; return weekView; } private int getIndex(final List<Allocatable> allocatables, Block block) { AbstractRaplaBlock b = (AbstractRaplaBlock)block; Allocatable a = b.getGroupAllocatable(); int index = a != null ? allocatables.indexOf( a ) : -1; return index; } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = super.createBuilder(); final List<Allocatable> allocatables = getSortedAllocatables(); builder.setSplitByAllocatables( true ); builder.selectAllocatables(allocatables); GroupAllocatablesStrategy strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ) { @Override protected Map<Block, Integer> getBlockMap(CalendarView wv, List<Block> blocks) { if (allocatables != null) { Map<Block,Integer> map = new LinkedHashMap<Block, Integer>(); for (Block block:blocks) { int index = getIndex(allocatables, block); if ( index >= 0 ) { map.put( block, index ); } } return map; } else { return super.getBlockMap(wv, blocks); } } }; strategy.setResolveConflictsEnabled( true ); builder.setBuildStrategy( strategy ); return builder; } }
04900db4-rob
src/org/rapla/plugin/dayresource/server/HTMLDayResourcePage.java
Java
gpl3
3,507
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.dayresource.server; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.plugin.dayresource.DayResourceViewPlugin; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.server.ServerServiceContainer; public class DayResourceViewServerPlugin implements PluginDescriptor<ServerServiceContainer> { public void provideServices(ServerServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", DayResourceViewPlugin.ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,DayResourceHTMLViewFactory.class); } }
04900db4-rob
src/org/rapla/plugin/dayresource/server/DayResourceViewServerPlugin.java
Java
gpl3
1,681
package org.rapla.plugin.autoexport; import java.awt.BorderLayout; import java.util.Locale; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import org.rapla.components.layout.TableLayout; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.DefaultPluginOption; public class AutoExportPluginOption extends DefaultPluginOption { JCheckBox booleanField = new JCheckBox(); // public AutoExportPluginOption( RaplaContext sm ) { super( sm ); } protected JPanel createPanel() throws RaplaException { JPanel panel = super.createPanel(); JPanel content = new JPanel(); double[][] sizes = new double[][] { {5,TableLayout.PREFERRED, 5,TableLayout.FILL,5} ,{TableLayout.PREFERRED,5,TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED} }; TableLayout tableLayout = new TableLayout(sizes); content.setLayout(tableLayout); content.add(new JLabel("Show list of exported calendars im HTML Menu"), "1,4"); content.add(booleanField,"3,4"); panel.add( content, BorderLayout.CENTER); return panel; } protected void addChildren( DefaultConfiguration newConfig) { newConfig.setAttribute( AutoExportPlugin.SHOW_CALENDAR_LIST_IN_HTML_MENU, booleanField.isSelected() ); } protected void readConfig( Configuration config) { booleanField.setSelected( config.getAttributeAsBoolean(AutoExportPlugin.SHOW_CALENDAR_LIST_IN_HTML_MENU, false)); } public Class<? extends PluginDescriptor<?>> getPluginClass() { return AutoExportPlugin.class; } @Override public String getName(Locale locale) { return "HTML Export Plugin"; } }
04900db4-rob
src/org/rapla/plugin/autoexport/AutoExportPluginOption.java
Java
gpl3
1,991
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.autoexport; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.components.xmlbundle.impl.I18nBundleImpl; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.RaplaMap; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContextException; import org.rapla.framework.TypedComponentRole; public class AutoExportPlugin implements PluginDescriptor<ClientServiceContainer> { public static final String CALENDAR_GENERATOR = "calendar"; public static final TypedComponentRole<I18nBundle> AUTOEXPORT_PLUGIN_RESOURCE = new TypedComponentRole<I18nBundle>( AutoExportPlugin.class.getPackage().getName() + ".AutoExportResources"); public static final TypedComponentRole<RaplaMap<CalendarModelConfiguration>> PLUGIN_ENTRY = CalendarModelConfiguration.EXPORT_ENTRY; public static final String HTML_EXPORT= PLUGIN_ENTRY + ".selected"; public static final String SHOW_CALENDAR_LIST_IN_HTML_MENU = "show_calendar_list_in_html_menu"; public static final boolean ENABLE_BY_DEFAULT = true; public void provideServices(ClientServiceContainer container, Configuration config) throws RaplaContextException { container.addContainerProvidedComponent( AUTOEXPORT_PLUGIN_RESOURCE, I18nBundleImpl.class, I18nBundleImpl.createConfig( AUTOEXPORT_PLUGIN_RESOURCE.getId() ) ); container.addContainerProvidedComponent( RaplaClientExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION, AutoExportPluginOption.class); if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent( RaplaClientExtensionPoints.PUBLISH_EXTENSION_OPTION, HTMLPublicExtensionFactory.class); } }
04900db4-rob
src/org/rapla/plugin/autoexport/AutoExportPlugin.java
Java
gpl3
2,857
package org.rapla.plugin.autoexport; import java.beans.PropertyChangeListener; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.PublishExtension; import org.rapla.gui.PublishExtensionFactory; public class HTMLPublicExtensionFactory extends RaplaComponent implements PublishExtensionFactory { public HTMLPublicExtensionFactory(RaplaContext context) { super(context); } public PublishExtension creatExtension(CalendarSelectionModel model,PropertyChangeListener revalidateCallback) throws RaplaException { return new HTMLPublishExtension(getContext(), model); } }
04900db4-rob
src/org/rapla/plugin/autoexport/HTMLPublicExtensionFactory.java
Java
gpl3
741
package org.rapla.plugin.autoexport.server; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.framework.RaplaContext; import org.rapla.plugin.autoexport.AutoExportPlugin; import org.rapla.servletpages.DefaultHTMLMenuEntry; public class ExportMenuEntry extends DefaultHTMLMenuEntry { public ExportMenuEntry(RaplaContext context) { super(context); } @Override public String getName() { I18nBundle i18n = getService( AutoExportPlugin.AUTOEXPORT_PLUGIN_RESOURCE ); return i18n.getString( "calendar_list"); } @Override public String getLinkName() { return "rapla?page=calendarlist"; } }
04900db4-rob
src/org/rapla/plugin/autoexport/server/ExportMenuEntry.java
Java
gpl3
653
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.autoexport.server; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.rapla.components.util.IOUtil; import org.rapla.components.util.ParseDateException; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.facade.CalendarNotFoundExeption; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory; import org.rapla.plugin.autoexport.AutoExportPlugin; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.servletpages.RaplaPageGenerator; /******* USAGE: ************ * ReadOnly calendarview view. * You will need the autoexport plugin to create a calendarview-view. * * Call: * rapla?page=calendar&user=<username>&file=<export_name> * * Optional Parameters: * * &hide_nav: will hide the navigation bar. * &day=<day>: int-value of the day of month that should be displayed * &month=<month>: int-value of the month * &year=<year>: int-value of the year * &today: will set the view to the current day. Ignores day, month and year */ public class CalendarPageGenerator extends RaplaComponent implements RaplaPageGenerator { private Map<String,HTMLViewFactory> factoryMap = new HashMap<String, HTMLViewFactory>(); public CalendarPageGenerator(RaplaContext context) throws RaplaContextException { super(context); for (HTMLViewFactory fact: getContainer().lookupServicesFor(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION)) { String id = fact.getViewId(); factoryMap.put( id , fact); } } public void generatePage( ServletContext servletContext, HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException { try { String username = request.getParameter( "user" ); String filename = request.getParameter( "file" ); CalendarSelectionModel model = null; User user; try { user = getQuery().getUser( username ); } catch (EntityNotFoundException ex) { String message = "404 Calendar not availabe " + username +"/" + filename ; write404(response, message); getLogger().getChildLogger("html.404").warn("404 User not found "+ username); return; } try { model = getModification().newCalendarModel( user ); model.load(filename); } catch (CalendarNotFoundExeption ex) { String message = "404 Calendar not availabe " + user +"/" + filename ; write404(response, message); return; } String allocatableId = request.getParameter( "allocatable_id" ); if ( allocatableId != null) { Allocatable[] selectedAllocatables = model.getSelectedAllocatables(); Allocatable foundAlloc = null; for ( Allocatable alloc:selectedAllocatables) { if (alloc.getId().equals( allocatableId)) { foundAlloc = alloc; break; } } if ( foundAlloc != null) { model.setSelectedObjects( Collections.singleton(foundAlloc)); request.setAttribute("allocatable_id", allocatableId); } else { String message = "404 allocatable with id '" + allocatableId + "' not found for calendar " + user + "/" + filename ; write404(response, message); return; } } final Object isSet = model.getOption(AutoExportPlugin.HTML_EXPORT); if( isSet == null || isSet.equals("false")) { String message = "404 Calendar not published " + username + "/" + filename ; write404(response, message); return; } final String viewId = model.getViewId(); HTMLViewFactory factory = getFactory(viewId); if ( factory != null ) { RaplaPageGenerator currentView = factory.createHTMLView( getContext(), model ); if ( currentView != null ) { try { currentView.generatePage( servletContext, request, response ); } catch ( ServletException ex) { Throwable cause = ex.getCause(); if ( cause instanceof ParseDateException) { write404( response, cause.getMessage() + " in calendar " + user + "/" + filename); } else { throw ex; } } } else { write404( response, "No view available for calendar " + user + "/" + filename + ". Rapla has currently no html support for the view with the id '" + viewId + "'." ); } } else { writeError( response, "No view available for exportfile '" + filename + "'. Please install and select the plugin for " + viewId ); } } catch ( Exception ex ) { writeStacktrace(response, ex); throw new ServletException( ex ); } } protected HTMLViewFactory getFactory(final String viewId) { return factoryMap.get( viewId ); } private void writeStacktrace(HttpServletResponse response, Exception ex) throws IOException { response.setContentType( "text/html; charset=" + getRaplaLocale().getCharsetNonUtf() ); java.io.PrintWriter out = response.getWriter(); out.println( IOUtil.getStackTraceAsString( ex ) ); out.close(); } protected void write404(HttpServletResponse response, String message) throws IOException { response.setStatus( 404 ); response.getWriter().print(message); getLogger().getChildLogger("html.404").warn( message); response.getWriter().close(); } private void writeError( HttpServletResponse response, String message ) throws IOException { response.setStatus( 500 ); response.setContentType( "text/html; charset=" + getRaplaLocale().getCharsetNonUtf() ); java.io.PrintWriter out = response.getWriter(); out.println( message ); out.close(); } }
04900db4-rob
src/org/rapla/plugin/autoexport/server/CalendarPageGenerator.java
Java
gpl3
8,177
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.autoexport.server; import org.rapla.components.xmlbundle.impl.I18nBundleImpl; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContextException; import org.rapla.plugin.autoexport.AutoExportPlugin; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.server.ServerServiceContainer; public class AutoExportServerPlugin implements PluginDescriptor<ServerServiceContainer> { public void provideServices(ServerServiceContainer container, Configuration config) throws RaplaContextException { container.addContainerProvidedComponent( AutoExportPlugin.AUTOEXPORT_PLUGIN_RESOURCE, I18nBundleImpl.class, I18nBundleImpl.createConfig( AutoExportPlugin.AUTOEXPORT_PLUGIN_RESOURCE.getId() ) ); if ( !config.getAttributeAsBoolean("enabled", AutoExportPlugin.ENABLE_BY_DEFAULT) ) return; container.addWebpage(AutoExportPlugin.CALENDAR_GENERATOR,CalendarPageGenerator.class); //RaplaResourcePageGenerator resourcePageGenerator = container.getContext().lookup(RaplaResourcePageGenerator.class); // registers the standard calendar files //resourcePageGenerator.registerResource( "calendar.css", "text/css", this.getClass().getResource("/org/rapla/plugin/autoexport/server/calendar.css")); // look if we should add a menu entry of exported lists if (config.getAttributeAsBoolean(AutoExportPlugin.SHOW_CALENDAR_LIST_IN_HTML_MENU, false)) { container.addWebpage("calendarlist",CalendarListPageGenerator.class); container.addContainerProvidedComponent( RaplaServerExtensionPoints.HTML_MAIN_MENU_EXTENSION_POINT, ExportMenuEntry.class); } } }
04900db4-rob
src/org/rapla/plugin/autoexport/server/AutoExportServerPlugin.java
Java
gpl3
2,692
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.autoexport.server; import java.io.IOException; import java.net.URLEncoder; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.TreeSet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.rapla.RaplaMainContainer; import org.rapla.components.util.IOUtil; import org.rapla.entities.User; import org.rapla.entities.configuration.CalendarModelConfiguration; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.RaplaMap; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.plugin.autoexport.AutoExportPlugin; import org.rapla.servletpages.RaplaPageGenerator; public class CalendarListPageGenerator extends RaplaComponent implements RaplaPageGenerator { public CalendarListPageGenerator( RaplaContext context ) { super( context ); setChildBundleName( AutoExportPlugin.AUTOEXPORT_PLUGIN_RESOURCE ); } public void generatePage( ServletContext servletContext, HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException { java.io.PrintWriter out = response.getWriter(); try { String username = request.getParameter( "user" ); response.setContentType("text/html; charset=" + getRaplaLocale().getCharsetNonUtf() ); User[] users = getQuery().getUsers(); Set<User> sortedUsers =new TreeSet<User>( Arrays.asList( users)); if ( username != null) { users = new User[] { getQuery().getUser( username )}; } String calendarName = getQuery().getSystemPreferences().getEntryAsString(RaplaMainContainer.TITLE, getString("rapla.title")); out.println( "<html>" ); out.println( "<head>" ); out.println( "<title>" + calendarName + "</title>" ); out.println( "</head>" ); out.println( "<body>" ); out.println( "<h2>" + getString("webserver") + ": " + calendarName + "</h2>"); for (User user : sortedUsers) { Preferences preferences = getQuery().getPreferences( user ); LinkedHashMap<String, CalendarModelConfiguration> completeMap = new LinkedHashMap<String, CalendarModelConfiguration>(); CalendarModelConfiguration defaultConf = preferences.getEntry( CalendarModelConfiguration.CONFIG_ENTRY ); if ( defaultConf != null) { completeMap.put( getString("default"), defaultConf); } final RaplaMap<CalendarModelConfiguration> raplaMap = preferences.getEntry( AutoExportPlugin.PLUGIN_ENTRY ); if ( raplaMap != null) { for ( Map.Entry<String, CalendarModelConfiguration> entry: raplaMap.entrySet()) { CalendarModelConfiguration value = entry.getValue(); completeMap.put(entry.getKey(),value); } } SortedMap<String,CalendarModelConfiguration> sortedMap = new TreeMap<String,CalendarModelConfiguration>( new TitleComparator( completeMap)); sortedMap.putAll( completeMap); Iterator<Map.Entry<String, CalendarModelConfiguration>> it = sortedMap.entrySet().iterator(); int count =0; while ( it.hasNext()) { Map.Entry<String,CalendarModelConfiguration> entry = it.next(); String key = entry.getKey(); CalendarModelConfiguration conf = entry.getValue(); final Object isSet = conf.getOptionMap().get(AutoExportPlugin.HTML_EXPORT); if( isSet != null && isSet.equals("false")) { it.remove(); continue; } if(count == 0) { String userName = user.getName(); if(username == null || userName.trim().length() ==0) userName = user.getUsername(); out.println( "<h3>" + userName + "</h3>" ); //BJO out.println( "<ul>" ); } count++; String title = getTitle(key, conf); String filename =URLEncoder.encode( key, "UTF-8" ); out.print( "<li>" ); out.print( "<a href=\"?page=calendar&user=" + user.getUsername() + "&file=" + filename + "&details=*" + "&folder=true" + "\">"); out.print( title); out.print( "</a>" ); out.println( "</li>" ); } if (count > 0) { out.println( "</ul>" ); } } out.println( "</body>" ); out.println( "</html>" ); } catch ( Exception ex ) { out.println( IOUtil.getStackTraceAsString( ex ) ); throw new ServletException( ex ); } finally { out.close(); } } private String getTitle(String key, CalendarModelConfiguration conf) { String title = conf.getTitle() ; if ( title == null || title.trim().length() == 0) { title = key; } return title; } class TitleComparator implements Comparator<String> { Map<String,CalendarModelConfiguration> base; public TitleComparator(Map<String,CalendarModelConfiguration> base) { this.base = base; } public int compare(String a, String b) { final String title1 = getTitle(a,base.get(a)); final String title2 = getTitle(b,base.get(b)); int result = title1.compareToIgnoreCase( title2); if ( result != 0) { return result; } return a.compareToIgnoreCase( b); } } }
04900db4-rob
src/org/rapla/plugin/autoexport/server/CalendarListPageGenerator.java
Java
gpl3
7,470
package org.rapla.plugin.autoexport; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.rapla.components.layout.TableLayout; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarSelectionModel; import org.rapla.framework.RaplaContext; import org.rapla.gui.PublishExtension; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.toolkit.RaplaButton; class HTMLPublishExtension extends RaplaGUIComponent implements PublishExtension { JPanel panel = new JPanel(); CalendarSelectionModel model; final JCheckBox showNavField; final JCheckBox saveSelectedDateField; final JTextField htmlURL; final JCheckBox checkbox; final JTextField titleField; final JPanel statusHtml; final JCheckBox onlyAllocationInfoField; public HTMLPublishExtension(RaplaContext context,CalendarSelectionModel model) { super(context); setChildBundleName( AutoExportPlugin.AUTOEXPORT_PLUGIN_RESOURCE); this.model = model; panel.setLayout(new TableLayout( new double[][] {{TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.FILL}, {TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.PREFERRED, 5, TableLayout.PREFERRED }})); titleField = new JTextField(20); addCopyPaste(titleField); showNavField = new JCheckBox(); saveSelectedDateField = new JCheckBox(); onlyAllocationInfoField = new JCheckBox(); htmlURL = new JTextField(); checkbox = new JCheckBox("HTML " + getString("publish")); statusHtml = createStatus( htmlURL); panel.add(checkbox,"0,0"); checkbox.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { updateCheck(); } }); panel.add(new JLabel(getString("weekview.print.title_textfield") +":"),"2,2"); panel.add( titleField, "4,2"); panel.add(new JLabel(getString("show_navigation")),"2,4"); panel.add( showNavField, "4,4"); String dateString = getRaplaLocale().formatDate(model.getSelectedDate()); panel.add(new JLabel(getI18n().format("including_date",dateString)),"2,6"); panel.add( saveSelectedDateField, "4,6"); panel.add(new JLabel(getI18n().getString("only_allocation_info")),"2,8"); panel.add( onlyAllocationInfoField, "4,8"); panel.add( statusHtml, "2,10,4,1"); { final String entry = model.getOption(AutoExportPlugin.HTML_EXPORT); checkbox.setSelected( entry != null && entry.equals("true")); } { final String entry = model.getOption(CalendarModel.SHOW_NAVIGATION_ENTRY); showNavField.setSelected( entry == null || entry.equals("true")); } { final String entry = model.getOption(CalendarModel.ONLY_ALLOCATION_INFO); onlyAllocationInfoField.setSelected( entry != null && entry.equals("true")); } { final String entry = model.getOption(CalendarModel.SAVE_SELECTED_DATE); if(entry != null) saveSelectedDateField.setSelected( entry.equals("true")); } updateCheck(); final String title = model.getTitle(); titleField.setText(title); } protected void updateCheck() { boolean htmlEnabled = checkbox.isSelected() && checkbox.isEnabled(); titleField.setEnabled( htmlEnabled); showNavField.setEnabled( htmlEnabled); saveSelectedDateField.setEnabled( htmlEnabled); statusHtml.setEnabled( htmlEnabled); } JPanel createStatus( final JTextField urlLabel) { addCopyPaste(urlLabel); final RaplaButton copyButton = new RaplaButton(); JPanel status = new JPanel() { private static final long serialVersionUID = 1L; public void setEnabled(boolean enabled) { super.setEnabled(enabled); urlLabel.setEnabled( enabled); copyButton.setEnabled( enabled); } }; status.setLayout( new BorderLayout()); urlLabel.setText( ""); urlLabel.setEditable( true ); urlLabel.setFont( urlLabel.getFont().deriveFont( (float)10.0)); status.add( new JLabel("URL: "), BorderLayout.WEST ); status.add( urlLabel, BorderLayout.CENTER ); copyButton.setBorder(BorderFactory.createEmptyBorder(2,2,2,2)); copyButton.setFocusable(false); copyButton.setRolloverEnabled(false); copyButton.setIcon(getIcon("icon.copy")); copyButton.setToolTipText(getString("copy_to_clipboard")); copyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { urlLabel.requestFocus(); urlLabel.selectAll(); copy(urlLabel,e); } }); status.add(copyButton, BorderLayout.EAST); return status; } public void mapOptionTo() { String title = titleField.getText().trim(); if ( title.length() > 0) { model.setTitle( title ); } else { model.setTitle( null); } String showNavEntry = showNavField.isSelected() ? "true" : "false"; model.setOption( CalendarModel.SHOW_NAVIGATION_ENTRY, showNavEntry); String saveSelectedDate = saveSelectedDateField.isSelected() ? "true" : "false"; model.setOption( CalendarModel.SAVE_SELECTED_DATE, saveSelectedDate); String onlyAlloactionInfo = onlyAllocationInfoField.isSelected() ? "true" : "false"; model.setOption( CalendarModel.ONLY_ALLOCATION_INFO, onlyAlloactionInfo); final String htmlSelected = checkbox.isSelected() ? "true" : "false"; model.setOption( AutoExportPlugin.HTML_EXPORT, htmlSelected); } public JPanel getPanel() { return panel; } public JTextField getURLField() { return htmlURL; } public boolean hasAddressCreationStrategy() { return false; } public String getAddress(String filename, String generator) { return null; } public String getGenerator() { return AutoExportPlugin.CALENDAR_GENERATOR; } }
04900db4-rob
src/org/rapla/plugin/autoexport/HTMLPublishExtension.java
Java
gpl3
6,354
package org.rapla.plugin.appointmentcounter; import java.awt.Font; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.JComponent; import javax.swing.JLabel; import org.rapla.components.util.DateTools; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.AppointmentListener; import org.rapla.gui.AppointmentStatusFactory; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.ReservationEdit; import org.rapla.gui.toolkit.RaplaWidget; public class AppointmentCounterFactory implements AppointmentStatusFactory { public RaplaWidget createStatus(RaplaContext context, ReservationEdit reservationEdit) throws RaplaException { return new AppointmentCounter(context, reservationEdit); } class AppointmentCounter extends RaplaGUIComponent implements RaplaWidget { JLabel statusBar = new JLabel(); ReservationEdit reservationEdit; public AppointmentCounter(final RaplaContext context, final ReservationEdit reservationEdit) { super(context); Font font = statusBar.getFont().deriveFont( (float)9.0); statusBar.setFont( font ); this.reservationEdit = reservationEdit; reservationEdit.addAppointmentListener( new AppointmentListener() { public void appointmentRemoved(Collection<Appointment> appointment) { updateStatus(); } public void appointmentChanged(Collection<Appointment> appointment) { updateStatus(); } public void appointmentAdded(Collection<Appointment> appointment) { updateStatus(); } public void appointmentSelected(Collection<Appointment> appointment) { updateStatus(); } }); updateStatus(); } private void updateStatus() { Reservation event = reservationEdit.getReservation(); if ( event == null) { return; } Appointment[] appointments = event.getAppointments(); int count = 0; for (int i = 0; i<appointments.length; i++) { Appointment appointment = appointments[i]; Repeating repeating = appointment.getRepeating(); if ( repeating == null ) { count ++; continue; } if ( repeating.getEnd() == null ){ // Repeats foreever ? count = -1; break; } List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>(); appointment.createBlocks( appointment.getStart(), DateTools.fillDate(repeating.getEnd()), blocks); count += blocks.size(); } String status = ""; if (count >= 0) status = getString("total_occurances")+ ": " + count; else status = getString("total_occurances")+ ": ? "; // uncomment for selection change test // status += "Selected Appointments " + reservationEdit.getSelectedAppointments(); statusBar.setText( status ); } public JComponent getComponent() { return statusBar; } } }
04900db4-rob
src/org/rapla/plugin/appointmentcounter/AppointmentCounterFactory.java
Java
gpl3
3,448
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.appointmentcounter; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; public class AppointmentCounterPlugin implements PluginDescriptor<ClientServiceContainer> { public final static boolean ENABLE_BY_DEFAULT = true; public String toString() { return "Appointment Counter"; } public void provideServices(ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent( RaplaClientExtensionPoints.APPOINTMENT_STATUS, AppointmentCounterFactory.class, config); } }
04900db4-rob
src/org/rapla/plugin/appointmentcounter/AppointmentCounterPlugin.java
Java
gpl3
1,743
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.weekview; import javax.swing.Icon; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.SwingCalendarView; import org.rapla.gui.SwingViewFactory; import org.rapla.gui.images.Images; public class WeekViewFactory extends RaplaComponent implements SwingViewFactory { public WeekViewFactory( RaplaContext context ) { super( context ); } public final static String WEEK_VIEW = "week"; public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException { return new SwingWeekCalendar( context, model, editable); } public String getViewId() { return WEEK_VIEW; } public String getName() { return getString(WEEK_VIEW); } Icon icon; public Icon getIcon() { if ( icon == null) { icon = Images.getIcon("/org/rapla/plugin/weekview/images/week.png"); } return icon; } public String getMenuSortKey() { return "B"; } }
04900db4-rob
src/org/rapla/plugin/weekview/WeekViewFactory.java
Java
gpl3
2,118
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.weekview; import java.util.Calendar; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarOptions; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; public class SwingDayCalendar extends SwingWeekCalendar { public SwingDayCalendar( RaplaContext sm, CalendarModel model, boolean editable ) throws RaplaException { super( sm, model, editable ); } @Override protected int getDays( CalendarOptions calendarOptions) { return 1; } public int getIncrementSize() { return Calendar.DAY_OF_YEAR; } }
04900db4-rob
src/org/rapla/plugin/weekview/SwingDayCalendar.java
Java
gpl3
1,573
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.weekview; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; public class WeekViewPlugin implements PluginDescriptor<ClientServiceContainer> { public static final boolean ENABLE_BY_DEFAULT = true; public void provideServices(ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,WeekViewFactory.class); container.addContainerProvidedComponent(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,DayViewFactory.class); } }
04900db4-rob
src/org/rapla/plugin/weekview/WeekViewPlugin.java
Java
gpl3
1,738
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.weekview; import java.awt.Font; import java.text.MessageFormat; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.swing.JComponent; import javax.swing.JLabel; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateRenderer; import org.rapla.components.calendar.DateRenderer.RenderingInfo; import org.rapla.components.calendar.DateRendererAdapter; import org.rapla.components.calendarview.swing.AbstractSwingCalendar; import org.rapla.components.calendarview.swing.SwingWeekView; import org.rapla.components.util.DateTools; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarOptions; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.AbstractRaplaSwingCalendar; import org.rapla.plugin.abstractcalendar.RaplaBuilder; public class SwingWeekCalendar extends AbstractRaplaSwingCalendar { public SwingWeekCalendar( RaplaContext context, CalendarModel model, boolean editable ) throws RaplaException { super( context, model, editable ); } protected AbstractSwingCalendar createView(boolean showScrollPane) { final DateRenderer dateRenderer; final DateRendererAdapter dateRendererAdapter; dateRenderer = getService(DateRenderer.class); dateRendererAdapter = new DateRendererAdapter(dateRenderer, getRaplaLocale().getTimeZone(), getRaplaLocale().getLocale()); final SwingWeekView wv = new SwingWeekView( showScrollPane ) { protected JComponent createSlotHeader(Integer column) { JLabel component = (JLabel) super.createSlotHeader(column); Date date = getDateFromColumn(column); boolean today = DateTools.isSameDay(getQuery().today().getTime(), date.getTime()); if ( today) { component.setFont(component.getFont().deriveFont( Font.BOLD)); } if (isEditable() ) { component.setOpaque(true); RenderingInfo info = dateRendererAdapter.getRenderingInfo(date); if (info.getBackgroundColor() != null) { component.setBackground(info.getBackgroundColor()); } if (info.getForegroundColor() != null) { component.setForeground(info.getForegroundColor()); } if (info.getTooltipText() != null) { component.setToolTipText(info.getTooltipText()); } } return component; } @Override public void rebuild() { // update week weekTitle.setText(MessageFormat.format(getString("calendarweek.abbreviation"), getStartDate())); super.rebuild(); } }; return wv; } public void dateChanged(DateChangeEvent evt) { super.dateChanged( evt ); ((SwingWeekView)view).scrollDateVisible( evt.getDate()); } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = super.createBuilder(); return builder; } @Override protected void configureView() { SwingWeekView view = (SwingWeekView) this.view; CalendarOptions calendarOptions = getCalendarOptions(); int rowsPerHour = calendarOptions.getRowsPerHour(); int startMinutes = calendarOptions.getWorktimeStartMinutes(); int endMinutes = calendarOptions.getWorktimeEndMinutes(); int hours = Math.max(1, (endMinutes - startMinutes) / 60); view.setRowsPerHour( rowsPerHour ); if ( rowsPerHour == 1 ) { if ( hours < 10) { view.setRowSize( 80); } else if ( hours < 15) { view.setRowSize( 60); } else { view.setRowSize( 30); } } else if ( rowsPerHour == 2 ) { if ( hours < 10) { view.setRowSize( 40); } else { view.setRowSize( 20); } } else if ( rowsPerHour >= 4 ) { view.setRowSize( 15); } view.setWorktimeMinutes(startMinutes, endMinutes); int days = getDays( calendarOptions); view.setDaysInView( days); Set<Integer> excludeDays = calendarOptions.getExcludeDays(); if ( days <3) { excludeDays = new HashSet<Integer>(); } view.setExcludeDays( excludeDays ); view.setFirstWeekday( calendarOptions.getFirstDayOfWeek()); view.setToDate(model.getSelectedDate()); // if ( !view.isEditable() ) { // view.setSlotSize( model.getSize()); // } else { // view.setSlotSize( 135 ); // } } /** overide this for dayly views*/ protected int getDays(CalendarOptions calendarOptions) { return calendarOptions.getDaysInWeekview(); } public void scrollToStart() { ((SwingWeekView)view).scrollToStart(); } public int getIncrementSize() { return Calendar.WEEK_OF_YEAR; } }
04900db4-rob
src/org/rapla/plugin/weekview/SwingWeekCalendar.java
Java
gpl3
6,356
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.weekview.server; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory; import org.rapla.servletpages.RaplaPageGenerator; public class HTMLWeekViewFactory extends RaplaComponent implements HTMLViewFactory { public HTMLWeekViewFactory( RaplaContext context ) { super( context ); } public final static String WEEK_VIEW = "week"; public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) throws RaplaException { return new HTMLWeekViewPage( context, model); } public String getViewId() { return WEEK_VIEW; } public String getName() { return getString(WEEK_VIEW); } }
04900db4-rob
src/org/rapla/plugin/weekview/server/HTMLWeekViewFactory.java
Java
gpl3
1,820
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.weekview.server; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.server.ServerServiceContainer; public class WeekViewServerPlugin implements PluginDescriptor<ServerServiceContainer> { static boolean ENABLE_BY_DEFAULT = true; public String toString() { return "Week View"; } public void provideServices(ServerServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,HTMLWeekViewFactory.class); container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,HTMLDayViewFactory.class); } }
04900db4-rob
src/org/rapla/plugin/weekview/server/WeekViewServerPlugin.java
Java
gpl3
1,825
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.weekview.server; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory; import org.rapla.servletpages.RaplaPageGenerator; public class HTMLDayViewFactory extends RaplaComponent implements HTMLViewFactory { public HTMLDayViewFactory( RaplaContext context ) { super( context ); } public final static String DAY_VIEW = "day"; public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) { return new HTMLDayViewPage( context, model); } public String getViewId() { return DAY_VIEW; } public String getName() { return getString(DAY_VIEW); } }
04900db4-rob
src/org/rapla/plugin/weekview/server/HTMLDayViewFactory.java
Java
gpl3
1,752
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.weekview.server; import java.text.MessageFormat; import java.util.Calendar; import java.util.HashSet; import java.util.Set; import org.rapla.components.calendarview.html.AbstractHTMLView; import org.rapla.components.calendarview.html.HTMLWeekView; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarOptions; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.GroupAllocatablesStrategy; import org.rapla.plugin.abstractcalendar.RaplaBuilder; import org.rapla.plugin.abstractcalendar.server.AbstractHTMLCalendarPage; public class HTMLWeekViewPage extends AbstractHTMLCalendarPage { public HTMLWeekViewPage( RaplaContext context, CalendarModel calendarModel ) { super( context, calendarModel ); } protected AbstractHTMLView createCalendarView() { HTMLWeekView weekView = new HTMLWeekView() { public void rebuild() { setWeeknumber(MessageFormat.format(getString("calendarweek.abbreviation"), getStartDate())); super.rebuild(); } }; return weekView; } protected void configureView() { HTMLWeekView weekView = (HTMLWeekView) view; CalendarOptions opt = getCalendarOptions(); weekView.setRowsPerHour( opt.getRowsPerHour() ); weekView.setWorktimeMinutes(opt.getWorktimeStartMinutes(), opt.getWorktimeEndMinutes() ); weekView.setFirstWeekday( opt.getFirstDayOfWeek()); int days = getDays(opt); weekView.setDaysInView( days); Set<Integer> excludeDays = opt.getExcludeDays(); if ( days <3) { excludeDays = new HashSet<Integer>(); } weekView.setExcludeDays( excludeDays ); } /** overide this for daily views*/ protected int getDays(CalendarOptions calendarOptions) { return calendarOptions.getDaysInWeekview(); } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = super.createBuilder(); GroupAllocatablesStrategy strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ); boolean compactColumns = getCalendarOptions().isCompactColumns() || builder.getAllocatables().size() ==0 ; strategy.setFixedSlotsEnabled( !compactColumns); strategy.setResolveConflictsEnabled( true ); builder.setBuildStrategy( strategy ); return builder; } public int getIncrementSize() { return Calendar.WEEK_OF_YEAR; } }
04900db4-rob
src/org/rapla/plugin/weekview/server/HTMLWeekViewPage.java
Java
gpl3
3,492
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.weekview.server; import java.util.Calendar; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarOptions; import org.rapla.framework.RaplaContext; public class HTMLDayViewPage extends HTMLWeekViewPage { public HTMLDayViewPage( RaplaContext context, CalendarModel calendarModel ) { super( context, calendarModel ); } @Override protected int getDays(CalendarOptions calendarOptions) { return 1; } public int getIncrementSize() { return Calendar.DAY_OF_YEAR; } }
04900db4-rob
src/org/rapla/plugin/weekview/server/HTMLDayViewPage.java
Java
gpl3
1,507
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.weekview; import javax.swing.Icon; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.SwingCalendarView; import org.rapla.gui.SwingViewFactory; import org.rapla.gui.images.Images; public class DayViewFactory extends RaplaComponent implements SwingViewFactory { public DayViewFactory( RaplaContext context ) { super( context ); } public final static String DAY_VIEW = "day"; public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException { return new SwingDayCalendar( context, model, editable); } public String getViewId() { return DAY_VIEW; } public String getName() { return getString(DAY_VIEW); } Icon icon; public Icon getIcon() { if ( icon == null) { icon = Images.getIcon("/org/rapla/plugin/weekview/images/day.png"); } return icon; } public String getMenuSortKey() { return "A"; } }
04900db4-rob
src/org/rapla/plugin/weekview/DayViewFactory.java
Java
gpl3
2,111
package org.rapla.plugin.mail; import javax.jws.WebService; import org.rapla.framework.RaplaException; @WebService public interface MailToUserInterface { void sendMail(String username,String subject, String body) throws RaplaException; }
04900db4-rob
src/org/rapla/plugin/mail/MailToUserInterface.java
Java
gpl3
244
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.mail.internal; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.mail.MailToUserInterface; /** RemoteStub */ public class RaplaMailToUserOnServer extends RaplaComponent implements MailToUserInterface { MailToUserInterface service; public RaplaMailToUserOnServer( RaplaContext context, MailToUserInterface service ) { super( context ); this.service = service; } public void sendMail( String username, String subject, String mailBody ) throws RaplaException { service.sendMail(username, subject, mailBody); } }
04900db4-rob
src/org/rapla/plugin/mail/internal/RaplaMailToUserOnServer.java
Java
gpl3
1,633
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.mail.client; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Locale; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import org.rapla.components.calendar.RaplaNumber; import org.rapla.components.layout.TableLayout; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; import org.rapla.gui.DefaultPluginOption; import org.rapla.gui.toolkit.RaplaButton; import org.rapla.plugin.mail.MailConfigService; import org.rapla.plugin.mail.MailPlugin; public class MailOption extends DefaultPluginOption { JTextField mailServer; RaplaNumber smtpPortField ; JTextField defaultSender; JTextField username; JPasswordField password; RaplaButton send ; JCheckBox useSsl = new JCheckBox(); private boolean listenersEnabled; private boolean externalConfigEnabled; MailConfigService configService; public MailOption(RaplaContext sm,MailConfigService mailConfigService) { super(sm); this.configService = mailConfigService; } protected JPanel createPanel() throws RaplaException { JPanel panel = super.createPanel(); externalConfigEnabled = configService.isExternalConfigEnabled(); mailServer = new JTextField(); smtpPortField = new RaplaNumber(new Integer(25), new Integer(0),null,false); defaultSender = new JTextField(); username = new JTextField(); password = new JPasswordField(); send = new RaplaButton(); password.setEchoChar('*'); JPanel content = new JPanel(); addCopyPaste( mailServer); addCopyPaste( defaultSender); addCopyPaste(username); addCopyPaste(password); double[][] sizes = new double[][] { {5,TableLayout.PREFERRED, 5,TableLayout.FILL,5} ,{TableLayout.PREFERRED,5,TableLayout.PREFERRED, 5, TableLayout.PREFERRED,5,TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED} }; TableLayout tableLayout = new TableLayout(sizes); content.setLayout(tableLayout); if (externalConfigEnabled) { JLabel info = new JLabel("Mail config is provided by servlet container."); content.add(info, "3,0"); } else { content.add(new JLabel("Mail Server"), "1,0"); content.add( mailServer, "3,0"); content.add(new JLabel("Use SSL*"), "1,2"); content.add(useSsl,"3,2"); content.add(new JLabel("Mail Port"), "1,4"); content.add( smtpPortField, "3,4"); content.add(new JLabel("Username"), "1,6"); content.add( username, "3,6"); content.add(new JLabel("Password"), "1,8"); JPanel passwordPanel = new JPanel(); passwordPanel.setLayout( new BorderLayout()); content.add( passwordPanel, "3,8"); passwordPanel.add( password, BorderLayout.CENTER); final JCheckBox showPassword = new JCheckBox("show password"); passwordPanel.add( showPassword, BorderLayout.EAST); showPassword.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean show = showPassword.isSelected(); password.setEchoChar( show ? ((char) 0): '*'); } }); content.add(new JLabel("Default Sender"), "1,10"); content.add( defaultSender, "3,10"); } content.add(new JLabel("Test Mail"), "1,12"); content.add( send, "3,12"); String mailid = getUser().getEmail(); if(mailid.length() == 0) { send.setText("Send to " + getUser()+ " : Provide email in user profile"); send.setEnabled(false); //java.awt.Font font = send.getFont(); //send.setFont( font.deriveFont( Font.BOLD)); } else { send.setText("Send to " + getUser()+ " : " + mailid); send.setEnabled(true); //send.setBackground(Color.GREEN); } useSsl.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if ( listenersEnabled) { int port = useSsl.isSelected() ? 465 : 25; smtpPortField.setNumber( new Integer(port)); } } }); send.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { DefaultConfiguration newConfig = new DefaultConfiguration( config); Configuration[] children = newConfig.getChildren(); for (Configuration child:children) { newConfig.removeChild(child); } String className = getPluginClass().getName(); newConfig.setAttribute( "class", className); newConfig.setAttribute( "enabled", activate.isSelected()); // if ( !activate.isSelected()) // { // throw new RaplaException("You need to activate MailPlugin " + getString("restart_options")); // } if (!externalConfigEnabled) { addChildren( newConfig); // if ( !newConfig.equals( config)) // { // getLogger().info("old config" + config ); // getLogger().info("new config" + newConfig); // throw new RaplaException(getString("restart_options")); // } } else { String attribute = config.getAttribute("enabled", null); if ( attribute == null || !attribute.equalsIgnoreCase("true") ) { throw new RaplaException(getString("restart_options")); } } //String senderMail = defaultSender.getText(); String recipient = getUser().getEmail(); if ( recipient == null || recipient.trim().length() == 0) { throw new RaplaException("You need to set an email address in your user settings."); } try { send.setBackground(new Color(255,100,100, 255)); configService.testMail( newConfig, defaultSender.getText()); send.setBackground(Color.GREEN); send.setText("Please check your mailbox."); } catch (UnsupportedOperationException ex) { JComponent component = getComponent(); showException( new RaplaException(getString("restart_options")), component); } } catch (RaplaException ex ) { JComponent component = getComponent(); showException( ex, component); // } catch (ConfigurationException ex) { // JComponent component = getComponent(); // showException( ex, component); } } }); panel.add( content, BorderLayout.CENTER); return panel; } protected void addChildren( DefaultConfiguration newConfig) { if ( !externalConfigEnabled) { DefaultConfiguration smtpPort = new DefaultConfiguration("smtp-port"); DefaultConfiguration smtpServer = new DefaultConfiguration("smtp-host"); DefaultConfiguration ssl = new DefaultConfiguration("ssl"); smtpPort.setValue(smtpPortField.getNumber().intValue() ); smtpServer.setValue( mailServer.getText()); ssl.setValue( useSsl.isSelected() ); newConfig.addChild( smtpPort ); newConfig.addChild( smtpServer ); newConfig.addChild( ssl ); DefaultConfiguration username = new DefaultConfiguration("username"); DefaultConfiguration password = new DefaultConfiguration("password"); String usernameValue = this.username.getText(); if ( usernameValue != null && usernameValue.trim().length() > 0) { username.setValue( usernameValue); } newConfig.addChild( username ); String passwordString = new String(this.password.getPassword()); if ( passwordString.trim().length() > 0 ) { password.setValue( passwordString); } newConfig.addChild( password ); } } @Override protected void readConfig( Configuration config) { try { config = configService.getConfig(); } catch (RaplaException ex) { showException(ex, getComponent()); } listenersEnabled = false; try { useSsl.setSelected( config.getChild("ssl").getValueAsBoolean( false)); mailServer.setText( config.getChild("smtp-host").getValue("localhost")); smtpPortField.setNumber( new Integer(config.getChild("smtp-port").getValueAsInteger(25))); username.setText( config.getChild("username").getValue("")); password.setText( config.getChild("password").getValue("")); } finally { listenersEnabled = true; } } public void show() throws RaplaException { super.show(); defaultSender.setText( preferences.getEntryAsString(MailPlugin.DEFAULT_SENDER_ENTRY,"rapla@domainname")); } public void commit() throws RaplaException { writePluginConfig(false); TypedComponentRole<RaplaConfiguration> configEntry = MailPlugin.MAILSERVER_CONFIG; RaplaConfiguration newConfig = new RaplaConfiguration("config" ); addChildren( newConfig ); preferences.putEntry( configEntry,newConfig); preferences.putEntry(MailPlugin.DEFAULT_SENDER_ENTRY, defaultSender.getText() ); } /** * @see org.rapla.gui.DefaultPluginOption#getPluginClass() */ public Class<? extends PluginDescriptor<?>> getPluginClass() { return MailPlugin.class; } public String getName(Locale locale) { return "Mail Plugin"; } }
04900db4-rob
src/org/rapla/plugin/mail/client/MailOption.java
Java
gpl3
10,893
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.mail; import org.rapla.framework.RaplaException; public class MailException extends RaplaException { private static final long serialVersionUID = 1L; public MailException(String text,Throwable ex) { super(text,ex); } public MailException(String text) { super(text); } }
04900db4-rob
src/org/rapla/plugin/mail/MailException.java
Java
gpl3
1,291
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.mail; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContextException; import org.rapla.framework.TypedComponentRole; import org.rapla.plugin.mail.client.MailOption; import org.rapla.plugin.mail.internal.RaplaMailToUserOnServer; /** Provides the MailToUserInterface and the MailInterface for sending mails. * The MailInterface can only be used on a machine that can connect to the mailserver. * While the MailToUserInterface can be called from a client, it redirects the mail request to * the server, which must be able to connect to the mailserver. * * Example 1: * * <code> * MailToUserInterface mail = getContext().loopup( MailToUserInterface.class ); * mail.sendMail( subject, body ); * </code> * * @see MailToUserInterface */ public class MailPlugin implements PluginDescriptor<ClientServiceContainer> { public static final boolean ENABLE_BY_DEFAULT = false; public static final TypedComponentRole<String> DEFAULT_SENDER_ENTRY = new TypedComponentRole<String>("org.rapla.plugin.mail.DefaultSender"); public static final TypedComponentRole<RaplaConfiguration> MAILSERVER_CONFIG = new TypedComponentRole<RaplaConfiguration>("org.rapla.plugin.mail.server.Config"); public void provideServices(ClientServiceContainer container, Configuration config) throws RaplaContextException { container.addContainerProvidedComponent( RaplaClientExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION,MailOption.class); if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent( MailToUserInterface.class, RaplaMailToUserOnServer.class); } }
04900db4-rob
src/org/rapla/plugin/mail/MailPlugin.java
Java
gpl3
2,856
package org.rapla.plugin.mail; import javax.jws.WebService; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.RaplaException; @WebService public interface MailConfigService { boolean isExternalConfigEnabled() throws RaplaException; void testMail( DefaultConfiguration config,String defaultSender) throws RaplaException; DefaultConfiguration getConfig() throws RaplaException; // LoginInfo getLoginInfo() throws RaplaException; // void setLogin(String username,String password) throws RaplaException; // public class LoginInfo // { // public String username; // public String password; // } }
04900db4-rob
src/org/rapla/plugin/mail/MailConfigService.java
Java
gpl3
632
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.mail.server; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.facade.ClientFacade; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.mail.MailPlugin; import org.rapla.plugin.mail.MailToUserInterface; import org.rapla.server.RemoteMethodFactory; import org.rapla.server.RemoteSession; public class RaplaMailToUserOnLocalhost extends RaplaComponent implements MailToUserInterface, RemoteMethodFactory<MailToUserInterface> { public RaplaMailToUserOnLocalhost( RaplaContext context) { super( context ); } public void sendMail(String userName,String subject, String body) throws RaplaException { User recipientUser = getQuery().getUser( userName ); // O.K. We need to generate the mail String recipientEmail = recipientUser.getEmail(); if (recipientEmail == null || recipientEmail.trim().length() == 0) { getLogger().warn("No email address specified for user " + recipientUser.getUsername() + " Can't send mail."); return; } final MailInterface mail = getContext().lookup(MailInterface.class); ClientFacade facade = getContext().lookup(ClientFacade.class); Preferences prefs = facade.getSystemPreferences(); final String defaultSender = prefs.getEntryAsString( MailPlugin.DEFAULT_SENDER_ENTRY, ""); mail.sendMail( defaultSender, recipientEmail,subject, body); getLogger().getChildLogger("mail").info("Email send to user " + userName); } public MailToUserInterface createService(RemoteSession remoteSession) { return this; } }
04900db4-rob
src/org/rapla/plugin/mail/server/RaplaMailToUserOnLocalhost.java
Java
gpl3
2,863
package org.rapla.plugin.mail.server; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Properties; import org.rapla.RaplaMainContainer; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.facade.ClientFacade; import org.rapla.framework.Configuration; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.mail.MailException; import org.rapla.plugin.mail.MailPlugin; public class MailapiClient implements MailInterface { String mailhost = "localhost"; int port = 25; boolean ssl =false; String username; String password; RaplaContext context; Object lookup; public MailapiClient( RaplaContext context) throws RaplaException { this.context = context; if ( context.has(RaplaMainContainer.ENV_RAPLAMAIL)) { lookup = context.lookup(RaplaMainContainer.ENV_RAPLAMAIL); } } public MailapiClient() { } public boolean isSsl() { return ssl; } public void setSsl(boolean ssl) { this.ssl = ssl; } public void sendMail( String senderMail, String recipient, String subject, String mailBody ) throws MailException { if ( lookup != null) { send(senderMail, recipient, subject, mailBody, lookup); return; } else { sendMail(senderMail, recipient, subject, mailBody, (Configuration)null); } } public void sendMail( String senderMail, String recipient, String subject, String mailBody, Configuration config ) throws MailException { Object session; if ( config == null && context != null && context.has( ClientFacade.class)) { Preferences systemPreferences; try { systemPreferences = context.lookup(ClientFacade.class).getSystemPreferences(); } catch (RaplaException e) { throw new MailException( e.getMessage(),e); } config = systemPreferences.getEntry(MailPlugin.MAILSERVER_CONFIG, new RaplaConfiguration()); } if ( config != null) { // get the configuration entry text with the default-value "Welcome" int port = config.getChild("smtp-port").getValueAsInteger(25); String mailhost = config.getChild("smtp-host").getValue("localhost"); String username= config.getChild("username").getValue(""); String password= config.getChild("password").getValue(""); boolean ssl = config.getChild("ssl").getValueAsBoolean(false); session = createSessionFromProperties(mailhost,port,ssl, username, password); } else { session = createSessionFromProperties(mailhost,port,ssl, username, password); } send(senderMail, recipient, subject, mailBody, session); } private Object createSessionFromProperties(String mailhost, int port, boolean ssl, String username, String password) throws MailException { Properties props = new Properties(); props.put("mail.smtp.host", mailhost); props.put("mail.smtp.port", new Integer(port)); boolean usernameSet = username != null && username.trim().length() > 0; if ( usernameSet) { props.put("username", username); props.put("mail.smtp.auth","true"); } if ( password != null) { if ( usernameSet || password.length() > 0) { props.put("password", password); } } if (ssl) { props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.port", new Integer(port)); } Object session; try { Class<?> MailLibsC = Class.forName("org.rapla.plugin.mail.server.RaplaMailLibs"); session = MailLibsC.getMethod("getSession", Properties.class).invoke( null, props); } catch (Exception e) { Throwable cause = e; if ( e instanceof InvocationTargetException) { cause = e.getCause(); } throw new MailException( cause.getMessage(), cause); } return session; } private void send(String senderMail, String recipient, String subject, String mailBody, Object uncastedSession) throws MailException { ClassLoader classLoader = uncastedSession.getClass().getClassLoader(); try { sendWithReflection(senderMail, recipient, subject, mailBody, uncastedSession, classLoader); // try // { // Session castedSession = (Session) uncastedSession; // sendWithoutReflection(senderMail, recipient, subject, mailBody, castedSession); // } // catch ( ClassCastException ex) // { // sendWithReflection(senderMail, recipient, subject, mailBody, uncastedSession, classLoader); // return; // } } catch (Exception ex) { String message = ex.getMessage(); throw new MailException( message, ex); } } // private void sendWithoutReflection(String senderMail, String recipient, // String subject, String mailBody, Session session) throws Exception { // Message message = new MimeMessage(session); // if ( senderMail != null && senderMail.trim().length() > 0) // { // message.setFrom(new InternetAddress(senderMail)); // } // RecipientType type = Message.RecipientType.TO; // Address[] parse = InternetAddress.parse(recipient); // message.setRecipients(type, parse); // message.setSubject(subject); // message.setText(mailBody); // Transport.send(message); // } private void sendWithReflection(String senderMail, String recipient, String subject, String mailBody, Object session, ClassLoader classLoader) throws Exception { Thread currentThread = Thread.currentThread(); ClassLoader original = currentThread.getContextClassLoader(); boolean changedClass =false; try { try { currentThread.setContextClassLoader( classLoader); changedClass = true; } catch (Throwable ex) { } Class<?> SessionC = classLoader.loadClass("javax.mail.Session"); Class<?> MimeMessageC = classLoader.loadClass("javax.mail.internet.MimeMessage"); Class<?> MessageC = classLoader.loadClass("javax.mail.Message"); Class<?> AddressC = classLoader.loadClass("javax.mail.Address"); Class<?> RecipientTypeC = classLoader.loadClass("javax.mail.Message$RecipientType"); Class<?> InternetAddressC = classLoader.loadClass("javax.mail.internet.InternetAddress"); Class<?> TransportC = classLoader.loadClass("javax.mail.Transport"); //Message message = new MimeMessage(session); Object message = MimeMessageC.getConstructor( SessionC).newInstance( session); if ( senderMail != null && senderMail.trim().length() > 0) { //message.setFrom(new InternetAddress(senderMail)); Object senderMailAddress = InternetAddressC.getConstructor( String.class).newInstance( senderMail); MimeMessageC.getMethod("setFrom", AddressC).invoke( message, senderMailAddress); } //RecipientType type = Message.RecipientType.TO; //Address[] parse = InternetAddress.parse(recipient); //message.setRecipients(type, parse); Object type = RecipientTypeC.getField("TO").get(null); Object[] parsedRecipientDummy = (Object[]) Array.newInstance(AddressC, 0); Object parsedRecipient = InternetAddressC.getMethod("parse", String.class).invoke(null, recipient); Method method = MessageC.getMethod("setRecipients", RecipientTypeC, parsedRecipientDummy.getClass()); method.invoke( message, type, parsedRecipient); //message.setSubject(subject); MimeMessageC.getMethod("setSubject", String.class).invoke( message, subject); //message.setText(mailBody); //MimeMessageC.getMethod("setText", String.class).invoke( message, mailBody); MimeMessageC.getMethod("setContent", Object.class, String.class).invoke( message, mailBody, "text/plain; charset=UTF-8"); //Transport.send(message); TransportC.getMethod("send", MessageC).invoke( null, message); } catch (Exception ex) { Throwable e = ex; if ( ex instanceof InvocationTargetException){ e = ex.getCause(); } String message = e.getMessage(); throw new RaplaException( message, e); } finally { if ( changedClass) { currentThread.setContextClassLoader( original); } } } public String getSmtpHost() { return mailhost; } public void setSmtpHost( String mailhost ) { this.mailhost = mailhost; } public String getPassword() { return password; } public void setPassword( String password ) { this.password = password; } public int getPort() { return port; } public void setPort( int port ) { this.port = port; } public String getUsername() { return username; } public void setUsername( String username ) { this.username = username; } }
04900db4-rob
src/org/rapla/plugin/mail/server/MailapiClient.java
Java
gpl3
9,133
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.mail.server; import org.rapla.RaplaMainContainer; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.configuration.internal.PreferencesImpl; import org.rapla.facade.RaplaComponent; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaException; import org.rapla.plugin.mail.MailConfigService; import org.rapla.plugin.mail.MailPlugin; import org.rapla.server.RaplaKeyStorage; import org.rapla.server.RemoteMethodFactory; import org.rapla.server.RemoteSession; import org.rapla.storage.RaplaSecurityException; public class RaplaConfigServiceImpl extends RaplaComponent implements RemoteMethodFactory<MailConfigService> { RaplaKeyStorage keyStore; public RaplaConfigServiceImpl( RaplaContext context) throws RaplaContextException { super( context ); keyStore = context.lookup( RaplaKeyStorage.class); } public MailConfigService createService(final RemoteSession remoteSession) { return new MailConfigService() { public boolean isExternalConfigEnabled() throws RaplaException { return getContext().has(RaplaMainContainer.ENV_RAPLAMAIL); } @SuppressWarnings("deprecation") @Override public DefaultConfiguration getConfig() throws RaplaException { User user = remoteSession.getUser(); if ( !user.isAdmin()) { throw new RaplaSecurityException("Access only for admin users"); } Preferences preferences = getQuery().getSystemPreferences(); DefaultConfiguration config = preferences.getEntry( MailPlugin.MAILSERVER_CONFIG); if ( config == null) { config = (DefaultConfiguration) ((PreferencesImpl)preferences).getOldPluginConfig(MailPlugin.class.getName()); } return config; } @Override public void testMail(DefaultConfiguration config, String defaultSender) throws RaplaException { User user = remoteSession.getUser(); if ( !user.isAdmin()) { throw new RaplaSecurityException("Access only for admin users"); } String subject ="Rapla Test Mail"; String mailBody ="If you receive this mail the rapla mail settings are successfully configured."; MailInterface test = getService(MailInterface.class); String recipient = user.getEmail(); if (test instanceof MailapiClient) { ((MailapiClient)test).sendMail(defaultSender, recipient, subject, mailBody, config); } else { test.sendMail(defaultSender,recipient, subject, mailBody); } } // @Override // public LoginInfo getLoginInfo() throws RaplaException { // User user = remoteSession.getUser(); // if ( user == null || !user.isAdmin()) // { // throw new RaplaSecurityException("Only admins can get mailserver login info"); // } // org.rapla.server.RaplaKeyStorage.LoginInfo secrets = keyStore.getSecrets( null, MailPlugin.MAILSERVER_CONFIG); // LoginInfo result = new LoginInfo(); // if ( secrets != null) // { // result.username = secrets.login; // result.password = secrets.secret; // } // return result; // } // // @Override // public void setLogin(String username, String password) throws RaplaException { // User user = remoteSession.getUser(); // if ( user == null || !user.isAdmin()) // { // throw new RaplaSecurityException("Only admins can set mailserver login info"); // } // if ( username.length() == 0 && password.length() == 0) // { // keyStore.removeLoginInfo(null, MailPlugin.MAILSERVER_CONFIG); // } // else // { // keyStore.storeLoginInfo( null, MailPlugin.MAILSERVER_CONFIG, username, password); // } // } }; } }
04900db4-rob
src/org/rapla/plugin/mail/server/RaplaConfigServiceImpl.java
Java
gpl3
5,005
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.mail.server; import org.rapla.entities.configuration.RaplaConfiguration; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.TypedComponentRole; import org.rapla.framework.logger.Logger; import org.rapla.plugin.mail.MailConfigService; import org.rapla.plugin.mail.MailPlugin; import org.rapla.plugin.mail.MailToUserInterface; import org.rapla.server.ServerServiceContainer; import org.rapla.server.internal.RemoteStorageImpl; /** Provides the MailToUserInterface and the MailInterface for sending mails. * The MailInterface can only be used on a machine that can connect to the mailserver. * While the MailToUserInterface can be called from a client, it redirects the mail request to * the server, which must be able to connect to the mailserver. * * Example 1: * * <code> * MailToUserInterface mail = getContext().loopup( MailToUserInterface.class ); * mail.sendMail( subject, body ); * </code> * * Example 2: * * <code> * MailInterface mail = getContext().loopup( MailInterface.class ); * mail.sendMail( senderMail, recipient, subject, body ); * </code> * @see MailInterface * @see MailToUserInterface */ public class MailServerPlugin implements PluginDescriptor<ServerServiceContainer> { public void provideServices(ServerServiceContainer container, Configuration config) throws RaplaContextException { container.addRemoteMethodFactory(MailConfigService.class,RaplaConfigServiceImpl.class); convertSettings(container.getContext(), config); if ( !config.getAttributeAsBoolean("enabled", false) ) return; Class<? extends MailInterface> mailClass = null; String mailClassConfig =config.getChild("mailinterface").getValue( null); if ( mailClassConfig != null) { try { @SuppressWarnings("unchecked") Class<? extends MailInterface> forName = (Class<? extends MailInterface>) Class.forName( mailClassConfig); mailClass = forName; } catch (Exception e) { container.getContext().lookup(Logger.class).error( "Error loading mailinterface " +e.getMessage() ); } } if ( mailClass == null) { mailClass = MailapiClient.class; } container.addContainerProvidedComponent( MailInterface.class, mailClass); // only add mail service on localhost container.addRemoteMethodFactory(MailToUserInterface.class,RaplaMailToUserOnLocalhost.class); container.addContainerProvidedComponent( MailToUserInterface.class, RaplaMailToUserOnLocalhost.class); } private void convertSettings(RaplaContext context,Configuration config) throws RaplaContextException { String className = MailPlugin.class.getName(); TypedComponentRole<RaplaConfiguration> newConfKey = MailPlugin.MAILSERVER_CONFIG; if ( config.getChildren().length > 0) { RemoteStorageImpl.convertToNewPluginConfig(context, className, newConfKey); } } }
04900db4-rob
src/org/rapla/plugin/mail/server/MailServerPlugin.java
Java
gpl3
4,161
package org.rapla.plugin.mail.server; import org.rapla.plugin.mail.MailException; public interface MailInterface { /* Sends the mail. Callers should check if the parameters are all valid according to the SMTP RFC at http://www.ietf.org/rfc/rfc821.txt because the implementing classes may not check for validity */ public void sendMail ( String senderMail ,String recipient ,String subject ,String mailBody ) throws MailException; }
04900db4-rob
src/org/rapla/plugin/mail/server/MailInterface.java
Java
gpl3
529
package org.rapla.plugin.mail.server; import java.util.Properties; import javax.mail.PasswordAuthentication; import javax.mail.Session; public class RaplaMailLibs { static public Object getSession(Properties props) { javax.mail.Authenticator authenticator = null; final String username2 = (String) props.get("username"); final String password2 = (String) props.get("password"); if ( props.containsKey("username")) { authenticator = new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username2,password2); } }; } Object session = Session.getInstance(props, authenticator); return session; } }
04900db4-rob
src/org/rapla/plugin/mail/server/RaplaMailLibs.java
Java
gpl3
748
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.compactweekview; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; public class CompactWeekViewPlugin implements PluginDescriptor<ClientServiceContainer> { public final static boolean ENABLE_BY_DEFAULT = true; public void provideServices(ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT)) return; container.addContainerProvidedComponent(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION,CompactWeekViewFactory.class ); } }
04900db4-rob
src/org/rapla/plugin/compactweekview/CompactWeekViewPlugin.java
Java
gpl3
1,638
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.compactweekview; import javax.swing.Icon; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.SwingCalendarView; import org.rapla.gui.SwingViewFactory; import org.rapla.gui.images.Images; public class CompactWeekViewFactory extends RaplaComponent implements SwingViewFactory { public final static String COMPACT_WEEK_VIEW = "week_compact"; public CompactWeekViewFactory( RaplaContext context ) { super( context ); } public SwingCalendarView createSwingView(RaplaContext context, CalendarModel model, boolean editable) throws RaplaException { return new SwingCompactWeekCalendar( context, model, editable); } public String getViewId() { return COMPACT_WEEK_VIEW; } public String getName() { return getString(COMPACT_WEEK_VIEW); } Icon icon; public Icon getIcon() { if ( icon == null) { icon = Images.getIcon("/org/rapla/plugin/compactweekview/images/week_compact.png"); } return icon; } public String getMenuSortKey() { return "B1"; } }
04900db4-rob
src/org/rapla/plugin/compactweekview/CompactWeekViewFactory.java
Java
gpl3
2,194
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.compactweekview; import java.awt.Font; import java.awt.Point; import java.text.MessageFormat; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.JComponent; import javax.swing.JLabel; import org.rapla.components.calendar.DateRenderer; import org.rapla.components.calendar.DateRenderer.RenderingInfo; import org.rapla.components.calendar.DateRendererAdapter; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.swing.AbstractSwingCalendar; import org.rapla.components.calendarview.swing.SwingCompactWeekView; import org.rapla.components.calendarview.swing.ViewListener; import org.rapla.components.util.DateTools; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarOptions; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.AbstractRaplaBlock; import org.rapla.plugin.abstractcalendar.AbstractRaplaSwingCalendar; import org.rapla.plugin.abstractcalendar.GroupAllocatablesStrategy; import org.rapla.plugin.abstractcalendar.RaplaBuilder; import org.rapla.plugin.abstractcalendar.RaplaCalendarViewListener; public class SwingCompactWeekCalendar extends AbstractRaplaSwingCalendar { public SwingCompactWeekCalendar(RaplaContext sm,CalendarModel settings, boolean editable) throws RaplaException { super( sm, settings, editable); } protected AbstractSwingCalendar createView(boolean showScrollPane) { final DateRendererAdapter dateRenderer = new DateRendererAdapter(getService(DateRenderer.class), getRaplaLocale().getTimeZone(), getRaplaLocale().getLocale()); SwingCompactWeekView compactWeekView = new SwingCompactWeekView( showScrollPane ) { @Override protected JComponent createColumnHeader(Integer column) { JLabel component = (JLabel) super.createColumnHeader(column); if ( column != null ) { Date date = getDateFromColumn(column); boolean today = DateTools.isSameDay(getQuery().today().getTime(), date.getTime()); if ( today) { component.setFont(component.getFont().deriveFont( Font.BOLD)); } if (isEditable() ) { component.setOpaque(true); RenderingInfo renderingInfo = dateRenderer.getRenderingInfo( date); if ( renderingInfo.getBackgroundColor() != null) { component.setBackground(renderingInfo.getBackgroundColor()); } if ( renderingInfo.getForegroundColor() != null) { component.setForeground(renderingInfo.getForegroundColor()); } component.setToolTipText(renderingInfo.getTooltipText()); } } else { String calendarWeek = MessageFormat.format(getString("calendarweek.abbreviation"), getStartDate()); component.setText( calendarWeek); } return component; } protected int getColumnCount() { return getDaysInView(); } }; return compactWeekView; } protected ViewListener createListener() throws RaplaException { RaplaCalendarViewListener listener = new RaplaCalendarViewListener(getContext(), model, view.getComponent()) { @Override public void selectionChanged(Date start, Date end) { if ( end.getTime()- start.getTime() == DateTools.MILLISECONDS_PER_DAY ) { Calendar cal = getRaplaLocale().createCalendar(); cal.setTime ( start ); int worktimeStartMinutes = getCalendarOptions().getWorktimeStartMinutes(); cal.set( Calendar.HOUR_OF_DAY, worktimeStartMinutes / 60); cal.set( Calendar.MINUTE, worktimeStartMinutes%60); start = cal.getTime(); end = new Date ( start.getTime() + 30 * DateTools.MILLISECONDS_PER_MINUTE ); } super.selectionChanged(start, end); } @Override protected Collection<Allocatable> getMarkedAllocatables() { final List<Allocatable> selectedAllocatables = getSortedAllocatables(); Set<Allocatable> allSelected = new HashSet<Allocatable>(); if ( selectedAllocatables.size() == 1 ) { allSelected.add(selectedAllocatables.get(0)); } int i= 0; int daysInView = view.getDaysInView(); for ( Allocatable alloc:selectedAllocatables) { boolean add = false; for (int slot = i*daysInView;slot< (i+1)*daysInView;slot++) { if ( view.isSelected(slot)) { add = true; } } if ( add ) { allSelected.add(alloc); } i++; } return allSelected; } @Override public void moved(Block block, Point p, Date newStart, int slotNr) { int index= slotNr / view.getDaysInView();//getIndex( selectedAllocatables, block ); if ( index < 0) { return; } try { final List<Allocatable> selectedAllocatables = getSortedAllocatables(); Allocatable newAlloc = selectedAllocatables.get(index); AbstractRaplaBlock raplaBlock = (AbstractRaplaBlock)block; Allocatable oldAlloc = raplaBlock.getGroupAllocatable(); if ( newAlloc != null && oldAlloc != null && !newAlloc.equals(oldAlloc)) { AppointmentBlock appointmentBlock = raplaBlock.getAppointmentBlock(); getReservationController().exchangeAllocatable(appointmentBlock, oldAlloc,newAlloc, newStart,getMainComponent(),p); } else { super.moved(block, p, newStart, slotNr); } } catch (RaplaException ex) { showException(ex, getMainComponent()); } } }; listener.setKeepTime( true); return listener; } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = super.createBuilder(); builder.setSmallBlocks( true ); String[] slotNames; final List<Allocatable> allocatables = getSortedAllocatables(); GroupAllocatablesStrategy strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ); strategy.setFixedSlotsEnabled( true); strategy.setResolveConflictsEnabled( false ); strategy.setAllocatables(allocatables) ; builder.setBuildStrategy( strategy ); slotNames = new String[ allocatables.size() ]; for (int i = 0; i <allocatables.size(); i++ ) { slotNames[i] = allocatables.get(i).getName( getRaplaLocale().getLocale() ); } builder.setSplitByAllocatables( true ); ((SwingCompactWeekView)view).setLeftColumnSize( 150); ((SwingCompactWeekView)view).setSlots( slotNames ); return builder; } protected void configureView() throws RaplaException { CalendarOptions calendarOptions = getCalendarOptions(); Set<Integer> excludeDays = calendarOptions.getExcludeDays(); view.setExcludeDays( excludeDays ); view.setDaysInView( calendarOptions.getDaysInWeekview()); int firstDayOfWeek = calendarOptions.getFirstDayOfWeek(); view.setFirstWeekday( firstDayOfWeek); view.setToDate(model.getSelectedDate()); // if ( !view.isEditable() ) { // view.setSlotSize( model.getSize()); // } else { // view.setSlotSize( 200 ); // } } public int getIncrementSize() { return Calendar.WEEK_OF_YEAR; } }
04900db4-rob
src/org/rapla/plugin/compactweekview/SwingCompactWeekCalendar.java
Java
gpl3
9,119
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.compactweekview.server; import org.rapla.facade.CalendarModel; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory; import org.rapla.servletpages.RaplaPageGenerator; public class CompactHTMLWeekViewFactory extends RaplaComponent implements HTMLViewFactory { public final static String COMPACT_WEEK_VIEW = "week_compact"; public CompactHTMLWeekViewFactory( RaplaContext context ) { super( context ); } public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) { return new HTMLCompactWeekViewPage( context, model); } public String getViewId() { return COMPACT_WEEK_VIEW; } public String getName() { return getString(COMPACT_WEEK_VIEW); } }
04900db4-rob
src/org/rapla/plugin/compactweekview/server/CompactHTMLWeekViewFactory.java
Java
gpl3
1,813
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.compactweekview.server; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.plugin.compactweekview.CompactWeekViewPlugin; import org.rapla.server.RaplaServerExtensionPoints; import org.rapla.server.ServerServiceContainer; public class CompactWeekViewServerPlugin implements PluginDescriptor<ServerServiceContainer> { public void provideServices(ServerServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", CompactWeekViewPlugin.ENABLE_BY_DEFAULT)) return; container.addContainerProvidedComponent(RaplaServerExtensionPoints.HTML_CALENDAR_VIEW_EXTENSION,CompactHTMLWeekViewFactory.class ); } }
04900db4-rob
src/org/rapla/plugin/compactweekview/server/CompactWeekViewServerPlugin.java
Java
gpl3
1,690
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.compactweekview.server; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.List; import java.util.Set; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.html.AbstractHTMLView; import org.rapla.components.calendarview.html.HTMLCompactWeekView; import org.rapla.components.util.xml.XMLWriter; import org.rapla.entities.domain.Allocatable; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarOptions; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.GroupAllocatablesStrategy; import org.rapla.plugin.abstractcalendar.RaplaBuilder; import org.rapla.plugin.abstractcalendar.server.AbstractHTMLCalendarPage; public class HTMLCompactWeekViewPage extends AbstractHTMLCalendarPage { public HTMLCompactWeekViewPage( RaplaContext context, CalendarModel calendarModel) { super( context, calendarModel); } protected AbstractHTMLView createCalendarView() { HTMLCompactWeekView weekView = new HTMLCompactWeekView() { @Override public void rebuild() { String weeknumberString = MessageFormat.format(getString("calendarweek.abbreviation"), getStartDate()); setWeeknumber(weeknumberString); super.rebuild(); } }; return weekView; } @Override protected void configureView() throws RaplaException { CalendarOptions opt = getCalendarOptions(); Set<Integer> excludeDays = opt.getExcludeDays(); view.setExcludeDays( excludeDays ); view.setDaysInView( opt.getDaysInWeekview()); int firstDayOfWeek = opt.getFirstDayOfWeek(); view.setFirstWeekday( firstDayOfWeek); view.setExcludeDays( excludeDays ); } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = super.createBuilder(); builder.setSmallBlocks( true ); builder.setSplitByAllocatables( true ); GroupAllocatablesStrategy strategy; if ( builder.getAllocatables().size() > 0) { strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ); strategy.setAllocatables( builder.getAllocatables() ) ; } else { // put all Allocatables in the same group strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ) { protected Collection<List<Block>> group(List<Block> blockList) { ArrayList<List<Block>> list = new ArrayList<List<Block>>(); list.add( blockList ); return list; } }; } strategy.setFixedSlotsEnabled( true ); builder.setBuildStrategy( strategy ); List<Allocatable> allocatables = builder.getAllocatables(); String[] slotNames = new String[ allocatables.size() ]; for (int i = 0; i < slotNames.length; i++ ) { Allocatable allocatable = allocatables.get( i ); String slotName = allocatable.getName( getRaplaLocale().getLocale() ); slotNames[i] = XMLWriter.encode( slotName ); } ((HTMLCompactWeekView)view).setSlots( slotNames ); return builder; } protected int getIncrementSize() { return Calendar.WEEK_OF_YEAR; } }
04900db4-rob
src/org/rapla/plugin/compactweekview/server/HTMLCompactWeekViewPage.java
Java
gpl3
4,419
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.defaultwizard; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.swing.MenuElement; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.toolkit.IdentifiableMenuEntry; import org.rapla.gui.toolkit.RaplaMenu; import org.rapla.gui.toolkit.RaplaMenuItem; /** This ReservationWizard displays no wizard and directly opens a ReservationEdit Window */ public class DefaultWizard extends RaplaGUIComponent implements IdentifiableMenuEntry, ActionListener { Map<Component,DynamicType> typeMap = new HashMap<Component, DynamicType>(); public DefaultWizard(RaplaContext sm){ super(sm); } public String getId() { return "000_defaultWizard"; } public MenuElement getMenuElement() { typeMap.clear(); DynamicType[] eventTypes; try { eventTypes = getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION); } catch (RaplaException e) { return null; } boolean canCreateReservation = canCreateReservation(); MenuElement element; if ( eventTypes.length == 1) { RaplaMenuItem item = new RaplaMenuItem( getId()); item.setEnabled( canAllocate() && canCreateReservation); item.setText(getString("new_reservation")); item.setIcon( getIcon("icon.new"));item.addActionListener( this); typeMap.put( item, eventTypes[0]); element = item; } else { RaplaMenu item = new RaplaMenu( getId()); item.setEnabled( canAllocate() && canCreateReservation); item.setText(getString("new_reservation")); item.setIcon( getIcon("icon.new")); for ( DynamicType type:eventTypes) { RaplaMenuItem newItem = new RaplaMenuItem(type.getKey()); newItem.setText( type.getName( getLocale())); item.add( newItem); newItem.addActionListener( this); typeMap.put( newItem, type); } element = item; } return element; } public void actionPerformed(ActionEvent e) { try { CalendarModel model = getService(CalendarModel.class); Object source = e.getSource(); DynamicType type = typeMap.get( source); if ( type == null) { getLogger().warn("Type not found for " + source + " in map " + typeMap); return; } Classification newClassification = type.newClassification(); Reservation r = getModification().newReservation( newClassification ); Appointment appointment = createAppointment(model); r.addAppointment(appointment); Collection<Allocatable> markedAllocatables = model.getMarkedAllocatables(); if ( markedAllocatables == null || markedAllocatables.size() == 0) { Allocatable[] allocatables = model.getSelectedAllocatables(); if ( allocatables.length == 1) { r.addAllocatable( allocatables[0]); } } else { for ( Allocatable alloc: markedAllocatables) { r.addAllocatable( alloc); } } getReservationController().edit( r ); } catch (RaplaException ex) { showException( ex, getMainComponent()); } } protected Appointment createAppointment(CalendarModel model) throws RaplaException { Date startDate = getStartDate(model); Date endDate = getEndDate( model, startDate); Appointment appointment = getModification().newAppointment(startDate, endDate); return appointment; } // /** // * @param model // * @param startDate // * @return // */ // protected Date getEndDate( CalendarModel model,Date startDate) { // Collection<TimeInterval> markedIntervals = model.getMarkedIntervals(); // Date endDate = null; // if ( markedIntervals.size() > 0) // { // TimeInterval first = markedIntervals.iterator().next(); // endDate = first.getEnd(); // } // if ( endDate != null) // { // return endDate; // } // return new Date(startDate.getTime() + DateTools.MILLISECONDS_PER_HOUR); // } // // protected Date getStartDate(CalendarModel model) { // Collection<TimeInterval> markedIntervals = model.getMarkedIntervals(); // Date startDate = null; // if ( markedIntervals.size() > 0) // { // TimeInterval first = markedIntervals.iterator().next(); // startDate = first.getStart(); // } // if ( startDate != null) // { // return startDate; // } // // // Date selectedDate = model.getSelectedDate(); // if ( selectedDate == null) // { // selectedDate = getQuery().today(); // } // Date time = new Date (DateTools.MILLISECONDS_PER_MINUTE * getCalendarOptions().getWorktimeStartMinutes()); // startDate = getRaplaLocale().toDate(selectedDate,time); // return startDate; // } }
04900db4-rob
src/org/rapla/plugin/defaultwizard/DefaultWizard.java
Java
gpl3
6,231
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.defaultwizard; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; public class DefaultWizardPlugin implements PluginDescriptor<ClientServiceContainer> { public static final String PLUGIN_CLASS = DefaultWizardPlugin.class.getName(); public static boolean ENABLE_BY_DEFAULT = true; public void provideServices(ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent( RaplaClientExtensionPoints.RESERVATION_WIZARD_EXTENSION, DefaultWizard.class); } }
04900db4-rob
src/org/rapla/plugin/defaultwizard/DefaultWizardPlugin.java
Java
gpl3
1,710
package org.rapla.plugin.rightsreport; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Icon; import javax.swing.MenuElement; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.IdentifiableMenuEntry; import org.rapla.gui.toolkit.RaplaMenuItem; public class RightsReportMenu extends RaplaGUIComponent implements IdentifiableMenuEntry, ActionListener{ private RaplaMenuItem report; final String name = getString("user") +"/"+ getString("groups") + " "+getString("report") ; public RightsReportMenu(RaplaContext context) { super(context); report = new RaplaMenuItem("report"); report.getMenuElement().setText( name); final Icon icon = getIcon("icon.info_small"); report.getMenuElement().setIcon( icon); report.addActionListener( this); } public String getId() { return "report"; } @Override public MenuElement getMenuElement() { return report; } public void actionPerformed( ActionEvent e ) { try { RaplaRightsReport report = new RaplaRightsReport( getContext()); DialogUI dialog = DialogUI.create( getContext(),getMainComponent(),true, report.getComponent(), new String[] {getString("ok")}); dialog.setTitle( name); dialog.setSize( 650, 550); report.show(); dialog.startNoPack(); } catch (RaplaException ex) { showException( ex, getMainComponent()); } } }
04900db4-rob
src/org/rapla/plugin/rightsreport/RightsReportMenu.java
Java
gpl3
1,658
package org.rapla.plugin.rightsreport; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeModel; import org.rapla.entities.Category; import org.rapla.entities.User; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.TreeFactory; import org.rapla.gui.toolkit.RaplaTree; public class RaplaRightsReport extends RaplaGUIComponent implements ItemListener, TreeSelectionListener, DocumentListener { final Category rootCategory = getQuery().getUserGroupsCategory(); // definition of different panels JPanel mainPanel; JPanel northPanel; JPanel centerPanel; JComboBox cbView; View view = View.USERGROUPS; // hierarchical tree RaplaTree selectionTreeTable; // list for the presentation of the assigned elements DefaultListModel assignedElementsListModel; JList assignedElementsList; JScrollPane assignedElementsScrollPane; // text field for filter JTextField filterTextField; Collection<Object> notAllList = new HashSet<Object>(); public RaplaRightsReport(RaplaContext context) throws RaplaException { super(context); // creation of different panels mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); northPanel = new JPanel(); northPanel.setLayout(new GridLayout(0, 1)); centerPanel = new JPanel(); centerPanel.setLayout(new GridLayout(0, 2)); // add northPanel and centerPanel to the mainPanel - using BoarderLayout mainPanel.add(northPanel, BorderLayout.NORTH); mainPanel.add(centerPanel, BorderLayout.CENTER); // creation of the ComboBox to choose one of the views // adding the ComboBox to the northPanel @SuppressWarnings("unchecked") JComboBox jComboBox = new JComboBox(new String[] {getString("groups"), getString("users")}); cbView = jComboBox; cbView.addItemListener(this); northPanel.add(cbView); // creation of the filter-text field and adding this object (this) as // DocumentListener // note: DocumentListener registers all changes filterTextField = new JTextField(); filterTextField.getDocument().addDocumentListener(this); northPanel.add(filterTextField); // creation of the tree selectionTreeTable = new RaplaTree(); selectionTreeTable.setMultiSelect( true); selectionTreeTable.getTree().setCellRenderer(getTreeFactory().createRenderer()); selectionTreeTable.getTree().addTreeSelectionListener(this); // including the tree in ScrollPane and adding this to the GUI centerPanel.add(selectionTreeTable); // creation of the list for the assigned elements assignedElementsList = new JList(); assignedElementsListModel = new DefaultListModel(); setRenderer(); // including the list in ScrollPaneListe and adding this to the GUI assignedElementsScrollPane = new JScrollPane(assignedElementsList); centerPanel.add(assignedElementsScrollPane); } @SuppressWarnings("unchecked") private void setRenderer() { assignedElementsList.setCellRenderer(new CategoryListCellRenderer()); } public JComponent getComponent() { return mainPanel; } public void show() { // set default values view = View.USERGROUPS; filterTextField.setText(""); loadView(); } // provides a TreeFactory -> interface for facade, provides the tree // (groups/users) private TreeFactory getTreeFactory() { return getService(TreeFactory.class); } // change of the ComboBox -> new view has been chosen public void itemStateChanged(ItemEvent e) { JComboBox cbViewSelection = (JComboBox) e.getSource(); // definition of the internal variable for storing the view if (cbViewSelection.getSelectedIndex() == 0) view = View.USERGROUPS; else if (cbViewSelection.getSelectedIndex() == 1) view = View.USERS; // build of the screen according to the view loadView(); } // selection of one or more elements in the tree @SuppressWarnings("unchecked") public void valueChanged(TreeSelectionEvent event) { try { assignedElementsListModel.clear(); List<Object> selectedElements = selectionTreeTable.getSelectedElements(); Set<Object> commonElements = new TreeSet<Object>(); notAllList.clear(); User[] allUsers = getQuery().getUsers(); boolean first = true; for ( Object sel:selectedElements) { List<Object> elementsToAdd = new ArrayList<Object>(); if ( sel instanceof User) { User user= (User) sel; for ( Category cat:user.getGroups()) { elementsToAdd.add( cat); } } if ( sel instanceof Category) { Category category = (Category) sel; for (User user : allUsers) { if (user.belongsTo(category)) elementsToAdd.add(user); } } for ( Object toAdd: elementsToAdd) { if (!first && !commonElements.contains(toAdd)) { notAllList.add( toAdd); } commonElements.add( toAdd); } first = false; } for (Object element : commonElements) { assignedElementsListModel.addElement(element); } assignedElementsList.setModel(assignedElementsListModel); } catch (RaplaException ex) { showException(ex, getMainComponent()); } } // this method builds the current screen (GUI) according to the variable // "view" private void loadView() { // reset the filter filterTextField.setText(""); filter(); } // search categories with specified pattern in categoryname (only child of // rootCategory) private List<Category> searchCategoryName(Category rootCategory, String pattern) { List<Category> categories = new ArrayList<Category>(); Locale locale = getLocale(); // loop all child of rootCategory for (Category category : rootCategory.getCategories()) { // is category a leaf? if (category.getCategories().length == 0) { // does the specified pattern matches with the the categoryname? if (Pattern.matches(pattern.toLowerCase(locale), category.getName(locale).toLowerCase(locale))) categories.add(category); } else { // get all child with a matching name (recursive) categories.addAll(searchCategoryName(category, pattern)); } } sortCategories(categories); return categories; } @SuppressWarnings("unchecked") public void sortCategories(List<Category> categories) { Collections.sort(categories); } // search users with specified pattern in username private List<User> searchUserName(String pattern) throws RaplaException { List<User> users = new ArrayList<User>(); Locale locale = getLocale(); // get all users for (User user : getQuery().getUsers()) { // does the specified pattern matches with the the username? if (Pattern.matches(pattern.toLowerCase(locale), user.getUsername() .toLowerCase(locale))) users.add(user); } sort(users); return users; } @SuppressWarnings("unchecked") public void sort(List<User> users) { Collections.sort(users); } private void filter() { // add regular expressions to filter pattern String pattern = ".*" + filterTextField.getText() + ".*"; try { selectionTreeTable.getTree().clearSelection(); TreeModel selectionModel = null; switch (view) { case USERGROUPS: // search all categories for the specified pattern and add // them to the list List<Category> categoriesToMatch = searchCategoryName(rootCategory,pattern); selectionModel = getTreeFactory().createModel(categoriesToMatch, false); break; case USERS: User[] users =searchUserName(pattern).toArray( User.USER_ARRAY); selectionModel = getTreeFactory().createModelFlat( users); // change the name of the root node in "user" ((DefaultMutableTreeNode) (selectionModel.getRoot())).setUserObject(getString("users")); break; } selectionTreeTable.getTree().setModel(selectionModel); assignedElementsListModel.clear(); } catch (RaplaException ex) { showException(ex, getMainComponent()); } } public void changedUpdate(DocumentEvent e) { } public void insertUpdate(DocumentEvent e) { // filter elements filter(); } public void removeUpdate(DocumentEvent e) { // filter elements filter(); } public enum View { USERS, USERGROUPS; } // ListCellRenderer to display the right name of categories based on locale class CategoryListCellRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 1L; public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Object userObject = value; if (value != null && value instanceof Category) { // if element in cell is a category: set the name of the // category value = ((Category) value).getName(getLocale()); } Component component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); Font f; if (notAllList.contains( userObject)) { f =component.getFont().deriveFont(Font.ITALIC); } else { f =component.getFont().deriveFont(Font.BOLD); } component.setFont(f); return component; } } }
04900db4-rob
src/org/rapla/plugin/rightsreport/RaplaRightsReport.java
Java
gpl3
9,908
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.rightsreport; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.TypedComponentRole; import org.rapla.plugin.periodcopy.PeriodCopyPlugin; public class RightsReportPlugin implements PluginDescriptor<ClientServiceContainer> { public static final boolean ENABLE_BY_DEFAULT = true; public static final TypedComponentRole<I18nBundle> RESOURCE_FILE = new TypedComponentRole<I18nBundle>(PeriodCopyPlugin.class.getPackage().getName() + ".PeriodCopy"); public void provideServices(ClientServiceContainer container, Configuration config) { if ( !config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT) ) return; container.addContainerProvidedComponent( RaplaClientExtensionPoints.ADMIN_MENU_EXTENSION_POINT, RightsReportMenu.class); } }
04900db4-rob
src/org/rapla/plugin/rightsreport/RightsReportPlugin.java
Java
gpl3
1,949
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.abstractcalendar; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import org.rapla.components.calendarview.AbstractGroupStrategy; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.CalendarView; import org.rapla.entities.NamedComparator; import org.rapla.entities.domain.Allocatable; /** Tries to put reservations that allocate the same Resources in the same column.*/ public class GroupAllocatablesStrategy extends AbstractGroupStrategy { Comparator<Allocatable> allocatableComparator; Collection<Allocatable> allocatables = new ArrayList<Allocatable>(); public GroupAllocatablesStrategy(Locale locale) { allocatableComparator = new NamedComparator<Allocatable>( locale ); } public void setAllocatables( Collection<Allocatable> allocatables) { this.allocatables = allocatables; } @Override protected Map<Block, Integer> getBlockMap(CalendarView wv, List<Block> blocks) { return super.getBlockMap(wv, blocks); } protected Collection<List<Block>> group(List<Block> list) { HashMap<Allocatable,List<Block>> groups = new HashMap<Allocatable,List<Block>>(); for (Iterator<Allocatable> it = allocatables.iterator();it.hasNext(); ) { groups.put( it.next(), new ArrayList<Block>() ); } List<Block> noAllocatablesGroup = null; for (Iterator<Block> it = list.iterator();it.hasNext();) { AbstractRaplaBlock block = (AbstractRaplaBlock) it.next(); Allocatable allocatable = block.getContext().getGroupAllocatable(); if (allocatable == null) { if (noAllocatablesGroup == null) noAllocatablesGroup = new ArrayList<Block>(); noAllocatablesGroup.add(block); continue; } List<Block> col = groups.get( allocatable ); if (col == null) { col = new ArrayList<Block>(); groups.put( allocatable, col ); } col.add(block); } ArrayList<Allocatable> sortedAllocatables = new ArrayList<Allocatable>(groups.keySet()); Collections.sort(sortedAllocatables, allocatableComparator); ArrayList<List<Block>> sortedList = new ArrayList<List<Block>>(); for (Iterator<Allocatable> it = sortedAllocatables.iterator();it.hasNext();) { sortedList.add( groups.get(it.next()) ); } if (noAllocatablesGroup != null) sortedList.add(noAllocatablesGroup); return sortedList; } }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/GroupAllocatablesStrategy.java
Java
gpl3
3,762
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.abstractcalendar; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.border.TitledBorder; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateChangeListener; import org.rapla.components.calendar.RaplaArrowButton; import org.rapla.components.calendar.RaplaCalendar; import org.rapla.components.layout.TableLayout; import org.rapla.entities.domain.Period; import org.rapla.facade.CalendarModel; import org.rapla.facade.PeriodModel; import org.rapla.facade.QueryModule; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.internal.common.PeriodChooser; import org.rapla.gui.toolkit.RaplaButton; import org.rapla.gui.toolkit.RaplaWidget; public class DateChooserPanel extends RaplaGUIComponent implements Disposable ,RaplaWidget { Collection<DateChangeListener> listenerList = new ArrayList<DateChangeListener>(); JPanel panel = new JPanel(); JButton prevButton = new RaplaArrowButton('<', 20); RaplaCalendar dateSelection; PeriodChooser periodChooser; JButton nextButton = new RaplaArrowButton('>', 20); int incrementSize = Calendar.WEEK_OF_YEAR; CalendarModel model; Listener listener = new Listener(); JPanel periodPanel; JButton todayButton= new RaplaButton(getString("today"), RaplaButton.SMALL); public DateChooserPanel(RaplaContext sm, CalendarModel model) throws RaplaException { super( sm ); this.model = model; prevButton.setSize(30, 20); nextButton.setSize(30, 20); periodChooser = new PeriodChooser(getContext(),PeriodChooser.START_ONLY); dateSelection = createRaplaCalendar(); //prevButton.setText("<"); //nextButton.setText(">"); double pre =TableLayout.PREFERRED; double[][] sizes = {{5,pre,5,pre,2,pre,0.02,0.9,5,0.02} ,{/*0.5,*/pre/*,0.5*/}}; TableLayout tableLayout = new TableLayout(sizes); JPanel calendarPanel = new JPanel(); TitledBorder titleBorder = BorderFactory.createTitledBorder(getI18n().getString("date")); calendarPanel.setBorder(titleBorder); panel.setLayout(tableLayout); calendarPanel.add(dateSelection); calendarPanel.add(todayButton); int todayWidth = (int)Math.max(40, todayButton.getPreferredSize().getWidth()); todayButton.setPreferredSize( new Dimension(todayWidth,20)); calendarPanel.add(prevButton); calendarPanel.add(nextButton); panel.add(calendarPanel, "1, 0"); periodPanel = new JPanel(new GridLayout(1,1)); titleBorder = BorderFactory.createTitledBorder(getI18n().getString("period")); periodPanel.setBorder(titleBorder); periodPanel.add(periodChooser); panel.add(periodPanel,"7,0"); periodChooser.setDate(getQuery().today()); nextButton.addActionListener( listener ); prevButton.addActionListener( listener); dateSelection.addDateChangeListener( listener); periodChooser.addActionListener( listener); todayButton.addActionListener(listener); update(); } boolean listenersEnabled = true; public void update() { listenersEnabled = false; try { final PeriodModel periodModel = getPeriodModel(); periodChooser.setPeriodModel( periodModel); if ( model.getSelectedDate() == null) { QueryModule query = getQuery(); Date today = query.today(); model.setSelectedDate( today); } Date date = model.getSelectedDate(); periodChooser.setDate( date); dateSelection.setDate( date); periodPanel.setVisible( periodModel.getSize() > 0); } finally { listenersEnabled = true; } } public void dispose() { periodChooser.removeActionListener( listener ); periodChooser.dispose(); } public void setNavigationVisible( boolean enable) { nextButton.setVisible( enable); prevButton.setVisible( enable); } /** possible values are Calendar.DATE, Calendar.WEEK_OF_YEAR, Calendar.MONTH and Calendar.YEAR. Default is Calendar.WEEK_OF_YEAR. */ public void setIncrementSize(int incrementSize) { this.incrementSize = incrementSize; } /** registers new DateChangeListener for this component. * An DateChangeEvent will be fired to every registered DateChangeListener * when the a different date is selected. * @see DateChangeListener * @see DateChangeEvent */ public void addDateChangeListener(DateChangeListener listener) { listenerList.add(listener); } /** removes a listener from this component.*/ public void removeDateChangeListener(DateChangeListener listener) { listenerList.remove(listener); } public DateChangeListener[] getDateChangeListeners() { return listenerList.toArray(new DateChangeListener[]{}); } /** An ActionEvent will be fired to every registered ActionListener * when the a different date is selected. */ protected void fireDateChange(Date date) { if (listenerList.size() == 0) return; DateChangeListener[] listeners = getDateChangeListeners(); DateChangeEvent evt = new DateChangeEvent(this,date); for (int i = 0;i<listeners.length;i++) { listeners[i].dateChanged(evt); } } public JComponent getComponent() { return panel; } class Listener implements ActionListener, DateChangeListener { public void actionPerformed(ActionEvent evt) { if (!listenersEnabled) return; Date date; Calendar calendar = getRaplaLocale().createCalendar(); Date date2 = dateSelection.getDate(); calendar.setTime(date2); if (evt.getSource() == prevButton) { calendar.add(incrementSize,-1); } //eingefuegt: rku if (evt.getSource() == todayButton) { Date today = getQuery().today(); calendar.setTime(today); } if (evt.getSource() == nextButton) { calendar.add(incrementSize,1); } if (evt.getSource() == periodChooser) { date = periodChooser.getDate(); Period period = periodChooser.getPeriod(); model.setStartDate( period.getStart() ); model.setEndDate( period.getEnd() ); } else { date = calendar.getTime(); } updateDates( date ); fireDateChange( date); } public void dateChanged(DateChangeEvent evt) { if ( !listenersEnabled) return; try { listenersEnabled = false; } finally { listenersEnabled = true; } Date date = evt.getDate(); updateDates( date); fireDateChange(date); } private void updateDates(Date date) { try { listenersEnabled = false; model.setSelectedDate( date ); // EXCO: It seems not nice to me that the start date // is in the parameter and the end date is extracted // from the model. // But, with this way, I am certain that // nothing can get broken. Date endDate = model.getEndDate(); periodChooser.setDate( date, endDate ); dateSelection.setDate( date); } finally { listenersEnabled = true; } } } }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/DateChooserPanel.java
Java
gpl3
9,117
package org.rapla.plugin.abstractcalendar; public interface MultiCalendarPrint { String getCalendarUnit(); void setUnits(int units); int getUnits(); }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/MultiCalendarPrint.java
Java
gpl3
170
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.abstractcalendar; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.MediaTracker; import java.awt.Paint; import java.awt.Point; import java.awt.Rectangle; import java.awt.TexturePaint; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.event.MouseInputListener; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.swing.SwingBlock; import org.rapla.entities.Named; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Repeating; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaContextException; import org.rapla.gui.InfoFactory; import org.rapla.gui.toolkit.AWTColorUtil; public class SwingRaplaBlock extends AbstractRaplaBlock implements SwingBlock { private static BufferedImage exceptionImage; RaplaBlockView m_view = new RaplaBlockView(); public Icon getRepeatingIcon() { return getI18n().getIcon("icon.repeating"); } public ImageIcon getExceptionBackgroundIcon() { return getI18n().getIcon("icon.exceptionBackground"); } private BufferedImage getExceptionImage() { if ( exceptionImage != null ) return exceptionImage; Image image = getExceptionBackgroundIcon().getImage(); MediaTracker m = new MediaTracker( m_view ); m.addImage( image, 0 ); try { m.waitForID( 0 ); } catch ( InterruptedException ex ) { } exceptionImage = new BufferedImage( image.getWidth( null ), image.getHeight( null ), BufferedImage.TYPE_INT_ARGB ); Graphics g = exceptionImage.getGraphics(); g.drawImage( image, 0, 0, null ); return exceptionImage; } public Component getView() { return m_view; } public boolean isException() { Repeating repeating = getAppointment().getRepeating(); return repeating != null && repeating.isException( getStart().getTime() ); } static Color TRANS = new Color( 100, 100, 100, 100 ); public void paintDragging( Graphics g, int width, int height ) { g.setColor( TRANS ); m_view.paint( g, width, height ); g.setColor( LINECOLOR_ACTIVE ); g.drawRoundRect( 0, 0, width, height, 5, 5 ); } static Font FONT_TITLE = new Font( "SansSerif", Font.BOLD, 12 ); static Font FONT_SMALL_TITLE = new Font( "SansSerif", Font.BOLD, 10 ); static Font FONT_INVISIBLE = new Font( "SansSerif", Font.PLAIN, 10 ); static Font FONT_RESOURCE = new Font( "SansSerif", Font.PLAIN, 12 ); static Font FONT_PERSON = new Font( "SansSerif", Font.ITALIC, 12 ); static String FOREGROUND_COLOR = AWTColorUtil.getHexForColor( Color.black ); static Map<Integer,Map<String,Color>> alphaMap = new HashMap<Integer, Map<String,Color>>(); private static Color LINECOLOR_INACTIVE = Color.darkGray; private static Color LINECOLOR_ACTIVE = new Color( 255, 90, 10 ); private static Color LINECOLOR_SAME_RESERVATION = new Color( 180, 20, 120 ); // The Linecolor is not static because it can be changed depending on the mouse move private Color linecolor = LINECOLOR_INACTIVE; class RaplaBlockView extends JComponent implements MouseInputListener { private static final long serialVersionUID = 1L; RaplaBlockView() { javax.swing.ToolTipManager.sharedInstance().registerComponent( this ); addMouseListener( this ); } public String getName( Named named ) { return SwingRaplaBlock.this.getName( named ); } public String getToolTipText( MouseEvent evt ) { String text = ""; if ( getContext().isAnonymous() ) { text = getI18n().getString( "not_visible.help" ); } else if ( !getContext().isBlockSelected() && !getBuildContext().isConflictSelected() ) { text = getI18n().getString( "not_selected.help" ); } else { try { InfoFactory infoFactory = getBuildContext().getServiceManager().lookup( InfoFactory.class); text = infoFactory.getToolTip( getAppointment(), false ); } catch ( RaplaContextException ex ) { } } return "<html>" + text + "</html>"; } private Color adjustColor( String org, int alpha ) { Map<String,Color> colorMap = alphaMap.get( alpha ); if ( colorMap == null ) { colorMap = new HashMap<String,Color>(); alphaMap.put( alpha, colorMap ); } Color color = colorMap.get( org ); if ( color == null ) { Color or; try { or = AWTColorUtil.getColorForHex( org ); } catch ( NumberFormatException nf ) { or = AWTColorUtil.getColorForHex( "#FFFFFF" ); } color = new Color( or.getRed(), or.getGreen(), or.getBlue(), alpha ); colorMap.put( org, color ); } return color; } public void paint( Graphics g ) { Dimension dim = getSize(); paint( g, dim.width, dim.height ); } public void paint( Graphics g, int width, int height ) { int alpha = g.getColor().getAlpha(); if ( !getContext().isBlockSelected() ) { alpha = 80; paintBackground( g, width, height, alpha ); } else { paintBackground( g, width, height, alpha ); } if (width <=5) { return; } //boolean isException = getAppointment().getRepeating().isException(getStart().getTime()); Color fg = adjustColor( FOREGROUND_COLOR, alpha ); //(isException() ? Color.white : Color.black); g.setColor( fg ); if ( getAppointment().getRepeating() != null && getBuildContext().isRepeatingVisible() ) { if ( !getContext().isAnonymous() && getContext().isBlockSelected() && !isException() ) { getRepeatingIcon().paintIcon( this, g, width - 17, 0 ); } /* if ( getBuildContext().isTimeVisible() ) g.clipRect(0,0, width -17, height); */ } // y will store the y-position of the carret int y = -2; // Draw the Reservationname boolean small = (height < 30); String timeString = getTimeString(small); StringBuffer buf = new StringBuffer(); if ( timeString != null ) { if ( !small) { g.setFont( FONT_SMALL_TITLE ); List<Allocatable> resources = getContext().getAllocatables(); StringBuffer buffer = new StringBuffer() ; for (Allocatable resource: resources) { if ( getContext().isVisible( resource) && !resource.isPerson()) { if ( buffer.length() > 0) { buffer.append(", "); } buffer.append( getName(resource)); } } if ( !getBuildContext().isResourceVisible() && buffer.length() > 0) { timeString = timeString + " " + buffer.toString(); } y = drawString( g, timeString, y, 2, false ) - 1; } else { buf.append( timeString ); buf.append( " " ); } } if ( !small) { g.setFont( FONT_TITLE ); } else { g.setFont( FONT_SMALL_TITLE ); } if ( getContext().isAnonymous() ) { y += 4; g.setFont( FONT_INVISIBLE ); String label = getI18n().getString( "not_visible" ); buf.append(label); y = drawString( g, buf.toString(), y, 5, true ) + 2; return; } String label = getName( getReservation() ); buf.append(label); y = drawString( g, buf.toString(), y, 2, true ) + 2; // If the y reaches the lowerBound "..." will be displayed double lowerBound = height - 11; if ( getBuildContext().isPersonVisible() ) { g.setFont( FONT_PERSON ); g.setColor( fg ); List<Allocatable> persons = getContext().getAllocatables(); for ( Allocatable person:persons) { String text = getName( person); if ( !getContext().isVisible( person) || !person.isPerson()) continue; if ( y > lowerBound ) { text = "..."; y -= 7; } y = drawString( g, text, y, 7, true ); } } else { g.setFont( FONT_PERSON ); g.setColor( fg ); buf = new StringBuffer(); List<Allocatable> persons = getContext().getAllocatables(); for ( Allocatable person:persons) { if ( !getContext().isVisible( person) || !person.isPerson()) continue; if ( buf.length() > 0) { buf.append(", "); } buf.append( getName( person )); } String text = buf.toString(); y = drawString( g, text, y, 7, true ); } if ( getBuildContext().isResourceVisible() ) { List<Allocatable> resources = getContext().getAllocatables(); g.setFont( FONT_RESOURCE ); g.setColor( fg ); for ( Allocatable resource:resources) { if ( !getContext().isVisible( resource) || resource.isPerson()) continue; String text = getName( resource ); if ( y > lowerBound ) { text = "..."; y -= 7; } y = drawString( g, text, y, 7, true ); } } } private void setExceptionPaint( Graphics g ) { Paint p = new TexturePaint( getExceptionImage(), new Rectangle( 14, 14 ) ); ( (Graphics2D) g ).setPaint( p ); } private void paintBackground( Graphics g, int width, int height, int alpha ) { String[] colors = getColorsAsHex(); double colWidth = (double) ( width - 2 ) / colors.length; int x = 0; for ( int i = 0; i < colors.length; i++ ) { g.setColor( adjustColor( colors[i], alpha ) ); g.fillRect( (int) Math.ceil( x ) + 1, 1, (int) Math.ceil( colWidth ), height - 2 ); if ( isException() ) { setExceptionPaint( g ); g.fillRect( (int) Math.ceil( x ) + 1, 1, (int) Math.ceil( colWidth ), height - 2 ); } x += colWidth; } //g.setColor( adjustColor( "#000000", alpha ) ); g.setColor( linecolor ); g.drawRoundRect( 0, 0, width - 1, height - 1, 5, 5 ); } private int findBreaking( final char[] c, final int offset, final int len, final int maxWidth, final FontMetrics fm, final boolean allCharacters ) { int index = -1; for ( int i = offset; i < offset + len; i++ ) { if ( allCharacters || c[i] == ' ' ) { int charsWidth = fm.charsWidth( c, offset, i - offset ); if ( charsWidth < maxWidth ) { index = i; } else { return index; } } } return index; } // @return the new y-coordiante below the text private int drawString( Graphics g, String text, int y, int indent, boolean breakLines ) { FontMetrics fm = g.getFontMetrics(); //g.setFont(new Font("SimSun",Font.PLAIN, 12)); char[] c = text.toCharArray(); int cWidth = getSize().width - indent; int cHeight = getSize().height; int height = fm.getHeight(); int len = c.length; int offset = 0; int x = indent; int maxWidth = ( y >= 14 || getAppointment().getRepeating() == null || !getBuildContext() .isRepeatingVisible() ) ? cWidth : cWidth - 12; if ( !breakLines ) { maxWidth = maxWidth - 5; } else { if (breakLines) { while ( offset < c.length && fm.charsWidth( c, offset, len ) > maxWidth ) { int breakingSpace = findBreaking( c, offset, len, maxWidth, fm, false ); //int x = bCenter ? (getSize().width - width)/2 : indent ; if ( breakingSpace >= offset ) { y+= height; int length = breakingSpace-offset; g.drawChars(c,offset,length,x,y); // System.out.println("Drawing " + new String(c,offset,breakingSpace-offset)); len -= length + 1; offset = breakingSpace + 1; } else { int breakingChar = findBreaking( c, offset, len, maxWidth, fm, true ); if ( breakingChar >= offset) { y+= height; int length = breakingChar-offset; if ( c.length >= offset + length) { g.drawChars(c,offset,length,x,y); } else { getContext().getBuildContext().getLogger().error("wrong offset[" + offset + "] or length["+ length + "] for string '"+ text + "'"); } // System.out.println("Drawing " + new String(c,offset,breakingSpace-offset)); len -= length ; offset = breakingChar; } else { break; } } if (y >= cHeight) { break; } // System.out.println("New len " + len + " new offset " + offset); maxWidth = cWidth; } } } if (y <= cHeight - height/2 ) { y = y + height; if (c.length >= offset + len) { g.drawChars( c, offset, len, x, y ); } else { getContext().getBuildContext().getLogger().error("wrong offset[" + offset + "] or length["+ len + "] for string '"+ text + "'"); } } // System.out.println("Drawing rest " + new String(c,offset,len)); return y; } public void mouseClicked( MouseEvent arg0 ) { } public void mousePressed( MouseEvent arg0 ) {} public void mouseReleased( MouseEvent evt ) { Point mp = evt.getPoint(); boolean inside = mp.x >= 0 && mp.y >= 0 && mp.x <= getWidth() && mp.y <= getHeight(); changeLineBorder( inside && getContext().isBlockSelected() ); } public void mouseEntered( MouseEvent evt ) { if ( ( ( evt.getModifiers() & MouseEvent.BUTTON1_MASK ) > 0 ) || !getContext().isBlockSelected() ) { return; } changeLineBorder( true ); } public void mouseExited( MouseEvent evt ) { if ( ( evt.getModifiers() & MouseEvent.BUTTON1_MASK ) > 0 ) { return; } changeLineBorder( false ); } public void mouseDragged( MouseEvent arg0 ) {} public void mouseMoved( MouseEvent arg0 ) { } private void changeLineBorder( boolean active ) { List<Block> blocks = getBuildContext().getBlocks(); for ( Iterator<Block> it = blocks.iterator(); it.hasNext(); ) { SwingRaplaBlock block = (SwingRaplaBlock) it.next(); Appointment appointment = block.getAppointment(); Reservation reservation = appointment.getReservation(); // A reservation can be null because the appointment was recently removed from the reservation and the swing view had no time to rebuild if ( reservation == null) { return; } if ( appointment.equals( getAppointment() ) ) { block.linecolor = active ? LINECOLOR_ACTIVE : LINECOLOR_INACTIVE; block.m_view.repaint(); } else if ( reservation.equals( getReservation() ) ) { block.linecolor = active ? LINECOLOR_SAME_RESERVATION : LINECOLOR_INACTIVE; block.m_view.repaint(); } } } } public String toString() { return getName() + " " + getStart() + " - " + getEnd(); } }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/SwingRaplaBlock.java
Java
gpl3
20,427
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.abstractcalendar; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.border.TitledBorder; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateChangeListener; import org.rapla.components.calendar.RaplaArrowButton; import org.rapla.components.calendar.RaplaCalendar; import org.rapla.components.layout.TableLayout; import org.rapla.components.util.DateTools; import org.rapla.entities.domain.Period; import org.rapla.facade.CalendarModel; import org.rapla.facade.PeriodModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.internal.common.PeriodChooser; import org.rapla.gui.toolkit.RaplaButton; import org.rapla.gui.toolkit.RaplaWidget; public class IntervalChooserPanel extends RaplaGUIComponent implements RaplaWidget { Collection<DateChangeListener> listenerList = new ArrayList<DateChangeListener>(); PeriodChooser periodChooser; JPanel panel = new JPanel(); RaplaCalendar startDateSelection; RaplaCalendar endDateSelection; // BJO 00000042 JButton startTodayButton= new RaplaButton(getString("today"), RaplaButton.SMALL); JButton prevStartButton = new RaplaArrowButton('<', 20); JButton nextStartButton = new RaplaArrowButton('>', 20); { prevStartButton.setSize(30, 20); nextStartButton.setSize(30, 20); } JButton endTodayButton= new RaplaButton(getString("today"), RaplaButton.SMALL); JButton prevEndButton = new RaplaArrowButton('<', 20); JButton nextEndButton = new RaplaArrowButton('>', 20); { prevEndButton.setSize(30, 20); nextEndButton.setSize(30, 20); } int incrementSize = Calendar.WEEK_OF_YEAR; // BJO00000042 boolean listenersEnabled = true; CalendarModel model; Listener listener = new Listener(); JPanel periodPanel; public IntervalChooserPanel(RaplaContext sm, CalendarModel model) throws RaplaException { super(sm); this.model = model; periodChooser = new PeriodChooser(getContext(),PeriodChooser.START_AND_END); periodChooser.setWeekOfPeriodVisible( false ); startDateSelection = createRaplaCalendar(); endDateSelection = createRaplaCalendar(); //prevButton.setText("<"); //nextButton.setText(">"); double pre =TableLayout.PREFERRED; double[][] sizes = {{5,pre, 5, pre, 5,0.9,0.02} ,{pre}}; TableLayout tableLayout = new TableLayout(sizes); int todayWidth = (int)Math.max(40, startTodayButton.getPreferredSize().getWidth()); startTodayButton.setPreferredSize( new Dimension(todayWidth,20)); endTodayButton.setPreferredSize( new Dimension(todayWidth,20)); panel.setLayout(tableLayout); JPanel startPanel = new JPanel(); TitledBorder titleBorder = BorderFactory.createTitledBorder(getString("start_date")); startPanel.setBorder(titleBorder); startPanel.add(startDateSelection); // BJO 00000042 startPanel.add(startTodayButton); startPanel.add(prevStartButton); startPanel.add(nextStartButton); startTodayButton.addActionListener( listener ); prevStartButton.addActionListener( listener ); nextStartButton.addActionListener( listener ); // BJO 00000042 panel.add(startPanel,"1,0"); JPanel endPanel = new JPanel(); titleBorder = BorderFactory.createTitledBorder(getString("end_date")); endPanel.setBorder(titleBorder); endPanel.add(endDateSelection); // BJO 00000042 endPanel.add(endTodayButton); endPanel.add(prevEndButton); endPanel.add(nextEndButton); endTodayButton.addActionListener( listener ); prevEndButton.addActionListener( listener ); nextEndButton.addActionListener( listener ); // BJO 00000042 panel.add(endPanel,"3,0"); periodPanel = new JPanel(new GridLayout(1,1)); titleBorder = BorderFactory.createTitledBorder(getString("period")); periodPanel.setBorder(titleBorder); periodPanel.add(periodChooser); panel.add( periodPanel,"5,0"); periodChooser.addActionListener( listener ); startDateSelection.addDateChangeListener( listener ); endDateSelection.addDateChangeListener( listener ); update(); } public void update() { listenersEnabled = false; try { Date startDate = model.getStartDate(); startDateSelection.setDate( startDate); final PeriodModel periodModel = getPeriodModel(); periodChooser.setPeriodModel( periodModel); periodChooser.setDate( startDate ); Date endDate = model.getEndDate(); periodPanel.setVisible( periodModel.getSize() > 0); endDateSelection.setDate( DateTools.subDay(endDate)); } finally { listenersEnabled = true; } } // BJO00000042 /** possible values are Calendar.DATE, Calendar.WEEK_OF_YEAR, Calendar.MONTH and Calendar.YEAR. Default is Calendar.WEEK_OF_YEAR. */ public void setIncrementSize(int incrementSize) { this.incrementSize = incrementSize; } // BJO00000042 /** registers new DateChangeListener for this component. * An DateChangeEvent will be fired to every registered DateChangeListener * when the a different date is selected. * @see DateChangeListener * @see DateChangeEvent */ public void addDateChangeListener(DateChangeListener listener) { listenerList.add(listener); } /** removes a listener from this component.*/ public void removeDateChangeListener(DateChangeListener listener) { listenerList.remove(listener); } public DateChangeListener[] getDateChangeListeners() { return listenerList.toArray(new DateChangeListener[]{}); } /** An ActionEvent will be fired to every registered ActionListener * when a different date is selected. */ protected void fireDateChange(Date date) { if (listenerList.size() == 0) return; DateChangeListener[] listeners = getDateChangeListeners(); DateChangeEvent evt = new DateChangeEvent(this,date); for (int i = 0;i<listeners.length;i++) { listeners[i].dateChanged(evt); } } public JComponent getComponent() { return panel; } class Listener implements DateChangeListener, ActionListener { public void actionPerformed( ActionEvent e ) { if ( !listenersEnabled ) return; // BJO 00000042 Date date; Calendar calendar = getRaplaLocale().createCalendar(); if (e.getSource() == prevStartButton) { calendar.setTime(startDateSelection.getDate()); calendar.add(incrementSize,-1); date = calendar.getTime(); startDateSelection.setDate(date); } else if (e.getSource() == nextStartButton) { calendar.setTime(startDateSelection.getDate()); calendar.add(incrementSize,1); date = calendar.getTime(); startDateSelection.setDate(date); } else if (e.getSource() == prevEndButton) { calendar.setTime(endDateSelection.getDate()); calendar.add(incrementSize,-1); date = calendar.getTime(); endDateSelection.setDate(date); } else if (e.getSource() == nextEndButton) { calendar.setTime(endDateSelection.getDate()); calendar.add(incrementSize,1); date = calendar.getTime(); endDateSelection.setDate(date); } else if (e.getSource() == startTodayButton) { calendar.setTime(new Date()); date = calendar.getTime(); startDateSelection.setDate(date); } else if (e.getSource() == endTodayButton) { calendar.setTime(new Date()); date = calendar.getTime(); endDateSelection.setDate(date); } // BJO 00000042 Period period = periodChooser.getPeriod(); if ( period == null) { return; } updateDates( period.getStart(), period.getEnd()); fireDateChange( period.getStart()); } public void dateChanged(DateChangeEvent evt) { if ( !listenersEnabled ) return; if ( evt.getSource() == startDateSelection) { Date newStartDate = startDateSelection.getDate(); if (newStartDate.after( endDateSelection.getDate())) { Date endDate = DateTools.addDays(newStartDate, 1); endDateSelection.setDate( endDate); } } if ( evt.getSource() == endDateSelection) { Date newEndDate = endDateSelection.getDate(); if (newEndDate.before( startDateSelection.getDate())) { Date startDate = DateTools.addDays(newEndDate, -1); startDateSelection.setDate( startDate); } } updateDates( startDateSelection.getDate(), DateTools.addDay(endDateSelection.getDate())); fireDateChange(evt.getDate()); } private void updateDates(Date start, Date end) { try { listenersEnabled = false; model.setStartDate( start); model.setEndDate( end ); model.setSelectedDate( start ); // start startDateSelection.setDate( start); endDateSelection.setDate( end ); } finally { listenersEnabled = true; } } } }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/IntervalChooserPanel.java
Java
gpl3
11,527
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.abstractcalendar; import java.util.Date; import org.rapla.components.calendarview.Block; import org.rapla.framework.RaplaContext; public class SwingRaplaBuilder extends RaplaBuilder { public SwingRaplaBuilder(RaplaContext sm) { super(sm); } /** * @see org.rapla.plugin.abstractcalendar.RaplaBuilder#createBlock(calendar.RaplaBuilder.RaplaBlockContext, java.util.Date, java.util.Date) */ protected Block createBlock(RaplaBlockContext blockContext, Date start, Date end) { SwingRaplaBlock block = new SwingRaplaBlock(); block.contextualize(blockContext); block.setStart(start); block.setEnd(end); return block; } }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/SwingRaplaBuilder.java
Java
gpl3
1,665
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.abstractcalendar; import java.util.Date; import java.util.LinkedHashSet; import java.util.List; import org.rapla.components.calendarview.Block; import org.rapla.components.util.DateTools; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.Named; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.Reservation; import org.rapla.framework.RaplaLocale; import org.rapla.plugin.abstractcalendar.RaplaBuilder.BuildContext; public abstract class AbstractRaplaBlock implements Block { RaplaBuilder.RaplaBlockContext m_context; Date m_start; Date m_end; RaplaLocale m_raplaLocale; protected String timeStringSeperator = " -"; protected AbstractRaplaBlock() { } public void contextualize(RaplaBuilder.RaplaBlockContext context) { m_context = context; m_raplaLocale = getBuildContext().getRaplaLocale(); } public String getName(Named named) { return named.getName(m_raplaLocale.getLocale()); } public String getName() { return getReservation().getName( m_raplaLocale.getLocale()); } public Date getStart() { return m_start; } public Date getEnd() { return m_end; } protected I18nBundle getI18n() { return getBuildContext().getI18n(); } public void setStart(Date start) { m_start = start; } public void setEnd(Date end) { m_end = end; } public Appointment getAppointment() { return getContext().getAppointment(); } public Reservation getReservation() { return getAppointment().getReservation(); } public AppointmentBlock getAppointmentBlock() { return getContext().getAppointmentBlock(); } protected RaplaBuilder.RaplaBlockContext getContext() { return m_context; } public Allocatable getGroupAllocatable() { return getContext().getGroupAllocatable(); } public RaplaBuilder.BuildContext getBuildContext() { return getContext().getBuildContext(); } public boolean isMovable() { return getContext().isMovable() && !isException(); } public boolean startsAndEndsOnSameDay() { return DateTools.isSameDay( getAppointment().getStart().getTime() ,getAppointment().getEnd().getTime() -1 ) ; } protected String[] getColorsAsHex() { BuildContext buildContext = getBuildContext(); LinkedHashSet<String> colorList = new LinkedHashSet<String>(); if ( buildContext.isEventColoringEnabled()) { Reservation reservation = getReservation(); if (reservation != null) { String eventColor = RaplaBuilder.getColorForClassifiable( reservation ); if ( eventColor != null) { colorList.add( eventColor); } } } if ( buildContext.isResourceColoringEnabled()) { List<Allocatable> allocatables = getContext().getSelectedAllocatables(); for (Allocatable alloc:allocatables) { String lookupColorString = buildContext.lookupColorString(alloc); if ( lookupColorString != null) { colorList.add( lookupColorString); } } } if ( colorList.size() == 0) { colorList.add(buildContext.lookupColorString(null)); } return colorList.toArray(new String[] {}); } protected String getTimeString(boolean small) { RaplaLocale loc = getBuildContext().getRaplaLocale(); String timeString = null; if ( getBuildContext().isTimeVisible()) { timeString = ""; // Don't show startTime if its 00:00 /* TODO nicht sinnvoll auch 0:00 als Start und Endzeit anzuzeigen?*/ if ( !DateTools.isMidnight(getStart()) ) { timeString = loc.formatTime( getStart() ); } if ( !small && !DateTools.isMidnight(getEnd().getTime() + 1)) { timeString = timeString + timeStringSeperator; timeString = timeString + loc.formatTime( getEnd()); } } return timeString; } public boolean isException() { return getAppointment().getRepeating() != null && getAppointment().getRepeating().isException(getStart().getTime()); } public boolean isStartResizable() { return startsAndEndsOnSameDay() && !isException(); } public boolean isEndResizable() { return startsAndEndsOnSameDay() && !isException(); } }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/AbstractRaplaBlock.java
Java
gpl3
5,704
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.abstractcalendar; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.RepaintManager; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateChangeListener; import org.rapla.components.calendarview.CalendarView; import org.rapla.components.calendarview.swing.AbstractSwingCalendar; import org.rapla.components.calendarview.swing.ViewListener; import org.rapla.components.util.DateTools; import org.rapla.components.util.TimeInterval; import org.rapla.entities.NamedComparator; import org.rapla.entities.domain.Allocatable; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.SwingCalendarView; import org.rapla.gui.SwingViewFactory; import org.rapla.gui.VisibleTimeInterval; public abstract class AbstractRaplaSwingCalendar extends RaplaGUIComponent implements SwingCalendarView, DateChangeListener, MultiCalendarPrint, VisibleTimeInterval, Printable { protected final CalendarModel model; protected final AbstractSwingCalendar view; protected DateChooserPanel dateChooser; JComponent container; JLabel titleView; int units = 1; public AbstractRaplaSwingCalendar(RaplaContext sm,CalendarModel model, boolean editable) throws RaplaException { super( sm); this.model = model; boolean printable = isPrintContext(); view = createView( !printable); view.setEditable(editable); view.setLocale( getRaplaLocale().getLocale() ); view.setTimeZone(getRaplaLocale().getTimeZone()); if ( editable ) { view.addCalendarViewListener( createListener() ); } if ( !printable ) { container = view.getComponent(); } else { container = new JPanel(); container.setLayout( new BorderLayout()); container.setOpaque( false ); view.getComponent().setOpaque( false); titleView = new JLabel(); titleView.setFont(new Font("SansSerif", Font.BOLD, 14)); titleView.setOpaque(false); titleView.setForeground(Color.black); //titleView.setHorizontalAlignment(JLabel.CENTER); titleView.setBorder(BorderFactory.createEmptyBorder(0,11,12,11)); container.add( titleView, BorderLayout.NORTH); container.add( view.getComponent(), BorderLayout.CENTER); } dateChooser = new DateChooserPanel(getContext(), model); dateChooser.addDateChangeListener(this); dateChooser.setIncrementSize( getIncrementSize() ); update(); } protected boolean isPrintContext() { return getContext().has(SwingViewFactory.PRINT_CONTEXT) && getService( SwingViewFactory.PRINT_CONTEXT); } abstract protected AbstractSwingCalendar createView(boolean showScrollPane) throws RaplaException; abstract protected void configureView() throws RaplaException; abstract public int getIncrementSize(); /** * @throws RaplaException */ protected ViewListener createListener() throws RaplaException { return new RaplaCalendarViewListener(getContext(), model, view.getComponent()); } public JComponent getDateSelection() { return dateChooser.getComponent(); } public void dateChanged(DateChangeEvent evt) { try { // TODO why is that here //Date date = evt.getDate(); // model.setSelectedDate( date ); update(); } catch (RaplaException ex) { showException(ex, view.getComponent()); } } public void update( ) throws RaplaException { if ( titleView != null) { titleView.setText( model.getNonEmptyTitle()); } dateChooser.update(); if (!isPrintContext()) { int minBlockWidth = getCalendarOptions().getMinBlockWidth(); view.setMinBlockWidth( minBlockWidth); } configureView( ); Date startDate = getStartDate() ; Date endDate = getEndDate(); ensureViewTimeframeIsInModel(startDate, endDate); view.rebuild( createBuilder() ); if ( !view.isEditable()) { Dimension size = view.getComponent().getPreferredSize(); container.setBounds( 0,0, size.width, size.height + 40); } } protected Date getEndDate() { return view.getEndDate() ; } protected Date getStartDate() { return view.getStartDate(); } public TimeInterval getVisibleTimeInterval() { return new TimeInterval( getStartDate(),getEndDate()); } protected void ensureViewTimeframeIsInModel( Date startDate, Date endDate) { // Update start- and enddate of the model Date modelStart = model.getStartDate(); Date modelEnd = model.getEndDate(); if ( modelStart == null || modelStart.after( startDate)) { model.setStartDate( startDate); } if ( modelEnd == null || modelEnd.before( endDate)) { model.setEndDate( endDate); } } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = new SwingRaplaBuilder(getContext()); Date startDate = getStartDate() ; Date endDate = getEndDate(); builder.setFromModel( model, startDate, endDate ); builder.setRepeatingVisible( view.isEditable()); GroupAllocatablesStrategy strategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ); boolean compactColumns = getCalendarOptions().isCompactColumns() || builder.getAllocatables().size() ==0 ; strategy.setFixedSlotsEnabled( !compactColumns); strategy.setResolveConflictsEnabled( true ); builder.setBuildStrategy( strategy ); return builder; } public JComponent getComponent() { return container; } public List<Allocatable> getSortedAllocatables() throws RaplaException { Allocatable[] selectedAllocatables = model.getSelectedAllocatables(); List<Allocatable> sortedAllocatables = new ArrayList<Allocatable>( Arrays.asList( selectedAllocatables)); Collections.sort(sortedAllocatables, new NamedComparator<Allocatable>( getLocale() )); return sortedAllocatables; } public void scrollToStart() { } public CalendarView getCalendarView() { return view; } //DateTools.addDays(new Date(), 100); Date currentPrintDate; Map<Date,Integer> pageStartMap = new HashMap<Date,Integer>(); Double scaleFactor = null; /** * @see java.awt.print.Printable#print(java.awt.Graphics, java.awt.print.PageFormat, int) */ public int print(Graphics g, PageFormat format, int page) throws PrinterException { /*JFrame frame = new JFrame(); frame.setSize(300,300); frame.getContentPane().add( container); frame.pack(); frame.setVisible(false);*/ final Date startDate = model.getStartDate(); final Date endDate = model.getEndDate(); final Date selectedDate = model.getSelectedDate(); int pages = getUnits(); Date targetDate; { Calendar cal = getRaplaLocale().createCalendar(); cal.setTime( selectedDate); cal.add(getIncrementSize(), pages-1); targetDate = cal.getTime(); } if ( page <= 0 ) { currentPrintDate = selectedDate; pageStartMap.clear(); scaleFactor = null; pageStartMap.put(currentPrintDate,page); } while (true) { int printOffset = (int)DateTools.countDays(selectedDate, currentPrintDate); model.setStartDate(DateTools.addDays(startDate, printOffset)); model.setEndDate(DateTools.addDays(endDate, printOffset)); model.setSelectedDate( DateTools.addDays(selectedDate, printOffset)); try { Graphics2D g2 = (Graphics2D) g; try { update(); } catch (RaplaException e) { throw new PrinterException(e.getMessage()); } double preferedHeight = view.getComponent().getPreferredSize().getHeight(); if ( scaleFactor == null) { scaleFactor = Math.min(1, 1/ Math.min(2.5,preferedHeight / format.getImageableHeight())); } double newWidth = format.getImageableWidth() / scaleFactor ; double scaledPreferedHeigth =preferedHeight * scaleFactor; Component component = container; view.updateSize( (int)newWidth ); container.setBounds( 0,0, (int)newWidth, (int)preferedHeight); try { update(); } catch (RaplaException e) { throw new PrinterException(e.getMessage()); } Integer pageStart = pageStartMap.get( currentPrintDate); if ( pageStart == null) { return NO_SUCH_PAGE; } int translatey = (int)((page-pageStart )* format.getImageableHeight()); if ( translatey > scaledPreferedHeigth-20) { if ( targetDate != null && currentPrintDate.before( targetDate)) { Calendar cal = getRaplaLocale().createCalendar(); cal.setTime( currentPrintDate); cal.add(getIncrementSize(), 1); currentPrintDate = cal.getTime(); pageStartMap.put(currentPrintDate,page); continue; } else { return NO_SUCH_PAGE; } } if ( translatey <0 && targetDate!= null) { Calendar cal = getRaplaLocale().createCalendar(); cal.setTime( currentPrintDate); cal.add(getIncrementSize(), -1); currentPrintDate = cal.getTime(); continue; } if ( targetDate != null && currentPrintDate.after( targetDate)) { return NO_SUCH_PAGE; } g2.translate(format.getImageableX(), format.getImageableY() - translatey ); g2.clipRect(0, translatey , (int)(format.getImageableWidth() ), (int)(format.getImageableHeight())); g2.scale(scaleFactor, scaleFactor); RepaintManager rm = RepaintManager.currentManager(component); boolean db= rm.isDoubleBufferingEnabled(); try { rm.setDoubleBufferingEnabled(false); component.printAll(g); return Printable.PAGE_EXISTS; } finally { rm.setDoubleBufferingEnabled(db); } } finally { model.setStartDate(startDate); model.setEndDate(endDate); model.setSelectedDate( selectedDate); } } } public String getCalendarUnit() { int incrementSize = getIncrementSize(); if ( incrementSize == Calendar.DAY_OF_YEAR) { return getString("days"); } else if ( incrementSize == Calendar.WEEK_OF_YEAR) { return getString("weeks"); } else if ( incrementSize == Calendar.MONTH) { return getString("months"); } else { return ""; } } public int getUnits() { return units; } public void setUnits(int units) { this.units = units; } }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/AbstractRaplaSwingCalendar.java
Java
gpl3
12,932
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.abstractcalendar.server; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.servletpages.RaplaPageGenerator; public interface HTMLViewFactory { public RaplaPageGenerator createHTMLView(RaplaContext context, CalendarModel model) throws RaplaException; public String getViewId(); }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/server/HTMLViewFactory.java
Java
gpl3
1,369
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.abstractcalendar.server; import java.util.Calendar; import java.util.Date; import org.rapla.components.calendarview.Block; import org.rapla.entities.User; import org.rapla.entities.domain.Appointment; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.plugin.abstractcalendar.RaplaBuilder; public class HTMLRaplaBuilder extends RaplaBuilder { static String COLOR_NO_RESOURCE = "#BBEEBB"; int m_rowsPerHour = 4; /** shared calendar instance. Only used for temporary stored values. */ String m_html; int index = 0; protected boolean onlyAllocationInfo; public HTMLRaplaBuilder(RaplaContext sm) { super(sm); } @Override public void setFromModel(CalendarModel model, Date startDate, Date endDate) throws RaplaException { super.setFromModel(model, startDate, endDate); { String option = model.getOption(CalendarModel.ONLY_ALLOCATION_INFO); if (option != null && option.equalsIgnoreCase("true")) { onlyAllocationInfo = true; } } } @Override protected boolean isAnonymous(User user, Appointment appointment) { if ( onlyAllocationInfo) { return true; } return super.isAnonymous(user, appointment); } @Override protected boolean isExceptionsExcluded() { return true; } @Override protected Block createBlock(RaplaBlockContext blockContext, Date start, Date end) { HTMLRaplaBlock block = createBlock(); block.setIndex( index ++ ); block.setStart(start); block.setEnd(end); block.contextualize(blockContext); Calendar calendar = getRaplaLocale().createCalendar(); calendar.setTime(start); int row = (int) ( calendar.get(Calendar.HOUR_OF_DAY)* m_rowsPerHour + Math.round((calendar.get(Calendar.MINUTE) * m_rowsPerHour)/60.0) ); block.setRow(row); block.setDay(calendar.get(Calendar.DAY_OF_WEEK)); calendar.setTime(block.getEnd()); int endRow = (int) ( calendar.get(Calendar.HOUR_OF_DAY)* m_rowsPerHour + Math.round((calendar.get(Calendar.MINUTE) * m_rowsPerHour)/60.0) ); int rowCount = endRow -row; block.setRowCount(rowCount); //System.out.println("Start " + start + " End " + end); //System.out.println("Block " + block.getReservation().getName(null) // + " Row: " + row + " Endrow: " + endRow + " Rowcount " + rowCount ); return block; } protected HTMLRaplaBlock createBlock() { HTMLRaplaBlock block = new HTMLRaplaBlock(); return block; } }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/server/HTMLRaplaBuilder.java
Java
gpl3
3,763
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.abstractcalendar.server; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.rapla.components.calendarview.html.AbstractHTMLView; import org.rapla.components.util.ParseDateException; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.entities.NamedComparator; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarOptions; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.plugin.abstractcalendar.RaplaBuilder; import org.rapla.servletpages.RaplaPageGenerator; public abstract class AbstractHTMLCalendarPage extends RaplaComponent implements RaplaPageGenerator { protected AbstractHTMLView view; protected String calendarviewHTML; protected CalendarModel model = null; RaplaBuilder builder; public AbstractHTMLCalendarPage(RaplaContext context, CalendarModel calendarModel) { super( context); this.model = calendarModel.clone(); } protected RaplaBuilder createBuilder() throws RaplaException { RaplaBuilder builder = new HTMLRaplaBuilder( getContext()); Date startDate = view.getStartDate(); Date endDate = view.getEndDate(); builder.setFromModel( model, startDate, endDate ); builder.setNonFilteredEventsVisible( false); return builder; } abstract protected AbstractHTMLView createCalendarView(); abstract protected int getIncrementSize(); public List<Allocatable> getSortedAllocatables() throws RaplaException { Allocatable[] selectedAllocatables = model.getSelectedAllocatables(); List<Allocatable> sortedAllocatables = new ArrayList<Allocatable>( Arrays.asList( selectedAllocatables)); Collections.sort(sortedAllocatables, new NamedComparator<Allocatable>( getLocale() )); return sortedAllocatables; } public String getCalendarHTML() { return calendarviewHTML; } public String getDateChooserHTML( Date date) { Calendar calendar = getRaplaLocale().createCalendar(); calendar.setTime( date ); return HTMLDateComponents.getDateSelection( "", calendar,getLocale()); } public Date getStartDate() { return view.getStartDate(); } public Date getEndDate() { return view.getEndDate(); } public String getTitle() { return model.getNonEmptyTitle(); } public int getDay( Date date) { Calendar calendarview = getRaplaLocale().createCalendar(); calendarview.setTime( date); return calendarview.get( Calendar.DATE); } public int getMonth( Date date) { Calendar calendarview = getRaplaLocale().createCalendar(); calendarview.setTime( date); return calendarview.get( Calendar.MONTH) + 1; } public int getYear( Date date) { Calendar calendarview = getRaplaLocale().createCalendar(); calendarview.setTime( date); return calendarview.get( Calendar.YEAR); } abstract protected void configureView() throws RaplaException; public void generatePage( ServletContext context,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=" + getRaplaLocale().getCharsetNonUtf() ); java.io.PrintWriter out = response.getWriter(); Calendar calendarview = getRaplaLocale().createCalendar(); calendarview.setTime( model.getSelectedDate() ); if ( request.getParameter("today") != null ) { Date today = getQuery().today(); calendarview.setTime( today ); } else if ( request.getParameter("day") != null ) { String dateString = request.getParameter("year") + "-" + request.getParameter("month") + "-" + request.getParameter("day"); try { SerializableDateTimeFormat format = getRaplaLocale().getSerializableFormat(); calendarview.setTime( format.parseDate( dateString, false ) ); } catch (ParseDateException ex) { out.close(); throw new ServletException( ex); } if ( request.getParameter("next") != null) calendarview.add( getIncrementSize(), 1); if ( request.getParameter("prev") != null) calendarview.add( getIncrementSize(), -1); } Date currentDate = calendarview.getTime(); model.setSelectedDate( currentDate ); view = createCalendarView(); try { configureView(); } catch (RaplaException ex) { getLogger().error("Can't configure view ", ex); throw new ServletException( ex ); } view.setLocale( getRaplaLocale().getLocale() ); view.setTimeZone(getRaplaLocale().getTimeZone()); view.setToDate(model.getSelectedDate()); model.setStartDate( view.getStartDate() ); model.setEndDate( view.getEndDate() ); try { builder = createBuilder(); } catch (RaplaException ex) { getLogger().error("Can't create builder ", ex); out.close(); throw new ServletException( ex ); } view.rebuild( builder); printPage(request, out, calendarview); } /** * @throws ServletException * @throws UnsupportedEncodingException */ protected void printPage(HttpServletRequest request, java.io.PrintWriter out, Calendar currentDate) throws ServletException, UnsupportedEncodingException { boolean navigationVisible = isNavigationVisible( request ); String linkPrefix = request.getPathTranslated() != null ? "../": ""; RaplaLocale raplaLocale= getRaplaLocale(); calendarviewHTML = view.getHtml(); out.println("<!DOCTYPE html>"); // we have HTML5 out.println("<html>"); out.println("<head>"); out.println(" <title>" + getTitle() + "</title>"); out.println(" <link REL=\"stylesheet\" href=\""+linkPrefix + "calendar.css\" type=\"text/css\">"); out.println(" <link REL=\"stylesheet\" href=\"" + linkPrefix + "default.css\" type=\"text/css\">"); // tell the html page where its favourite icon is stored out.println(" <link REL=\"shortcut icon\" type=\"image/x-icon\" href=\""+linkPrefix + "images/favicon.ico\">"); out.println(" <meta HTTP-EQUIV=\"Content-Type\" content=\"text/html; charset=" + raplaLocale.getCharsetNonUtf() + "\">"); out.println("</head>"); out.println("<body>"); if (request.getParameter("selected_allocatables") != null && request.getParameter("allocatable_id")==null) { try { Allocatable[] selectedAllocatables = model.getSelectedAllocatables(); printAllocatableList(request, out, getLocale(), selectedAllocatables); } catch (RaplaException e) { throw new ServletException(e); } } else { String allocatable_id = request.getParameter("allocatable_id"); // Start DateChooser if (navigationVisible) { out.println("<div class=\"datechooser\">"); out.println("<form action=\""+linkPrefix + "rapla\" method=\"get\">"); String keyParamter = request.getParameter("key"); if (keyParamter != null) { out.println(getHiddenField("key", keyParamter)); } else { out.println(getHiddenField("page", "calendar")); out.println(getHiddenField("user", model.getUser().getUsername())); String filename = getFilename( request ); if ( filename != null) { out.println(getHiddenField("file", filename)); } } if ( allocatable_id != null) { out.println(getHiddenField("allocatable_id", allocatable_id)); } // add the "previous" button including the css class="super button" out.println("<span class=\"button\"><input type=\"submit\" name=\"prev\" value=\"&lt;&lt;\"/></span> "); out.println("<span class=\"spacer\">&nbsp;</span> "); out.println(getDateChooserHTML(currentDate.getTime())); // add the "goto" button including the css class="super button" out.println("<span class=\"button\"><input type=\"submit\" name=\"goto\" value=\"" + getString("goto_date") + "\"/></span>"); out.println("<span class=\"spacer\">&nbsp;</span>"); out.println("<span class=\"spacer\">&nbsp;</span>"); // add the "today" button including the css class="super button" out.println("<span class=\"button\"><input type=\"submit\" name=\"today\" value=\"" + getString("today") + "\"/></span>"); out.println("<span class=\"spacer\">&nbsp;</span>"); // add the "next" button including the css class="super button" out.println("<span class=\"button\"><input type=\"submit\" name=\"next\" value=\"&gt;&gt;\"/></span>"); out.println("</form>"); out.println("</div>"); } // End DateChooser // Start weekview out.println("<h2 class=\"title\">"); out.println(getTitle()); out.println("</h2>"); out.println("<div id=\"calendar\">"); out.println(getCalendarHTML()); out.println("</div>"); // end weekview } out.println("</body>"); out.println("</html>"); } static public void printAllocatableList(HttpServletRequest request, java.io.PrintWriter out, Locale locale, Allocatable[] selectedAllocatables) throws UnsupportedEncodingException { out.println("<table>"); String base = request.getRequestURL().toString(); String queryPath = request.getQueryString(); queryPath = queryPath.replaceAll("&selected_allocatables[^&]*",""); List<Allocatable> sortedAllocatables = new ArrayList<Allocatable>(Arrays.asList(selectedAllocatables)); Collections.sort( sortedAllocatables, new NamedComparator<Allocatable>(locale) ); for (Allocatable alloc:sortedAllocatables) { out.print("<tr>"); out.print("<td>"); String name = alloc.getName(locale); out.print(name); out.print("</a>"); out.print("</td>"); out.print("<td>"); String link = base + "?" + queryPath + "&allocatable_id=" + URLEncoder.encode(alloc.getId(),"UTF-8"); out.print("<a href=\""+ link+ "\">"); out.print(link); out.print("</a>"); out.print("</td>"); out.print("</tr>"); } out.println("</table>"); } public String getFilename(HttpServletRequest request) { return request.getParameter("file"); } public boolean isNavigationVisible( HttpServletRequest request) { String config = model.getOption( CalendarModel.SHOW_NAVIGATION_ENTRY ); if ( config == null || config.equals( "true" )) { return true; } return !config.equals( "false" ) && request.getParameter("hide_nav") == null; } String getHiddenField( String fieldname, String value) { return "<input type=\"hidden\" name=\"" + fieldname + "\" value=\"" + value + "\"/>"; } String getHiddenField( String fieldname, int value) { return getHiddenField( fieldname, String.valueOf(value)); } /* public String getLegend() { if ( !getCalendarOptions().isResourceColoring()) { return ""; } Iterator it = view.getBlocks().iterator(); LinkedList coloredAllocatables = new LinkedList(); while (it.hasNext()) { List list = ((HTMLRaplaBlock)it.next()).getContext().getColoredAllocatables(); for (int i=0;i<list.size();i++) { Object obj = list.get(i); if (!coloredAllocatables.contains(obj)) coloredAllocatables.add(obj); } } if (coloredAllocatables.size() < 1) { return ""; } StringBuffer buf = new StringBuffer(); it = coloredAllocatables.iterator(); buf.append("<table>\n"); buf.append("<tr>\n"); buf.append("<td>"); buf.append( getI18n().getString("legend")); buf.append(":"); buf.append("</td>"); try { AllocatableInfoUI allocatableInfo = new AllocatableInfoUI(getContext()); while (it.hasNext()) { Allocatable allocatable = (Allocatable) it.next(); String color = (String) builder.getColorMap().get(allocatable); if (color == null) // (!color_map.containsKey(allocatable)) continue; buf.append("<td style=\"background-color:"); buf.append( color ); buf.append("\">"); buf.append("<a href=\"#\">"); buf.append( allocatable.getName(getRaplaLocale().getLocale()) ); buf.append("<span>"); buf.append( allocatableInfo.getTooltip( allocatable)); buf.append("</span>"); buf.append("</a>"); buf.append("</td>"); } } catch (RaplaException ex) { getLogger().error( "Error generating legend",ex); } buf.append("</tr>\n"); buf.append("</table>"); return buf.toString(); } */ public CalendarOptions getCalendarOptions() { User user = model.getUser(); return getCalendarOptions(user); } }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/server/AbstractHTMLCalendarPage.java
Java
gpl3
14,882
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.abstractcalendar.server; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import org.rapla.components.calendarview.html.HTMLBlock; import org.rapla.components.util.xml.XMLWriter; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.Attribute; import org.rapla.gui.internal.view.AppointmentInfoUI; import org.rapla.plugin.abstractcalendar.AbstractRaplaBlock; public class HTMLRaplaBlock extends AbstractRaplaBlock implements HTMLBlock { private int m_day; private int m_row; private int m_rowCount; private int index = 0; { timeStringSeperator ="&#160;-"; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public void setRowCount(int rows) { m_rowCount = rows; } public void setRow(int row) { m_row = row; } public int getRowCount() { return m_rowCount; } public int getRow() { return m_row; } public void setDay(int day) { m_day = day; } public int getDay() { return m_day; } public String getBackgroundColor() { return getColorsAsHex()[0]; } public String toString() { StringBuffer buf = new StringBuffer(); String label = XMLWriter.encode(getName( getReservation())); String timeString = getTimeString(false); if ( getContext().isAnonymous()) { String anonymous = "&#160;&#160;&#160;&#160;???"; if ( timeString != null) { return timeString + " " + anonymous; } else { return anonymous; } } if ( timeString != null) { List<Allocatable> resources = getContext().getAllocatables(); StringBuffer buffer = new StringBuffer() ; for (Allocatable resource: resources) { if ( getContext().isVisible( resource) && !resource.isPerson()) { if ( buffer.length() > 0) { buffer.append(", "); } buffer.append(XMLWriter.encode( getName(resource))); } } if ( !getBuildContext().isResourceVisible() && buffer.length() > 0) { timeString = timeString + " " + buffer.toString(); } label = timeString + "<br/>" + label; } AppointmentInfoUI reservationInfo = new AppointmentInfoUI(getContext().getBuildContext().getServiceManager()); URL url = null; Attribute[] attributes = getReservation().getClassification().getAttributes(); for ( int i=0;i<attributes.length;i++) { String value = getReservation().getClassification().getValueAsString( attributes[i],getBuildContext().getRaplaLocale().getLocale()); if ( value == null) continue; try{ int httpEnd = Math.max( value.indexOf(" ")-1, value.length()); url = new URL( value.substring(0,httpEnd)); break; } catch (MalformedURLException ex) { } } buf.append( "<a href=\""); if ( url != null) { buf.append( url ); } else { buf.append( "#" + index ); } buf.append( "\">" ); if ( url != null) { buf.append( "<span class=\"link\">"); } buf.append( label ); if ( url != null) { buf.append( "</span>"); } if (getBuildContext().isShowToolTips()) { buf.append( "<span class=\"tooltip\">"); buf.append(reservationInfo.getTooltip(getAppointment())); buf.append( "</span>"); } buf.append( "</a>" ); if (getBuildContext().isPersonVisible()) { List<Allocatable> persons = getContext().getAllocatables(); for ( Allocatable person:persons) { if ( !getContext().isVisible( person) || !person.isPerson()) continue; buf.append("<br>"); buf.append("<span class=\"person\">"); buf.append(XMLWriter.encode(getName(person))); buf.append("</span>"); } } else { List<Allocatable> persons = getContext().getAllocatables(); if ( persons.size() > 0) { buf.append("<br>"); buf.append("<span class=\"person\">"); boolean first = true; for ( Allocatable person:persons) { if ( !getContext().isVisible( person) || !person.isPerson()) continue; if ( !first) { buf.append(", "); } else { first = false; } buf.append( XMLWriter.encode(getName( person ))); } buf.append("</span>"); } } if (getBuildContext().isResourceVisible()) { Allocatable[] resources = getReservation().getResources(); for (int i=0; i<resources.length;i ++) { if (!getContext().isVisible(resources[i])) continue; buf.append("<br>"); buf.append("<span class=\"resource\">"); buf.append(XMLWriter.encode(getName(resources[i]))); buf.append("</span>"); } } return buf.toString(); } }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/server/HTMLRaplaBlock.java
Java
gpl3
6,924
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.plugin.abstractcalendar.server; import java.util.Calendar; import java.util.Locale; public class HTMLDateComponents { static public String getDateSelection(String prefix,Calendar calendarview, Locale locale) { StringBuffer buf = new StringBuffer(); int day = calendarview.get(Calendar.DATE); int month = calendarview.get(Calendar.MONTH) +1; int year = calendarview.get(Calendar.YEAR); int minYear = 2003; int maxYear = 2020; buf.append( getDaySelection(prefix + "day",day)); buf.append( getMonthSelection(prefix + "month",month, locale)); buf.append( getYearSelection(prefix + "year", year,minYear, maxYear)); return buf.toString(); } static public String getDaySelection(String name, int selectedValue) { StringBuffer buf = new StringBuffer(); buf.append("<select name=\""); buf.append( name ); buf.append("\">\n"); for (int i=1;i<=31;i++) { buf.append("<option "); if ( i == selectedValue) { buf.append("selected"); } buf.append(">"); buf.append(i); buf.append("</option>"); buf.append("\n"); } buf.append("</select>"); return buf.toString(); } static public String getMonthSelection(String name, int selectedValue, Locale locale) { StringBuffer buf = new StringBuffer(); buf.append("<select name=\""); buf.append( name ); buf.append("\">\n"); Calendar calendar = Calendar.getInstance( locale ); java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("MMMMM", locale); calendar.set(Calendar.MONTH,Calendar.JANUARY); for (int i=1;i<=12;i++) { buf.append("<option "); buf.append("value=\""); buf.append(i); buf.append("\" "); if ( i == selectedValue ) { buf.append("selected"); } buf.append(">"); buf.append(format.format(calendar.getTime())); calendar.add(Calendar.MONTH,1); buf.append("</option>"); buf.append("\n"); } buf.append("</select>"); return buf.toString(); } static public String getYearSelection(String name, int selectedValue, int minYear, int maxYear) { StringBuffer buf = new StringBuffer(); buf.append("<select name=\""); buf.append( name ); buf.append("\">\n"); for (int i=minYear;i<=maxYear;i++) { buf.append("<option "); if ( i == selectedValue ) { buf.append("selected"); } buf.append(">"); buf.append(i); buf.append("</option>"); } buf.append("</select>"); return buf.toString(); } }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/server/HTMLDateComponents.java
Java
gpl3
4,223
<body> Contains the rapla-specific classes that helps in the creation of the calendar-like view plugins. API in this package is likly to change </body>
04900db4-rob
src/org/rapla/plugin/abstractcalendar/package.html
HTML
gpl3
155
/** * */ package org.rapla.plugin.abstractcalendar; import java.awt.Component; import java.awt.Point; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.swing.JComponent; import javax.swing.JMenuItem; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.swing.ViewListener; import org.rapla.entities.NamedComparator; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarSelectionModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.TypedComponentRole; import org.rapla.gui.MenuContext; import org.rapla.gui.MenuFactory; import org.rapla.gui.ObjectMenuFactory; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.ReservationEdit; import org.rapla.gui.internal.action.AppointmentAction; import org.rapla.gui.internal.common.RaplaClipboard; import org.rapla.gui.toolkit.MenuInterface; import org.rapla.gui.toolkit.RaplaMenu; import org.rapla.gui.toolkit.RaplaMenuItem; import org.rapla.gui.toolkit.RaplaPopupMenu; public class RaplaCalendarViewListener extends RaplaGUIComponent implements ViewListener { public static TypedComponentRole<Date> SELECTED_DATE = new TypedComponentRole<Date>( RaplaCalendarViewListener.class.getName()); protected boolean keepTime = false; protected JComponent calendarContainerComponent; CalendarModel model; public RaplaCalendarViewListener(RaplaContext context, CalendarModel model, JComponent calendarContainerComponent) { super( context); this.model = model; this.calendarContainerComponent = calendarContainerComponent; } protected CalendarModel getModel() { return model; } /** override this method if you want to implement a custom time selection */ public void selectionChanged(Date start,Date end) { // #TODO this cast need to be replaced without adding the setter methods to the readOnly interface CalendarModel CalendarSelectionModel castedModel = (CalendarSelectionModel)model; castedModel.markInterval( start, end); Collection<Allocatable> markedAllocatables = getMarkedAllocatables(); castedModel.setMarkedAllocatables( markedAllocatables); } /** * start, end and slotNr are not used because they are handled by selectionChanged method * @param start not used because handled by selectionChanged method * @param end not used because handled by selectionChanged method * @param slotNr not used because handled by selectionChanged method * */ public void selectionPopup(Component component,Point p,Date start,Date end, int slotNr) { selectionPopup(component, p); } public void selectionPopup(Component component,Point p) { try { RaplaPopupMenu menu= new RaplaPopupMenu(); Object focusedObject = null; MenuContext context = new MenuContext(getContext(), focusedObject); getService(MenuFactory.class).addReservationWizards(menu, context, null); if (canCreateReservation()) { // User user = getUser(); // Date today = getQuery().today(); // boolean canAllocate = false; // Collection<Allocatable> selectedAllocatables = getMarkedAllocatables(); // for ( Allocatable alloc: selectedAllocatables) { // if (alloc.canAllocate( user, start, end, today)) // canAllocate = true; // } // canAllocate || (selectedAllocatables.size() == 0 && if ( canUserAllocateSomething( getUser()) ) { ReservationEdit[] editWindows = getReservationController().getEditWindows(); if ( editWindows.length >0 ) { RaplaMenu addItem = new RaplaMenu("add_to"); addItem.setText(getString("add_to")); menu.add(addItem); for ( ReservationEdit reservationEdit: editWindows) { addAppointmentAction(addItem,component,p).setAddTo( reservationEdit); } } } else { JMenuItem cantAllocate = new JMenuItem(getString("permission.denied")); cantAllocate.setEnabled( false); menu.add( cantAllocate); } } // RaplaClipboard clipboard = getService(RaplaClipboard.class); Appointment appointment = clipboard.getAppointment(); if ( appointment != null ) { if (!clipboard.isWholeReservation()) { addAppointmentAction(menu,component,p).setPaste( keepTime ); } addAppointmentAction(menu,component,p).setPasteAsNew( keepTime ); } menu.show(component,p.x,p.y); } catch (RaplaException ex) { showException(ex, calendarContainerComponent); } } public void blockPopup(Block block,Point p) { SwingRaplaBlock b = (SwingRaplaBlock) block; if ( !b.getContext().isBlockSelected() ) { return; } showPopupMenu(b, p); } public void blockEdit(Block block,Point p) { // double click on block in view. SwingRaplaBlock b = (SwingRaplaBlock) block; if ( !b.getContext().isBlockSelected() ) { return; } try { if (!canModify(b.getReservation())) return; final AppointmentBlock appointmentBlock = b.getAppointmentBlock(); getReservationController().edit(appointmentBlock); } catch (RaplaException ex) { showException(ex,b.getView()); } } public void moved(Block block,Point p,Date newStart, int slotNr) { moved(block, p, newStart); } protected void moved(Block block, Point p, Date newStart) { SwingRaplaBlock b = (SwingRaplaBlock) block; try { long offset = newStart.getTime() - b.getStart().getTime(); Date newStartWithOffset = new Date(b.getAppointmentBlock().getStart() + offset); getReservationController().moveAppointment(b.getAppointmentBlock() ,newStartWithOffset ,calendarContainerComponent ,p, keepTime); } catch (RaplaException ex) { showException(ex,b.getView()); } } public boolean isKeepTime() { return keepTime; } public void setKeepTime(boolean keepTime) { this.keepTime = keepTime; } public void resized(Block block,Point p,Date newStart, Date newEnd, int slotNr) { SwingRaplaBlock b = (SwingRaplaBlock) block; try { getReservationController().resizeAppointment(b.getAppointmentBlock() ,newStart ,newEnd ,calendarContainerComponent ,p, keepTime); } catch (RaplaException ex) { showException(ex,b.getView()); } } public List<Allocatable> getSortedAllocatables() { try { Allocatable[] selectedAllocatables; selectedAllocatables = model.getSelectedAllocatables(); List<Allocatable> sortedAllocatables = new ArrayList<Allocatable>( Arrays.asList( selectedAllocatables)); Collections.sort(sortedAllocatables, new NamedComparator<Allocatable>( getLocale() )); return sortedAllocatables; } catch (RaplaException e) { getLogger().error(e.getMessage(), e); return Collections.emptyList(); } } /** override this method if you want to implement a custom allocatable marker */ protected Collection<Allocatable> getMarkedAllocatables() { List<Allocatable> selectedAllocatables = getSortedAllocatables(); if ( selectedAllocatables.size()== 1 ) { return Collections.singletonList(selectedAllocatables.get(0)); } return Collections.emptyList(); } protected void showPopupMenu(SwingRaplaBlock b,Point p) { Component component = b.getView(); AppointmentBlock appointmentBlock = b.getAppointmentBlock(); Appointment appointment = b.getAppointment(); Date start = b.getStart(); boolean isException = b.isException(); try { RaplaPopupMenu menu= new RaplaPopupMenu(); Allocatable groupAllocatable = b.getGroupAllocatable(); Collection<Allocatable> copyContextAllocatables; if (groupAllocatable != null) { copyContextAllocatables = Collections.singleton( groupAllocatable); } else { copyContextAllocatables = Collections.emptyList(); } addAppointmentAction( menu, component, p).setCopy(appointmentBlock,copyContextAllocatables); addAppointmentAction( menu, component, p ).setEdit(appointmentBlock); if ( !isException) { addAppointmentAction( menu, component, p).setDelete(appointmentBlock); } addAppointmentAction( menu, component, p).setView(appointmentBlock); Iterator<?> it = getContainer().lookupServicesFor( RaplaClientExtensionPoints.OBJECT_MENU_EXTENSION).iterator(); while (it.hasNext()) { ObjectMenuFactory objectMenuFact = (ObjectMenuFactory) it.next(); MenuContext menuContext = new MenuContext( getContext(), appointment); menuContext.put(SELECTED_DATE, start); RaplaMenuItem[] items = objectMenuFact.create( menuContext, appointment ); for ( int i =0;i<items.length;i++) { RaplaMenuItem item = items[i]; menu.add( item); } } menu.show(component,p.x,p.y); } catch (RaplaException ex) { showException(ex, calendarContainerComponent); } } public AppointmentAction addAppointmentAction(MenuInterface menu, Component parent, Point p) { AppointmentAction action = new AppointmentAction(getContext(),parent,p); menu.add(new JMenuItem(action)); return action; } }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/RaplaCalendarViewListener.java
Java
gpl3
10,658
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by the | | Free Software Foundation. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ /** rapla-specific implementation of builder. * Splits the appointments into day-blocks. */ package org.rapla.plugin.abstractcalendar; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.rapla.components.calendarview.Block; import org.rapla.components.calendarview.BuildStrategy; import org.rapla.components.calendarview.Builder; import org.rapla.components.calendarview.CalendarView; import org.rapla.components.util.Assert; import org.rapla.components.util.DateTools; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.Category; import org.rapla.entities.CategoryAnnotations; import org.rapla.entities.NamedComparator; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.AppointmentBlock; import org.rapla.entities.domain.Reservation; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.Classifiable; import org.rapla.entities.dynamictype.Classification; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarOptions; import org.rapla.facade.Conflict; import org.rapla.facade.Conflict.Util; import org.rapla.facade.RaplaComponent; import org.rapla.facade.internal.CalendarModelImpl; import org.rapla.facade.internal.ConflictImpl; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.framework.TypedComponentRole; import org.rapla.framework.logger.Logger; import org.rapla.gui.toolkit.RaplaColors; public abstract class RaplaBuilder extends RaplaComponent implements Builder ,Cloneable { private Collection<Reservation> selectedReservations; private List<Allocatable> selectedAllocatables = new ArrayList<Allocatable>(); private boolean enabled= true; private boolean bExceptionsExcluded = false; private boolean bResourceVisible = true; private boolean bPersonVisible = true; private boolean bRepeatingVisible = true; private boolean bTimeVisible = true; //Shows time <from - till> in top of all HTML- and Swing-View Blocks private boolean splitByAllocatables = false; private HashMap<Allocatable,String> colors = new HashMap<Allocatable,String>(); //This currently only works with HashMap private User editingUser; private boolean isResourceColoring; private boolean isEventColoring; private boolean nonFilteredEventsVisible; /** default buildStrategy is {@link GroupAllocatablesStrategy}.*/ BuildStrategy buildStrategy; HashSet<Reservation> allReservationsForAllocatables = new HashSet<Reservation>(); int max =0; int min =0; List<AppointmentBlock> preparedBlocks = null; public static final TypedComponentRole<Boolean> SHOW_TOOLTIP_CONFIG_ENTRY = new TypedComponentRole<Boolean>("org.rapla.showTooltips"); Map<Appointment,Set<Appointment>> conflictingAppointments; public RaplaBuilder(RaplaContext sm) { super(sm); buildStrategy = new GroupAllocatablesStrategy( getRaplaLocale().getLocale() ); } public void setFromModel(CalendarModel model, Date startDate, Date endDate) throws RaplaException { Collection<Conflict> conflictsSelected = new ArrayList<Conflict>(); conflictingAppointments = null; conflictsSelected.clear(); conflictsSelected.addAll( ((CalendarModelImpl)model).getSelectedConflicts()); Collection<Allocatable> allocatables ; List<Reservation> filteredReservations; if ( !conflictsSelected.isEmpty() ) { allocatables = Util.getAllocatables( conflictsSelected ); } else { allocatables = Arrays.asList( model.getSelectedAllocatables()); } if ( startDate != null && !allocatables.isEmpty()) { List<Reservation> reservationsForAllocatables = Arrays.asList(getQuery().getReservations( allocatables.toArray(Allocatable.ALLOCATABLE_ARRAY), startDate, endDate)); allReservationsForAllocatables.addAll( reservationsForAllocatables); } if ( !conflictsSelected.isEmpty() ) { filteredReservations = getQuery().getReservations( conflictsSelected); conflictingAppointments = ConflictImpl.getMap( conflictsSelected, filteredReservations); } else { if ( allocatables.isEmpty() || startDate == null) { filteredReservations = Arrays.asList( model.getReservations( startDate, endDate )); } else { filteredReservations = ((CalendarModelImpl)model).restrictReservations( allReservationsForAllocatables); } } User user = model.getUser(); CalendarOptions calendarOptions = getCalendarOptions( user); nonFilteredEventsVisible = calendarOptions.isNonFilteredEventsVisible(); isResourceColoring =calendarOptions.isResourceColoring(); isEventColoring =calendarOptions.isEventColoring(); Collection<Reservation> reservations = new HashSet<Reservation>(filteredReservations); selectReservations( reservations ); setEditingUser( user); setExceptionsExcluded( !calendarOptions.isExceptionsVisible()); /* Uncomment this to color allocatables in the reservation view if ( allocatables.size() == 0) { allocatables = new ArrayList(); for (int i=0;i< reservations.size();i++) { Reservation r = (Reservation) reservations.get( i ); Allocatable[] a = r.getAllocatables(); for (int j=0;j<a.length;j++) { if ( !allocatables.contains( a[j] )) { allocatables.add( a[j]); } } } }*/ selectAllocatables( allocatables ); } public boolean isNonFilteredEventsVisible() { return nonFilteredEventsVisible; } public void setNonFilteredEventsVisible(boolean nonFilteredEventsVisible) { this.nonFilteredEventsVisible = nonFilteredEventsVisible; } public void setSmallBlocks( boolean isSmallView) { setTimeVisible( isSmallView ); setPersonVisible( !isSmallView ); setResourceVisible( !isSmallView ); } public void setSplitByAllocatables( boolean enable) { splitByAllocatables = enable; } public void setExceptionsExcluded( boolean exclude) { this.bExceptionsExcluded = exclude; } protected boolean isExceptionsExcluded() { return bExceptionsExcluded; } public void setEditingUser(User editingUser) { this.editingUser = editingUser; } public User getEditingUser() { return this.editingUser; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enable) { this.enabled = enable; } public void setBuildStrategy(BuildStrategy strategy) { this.buildStrategy = strategy; } public void setTimeVisible(boolean bTimeVisible) { this.bTimeVisible = bTimeVisible; } public boolean isTimeVisible() { return bTimeVisible; } private void setResourceVisible(boolean bVisible) { this.bResourceVisible = bVisible; } private void setPersonVisible(boolean bVisible) { this.bPersonVisible = bVisible; } public void setRepeatingVisible(boolean bVisible) { this.bRepeatingVisible = bVisible; } public List<Allocatable> getAllocatables() { return selectedAllocatables; } /** Map enthaelt die fuer die resourcen-darstellung benutzten farben mit resource-id (vom typ Integer) als schluessel. erst nach rebuild() verfuegbar. */ Map<Allocatable,String> getColorMap() { return colors; } private void createColorMap() { colors.clear(); List<Allocatable> arrayList = new ArrayList<Allocatable>(selectedAllocatables); Comparator<Allocatable> comp =new Comparator<Allocatable>() { public int compare(Allocatable o1, Allocatable o2) { if (o1.hashCode()>o2.hashCode()) return -1; if (o1.hashCode()<o2.hashCode()) return 1; return 0; } }; Collections.sort(arrayList,comp); Iterator<Allocatable> it = arrayList.iterator(); int i=0; while (it.hasNext()) { Allocatable allocatable = it.next(); DynamicType type = allocatable.getClassification().getType(); String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_COLORS); String color =null; if (annotation == null) { annotation = type.getAttribute("color") != null ? DynamicTypeAnnotations.VALUE_COLORS_COLOR_ATTRIBUTE: DynamicTypeAnnotations.VALUE_COLORS_AUTOMATED; } color = getColorForClassifiable( allocatable ); if ( color == null && annotation.equals(DynamicTypeAnnotations.VALUE_COLORS_AUTOMATED)) { color = RaplaColors.getResourceColor(i++); } else if ( annotation.equals(DynamicTypeAnnotations.VALUE_COLORS_DISABLED)) { color = null; } if ( color != null) { colors.put(allocatable, color); } } } static String getColorForClassifiable( Classifiable classifiable ) { Classification c = classifiable.getClassification(); Attribute colorAttribute = c.getAttribute("color"); String annotation = c.getType().getAnnotation(DynamicTypeAnnotations.KEY_COLORS); if ( annotation != null && annotation.equals( DynamicTypeAnnotations.VALUE_COLORS_DISABLED)) { return null; } String color = null; if ( colorAttribute != null) { Object hexValue = c.getValue( colorAttribute ); if ( hexValue != null) { if ( hexValue instanceof Category) { hexValue = ((Category) hexValue).getAnnotation( CategoryAnnotations.KEY_NAME_COLOR ); } if ( hexValue != null) { color = hexValue.toString(); } } } return color; } /** diese reservierungen werden vom WeekView angezeigt. */ public void selectReservations(Collection<Reservation> reservations) { this.selectedReservations= reservations; } /** nur diese resourcen werden angezeigt. */ public void selectAllocatables(Collection<Allocatable> allocatables) { selectedAllocatables.clear(); if (allocatables != null ) { selectedAllocatables.addAll(new HashSet<Allocatable>(allocatables)); Collections.sort( selectedAllocatables, new NamedComparator<Allocatable>( getRaplaLocale().getLocale() )); } createColorMap(); } public static List<Appointment> getAppointments( Reservation[] reservations, Allocatable[] allocatables) { return getAppointments( Arrays.asList( reservations), Arrays.asList( allocatables)); } public static List<Appointment> getAppointments( Collection<Reservation> reservations, Collection<Allocatable> allocatables) { List<Appointment> appointments = new ArrayList<Appointment>(); for (Reservation r:reservations) { for ( Appointment app:r.getAppointments()) { if (allocatables == null || allocatables.isEmpty()) { appointments.add( app); } else { // this flag is set true if one of the allocatables of a // reservation matches a selected allocatable. boolean allocatableMatched = false; for (Allocatable alloc:r.getAllocatablesFor(app)) { if (allocatables.contains(alloc)) { allocatableMatched = true; break; } } if ( allocatableMatched ) { appointments.add( app); } } } } return appointments; } static public class SplittedBlock extends AppointmentBlock { public SplittedBlock(AppointmentBlock original,long start, long end, Appointment appointment, boolean isException) { super(start, end, appointment, isException); this.original = original; } public AppointmentBlock getOriginal() { return original; } AppointmentBlock original; } static public List<AppointmentBlock> splitBlocks(Collection<AppointmentBlock> preparedBlocks, Date startDate, Date endDate) { List<AppointmentBlock> result = new ArrayList<AppointmentBlock>(); for (AppointmentBlock block:preparedBlocks) { long blockStart = block.getStart(); long blockEnd = block.getEnd(); Appointment appointment = block.getAppointment(); boolean isException = block.isException(); if (DateTools.isSameDay(blockStart, blockEnd)) { result.add( block); } else { long firstBlockDate = Math.max(blockStart, startDate.getTime()); long lastBlockDate = Math.min(blockEnd, endDate.getTime()); long currentBlockDate = firstBlockDate; while ( currentBlockDate >= blockStart && DateTools.cutDate( currentBlockDate ) < lastBlockDate) { long start; long end; if (DateTools.isSameDay(blockStart, currentBlockDate)) { start= blockStart; } else { start = DateTools.cutDate(currentBlockDate); } if (DateTools.isSameDay(blockEnd, currentBlockDate) && !DateTools.isMidnight(blockEnd)) { end = blockEnd; }else { end = DateTools.fillDate( currentBlockDate ) -1; } //System.out.println("Adding Block " + new Date(start) + " - " + new Date(end)); result.add ( new SplittedBlock(block,start, end, appointment,isException)); currentBlockDate+= DateTools.MILLISECONDS_PER_DAY; } } } return result; } /** selects all blocks that should be visible and calculates the max start- and end-time */ public void prepareBuild(Date start,Date end) { boolean excludeExceptions = isExceptionsExcluded(); HashSet<Reservation> allReservations = new HashSet<Reservation>( selectedReservations); allReservations.addAll( allReservationsForAllocatables); Collection<Appointment> appointments = getAppointments( selectedReservations, selectedAllocatables); // Add appointment to the blocks final List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>(); for (Appointment app:appointments) { app.createBlocks(start, end, blocks, excludeExceptions); } preparedBlocks = splitBlocks(blocks, start, end); // calculate new start and end times max =0; min =24*60; for (AppointmentBlock block:blocks) { int starthour = DateTools.getHourOfDay(block.getStart()); int startminute = DateTools.getMinuteOfHour(block.getStart()); int endhour = DateTools.getHourOfDay(block.getEnd()); int endminute = DateTools.getMinuteOfHour(block.getEnd()); if ((starthour != 0 || startminute != 0) && starthour*60 + startminute<min) min = starthour * 60 + startminute; if ((endhour >0 || endminute>0) && (endhour *60 + endminute)<min ) min = Math.max(0,endhour-1) * 60 + endminute; if ((endhour != 0 || endminute != 0) && (endhour != 23 && endminute!=59) && (endhour *60 + endminute)>max) max = Math.min(24*60 , endhour * 60 + endminute); if (starthour>=max) max = Math.min(24*60 , starthour *60 + startminute); } } public int getMinMinutes() { Assert.notNull(preparedBlocks, "call prepareBuild first"); return min; } public int getMaxMinutes() { Assert.notNull(preparedBlocks, "call prepareBuild first"); return max; } protected abstract Block createBlock(RaplaBlockContext blockContext, Date start, Date end); public void build(CalendarView wv) { ArrayList<Block> blocks = new ArrayList<Block>(); BuildContext buildContext = new BuildContext(this, blocks); Assert.notNull(preparedBlocks, "call prepareBuild first"); for (AppointmentBlock block:preparedBlocks) { Date start = new Date( block.getStart() ); Date end = new Date( block.getEnd() ); RaplaBlockContext[] blockContext = getBlocksForAppointment( block, buildContext ); for ( int j=0;j< blockContext.length; j++) { blocks.add( createBlock(blockContext[j], start, end)); } } buildStrategy.build(wv, blocks); } private RaplaBlockContext[] getBlocksForAppointment(AppointmentBlock block, BuildContext buildContext) { Appointment appointment = block.getAppointment(); boolean isBlockSelected = selectedReservations.contains( appointment.getReservation()); boolean isConflictsSelected = isConflictsSelected(); if ( !isBlockSelected && (!nonFilteredEventsVisible && !isConflictsSelected)) { return new RaplaBlockContext[] {}; } if ( isConflictsSelected) { boolean found = false; Collection<Appointment> collection = conflictingAppointments.get(appointment); if ( collection != null) { for (Appointment conflictingApp:collection) { if ( conflictingApp.overlaps( block)) { found = true; break; } } } if ( !found) { isBlockSelected = false; } } boolean isAnonymous = isAnonymous(buildContext.user, appointment); RaplaBlockContext firstContext = new RaplaBlockContext( block, this, buildContext, null, isBlockSelected, isAnonymous ); List<Allocatable> selectedAllocatables = firstContext.getSelectedAllocatables(); if ( !splitByAllocatables || selectedAllocatables.size() < 2) { return new RaplaBlockContext[] { firstContext }; } RaplaBlockContext[] context = new RaplaBlockContext[ selectedAllocatables.size() ]; for ( int i= 0;i<context.length;i ++) { context[i] = new RaplaBlockContext( block, this, buildContext, selectedAllocatables.get( i ), isBlockSelected, isAnonymous); } return context; } protected boolean isAnonymous(User user,Appointment appointment) { return !canRead(appointment, user); } private boolean isMovable(Reservation reservation) { return selectedReservations.contains( reservation ) && canModify(reservation, editingUser); } public boolean isConflictsSelected() { return conflictingAppointments != null; } /** This context contains the shared information for all RaplaBlocks.*/ public static class BuildContext { boolean bResourceVisible = true; boolean bPersonVisible = true; boolean bRepeatingVisible = true; boolean bTimeVisible = false; boolean conflictsSelected = false; Map<Allocatable,String> colors; I18nBundle i18n; RaplaLocale raplaLocale; RaplaContext serviceManager; Logger logger; User user; List<Block> blocks; private boolean isResourceColoring; private boolean isEventColoring; private boolean showTooltips; @SuppressWarnings("unchecked") public BuildContext(RaplaBuilder builder, List<Block> blocks) { this.blocks = blocks; this.raplaLocale = builder.getRaplaLocale(); this.bResourceVisible = builder.bResourceVisible; this.bPersonVisible= builder.bPersonVisible; this.bTimeVisible= builder.isTimeVisible(); this.bRepeatingVisible= builder.bRepeatingVisible; this.colors = (Map<Allocatable,String>) builder.colors.clone(); this.i18n =builder.getI18n(); this.serviceManager = builder.getContext(); this.logger = builder.getLogger(); this.user = builder.editingUser; this.conflictsSelected = builder.isConflictsSelected(); this.isResourceColoring = builder.isResourceColoring; this.isEventColoring = builder.isEventColoring; try { this.showTooltips = builder.getClientFacade().getPreferences(user).getEntryAsBoolean(RaplaBuilder.SHOW_TOOLTIP_CONFIG_ENTRY, true); } catch (RaplaException e) { this.showTooltips = true; getLogger().error(e.getMessage(), e); } } public RaplaLocale getRaplaLocale() { return raplaLocale; } public RaplaContext getServiceManager() { return serviceManager; } public List<Block> getBlocks() { return blocks; } public I18nBundle getI18n() { return i18n; } public boolean isTimeVisible() { return bTimeVisible; } public boolean isPersonVisible() { return bPersonVisible; } public boolean isRepeatingVisible() { return bRepeatingVisible; } public boolean isResourceVisible() { return bResourceVisible; } public String lookupColorString(Allocatable allocatable) { if (allocatable == null) return RaplaColors.DEFAULT_COLOR_AS_STRING; return colors.get(allocatable); } public boolean isConflictSelected() { return conflictsSelected; } public boolean isResourceColoringEnabled() { return isResourceColoring; } public boolean isEventColoringEnabled() { return isEventColoring; } public Logger getLogger() { return logger; } public boolean isShowToolTips() { return showTooltips; } } /** This context contains the shared information for one particular RaplaBlock.*/ public static class RaplaBlockContext { ArrayList<Allocatable> selectedMatchingAllocatables = new ArrayList<Allocatable>(3); ArrayList<Allocatable> matchingAllocatables = new ArrayList<Allocatable>(3); AppointmentBlock appointmentBlock; boolean movable; BuildContext buildContext; boolean isBlockSelected; boolean isAnonymous; public RaplaBlockContext(AppointmentBlock appointmentBlock,RaplaBuilder builder,BuildContext buildContext, Allocatable selectedAllocatable, boolean isBlockSelected, boolean isAnonymous) { this.buildContext = buildContext; this.isAnonymous = isAnonymous; if ( appointmentBlock instanceof SplittedBlock) { this.appointmentBlock = ((SplittedBlock)appointmentBlock).getOriginal(); } else { this.appointmentBlock = appointmentBlock; } Appointment appointment =appointmentBlock.getAppointment(); this.isBlockSelected = isBlockSelected; Reservation reservation = appointment.getReservation(); if(isBlockSelected) this.movable = builder.isMovable( reservation ); // Prefer resources when grouping addAllocatables(builder, reservation.getResources(), selectedAllocatable); addAllocatables(builder, reservation.getPersons(), selectedAllocatable); } private void addAllocatables(RaplaBuilder builder, Allocatable[] allocatables,Allocatable selectedAllocatable) { Appointment appointment =appointmentBlock.getAppointment(); Reservation reservation = appointment.getReservation(); for (int i=0; i<allocatables.length; i++) { if ( !reservation.hasAllocated( allocatables[i], appointment ) ) { continue; } matchingAllocatables.add(allocatables[i]); if ( builder.selectedAllocatables.contains(allocatables[i])) { if ( selectedAllocatable == null || selectedAllocatable.equals( allocatables[i]) ) { selectedMatchingAllocatables.add(allocatables[i]); } } } } public boolean isMovable() { return movable;// && !isAnonymous; } public AppointmentBlock getAppointmentBlock() { return appointmentBlock; } public Appointment getAppointment() { Appointment appointment =appointmentBlock.getAppointment(); return appointment; } public List<Allocatable> getSelectedAllocatables() { return selectedMatchingAllocatables; } public List<Allocatable> getAllocatables() { return matchingAllocatables; } public boolean isVisible(Allocatable allocatable) { User user = buildContext.user; if ( user != null && !allocatable.canReadOnlyInformation( user) ) { return false; } return matchingAllocatables.contains(allocatable); } public BuildContext getBuildContext() { return buildContext; } /** * @return null if no allocatables found */ public Allocatable getGroupAllocatable() { // Look if block belongs to a group according to the selected allocatables List<Allocatable> allocatables = getSelectedAllocatables(); // Look if block belongs to a group according to its reserved allocatables if ( allocatables.size() == 0) allocatables = getAllocatables(); if ( allocatables.size() == 0) return null; return allocatables.get( 0 ); } public boolean isBlockSelected() { return isBlockSelected; } public boolean isAnonymous() { return isAnonymous; } } }
04900db4-rob
src/org/rapla/plugin/abstractcalendar/RaplaBuilder.java
Java
gpl3
28,295
package org.rapla.plugin.ical; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.border.BevelBorder; import org.rapla.components.iolayer.FileContent; import org.rapla.components.iolayer.IOInterface; import org.rapla.components.layout.TableLayout; import org.rapla.entities.Named; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.dynamictype.Attribute; import org.rapla.entities.dynamictype.AttributeType; import org.rapla.entities.dynamictype.DynamicType; import org.rapla.entities.dynamictype.DynamicTypeAnnotations; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.TreeFactory; import org.rapla.gui.internal.TreeAllocatableSelection; import org.rapla.gui.toolkit.DialogUI; import org.rapla.gui.toolkit.IdentifiableMenuEntry; /** * * Creates and shows a dialog for the iCal-import to select a URL or file. Also, you can add resources if you like. * * @author Jan Fischer */ public class ImportFrom2iCalMenu extends RaplaGUIComponent implements IdentifiableMenuEntry, ActionListener { JMenuItem item; String id = "ical"; ICalImport importService; public ImportFrom2iCalMenu(RaplaContext context,ICalImport importService) { super(context); this.importService = importService; setChildBundleName(ImportFromICalPlugin.RESOURCE_FILE); item = new JMenuItem(getString("ical.import")); item.setIcon(getIcon("icon.import")); item.addActionListener(this); } public JMenuItem getMenuElement() { return item; } public String getId() { return id; } public void actionPerformed(ActionEvent evt) { try { show(); } catch (Exception ex) { showException(ex, getMainComponent()); } } String bufferedICal; /** * shows a dialog to to import an iCal calendar. * * @throws RaplaException */ public void show() throws RaplaException { final TreeAllocatableSelection resourceSelection = new TreeAllocatableSelection( getContext()); JPanel container = new JPanel(); final JPanel superpanel = new JPanel(); superpanel.setLayout(new TableLayout( new double[][] { { TableLayout.PREFERRED }, { TableLayout.PREFERRED, 2, TableLayout.PREFERRED } })); superpanel.setAlignmentX(Component.LEFT_ALIGNMENT); superpanel.setAlignmentY(Component.TOP_ALIGNMENT); final JPanel panel1 = new JPanel(); Dimension size = new Dimension(850, 125); panel1.setPreferredSize(size); panel1.setMinimumSize(size); panel1.setLayout(new TableLayout( new double[][] { {TableLayout.PREFERRED, 5, TableLayout.FILL, }, { TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, } })); panel1.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); final String urlText = getString("enter_url"); final JTextField urlField = new JTextField(urlText); addCopyPaste(urlField); panel1.add(urlField, "2,0"); final JTextField fileField = new JTextField(getString("click_for_file")); panel1.add(fileField, "2,2"); fileField.setEditable(false); fileField.setBackground(new Color(240, 240, 255)); fileField.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); ButtonGroup bg = new ButtonGroup(); final JRadioButton urlRadio = new JRadioButton(getString("url")); panel1.add(urlRadio, "0,0"); bg.add(urlRadio); final JRadioButton fileRadio = new JRadioButton(getString("file")); panel1.add(fileRadio, "0,2"); bg.add(fileRadio); @SuppressWarnings("unchecked") final JComboBox comboEventType = new JComboBox(getClientFacade().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)); final JLabel labelEventType = new JLabel(getString("reservation_type")); panel1.add(labelEventType, "0,4"); panel1.add(comboEventType, "2,4"); final JComboBox comboNameAttribute = new JComboBox(); final JLabel labelNameAttribute = new JLabel(getString("attribute")); panel1.add(labelNameAttribute, "0,6"); panel1.add(comboNameAttribute, "2,6"); comboEventType.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { updateNameAttributes(comboEventType, comboNameAttribute); } } }); updateNameAttributes(comboEventType, comboNameAttribute); urlRadio.setSelected(true); fileField.setEnabled(false); setRenderer(comboEventType, comboNameAttribute); superpanel.add(panel1, "0,0"); superpanel.add(resourceSelection.getComponent(), "0,2"); container.setLayout( new BorderLayout()); JLabel warning = new JLabel("Warning: The ical import is still experimental. Not all events maybe imported correctly."); warning.setForeground( Color.RED); container.add( warning, BorderLayout.NORTH); container.add( superpanel, BorderLayout.CENTER); final DialogUI dlg = DialogUI.create(getContext(), getMainComponent(), false, container, new String[] { getString("import"), getString("cancel") }); final ActionListener radioListener = new ActionListener() { public void actionPerformed(ActionEvent e) { boolean isURL = urlRadio.isSelected() && urlRadio.isEnabled(); boolean isFile = fileRadio.isSelected() && fileRadio.isEnabled(); urlField.setEnabled(isURL); fileField.setEnabled(isFile); } }; urlRadio.addActionListener(radioListener); fileRadio.addActionListener(radioListener); MouseAdapter listener = new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { Object source = e.getSource(); if ( source == urlField) { if (urlField.isEnabled() && urlField.getText().equalsIgnoreCase(urlText)) { urlField.setText(""); } dlg.getButton(0).setEnabled( true ); } else if ( source == fileField) { dlg.getButton(0).setEnabled( bufferedICal != null ); if (fileField.isEnabled()) { final Frame frame = (Frame) SwingUtilities.getRoot(getMainComponent()); IOInterface io = getService( IOInterface.class); try { FileContent file = io.openFile( frame, null, new String[] {".ics"}); if ( file != null) { BufferedReader reader = new BufferedReader(new InputStreamReader( file.getInputStream())); StringBuffer buf = new StringBuffer(); while ( true) { String line = reader.readLine(); if ( line == null) { break; } buf.append( line); buf.append( "\n"); } fileField.setText(file.getName()); bufferedICal = buf.toString(); dlg.getButton(0).setEnabled( true ); } } catch (IOException ex) { bufferedICal = null; dlg.getButton(0).setEnabled( false ); showException(ex, getMainComponent()); } } } } }; urlField.addMouseListener(listener); fileField.addMouseListener(listener); final String title = "iCal-" + getString("import"); dlg.setTitle(title); dlg.setSize(new Dimension(850, 100)); // dlg.setResizable(false); dlg.getButton(0).setIcon(getIcon("icon.import")); dlg.getButton(1).setIcon(getIcon("icon.cancel")); dlg.getButton(0).setAction(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { Collection<Allocatable> liste = resourceSelection.getAllocatables(); try { boolean isURL = urlRadio.isSelected() && urlRadio.isEnabled(); String iCal; if (isURL) { iCal = urlField.getText(); } else { iCal = bufferedICal; } String[] allocatableIds = new String[liste.size()]; int i = 0; for ( Allocatable alloc:liste) { allocatableIds[i++] = alloc.getId(); } final DynamicType dynamicType = (DynamicType) comboEventType.getSelectedItem(); if (dynamicType == null) return; String eventTypeKey = dynamicType.getKey(); Object selectedItem = comboNameAttribute.getSelectedItem(); if (selectedItem == null) return; String eventTypeAttributeNameKey = ((Attribute) selectedItem).getKey(); Integer[] status = importService.importICal(iCal, isURL, allocatableIds, eventTypeKey, eventTypeAttributeNameKey).get(); int eventsInICal = status[0]; int eventsImported = status[1]; int eventsPresent = status[2]; int eventsSkipped = status[3]; getClientFacade().refresh(); dlg.close(); String text = "Imported " + eventsImported + "/" + eventsInICal + ". " + eventsPresent + " present"; if (eventsSkipped > 0) { text += " and " + eventsSkipped + " skipped "; } else { text+="."; } DialogUI okDlg = DialogUI.create(getContext(), getMainComponent(), false, title, text); okDlg.start(); } catch (Exception e1) { showException(e1, getMainComponent()); } } }); dlg.start(); } @SuppressWarnings("unchecked") private void setRenderer(final JComboBox comboEventType, final JComboBox comboNameAttribute) { final DefaultListCellRenderer aRenderer = new NamedListCellRenderer(); comboEventType.setRenderer(aRenderer); comboNameAttribute.setRenderer(aRenderer); } final protected TreeFactory getTreeFactory() { return getService(TreeFactory.class); } private class NamedListCellRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 1L; public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value != null && value instanceof Named) value = ((Named) value).getName(ImportFrom2iCalMenu.this.getLocale()); return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } } @SuppressWarnings("unchecked") private void updateNameAttributes(JComboBox comboEventType, JComboBox comboNameAttribute) { final DynamicType dynamicType = (DynamicType) comboEventType.getSelectedItem(); ComboBoxModel result; if (dynamicType == null) { //no dynamic type found, so empty combobox model result = new DefaultComboBoxModel(); } else { // found one, so determine all string attribute of event type and update model final Attribute[] attributes = dynamicType.getAttributes(); final List<Attribute> attributeResult = new ArrayList<Attribute>(); for (Attribute attribute : attributes) { if (attribute.getType().is(AttributeType.STRING)) { attributeResult.add(attribute); } } DefaultComboBoxModel defaultComboBoxModel = new DefaultComboBoxModel(attributeResult.toArray()); result = defaultComboBoxModel; } //initialize model comboNameAttribute.setModel(result); } }
04900db4-rob
src/org/rapla/plugin/ical/ImportFrom2iCalMenu.java
Java
gpl3
13,202
package org.rapla.plugin.ical; import org.rapla.client.ClientServiceContainer; import org.rapla.client.RaplaClientExtensionPoints; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.components.xmlbundle.impl.I18nBundleImpl; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContextException; import org.rapla.framework.StartupEnvironment; import org.rapla.framework.TypedComponentRole; public class ImportFromICalPlugin implements PluginDescriptor<ClientServiceContainer>{ public static final TypedComponentRole<I18nBundle> RESOURCE_FILE = new TypedComponentRole<I18nBundle>(ImportFromICalPlugin.class.getPackage().getName() + ".ImportFromICalResources"); public static final boolean ENABLE_BY_DEFAULT = false; public void provideServices(ClientServiceContainer container, Configuration config) throws RaplaContextException { if (!config.getAttributeAsBoolean("enabled", ENABLE_BY_DEFAULT)) return; container.addContainerProvidedComponent(RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig(RESOURCE_FILE.getId())); final int startupMode = container.getStartupEnvironment().getStartupMode(); if ( startupMode != StartupEnvironment.APPLET) { container.addContainerProvidedComponent(RaplaClientExtensionPoints.IMPORT_MENU_EXTENSION_POINT, ImportFrom2iCalMenu.class); } } }
04900db4-rob
src/org/rapla/plugin/ical/ImportFromICalPlugin.java
Java
gpl3
1,426
package org.rapla.plugin.ical; import javax.jws.WebService; import org.rapla.rest.gwtjsonrpc.common.FutureResult; @WebService public interface ICalImport { FutureResult<Integer[]> importICal(String content, boolean isURL, String[] allocatableIds, String eventTypeKey, String eventTypeNameAttributeKey); }
04900db4-rob
src/org/rapla/plugin/ical/ICalImport.java
Java
gpl3
310
package org.rapla.plugin.ical.server; import org.rapla.components.xmlbundle.impl.I18nBundleImpl; import org.rapla.framework.Configuration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContextException; import org.rapla.plugin.export2ical.Export2iCalPlugin; import org.rapla.plugin.ical.ICalImport; import org.rapla.plugin.ical.ImportFromICalPlugin; import org.rapla.server.ServerServiceContainer; public class ImportFromICalServerPlugin implements PluginDescriptor<ServerServiceContainer> { public void provideServices(ServerServiceContainer container, Configuration config) throws RaplaContextException { if (!config.getAttributeAsBoolean("enabled", Export2iCalPlugin.ENABLE_BY_DEFAULT)) return; container.addContainerProvidedComponent(ImportFromICalPlugin.RESOURCE_FILE, I18nBundleImpl.class, I18nBundleImpl.createConfig(Export2iCalPlugin.RESOURCE_FILE.getId())); container.addRemoteMethodFactory(ICalImport.class, RaplaICalImport.class, config); } }
04900db4-rob
src/org/rapla/plugin/ical/server/ImportFromICalServerPlugin.java
Java
gpl3
1,007
package org.rapla.plugin.ical.server; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import net.fortuna.ical4j.data.CalendarBuilder; import net.fortuna.ical4j.data.ParserException; import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.ComponentList; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.Dur; import net.fortuna.ical4j.model.NumberList; import net.fortuna.ical4j.model.Period; import net.fortuna.ical4j.model.PeriodList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyList; import net.fortuna.ical4j.model.Recur; import net.fortuna.ical4j.model.WeekDayList; import net.fortuna.ical4j.model.property.DateProperty; import net.fortuna.ical4j.model.property.RRule; import net.fortuna.ical4j.util.CompatibilityHints; import org.rapla.components.util.DateTools; import org.rapla.entities.Entity; import org.rapla.entities.EntityNotFoundException; import org.rapla.entities.User; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.RepeatingType; import org.rapla.entities.domain.Reservation; import org.rapla.entities.domain.RaplaObjectAnnotations; import org.rapla.entities.dynamictype.Classification; import org.rapla.facade.RaplaComponent; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaException; import org.rapla.plugin.ical.ICalImport; import org.rapla.rest.gwtjsonrpc.common.FutureResult; import org.rapla.rest.gwtjsonrpc.common.ResultImpl; import org.rapla.server.RemoteMethodFactory; import org.rapla.server.RemoteSession; import org.rapla.server.TimeZoneConverter; import org.rapla.storage.impl.AbstractCachableOperator; public class RaplaICalImport extends RaplaComponent implements RemoteMethodFactory<ICalImport> { private TimeZone timeZone; private TimeZoneConverter timeZoneConverter; public RaplaICalImport( RaplaContext context) throws RaplaContextException{ this( context, context.lookup(TimeZoneConverter.class).getImportExportTimeZone()); } public RaplaICalImport( RaplaContext context, TimeZone timeZone) throws RaplaContextException{ super( context); this.timeZone = timeZone; this.timeZoneConverter = context.lookup( TimeZoneConverter.class); } public ICalImport createService(final RemoteSession remoteSession) { return new ICalImport() { @Override public FutureResult<Integer[]> importICal(String content, boolean isURL, String[] allocatableIds, String eventTypeKey, String eventTypeNameAttributeKey) { try { List<Allocatable> allocatables = new ArrayList<Allocatable>(); if ( allocatableIds.length > 0) { for ( String id:allocatableIds) { Allocatable allocatable = getAllocatable(id); allocatables.add ( allocatable); } } User user = remoteSession.getUser(); Integer[] count = importCalendar(content, isURL, allocatables, user, eventTypeKey, eventTypeNameAttributeKey); return new ResultImpl<Integer[]>(count); } catch (RaplaException ex) { return new ResultImpl<Integer[]>(ex); } } }; } private Allocatable getAllocatable( final String id) throws EntityNotFoundException { AbstractCachableOperator operator = (AbstractCachableOperator) getClientFacade().getOperator(); final Allocatable refEntity = operator.resolve( id, Allocatable.class); return refEntity; } /** * parses iCal calendar and creates reservations for the contained VEVENTS. * SUMMARY will match to the name of the reservation. * can handle events with DTEND or DURATION. * recurrance information from RRULE will be handled by google-rfc-2445. * reads TZID information from given file. If the is none, passedTimezone * will be used. * * @param content * path of the *.ics file * @param isURL * set true if the path is a URL and no local filepath * @param resources * if you want to add resources to all event in the given * calendar, pass a list. * each element of the list has to be a String[] and stands for * one resource. * * <pre> * element[0] contains the name of the dynamic Type for the allocatable * element[1] contains the name of the allocatable * </pre> * @param user * @param eventTypeKey * @throws FileNotFoundException * @throws MalformedURLException * @throws RaplaException */ public Integer[] importCalendar(String content, boolean isURL, List<Allocatable> resources, User user, String eventTypeKey, String eventTypeNameAttributeKey) throws RaplaException { CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_NOTES_COMPATIBILITY, true); CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY, true); CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_RELAXED_PARSING, true); CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_RELAXED_UNFOLDING, true); CompatibilityHints.setHintEnabled( CompatibilityHints.KEY_RELAXED_VALIDATION, true); CalendarBuilder builder = new CalendarBuilder(); Calendar calendar = null; int eventsInICal = 0; int eventsImported = 0; int eventsPresent = 0; int eventsSkipped = 0; try { if (isURL) { InputStream in = new URL(content).openStream(); calendar = builder.build(in); in.close(); } else { StringReader fin = new StringReader(content); calendar = builder.build(fin); } } catch (IOException ioe) { throw new RaplaException(ioe.getMessage()); } catch (ParserException pe) { throw new RaplaException(pe.getMessage()); } catch (IllegalArgumentException pe) { throw new RaplaException(pe.getMessage()); } ComponentList events = calendar.getComponents(); @SuppressWarnings("unchecked") Iterator<Component> iterator = events.iterator(); List<Reservation> eventList = new ArrayList<Reservation>(); Map<String, Reservation> reservationMap = new HashMap<String, Reservation>(); while (iterator.hasNext()) { Component component = iterator.next(); if (component.getName().equalsIgnoreCase("VEVENT") ) { try { eventsInICal ++; String uid = null; Reservation lookupEvent = null; String name = component.getProperty("SUMMARY").getValue(); Property uidProperty = component.getProperty("UID"); if ( uidProperty != null) { uid = uidProperty.getValue(); lookupEvent = reservationMap.get( uid); } if (name == null || name.trim().length() == 0) { getLogger().debug("Ignoring event with empty name [" + uid + "]" ); eventsSkipped ++; continue; } if ( lookupEvent == null) { // create the reservation Classification classification = getClientFacade().getDynamicType(eventTypeKey).newClassification(); lookupEvent = getClientFacade().newReservation(classification,user); if ( uid != null) { lookupEvent.setAnnotation( RaplaObjectAnnotations.KEY_EXTERNALID, uid); } classification.setValue(eventTypeNameAttributeKey, name); } Reservation event = lookupEvent; DateProperty startDateProperty = (DateProperty)component.getProperty("DTSTART"); Date startdate = startDateProperty.getDate(); Date enddate = null; boolean wholeDay = false; long duration_millis = 0; Dur duration; if (component.getProperties("DTEND").size() > 0) { DateProperty endDateProperty = (DateProperty)component.getProperty("DTEND"); enddate = endDateProperty.getDate(); duration = null; } else if (component.getProperties("DURATION").size() > 0) { duration = new Dur(component.getProperty("DURATION").getValue()); Date t1 = new Date(); Date t2 = duration.getTime(t1); duration_millis = t2.getTime() - t1.getTime(); } else { getLogger().warn("Error in ics File. There is an event without DTEND or DURATION. " + "SUMMARY: " + name + ", DTSTART: " + startdate); eventsSkipped ++; continue; } for (Allocatable allocatable: resources) { event.addAllocatable(allocatable); } if (duration_millis == 0 && enddate != null) { duration_millis = enddate.getTime() - startdate.getTime(); } // create appointment Appointment appointment; if ( !(startdate instanceof DateTime)) { Date begin = new Date( startdate.getTime()); Date end = new Date(begin.getTime() + duration_millis); appointment = newAppointment(user,begin, end); wholeDay = true; appointment.setWholeDays(wholeDay); } else { Date begin = timeZoneConverter.toRaplaTime(timeZone, startdate); Date end = new Date(begin.getTime() + duration_millis); appointment = newAppointment(user,begin, end); } PropertyList rrules = component.getProperties("RRULE"); if ( rrules.size() >0) { List<Recur> recurList = new ArrayList<Recur>(rrules.size()); for ( int i=0;i<rrules.size();i++) { Property prop = (Property) rrules.get( i); RRule rrule = new RRule(prop.getParameters(),prop.getValue()); recurList.add(rrule.getRecur()); } List<Appointment> list = calcRepeating( recurList, appointment); if ( list != null) { for ( Appointment app: list) { event.addAppointment( app); } } else { net.fortuna.ical4j.model.Date periodEnd = null; for (Recur recur: recurList) { net.fortuna.ical4j.model.Date until = recur.getUntil(); if ( until != null) { if ( periodEnd == null || periodEnd.before( until)) { periodEnd = until; } } } if ( periodEnd == null) { periodEnd = new net.fortuna.ical4j.model.Date(startdate.getTime() + DateTools.MILLISECONDS_PER_WEEK * 52 *6); } PeriodList periodList; { long e4 = DateTools.addDays( periodEnd, 1).getTime(); long s1 = startdate.getTime(); Period period = new Period(new DateTime( s1), new DateTime(e4)); periodList = component.calculateRecurrenceSet(period); } for ( @SuppressWarnings("unchecked") Iterator<Period> it = periodList.iterator();it.hasNext();) { Period p = it.next(); Date s = timeZoneConverter.toRaplaTime(timeZone, p.getStart()); Date e = timeZoneConverter.toRaplaTime(timeZone,p.getEnd()); Appointment singleAppointment = newAppointment( user,s, e); event.addAppointment( singleAppointment); } } } else { event.addAppointment( appointment); } /* * get a date iterable for given startdate and recurrance * rule. * timezone passed is UTC, because timezone calculation has * already been taken care of earlier */ if (uid != null) { reservationMap.put( uid, lookupEvent); } eventList.add( lookupEvent); } catch (ParseException ex) { } } else if (component.getName().equalsIgnoreCase("VTIMEZONE")) { if (component.getProperties("TZID").size() > 0) { // TimeZone timezoneFromICal = TimeZone.getTimeZone(component.getProperty("TZID").getValue()); } } } Date minStart = null; Map<String, List<Entity<Reservation>>> imported = getImportedReservations(minStart); List<Reservation> toImport = new ArrayList<Reservation>(); for (Reservation reservation:eventList) { String uid = reservation.getAnnotation(RaplaObjectAnnotations.KEY_EXTERNALID); if ( uid == null) { eventsImported++; toImport.add( reservation); } else { List<Entity<Reservation>> alreadyImported = imported.get( uid); if ( alreadyImported == null || alreadyImported.isEmpty()) { eventsImported++; toImport.add( reservation); } else { getLogger().debug("Ignoring event with uid " + uid + " already imported. Ignoring" ); eventsPresent++; } } } getClientFacade().storeObjects(toImport.toArray(Reservation.RESERVATION_ARRAY)); return new Integer[] {eventsInICal, eventsImported, eventsPresent, eventsSkipped}; } protected Map<String, List<Entity<Reservation>>> getImportedReservations(Date start) throws RaplaException { Map<String,List<Entity<Reservation>>> keyMap; User user = null; Date end = null; keyMap = new LinkedHashMap<String, List<Entity<Reservation>>>(); Reservation[] reservations = getQuery().getReservations(user, start, end, null); for ( Reservation r:reservations) { String key = r.getAnnotation(RaplaObjectAnnotations.KEY_EXTERNALID); if ( key != null ) { List<Entity<Reservation>> list = keyMap.get( key); if ( list == null) { list = new ArrayList<Entity<Reservation>>(); keyMap.put( key, list); } list.add( r); } } return keyMap; } // // private Date toRaplaDate(TimeZone timeZone2, // net.fortuna.ical4j.model.Date startdate) // { // java.util.Calendar cal = java.util.Calendar.getInstance( getRaplaLocale().getSystemTimeZone()); // cal.setTime(startdate); // cal.add( java.util.Calendar.HOUR_OF_DAY, 2); // int date = cal.get( java.util.Calendar.DATE); // int month = cal.get( java.util.Calendar.MONTH); // int year = cal.get( java.util.Calendar.YEAR); // // Date time = cal.getTime(); // Date convertedDate = getRaplaLocale().toRaplaTime(timeZone2, time); // return null; // } private Appointment newAppointment(User user,Date begin, Date end) throws RaplaException { Appointment appointment = getClientFacade().newAppointment(begin,end,user); return appointment; } /** if the recurances can be matched to one or more appointments return the appointment list else return null*/ private List<Appointment> calcRepeating(List<Recur> recurList, Appointment start) throws RaplaException { final List<Appointment> appointments = new ArrayList<Appointment>(); for (Recur recur : recurList) { // FIXME need to implement UTC mapping final Appointment appointment = getClientFacade().newAppointment(start.getStart(), start.getEnd(), start.getOwner()); appointment.setRepeatingEnabled(true); WeekDayList dayList = recur.getDayList(); if (dayList.size() > 1 || (dayList.size() == 1 && !recur.getFrequency().equals(Recur.WEEKLY) )) { return null; } NumberList yearDayList = recur.getYearDayList(); if ( yearDayList.size() > 0) { return null; } NumberList weekNoList = recur.getWeekNoList(); if ( weekNoList.size() > 0){ return null; } NumberList hourList = recur.getHourList(); if ( hourList.size() > 0){ return null; } NumberList monthList = recur.getMonthList(); if (monthList.size() > 1 || (monthList.size() == 1 && !recur.getFrequency().equals(Recur.MONTHLY) )) { return null; } if (recur.getFrequency().equals(Recur.DAILY)) appointment.getRepeating().setType(RepeatingType.DAILY); else if (recur.getFrequency().equals(Recur.MONTHLY)) appointment.getRepeating().setType(RepeatingType.MONTHLY); else if (recur.getFrequency().equals(Recur.YEARLY)) appointment.getRepeating().setType(RepeatingType.YEARLY); else if (recur.getFrequency().equals(Recur.WEEKLY)) appointment.getRepeating().setType(RepeatingType.WEEKLY); else throw new IllegalStateException("Repeating type "+recur.getFrequency()+" not (yet) supported"); //recur.getCount() == -1 when it never ends int count = recur.getCount(); appointment.getRepeating().setNumber(count); if (count <= 0) { net.fortuna.ical4j.model.Date until = recur.getUntil(); Date repeatingEnd; if ( until instanceof DateTime) { repeatingEnd = timeZoneConverter.toRaplaTime( timeZone, until); } else if ( until != null) { repeatingEnd = new Date(until.getTime()); } else { repeatingEnd = null; } appointment.getRepeating().setEnd(repeatingEnd); } //interval appointment.getRepeating().setInterval(recur.getInterval()); appointments.add(appointment); } return appointments; } }
04900db4-rob
src/org/rapla/plugin/ical/server/RaplaICalImport.java
Java
gpl3
19,615
package org.rapla.plugin.export2ical; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.List; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import org.rapla.components.iolayer.IOInterface; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Appointment; import org.rapla.entities.domain.Reservation; import org.rapla.facade.CalendarModel; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.toolkit.IdentifiableMenuEntry; import org.rapla.plugin.abstractcalendar.RaplaBuilder; public class Export2iCalMenu extends RaplaGUIComponent implements IdentifiableMenuEntry, ActionListener{ String id = "export_file_text"; JMenuItem item; ICalExport exportService; public Export2iCalMenu(RaplaContext sm,ICalExport exportService){ super(sm); this.exportService = exportService; setChildBundleName(Export2iCalPlugin.RESOURCE_FILE); item = new JMenuItem(getString(id)); item.setIcon(getIcon("icon.export")); item.addActionListener(this); } public String getId() { return id; } public JMenuItem getMenuElement() { return item; } public void actionPerformed(ActionEvent evt) { getCalendarOptions(); try { CalendarModel raplaCal = getService(CalendarModel.class); Reservation[] reservations = raplaCal.getReservations(); Allocatable[] allocatables = raplaCal.getSelectedAllocatables(); List<Appointment> appointments= RaplaBuilder.getAppointments( reservations, allocatables); String[] appointmentIds = new String[appointments.size()]; for ( int i=0;i<appointmentIds.length;i++) { appointmentIds[i] = appointments.get(i).getId(); } String result = exportService.export(appointmentIds); if ( result.trim().length() == 0) { JOptionPane.showMessageDialog(null, getString("no_dates_text"), "Export2iCal", JOptionPane.INFORMATION_MESSAGE); } else { String nonEmptyTitle = raplaCal.getNonEmptyTitle(); if ( nonEmptyTitle.length() == 0) { nonEmptyTitle = "rapla_calendar"; } String name =nonEmptyTitle +".ics"; export(result, name); } } catch (Exception ex) { showException(ex, getMainComponent()); } } private void export(String result, String name) throws RaplaException { final byte[] bytes = result.getBytes(); saveFile(bytes, name , new String[] {"ics","ical"}); } public void saveFile(byte[] content, String filename, String[] extensions) throws RaplaException { final Frame frame = (Frame) SwingUtilities.getRoot(getMainComponent()); IOInterface io = getService(IOInterface.class); try { io.saveFile(frame, null, extensions, filename, content); } catch (IOException e) { throw new RaplaException("Can't export file!", e); } } }
04900db4-rob
src/org/rapla/plugin/export2ical/Export2iCalMenu.java
Java
gpl3
3,044
package org.rapla.plugin.export2ical; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Locale; import javax.swing.ButtonGroup; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JSpinner; import javax.swing.JTextArea; import javax.swing.SpinnerNumberModel; import org.rapla.components.layout.TableLayout; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; import org.rapla.framework.PluginDescriptor; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaException; import org.rapla.gui.DefaultPluginOption; import org.rapla.gui.RaplaGUIComponent; /******************************************************************************* * This is the admin-option panel * * @author Twardon * */ public class Export2iCalAdminOption extends DefaultPluginOption implements ActionListener { private JSpinner spiDaysBefore; private JSpinner spiDaysAfter; private JRadioButton optGlobalInterval; private JRadioButton optUserInterval; private JLabel lblLastModifiedInterval; private JSpinner spiLastModifiedInterval; private JCheckBox chkUseLastModifiedIntervall; private JCheckBox chkExportAttendees; private JTextArea txtEMailRessourceAttribute; private JComboBox cbDefaultParticipationsStatusRessourceAttribute; public Export2iCalAdminOption(RaplaContext sm){ super(sm); } protected JPanel createPanel() throws RaplaException { spiLastModifiedInterval = new JSpinner(new SpinnerNumberModel(5, 0, 365, 1)); chkUseLastModifiedIntervall = new JCheckBox("do not deliver new calendar"); chkExportAttendees = new JCheckBox("export attendees of vevent"); txtEMailRessourceAttribute = new JTextArea(Export2iCalPlugin.DEFAULT_attendee_resource_attribute); RaplaGUIComponent copyPasteWrapper = new RaplaGUIComponent( getContext()); copyPasteWrapper.addCopyPaste(txtEMailRessourceAttribute); txtEMailRessourceAttribute.setToolTipText("Define the key of the attribute containing the email address"); @SuppressWarnings("unchecked") JComboBox jComboBox = new JComboBox(new Object [] { "ACCEPTED", "TENTATIVE" }); cbDefaultParticipationsStatusRessourceAttribute = jComboBox; cbDefaultParticipationsStatusRessourceAttribute.setSelectedItem(Export2iCalPlugin.DEFAULT_attendee_participation_status); cbDefaultParticipationsStatusRessourceAttribute.setToolTipText("Define the default value for participation status"); spiDaysBefore = new JSpinner(new SpinnerNumberModel(Export2iCalPlugin.DEFAULT_daysBefore, 0, 365, 1)); spiDaysAfter = new JSpinner(new SpinnerNumberModel(Export2iCalPlugin.DEFAULT_daysAfter, 0, 365, 1)); optGlobalInterval = new JRadioButton("global interval setting"); optUserInterval = new JRadioButton("user interval settings"); lblLastModifiedInterval = new JLabel("interval for delivery in days"); //String[] availableIDs = net.fortuna.ical4j.model.TimeZone.getAvailableIDs(); ButtonGroup group = new ButtonGroup(); group.add(optGlobalInterval); group.add(optUserInterval); JPanel panel = super.createPanel(); JPanel content = new JPanel(); double[][] sizes = new double[][] { { 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5 }, { TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5, TableLayout.PREFERRED, 5 } }; TableLayout tableLayout = new TableLayout(sizes); content.setLayout(tableLayout); content.add(optGlobalInterval, "1,4"); content.add(optUserInterval, "3,4"); content.add(new JLabel("previous days:"), "1,6"); content.add(spiDaysBefore, "3,6"); content.add(new JLabel("subsequent days:"), "1,8"); content.add(spiDaysAfter, "3,8"); content.add(chkUseLastModifiedIntervall, "1,12"); content.add(lblLastModifiedInterval, "1,14"); content.add(spiLastModifiedInterval, "3,14"); content.add(chkExportAttendees, "1,16"); content.add(new JLabel("attribute key in person-type:"), "1,18"); content.add(txtEMailRessourceAttribute, "3,18"); content.add(new JLabel("participation status:"), "1,20"); content.add(cbDefaultParticipationsStatusRessourceAttribute, "3,20"); panel.add(content, BorderLayout.CENTER); optUserInterval.addActionListener(this); optGlobalInterval.addActionListener(this); chkUseLastModifiedIntervall.addActionListener(this); chkExportAttendees.addActionListener(this); return panel; } protected void addChildren(DefaultConfiguration newConfig) { newConfig.getMutableChild(Export2iCalPlugin.DAYS_BEFORE, true).setValue(Integer.parseInt(spiDaysBefore.getValue().toString())); newConfig.getMutableChild(Export2iCalPlugin.DAYS_AFTER, true).setValue(Integer.parseInt(spiDaysAfter.getValue().toString())); newConfig.getMutableChild(Export2iCalPlugin.GLOBAL_INTERVAL, true).setValue(optGlobalInterval.isSelected()); String lastModIntervall = chkUseLastModifiedIntervall.isSelected() ? new String("-1") : spiLastModifiedInterval.getValue().toString(); newConfig.getMutableChild(Export2iCalPlugin.LAST_MODIFIED_INTERVALL, true).setValue(lastModIntervall); newConfig.getMutableChild(Export2iCalPlugin.EXPORT_ATTENDEES, true).setValue(chkExportAttendees.isSelected()); newConfig.getMutableChild(Export2iCalPlugin.EXPORT_ATTENDEES_EMAIL_ATTRIBUTE, true).setValue(txtEMailRessourceAttribute.getText()); newConfig.getMutableChild(Export2iCalPlugin.EXPORT_ATTENDEES_PARTICIPATION_STATUS, true).setValue(cbDefaultParticipationsStatusRessourceAttribute.getSelectedItem().toString()); } protected void readConfig(Configuration config) { int daysBefore = config.getChild(Export2iCalPlugin.DAYS_BEFORE).getValueAsInteger(Export2iCalPlugin.DEFAULT_daysBefore); int daysAfter = config.getChild(Export2iCalPlugin.DAYS_AFTER).getValueAsInteger(Export2iCalPlugin.DEFAULT_daysAfter); int lastModifiedIntervall = config.getChild(Export2iCalPlugin.LAST_MODIFIED_INTERVALL).getValueAsInteger(Export2iCalPlugin.DEFAULT_lastModifiedIntervall); boolean global_interval = config.getChild(Export2iCalPlugin.GLOBAL_INTERVAL).getValueAsBoolean(Export2iCalPlugin.DEFAULT_globalIntervall); boolean exportAttendees = config.getChild(Export2iCalPlugin.EXPORT_ATTENDEES).getValueAsBoolean(Export2iCalPlugin.DEFAULT_exportAttendees); String exportAttendeeDefaultEmailAttribute = config.getChild(Export2iCalPlugin.EXPORT_ATTENDEES_EMAIL_ATTRIBUTE).getValue(Export2iCalPlugin.DEFAULT_attendee_resource_attribute); String exportAttendeeParticipationStatus = config.getChild(Export2iCalPlugin.EXPORT_ATTENDEES_PARTICIPATION_STATUS).getValue(Export2iCalPlugin.DEFAULT_attendee_participation_status); if (lastModifiedIntervall == -1) { spiLastModifiedInterval.setEnabled(false); lblLastModifiedInterval.setEnabled(false); chkUseLastModifiedIntervall.setSelected(true); } else { spiLastModifiedInterval.setValue(new Integer(lastModifiedIntervall)); lblLastModifiedInterval.setEnabled(true); chkUseLastModifiedIntervall.setSelected(false); } optGlobalInterval.setSelected(global_interval); optUserInterval.setSelected(!global_interval); spiDaysBefore.setValue(new Integer(daysBefore)); spiDaysAfter.setValue(new Integer(daysAfter)); chkExportAttendees.setSelected(exportAttendees); txtEMailRessourceAttribute.setText(exportAttendeeDefaultEmailAttribute); txtEMailRessourceAttribute.setEnabled(chkExportAttendees.isSelected()); cbDefaultParticipationsStatusRessourceAttribute.setSelectedItem(exportAttendeeParticipationStatus); cbDefaultParticipationsStatusRessourceAttribute.setEnabled(chkExportAttendees.isSelected()); //this.setTextFieldInput(); } public Class<? extends PluginDescriptor<?>> getPluginClass() { return Export2iCalPlugin.class; } public String getName(Locale locale) { return "Export2iCal"; } /* //This is now not needed anymore private void setTextFieldInput() { this.spiDaysBefore.setEnabled(optGlobalInterval.isSelected()); this.spiDaysAfter.setEnabled(optGlobalInterval.isSelected()); }*/ public void actionPerformed(ActionEvent e) { //this.setTextFieldInput(); if (e.getSource() == chkUseLastModifiedIntervall) { spiLastModifiedInterval.setEnabled(!chkUseLastModifiedIntervall.isSelected()); lblLastModifiedInterval.setEnabled(!chkUseLastModifiedIntervall.isSelected()); } if (e.getSource() == chkExportAttendees) { txtEMailRessourceAttribute.setEnabled(chkExportAttendees.isSelected()); cbDefaultParticipationsStatusRessourceAttribute.setEnabled(chkExportAttendees.isSelected()); } } }
04900db4-rob
src/org/rapla/plugin/export2ical/Export2iCalAdminOption.java
Java
gpl3
9,305
package org.rapla.plugin.export2ical; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.rapla.components.layout.TableLayout; import org.rapla.facade.CalendarSelectionModel; import org.rapla.framework.RaplaContext; import org.rapla.gui.PublishExtension; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.toolkit.RaplaButton; class IcalPublishExtension extends RaplaGUIComponent implements PublishExtension { JPanel panel = new JPanel(); CalendarSelectionModel model; final JCheckBox checkbox; final JTextField icalURL; public IcalPublishExtension(RaplaContext context, CalendarSelectionModel model) { super(context); this.model = model; panel.setLayout(new TableLayout( new double[][] {{TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.FILL}, {TableLayout.PREFERRED,5,TableLayout.PREFERRED }})); icalURL = new JTextField(); checkbox = new JCheckBox("ICAL " + getString("publish")); final JPanel statusICal = createStatus( icalURL); checkbox.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { boolean icalEnabled = checkbox.isSelected() ; statusICal.setEnabled( icalEnabled); } }); panel.add(checkbox,"0,0"); panel.add( statusICal, "2,2,4,1"); final String entry = model.getOption(Export2iCalPlugin.ICAL_EXPORT); boolean selected = entry != null && entry.equals("true"); checkbox.setSelected( selected); statusICal.setEnabled( selected); } JPanel createStatus( final JTextField urlLabel) { addCopyPaste(urlLabel); final RaplaButton copyButton = new RaplaButton(); JPanel status = new JPanel() { private static final long serialVersionUID = 1L; public void setEnabled(boolean enabled) { super.setEnabled(enabled); urlLabel.setEnabled( enabled); copyButton.setEnabled( enabled); } }; status.setLayout( new BorderLayout()); urlLabel.setText( ""); urlLabel.setEditable( true ); urlLabel.setFont( urlLabel.getFont().deriveFont( (float)10.0)); status.add( new JLabel("URL: "), BorderLayout.WEST ); status.add( urlLabel, BorderLayout.CENTER ); copyButton.setBorder(BorderFactory.createEmptyBorder(2,2,2,2)); copyButton.setFocusable(false); copyButton.setRolloverEnabled(false); copyButton.setIcon(getIcon("icon.copy")); copyButton.setToolTipText(getString("copy_to_clipboard")); copyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { urlLabel.requestFocus(); urlLabel.selectAll(); copy(urlLabel,e); } }); status.add(copyButton, BorderLayout.EAST); return status; } public JPanel getPanel() { return panel; } public void mapOptionTo() { final String icalSelected = checkbox.isSelected() ? "true" : "false"; model.setOption( Export2iCalPlugin.ICAL_EXPORT, icalSelected); } public JTextField getURLField() { return icalURL; } public boolean hasAddressCreationStrategy() { return false; } public String getAddress(String filename, String generator) { return null; } public String getGenerator() { return Export2iCalPlugin.GENERATOR; } }
04900db4-rob
src/org/rapla/plugin/export2ical/IcalPublishExtension.java
Java
gpl3
3,797