code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
package org.rapla.gui.internal.edit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.rapla.components.util.undo.CommandUndo;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.Named;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.dynamictype.Classifiable;
import org.rapla.entities.internal.ModifiableTimestamp;
import org.rapla.entities.storage.EntityReferencer.ReferenceInfo;
import org.rapla.entities.storage.internal.SimpleEntity;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class SaveUndo<T extends Entity> extends RaplaComponent implements CommandUndo<RaplaException> {
protected final List<T> newEntities;
protected final List<T> oldEntities;
protected final String commandoName;
protected boolean firstTimeCall = true;
public SaveUndo(RaplaContext context,Collection<T> newEntity,Collection<T> originalEntity)
{
this( context, newEntity, originalEntity, null);
}
public SaveUndo(RaplaContext context,Collection<T> newEntity,Collection<T> originalEntity, String commandoName)
{
super(context);
this.commandoName = commandoName;
this.newEntities = new ArrayList<T>();
for ( T entity: newEntity)
{
@SuppressWarnings("unchecked")
T clone = (T) entity.clone();
this.newEntities.add(clone);
}
if (originalEntity !=null)
{
if ( originalEntity.size() != newEntity.size() )
{
throw new IllegalArgumentException("Original and new list need the same size");
}
this.oldEntities = new ArrayList<T>();
for ( T entity: originalEntity)
{
@SuppressWarnings("unchecked")
T clone = (T) entity.clone();
this.oldEntities.add( clone);
}
}
else
{
this.oldEntities = null;
}
}
public boolean execute() throws RaplaException {
final boolean isNew = oldEntities == null;
List<T> toStore = new ArrayList<T>();
Map<T,T> newEntitiesPersistant = null;
if ( !firstTimeCall || !isNew)
{
newEntitiesPersistant= getModification().getPersistant(newEntities);
}
if ( firstTimeCall)
{
firstTimeCall = false;
}
else
{
checklastChanged(newEntities, newEntitiesPersistant);
}
for ( T entity: newEntities)
{
@SuppressWarnings("unchecked")
T mutableEntity = (T) entity.clone();
if (!isNew)
{
@SuppressWarnings("null")
Entity persistant = (Entity) newEntitiesPersistant.get( entity);
checkConsistency( mutableEntity );
setNewTimestamp( mutableEntity, persistant);
}
toStore.add( mutableEntity);
}
@SuppressWarnings("unchecked")
Entity<T>[] array = toStore.toArray(new Entity[]{});
getModification().storeObjects( array);
return true;
}
protected void checklastChanged(List<T> entities, Map<T,T> persistantVersions) throws RaplaException,
EntityNotFoundException {
getUpdateModule().refresh();
for ( T entity:entities)
{
if ( entity instanceof ModifiableTimestamp)
{
T persistant = persistantVersions.get( entity);
if ( persistant != null)
{
User lastChangedBy = ((ModifiableTimestamp) persistant).getLastChangedBy();
if (lastChangedBy != null && !getUser().equals(lastChangedBy))
{
String name = entity instanceof Named ? ((Named) entity).getName( getLocale()) : entity.toString();
throw new RaplaException(getI18n().format("error.new_version", name));
}
}
else
{
// if there exists an older version
if ( oldEntities != null)
{
String name = entity instanceof Named ? ((Named) entity).getName( getLocale()) : entity.toString();
throw new RaplaException(getI18n().format("error.new_version", name));
}
// otherwise we ignore it
}
}
}
}
public boolean undo() throws RaplaException {
boolean isNew = oldEntities == null;
if (isNew) {
Map<T,T> newEntitiesPersistant = getModification().getPersistant(newEntities);
checklastChanged(newEntities, newEntitiesPersistant);
Entity[] array = newEntities.toArray(new Entity[]{});
getModification().removeObjects(array);
} else {
List<T> toStore = new ArrayList<T>();
Map<T,T> oldEntitiesPersistant = getModification().getPersistant(oldEntities);
checklastChanged(oldEntities, oldEntitiesPersistant);
for ( T entity: oldEntities)
{
@SuppressWarnings("unchecked")
T mutableEntity = (T) entity.clone();
T persistantVersion = oldEntitiesPersistant.get( entity);
checkConsistency( mutableEntity);
setNewTimestamp( mutableEntity, persistantVersion);
toStore.add( mutableEntity);
}
@SuppressWarnings("unchecked")
Entity<T>[] array = toStore.toArray(new Entity[]{});
getModification().storeObjects( array);
}
return true;
}
private void checkConsistency(Entity entity) throws EntityNotFoundException {
// this will also be checked by the server but we try to avoid
if ( entity instanceof SimpleEntity)
{
for ( ReferenceInfo info: ((SimpleEntity) entity).getReferenceInfo())
{
getClientFacade().getOperator().resolve( info.getId(), info.getType());
}
}
if ( entity instanceof Classifiable)
{
Date lastChanged = ((Classifiable) entity).getClassification().getType().getLastChanged();
if ( lastChanged != null)
{
}
}
}
private void setNewTimestamp( Entity dest, Entity persistant) {
if ( persistant instanceof ModifiableTimestamp)
{
Date version = ((ModifiableTimestamp)persistant).getLastChanged();
((ModifiableTimestamp)dest).setLastChanged(version);
}
}
public String getCommandoName()
{
if ( commandoName != null)
{
return commandoName;
}
boolean isNew = oldEntities == null;
Iterator<T> iterator = newEntities.iterator();
StringBuffer buf = new StringBuffer();
buf.append(isNew ? getString("new"): getString("edit") );
if ( iterator.hasNext())
{
RaplaType raplaType = iterator.next().getRaplaType();
buf.append(" " + getString(raplaType.getLocalName()));
}
return buf.toString();
}
} | 04900db4-clienttest | src/org/rapla/gui/internal/edit/SaveUndo.java | Java | gpl3 | 6,422 |
/*--------------------------------------------------------------------------*
| 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.internal.edit;
import java.util.ArrayList;
import org.rapla.entities.domain.Reservation;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.EditField;
import org.rapla.gui.internal.edit.fields.ClassificationField;
/****************************************************************
* This is the controller-class for the Resource-Edit-Panel *
****************************************************************/
class ReservationEditUI extends AbstractEditUI<Reservation> {
ClassificationField<Reservation> classificationField;
public ReservationEditUI(RaplaContext context) {
super(context);
ArrayList<EditField> fields = new ArrayList<EditField>();
classificationField = new ClassificationField<Reservation>(context);
fields.add( classificationField);
setFields(fields);
}
public void mapToObjects() throws RaplaException {
classificationField.mapTo( objectList);
if ( getName(objectList).length() == 0)
throw new RaplaException(getString("error.no_name"));
}
protected void mapFromObjects() throws RaplaException {
classificationField.mapFrom( objectList);
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/ReservationEditUI.java | Java | gpl3 | 2,191 |
/*--------------------------------------------------------------------------*
| 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.internal.edit;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.components.calendar.DateChangeEvent;
import org.rapla.components.calendar.DateChangeListener;
import org.rapla.components.calendar.RaplaCalendar;
import org.rapla.components.calendar.RaplaNumber;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.Annotatable;
import org.rapla.entities.Category;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeAnnotations;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.ConstraintIds;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.AnnotationEditExtension;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.edit.annotation.AnnotationEditUI;
import org.rapla.gui.internal.edit.fields.AbstractEditField;
import org.rapla.gui.internal.edit.fields.BooleanField;
import org.rapla.gui.internal.edit.fields.CategorySelectField;
import org.rapla.gui.internal.edit.fields.ListField;
import org.rapla.gui.internal.edit.fields.MultiLanguageField;
import org.rapla.gui.internal.edit.fields.TextField;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.EmptyLineBorder;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaWidget;
public class AttributeEdit extends RaplaGUIComponent
implements
RaplaWidget
{
RaplaListEdit<Attribute> listEdit;
DynamicType dt;
DefaultConstraints constraintPanel;
ArrayList<ChangeListener> listenerList = new ArrayList<ChangeListener>();
Listener listener = new Listener();
DefaultListModel model = new DefaultListModel();
boolean editKeys;
public AttributeEdit(RaplaContext context) throws RaplaException {
super( context);
constraintPanel = new DefaultConstraints(context);
listEdit = new RaplaListEdit<Attribute>( getI18n(), constraintPanel.getComponent(), listener );
listEdit.setListDimension( new Dimension( 200,220 ) );
constraintPanel.addChangeListener( listener );
listEdit.getComponent().setBorder( BorderFactory.createTitledBorder( new EmptyLineBorder(),getString("attributes")) );
setRender();
constraintPanel.setEditKeys( false );
}
@SuppressWarnings("unchecked")
private void setRender() {
listEdit.getList().setCellRenderer(new DefaultListCellRenderer() {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
Attribute a = (Attribute) value;
value = a.getName(getRaplaLocale().getLocale());
if (editKeys) {
value = "{" + a.getKey() + "} " + value;
}
value = (index + 1) +") " + value;
return super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
}
});
}
public RaplaWidget getConstraintPanel() {
return constraintPanel;
}
public void selectAttribute( Attribute attribute)
{
boolean shouldScroll = true;
listEdit.getList().setSelectedValue( attribute, shouldScroll);
}
class Listener implements ActionListener,ChangeListener {
public void actionPerformed(ActionEvent evt) {
int index = getSelectedIndex();
try {
if (evt.getActionCommand().equals("remove")) {
removeAttribute();
} else if (evt.getActionCommand().equals("new")) {
createAttribute();
} else if (evt.getActionCommand().equals("edit")) {
Attribute attribute = (Attribute) listEdit.getList().getSelectedValue();
constraintPanel.mapFrom( attribute );
} else if (evt.getActionCommand().equals("moveUp")) {
dt.exchangeAttributes(index, index -1);
updateModel(null);
} else if (evt.getActionCommand().equals("moveDown")) {
dt.exchangeAttributes(index, index + 1);
updateModel(null);
}
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
public void stateChanged(ChangeEvent e) {
try {
confirmEdits();
fireContentChanged();
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
}
public JComponent getComponent() {
return listEdit.getComponent();
}
public int getSelectedIndex() {
return listEdit.getList().getSelectedIndex();
}
public void setDynamicType(DynamicType dt) {
this.dt = dt;
updateModel(null);
}
@SuppressWarnings("unchecked")
private void updateModel(Attribute newSelectedItem) {
Attribute selectedItem = newSelectedItem != null ? newSelectedItem : listEdit.getSelectedValue();
model.clear();
Attribute[] attributes = dt.getAttributes();
for (int i = 0; i < attributes.length; i++ ) {
model.addElement( attributes[i] );
}
listEdit.getList().setModel(model);
if ( listEdit.getSelectedValue() != selectedItem )
listEdit.getList().setSelectedValue(selectedItem, true );
}
@SuppressWarnings("unchecked")
public void confirmEdits() throws RaplaException {
if ( getSelectedIndex() < 0 )
return;
Attribute attribute = listEdit.getSelectedValue();
constraintPanel.mapTo (attribute );
model.set( model.indexOf( attribute ), attribute );
}
public void setEditKeys(boolean editKeys) {
constraintPanel.setEditKeys(editKeys);
this.editKeys = editKeys;
}
private String createNewKey() {
Attribute[] atts = dt.getAttributes();
int max = 1;
for (int i=0;i<atts.length;i++) {
String key = atts[i].getKey();
if (key.length()>1
&& key.charAt(0) =='a'
&& Character.isDigit(key.charAt(1))
)
{
try {
int value = Integer.valueOf(key.substring(1)).intValue();
if (value >= max)
max = value + 1;
} catch (NumberFormatException ex) {
}
}
}
return "a" + (max);
}
void removeAttribute() {
List<Attribute> toRemove = new ArrayList<Attribute>();
for ( int index:listEdit.getList().getSelectedIndices())
{
Attribute att = dt.getAttributes() [index];
toRemove.add( att);
}
for (Attribute att:toRemove)
{
dt.removeAttribute(att);
}
updateModel(null);
}
void createAttribute() throws RaplaException {
confirmEdits();
AttributeType type = AttributeType.STRING;
Attribute att = getModification().newAttribute(type);
String language = getRaplaLocale().getLocale().getLanguage();
att.getName().setName(language, getString("attribute"));
att.setKey(createNewKey());
dt.addAttribute(att);
updateModel( att);
// int index = dt.getAttributes().length -1;
// listEdit.getList().setSelectedIndex( index );
constraintPanel.name.selectAll();
constraintPanel.name.requestFocus();
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(listener);
}
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(listener);
}
public ChangeListener[] getChangeListeners() {
return listenerList.toArray(new ChangeListener[]{});
}
protected void fireContentChanged() {
if (listenerList.size() == 0)
return;
ChangeEvent evt = new ChangeEvent(this);
ChangeListener[] listeners = getChangeListeners();
for (int i = 0;i<listeners.length; i++) {
listeners[i].stateChanged(evt);
}
}
}
class DefaultConstraints extends AbstractEditField
implements
ActionListener
,ChangeListener
{
JPanel panel = new JPanel();
JLabel nameLabel = new JLabel();
JLabel keyLabel = new JLabel();
JLabel typeLabel = new JLabel();
JLabel categoryLabel = new JLabel();
JLabel dynamicTypeLabel = new JLabel();
JLabel defaultLabel = new JLabel();
JLabel multiSelectLabel = new JLabel();
JLabel tabLabel = new JLabel();
AttributeType types[] = {
AttributeType.BOOLEAN
,AttributeType.STRING
,AttributeType.INT
,AttributeType.CATEGORY
,AttributeType.ALLOCATABLE
,AttributeType.DATE
};
String tabs[] = {
AttributeAnnotations.VALUE_EDIT_VIEW_MAIN
,AttributeAnnotations.VALUE_EDIT_VIEW_ADDITIONAL
,AttributeAnnotations.VALUE_EDIT_VIEW_NO_VIEW
};
boolean mapping = false;
MultiLanguageField name ;
TextField key;
JComboBox classSelect = new JComboBox();
ListField<DynamicType> dynamicTypeSelect;
CategorySelectField categorySelect;
CategorySelectField defaultSelectCategory;
TextField defaultSelectText;
BooleanField defaultSelectBoolean;
BooleanField multiSelect;
RaplaNumber defaultSelectNumber = new RaplaNumber(new Long(0),null,null, false);
RaplaCalendar defaultSelectDate ;
RaplaButton annotationButton = new RaplaButton(RaplaButton.DEFAULT);
JComboBox tabSelect = new JComboBox();
DialogUI dialog;
boolean emailPossible = false;
Category rootCategory;
AnnotationEditUI annotationEdit;
Collection<AnnotationEditExtension> annotationExtensions;
Attribute attribute;
DefaultConstraints(RaplaContext context) throws RaplaException{
super( context );
annotationExtensions = context.lookup(Container.class).lookupServicesFor(AnnotationEditExtension.ATTRIBUTE_ANNOTATION_EDIT);
annotationEdit = new AnnotationEditUI(context, annotationExtensions);
key = new TextField(context);
name = new MultiLanguageField(context);
Collection<DynamicType> typeList = new ArrayList<DynamicType>(Arrays.asList(getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE)));
typeList.addAll(Arrays.asList(getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON)));
dynamicTypeSelect = new ListField<DynamicType>(context,true );
dynamicTypeSelect.setVector( typeList );
rootCategory = getQuery().getSuperCategory();
categorySelect = new CategorySelectField(context,rootCategory);
categorySelect.setUseNull(false);
defaultSelectCategory = new CategorySelectField(context,rootCategory);
defaultSelectText = new TextField(context);
addCopyPaste( defaultSelectNumber.getNumberField());
//addCopyPaste( expectedRows.getNumberField());
//addCopyPaste( expectedColumns.getNumberField());
defaultSelectBoolean = new BooleanField(context);
defaultSelectDate = createRaplaCalendar();
defaultSelectDate.setNullValuePossible( true);
defaultSelectDate.setDate( null);
multiSelect = new BooleanField(context);
double fill = TableLayout.FILL;
double pre = TableLayout.PREFERRED;
panel.setLayout( new TableLayout( new double[][]
{{5, pre, 5, fill }, // Columns
{5, pre ,5, pre, 5, pre, 5, pre, 5, pre, 5, pre, 5,pre, 5, pre, 5}} // Rows
));
panel.add("1,1,l,f", nameLabel);
panel.add("3,1,f,f", name.getComponent() );
panel.add("1,3,l,f", keyLabel);
panel.add("3,3,f,f", key.getComponent() );
panel.add("1,5,l,f", typeLabel);
panel.add("3,5,l,f", classSelect);
// constraints
panel.add("1,7,l,t", categoryLabel);
panel.add("3,7,l,t", categorySelect.getComponent());
panel.add("1,7,l,t", dynamicTypeLabel);
panel.add("3,7,l,t", dynamicTypeSelect.getComponent());
panel.add("1,9,l,t", defaultLabel);
panel.add("3,9,l,t", defaultSelectCategory.getComponent());
panel.add("3,9,l,t", defaultSelectText.getComponent());
panel.add("3,9,l,t", defaultSelectBoolean.getComponent());
panel.add("3,9,l,t", defaultSelectDate);
panel.add("3,9,l,t", defaultSelectNumber);
panel.add("1,11,l,t", multiSelectLabel);
panel.add("3,11,l,t", multiSelect.getComponent());
panel.add("1,13,l,t", tabLabel);
panel.add("3,13,l,t", tabSelect);
panel.add("1,15,l,t", new JLabel("erweitert"));
panel.add("3,15,l,t", annotationButton);
annotationButton.setText(getString("edit"));
annotationButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
showAnnotationDialog();
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
});
setModel();
nameLabel.setText(getString("name") + ":");
keyLabel.setText(getString("key") +" *"+ ":");
typeLabel.setText(getString("type") + ":");
categoryLabel.setText(getString("root") + ":");
dynamicTypeLabel.setText(getString("root") + ":");
tabLabel.setText(getString("edit-view") + ":");
multiSelectLabel.setText("Multiselect:");
defaultLabel.setText(getString("default") +":");
categorySelect.addChangeListener ( this );
categorySelect.addChangeListener( new ChangeListener() {
public void stateChanged(ChangeEvent e)
{
final Category rootCategory = categorySelect.getValue();
defaultSelectCategory.setRootCategory( rootCategory );
defaultSelectCategory.setValue( null);
defaultSelectCategory.getComponent().setEnabled( rootCategory != null);
}
}
);
name.addChangeListener ( this );
key.addChangeListener ( this );
classSelect.addActionListener ( this );
tabSelect.addActionListener( this);
defaultSelectCategory.addChangeListener( this );
defaultSelectText.addChangeListener( this );
defaultSelectBoolean.addChangeListener( this );
defaultSelectNumber.addChangeListener( this );
defaultSelectDate.addDateChangeListener( new DateChangeListener() {
public void dateChanged(DateChangeEvent evt)
{
stateChanged(null);
}
});
}
@SuppressWarnings("unchecked")
private void setModel() {
DefaultComboBoxModel model = new DefaultComboBoxModel();
for ( int i = 0; i < types.length; i++ ) {
model.addElement(getString("type." + types[i]));
}
classSelect.setModel( model );
model = new DefaultComboBoxModel();
for ( int i = 0; i < tabs.length; i++ ) {
model.addElement(getString(tabs[i]));
}
tabSelect.setModel( model );
}
public void setEditKeys(boolean editKeys) {
keyLabel.setVisible( editKeys );
key.getComponent().setVisible( editKeys );
}
public JComponent getComponent() {
return panel;
}
private void clearValues() {
categorySelect.setValue(null);
defaultSelectCategory.setValue( null);
defaultSelectText.setValue("");
defaultSelectBoolean.setValue( null);
defaultSelectNumber.setNumber(null);
defaultSelectDate.setDate(null);
multiSelect.setValue( Boolean.FALSE);
}
public void mapFrom(Attribute attribute) throws RaplaException {
clearValues();
try {
mapping = true;
this.attribute = attribute;
clearValues();
String classificationType = attribute.getDynamicType().getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
emailPossible = classificationType != null && (classificationType.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON) || classificationType.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE));
name.setValue( attribute.getName());
key.setValue( attribute.getKey());
final AttributeType attributeType = attribute.getType();
classSelect.setSelectedItem(getString("type." + attributeType));
if (attributeType.equals(AttributeType.CATEGORY)) {
final Category rootCategory = (Category)attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY);
categorySelect.setValue( rootCategory );
defaultSelectCategory.setRootCategory( rootCategory);
defaultSelectCategory.setValue( (Category)attribute.convertValue(attribute.defaultValue()));
defaultSelectCategory.getComponent().setEnabled( rootCategory != null);
}
else if (attributeType.equals(AttributeType.ALLOCATABLE)) {
final DynamicType rootCategory = (DynamicType)attribute.getConstraint(ConstraintIds.KEY_DYNAMIC_TYPE);
dynamicTypeSelect.setValue( rootCategory );
}
else if (attributeType.equals(AttributeType.STRING))
{
defaultSelectText.setValue( (String)attribute.defaultValue());
}
else if (attributeType.equals(AttributeType.BOOLEAN))
{
defaultSelectBoolean.setValue( (Boolean)attribute.defaultValue());
}
else if (attributeType.equals(AttributeType.INT))
{
defaultSelectNumber.setNumber( (Number)attribute.defaultValue());
}
else if (attributeType.equals(AttributeType.DATE))
{
defaultSelectDate.setDate( (Date)attribute.defaultValue());
}
if (attributeType.equals(AttributeType.CATEGORY) || attributeType.equals(AttributeType.ALLOCATABLE)) {
Boolean multiSelectValue = (Boolean) attribute.getConstraint(ConstraintIds.KEY_MULTI_SELECT) ;
multiSelect.setValue( multiSelectValue != null ? multiSelectValue: Boolean.FALSE );
}
String selectedTab = attribute.getAnnotation(AttributeAnnotations.KEY_EDIT_VIEW, AttributeAnnotations.VALUE_EDIT_VIEW_MAIN);
tabSelect.setSelectedItem(getString(selectedTab));
update();
} finally {
mapping = false;
}
}
public void mapTo(Attribute attribute) throws RaplaException {
attribute.getName().setTo( name.getValue());
attribute.setKey( key.getValue());
AttributeType type = types[classSelect.getSelectedIndex()];
attribute.setType( type );
if ( type.equals(AttributeType.CATEGORY)) {
Object defaultValue = defaultSelectCategory.getValue();
Object rootCategory = categorySelect.getValue();
if ( rootCategory == null)
{
rootCategory = this.rootCategory;
defaultValue = null;
}
attribute.setConstraint(ConstraintIds.KEY_ROOT_CATEGORY, rootCategory );
attribute.setDefaultValue( defaultValue);
} else {
attribute.setConstraint(ConstraintIds.KEY_ROOT_CATEGORY, null);
}
if ( type.equals(AttributeType.ALLOCATABLE)) {
Object rootType = dynamicTypeSelect.getValue();
// if ( rootType == null)
// {
// rootType = this.rootCategory;
// }
attribute.setConstraint(ConstraintIds.KEY_DYNAMIC_TYPE, rootType );
attribute.setDefaultValue( null);
} else {
attribute.setConstraint(ConstraintIds.KEY_DYNAMIC_TYPE, null);
}
if ( type.equals(AttributeType.ALLOCATABLE) || type.equals(AttributeType.CATEGORY))
{
Boolean value = multiSelect.getValue();
attribute.setConstraint(ConstraintIds.KEY_MULTI_SELECT, value);
}
else
{
attribute.setConstraint(ConstraintIds.KEY_MULTI_SELECT, null);
}
if ( type.equals(AttributeType.BOOLEAN)) {
final Object defaultValue = defaultSelectBoolean.getValue();
attribute.setDefaultValue( defaultValue);
}
if ( type.equals(AttributeType.INT)) {
final Object defaultValue = defaultSelectNumber.getNumber();
attribute.setDefaultValue( defaultValue);
}
if ( type.equals(AttributeType.DATE)) {
final Object defaultValue = defaultSelectDate.getDate();
attribute.setDefaultValue( defaultValue);
}
List<Annotatable> asList = Arrays.asList((Annotatable)attribute);
annotationEdit.mapTo(asList);
String selectedTab = tabs[tabSelect.getSelectedIndex()];
if ( selectedTab != null && !selectedTab.equals(AttributeAnnotations.VALUE_EDIT_VIEW_MAIN)) {
attribute.setAnnotation(AttributeAnnotations.KEY_EDIT_VIEW, selectedTab);
} else {
attribute.setAnnotation(AttributeAnnotations.KEY_EDIT_VIEW, null);
}
}
private void update() throws RaplaException {
AttributeType type = types[classSelect.getSelectedIndex()];
List<Annotatable> asList = Arrays.asList((Annotatable)attribute);
annotationEdit.setObjects( asList);
final boolean categoryVisible = type.equals(AttributeType.CATEGORY);
final boolean allocatableVisible = type.equals(AttributeType.ALLOCATABLE);
final boolean textVisible = type.equals(AttributeType.STRING);
final boolean booleanVisible = type.equals(AttributeType.BOOLEAN);
final boolean numberVisible = type.equals(AttributeType.INT);
final boolean dateVisible = type.equals(AttributeType.DATE);
categoryLabel.setVisible( categoryVisible );
categorySelect.getComponent().setVisible( categoryVisible );
dynamicTypeLabel.setVisible( allocatableVisible);
dynamicTypeSelect.getComponent().setVisible( allocatableVisible);
defaultLabel.setVisible( !allocatableVisible);
defaultSelectCategory.getComponent().setVisible( categoryVisible);
defaultSelectText.getComponent().setVisible( textVisible);
defaultSelectBoolean.getComponent().setVisible( booleanVisible);
defaultSelectNumber.setVisible( numberVisible);
defaultSelectDate.setVisible( dateVisible);
multiSelectLabel.setVisible( categoryVisible || allocatableVisible);
multiSelect.getComponent().setVisible( categoryVisible || allocatableVisible);
}
private void showAnnotationDialog() throws RaplaException
{
RaplaContext context = getContext();
boolean modal = false;
if (dialog != null)
{
dialog.close();
}
dialog = DialogUI.create(context
,getComponent()
,modal
,annotationEdit.getComponent()
,new String[] { getString("close")});
dialog.getButton(0).setAction( new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
fireContentChanged();
dialog.close();
}
});
dialog.setTitle(getString("select"));
dialog.start();
}
public void actionPerformed(ActionEvent evt) {
if (mapping)
return;
if ( evt.getSource() == classSelect) {
clearValues();
AttributeType newType = types[classSelect.getSelectedIndex()];
if (newType.equals(AttributeType.CATEGORY)) {
categorySelect.setValue( rootCategory );
}
}
fireContentChanged();
try {
update();
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
public void stateChanged(ChangeEvent e) {
if (mapping)
return;
fireContentChanged();
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/AttributeEdit.java | Java | gpl3 | 26,676 |
package org.rapla.gui.internal.edit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import org.rapla.components.util.undo.CommandUndo;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaType;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class DeleteUndo<T extends Entity<T>> extends RaplaComponent implements CommandUndo<RaplaException> {
// FIXME Delete of categories in multiple levels can cause the lower levels not to be deleted if it contains categories higher in rank but same hierarchy that are also deleted
// FIXME Needs a check last changed
private List<T> entities;
Map<Category,Category> removedCategories = new LinkedHashMap<Category, Category>();
public DeleteUndo(RaplaContext context,Collection<T> entities)
{
super(context);
this.entities = new ArrayList<T>();
for ( T entity: entities)
{
// Hack for 1.6 compiler compatibility
if ( ((Object)entity.getRaplaType()) == Category.TYPE)
{
this.entities.add(entity);
}
else
{
this.entities.add(entity.clone());
}
}
}
public boolean execute() throws RaplaException
{
Collection<Category> toStore = new ArrayList<Category>();
List<T> toRemove = new ArrayList<T>();
for ( T entity: entities)
{
// Hack for 1.6 compiler compatibility
if ( ((Object)entity.getRaplaType()) == Category.TYPE)
{
Entity casted = entity;
// to avoid compiler error
Category category = (Category) casted;
Category parent = category.getParent();
Category parentClone = null;
if ( toStore.contains( parent))
{
for ( Category cat: toStore)
{
if ( cat.equals(parent))
{
parentClone = parent;
}
}
}
else
{
parentClone = getModification().edit( parent );
toStore.add( parentClone);
}
if ( parentClone != null)
{
removedCategories.put( category, parent);
parentClone.removeCategory( parentClone.findCategory( category));
}
}
else
{
toRemove.add( entity);
}
}
Entity<?>[] arrayStore = toStore.toArray( Category.ENTITY_ARRAY);
@SuppressWarnings("unchecked")
Entity<T>[] arrayRemove = toRemove.toArray(new Entity[]{});
getModification().storeAndRemove(arrayStore,arrayRemove);
return true;
}
public boolean undo() throws RaplaException
{
List<Entity<T>> toStore = new ArrayList<Entity<T>>();
for ( T entity: entities)
{
Entity<T> mutableEntity = entity.clone();
toStore.add( mutableEntity);
}
Collection<Category> categoriesToStore2 = new LinkedHashSet<Category>();
for ( Category category: removedCategories.keySet())
{
Category parent = removedCategories.get( category);
Category parentClone = null;
if ( categoriesToStore2.contains( parent))
{
for ( Category cat: categoriesToStore2)
{
if ( cat.equals(parent))
{
parentClone = parent;
}
}
}
else
{
parentClone = getModification().edit( parent );
Entity castedParent1 = parentClone;
@SuppressWarnings({ "cast", "unchecked" })
Entity<T> castedParent = (Entity<T>) castedParent1;
toStore.add( castedParent);
categoriesToStore2.add( parentClone);
}
if ( parentClone != null)
{
parentClone.addCategory( category);
}
}
// Todo generate undo for category store
@SuppressWarnings("unchecked")
Entity<T>[] array = toStore.toArray(new Entity[]{});
getModification().storeObjects( array);
return true;
}
public String getCommandoName()
{
Iterator<T> iterator = entities.iterator();
StringBuffer buf = new StringBuffer();
buf.append(getString("delete") );
if ( iterator.hasNext())
{
RaplaType raplaType = iterator.next().getRaplaType();
buf.append( " " + getString(raplaType.getLocalName()));
}
return buf.toString();
}
} | 04900db4-clienttest | src/org/rapla/gui/internal/edit/DeleteUndo.java | Java | gpl3 | 4,444 |
/*--------------------------------------------------------------------------*
| 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.internal.edit;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.ItemSelectable;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.util.Assert;
import org.rapla.entities.Category;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.ClassificationFilterRule;
import org.rapla.entities.dynamictype.ConstraintIds;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.facade.ClassifiableFilter;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.EditField;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.common.NamedListCellRenderer;
import org.rapla.gui.internal.edit.fields.AbstractEditField;
import org.rapla.gui.internal.edit.fields.AllocatableSelectField;
import org.rapla.gui.internal.edit.fields.BooleanField;
import org.rapla.gui.internal.edit.fields.CategoryListField;
import org.rapla.gui.internal.edit.fields.CategorySelectField;
import org.rapla.gui.internal.edit.fields.DateField;
import org.rapla.gui.internal.edit.fields.LongField;
import org.rapla.gui.internal.edit.fields.SetGetField;
import org.rapla.gui.internal.edit.fields.TextField;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaWidget;
public class ClassifiableFilterEdit extends RaplaGUIComponent
implements
ActionListener
,RaplaWidget
{
JPanel content = new JPanel();
JScrollPane scrollPane;
JCheckBox[] checkBoxes;
ClassificationEdit[] filterEdit;
DynamicType[] types;
boolean isResourceSelection;
ArrayList<ChangeListener> listenerList = new ArrayList<ChangeListener>();
final RaplaButton everythingButton = new RaplaButton(RaplaButton.SMALL);
final RaplaButton nothingButton = new RaplaButton(RaplaButton.SMALL);
public ClassifiableFilterEdit(RaplaContext context, boolean isResourceSelection) {
super( context);
content.setBackground(UIManager.getColor("List.background"));
scrollPane = new JScrollPane(content
,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
);
scrollPane.setPreferredSize(new Dimension(590,400));
this.isResourceSelection = isResourceSelection;
content.setBorder( BorderFactory.createEmptyBorder(5,5,5,5));
everythingButton.setText( getString("select_everything") );
everythingButton.setIcon( getIcon("icon.all-checked"));
nothingButton.setText(getString("select_nothing"));
nothingButton.setIcon( getIcon("icon.all-unchecked"));
}
public JComponent getClassificationTitle(String classificationType) {
JLabel title = new JLabel( classificationType );
title.setFont( title.getFont().deriveFont( Font.BOLD ));
title.setText( getString( classificationType) + ":" );
return title;
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(listener);
}
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(listener);
}
public ChangeListener[] getChangeListeners() {
return listenerList.toArray(new ChangeListener[]{});
}
protected void fireFilterChanged() {
if (listenerList.size() == 0)
return;
ChangeEvent evt = new ChangeEvent(this);
ChangeListener[] listeners = getChangeListeners();
for (int i = 0;i<listeners.length; i++) {
listeners[i].stateChanged(evt);
}
everythingButton.setEnabled( true);
nothingButton.setEnabled( true);
}
public void setTypes(DynamicType[] types) {
this.types = types;
content.removeAll();
TableLayout tableLayout = new TableLayout();
content.setLayout(tableLayout);
tableLayout.insertColumn(0,TableLayout.PREFERRED);
tableLayout.insertColumn(1,10);
tableLayout.insertColumn(2,TableLayout.FILL);
tableLayout.insertRow(0, TableLayout.PREFERRED);
if (checkBoxes != null) {
for (int i=0;i<checkBoxes.length;i++) {
checkBoxes[i].removeActionListener(this);
}
}
int defaultRowSize = 35;
scrollPane.setPreferredSize(new Dimension(590,Math.max(200,Math.min(600, 70+ defaultRowSize + types.length * 33 + (isResourceSelection ? 20:0)))));
checkBoxes = new JCheckBox[types.length];
filterEdit = new ClassificationEdit[types.length];
String lastClassificationType= null;
int row = 0;
for (int i=0;i<types.length;i++) {
String classificationType = types[i].getAnnotation( DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
if ( !classificationType.equals( lastClassificationType)) {
tableLayout.insertRow( row, 2);
row ++;
lastClassificationType = classificationType;
tableLayout.insertRow( row, TableLayout.MINIMUM);
content.add( getClassificationTitle( classificationType),"0,"+ row +",1," + row) ;
if ( i== 0 )
{
everythingButton.setSelected( true);
ActionListener resetButtonListener = new ActionListener() {
private boolean enabled = true;
public void actionPerformed(ActionEvent evt) {
try
{
if ( !enabled)
{
return;
}
enabled = false;
JButton source = (JButton)evt.getSource();
boolean isEverything = source == everythingButton;
source.setSelected( isEverything ? true : false);
boolean deselectAllIfFilterIsNull = !isEverything;
mapFromIntern( null, deselectAllIfFilterIsNull);
fireFilterChanged();
source.setEnabled( false);
JButton opposite = isEverything ? nothingButton : everythingButton;
opposite.setEnabled( true);
}
catch (RaplaException ex)
{
showException(ex, getComponent());
}
finally
{
enabled = true;
}
}
};
everythingButton.addActionListener( resetButtonListener);
nothingButton.addActionListener( resetButtonListener);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground( content.getBackground());
buttonPanel.add( everythingButton);
buttonPanel.add( nothingButton);
content.add( buttonPanel,"2,"+ row +",r,c");
}
row ++;
tableLayout.insertRow( row, 4);
row ++;
tableLayout.insertRow( row, 2);
content.add( new JPanel() , "0," + row + ",2," + row );
row ++;
}
tableLayout.insertRow( row, 3);
tableLayout.insertRow( row + 1, TableLayout.MINIMUM);
tableLayout.insertRow( row + 2, TableLayout.MINIMUM);
tableLayout.insertRow( row + 3, 3);
tableLayout.insertRow( row + 4, 2);
checkBoxes[i] = new JCheckBox(getName(types[i]));
final JCheckBox checkBox = checkBoxes[i];
checkBox.setBorder( BorderFactory.createEmptyBorder(0,10,0,0));
checkBox.setOpaque( false );
checkBox.addActionListener(this);
checkBox.setSelected( true );
content.add( checkBox , "0," + (row + 1) + ",l,t");
filterEdit[i] = new ClassificationEdit(getContext(), scrollPane);
final ClassificationEdit edit = filterEdit[i];
content.add( edit.getNewComponent() , "2," + (row + 1));
content.add( edit.getRulesComponent() , "0," + (row + 2) + ",2,"+ (row + 2));
content.add( new JPanel() , "0," + (row + 4) + ",2," + (row + 4));
edit.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
everythingButton.setEnabled( true);
nothingButton.setEnabled( true);
fireFilterChanged();
}
}
);
row += 5;
}
}
private ClassificationFilter findFilter(DynamicType type,ClassificationFilter[] filters) {
for (int i=0;i<filters.length;i++)
if (filters[i].getType().equals(type))
return filters[i];
return null;
}
public void setFilter(ClassifiableFilter filter) throws RaplaException {
List<DynamicType> list = new ArrayList<DynamicType>();
if ( !isResourceSelection) {
list.addAll( Arrays.asList( getQuery().getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION )));
}
else
{
list.addAll( Arrays.asList( getQuery().getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE )));
list.addAll( Arrays.asList( getQuery().getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON )));
}
setTypes( list.toArray( DynamicType.DYNAMICTYPE_ARRAY));
mapFromIntern(filter, false);
}
private void mapFromIntern(ClassifiableFilter classifiableFilter, boolean deselectAllIfFilterIsNull) throws RaplaException {
final ClassificationFilter[] filters;
if ( classifiableFilter != null)
{
filters = isResourceSelection ? classifiableFilter.getAllocatableFilter() : classifiableFilter.getReservationFilter();
}
else
{
filters = new ClassificationFilter[] {};
}
boolean nothingSelectable = false;
for (int i=0;i<types.length;i++) {
final DynamicType dynamicType = types[i];
ClassificationFilter filter = findFilter(dynamicType, filters);
final boolean fillDefault;
if ( classifiableFilter != null)
{
fillDefault = isResourceSelection ? classifiableFilter.isDefaultResourceTypes() : classifiableFilter.isDefaultEventTypes();
}
else
{
fillDefault = !deselectAllIfFilterIsNull;
}
if ( filter == null && fillDefault)
{
filter = dynamicType.newClassificationFilter();
}
checkBoxes[i].setSelected( filter != null);
if ( filter != null)
{
nothingSelectable = true;
}
filterEdit[i].mapFrom(filter);
}
if ( classifiableFilter != null)
{
everythingButton.setEnabled( ! (isResourceSelection ? classifiableFilter.isDefaultResourceTypes() :classifiableFilter.isDefaultEventTypes()));
}
nothingButton.setEnabled( nothingSelectable);
scrollPane.revalidate();
scrollPane.repaint();
}
public ClassificationFilter[] getFilters() {
ArrayList<ClassificationFilter> list = new ArrayList<ClassificationFilter>();
for (int i=0; i< filterEdit.length; i++) {
ClassificationFilter filter = filterEdit[i].getFilter();
if (filter != null) {
list.add(filter);
}
}
return list.toArray(new ClassificationFilter[] {});
}
public void actionPerformed(ActionEvent evt) {
for (int i=0;i<checkBoxes.length;i++) {
if (checkBoxes[i] == evt.getSource()) {
if (checkBoxes[i].isSelected())
filterEdit[i].mapFrom(types[i].newClassificationFilter());
else
filterEdit[i].mapFrom(null);
// activate the i. filter
}
}
content.revalidate();
content.repaint();
fireFilterChanged();
everythingButton.setEnabled( true);
nothingButton.setEnabled( true);
}
public JComponent getComponent() {
return scrollPane;
}
}
class ClassificationEdit extends RaplaGUIComponent implements ItemListener {
JPanel ruleListPanel = new JPanel();
JPanel newPanel = new JPanel();
List<RuleComponent> ruleList = new ArrayList<RuleComponent>();
JComboBox attributeSelector;
JButton newLabel = new JButton();
DynamicType type;
ArrayList<ChangeListener> listenerList = new ArrayList<ChangeListener>();
JScrollPane pane;
ClassificationEdit(RaplaContext sm,JScrollPane pane){
super(sm );
this.pane = pane;
ruleListPanel.setOpaque( false );
ruleListPanel.setLayout(new BoxLayout(ruleListPanel,BoxLayout.Y_AXIS));
newPanel.setOpaque( false );
newPanel.setLayout(new TableLayout(new double[][] {{TableLayout.PREFERRED},{TableLayout.PREFERRED}}));
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(listener);
}
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(listener);
}
public ChangeListener[] getChangeListeners() {
return listenerList.toArray(new ChangeListener[]{});
}
protected void fireFilterChanged() {
if (listenerList.size() == 0)
return;
ChangeEvent evt = new ChangeEvent(this);
ChangeListener[] listeners = getChangeListeners();
for (int i = 0;i<listeners.length; i++) {
listeners[i].stateChanged(evt);
}
}
public JComponent getRulesComponent() {
return ruleListPanel;
}
public JComponent getNewComponent() {
return newPanel;
}
@SuppressWarnings("unchecked")
public void mapFrom(ClassificationFilter filter) {
getRulesComponent().removeAll();
ruleList.clear();
getNewComponent().removeAll();
if ( filter == null) {
type = null;
return;
}
this.type = filter.getType();
Attribute[] attributes = type.getAttributes();
if (attributes.length == 0 )
return;
if (attributeSelector != null)
attributeSelector.removeItemListener(this);
JComboBox jComboBox = new JComboBox(attributes);
attributeSelector = jComboBox;
attributeSelector.setRenderer(new NamedListCellRenderer(getI18n().getLocale()) {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
if (value == null) {
setText(getString("new_rule"));
return this;
} else {
return super.getListCellRendererComponent(list, value,index,isSelected,cellHasFocus);
}
}
});
attributeSelector.addItemListener(this);
newPanel.add(newLabel,"0,0,f,c");
newPanel.add(attributeSelector,"0,0,f,c");
newLabel.setText(getString("new_rule"));
newLabel.setVisible(false);
attributeSelector.setSelectedItem(null);
Iterator<? extends ClassificationFilterRule> it = filter.ruleIterator();
while (it.hasNext()) {
ClassificationFilterRule rule = it.next();
RuleComponent ruleComponent = new RuleComponent( rule);
ruleList.add( ruleComponent );
}
update();
}
public void update() {
ruleListPanel.removeAll();
int i=0;
for (Iterator<RuleComponent> it = ruleList.iterator();it.hasNext();) {
RuleComponent rule = it.next();
ruleListPanel.add( rule);
rule.setAndVisible( i > 0);
i++;
}
ruleListPanel.revalidate();
ruleListPanel.repaint();
}
public void itemStateChanged(ItemEvent e) {
Object item = e.getItem();
if ( e.getStateChange() != ItemEvent.SELECTED)
{
return;
}
Attribute att = (Attribute)item;
if (att != null) {
RuleComponent ruleComponent = getComponent(att);
final RuleRow row;
if (ruleComponent == null) {
ruleComponent = new RuleComponent( att);
ruleList.add( ruleComponent );
}
row = ruleComponent.addOr();
final RuleComponent comp = ruleComponent;
update();
// invokeLater prevents a deadlock in jdk <=1.3
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
attributeSelector.setSelectedIndex(-1);
comp.scrollRowVisible(row);
}
});
fireFilterChanged();
}
}
public ClassificationFilter getFilter() {
if ( type == null )
return null;
ClassificationFilter filter = type.newClassificationFilter();
int i=0;
for (Iterator<RuleComponent> it = ruleList.iterator();it.hasNext();) {
RuleComponent ruleComponent = it.next();
Attribute attribute = ruleComponent.getAttribute();
List<RuleRow> ruleRows = ruleComponent.getRuleRows();
int size = ruleRows.size();
Object[][] conditions = new Object[size][2];
for (int j=0;j<size;j++) {
RuleRow ruleRow = ruleRows.get(j);
conditions[j][0] = ruleRow.getOperatorValue();
conditions[j][1] = ruleRow.getValue();
}
filter.setRule(i++ , attribute, conditions);
}
return filter;
}
private RuleComponent getComponent(Attribute attribute) {
for (Iterator<RuleComponent> it = ruleList.iterator();it.hasNext();) {
RuleComponent c2 = it.next();
if (attribute.equals(c2.getAttribute())) {
return c2;
}
}
return null;
}
private void deleteRule(Component ruleComponent) {
ruleList.remove( ruleComponent );
update();
}
class RuleComponent extends JPanel {
private static final long serialVersionUID = 1L;
Attribute attribute;
private final Listener listener = new Listener();
List<RuleRow> ruleRows = new ArrayList<RuleRow>();
List<RaplaButton> deleteButtons = new ArrayList<RaplaButton>();
boolean isAndVisible;
JLabel and;
RuleComponent(Attribute attribute) {
Border outer = BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(5,20,0,3)
,BorderFactory.createEtchedBorder()
);
this.setBorder(BorderFactory.createCompoundBorder(
outer
,BorderFactory.createEmptyBorder(2,3,2,3)
));
this.setOpaque( false );
this.attribute = attribute;
}
RuleComponent(ClassificationFilterRule rule){
this( rule.getAttribute());
Assert.notNull(attribute);
Object[] ruleValues = rule.getValues();
String[] operators = rule.getOperators();
for (int i=0;i<ruleValues.length;i++) {
RuleRow row = createRow(operators[i], ruleValues[i]);
ruleRows.add(row);
}
rebuild();
}
public Attribute getAttribute() {
return attribute;
}
public List<RuleRow> getRuleRows() {
return ruleRows;
}
private RuleRow addOr() {
RuleRow row = createRow(null,null);
ruleRows.add(row);
rebuild();
return row;
}
protected void scrollRowVisible(RuleRow row) {
Component ruleComponent = row.ruleLabel;
if ( ruleComponent == null || ruleComponent.getParent() == null)
{
ruleComponent = row.field.getComponent();
}
if ( ruleComponent != null)
{
Point location1 = ruleComponent.getLocation();
Point location2 = getLocation();
Point location3 = ruleListPanel.getLocation();
int y = location1.y + location2.y + location3.y ;
int height2 = (int)ruleComponent.getPreferredSize().getHeight()+20;
Rectangle aRect = new Rectangle(location1.x,y , 10, height2);
JViewport viewport = pane.getViewport();
viewport.scrollRectToVisible( aRect);
}
}
public void setAndVisible( boolean andVisible) {
this.isAndVisible = andVisible;
if ( and!= null)
{
if ( andVisible) {
and.setText( getString("and"));
} else {
and.setText("");
}
}
}
private void rebuild() {
this.removeAll();
TableLayout layout = new TableLayout();
layout.insertColumn(0,TableLayout.PREFERRED);
layout.insertColumn(1,10);
layout.insertColumn(2,TableLayout.PREFERRED);
layout.insertColumn(3,5);
layout.insertColumn(4,TableLayout.PREFERRED);
layout.insertColumn(5,5);
layout.insertColumn(6,TableLayout.FILL);
this.setLayout(layout);
int row =0;
layout.insertRow(row,TableLayout.PREFERRED);
and = new JLabel();
// and.setAlignmentX( and.LEFT_ALIGNMENT);
this.add("0,"+row +",6,"+ row + ",l,c", and);
if ( isAndVisible) {
and.setText( getString("and"));
} else {
and.setText("");
}
row ++;
int size = ruleRows.size();
for (int i=0;i<size;i++) {
RuleRow ruleRow = ruleRows.get(i);
RaplaButton deleteButton = deleteButtons.get(i);
layout.insertRow(row,TableLayout.PREFERRED);
this.add("0," + row + ",l,c", deleteButton);
if (i == 0)
this.add("2," + row + ",l,c", ruleRow.ruleLabel);
else
this.add("2," + row + ",r,c", new JLabel(getString("or")));
this.add("4," + row + ",l,c", ruleRow.operatorComponent);
this.add("6," + row + ",f,c", ruleRow.field.getComponent());
row ++;
if (i<size -1) {
layout.insertRow(row , 2);
row++;
}
}
revalidate();
repaint();
}
private RuleRow createRow(String operator,Object ruleValue) {
RaplaButton deleteButton = new RaplaButton(RaplaButton.SMALL);
deleteButton.setToolTipText(getString("delete"));
deleteButton.setIcon(getIcon("icon.delete"));
deleteButton.addActionListener(listener);
deleteButtons.add(deleteButton);
RuleRow row = new RuleRow(attribute,operator,ruleValue);
return row;
}
class Listener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
int index = deleteButtons.indexOf(evt.getSource());
if (ruleRows.size() <= 1) {
deleteRule(RuleComponent.this);
} else {
ruleRows.remove(index);
deleteButtons.remove(index);
rebuild();
}
fireFilterChanged();
}
}
}
class RuleRow implements ChangeListener, ItemListener{
Object ruleValue;
JLabel ruleLabel;
JComponent operatorComponent;
AbstractEditField field;
Attribute attribute;
public void stateChanged(ChangeEvent e) {
fireFilterChanged();
}
public void itemStateChanged(ItemEvent e) {
fireFilterChanged();
}
RuleRow(Attribute attribute,String operator,Object ruleValue) {
this.attribute = attribute;
this.ruleValue = ruleValue;
ruleLabel = new JLabel();
ruleLabel.setText(attribute.getName().getName(getI18n().getLang()));
createField( attribute );
// we can cast here, because we tested in createField
@SuppressWarnings("unchecked")
SetGetField<Object> setGetField = (SetGetField<Object>)field;
setGetField.setValue(ruleValue);
field.addChangeListener( this);
setOperatorValue(operator);
if ( operatorComponent instanceof ItemSelectable)
{
((ItemSelectable)operatorComponent).addItemListener(this);
}
}
public String getOperatorValue() {
AttributeType type = attribute.getType();
if (type.equals(AttributeType.ALLOCATABLE) || type.equals(AttributeType.CATEGORY) || type.equals(AttributeType.BOOLEAN) )
return "is";
if (type.equals(AttributeType.STRING)) {
int index = ((JComboBox)operatorComponent).getSelectedIndex();
if (index == 0)
return "contains";
if (index == 1)
return "starts";
}
if (type.equals(AttributeType.DATE) || type.equals(AttributeType.INT)) {
int index = ((JComboBox)operatorComponent).getSelectedIndex();
if (index == 0)
return "<";
if (index == 1)
return "=";
if (index == 2)
return ">";
if (index == 3)
return "<>";
if (index == 4)
return "<=";
if (index == 5)
return ">=";
}
Assert.notNull(field,"Unknown AttributeType" + type);
return null;
}
private void setOperatorValue(String operator) {
AttributeType type = attribute.getType();
if ((type.equals(AttributeType.DATE) || type.equals(AttributeType.INT)))
{
if (operator == null)
operator = "<";
JComboBox box = (JComboBox)operatorComponent;
if (operator.equals("<"))
box.setSelectedIndex(0);
if (operator.equals("=") || operator.equals("is"))
box.setSelectedIndex(1);
if (operator.equals(">"))
box.setSelectedIndex(2);
if (operator.equals("<>"))
box.setSelectedIndex(3);
if (operator.equals("<="))
box.setSelectedIndex(4);
if (operator.equals(">="))
box.setSelectedIndex(5);
}
}
private EditField createField(Attribute attribute) {
operatorComponent = null;
AttributeType type = attribute.getType();
// used for static testing of the field type
@SuppressWarnings("unused")
SetGetField test;
RaplaContext context = getContext();
if (type.equals(AttributeType.ALLOCATABLE))
{
operatorComponent = new JLabel("");
DynamicType dynamicTypeConstraint = (DynamicType)attribute.getConstraint( ConstraintIds.KEY_DYNAMIC_TYPE);
AllocatableSelectField newField = new AllocatableSelectField(context, dynamicTypeConstraint);
field = newField;
test = newField;
}
else if (type.equals(AttributeType.CATEGORY))
{
operatorComponent = new JLabel("");
Category rootCategory = (Category)attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY);
if (rootCategory.getDepth() > 2) {
Category defaultCategory = (Category) attribute.defaultValue();
CategorySelectField newField = new CategorySelectField(context,rootCategory,defaultCategory);
field = newField;
test = newField;
} else {
CategoryListField newField = new CategoryListField(context,rootCategory);
field = newField;
test = newField;
}
}
else if (type.equals(AttributeType.STRING))
{
TextField newField = new TextField(context);
field = newField;
test = newField;
@SuppressWarnings("unchecked")
DefaultComboBoxModel model = new DefaultComboBoxModel(new String[] {
getString("filter.contains")
,getString("filter.starts")
});
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(model);
operatorComponent = jComboBox;
}
else if (type.equals(AttributeType.INT))
{
LongField newField = new LongField(context);
field = newField;
test = newField;
@SuppressWarnings("unchecked")
DefaultComboBoxModel model = new DefaultComboBoxModel(new String[] {
getString("filter.is_smaller_than")
,getString("filter.equals")
,getString("filter.is_greater_than")
,getString("filter.not_equals")
,getString("filter.smaller_or_equals")
,getString("filter.greater_or_equals")
});
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(model);
operatorComponent = jComboBox;
}
else if (type.equals(AttributeType.DATE))
{
DateField newField = new DateField(context);
field = newField;
test = newField;
@SuppressWarnings("unchecked")
DefaultComboBoxModel model = new DefaultComboBoxModel(new String[] {
getString("filter.earlier_than")
,getString("filter.equals")
,getString("filter.later_than")
,getString("filter.not_equals")
});
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(model);
operatorComponent = jComboBox; }
else if (type.equals(AttributeType.BOOLEAN))
{
operatorComponent = new JLabel("");
BooleanField newField = new BooleanField(context);
field = newField;
test = newField;
ruleValue = new Boolean(false);
}
Assert.notNull(field,"Unknown AttributeType");
return field;
}
public Object getValue() {
ruleValue = ((SetGetField<?>)field).getValue();
return ruleValue;
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/ClassifiableFilterEdit.java | Java | gpl3 | 34,412 |
/*--------------------------------------------------------------------------*
| 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.gui.internal.edit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collections;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JComponent;
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.components.util.Assert;
import org.rapla.components.util.Tools;
import org.rapla.entities.IllegalAnnotationException;
import org.rapla.entities.MultiLanguageName;
import org.rapla.entities.UniqueKeyException;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeAnnotations;
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.EditComponent;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.edit.fields.MultiLanguageField;
import org.rapla.gui.internal.edit.fields.TextField;
import org.rapla.gui.toolkit.DialogUI;
/****************************************************************
* This is the controller-class for the DynamicType-Edit-Panel *
****************************************************************/
class DynamicTypeEditUI extends RaplaGUIComponent
implements
EditComponent<DynamicType>
{
public static String WARNING_SHOWED = DynamicTypeEditUI.class.getName() + "/Warning";
DynamicType dynamicType;
JPanel editPanel = new JPanel();
JPanel annotationPanel = new JPanel();
JLabel nameLabel = new JLabel();
MultiLanguageField name;
JLabel elementKeyLabel = new JLabel();
TextField elementKey;
AttributeEdit attributeEdit;
JLabel annotationLabel = new JLabel();
JLabel annotationDescription = new JLabel();
JTextField annotationText = new JTextField();
JTextField annotationTreeText = new JTextField();
JComboBox colorChooser;
JLabel locationLabel = new JLabel("location");
JComboBox locationChooser;
JLabel conflictLabel = new JLabel("conflict creation");
JComboBox conflictChooser;
boolean isResourceType;
boolean isEventType;
public DynamicTypeEditUI(RaplaContext context) throws RaplaException {
super(context);
{
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(new String[] {getString("color.automated"),getString("color.manual"),getString("color.no")});
colorChooser = jComboBox;
}
{
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(new String[] {"yes","no"});
locationChooser = jComboBox;
}
{
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(new String[] {DynamicTypeAnnotations.VALUE_CONFLICTS_ALWAYS,DynamicTypeAnnotations.VALUE_CONFLICTS_NONE,DynamicTypeAnnotations.VALUE_CONFLICTS_WITH_OTHER_TYPES});
conflictChooser = jComboBox;
}
name = new MultiLanguageField(context,"name");
elementKey = new TextField(context,"elementKey");
attributeEdit = new AttributeEdit(context);
nameLabel.setText(getString("dynamictype.name") + ":");
elementKeyLabel.setText(getString("elementkey") + ":");
attributeEdit.setEditKeys( true );
annotationPanel.setVisible( true);
double PRE = TableLayout.PREFERRED;
double[][] sizes = new double[][] {
{5,PRE,5,TableLayout.FILL,5}
,{PRE,5,PRE,5,PRE,5,PRE,5,TableLayout.FILL,5,PRE}
};
TableLayout tableLayout = new TableLayout(sizes);
editPanel.setLayout(tableLayout);
editPanel.add(nameLabel,"1,2");
editPanel.add(name.getComponent(),"3,2");
editPanel.add(elementKeyLabel,"1,4");
editPanel.add(elementKey.getComponent(),"3,4");
editPanel.add(attributeEdit.getComponent(),"1,6,3,6");
// #FIXM Should be replaced by generic solution
tableLayout.insertRow(7,5);
tableLayout.insertRow(8,PRE);
editPanel.add(annotationPanel,"1,8,3,8");
annotationPanel.setLayout(new TableLayout(new double[][] {
{PRE,5,TableLayout.FILL}
,{PRE,5,PRE,5,PRE, 5, PRE,5, PRE,5,PRE}
}));
addCopyPaste( annotationText);
addCopyPaste(annotationTreeText);
annotationPanel.add(annotationLabel,"0,0");
annotationPanel.add(annotationText ,"2,0");
annotationPanel.add(annotationDescription,"2,2");
annotationPanel.add(annotationTreeText ,"2,4");
annotationPanel.add(new JLabel(getString("color")),"0,6");
annotationPanel.add(colorChooser,"2,6");
annotationPanel.add(locationLabel,"0,8");
annotationPanel.add(locationChooser,"2,8");
annotationPanel.add(conflictLabel,"0,10");
annotationPanel.add(conflictChooser,"2,10");
annotationLabel.setText(getString("dynamictype.annotation.nameformat") + ":");
annotationDescription.setText(getString("dynamictype.annotation.nameformat.description"));
float newSize = (float) (annotationDescription.getFont().getSize() * 0.8);
annotationDescription.setFont(annotationDescription.getFont().deriveFont( newSize));
attributeEdit.addChangeListener( new ChangeListener() {
public void stateChanged( ChangeEvent e )
{
updateAnnotations();
}
});
colorChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if ( dynamicType.getAttribute("color") != null || colorChooser.getSelectedIndex() != 1)
{
return;
}
DialogUI ui = DialogUI.create(getContext(), getMainComponent(), true, getString("color.manual"), getString("attribute_color_dialog"), new String[]{getString("yes"),getString("no")});
ui.start();
if (ui.getSelectedIndex() == 0)
{
Attribute colorAttribute = getModification().newAttribute(AttributeType.STRING);
colorAttribute.setKey( "color");
colorAttribute.getName().setName(getLocale().getLanguage(), getString("color"));
colorAttribute.setAnnotation(AttributeAnnotations.KEY_EDIT_VIEW, AttributeAnnotations.VALUE_EDIT_VIEW_NO_VIEW);
dynamicType.addAttribute( colorAttribute);
attributeEdit.setDynamicType(dynamicType);
}
else
{
colorChooser.setSelectedIndex(2);
}
} catch (RaplaException ex) {
showException(ex, getMainComponent());
}
}
});
/*
annotationText.addFocusListener( new FocusAdapter() {
public void focusLost( FocusEvent e )
{
try
{
setAnnotations();
}
catch ( RaplaException ex )
{
showException( ex, getComponent());
}
}
});
*/
}
public JComponent getComponent() {
return editPanel;
}
public void mapToObjects() throws RaplaException {
MultiLanguageName newName = name.getValue();
dynamicType.getName().setTo( newName);
dynamicType.setKey(elementKey.getValue());
attributeEdit.confirmEdits();
validate();
setAnnotations();
}
private void setAnnotations() throws RaplaException
{
try {
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT, annotationText.getText().trim());
String planningText = annotationTreeText.getText().trim();
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT_PLANNING, planningText.length() > 0 ? planningText : null);
} catch (IllegalAnnotationException ex) {
throw ex;
}
String color= null;
switch (colorChooser.getSelectedIndex())
{
case 0:color = DynamicTypeAnnotations.VALUE_COLORS_AUTOMATED;break;
case 1:color = DynamicTypeAnnotations.VALUE_COLORS_COLOR_ATTRIBUTE;break;
case 2:color = DynamicTypeAnnotations.VALUE_COLORS_DISABLED;break;
}
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS, color);
if ( isResourceType)
{
String location = null;
switch (locationChooser.getSelectedIndex())
{
case 0:location = "true";break;
case 1:location = "false";break;
}
if ( location == null || location.equals( "false"))
{
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_LOCATION, null);
}
else
{
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_LOCATION, location);
}
}
if ( isEventType)
{
String conflicts = null;
switch (conflictChooser.getSelectedIndex())
{
case 0:conflicts = DynamicTypeAnnotations.VALUE_CONFLICTS_ALWAYS;break;
case 1:conflicts = DynamicTypeAnnotations.VALUE_CONFLICTS_NONE;break;
case 2:conflicts = DynamicTypeAnnotations.VALUE_CONFLICTS_WITH_OTHER_TYPES;break;
}
if ( conflicts == null || conflicts.equals( DynamicTypeAnnotations.VALUE_CONFLICTS_ALWAYS))
{
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_CONFLICTS, null);
}
else
{
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_CONFLICTS, conflicts);
}
}
}
public List<DynamicType> getObjects() {
List<DynamicType> types = Collections.singletonList(dynamicType);
return types;
}
public void setObjects(List<DynamicType> o) {
dynamicType = o.get(0);
mapFromObjects();
}
public void mapFromObjects()
{
name.setValue( dynamicType.getName());
elementKey.setValue( dynamicType.getKey());
attributeEdit.setDynamicType(dynamicType);
String classificationType = dynamicType.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
isEventType = classificationType != null && classificationType.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
isResourceType = classificationType != null && classificationType.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE);
conflictLabel.setVisible( isEventType);
conflictChooser.setVisible( isEventType);
locationLabel.setVisible( isResourceType);
locationChooser.setVisible( isResourceType);
updateAnnotations();
}
private void updateAnnotations() {
annotationText.setText( dynamicType.getAnnotation( DynamicTypeAnnotations.KEY_NAME_FORMAT ) );
annotationTreeText.setText( dynamicType.getAnnotation( DynamicTypeAnnotations.KEY_NAME_FORMAT_PLANNING,"" ) );
{
String annotation = dynamicType.getAnnotation( DynamicTypeAnnotations.KEY_COLORS);
if (annotation == null)
{
annotation = dynamicType.getAttribute("color") != null ? DynamicTypeAnnotations.VALUE_COLORS_COLOR_ATTRIBUTE: DynamicTypeAnnotations.VALUE_COLORS_AUTOMATED;
}
if ( annotation.equals(DynamicTypeAnnotations.VALUE_COLORS_AUTOMATED))
{
colorChooser.setSelectedIndex(0);
}
else if ( annotation.equals( DynamicTypeAnnotations.VALUE_COLORS_COLOR_ATTRIBUTE))
{
colorChooser.setSelectedIndex(1);
}
else if ( annotation.equals( DynamicTypeAnnotations.VALUE_COLORS_DISABLED))
{
colorChooser.setSelectedIndex(2);
}
}
if ( isEventType)
{
String annotation = dynamicType.getAnnotation( DynamicTypeAnnotations.KEY_CONFLICTS);
if (annotation == null)
{
annotation = DynamicTypeAnnotations.VALUE_CONFLICTS_ALWAYS;
}
if ( annotation.equals( DynamicTypeAnnotations.VALUE_CONFLICTS_ALWAYS))
{
conflictChooser.setSelectedIndex(0);
}
else if ( annotation.equals(DynamicTypeAnnotations.VALUE_CONFLICTS_NONE))
{
conflictChooser.setSelectedIndex(1);
}
else if ( annotation.equals( DynamicTypeAnnotations.VALUE_CONFLICTS_WITH_OTHER_TYPES))
{
conflictChooser.setSelectedIndex(2);
}
}
if ( isResourceType)
{
String annotation = dynamicType.getAnnotation( DynamicTypeAnnotations.KEY_LOCATION);
if (annotation == null)
{
annotation = "false";
}
if ( annotation.equals( "true"))
{
locationChooser.setSelectedIndex(0);
}
else
{
locationChooser.setSelectedIndex(1);
}
}
}
private void validate() throws RaplaException {
Assert.notNull(dynamicType);
if ( getName( dynamicType ).length() == 0)
throw new RaplaException(getString("error.no_name"));
if (dynamicType.getKey().equals("")) {
throw new RaplaException(getI18n().format("error.no_key",""));
}
checkKey(dynamicType.getKey());
Attribute[] attributes = dynamicType.getAttributes();
for (int i=0;i<attributes.length;i++) {
String key = attributes[i].getKey();
if (key == null || key.trim().equals(""))
throw new RaplaException(getI18n().format("error.no_key","(" + i + ")"));
checkKey(key);
for (int j=i+1;j<attributes.length;j++) {
if ((key.equals(attributes[j].getKey()))) {
throw new UniqueKeyException(getI18n().format("error.not_unique",key));
}
}
}
}
private void checkKey(String key) throws RaplaException {
if (key.length() ==0)
throw new RaplaException(getString("error.no_key"));
if (!Tools.isKey(key) || key.length()>50)
{
Object[] param = new Object[3];
param[0] = key;
param[1] = "'-', '_'";
param[2] = "'_'";
throw new RaplaException(getI18n().format("error.invalid_key", param));
}
}
} | 04900db4-clienttest | src/org/rapla/gui/internal/edit/DynamicTypeEditUI.java | Java | gpl3 | 15,409 |
package org.rapla.gui.internal.edit;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.gui.toolkit.RaplaWidget;
final class RaplaTreeEdit implements
RaplaWidget
{
int oldIndex = -1;
JPanel mainPanel = new JPanel();
JLabel nothingSelectedLabel = new JLabel();
JScrollPane scrollPane;
Color selectionBackground = UIManager.getColor("List.selectionBackground");
Color background = UIManager.getColor("List.background");
JPanel jointPanel = new JPanel() {
private static final long serialVersionUID = 1L;
int xa[] = new int[4];
int ya[] = new int[4];
public void paint(Graphics g) {
super.paint(g);
TreePath selectedPath = tree.getPathForRow( getSelectedIndex() );
Rectangle rect = tree.getPathBounds( selectedPath );
Dimension dim = getSize();
if (rect != null) {
int y = rect.y -scrollPane.getViewport().getViewPosition().y;
int y1= Math.min(dim.height,Math.max(0, y) + scrollPane.getLocation().y);
int y2= Math.min(dim.height,Math.max(0,y + rect.height) + scrollPane.getLocation().y);
xa[0]=0;
ya[0]=y1;
xa[1]=dim.width;
ya[1]=0;
xa[2]=dim.width;
ya[2]=dim.height;
xa[3]=0;
ya[3]=y2;
g.setColor(selectionBackground);
g.fillPolygon(xa,ya,4);
g.setColor(background);
g.drawLine(xa[0],ya[0],xa[1],ya[1]);
g.drawLine(xa[3],ya[3],xa[2],ya[2]);
}
}
};
JPanel content = new JPanel();
JPanel detailContainer = new JPanel();
JPanel editPanel = new JPanel();
JTree tree = new JTree() {
private static final long serialVersionUID = 1L;
public void setModel(TreeModel model) {
if ( this.treeModel!= null)
{
treeModel.removeTreeModelListener( listener);
}
super.setModel( model );
model.addTreeModelListener(listener);
}
};
CardLayout cardLayout = new CardLayout();
private Listener listener = new Listener();
private ActionListener callback;
I18nBundle i18n;
public RaplaTreeEdit(I18nBundle i18n,JComponent detailContent,ActionListener callback) {
this.i18n = i18n;
this.callback = callback;
mainPanel.setLayout(new TableLayout(new double[][] {
{TableLayout.PREFERRED,TableLayout.PREFERRED,TableLayout.FILL}
,{TableLayout.FILL}
}));
jointPanel.setPreferredSize(new Dimension(20,50));
mainPanel.add(content,"0,0");
mainPanel.add(jointPanel,"1,0");
mainPanel.add(editPanel,"2,0");
editPanel.setLayout(cardLayout);
editPanel.add(nothingSelectedLabel, "0");
editPanel.add(detailContainer, "1");
content.setLayout(new BorderLayout());
scrollPane = new JScrollPane(tree
,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(310,80));
content.add(scrollPane, BorderLayout.CENTER);
detailContainer.setLayout(new BorderLayout());
editPanel.setBorder(BorderFactory.createRaisedBevelBorder());
detailContainer.add(detailContent, BorderLayout.CENTER);
scrollPane.getViewport().addChangeListener(listener);
tree.addMouseListener(listener);
tree.addTreeSelectionListener(listener);
modelUpdate();
nothingSelectedLabel.setHorizontalAlignment(JLabel.CENTER);
nothingSelectedLabel.setText(i18n.getString("nothing_selected"));
}
public JComponent getComponent() {
return mainPanel;
}
public JTree getTree() {
return tree;
}
public void setListDimension(Dimension d) {
scrollPane.setPreferredSize(d);
}
public int getSelectedIndex() {
return tree.getMinSelectionRow();
}
public void select(int index) {
tree.setSelectionRow(index);
if (index >=0) {
TreePath selectedPath = tree.getPathForRow(index);
tree.makeVisible( selectedPath );
}
}
private void modelUpdate() {
jointPanel.repaint();
}
public Object getSelectedValue() {
TreePath treePath = tree.getSelectionPath();
if (treePath == null)
return null;
return ((DefaultMutableTreeNode)treePath.getLastPathComponent()).getUserObject();
}
private void editSelectedEntry() {
Object selected = getSelectedValue();
if (selected == null) {
cardLayout.first(editPanel);
return;
} else {
cardLayout.last(editPanel);
callback.actionPerformed(new ActionEvent(this
,ActionEvent.ACTION_PERFORMED
,"edit"
)
);
}
}
class Listener extends MouseAdapter implements TreeSelectionListener,ChangeListener, TreeModelListener {
public void valueChanged(TreeSelectionEvent evt) {
int index = getSelectedIndex();
if (index != oldIndex) {
oldIndex = index;
editSelectedEntry();
modelUpdate();
}
}
public void stateChanged(ChangeEvent evt) {
if (evt.getSource() == scrollPane.getViewport()) {
jointPanel.repaint();
}
}
public void treeNodesChanged(TreeModelEvent e) {
modelUpdate();
}
public void treeNodesInserted(TreeModelEvent e) {
}
public void treeNodesRemoved(TreeModelEvent e) {
}
public void treeStructureChanged(TreeModelEvent e) {
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/RaplaTreeEdit.java | Java | gpl3 | 7,140 |
/*--------------------------------------------------------------------------*
| 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.internal.edit;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.entities.Named;
import org.rapla.entities.NamedComparator;
import org.rapla.entities.configuration.Preferences;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.DefaultPluginOption;
import org.rapla.gui.EditComponent;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.PluginOptionPanel;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.toolkit.RaplaTree;
public class PreferencesEditUI extends RaplaGUIComponent
implements
EditComponent<Preferences>
,ChangeListener
{
private JSplitPane content = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
protected TitledBorder selectionBorder;
protected RaplaTree jPanelSelection = new RaplaTree();
protected JPanel jPanelContainer = new JPanel();
protected JPanel container = new JPanel();
JLabel messages = new JLabel();
JPanel defaultPanel = new JPanel();
OptionPanel lastOptionPanel;
Preferences preferences;
/** called during initialization to create the info component */
public PreferencesEditUI(RaplaContext context) {
super( context);
jPanelContainer.setLayout(new BorderLayout());
jPanelContainer.add(messages,BorderLayout.SOUTH);
messages.setForeground( Color.red);
Border emptyLineBorder = new Border() {
Insets insets = new Insets(2,0,2,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(0,1, c.getWidth(), 1);
g.drawLine(0,c.getHeight()-2, c.getWidth(), c.getHeight()-2);
}
public Insets getBorderInsets( Component c )
{
return insets;
}
public boolean isBorderOpaque()
{
return true;
}
};
content.setBorder( emptyLineBorder);
jPanelContainer.add(content,BorderLayout.CENTER);
jPanelSelection.getTree().setCellRenderer(getTreeFactory().createRenderer());
jPanelSelection.setToolTipRenderer(getTreeFactory().createTreeToolTipRenderer());
container.setPreferredSize( new Dimension(700,550));
content.setLeftComponent(jPanelSelection);
content.setRightComponent(container);
content.setDividerLocation(260);
Border emptyBorder=BorderFactory.createEmptyBorder(4,4,4,4);
selectionBorder = BorderFactory.createTitledBorder(emptyBorder, getString("selection") + ":");
jPanelSelection.setBorder(selectionBorder);
content.setResizeWeight(0.4);
jPanelSelection.addChangeListener(this);
}
final private TreeFactory getTreeFactory() {
return getService(TreeFactory.class);
}
protected OptionPanel[] getPluginOptions() throws RaplaException {
Collection<PluginOptionPanel> panelList = getContainer().lookupServicesFor( RaplaClientExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION);
List<OptionPanel> optionList = new ArrayList<OptionPanel>();
List<PluginDescriptor<ClientServiceContainer>> pluginList = getService( ClientServiceContainer.CLIENT_PLUGIN_LIST);
for (final PluginDescriptor<ClientServiceContainer> plugin:pluginList) {
OptionPanel optionPanel = find(panelList, plugin);
if ( optionPanel == null ) {
optionPanel = new DefaultPluginOption(getContext()) {
@SuppressWarnings("unchecked")
public Class<? extends PluginDescriptor<ClientServiceContainer>> getPluginClass() {
return (Class<? extends PluginDescriptor<ClientServiceContainer>>) plugin.getClass();
}
@Override
public String getName(Locale locale) {
String string = plugin.getClass().getSimpleName();
return string;
}
};
}
optionList.add( optionPanel );
}
sort( optionList);
return optionList.toArray(new OptionPanel[] {});
}
private OptionPanel find(Collection<PluginOptionPanel> panels,
PluginDescriptor<?> plugin)
{
for (PluginOptionPanel panel: panels)
{
Class<? extends PluginDescriptor<?>> pluginClass = panel.getPluginClass();
if (plugin.getClass().equals( pluginClass))
{
return panel;
}
}
return null;
}
public void sort(List<OptionPanel> list) {
Collections.sort( list, new NamedComparator<OptionPanel>(getRaplaLocale().getLocale()));
}
public OptionPanel[] getUserOptions() throws RaplaException {
List<OptionPanel> optionList = new ArrayList<OptionPanel>(getContainer().lookupServicesFor( RaplaClientExtensionPoints.USER_OPTION_PANEL_EXTENSION ));
sort( optionList);
return optionList.toArray(new OptionPanel[] {});
}
public OptionPanel[] getAdminOptions() throws RaplaException {
List<OptionPanel> optionList = new ArrayList<OptionPanel>(getContainer().lookupServicesFor( RaplaClientExtensionPoints.SYSTEM_OPTION_PANEL_EXTENSION ));
sort( optionList);
return optionList.toArray(new OptionPanel[] {});
}
protected JComponent createInfoComponent() {
JPanel panel = new JPanel();
return panel;
}
private void setOptionPanel(OptionPanel optionPanel) throws Exception {
String title = getString("nothing_selected");
JComponent comp = defaultPanel;
if ( optionPanel != null) {
title = optionPanel.getName( getRaplaLocale().getLocale());
comp = optionPanel.getComponent();
}
TitledBorder titledBorder = new TitledBorder(BorderFactory.createEmptyBorder(4,4,4,4),title);
container.removeAll();
container.setLayout(new BorderLayout());
container.setBorder(titledBorder);
container.add( comp,BorderLayout.CENTER);
container.revalidate();
container.repaint();
}
public String getTitle() {
return getString("options");
}
/** maps all fields back to the current object.*/
public void mapToObjects() throws RaplaException {
if ( lastOptionPanel != null)
lastOptionPanel.commit();
}
public void setObjects(List<Preferences> o) throws RaplaException {
this.preferences = o.get(0);
if ( preferences.getOwner() == null) {
messages.setText(getString("restart_options"));
}
TreeFactory f = getTreeFactory();
DefaultMutableTreeNode root = new DefaultMutableTreeNode("");
if ( preferences.getOwner() != null) {
Named[] element = getUserOptions();
for (int i=0; i< element.length; i++) {
root.add( f.newNamedNode( element[i]));
}
} else {
{
Named[] element = getAdminOptions();
DefaultMutableTreeNode adminRoot = new DefaultMutableTreeNode("admin-options");
for (int i=0; i< element.length; i++) {
adminRoot.add( f.newNamedNode( element[i]));
}
root.add( adminRoot );
}
{
Named[] element = getPluginOptions();
DefaultMutableTreeNode pluginRoot = new DefaultMutableTreeNode("plugins");
for (int i=0; i< element.length; i++) {
pluginRoot.add( f.newNamedNode( element[i]));
}
root.add( pluginRoot );
}
}
DefaultTreeModel treeModel = new DefaultTreeModel(root);
jPanelSelection.exchangeTreeModel(treeModel);
}
public List<Preferences> getObjects() {
return Collections.singletonList(preferences);
}
public void stateChanged(ChangeEvent evt) {
try {
if ( lastOptionPanel != null)
lastOptionPanel.commit();
OptionPanel optionPanel = null;
if ( getSelectedElement() instanceof OptionPanel ) {
optionPanel = (OptionPanel) getSelectedElement();
if ( optionPanel != null) {
optionPanel.setPreferences( preferences );
optionPanel.show();
}
}
lastOptionPanel = optionPanel;
setOptionPanel( lastOptionPanel );
} catch (Exception ex) {
showException(ex,getComponent());
}
}
public Object getSelectedElement() {
return jPanelSelection.getSelectedElement();
}
public JComponent getComponent() {
return jPanelContainer;
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/PreferencesEditUI.java | Java | gpl3 | 10,652 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.reservation;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.components.util.undo.CommandUndo;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeAnnotations;
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.entities.dynamictype.internal.ClassificationImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.EditField;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.common.NamedListCellRenderer;
import org.rapla.gui.internal.edit.ClassificationEditUI;
import org.rapla.gui.internal.edit.fields.SetGetField;
import org.rapla.gui.toolkit.EmptyLineBorder;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaListComboBox;
import org.rapla.gui.toolkit.RaplaWidget;
/**
Gui for editing the {@link Classification} of a reservation. Same as
{@link org.rapla.gui.internal.edit.ClassificationEditUI}. It will only layout the
field with a {@link java.awt.FlowLayout}.
*/
public class ReservationInfoEdit extends RaplaGUIComponent
implements
RaplaWidget
,ActionListener
{
JPanel content = new JPanel();
MyClassificationEditUI editUI;
private Classification classification;
private Classification lastClassification = null;
private Classifiable classifiable;
private CommandHistory commandHistory;
ArrayList<ChangeListener> listenerList = new ArrayList<ChangeListener>();
ArrayList<DetailListener> detailListenerList = new ArrayList<DetailListener>();
RaplaListComboBox typeSelector;
RaplaButton tabSelector = new RaplaButton();
boolean isMainViewSelected = true;
private boolean internalUpdate = false;
public ReservationInfoEdit(RaplaContext sm, CommandHistory commandHistory)
{
super( sm);
typeSelector = new RaplaListComboBox( sm );
this.commandHistory = commandHistory;
editUI = new MyClassificationEditUI(sm);
}
public JComponent getComponent() {
return content;
}
public void requestFocus() {
editUI.requestFocus();
}
private boolean hasSecondTab(Classification classification) {
Attribute[] atts = classification.getAttributes();
for ( int i=0; i < atts.length; i++ ) {
String view = atts[i].getAnnotation(AttributeAnnotations.KEY_EDIT_VIEW,AttributeAnnotations.VALUE_EDIT_VIEW_MAIN);
if ( view.equals(AttributeAnnotations.VALUE_EDIT_VIEW_ADDITIONAL)) {
return true;
}
}
return false;
}
public void setReservation(Classifiable classifiable) throws RaplaException {
content.removeAll();
this.classifiable = classifiable;
classification = classifiable.getClassification();
lastClassification = classification;
DynamicType[] types = getQuery().getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
DynamicType dynamicType = classification.getType();
RaplaListComboBox jComboBox = new RaplaListComboBox( getContext() , types );
typeSelector = jComboBox;
typeSelector.setEnabled( types.length > 1);
typeSelector.setSelectedItem(dynamicType);
setRenderer();
typeSelector.addActionListener( this );
content.setLayout( new BorderLayout());
JPanel header = new JPanel();
header.setLayout( null );
header.add( typeSelector );
Border border = new EmptyLineBorder();
header.setBorder( BorderFactory.createTitledBorder( border, getString("reservation_type") +":"));
Dimension dim = typeSelector.getPreferredSize();
typeSelector.setBounds(135,0, dim.width,dim.height);
tabSelector.setText(getString("additional-view"));
tabSelector.addActionListener( this );
Dimension dim2 = tabSelector.getPreferredSize();
tabSelector.setBounds(145 + dim.width ,0,dim2.width,dim2.height);
header.add( tabSelector );
header.setPreferredSize( new Dimension(600, Math.max(dim2.height, dim.height)));
content.add( header,BorderLayout.NORTH);
content.add( editUI.getComponent(),BorderLayout.CENTER);
tabSelector.setVisible( hasSecondTab( classification ) || !isMainViewSelected);
editUI.setObjects( Collections.singletonList(classification ));
editUI.getComponent().validate();
updateHeight();
content.validate();
}
@SuppressWarnings("unchecked")
private void setRenderer() {
typeSelector.setRenderer(new NamedListCellRenderer(getI18n().getLocale()));
}
/** registers new ChangeListener for this component.
* An ChangeEvent will be fired to every registered ChangeListener
* when the info changes.
* @see javax.swing.event.ChangeListener
* @see javax.swing.event.ChangeEvent
*/
public void addChangeListener(ChangeListener listener) {
listenerList.add(listener);
}
/** removes a listener from this component.*/
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(listener);
}
public ChangeListener[] getChangeListeners() {
return listenerList.toArray(new ChangeListener[]{});
}
public void addDetailListener(DetailListener listener) {
detailListenerList.add(listener);
}
/** removes a listener from this component.*/
public void removeDetailListener(DetailListener listener) {
detailListenerList.remove(listener);
}
public DetailListener[] getDetailListeners() {
return detailListenerList.toArray(new DetailListener[]{});
}
protected void fireDetailChanged() {
DetailListener[] listeners = getDetailListeners();
for (int i = 0;i<listeners.length; i++) {
listeners[i].detailChanged();
}
}
public interface DetailListener {
void detailChanged();
}
protected void fireInfoChanged() {
if (listenerList.size() == 0)
return;
ChangeEvent evt = new ChangeEvent(this);
ChangeListener[] listeners = getChangeListeners();
for (int i = 0;i<listeners.length; i++) {
listeners[i].stateChanged(evt);
}
}
// The DynamicType has changed
public void actionPerformed(ActionEvent event) {
try {
Object source = event.getSource();
if (source == typeSelector ) {
if (internalUpdate) return;
DynamicType oldDynamicType = lastClassification.getType();
DynamicType newDynamicType = (DynamicType) typeSelector.getSelectedItem();
Classification oldClassification = (Classification) ((ClassificationImpl) lastClassification).clone();
Classification newClassification = (Classification) ((ClassificationImpl) newDynamicType.newClassification(classification)).clone();
UndoReservationTypeChange command = new UndoReservationTypeChange(oldClassification, newClassification, oldDynamicType, newDynamicType);
commandHistory.storeAndExecute(command);
lastClassification = newClassification;
}
if (source == tabSelector ) {
isMainViewSelected = !isMainViewSelected;
fireDetailChanged();
editUI.layout();
tabSelector.setText( isMainViewSelected ?
getString("additional-view")
:getString("appointments")
);
tabSelector.setIcon( isMainViewSelected ?
null
: getIcon("icon.list")
);
}
} catch (RaplaException ex) {
showException(ex, content);
}
}
private void updateHeight()
{
int newHeight = editUI.getHeight();
editUI.getComponent().setPreferredSize(new Dimension(600,newHeight));
}
class MyClassificationEditUI extends ClassificationEditUI {
int height = 0;
public MyClassificationEditUI(RaplaContext sm) {
super(sm);
}
public int getHeight()
{
return height;
}
protected void layout() {
editPanel.removeAll();
editPanel.setLayout( null );
if ( !isMainViewSelected ) {
super.layout();
return;
}
/*
FlowLayout layout = new FlowLayout();
layout.setAlignment(FlowLayout.LEFT);
layout.setHgap(10);
layout.setVgap(2);
editPanel.setLayout(layout);
for (int i=0;i<fields.length;i++) {
String tabview = getAttribute( i ).getAnnotation(AttributeAnnotations.KEY_EDIT_VIEW, AttributeAnnotations.VALUE_MAIN_VIEW);
JPanel fieldPanel = new JPanel();
fieldPanel.setLayout( new BorderLayout());
fieldPanel.add(new JLabel(fields[i].getName() + ": "),BorderLayout.WEST);
fieldPanel.add(fields[i].getComponent(),BorderLayout.CENTER);
if ( tabview.equals("main-view") || !isMainViewSelected ) {
editPanel.add(fieldPanel);
}
}
*/
TableLayout layout = new TableLayout();
layout.insertColumn(0, 5);
layout.insertColumn(1,TableLayout.PREFERRED);
layout.insertColumn(2,TableLayout.PREFERRED);
layout.insertColumn(3, 10);
layout.insertColumn(4,TableLayout.PREFERRED);
layout.insertColumn(5,TableLayout.PREFERRED);
layout.insertColumn(6,TableLayout.FULL);
int col= 1;
int row = 0;
layout.insertRow( row, 8);
row ++;
layout.insertRow( row, TableLayout.PREFERRED);
editPanel.setLayout(layout);
height = 10;
int maxCompHeightInRow = 0;
for (int i=0;i<fields.size();i++) {
EditField field = fields.get(i);
String tabview = getAttribute( i ).getAnnotation(AttributeAnnotations.KEY_EDIT_VIEW, AttributeAnnotations.VALUE_EDIT_VIEW_MAIN);
if ( !tabview.equals("main-view") ) {
continue;
}
editPanel.add(new JLabel(getFieldName(field) + ": "),col + "," + row +",l,c");
col ++;
editPanel.add(field.getComponent(), col + "," + row +",f,c");
int compHeight = (int)field.getComponent().getPreferredSize().getHeight();
compHeight = Math.max(25, compHeight);
// first row
maxCompHeightInRow = Math.max(maxCompHeightInRow ,compHeight);
col ++;
col ++;
if ( col >= layout.getNumColumn())
{
col = 1;
if ( i < fields.size() -1)
{
row ++;
layout.insertRow( row, 5);
height +=5;
row ++;
layout.insertRow( row, TableLayout.PREFERRED);
height += maxCompHeightInRow;
maxCompHeightInRow = 0;
}
}
}
height += maxCompHeightInRow;
}
public void requestFocus() {
if (fields.size()>0)
fields.get(0).getComponent().requestFocus();
}
public void stateChanged(ChangeEvent evt) {
try {
SetGetField<?> editField = (SetGetField<?>) evt.getSource();
String keyName = getKey(editField);
Object oldValue = getAttValue(keyName); //this.classification.getValue(keyName);
mapTo( editField );
Object newValue = getAttValue(keyName);
UndoClassificationChange classificationChange = new UndoClassificationChange(oldValue, newValue, keyName);
if (oldValue != newValue && (oldValue == null || newValue == null || !oldValue.equals(newValue))) {
commandHistory.storeAndExecute(classificationChange);
}
} catch (RaplaException ex) {
showException(ex, this.getComponent());
}
}
private Object getAttValue(String keyName)
{
Set<Object> uniqueAttValues = getUniqueAttValues(keyName);
if ( uniqueAttValues.size() > 0)
{
return uniqueAttValues.iterator().next();
}
return null;
}
/**
* This class collects any information of changes done to all fields at the top of the edit view.
* This is where undo/redo for all fields at the top of the edit view
* is realized.
* @author Jens Fritz
*
*/
//Erstellt von Dominik Krickl-Vorreiter
public class UndoClassificationChange implements CommandUndo<RaplaException> {
private final Object oldValue;
private final Object newValue;
private final String keyName;
public UndoClassificationChange(Object oldValue, Object newValue, String fieldName) {
this.oldValue = oldValue;
this.newValue = newValue;
this.keyName = fieldName;
}
public boolean execute() throws RaplaException {
return mapValue(newValue);
}
public boolean undo() throws RaplaException {
return mapValue(oldValue);
}
protected boolean mapValue(Object valueToSet) throws RaplaException {
Object attValue = getAttValue(keyName);
if (attValue != valueToSet && (attValue == null || valueToSet == null || !attValue.equals(valueToSet))) {
SetGetField<?> editField = (SetGetField<?>) getEditField();
if (editField == null)
throw new RaplaException("Field with key " + keyName + " not found!");
setAttValue(keyName, valueToSet);
mapFrom( editField);
}
fireInfoChanged();
return true;
}
protected EditField getEditField() {
EditField editField = null;
for (EditField field: editUI.fields) {
if (getKey(field).equals(keyName)) {
editField = field;
break;
}
}
return editField;
}
public String getCommandoName()
{
EditField editField = getEditField();
String fieldName;
if ( editField != null)
{
fieldName = getFieldName(editField);
}
else
{
fieldName = getString("attribute");
}
return getString("change") + " " + fieldName;
}
}
}
public boolean isMainView() {
return isMainViewSelected;
}
/**
* This class collects any information of changes done to the reservation type checkbox.
* This is where undo/redo for the reservatoin type-selection at the top of the edit view
* is realized
* @author Jens Fritz
*
*/
//Erstellt von Matthias Both
public class UndoReservationTypeChange implements CommandUndo<RaplaException>{
private final Classification oldClassification;
private final Classification newClassification;
private final DynamicType oldDynamicType;
private final DynamicType newDynamicType;
public UndoReservationTypeChange(Classification oldClassification, Classification newClassification, DynamicType oldDynamicType, DynamicType newDynamicType) {
this.oldDynamicType = oldDynamicType;
this.newDynamicType = newDynamicType;
this.oldClassification = oldClassification;
this.newClassification = newClassification;
}
public boolean execute() throws RaplaException {
classification = newClassification;
setType(newDynamicType);
return true;
}
public boolean undo() throws RaplaException {
classification = oldClassification;
setType(oldDynamicType);
return true;
}
protected void setType(DynamicType typeToSet) throws RaplaException {
if (!typeSelector.getSelectedItem().equals(typeToSet)) {
internalUpdate = true;
try {
typeSelector.setSelectedItem(typeToSet);
} finally {
internalUpdate = false;
}
}
classifiable.setClassification(classification);
editUI.setObjects(Collections.singletonList(classification));
tabSelector.setVisible(hasSecondTab(classification) || !isMainViewSelected);
content.validate();
updateHeight();
content.repaint();
fireInfoChanged();
}
public String getCommandoName()
{
return getString("change") + " " + getString("dynamictype");
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/reservation/ReservationInfoEdit.java | Java | gpl3 | 18,770 |
package org.rapla.gui.internal.edit.reservation;
/*
* SortedListModel.java
*
* Copyright 2006 Sun Microsystems, Inc. ALL RIGHTS RESERVED Use of
* this software is authorized pursuant to the terms of the license
* found at http://developers.sun.com/berkeley_license.html .
*
*/
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.AbstractListModel;
import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
/**
* SortedListModel decorates an unsorted ListModel to provide
* a sorted model. You can create a SortedListModel from models you
* already have. Place the SortedListModel into a JList, for example, to provide
* a sorted view of your underlying model.
*
* @author John O'Conner
*/
public class SortedListModel extends AbstractListModel {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Create a SortedListModel from an existing model
* using a default text comparator for the default Locale. Sort
* in ascending order.
* @param model the underlying, unsorted ListModel
*/
public SortedListModel(ListModel model) {
this(model, SortOrder.ASCENDING, null);
}
/**
* Create a SortedListModel from an existing model
* using a specific comparator and sort order. Use
* a default text comparator.
*
*@param model the unsorted list model
*@param sortOrder that should be used
*/
public SortedListModel(ListModel model, SortOrder sortOrder) {
this(model, sortOrder, null);
}
/**
* Create a SortedListModel from an existing model. Sort the model
* in the specified sort order using the given comparator.
*
*@param model
*@param sortOrder
*@param comp
*
*/
public SortedListModel(ListModel model, SortOrder sortOrder, Comparator<Object> comp) {
unsortedModel = model;
unsortedModel.addListDataListener(new ListDataListener() {
public void intervalAdded(ListDataEvent e) {
unsortedIntervalAdded(e);
}
public void intervalRemoved(ListDataEvent e) {
unsortedIntervalRemoved(e);
}
public void contentsChanged(ListDataEvent e) {
unsortedContentsChanged();
}
});
this.sortOrder = sortOrder;
if (comp != null) {
comparator = comp;
} else {
comparator = Collator.getInstance();
}
// get base model info
int size = model.getSize();
sortedModel = new ArrayList<SortedListEntry>(size);
for (int x = 0; x < size; ++x) {
SortedListEntry entry = new SortedListEntry(x);
int insertionPoint = findInsertionPoint(entry);
sortedModel.add(insertionPoint, entry);
}
}
/**
* Retrieve the sorted entry from the original model
* @param index index of an entry in the sorted model
* @return element in the original model to which our entry points
*/
public Object getElementAt(int index) throws IndexOutOfBoundsException {
int modelIndex = toUnsortedModelIndex(index);
Object element = unsortedModel.getElementAt(modelIndex);
return element;
}
/**
* Retrieve the size of the underlying model
* @return size of the model
*/
public int getSize() {
int size = sortedModel.size();
return size;
}
/**
* Convert sorted model index to an unsorted model index.
*
*@param index an index in the sorted model
*@return modelIndex an index in the unsorted model
*
*/
public int toUnsortedModelIndex(int index) throws IndexOutOfBoundsException {
int modelIndex = -1;
SortedListEntry entry = sortedModel.get(index);
modelIndex = entry.getIndex();
return modelIndex;
}
/**
* Convert an array of sorted model indices to their unsorted model indices. Sort
* the resulting set of indices.
*
*@param sortedSelectedIndices indices of selected elements in the sorted model
* or sorted view
*@return unsortedSelectedIndices selected indices in the unsorted model
*/
public int[] toUnsortedModelIndices(int[] sortedSelectedIndices) {
int[] unsortedSelectedIndices = new int[sortedSelectedIndices.length];
int x = 0;
for(int sortedIndex: sortedSelectedIndices) {
unsortedSelectedIndices[x++] = toUnsortedModelIndex(sortedIndex);
}
// sort the array of indices before returning
Arrays.sort(unsortedSelectedIndices);
return unsortedSelectedIndices;
}
/**
* Convert an unsorted model index to a sorted model index.
*
* @param unsortedIndex an element index in the unsorted model
* @return sortedIndex an element index in the sorted model
*/
public int toSortedModelIndex(int unsortedIndex) {
int sortedIndex = -1;
int x = -1;
for (SortedListEntry entry : sortedModel) {
++x;
if (entry.getIndex() == unsortedIndex) {
sortedIndex = x;
break;
}
}
return sortedIndex;
}
/**
* Convert an array of unsorted model selection indices to
* indices in the sorted model. Sort the model indices from
* low to high to duplicate JList's getSelectedIndices method
*
* @param unsortedModelIndices
* @return an array of selected indices in the sorted model
*/
public int[] toSortedModelIndices(int[] unsortedModelIndices) {
int[] sortedModelIndices = new int[unsortedModelIndices.length];
int x = 0;
for(int unsortedIndex : unsortedModelIndices) {
sortedModelIndices[x++] = toSortedModelIndex(unsortedIndex);
}
Arrays.sort(sortedModelIndices);
return sortedModelIndices;
}
private void resetModelData() {
int index = 0;
for (SortedListEntry entry : sortedModel) {
entry.setIndex(index++);
}
}
public void setComparator(Comparator<Object> comp) {
if (comp == null) {
sortOrder = SortOrder.UNORDERED;
comparator = Collator.getInstance();
resetModelData();
} else {
comparator = comp;
Collections.sort(sortedModel);
}
fireContentsChanged(ListDataEvent.CONTENTS_CHANGED, 0, sortedModel.size()-1);
}
/**
* Change the sort order of the model at runtime
* @param sortOrder
*/
public void setSortOrder(SortOrder sortOrder) {
if (this.sortOrder != sortOrder) {
this.sortOrder = sortOrder;
if (sortOrder == SortOrder.UNORDERED) {
resetModelData();
} else {
Collections.sort(sortedModel);
}
fireContentsChanged(ListDataEvent.CONTENTS_CHANGED, 0, sortedModel.size()-1);
}
}
/**
* Update the sorted model whenever new items
* are added to the original/decorated model.
*
*/
private void unsortedIntervalAdded(ListDataEvent e) {
int begin = e.getIndex0();
int end = e.getIndex1();
int nElementsAdded = end-begin+1;
/* Items in the decorated model have shifted in flight.
* Increment our model pointers into the decorated model.
* We must increment indices that intersect with the insertion
* point in the decorated model.
*/
for (SortedListEntry entry: sortedModel) {
int index = entry.getIndex();
// if our model points to a model index >= to where
// new model entries are added, we must bump up their index
if (index >= begin) {
entry.setIndex(index+nElementsAdded);
}
}
// now add the new items from the decorated model
for (int x = begin; x <= end; ++x) {
SortedListEntry newEntry = new SortedListEntry(x);
int insertionPoint = findInsertionPoint(newEntry);
sortedModel.add(insertionPoint, newEntry);
fireIntervalAdded(ListDataEvent.INTERVAL_ADDED, insertionPoint, insertionPoint);
}
}
/**
* Update this model when items are removed from the original/decorated
* model. Also, let our listeners know that we've removed items.
*/
private void unsortedIntervalRemoved(ListDataEvent e) {
int begin = e.getIndex0();
int end = e.getIndex1();
int nElementsRemoved = end-begin+1;
/*
* Move from end to beginning of our sorted model, updating
* element indices into the decorated model or removing
* elements as necessary
*/
int sortedSize = sortedModel.size();
boolean[] bElementRemoved = new boolean[sortedSize];
for (int x = sortedSize-1; x >=0; --x) {
SortedListEntry entry = sortedModel.get(x);
int index = entry.getIndex();
if (index > end) {
entry.setIndex(index - nElementsRemoved);
} else if (index >= begin) {
sortedModel.remove(x);
bElementRemoved[x] = true;
}
}
/*
* Let listeners know that we've removed items.
*/
for(int x = bElementRemoved.length-1; x>=0; --x) {
if (bElementRemoved[x]) {
fireIntervalRemoved(ListDataEvent.INTERVAL_REMOVED, x, x);
}
}
}
/**
* Resort the sorted model if there are changes in the original
* unsorted model. Let any listeners know about changes. Since I don't
* track specific changes, sort everywhere and redisplay all items.
*/
private void unsortedContentsChanged() {
Collections.sort(sortedModel);
fireContentsChanged(ListDataEvent.CONTENTS_CHANGED, 0, sortedModel.size()-1);
}
/**
* Internal helper method to find the insertion point for a new
* entry in the sorted model.
*/
private int findInsertionPoint(SortedListEntry entry) {
int insertionPoint = sortedModel.size();
if (sortOrder != SortOrder.UNORDERED) {
insertionPoint = Collections.binarySearch(sortedModel, entry);
if (insertionPoint < 0) {
insertionPoint = -(insertionPoint +1);
}
}
return insertionPoint;
}
private List<SortedListEntry> sortedModel;
private ListModel unsortedModel;
private Comparator<Object> comparator;
private SortOrder sortOrder;
public enum SortOrder {
UNORDERED,
ASCENDING,
DESCENDING;
}
class SortedListEntry implements Comparable<Object> {
public SortedListEntry(int index) {
this.index = index;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public int compareTo(Object o) {
// retrieve the element that this entry points to
// in the original model
Object thisElement = unsortedModel.getElementAt(index);
SortedListEntry thatEntry = (SortedListEntry)o;
// retrieve the element that thatEntry points to in the original
// model
Object thatElement = unsortedModel.getElementAt(thatEntry.getIndex());
if (comparator instanceof Collator) {
thisElement = thisElement.toString();
thatElement = thatElement.toString();
}
// compare the base model's elements using the provided comparator
int comparison = comparator.compare(thisElement, thatElement);
// convert to descending order as necessary
if (sortOrder == SortOrder.DESCENDING) {
comparison = -comparison;
}
return comparison;
}
private int index;
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/reservation/SortedListModel.java | Java | gpl3 | 12,623 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.reservation;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.ComponentInputMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.ActionMapUIResource;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.components.util.undo.CommandHistoryChangedListener;
import org.rapla.components.util.undo.CommandUndo;
import org.rapla.entities.EntityNotFoundException;
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.facade.ModificationEvent;
import org.rapla.facade.ModificationModule;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.AppointmentListener;
import org.rapla.gui.AppointmentStatusFactory;
import org.rapla.gui.ReservationController;
import org.rapla.gui.ReservationEdit;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.EmptyLineBorder;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaFrame;
import org.rapla.gui.toolkit.RaplaWidget;
class ReservationEditImpl extends AbstractAppointmentEditor implements ReservationEdit
{
ArrayList<ChangeListener> changeListenerList = new ArrayList<ChangeListener>();
protected Reservation mutableReservation;
private Reservation original;
CommandHistory commandHistory;
JToolBar toolBar = new JToolBar();
RaplaButton saveButtonTop = new RaplaButton();
RaplaButton saveButton = new RaplaButton();
RaplaButton deleteButton = new RaplaButton();
RaplaButton closeButton = new RaplaButton();
Action undoAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
try {
commandHistory.undo();
} catch (Exception ex) {
showException(ex, getMainComponent());
}
}
};
Action redoAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
try {
commandHistory.redo();
} catch (Exception ex) {
showException(ex, getMainComponent());
}
}
};
JPanel mainContent = new JPanel();
//JPanel split = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
RaplaFrame frame;
ReservationInfoEdit reservationInfo;
AppointmentListEdit appointmentEdit ;
AllocatableSelection allocatableEdit;
boolean bSaving = false;
boolean bDeleting = false;
boolean bSaved;
boolean bNew;
TableLayout tableLayout = new TableLayout(new double[][] {
{TableLayout.FILL}
,{TableLayout.PREFERRED,TableLayout.PREFERRED,TableLayout.FILL}
} );
private final Listener listener = new Listener();
List<AppointmentListener> appointmentListeners = new ArrayList<AppointmentListener>();
ReservationEditImpl(RaplaContext sm) throws RaplaException {
super( sm);
commandHistory = new CommandHistory();
reservationInfo = new ReservationInfoEdit(sm, commandHistory);
appointmentEdit = new AppointmentListEdit(sm, commandHistory);
allocatableEdit = new AllocatableSelection(sm,true, commandHistory);
// horizontalSplit.setTopComponent(appointmentEdit.getComponent());
//horizontalSplit.setBottomComponent(allocatableEdit.getComponent());
/*
try {
// If run on jdk < 1.3 this will throw a MethodNotFoundException
// horizontalSplit.setResizeWeight(0.1);
JSplitPane.class.getMethod("setResizeWeight",new Class[] {double.class}).invoke(horizontalSplit,new Object[] {new Double(0.1)});
} catch (Exception ex) {
}
*/
frame = new RaplaFrame(sm);
mainContent.setLayout( tableLayout );
mainContent.add(reservationInfo.getComponent(),"0,0");
mainContent.add(appointmentEdit.getComponent(),"0,1");
mainContent.add(allocatableEdit.getComponent(),"0,2");
//allocatableEdit.getComponent().setVisible(false);
saveButtonTop.setAction( listener );
saveButton.setAction( listener );
toolBar.setFloatable(false);
saveButton.setAlignmentY(JButton.CENTER_ALIGNMENT);
deleteButton.setAlignmentY(JButton.CENTER_ALIGNMENT);
closeButton.setAlignmentY(JButton.CENTER_ALIGNMENT);
JPanel buttonsPanel = new JPanel();
//buttonsPanel.add(deleteButton);
buttonsPanel.add(saveButton);
buttonsPanel.add(closeButton);
toolBar.add(saveButtonTop);
toolBar.add(deleteButton);
deleteButton.setAction( listener );
RaplaButton vor = new RaplaButton();
RaplaButton back = new RaplaButton();
// Undo-Buttons in Toolbar
// final JPanel undoContainer = new JPanel();
redoAction.setEnabled(false);
undoAction.setEnabled(false);
vor.setAction( redoAction);
back.setAction( undoAction);
final KeyStroke undoKeyStroke = KeyStroke.getKeyStroke( KeyEvent.VK_Z, ActionEvent.CTRL_MASK );
setAccelerator(back, undoAction, undoKeyStroke);
final KeyStroke redoKeyStroke = KeyStroke.getKeyStroke( KeyEvent.VK_Y, ActionEvent.CTRL_MASK );
setAccelerator(vor, redoAction, redoKeyStroke);
commandHistory.addCommandHistoryChangedListener(new CommandHistoryChangedListener() {
public void historyChanged()
{
redoAction.setEnabled(commandHistory.canRedo());
boolean canUndo = commandHistory.canUndo();
undoAction.setEnabled(canUndo);
String modifier = KeyEvent.getKeyModifiersText(ActionEvent.CTRL_MASK);
String redoKeyString =modifier+ "-Y";
String undoKeyString = modifier+ "-Z";
redoAction.putValue(Action.SHORT_DESCRIPTION,getString("redo") + ": " + commandHistory.getRedoText() + " " + redoKeyString);
undoAction.putValue(Action.SHORT_DESCRIPTION,getString("undo") + ": " + commandHistory.getUndoText() + " " + undoKeyString);
}
});
toolBar.add(back);
toolBar.add(vor);
closeButton.addActionListener(listener);
appointmentEdit.addAppointmentListener(allocatableEdit);
appointmentEdit.addAppointmentListener(listener);
allocatableEdit.addChangeListener(listener);
reservationInfo.addChangeListener(listener);
reservationInfo.addDetailListener(listener);
frame.addVetoableChangeListener(listener);
frame.setIconImage( getI18n().getIcon("icon.edit_window_small").getImage());
JPanel contentPane = (JPanel) frame.getContentPane();
contentPane.setLayout(new BorderLayout());
mainContent.setBorder(BorderFactory.createLoweredBevelBorder());
contentPane.add(toolBar, BorderLayout.NORTH);
contentPane.add(buttonsPanel, BorderLayout.SOUTH);
contentPane.add(mainContent, BorderLayout.CENTER);
Dimension dimension = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(new Dimension(
Math.min(dimension.width,990)
// BJO 00000032 temp fix for filter out of frame bounds
,Math.min(dimension.height-10,720)
//,Math.min(dimension.height-10,1000)
)
);
Border emptyLineBorder = new EmptyLineBorder();
//BorderFactory.createEmptyBorder();
Border border2 = BorderFactory.createTitledBorder(emptyLineBorder,getString("reservation.appointments"));
Border border3 = BorderFactory.createTitledBorder(emptyLineBorder,getString("reservation.allocations"));
appointmentEdit.getComponent().setBorder(border2);
allocatableEdit.getComponent().setBorder(border3);
saveButton.setText(getString("save"));
saveButton.setIcon(getIcon("icon.save"));
saveButtonTop.setText(getString("save"));
saveButtonTop.setMnemonic(KeyEvent.VK_S);
saveButtonTop.setIcon(getIcon("icon.save"));
deleteButton.setText(getString("delete"));
deleteButton.setIcon(getIcon("icon.delete"));
closeButton.setText(getString("abort"));
closeButton.setIcon(getIcon("icon.abort"));
vor.setToolTipText(getString("redo"));
vor.setIcon(getIcon("icon.redo"));
back.setToolTipText(getString("undo"));
back.setIcon(getIcon("icon.undo"));
}
protected void setAccelerator(JButton button, Action yourAction,
KeyStroke keyStroke) {
InputMap keyMap = new ComponentInputMap(button);
keyMap.put(keyStroke, "action");
ActionMap actionMap = new ActionMapUIResource();
actionMap.put("action", yourAction);
SwingUtilities.replaceUIActionMap(button, actionMap);
SwingUtilities.replaceUIInputMap(button, JComponent.WHEN_IN_FOCUSED_WINDOW, keyMap);
}
protected void setSaved(boolean flag) {
bSaved = flag;
saveButton.setEnabled(!flag);
saveButtonTop.setEnabled(!flag);
}
/* (non-Javadoc)
* @see org.rapla.gui.edit.reservation.IReservationEdit#isModifiedSinceLastChange()
*/
public boolean isModifiedSinceLastChange() {
return !bSaved;
}
final private ReservationControllerImpl getPrivateReservationController() {
return (ReservationControllerImpl) getService(ReservationController.class);
}
public void addAppointment( Date start, Date end) throws RaplaException
{
Appointment appointment = getModification().newAppointment( start, end );
AppointmentController controller = appointmentEdit.getAppointmentController();
Repeating repeating= controller.getRepeating();
if ( repeating!= null )
{
appointment.setRepeatingEnabled(true);
appointment.getRepeating().setFrom(repeating);
}
appointmentEdit.addAppointment( appointment);
}
void deleteReservation() throws RaplaException {
if (bDeleting)
return;
getLogger().debug("Reservation has been deleted.");
DialogUI dlg = DialogUI.create(
getContext()
,mainContent
,true
,getString("warning")
,getString("warning.reservation.delete")
);
dlg.setIcon(getIcon("icon.warning"));
dlg.start();
closeWindow();
}
void updateReservation(Reservation newReservation) throws RaplaException {
if (bSaving)
return;
getLogger().debug("Reservation has been changed.");
DialogUI dlg = DialogUI.create(
getContext()
,mainContent
,true
,getString("warning")
,getString("warning.reservation.update")
);
commandHistory.clear();
try {
dlg.setIcon(getIcon("icon.warning"));
dlg.start();
this.original = newReservation;
setReservation(getModification().edit(newReservation) , null);
} catch (RaplaException ex) {
showException(ex,frame);
}
}
void refresh(ModificationEvent evt) throws RaplaException {
allocatableEdit.dataChanged(evt);
}
void editReservation(Reservation reservation, AppointmentBlock appointmentBlock) throws RaplaException {
ModificationModule mod = getModification();
boolean bNew = false;
if ( reservation.isReadOnly()) {
mutableReservation = mod.edit(reservation);
original = reservation;
} else {
try {
original = getModification().getPersistant( reservation);
} catch ( EntityNotFoundException ex) {
bNew = true;
original = null;
}
mutableReservation = reservation;
}
setSaved(!bNew);
//printBlocks( appointment );
this.bNew = bNew;
deleteButton.setEnabled(!bNew);
Appointment appointment = appointmentBlock != null ? appointmentBlock.getAppointment() : null;
Appointment mutableAppointment = null;
for (Appointment app:mutableReservation.getAppointments()) {
if ( appointment != null && app.equals(appointment))
{
mutableAppointment = app;
}
}
Date selectedDate = appointmentBlock != null ? new Date(appointmentBlock.getStart()) : null;
setReservation(mutableReservation, mutableAppointment);
appointmentEdit.getAppointmentController().setSelectedEditDate( selectedDate);
setTitle();
boolean packFrame = false;
frame.place( true, packFrame);
frame.setVisible( true );
// Insert into open ReservationEditWindows, so that
// we can't edit the same Reservation in different windows
getPrivateReservationController().addReservationEdit(this);
reservationInfo.requestFocus();
getLogger().debug("New Reservation-Window created");
}
@Override
public Reservation getReservation() {
return mutableReservation;
}
public Reservation getOriginal() {
return original;
}
@Override
public Collection<Appointment> getSelectedAppointments() {
Collection<Appointment> appointments = new ArrayList<Appointment>();
for ( Appointment value:appointmentEdit.getListEdit().getSelectedValues())
{
appointments.add( value);
}
return appointments;
}
private void setTitle() {
String title = getI18n().format((bNew) ?
"new_reservation.format" : "edit_reservation.format"
,getName(mutableReservation));
frame.setTitle(title);
}
private void setReservation(Reservation newReservation, Appointment mutableAppointment) throws RaplaException {
commandHistory.clear();
this.mutableReservation = newReservation;
appointmentEdit.setReservation(mutableReservation, mutableAppointment);
allocatableEdit.setReservation(mutableReservation, original);
reservationInfo.setReservation(mutableReservation);
List<AppointmentStatusFactory> statusFactories = new ArrayList<AppointmentStatusFactory>();
Collection<AppointmentStatusFactory> list= getContainer().lookupServicesFor(RaplaClientExtensionPoints.APPOINTMENT_STATUS);
for (AppointmentStatusFactory entry:list)
{
statusFactories.add(entry);
}
JPanel status =appointmentEdit.getListEdit().getStatusBar();
status.removeAll();
for (AppointmentStatusFactory factory: statusFactories)
{
RaplaWidget statusWidget = factory.createStatus(getContext(), this);
status.add( statusWidget.getComponent());
}
// Should be done in initialization method of Appointmentstatus. The appointments are already selected then, so you can query the selected appointments thers.
// if(appointment == null)
// fireAppointmentSelected(Collections.singleton(mutableReservation.getAppointments()[0]));
// else
// fireAppointmentSelected(Collections.singleton(appointment));
}
public void closeWindow() {
appointmentEdit.dispose();
getPrivateReservationController().removeReservationEdit(this);
frame.dispose();
getLogger().debug("Edit window closed.");
}
class Listener extends AbstractAction implements AppointmentListener,ChangeListener,VetoableChangeListener, ReservationInfoEdit.DetailListener {
private static final long serialVersionUID = 1L;
// Implementation of ReservationListener
public void appointmentRemoved(Collection<Appointment> appointment) {
setSaved(false);
ReservationEditImpl.this.fireAppointmentRemoved(appointment);
fireReservationChanged(new ChangeEvent(appointmentEdit));
}
public void appointmentAdded(Collection<Appointment> appointment) {
setSaved(false);
ReservationEditImpl.this.fireAppointmentAdded(appointment);
fireReservationChanged(new ChangeEvent(appointmentEdit));
}
public void appointmentChanged(Collection<Appointment> appointment) {
setSaved(false);
ReservationEditImpl.this.fireAppointmentChanged(appointment);
fireReservationChanged(new ChangeEvent(appointmentEdit));
}
public void appointmentSelected(Collection<Appointment> appointment) {
ReservationEditImpl.this.fireAppointmentSelected(appointment);
}
public void stateChanged(ChangeEvent evt) {
if (evt.getSource() == reservationInfo) {
getLogger().debug("ReservationInfo changed");
setSaved(false);
setTitle();
}
if (evt.getSource() == allocatableEdit) {
getLogger().debug("AllocatableEdit changed");
setSaved(false);
}
fireReservationChanged(evt);
}
public void detailChanged() {
boolean isMain = reservationInfo.isMainView();
if ( isMain != appointmentEdit.getComponent().isVisible() ) {
appointmentEdit.getComponent().setVisible( isMain );
allocatableEdit.getComponent().setVisible( isMain );
if ( isMain ) {
tableLayout.setRow(0, TableLayout.PREFERRED);
tableLayout.setRow(1, TableLayout.PREFERRED);
tableLayout.setRow(2, TableLayout.FILL);
} else {
tableLayout.setRow(0, TableLayout.FILL);
tableLayout.setRow(1, 0);
tableLayout.setRow(2, 0);
}
mainContent.validate();
}
}
public void actionPerformed(ActionEvent evt) {
try {
if (evt.getSource() == saveButton || evt.getSource() == saveButtonTop) {
save();
}
if (evt.getSource() == deleteButton) {
delete();
}
if (evt.getSource() == closeButton) {
if (canClose())
closeWindow();
}
} catch (RaplaException ex) {
showException(ex, null);
}
}
public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
if (!canClose())
throw new PropertyVetoException("Don't close",evt);
closeWindow();
}
}
protected boolean canClose() {
if (!isModifiedSinceLastChange())
return true;
try {
DialogUI dlg = DialogUI.create(
getContext()
,mainContent
,true
,getString("confirm-close.title")
,getString("confirm-close.question")
,new String[] {
getString("confirm-close.ok")
,getString("back")
}
);
dlg.setIcon(getIcon("icon.question"));
dlg.setDefault(1);
dlg.start();
return (dlg.getSelectedIndex() == 0) ;
} catch (RaplaException e) {
return true;
}
}
/* (non-Javadoc)
* @see org.rapla.gui.edit.reservation.IReservationEdit#save()
*/
@Override
public void save() throws RaplaException {
try {
frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
bSaving = true;
ReservationControllerImpl.ReservationSave saveCommand = getPrivateReservationController().new ReservationSave(mutableReservation, original, frame);
if (getClientFacade().getCommandHistory().storeAndExecute(saveCommand))
{
setSaved(true);
}
} catch (RaplaException ex) {
showException(ex, frame);
} finally {
frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
if (bSaved)
closeWindow();
bSaving = false;
}
}
/* (non-Javadoc)
* @see org.rapla.gui.edit.reservation.IReservationEdit#delete()
*/
@Override
public void delete() throws RaplaException {
try {
DialogUI dlg = getInfoFactory().createDeleteDialog(new Object[] {mutableReservation}
,frame);
dlg.start();
if (dlg.getSelectedIndex() == 0) {
bDeleting = true;
Set<Reservation> reservationsToRemove = Collections.singleton( original);
Set<Appointment> appointmentsToRemove = Collections.emptySet();
Map<Appointment, List<Date>> exceptionsToAdd = Collections.emptyMap();
CommandUndo<RaplaException> deleteCommand = getPrivateReservationController().new DeleteBlocksCommand(reservationsToRemove, appointmentsToRemove, exceptionsToAdd)
{
public String getCommandoName() {
return getString("delete") + " " + getString("reservation");
}
};
getClientFacade().getCommandHistory().storeAndExecute(deleteCommand);
closeWindow();
}
} finally {
bDeleting = false;
}
}
protected ChangeListener[] getReservationInfpListeners() {
return changeListenerList.toArray(new ChangeListener[]{});
}
protected void fireReservationChanged(ChangeEvent evt) {
for (ChangeListener listener: getReservationInfpListeners())
{
listener.stateChanged( evt);
}
}
@Override
public void addReservationChangeListener(ChangeListener listener) {
changeListenerList.add(listener);
}
@Override
public void removeReservationChangeListener(ChangeListener listener) {
changeListenerList.remove( listener);
}
} | 04900db4-clienttest | src/org/rapla/gui/internal/edit/reservation/ReservationEditImpl.java | Java | gpl3 | 24,548 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.reservation;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.JLabel;
import org.rapla.gui.toolkit.AWTColorUtil;
import org.rapla.gui.toolkit.RaplaColors;
/** A label with a background-color corresponding to the index
of the appointment.
@see RaplaColors#getAppointmentColor
*/
public class AppointmentIdentifier extends JLabel {
private static final long serialVersionUID = 1L;
String text;
int index = 0;
public void setIndex(int index) {
this.index = index;
}
public void setText(String text) {
this.text = text;
super.setText(text + " ");
}
public void paintComponent(Graphics g) {
FontMetrics fm = g.getFontMetrics();
Insets insets = getInsets();
String s = text;
int width = fm.stringWidth(s);
int x = 1;
g.setColor(AWTColorUtil.getAppointmentColor(index));
g.fillRoundRect(x
,insets.top
,width +1
,getHeight()-insets.top -insets.bottom-1,4,4);
g.setColor(getForeground());
g.drawRoundRect(x-1
,insets.top
,width +2
,getHeight()-insets.top -insets.bottom-1,4,4);
g.drawString(s
,x
,getHeight() /2 + fm.getDescent() + 1);
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/reservation/AppointmentIdentifier.java | Java | gpl3 | 2,156 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.reservation;
import java.awt.Component;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.ReservationCheck;
import org.rapla.gui.toolkit.DialogUI;
public class DefaultReservationCheck extends RaplaGUIComponent implements ReservationCheck
{
public DefaultReservationCheck(RaplaContext context) {
super(context);
}
public boolean check(Reservation reservation, Component sourceComponent) throws RaplaException {
try
{
getClientFacade().checkReservation( reservation);
Appointment[] appointments = reservation.getAppointments();
Appointment duplicatedAppointment = null;
for (int i=0;i<appointments.length;i++) {
for (int j=i + 1;j<appointments.length;j++)
if (appointments[i].matches(appointments[j])) {
duplicatedAppointment = appointments[i];
break;
}
}
JPanel warningPanel = new JPanel();
warningPanel.setLayout( new BoxLayout( warningPanel, BoxLayout.Y_AXIS));
if (duplicatedAppointment != null) {
JLabel warningLabel = new JLabel();
warningLabel.setForeground(java.awt.Color.red);
warningLabel.setText
(getI18n().format
(
"warning.duplicated_appointments"
,getAppointmentFormater().getShortSummary(duplicatedAppointment)
)
);
warningPanel.add( warningLabel);
}
if (reservation.getAllocatables().length == 0)
{
JLabel warningLabel = new JLabel();
warningLabel.setForeground(java.awt.Color.red);
warningLabel.setText(getString("warning.no_allocatables_selected"));
warningPanel.add( warningLabel);
}
if ( warningPanel.getComponentCount() > 0) {
DialogUI dialog = DialogUI.create(
getContext()
,sourceComponent
,true
,warningPanel
,new String[] {
getString("continue")
,getString("back")
}
);
dialog.setTitle( getString("warning"));
dialog.setIcon(getIcon("icon.warning"));
dialog.setDefault(1);
dialog.getButton(0).setIcon(getIcon("icon.save"));
dialog.getButton(1).setIcon(getIcon("icon.cancel"));
dialog.start();
if (dialog.getSelectedIndex() == 0)
{
return true;
}
else
{
return false;
}
}
return true;
}
catch (RaplaException ex)
{
showWarning( ex.getMessage(), sourceComponent);
return false;
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/reservation/DefaultReservationCheck.java | Java | gpl3 | 4,407 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.reservation;
import java.util.ArrayList;
import java.util.Collection;
import org.rapla.entities.domain.Appointment;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.AppointmentListener;
import org.rapla.gui.RaplaGUIComponent;
/** Provides AppointmentListener handling.*/
public class AbstractAppointmentEditor extends RaplaGUIComponent {
ArrayList<AppointmentListener> listenerList = new ArrayList<AppointmentListener>();
public AbstractAppointmentEditor(RaplaContext sm) {
super(sm);
}
public void addAppointmentListener(AppointmentListener listener) {
listenerList.add(listener);
}
public void removeAppointmentListener(AppointmentListener listener) {
listenerList.remove(listener);
}
public AppointmentListener[] getAppointmentListeners() {
return listenerList.toArray(new AppointmentListener[]{});
}
protected void fireAppointmentAdded(Collection<Appointment> appointment) {
AppointmentListener[] listeners = getAppointmentListeners();
for (int i = 0;i<listeners.length; i++) {
listeners[i].appointmentAdded(appointment);
}
}
protected void fireAppointmentRemoved(Collection<Appointment> appointment) {
AppointmentListener[] listeners = getAppointmentListeners();
for (int i = 0;i<listeners.length; i++) {
listeners[i].appointmentRemoved(appointment);
}
}
protected void fireAppointmentChanged(Collection<Appointment> appointment) {
AppointmentListener[] listeners = getAppointmentListeners();
for (int i = 0;i<listeners.length; i++) {
listeners[i].appointmentChanged(appointment);
}
}
protected void fireAppointmentSelected(Collection<Appointment> appointment) {
AppointmentListener[] listeners = getAppointmentListeners();
for (int i = 0;i<listeners.length; i++) {
listeners[i].appointmentSelected(appointment);
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/reservation/AbstractAppointmentEditor.java | Java | gpl3 | 2,904 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.reservation;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.DefaultCellEditor;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.MenuSelectionManager;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.EventListenerList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.basic.BasicCheckBoxMenuItemUI;
import javax.swing.plaf.basic.BasicRadioButtonMenuItemUI;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.treetable.AbstractTreeTableModel;
import org.rapla.components.treetable.JTreeTable;
import org.rapla.components.treetable.TableToolTipRenderer;
import org.rapla.components.treetable.TreeTableModel;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.components.util.undo.CommandUndo;
import org.rapla.entities.Named;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentStartComparator;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.ResourceAnnotations;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.RaplaComponent;
import org.rapla.facade.internal.FacadeImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.AppointmentListener;
import org.rapla.gui.MenuContext;
import org.rapla.gui.MenuFactory;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.internal.FilterEditButton;
import org.rapla.gui.internal.MenuFactoryImpl;
import org.rapla.gui.internal.common.CalendarAction;
import org.rapla.gui.internal.edit.ClassifiableFilterEdit;
import org.rapla.gui.toolkit.AWTColorUtil;
import org.rapla.gui.toolkit.PopupEvent;
import org.rapla.gui.toolkit.PopupListener;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaPopupMenu;
import org.rapla.gui.toolkit.RaplaSeparator;
import org.rapla.gui.toolkit.RaplaWidget;
/**
* <p>
* GUI for editing the allocations of a reservation. Presents two TreeTables. The left one displays
* all available Resources and Persons the right one all selected Resources and Persons.
* </p>
* <p>
* The second column of the first table contains information about the availability on the
* appointments of the reservation. In the second column of the second table the user can add
* special Restrictions on the selected Resources and Persons.
* </p>
*
* @see Reservation
* @see Allocatable
*/
public class AllocatableSelection extends RaplaGUIComponent implements AppointmentListener, PopupListener, RaplaWidget
{
JSplitPane content = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
JPanel leftPanel = new JPanel();
JTreeTable completeTable;
RaplaButton btnAdd = new RaplaButton(RaplaButton.SMALL);
RaplaButton btnCalendar1 = new RaplaButton(RaplaButton.SMALL);
JPanel rightPanel = new JPanel();
JTreeTable selectedTable;
RaplaButton btnRemove = new RaplaButton(RaplaButton.SMALL);
RaplaButton btnCalendar2 = new RaplaButton(RaplaButton.SMALL);
Reservation mutableReservation;
Reservation originalReservation;
AllocatablesModel completeModel = new CompleteModel();
AllocatablesModel selectedModel = new SelectedModel();
Map<Allocatable, Collection<Appointment>> allocatableBindings = new HashMap<Allocatable, Collection<Appointment>>();
// Map<Appointment,Collection<Allocatable>> appointmentMap = new HashMap<Appointment,Collection<Allocatable>>();
Appointment[] appointments;
String[] appointmentStrings;
String[] appointmentIndexStrings;
CalendarSelectionModel calendarModel;
EventListenerList listenerList = new EventListenerList();
Listener listener = new Listener();
//FilterAction filterAction;
AllocatableAction addAction;
AllocatableAction removeAction;
AllocatableAction calendarAction1;
AllocatableAction calendarAction2;
User user;
CommandHistory commandHistory;
FilterEditButton filter;
public AllocatableSelection(RaplaContext sm)
{
this(sm, false, new CommandHistory());
}
public AllocatableSelection(RaplaContext sm, boolean addCalendarButton,CommandHistory commandHistory)
{
super(sm);
// Undo Command History
this.commandHistory = commandHistory;
double pre = TableLayout.PREFERRED;
double fill = TableLayout.FILL;
double tableSize[][] = { { pre, 12, pre, 3, fill, pre}, // Columns
{ pre, fill } }; // Rows
leftPanel.setLayout(new TableLayout(tableSize));
if (addCalendarButton)
leftPanel.add(btnCalendar1, "0,0,l,f");
leftPanel.add(btnAdd, "5,0,r,f");
rightPanel.setLayout(new TableLayout(tableSize));
rightPanel.add(btnRemove, "0,0,l,f");
if (addCalendarButton)
rightPanel.add(btnCalendar2, "2,0,c,c");
content.setLeftComponent(leftPanel);
content.setRightComponent(rightPanel);
content.setResizeWeight(0.3);
btnAdd.setEnabled(false);
btnCalendar1.setEnabled(false);
btnRemove.setEnabled(false);
btnCalendar2.setEnabled(false);
addAction = new AllocatableAction("add");
removeAction = new AllocatableAction("remove");
calendarAction1 = new AllocatableAction("calendar1");
calendarAction2 = new AllocatableAction("calendar2");
btnAdd.setAction(addAction);
btnRemove.setAction(removeAction);
btnCalendar1.setAction(calendarAction1);
btnCalendar2.setAction(calendarAction2);
completeTable = new JTreeTable(completeModel);
Color tableBackground = completeTable.getTree().getBackground();
JScrollPane leftScrollpane = new JScrollPane(completeTable);
leftScrollpane.getViewport().setBackground(tableBackground);
leftPanel.add(leftScrollpane, "0,1,5,1,f,f");
completeTable.setGridColor(darken(tableBackground, 20));
completeTable.setToolTipRenderer(new RaplaToolTipRenderer());
completeTable.getSelectionModel().addListSelectionListener(listener);
completeTable.setDefaultRenderer(Allocatable.class, new AllocationCellRenderer());
completeTable.setDefaultEditor(Allocatable.class, new AppointmentCellEditor2(new AllocationTextField()));
completeTable.getTree().setCellRenderer(new AllocationTreeCellRenderer(false));
completeTable.addMouseListener(listener);
selectedTable = new JTreeTable(selectedModel);
JScrollPane rightScrollpane = new JScrollPane(selectedTable);
rightScrollpane.getViewport().setBackground(tableBackground);
rightPanel.add(rightScrollpane, "0,1,5,1,f,f");
selectedTable.setToolTipRenderer(new RaplaToolTipRenderer());
selectedTable.getSelectionModel().addListSelectionListener(listener);
selectedTable.setGridColor(darken(tableBackground, 20));
selectedTable.setDefaultRenderer(Appointment[].class, new RestrictionCellRenderer());
AppointmentCellEditor appointmentCellEditor = new AppointmentCellEditor(new RestrictionTextField());
selectedTable.setDefaultEditor(Appointment[].class, appointmentCellEditor);
selectedTable.addMouseListener(listener);
selectedTable.getTree().setCellRenderer(new AllocationTreeCellRenderer(true));
completeTable.getColumnModel().getColumn(0).setMinWidth(60);
completeTable.getColumnModel().getColumn(0).setPreferredWidth(120);
completeTable.getColumnModel().getColumn(1).sizeWidthToFit();
selectedTable.getColumnModel().getColumn(0).setMinWidth(60);
selectedTable.getColumnModel().getColumn(0).setPreferredWidth(120);
selectedTable.getColumnModel().getColumn(1).sizeWidthToFit();
content.setDividerLocation(0.3);
CalendarSelectionModel originalModel = getService(CalendarSelectionModel.class);
calendarModel = originalModel.clone();
filter = new FilterEditButton( sm, calendarModel, listener,true);
leftPanel.add(filter.getButton(), "4,0,r,f");
// filterAction = new FilterAction(getContext(), getComponent(), null);
// filterAction.setFilter(calendarModel);
// filterAction.setResourceOnly(true);
}
public void addChangeListener(ChangeListener listener)
{
listenerList.add(ChangeListener.class, listener);
}
public void removeChangeListener(ChangeListener listener)
{
listenerList.remove(ChangeListener.class, listener);
}
final private TreeFactory getTreeFactory()
{
return getService(TreeFactory.class);
}
protected void fireAllocationsChanged()
{
ChangeEvent evt = new ChangeEvent(this);
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2)
{
if (listeners[i] == ChangeListener.class)
{
((ChangeListener) listeners[i + 1]).stateChanged(evt);
}
}
}
public void dataChanged(ModificationEvent evt) throws RaplaException
{
calendarModel.dataChanged( evt);
boolean updateBindings = false;
if (evt.isModified(Allocatable.TYPE))
{
updateBindings = true;
Collection<Allocatable> allAllocatables = getAllAllocatables();
completeModel.setAllocatables(allAllocatables, completeTable.getTree());
for ( Allocatable allocatable:selectedModel.getAllocatables())
{
if ( !allAllocatables.contains(allocatable ))
{
mutableReservation.removeAllocatable( allocatable);
}
}
selectedModel.setAllocatables(Arrays.asList(mutableReservation.getAllocatables()), selectedTable.getTree());
updateButtons();
}
if (updateBindings || evt.isModified(Reservation.TYPE))
{
updateBindings(null);
}
}
/** Implementation of appointment listener */
public void appointmentAdded(Collection<Appointment> appointments)
{
setAppointments(mutableReservation.getAppointments());
selectedModel.setAllocatables(getAllocated(), selectedTable.getTree());
updateBindings( appointments);
}
public void appointmentChanged(Collection<Appointment> appointments)
{
setAppointments(mutableReservation.getAppointments());
updateBindings( appointments );
}
public void appointmentRemoved(Collection<Appointment> appointments)
{
removeFromBindings( appointments);
setAppointments(mutableReservation.getAppointments());
selectedModel.setAllocatables(getAllocated(), selectedTable.getTree());
removeFromBindings( appointments);
List<Appointment> emptyList = Collections.emptyList();
updateBindings(emptyList);
}
public void appointmentSelected(Collection<Appointment> appointments)
{
}
private void updateBindings(Collection<Appointment> appointments)
{
Collection<Allocatable> allAllocatables = new LinkedHashSet<Allocatable>( completeModel.getAllocatables());
allAllocatables.addAll(Arrays.asList( mutableReservation.getAllocatables()));
if ( appointments == null)
{
allocatableBindings.clear();
for ( Allocatable allocatable: allAllocatables)
{
allocatableBindings.put( allocatable, new HashSet<Appointment>());
}
appointments = Arrays.asList(mutableReservation.getAppointments());
}
try
{
if (!RaplaComponent.isTemplate( this.mutableReservation))
{
// System.out.println("getting allocated resources");
Map<Allocatable, Collection<Appointment>> allocatableBindings = getQuery().getAllocatableBindings(allAllocatables,appointments);
removeFromBindings( appointments);
for ( Map.Entry<Allocatable, Collection<Appointment>> entry: allocatableBindings.entrySet())
{
Allocatable alloc = entry.getKey();
Collection<Appointment> list = this.allocatableBindings.get( alloc);
if ( list == null)
{
list = new HashSet<Appointment>();
this.allocatableBindings.put( alloc, list);
}
Collection<Appointment> bindings = entry.getValue();
list.addAll( bindings);
}
}
//this.allocatableBindings.putAll(allocatableBindings);
completeModel.treeDidChange();
selectedModel.treeDidChange();
}
catch (RaplaException ex)
{
showException(ex, content);
}
}
private void removeFromBindings(Collection<Appointment> appointments) {
for ( Collection<Appointment> list: allocatableBindings.values())
{
for ( Appointment app:appointments)
{
list.remove(app);
}
}
}
public JComponent getComponent()
{
return content;
}
private Set<Allocatable> getAllAllocatables() throws RaplaException
{
Allocatable[] allocatables = getQuery().getAllocatables(calendarModel.getAllocatableFilter());
Set<Allocatable> rightsToAllocate = new HashSet<Allocatable>();
Date today = getQuery().today();
for (Allocatable alloc:allocatables)
{
if (alloc.canAllocate(user, today))
{
rightsToAllocate.add( alloc );
}
}
return rightsToAllocate;
}
private Set<Allocatable> getAllocated()
{
Allocatable[] allocatables = mutableReservation.getAllocatables();
Set<Allocatable> result = new HashSet<Allocatable>(Arrays.asList(allocatables));
return result;
}
private boolean bWorkaround = false; // Workaround for Bug ID 4480264 on developer.java.sun.com
public void setReservation(Reservation mutableReservation, Reservation originalReservation) throws RaplaException
{
this.originalReservation = originalReservation;
this.mutableReservation = mutableReservation;
this.user = getUser();
setAppointments(mutableReservation.getAppointments());
Collection<Allocatable> allocatableList = getAllAllocatables();
completeModel.setAllocatables(allocatableList);
updateBindings( null);
// Expand allocatableTree if only one DynamicType
final CalendarModel calendarModel = getService(CalendarModel.class);
Collection<?> selectedObjectsAndChildren = calendarModel.getSelectedObjects();
expandObjects(selectedObjectsAndChildren, completeTable.getTree());
selectedModel.setAllocatables(getAllocated(), selectedTable.getTree());
expandObjects( getAllocated(), selectedTable.getTree());
updateButtons();
JTree tree = selectedTable.getTree();
for (int i = 0; i < tree.getRowCount(); i++)
tree.expandRow(i);
// Workaround for Bug ID 4480264 on developer.java.sun.com
bWorkaround = true;
if (selectedTable.getRowCount() > 0)
{
selectedTable.editCellAt(1, 1);
selectedTable.editCellAt(1, 0);
}
bWorkaround = false;
//filterAction.removePropertyChangeListener(listener);
// filterAction.addPropertyChangeListener(listener);
// btnFilter.setAction(filterAction);
// We have to add this after processing, because the Adapter in the JTreeTable does the same
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
selectObjects(calendarModel.getSelectedObjects(), completeTable.getTree());
}
});
}
private void setAppointments(Appointment[] appointmentArray)
{
List<Appointment> sortedAppointments = new ArrayList<Appointment>( Arrays.asList( appointmentArray));
Collections.sort(sortedAppointments, new AppointmentStartComparator() );
this.appointments = sortedAppointments.toArray( Appointment.EMPTY_ARRAY);
this.appointmentStrings = new String[appointments.length];
this.appointmentIndexStrings = new String[appointments.length];
for (int i = 0; i < appointments.length; i++)
{
this.appointmentStrings[i] = getAppointmentFormater().getVeryShortSummary(appointments[i]);
this.appointmentIndexStrings[i] = getRaplaLocale().formatNumber(i + 1);
}
}
private boolean isAllocatableSelected(JTreeTable table)
{
// allow folders to be selected
return isElementSelected(table, false);
}
private boolean isElementSelected(JTreeTable table, boolean allocatablesOnly)
{
int start = table.getSelectionModel().getMinSelectionIndex();
int end = table.getSelectionModel().getMaxSelectionIndex();
if (start >= 0)
{
for (int i = start; i <= end; i++)
{
TreePath path = table.getTree().getPathForRow(i);
if (path != null && (!allocatablesOnly || ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject() instanceof Allocatable))
return true;
}
}
return false;
}
public Set<Allocatable> getMarkedAllocatables()
{
return new HashSet<Allocatable>(getSelectedAllocatables(completeTable.getTree()));
}
protected Collection<Allocatable> getSelectedAllocatables(JTree tree)
{
// allow folders to be selected
Collection<?> selectedElementsIncludingChildren = getSelectedElementsIncludingChildren(tree);
List<Allocatable> allocatables = new ArrayList<Allocatable>();
for (Object obj:selectedElementsIncludingChildren)
{
if ( obj instanceof Allocatable)
{
allocatables.add(( Allocatable) obj);
}
}
return allocatables;
}
protected Collection<?> getSelectedElementsIncludingChildren(JTree tree)
{
TreePath[] paths = tree.getSelectionPaths();
List<Object> list = new LinkedList<Object>();
if ( paths == null)
{
return list;
}
for (TreePath p:paths)
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode) p.getLastPathComponent();
{
Object obj = node.getUserObject();
if (obj != null )
list.add(obj);
}
Enumeration<?> tt = node.children();
for(;tt.hasMoreElements();)
{
DefaultMutableTreeNode nodeChild = (DefaultMutableTreeNode) tt.nextElement();
Object obj = nodeChild.getUserObject();
if (obj != null )
{
list.add(obj);
}
}
}
return list;
}
protected void remove(Collection<Allocatable> elements)
{
Iterator<Allocatable> it = elements.iterator();
boolean bChanged = false;
while (it.hasNext())
{
Allocatable a = it.next();
if (mutableReservation.hasAllocated(a))
{
mutableReservation.removeAllocatable(a);
bChanged = true;
}
}
if (bChanged)
{
selectedModel.setAllocatables(getAllocated(), selectedTable.getTree());
}
fireAllocationsChanged();
}
protected void add(Collection<Allocatable> elements)
{
Iterator<Allocatable> it = elements.iterator();
boolean bChanged = false;
while (it.hasNext())
{
Allocatable a = it.next();
if (!mutableReservation.hasAllocated(a))
{
mutableReservation.addAllocatable(a);
bChanged = true;
}
}
if (bChanged)
{
selectedModel.setAllocatables(getAllocated(), selectedTable.getTree());
expandObjects(elements, selectedTable.getTree());
}
fireAllocationsChanged();
}
private Date findFirstStart(Collection<Appointment> appointments)
{
Date firstStart = null;
for (Appointment app: appointments)
if (firstStart == null || app.getStart().before(firstStart))
firstStart = app.getStart();
return firstStart;
}
private void updateButtons()
{
{
boolean enable = isElementSelected(completeTable, false);
calendarAction1.setEnabled(enable);
enable = enable && isAllocatableSelected(completeTable);
addAction.setEnabled(enable);
}
{
boolean enable = isElementSelected(selectedTable, false);
calendarAction2.setEnabled(enable);
enable = enable && isAllocatableSelected(selectedTable);
removeAction.setEnabled(enable);
}
}
class Listener extends MouseAdapter implements ListSelectionListener, ChangeListener
{
public void valueChanged(ListSelectionEvent e)
{
updateButtons();
}
public void mousePressed(MouseEvent me)
{
if (me.isPopupTrigger())
firePopup(me);
}
public void mouseReleased(MouseEvent me)
{
if (me.isPopupTrigger())
firePopup(me);
}
public void mouseClicked(MouseEvent evt)
{
if (evt.getClickCount() < 2)
return;
JTreeTable table = (JTreeTable) evt.getSource();
int row = table.rowAtPoint(new Point(evt.getX(), evt.getY()));
if (row < 0)
return;
Object obj = table.getValueAt(row, 0);
if (!(obj instanceof Allocatable))
return;
AllocatableChange commando;
if (table == completeTable)
commando = newAllocatableChange("add",completeTable);
else
commando = newAllocatableChange("remove",selectedTable);
commandHistory.storeAndExecute(commando);
}
public void stateChanged(ChangeEvent e) {
try {
ClassifiableFilterEdit filterUI = filter.getFilterUI();
if ( filterUI != null)
{
final ClassificationFilter[] filters = filterUI.getFilters();
calendarModel.setAllocatableFilter( filters);
completeModel.setAllocatables(getAllAllocatables(), completeTable.getTree());
//List<Appointment> appointments = Arrays.asList(mutableReservation.getAppointments());
// it is important to update all bindings, because a
updateBindings( null );
}
} catch (Exception ex) {
showException(ex, getComponent());
}
}
}
protected void firePopup(MouseEvent me)
{
Point p = new Point(me.getX(), me.getY());
JTreeTable table = ((JTreeTable) me.getSource());
int row = table.rowAtPoint(p);
int column = table.columnAtPoint(p);
Object selectedObject = null;
if (row >= 0 && column >= 0)
selectedObject = table.getValueAt(row, column);
//System.out.println("row " + row + " column " + column + " selected " + selectedObject);
showPopup(new PopupEvent(table, selectedObject, p));
}
public void showPopup(PopupEvent evt)
{
try
{
Point p = evt.getPoint();
Object selectedObject = evt.getSelectedObject();
JTreeTable table = ((JTreeTable) evt.getSource());
RaplaPopupMenu menu = new RaplaPopupMenu();
if (table == completeTable)
{
menu.add(new JMenuItem(addAction));
menu.add(new JMenuItem(calendarAction1));
}
else
{
menu.add(new JMenuItem(removeAction));
menu.add(new JMenuItem(calendarAction2));
}
String seperatorId = "ADD_REMOVE_SEPERATOR";
menu.add( new RaplaSeparator(seperatorId));
MenuContext menuContext = createMenuContext(p, selectedObject);
Collection<?> list = getSelectedAllocatables( table.getTree());
menuContext.setSelectedObjects(list);
RaplaMenu newMenu = new RaplaMenu("new");
newMenu.setText(getString("new"));
MenuFactory menuFactory = getService( MenuFactory.class);
((MenuFactoryImpl) menuFactory).addNew(newMenu, menuContext, null);
menuFactory.addObjectMenu(menu, menuContext, seperatorId);
newMenu.setEnabled( newMenu.getMenuComponentCount() > 0);
menu.insertAfterId(newMenu, seperatorId);
menu.show(table, p.x, p.y);
}
catch (RaplaException ex)
{
showException(ex, getComponent());
}
}
protected MenuContext createMenuContext(Point p, Object obj) {
MenuContext menuContext = new MenuContext(getContext(), obj, getComponent(), p);
return menuContext;
}
public void expandObjects(Collection<? extends Object> expandedNodes, JTree tree)
{
Set<Object> expandedObjects = new LinkedHashSet<Object>();
expandedObjects.addAll( expandedNodes);
// we need an enumeration, because we modife the set
Enumeration<?> enumeration = ((DefaultMutableTreeNode) tree.getModel().getRoot()).preorderEnumeration();
while (enumeration.hasMoreElements())
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumeration.nextElement();
Object userObject = node.getUserObject();
if (expandedObjects.contains(userObject))
{
expandedObjects.remove( userObject );
TreePath path = new TreePath(node.getPath());
while ( path != null)
{
tree.expandPath(path);
path = path.getParentPath();
}
}
}
}
static public void selectObjects(Collection<?> expandedNodes, JTree tree)
{
Enumeration<?> enumeration = ((DefaultMutableTreeNode) tree.getModel().getRoot()).preorderEnumeration();
List<TreePath> selectionPaths = new ArrayList<TreePath>();
Set<Object> alreadySelected = new HashSet<Object>();
while (enumeration.hasMoreElements())
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumeration.nextElement();
Iterator<?> it = expandedNodes.iterator();
while (it.hasNext())
{
Object userObject = node.getUserObject();
if (it.next().equals(userObject) && !alreadySelected.contains( userObject))
{
alreadySelected.add( userObject );
selectionPaths.add(new TreePath(node.getPath()));
}
}
}
tree.setSelectionPaths( selectionPaths.toArray(new TreePath[] {}));
}
class CompleteModel extends AllocatablesModel
{
public int getColumnCount()
{
return 2;
}
public boolean isCellEditable(Object node, int column)
{
return column > 0;
}
public Object getValueAt(Object node, int column)
{
return ((DefaultMutableTreeNode) node).getUserObject();
}
public String getColumnName(int column)
{
switch (column)
{
case 0:
return getString("selectable");
case 1:
return getString("selectable_on");
}
throw new IndexOutOfBoundsException();
}
public Class<?> getColumnClass(int column)
{
switch (column)
{
case 0:
return TreeTableModel.class;
case 1:
return Allocatable.class;
}
throw new IndexOutOfBoundsException();
}
}
class SelectedModel extends AllocatablesModel
{
public SelectedModel() {
super();
useCategorizations = false;
}
public int getColumnCount()
{
return 2;
}
public boolean isCellEditable(Object node, int column)
{
if (column == 1 && bWorkaround)
return true;
Object o = ((DefaultMutableTreeNode) node).getUserObject();
if (column == 1 && o instanceof Allocatable)
return true;
else
return false;
}
public Object getValueAt(Object node, int column)
{
Object o = ((DefaultMutableTreeNode) node).getUserObject();
if (o instanceof Allocatable)
{
switch (column)
{
case 0:
return o;
case 1:
return mutableReservation.getRestriction((Allocatable) o);
}
}
if (o instanceof DynamicType)
{
return o;
}
return o;
//throw new IndexOutOfBoundsException();
}
public void setValueAt(Object value, Object node, int column)
{
Object o = ((DefaultMutableTreeNode) node).getUserObject();
if (column == 1 && o instanceof Allocatable && value instanceof Appointment[])
{
Appointment[] restriction = mutableReservation.getRestriction((Allocatable) o);
Appointment[] newValue = (Appointment[]) value;
if (!Arrays.equals(restriction,newValue))
{
mutableReservation.setRestriction((Allocatable) o, newValue);
fireAllocationsChanged();
}
}
fireTreeNodesChanged(node, ((DefaultMutableTreeNode) node).getPath(), new int[] {}, new Object[] {});
}
public String getColumnName(int column)
{
switch (column)
{
case 0:
return getString("selected");
case 1:
return getString("selected_on");
}
throw new IndexOutOfBoundsException();
}
public Class<?> getColumnClass(int column)
{
switch (column)
{
case 0:
return TreeTableModel.class;
case 1:
return Appointment[].class;
}
throw new IndexOutOfBoundsException();
}
}
abstract class AllocatablesModel extends AbstractTreeTableModel
{
TreeModel treeModel;
boolean useCategorizations;
public AllocatablesModel()
{
super(new DefaultMutableTreeNode());
treeModel = new DefaultTreeModel((DefaultMutableTreeNode) super.getRoot());
useCategorizations = true;
}
// Types of the columns.
Collection<Allocatable> allocatables;
public void setAllocatables(Collection<Allocatable> allocatables)
{
this.allocatables = allocatables;
treeModel = getTreeFactory().createClassifiableModel( allocatables.toArray(Allocatable.ALLOCATABLE_ARRAY), useCategorizations);
DefaultMutableTreeNode root = (DefaultMutableTreeNode) getRoot();
int childCount = root.getChildCount();
int[] childIndices = new int[childCount];
Object[] children = new Object[childCount];
for (int i = 0; i < childCount; i++)
{
childIndices[i] = i;
children[i] = root.getChildAt(i);
}
fireTreeStructureChanged(root, root.getPath(), childIndices, children);
}
public void setAllocatables(Collection<Allocatable> allocatables, JTree tree)
{
this.allocatables = allocatables;
Collection<Object> expanded = new HashSet<Object>();
for (int i = 0; i < tree.getRowCount(); i++)
{
if (tree.isExpanded(i))
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getPathForRow(i).getLastPathComponent();
expanded.add(node.getUserObject());
}
}
setAllocatables(allocatables);
expandNodes(expanded, tree);
}
void expandNodes(Collection<Object> expanded, JTree tree)
{
if (expanded.size() == 0)
return;
Collection<Object> expandedToRemove = new LinkedHashSet<Object>( expanded);
for (int i = 0; i < tree.getRowCount(); i++)
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getPathForRow(i).getLastPathComponent();
Object userObject = node.getUserObject();
if (expandedToRemove.contains(userObject))
{
expandedToRemove.remove( userObject );
tree.expandRow(i);
}
}
}
public Collection<Allocatable> getAllocatables()
{
return allocatables;
}
public void treeDidChange()
{
DefaultMutableTreeNode root = (DefaultMutableTreeNode) getRoot();
int childCount = root.getChildCount();
int[] childIndices = new int[childCount];
Object[] children = new Object[childCount];
for (int i = 0; i < childCount; i++)
{
childIndices[i] = i;
children[i] = root.getChildAt(i);
}
fireTreeNodesChanged(root, root.getPath(), childIndices, children);
}
public Object getRoot()
{
return treeModel.getRoot();
}
public int getChildCount(Object node)
{
return treeModel.getChildCount(node);
}
public Object getChild(Object node, int i)
{
return treeModel.getChild(node, i);
}
}
class RestrictionCellRenderer extends DefaultTableCellRenderer
{
private static final long serialVersionUID = 1L;
Object newValue;
JButton button = new JButton();
public void setValue(Object value)
{
newValue = value;
super.setValue("");
}
public void setBounds(int x, int y, int width, int heigth)
{
super.setBounds(x, y, width, heigth);
button.setBounds(x, y, width, heigth);
}
public void paint(Graphics g)
{
Object value = newValue;
if (value instanceof Appointment[])
{
super.paint(g);
java.awt.Font f = g.getFont();
button.paint(g);
g.setFont(f);
paintRestriction(g, (Appointment[]) value, this);
}
}
}
class AllocationCellRenderer extends DefaultTableCellRenderer
{
private static final long serialVersionUID = 1L;
Object newValue;
public void setValue(Object value)
{
newValue = value;
super.setValue("");
}
public void paint(Graphics g)
{
Object value = newValue;
super.paint(g);
if (value instanceof Allocatable)
{
paintAllocation(g, (Allocatable) value, this);
}
}
}
class RaplaToolTipRenderer implements TableToolTipRenderer
{
public String getToolTipText(JTable table, int row, int column)
{
Object value = table.getValueAt(row, column);
return getInfoFactory().getToolTip(value);
}
}
private int indexOf(Appointment appointment)
{
for (int i = 0; i < appointments.length; i++)
if (appointments[i].equals(appointment))
return i;
return -1;
}
// returns if the user is allowed to allocate the passed allocatable
private boolean isAllowed(Allocatable allocatable, Appointment appointment)
{
Date start = appointment.getStart();
Date end = appointment.getMaxEnd();
Date today = getQuery().today();
return allocatable.canAllocate(user, start, end, today);
}
class AllocationRendering
{
boolean conflictingAppointments[] = new boolean[appointments.length]; // stores the temp conflicting appointments
int conflictCount = 0; // temp value for conflicts
int permissionConflictCount = 0; // temp value for conflicts that are the result of denied permissions
}
// calculates the number of conflicting appointments for this allocatable
private AllocationRendering calcConflictingAppointments(Allocatable allocatable)
{
AllocationRendering result = new AllocationRendering();
String annotation = allocatable.getAnnotation( ResourceAnnotations.KEY_CONFLICT_CREATION, null);
boolean holdBackConflicts = annotation != null && annotation.equals( ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE);
for (int i = 0; i < appointments.length; i++)
{
Appointment appointment = appointments[i];
Collection<Appointment> collection = allocatableBindings.get( allocatable);
boolean conflictingAppointments = collection != null && collection.contains( appointment);
result.conflictingAppointments[i] = false;
if ( conflictingAppointments )
{
if ( ! holdBackConflicts)
{
result.conflictingAppointments[i] = true;
result.conflictCount++;
}
}
else if (!isAllowed(allocatable, appointment) )
{
if ( ! holdBackConflicts)
{
result.conflictingAppointments[i] = true;
result.conflictCount++;
}
result.permissionConflictCount++;
}
}
return result;
}
private void paintAllocation(Graphics g, Allocatable allocatable, JComponent c)
{
AllocationRendering a = calcConflictingAppointments(allocatable);
if (appointments.length == 0)
{
}
else if (a.conflictCount == 0)
{
g.setColor(Color.green);
g.drawString(getString("every_appointment"), 2, c.getHeight() - 4);
return;
} /*
* else if (conflictCount == appointments.length) {
* g.setColor(Color.red);
* g.drawString(getString("zero_appointment"),2,c.getHeight()-4);
* return;
* }
*/
int x = 2;
Insets insets = c.getInsets();
FontMetrics fm = g.getFontMetrics();
for (int i = 0; i < appointments.length; i++)
{
if (a.conflictingAppointments[i])
continue;
x = paintApp(c, g, fm, i, insets, x);
}
}
private void paintRestriction(Graphics g, Appointment[] restriction, JComponent c)
{
if (restriction.length == 0)
{
g.drawString(getString("every_appointment"), 2, c.getHeight() - 4);
return;
}
int x = 0;
Insets insets = c.getInsets();
FontMetrics fm = g.getFontMetrics();
int i=0;
for (Appointment app:appointments)
{
for (Appointment res:restriction)
{
if (res.equals(app))
{
x = paintApp(c, g, fm, i, insets, x);
}
}
i++;
}
}
private int paintApp(Component c, Graphics g, FontMetrics fm, int index, Insets insets, int x)
{
int xborder = 4;
int yborder = 1;
int width = fm.stringWidth(appointmentIndexStrings[index]);
x += xborder;
g.setColor(AWTColorUtil.getAppointmentColor(index));
g.fillRoundRect(x, insets.top, width, c.getHeight() - insets.top - insets.bottom - yborder * 2, 4, 4);
g.setColor(c.getForeground());
g.drawRoundRect(x - 1, insets.top, width + 1, c.getHeight() - insets.top - insets.bottom - yborder * 2, 4, 4);
g.drawString(appointmentIndexStrings[index], x, c.getHeight() - yborder - fm.getDescent());
x += width;
x += 2;
int textWidth = fm.stringWidth(appointmentStrings[index]);
g.drawString(appointmentStrings[index], x, c.getHeight() - fm.getDescent());
x += textWidth;
x += xborder;
return x;
}
class RestrictionTextField extends JTextField
{
private static final long serialVersionUID = 1L;
Object newValue;
public void setValue(Object value)
{
newValue = value;
}
public void paint(Graphics g)
{
Object value = newValue;
super.paint(g);
if (value instanceof Appointment[])
{
paintRestriction(g, (Appointment[]) value, this);
}
}
}
class AllocationTextField extends JTextField
{
private static final long serialVersionUID = 1L;
Object newValue;
public void setValue(Object value)
{
newValue = value;
}
public void paint(Graphics g)
{
Object value = newValue;
super.paint(g);
if (value instanceof Allocatable)
{
paintAllocation(g, (Allocatable) value, this);
}
}
}
class AppointmentCellEditor extends DefaultCellEditor implements MouseListener, KeyListener, PopupMenuListener, ActionListener
{
private static final long serialVersionUID = 1L;
JPopupMenu menu = new JPopupMenu();
RestrictionTextField editingComponent;
boolean bStopEditingCalled = false; /*
* We need this variable
* to check if
* stopCellEditing
* was already called.
*/
DefaultMutableTreeNode selectedNode;
int selectedColumn = 0;
Appointment[] restriction;
public AppointmentCellEditor(RestrictionTextField textField)
{
super(textField);
editingComponent = (RestrictionTextField) this.getComponent();
editingComponent.setEditable(false);
editingComponent.addMouseListener(this);
editingComponent.addKeyListener(this);
menu.addPopupMenuListener(this);
}
public void mouseReleased(MouseEvent evt)
{
showComp();
}
public void mousePressed(MouseEvent evt)
{
}
public void mouseClicked(MouseEvent evt)
{
}
public void mouseEntered(MouseEvent evt)
{
}
public void mouseExited(MouseEvent evt)
{
}
public void keyPressed(KeyEvent evt)
{
}
public void keyTyped(KeyEvent evt)
{
}
public void keyReleased(KeyEvent evt)
{
showComp();
}
/**
* This method is performed, if the user clicks on a menu item of the
* <code>JPopupMenu</code> in order to select invividual appointments
* for a resource.
*
* Changed in Rapla 1.4
*/
public void actionPerformed(ActionEvent evt)
{
// Refresh the selected appointments for the resource which is being
// edited
int oldRestrictionLength = restriction.length;
Appointment[] oldRestriction = restriction;
Object selectedObject = selectedNode.getUserObject();
Object source = evt.getSource();
if ( source == selectedMenu)
{
AllocationRendering allocBinding = null;
if (selectedObject instanceof Allocatable)
{
Allocatable allocatable = (Allocatable) selectedObject;
allocBinding = calcConflictingAppointments(allocatable);
}
List<Appointment> newRestrictions = new ArrayList<Appointment>();
for (int i = 0; i < appointments.length; i++)
{
boolean conflicting = (allocBinding != null && allocBinding.conflictingAppointments[i]);
( appointmentList.get(i)).setSelected(!conflicting);
if ( !conflicting)
{
newRestrictions.add(appointments[i]);
}
}
restriction = newRestrictions.toArray( Appointment.EMPTY_ARRAY);
// Refresh the state of the "every Appointment" menu item
allMenu.setSelected(restriction.length == 0);
selectedMenu.setSelected(restriction.length != 0);
}
else if (source instanceof javax.swing.JCheckBoxMenuItem)
{
// Refresh the state of the "every Appointment" menu item
updateRestriction(Integer.valueOf(evt.getActionCommand()).intValue());
allMenu.setSelected(restriction.length == 0);
selectedMenu.setSelected(restriction.length != 0);
}
else
{
updateRestriction(Integer.valueOf(evt.getActionCommand()).intValue());
// "every Appointment" has been selected, stop editing
fireEditingStopped();
selectedTable.requestFocus();
}
if (oldRestrictionLength != restriction.length) {
RestrictionChange commando = new RestrictionChange( oldRestriction, restriction, selectedNode, selectedColumn);
commandHistory.storeAndExecute(commando);
}
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
bStopEditingCalled = false;
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
{
if (!bStopEditingCalled)
{
AppointmentCellEditor.super.stopCellEditing();
}
}
public void popupMenuCanceled(PopupMenuEvent e)
{
// BUGID: 4234793
// This method is never called
}
Map<Integer,JMenuItem> appointmentList = new HashMap<Integer, JMenuItem>();
JMenuItem allMenu = new JRadioButtonMenuItem();
JMenuItem selectedMenu = new JRadioButtonMenuItem();
/**
* This method builds and shows the JPopupMenu for the appointment selection
*
* Changed in Rapla 1.4
*/
private void showComp()
{
Object selectedObject = selectedNode.getUserObject();
AllocationRendering allocBinding = null;
if (selectedObject instanceof Allocatable)
{
Allocatable allocatable = (Allocatable) selectedObject;
allocBinding = calcConflictingAppointments(allocatable);
}
Icon conflictIcon = getI18n().getIcon("icon.allocatable_taken");
allMenu.setText(getString("every_appointment"));
selectedMenu.setText(getString("selected_on"));
appointmentList.clear();
menu.removeAll();
allMenu.setActionCommand("-1");
allMenu.addActionListener(this);
selectedMenu.setActionCommand("-2");
selectedMenu.addActionListener( this );
selectedMenu.setUI(new StayOpenRadioButtonMenuItemUI());
menu.add(new JMenuItem(getString("close")));
menu.add(new JSeparator());
menu.add(allMenu);
menu.add(selectedMenu);
menu.add(new JSeparator());
for (int i = 0; i < appointments.length; i++)
{
JMenuItem item = new JCheckBoxMenuItem();
// Prevent the JCheckboxMenuItem from closing the JPopupMenu
item.setUI(new StayOpenCheckBoxMenuItemUI());
// set conflicting icon if appointment causes conflicts
String appointmentSummary = getAppointmentFormater().getShortSummary(appointments[i]);
if (allocBinding != null && allocBinding.conflictingAppointments[i])
{
item.setText((i + 1) + ": " + appointmentSummary);
item.setIcon(conflictIcon);
}
else
{
item.setText((i + 1) + ": " + appointmentSummary);
}
appointmentList.put(i, item);
item.setBackground(AWTColorUtil.getAppointmentColor(i));
item.setActionCommand(String.valueOf(i));
item.addActionListener(this);
menu.add(item);
}
for (int i = 0; i < appointments.length; i++)
{
appointmentList.get(i).setSelected(false);
}
Appointment[] apps = restriction;
allMenu.setSelected(apps.length == 0);
selectedMenu.setSelected(apps.length > 0);
for (int i = 0; i < apps.length; i++)
{
// System.out.println("Select " + indexOf(apps[i]));
appointmentList.get(indexOf(apps[i])).setSelected(true);
}
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension menuSize = menu.getPreferredSize();
Point location = editingComponent.getLocationOnScreen();
int diffx = Math.min(0, screenSize.width - (location.x + menuSize.width));
int diffy = Math.min(0, screenSize.height - (location.y + menuSize.height));
menu.show(editingComponent, diffx, diffy);
}
private void setRestriction(Appointment[] restriction)
{
this.restriction = restriction;
}
/** select or deselect the appointment at the given index */
private void updateRestriction(int index)
{
if (index == -1)
{
restriction = Appointment.EMPTY_ARRAY;
}
else if (index == -2)
{
restriction = appointments;
}
else
{
Collection<Appointment> newAppointments = new ArrayList<Appointment>();
// get the selected appointments
// add all previous selected appointments, except the appointment that
// is clicked
for (int i = 0; i < restriction.length; i++)
if (!restriction[i].equals(appointments[index]))
{
newAppointments.add(restriction[i]);
}
// If the clicked appointment was selected then deselect
// otherwise select ist
if (!containsAppointment(appointments[index]))
newAppointments.add(appointments[index]);
restriction = newAppointments.toArray(Appointment.EMPTY_ARRAY);
}
}
private boolean containsAppointment(Appointment appointment)
{
for (int i = 0; i < restriction.length; i++)
if (restriction[i].equals(appointment))
return true;
return false;
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
{
Component component = super.getTableCellEditorComponent(table, value, isSelected, row, column);
if (value instanceof Appointment[])
{
setRestriction((Appointment[]) value);
((RestrictionTextField) component).setText("");
}
((RestrictionTextField) component).setValue(value);
// Workaround for JDK 1.4 Bug ID: 4234793
// We have to change the table-model after cell-editing stopped
this.selectedNode = (DefaultMutableTreeNode) selectedTable.getTree().getPathForRow(row).getLastPathComponent();
this.selectedColumn = column;
return component;
}
public Object getCellEditorValue()
{
return restriction;
}
public boolean shouldSelectCell(EventObject event)
{
return true;
}
public boolean isCellEditable(EventObject event)
{
return true;
}
public boolean stopCellEditing()
{
bStopEditingCalled = true;
boolean bResult = super.stopCellEditing();
menu.setVisible(false);
return bResult;
}
}
class AppointmentCellEditor2 extends DefaultCellEditor implements MouseListener, KeyListener, PopupMenuListener, ActionListener
{
private static final long serialVersionUID = 1L;
JPopupMenu menu = new JPopupMenu();
AllocationTextField editingComponent;
boolean bStopEditingCalled = false; /*
* We need this variable
* to check if
* stopCellEditing
* was already called.
*/
DefaultMutableTreeNode selectedNode;
int selectedColumn = 0;
Appointment[] restriction;
public AppointmentCellEditor2(AllocationTextField textField)
{
super(textField);
editingComponent = (AllocationTextField) this.getComponent();
editingComponent.setEditable(false);
editingComponent.addMouseListener(this);
editingComponent.addKeyListener(this);
menu.addPopupMenuListener(this);
}
public void mouseReleased(MouseEvent evt)
{
showComp();
}
public void mousePressed(MouseEvent evt)
{
}
public void mouseClicked(MouseEvent evt)
{
}
public void mouseEntered(MouseEvent evt)
{
}
public void mouseExited(MouseEvent evt)
{
}
public void keyPressed(KeyEvent evt)
{
}
public void keyTyped(KeyEvent evt)
{
}
public void keyReleased(KeyEvent evt)
{
showComp();
}
/**
* This method is performed, if the user clicks on a menu item of the
* <code>JPopupMenu</code> in order to select invividual appointments
* for a resource.
*
*/
public void actionPerformed(ActionEvent evt)
{
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
bStopEditingCalled = false;
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
{
if (!bStopEditingCalled)
{
AppointmentCellEditor2.super.stopCellEditing();
}
}
public void popupMenuCanceled(PopupMenuEvent e)
{
// BUGID: 4234793
// This method is never called
}
/**
* This method builds and shows the JPopupMenu for the appointment selection
*
*/
private void showComp()
{
Object selectedObject = selectedNode.getUserObject();
AllocationRendering allocBinding;
if (selectedObject != null && selectedObject instanceof Allocatable)
{
Allocatable allocatable = (Allocatable) selectedObject;
allocBinding = calcConflictingAppointments(allocatable);
}
else
{
return;
}
menu.removeAll();
boolean test = true;
for (int i = 0; i < appointments.length; i++)
{
if (allocBinding.conflictingAppointments[i])
test = false;
}
if ( test)
{
return;
}
else
{
for (int i = 0; i < appointments.length; i++)
{
if (allocBinding.conflictingAppointments[i])
continue;
JMenuItem item = new JMenuItem();
// Prevent the JCheckboxMenuItem from closing the JPopupMenu
// set conflicting icon if appointment causes conflicts
String appointmentSummary = getAppointmentFormater().getShortSummary(appointments[i]);
if (allocBinding.conflictingAppointments[i])
{
item.setText((i + 1) + ": " + appointmentSummary);
Icon conflictIcon = getI18n().getIcon("icon.allocatable_taken");
item.setIcon(conflictIcon);
}
else
{
item.setText((i + 1) + ": " + appointmentSummary);
}
item.setBackground(AWTColorUtil.getAppointmentColor(i));
menu.add(item);
}
}
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension menuSize = menu.getPreferredSize();
Point location = editingComponent.getLocationOnScreen();
int diffx = Math.min(0, screenSize.width - (location.x + menuSize.width));
int diffy = Math.min(0, screenSize.height - (location.y + menuSize.height));
menu.show(editingComponent, diffx, diffy);
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
{
Component component = super.getTableCellEditorComponent(table, value, isSelected, row, column);
if (value instanceof Allocatable)
{
((AllocationTextField) component).setText("");
}
((AllocationTextField) component).setValue(value);
// Workaround for JDK 1.4 Bug ID: 4234793
// We have to change the table-model after cell-editing stopped
this.selectedNode = (DefaultMutableTreeNode) completeTable.getTree().getPathForRow(row).getLastPathComponent();
this.selectedColumn = column;
return component;
}
public Object getCellEditorValue()
{
return restriction;
}
public boolean shouldSelectCell(EventObject event)
{
return true;
}
public boolean isCellEditable(EventObject event)
{
return true;
}
public boolean stopCellEditing()
{
bStopEditingCalled = true;
boolean bResult = super.stopCellEditing();
menu.setVisible(false);
return bResult;
}
}
class AllocationTreeCellRenderer extends DefaultTreeCellRenderer
{
private static final long serialVersionUID = 1L;
Icon conflictIcon;
Icon freeIcon;
Icon notAlwaysAvailableIcon;
Icon personIcon;
Icon personNotAlwaysAvailableIcon;
Icon forbiddenIcon;
boolean checkRestrictions;
public AllocationTreeCellRenderer(boolean checkRestrictions)
{
forbiddenIcon = getI18n().getIcon("icon.no_perm");
conflictIcon = getI18n().getIcon("icon.allocatable_taken");
freeIcon = getI18n().getIcon("icon.allocatable_available");
notAlwaysAvailableIcon = getI18n().getIcon("icon.allocatable_not_always_available");
personIcon = getI18n().getIcon("icon.tree.persons");
personNotAlwaysAvailableIcon = getI18n().getIcon("icon.tree.person_not_always_available");
this.checkRestrictions = checkRestrictions;
setOpenIcon(getI18n().getIcon("icon.folder"));
setClosedIcon(getI18n().getIcon("icon.folder"));
setLeafIcon(freeIcon);
}
public Icon getAvailableIcon(Allocatable allocatable)
{
if (allocatable.isPerson())
return personIcon;
else
return freeIcon;
}
public Icon getNotAlwaysAvailableIcon(Allocatable allocatable)
{
if (allocatable.isPerson())
return personNotAlwaysAvailableIcon;
else
return notAlwaysAvailableIcon;
}
private Icon getIcon(Allocatable allocatable)
{
AllocationRendering allocBinding = calcConflictingAppointments(allocatable);
if (allocBinding.conflictCount == 0)
{
return getAvailableIcon(allocatable);
}
else if (allocBinding.conflictCount == appointments.length)
{
if (allocBinding.conflictCount == allocBinding.permissionConflictCount)
{
if (!checkRestrictions)
{
return forbiddenIcon;
}
}
else
{
return conflictIcon;
}
}
else if (!checkRestrictions)
{
return getNotAlwaysAvailableIcon(allocatable);
}
for (int i = 0; i < appointments.length; i++)
{
Appointment appointment = appointments[i];
if (mutableReservation.hasAllocated(allocatable, appointment) && !hasPermissionToAllocate(appointment, allocatable))
{
return forbiddenIcon;
}
}
if (allocBinding.permissionConflictCount - allocBinding.conflictCount == 0)
{
return getAvailableIcon(allocatable);
}
Appointment[] restriction = mutableReservation.getRestriction(allocatable);
if (restriction.length == 0)
{
return conflictIcon;
}
else
{
boolean conflict = false;
for (int i = 0; i < restriction.length; i++)
{
Collection<Appointment> list = allocatableBindings.get( allocatable);
if (list.contains( restriction[i]) )
{
conflict = true;
break;
}
}
if (conflict)
return conflictIcon;
else
return getNotAlwaysAvailableIcon(allocatable);
}
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus)
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
Object nodeInfo = node.getUserObject();
Locale locale = getI18n().getLocale();
if (nodeInfo != null && nodeInfo instanceof Named)
{
value = ((Named) nodeInfo).getName(locale);
}
if (leaf)
{
if (nodeInfo instanceof Allocatable)
{
Allocatable allocatable = (Allocatable) nodeInfo;
setLeafIcon(getIcon(allocatable));
Classification classification = allocatable.getClassification();
if ( classification.getType().getAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT_PLANNING) != null)
{
value = classification.getNamePlaning(locale);
}
}
}
Component result = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
return result;
}
}
public boolean hasPermissionToAllocate(Appointment appointment,
Allocatable allocatable) {
Date today = getQuery().today();
User workingUser;
try {
workingUser = getUser();
} catch (RaplaException ex) {
getLogger().error("Can't get permissions!", ex);
return false;
}
if (originalReservation == null)
{
return allocatable.canAllocate(workingUser, appointment.getStart(), appointment.getMaxEnd(),today);
}
else
{
return FacadeImpl.hasPermissionToAllocate(workingUser, appointment, allocatable, originalReservation, today);
}
}
class AllocatableAction extends AbstractAction
{
private static final long serialVersionUID = 1L;
String command;
AllocatableAction(String command)
{
this.command = command;
if (command.equals("add"))
{
putValue(NAME, getString("add"));
putValue(SMALL_ICON, getIcon("icon.arrow_right"));
}
if (command.equals("remove"))
{
putValue(NAME, getString("remove"));
putValue(SMALL_ICON, getIcon("icon.arrow_left"));
}
if (command.equals("calendar1") || command.equals("calendar2"))
{
putValue(NAME, getString("calendar"));
putValue(SMALL_ICON, getIcon("icon.calendar"));
}
}
public void actionPerformed(ActionEvent evt)
{
if (command.equals("add")) {
AllocatableChange commando = newAllocatableChange(command,completeTable);
commandHistory.storeAndExecute(commando);
}
if (command.equals("remove")) {
AllocatableChange commando = newAllocatableChange(command,selectedTable);
commandHistory.storeAndExecute(commando);
}
if (command.indexOf("calendar") >= 0)
{
JTreeTable tree = (command.equals("calendar1") ? completeTable : selectedTable);
CalendarAction calendarAction = new CalendarAction(getContext(), getComponent(), calendarModel);
calendarAction.changeObjects(new ArrayList<Object>(getSelectedAllocatables(tree.getTree())));
Collection<Appointment> appointments = Arrays.asList( AllocatableSelection.this.appointments);
calendarAction.setStart(findFirstStart(appointments));
calendarAction.actionPerformed(evt);
}
}
}
/**
* This class is used to prevent the JPopupMenu from disappearing when a
* <code>JCheckboxMenuItem</code> is clicked.
*
* @since Rapla 1.4
* @see http://forums.oracle.com/forums/thread.jspa?messageID=5724401#5724401
*/
class StayOpenCheckBoxMenuItemUI extends BasicCheckBoxMenuItemUI
{
protected void doClick(MenuSelectionManager msm)
{
menuItem.doClick(0);
}
}
class StayOpenRadioButtonMenuItemUI extends BasicRadioButtonMenuItemUI
{
protected void doClick(MenuSelectionManager msm)
{
menuItem.doClick(0);
}
}
private AllocatableChange newAllocatableChange(String command,JTreeTable treeTable)
{
Collection<Allocatable> elements = getSelectedAllocatables( treeTable.getTree());
return new AllocatableChange(command, elements);
}
public static Color darken(Color color, int i) {
int newBlue = Math.max( color.getBlue() - i, 0);
int newRed = Math.max( color.getRed() - i, 0);
int newGreen = Math.max( color.getGreen() - i, 0);
return new Color( newRed, newGreen,newBlue, color.getAlpha());
}
/**
* This Class collects any information changes done to selected or deselected allocatables.
* This is where undo/redo for the Allocatable-selection at the bottom of the edit view
* is realized.
* @author Jens Fritz
*
*/
//Erstellt und bearbeitet von Matthias Both und Jens Fritz
public class AllocatableChange implements CommandUndo<RuntimeException> {
String command;
Collection<Allocatable> elements;
public AllocatableChange(String command,
Collection<Allocatable> elements) {
this.command = command;
List<Allocatable> changed = new ArrayList<Allocatable>();
boolean addOrRemove;
if (command.equals("add"))
addOrRemove = false;
else
addOrRemove = true;
Iterator<Allocatable> it = elements.iterator();
while (it.hasNext()) {
Allocatable a = it.next();
if (mutableReservation.hasAllocated(a) == addOrRemove) {
changed.add(a);
}
}
this.elements = changed;
}
public boolean execute() {
if (command.equals("add"))
add(elements);
else
remove(elements);
return true;
}
public boolean undo() {
if (command.equals("add"))
remove(elements);
else
add(elements);
return true;
}
public String getCommandoName()
{
return getString(command) + " " + getString("resource");
}
}
/**
* This Class collects any information of changes done to the exceptions
* of an selected allocatable.
* This is where undo/redo for the Allocatable-exceptions at the bottom of the edit view
* is realized.
* @author Jens Fritz
*
*/
//Erstellt von Matthias Both
public class RestrictionChange implements CommandUndo<RuntimeException> {
Appointment[] oldRestriction;
Appointment[] newRestriction;
DefaultMutableTreeNode selectedNode;
int selectedColumn;
public RestrictionChange(Appointment[] old, Appointment[] newOne,
DefaultMutableTreeNode selectedNode, int selectedColummn) {
this.oldRestriction = old;
this.newRestriction = newOne;
this.selectedNode = selectedNode;
this.selectedColumn = selectedColummn;
}
public boolean execute() {
selectedModel.setValueAt(newRestriction, selectedNode,
selectedColumn);
return true;
}
public boolean undo() {
selectedModel.setValueAt(oldRestriction, selectedNode,
selectedColumn);
return true;
}
public String getCommandoName()
{
return getString("change") + " " + getString("constraints");
}
}
} | 04900db4-clienttest | src/org/rapla/gui/internal/edit/reservation/AllocatableSelection.java | Java | gpl3 | 64,972 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.reservation;
import java.awt.Component;
import java.awt.Container;
import java.awt.Point;
import java.awt.datatransfer.StringSelection;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.Icon;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.iolayer.IOInterface;
import org.rapla.components.util.Command;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.components.util.undo.CommandUndo;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.domain.Allocatable;
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.facade.CalendarSelectionModel;
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.ReservationCheck;
import org.rapla.gui.ReservationController;
import org.rapla.gui.ReservationEdit;
import org.rapla.gui.internal.common.RaplaClipboard;
import org.rapla.gui.internal.edit.DeleteUndo;
import org.rapla.gui.internal.edit.SaveUndo;
import org.rapla.gui.internal.view.HTMLInfo.Row;
import org.rapla.gui.internal.view.ReservationInfoUI;
import org.rapla.gui.toolkit.DialogUI;
public class ReservationControllerImpl extends RaplaGUIComponent implements ModificationListener, ReservationController
{
/** We store all open ReservationEditWindows with their reservationId
* in a map, to lookup if the reservation is already beeing edited.
That prevents editing the same Reservation in different windows
*/
Collection<ReservationEditImpl> editWindowList = new ArrayList<ReservationEditImpl>();
public ReservationControllerImpl(RaplaContext sm)
{
super(sm);
getUpdateModule().addModificationListener(this);
}
void addReservationEdit(ReservationEdit editWindow) {
editWindowList.add((ReservationEditImpl)editWindow);
}
void removeReservationEdit(ReservationEdit editWindow) {
editWindowList.remove(editWindow);
}
public ReservationEdit edit(Reservation reservation) throws RaplaException {
return startEdit(reservation,null);
}
public ReservationEdit edit(AppointmentBlock appointmentBlock)throws RaplaException {
return startEdit(appointmentBlock.getAppointment().getReservation(), appointmentBlock);
}
public ReservationEdit[] getEditWindows() {
return editWindowList.toArray( new ReservationEdit[] {});
}
private ReservationEditImpl newEditWindow() throws RaplaException {
ReservationEditImpl c = new ReservationEditImpl(getContext());
return c;
}
private ReservationEdit startEdit(Reservation reservation,AppointmentBlock appointmentBlock)
throws RaplaException {
// Lookup if the reservation is already beeing edited
ReservationEditImpl c = null;
Iterator<ReservationEditImpl> it = editWindowList.iterator();
while (it.hasNext()) {
c = it.next();
if (c.getReservation().isIdentical(reservation))
break;
else
c = null;
}
if (c != null) {
c.frame.requestFocus();
c.frame.toFront();
} else {
c = newEditWindow();
// only is allowed to exchange allocations
c.editReservation(reservation, appointmentBlock);
if ( !canModify( reservation) )
{
c.deleteButton.setEnabled( false);
disableComponentAndAllChildren(c.appointmentEdit.getComponent());
disableComponentAndAllChildren(c.reservationInfo.getComponent());
}
}
return c;
}
static void disableComponentAndAllChildren(Container component) {
component.setEnabled( false );
Component[] components = component.getComponents();
for ( int i=0; i< components.length; i++)
{
if ( components[i] instanceof Container) {
disableComponentAndAllChildren( (Container) components[i] );
}
}
}
public void deleteBlocks(Collection<AppointmentBlock> blockList,
Component parent, Point point) throws RaplaException
{
DialogUI dlg = getInfoFactory().createDeleteDialog(blockList.toArray(), parent);
dlg.start();
if (dlg.getSelectedIndex() != 0)
return;
Set<Appointment> appointmentsToRemove = new LinkedHashSet<Appointment>();
HashMap<Appointment,List<Date>> exceptionsToAdd = new LinkedHashMap<Appointment,List<Date>>();
HashMap<Reservation,Integer> appointmentsRemoved = new LinkedHashMap<Reservation,Integer>();
Set<Reservation> reservationsToRemove = new LinkedHashSet<Reservation>();
for ( AppointmentBlock block: blockList)
{
Appointment appointment = block.getAppointment();
Date from = new Date(block.getStart());
Repeating repeating = appointment.getRepeating();
boolean exceptionsAdded = false;
if ( repeating != null)
{
List<Date> dateList = exceptionsToAdd.get( appointment );
if ( dateList == null)
{
dateList = new ArrayList<Date>();
exceptionsToAdd.put( appointment,dateList);
}
dateList.add(from);
if ( isNotEmptyWithExceptions(appointment, dateList))
{
exceptionsAdded = true;
}
else
{
exceptionsToAdd.remove( appointment);
}
}
if (!exceptionsAdded)
{
boolean added = appointmentsToRemove.add(appointment);
if ( added)
{
Reservation reservation = appointment.getReservation();
Integer count = appointmentsRemoved.get(reservation);
if ( count == null)
{
count = 0;
}
count++;
appointmentsRemoved.put( reservation, count);
}
}
}
for (Reservation reservation: appointmentsRemoved.keySet())
{
Integer count = appointmentsRemoved.get( reservation);
Appointment[] appointments = reservation.getAppointments();
if ( count == appointments.length)
{
reservationsToRemove.add( reservation);
for (Appointment appointment:appointments)
{
appointmentsRemoved.remove(appointment);
}
}
}
DeleteBlocksCommand command = new DeleteBlocksCommand(reservationsToRemove, appointmentsToRemove, exceptionsToAdd);
CommandHistory commanHistory = getModification().getCommandHistory();
commanHistory.storeAndExecute( command);
}
class DeleteBlocksCommand extends DeleteUndo<Reservation>
{
Set<Reservation> reservationsToRemove;
Set<Appointment> appointmentsToRemove;
Map<Appointment, List<Date>> exceptionsToAdd;
private Map<Appointment,Allocatable[]> allocatablesRemoved = new HashMap<Appointment,Allocatable[]>();
private Map<Appointment,Reservation> parentReservations = new HashMap<Appointment,Reservation>();
public DeleteBlocksCommand(Set<Reservation> reservationsToRemove, Set<Appointment> appointmentsToRemove, Map<Appointment, List<Date>> exceptionsToAdd) {
super( ReservationControllerImpl.this.getContext(),reservationsToRemove);
this.reservationsToRemove = reservationsToRemove;
this.appointmentsToRemove = appointmentsToRemove;
this.exceptionsToAdd = exceptionsToAdd;
}
public boolean execute() throws RaplaException {
HashMap<Reservation,Reservation> toUpdate = new LinkedHashMap<Reservation,Reservation>();
allocatablesRemoved.clear();
for (Appointment appointment:appointmentsToRemove)
{
Reservation reservation = appointment.getReservation();
if ( reservationsToRemove.contains( reservation))
{
continue;
}
parentReservations.put(appointment, reservation);
Reservation mutableReservation= toUpdate.get(reservation);
if ( mutableReservation == null)
{
mutableReservation = getModification().edit( reservation);
toUpdate.put( reservation, mutableReservation);
}
Allocatable[] restrictedAllocatables = mutableReservation.getRestrictedAllocatables(appointment);
mutableReservation.removeAppointment( appointment);
allocatablesRemoved.put( appointment, restrictedAllocatables);
}
for (Appointment appointment:exceptionsToAdd.keySet())
{
Reservation reservation = appointment.getReservation();
if ( reservationsToRemove.contains( reservation))
{
continue;
}
Reservation mutableReservation= toUpdate.get(reservation);
if ( mutableReservation == null)
{
mutableReservation = getModification().edit( reservation);
toUpdate.put( reservation, mutableReservation);
}
Appointment found = mutableReservation.findAppointment( appointment);
if ( found != null)
{
Repeating repeating = found.getRepeating();
if ( repeating != null)
{
List<Date> list = exceptionsToAdd.get( appointment);
for (Date exception: list)
{
repeating.addException( exception);
}
}
}
}
Reservation[] updateArray = toUpdate.values().toArray(Reservation.RESERVATION_ARRAY);
Reservation[] removeArray = reservationsToRemove.toArray( Reservation.RESERVATION_ARRAY);
getModification().storeAndRemove(updateArray, removeArray);
return true;
}
public boolean undo() throws RaplaException {
if (!super.undo())
{
return false;
}
HashMap<Reservation,Reservation> toUpdate = new LinkedHashMap<Reservation,Reservation>();
for (Appointment appointment:appointmentsToRemove)
{
Reservation reservation = parentReservations.get(appointment);
Reservation mutableReservation= toUpdate.get(reservation);
if ( mutableReservation == null)
{
mutableReservation = getModification().edit( reservation);
toUpdate.put( reservation, mutableReservation);
}
mutableReservation.addAppointment( appointment);
Allocatable[] removedAllocatables = allocatablesRemoved.get( appointment);
mutableReservation.setRestriction( appointment, removedAllocatables);
}
for (Appointment appointment:exceptionsToAdd.keySet())
{
Reservation reservation = appointment.getReservation();
Reservation mutableReservation= toUpdate.get(reservation);
if ( mutableReservation == null)
{
mutableReservation = getModification().edit( reservation);
toUpdate.put( reservation, mutableReservation);
}
Appointment found = mutableReservation.findAppointment( appointment);
if ( found != null)
{
Repeating repeating = found.getRepeating();
if ( repeating != null)
{
List<Date> list = exceptionsToAdd.get( appointment);
for (Date exception: list)
{
repeating.removeException( exception);
}
}
}
}
Reservation[] updateArray = toUpdate.values().toArray(Reservation.RESERVATION_ARRAY);
Reservation[] removeArray = Reservation.RESERVATION_ARRAY;
getModification().storeAndRemove(updateArray,removeArray);
return true;
}
public String getCommandoName()
{
return getString("delete") + " " + getString("appointments");
}
}
public void deleteAppointment(AppointmentBlock appointmentBlock, Component sourceComponent, Point point) throws RaplaException {
boolean includeEvent = true;
Appointment appointment = appointmentBlock.getAppointment();
final DialogAction dialogResult = showDialog(appointmentBlock, "delete", includeEvent, sourceComponent, point);
Set<Appointment> appointmentsToRemove = new LinkedHashSet<Appointment>();
HashMap<Appointment,List<Date>> exceptionsToAdd = new LinkedHashMap<Appointment,List<Date>>();
Set<Reservation> reservationsToRemove = new LinkedHashSet<Reservation>();
final Date startDate = new Date(appointmentBlock.getStart());
switch (dialogResult) {
case SINGLE:
Repeating repeating = appointment.getRepeating();
if ( repeating != null )
{
List<Date> exceptionList = Collections.singletonList( startDate);
if ( isNotEmptyWithExceptions(appointment, exceptionList))
{
exceptionsToAdd.put( appointment,exceptionList);
}
else
{
appointmentsToRemove.add( appointment);
}
}
else
{
appointmentsToRemove.add( appointment);
}
break;
case EVENT:
reservationsToRemove.add( appointment.getReservation());
break;
case SERIE:
appointmentsToRemove.add( appointment);
break;
case CANCEL:
return;
}
DeleteBlocksCommand command = new DeleteBlocksCommand(reservationsToRemove, appointmentsToRemove, exceptionsToAdd)
{
public String getCommandoName() {
String name;
if (dialogResult == DialogAction.SINGLE)
name =getI18n().format("single_appointment.format",startDate);
else if (dialogResult == DialogAction.EVENT)
name = getString("reservation");
else if (dialogResult == DialogAction.SERIE)
name = getString("serie");
else
name = getString("appointment");
return getString("delete") + " " + name;
}
};
CommandHistory commandHistory = getModification().getCommandHistory();
commandHistory.storeAndExecute( command );
}
private boolean isNotEmptyWithExceptions(Appointment appointment, List<Date> exceptions) {
Repeating repeating = appointment.getRepeating();
if ( repeating != null)
{
int number = repeating.getNumber();
if ( number>=1)
{
if (repeating.getExceptions().length >= number-1)
{
Collection<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
appointment.createBlocks(appointment.getStart(), appointment.getMaxEnd(), blocks);
int blockswithException = 0;
for (AppointmentBlock block:blocks)
{
long start = block.getStart();
boolean blocked = false;
for (Date excepion: exceptions)
{
if (DateTools.isSameDay(excepion.getTime(), start))
{
blocked = true;
}
}
if ( blocked)
{
blockswithException++;
}
}
if ( blockswithException >= blocks.size())
{
return false;
}
}
}
}
return true;
}
public Appointment copyAppointment(Appointment appointment) throws RaplaException {
return getModification().clone(appointment);
}
enum DialogAction
{
EVENT,
SERIE,
SINGLE,
CANCEL
}
private DialogAction showDialog(AppointmentBlock appointmentBlock
,String action
,boolean includeEvent
,Component sourceComponent
,Point point
) throws RaplaException
{
Appointment appointment = appointmentBlock.getAppointment();
Date from = new Date(appointmentBlock.getStart());
Reservation reservation = appointment.getReservation();
getLogger().debug(action + " '" + appointment + "' for reservation '" + reservation + "'");
List<String> optionList = new ArrayList<String>();
List<Icon> iconList = new ArrayList<Icon>();
List<DialogAction> actionList = new ArrayList<ReservationControllerImpl.DialogAction>();
String dateString = getRaplaLocale().formatDate(from);
if ( reservation.getAppointments().length <=1 || includeEvent)
{
optionList.add(getString("reservation"));
iconList.add(getIcon("icon.edit_window_small"));
actionList.add(DialogAction.EVENT);
}
if ( appointment.getRepeating() != null && reservation.getAppointments().length > 1 )
{
String shortSummary = getAppointmentFormater().getShortSummary(appointment);
optionList.add(getString("serie") + ": " + shortSummary);
iconList.add(getIcon("icon.repeating"));
actionList.add(DialogAction.SERIE);
}
if ( (appointment.getRepeating() != null && isNotEmptyWithExceptions( appointment, Collections.singletonList(from)))|| reservation.getAppointments().length > 1)
{
optionList.add(getI18n().format("single_appointment.format",dateString));
iconList.add(getIcon("icon.single"));
actionList.add( DialogAction.SINGLE);
}
if (optionList.size() > 1) {
DialogUI dialog = DialogUI.create(
getContext()
,sourceComponent
,true
,getString(action)
,getString(action+ "_appointment.format")
,optionList.toArray(new String[] {})
);
dialog.setIcon(getIcon("icon.question"));
for ( int i=0;i< optionList.size();i++)
{
dialog.getButton(i).setIcon(iconList.get( i));
}
dialog.start(point);
int index = dialog.getSelectedIndex();
if ( index < 0)
{
return DialogAction.CANCEL;
}
return actionList.get(index);
}
else
{
if ( action.equals("delete"))
{
DialogUI dlg = getInfoFactory().createDeleteDialog( new Object[]{ appointment.getReservation()}, sourceComponent);
dlg.start();
if (dlg.getSelectedIndex() != 0)
return DialogAction.CANCEL;
}
}
if ( actionList.size() > 0)
{
return actionList.get( 0 );
}
return DialogAction.EVENT;
}
public Appointment copyAppointment(
AppointmentBlock appointmentBlock
,Component sourceComponent
,Point point
,Collection<Allocatable> contextAllocatables
)
throws RaplaException
{
RaplaClipboard raplaClipboard = getClipboard();
Appointment appointment = appointmentBlock.getAppointment();
DialogAction result = showDialog(appointmentBlock, "copy", true, sourceComponent, point);
Reservation sourceReservation = appointment.getReservation();
// copy info text to system clipboard
{
StringBuffer buf = new StringBuffer();
ReservationInfoUI reservationInfoUI = new ReservationInfoUI(getContext());
boolean excludeAdditionalInfos = false;
List<Row> attributes = reservationInfoUI.getAttributes(sourceReservation, null, null, excludeAdditionalInfos);
for (Row row:attributes)
{
buf.append( row.getField());
}
String string = buf.toString();
try
{
final IOInterface service = getIOService();
if (service != null) {
StringSelection transferable = new StringSelection(string);
service.setContents(transferable, null);
}
}
catch (AccessControlException ex)
{
}
}
Allocatable[] restrictedAllocatables = sourceReservation.getRestrictedAllocatables(appointment);
if ( result == DialogAction.SINGLE)
{
Appointment copy = copyAppointment(appointment);
copy.setRepeatingEnabled(false);
Calendar cal = getRaplaLocale().createCalendar();
cal.setTime( copy.getStart());
int hour_of_day = cal.get( Calendar.HOUR_OF_DAY);
int minute = cal.get( Calendar.MINUTE);
int second = cal.get( Calendar.SECOND);
cal.setTimeInMillis( appointmentBlock.getStart());
cal.set( Calendar.HOUR_OF_DAY, hour_of_day);
cal.set( Calendar.MINUTE,minute);
cal.set( Calendar.SECOND,second);
cal.set( Calendar.MILLISECOND,0);
Date newStart = cal.getTime();
copy.move(newStart);
raplaClipboard.setAppointment(copy, false, sourceReservation, restrictedAllocatables, contextAllocatables);
return copy;
}
else if ( result == DialogAction.EVENT && appointment.getReservation().getAppointments().length >1)
{
int num = getAppointmentIndex(appointment);
Reservation reservation = appointment.getReservation();
Reservation clone = getModification().clone( reservation);
Appointment[] clonedAppointments = clone.getAppointments();
if ( num >= clonedAppointments.length)
{
return null;
}
Appointment clonedAppointment = clonedAppointments[num];
boolean wholeReservation = true;
raplaClipboard.setAppointment(clonedAppointment, wholeReservation, clone, restrictedAllocatables, contextAllocatables);
return clonedAppointment;
}
else
{
Appointment copy = copyAppointment(appointment);
raplaClipboard.setAppointment(copy, false, sourceReservation, restrictedAllocatables, contextAllocatables);
return copy;
}
}
public int getAppointmentIndex(Appointment appointment) {
int num;
Reservation reservation = appointment.getReservation();
num = 0;
for (Appointment app:reservation.getAppointments())
{
if ( appointment.equals(app))
{
break;
}
num++;
}
return num;
}
public void dataChanged(ModificationEvent evt) throws RaplaException {
// we need to clone the list, because it could be modified during edit
ArrayList<ReservationEditImpl> clone = new ArrayList<ReservationEditImpl>(editWindowList);
for ( ReservationEditImpl c:clone)
{
c.refresh(evt);
TimeInterval invalidateInterval = evt.getInvalidateInterval();
Reservation original = c.getOriginal();
if ( invalidateInterval != null && original != null)
{
boolean test = false;
for (Appointment app:original.getAppointments())
{
if ( app.overlaps( invalidateInterval))
{
test = true;
}
}
if ( test )
{
try
{
Reservation persistant = getModification().getPersistant( original);
Date version = persistant.getLastChanged();
Date originalVersion = original.getLastChanged();
if ( originalVersion != null && version!= null && originalVersion.before( version))
{
c.updateReservation(persistant);
}
}
catch (EntityNotFoundException ex)
{
c.deleteReservation();
}
}
}
}
}
private RaplaClipboard getClipboard()
{
return getService(RaplaClipboard.class);
}
public boolean isAppointmentOnClipboard() {
return (getClipboard().getAppointment() != null || !getClipboard().getReservations().isEmpty());
}
public void pasteAppointment(Date start, Component sourceComponent, Point point, boolean asNewReservation, boolean keepTime) throws RaplaException {
RaplaClipboard clipboard = getClipboard();
Collection<Reservation> reservations = clipboard.getReservations();
CommandUndo<RaplaException> pasteCommand;
if ( reservations.size() > 1)
{
pasteCommand = new ReservationPaste(reservations, start);
}
else
{
Appointment appointment = clipboard.getAppointment();
if (appointment == null) {
return;
}
Reservation reservation = clipboard.getReservation();
boolean copyWholeReservation = clipboard.isWholeReservation();
Allocatable[] restrictedAllocatables = clipboard.getRestrictedAllocatables();
long offset = getOffset(appointment.getStart(), start, keepTime);
getLogger().debug("Paste appointment '" + appointment
+ "' for reservation '" + reservation
+ "' at " + start);
Collection<Allocatable> currentlyMarked = getService(CalendarSelectionModel.class).getMarkedAllocatables();
Collection<Allocatable> previouslyMarked = clipboard.getConextAllocatables();
// exchange allocatables if pasted in a different allocatable slot
if ( copyWholeReservation && currentlyMarked != null && previouslyMarked != null && currentlyMarked.size() == 1 && previouslyMarked.size() == 1)
{
Allocatable newAllocatable = currentlyMarked.iterator().next();
Allocatable oldAllocatable = previouslyMarked.iterator().next();
if ( !newAllocatable.equals( oldAllocatable))
{
if ( !reservation.hasAllocated(newAllocatable))
{
AppointmentBlock appointmentBlock = new AppointmentBlock(appointment);
AllocatableExchangeCommand cmd = exchangeAllocatebleCmd(appointmentBlock, oldAllocatable, newAllocatable,null, sourceComponent, point);
reservation = cmd.getModifiedReservationForExecute();
appointment = reservation.getAppointments()[0];
}
}
}
pasteCommand = new AppointmentPaste(appointment, reservation, restrictedAllocatables, asNewReservation, copyWholeReservation, offset, sourceComponent);
}
getClientFacade().getCommandHistory().storeAndExecute(pasteCommand);
}
public void moveAppointment(AppointmentBlock appointmentBlock,Date newStart,Component sourceComponent,Point p, boolean keepTime) throws RaplaException {
Date from = new Date( appointmentBlock.getStart());
if ( newStart.equals(from))
return;
getLogger().debug("Moving appointment " + appointmentBlock.getAppointment() + " from " + from + " to " + newStart);
resizeAppointment(appointmentBlock, newStart, null, sourceComponent, p, keepTime);
}
public void resizeAppointment(AppointmentBlock appointmentBlock, Date newStart, Date newEnd, Component sourceComponent, Point p, boolean keepTime) throws RaplaException {
boolean includeEvent = newEnd == null;
Appointment appointment = appointmentBlock.getAppointment();
Date from = new Date(appointmentBlock.getStart());
DialogAction result = showDialog(appointmentBlock, "move", includeEvent, sourceComponent, p);
if (result == DialogAction.CANCEL) {
return;
}
Date oldStart = from;
Date oldEnd = (newEnd == null) ? null : new Date(from.getTime() + appointment.getEnd().getTime() - appointment.getStart().getTime());
if ( keepTime && newStart != null && !newStart.equals( oldStart))
{
newStart = new Date( oldStart.getTime() + getOffset(oldStart, newStart, keepTime));
}
AppointmentResize resizeCommand = new AppointmentResize(appointment, oldStart, oldEnd, newStart, newEnd, sourceComponent, result, keepTime);
getClientFacade().getCommandHistory().storeAndExecute(resizeCommand);
}
public long getOffset(Date appStart, Date newStart, boolean keepTime) {
Calendar calendar = getRaplaLocale().createCalendar();
calendar.setTime( newStart);
if ( keepTime)
{
Calendar cal2 = getRaplaLocale().createCalendar();
cal2.setTime( appStart);
calendar.set(Calendar.HOUR_OF_DAY, cal2.get( Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, cal2.get( Calendar.MINUTE));
calendar.set(Calendar.SECOND, cal2.get( Calendar.SECOND));
calendar.set(Calendar.MILLISECOND, cal2.get( Calendar.MILLISECOND));
}
Date newStartAdjusted = calendar.getTime();
long offset = newStartAdjusted.getTime() - appStart.getTime();
return offset;
}
public boolean save(Reservation reservation, Component sourceComponent) throws RaplaException {
SaveCommand saveCommand = new SaveCommand(reservation);
save(reservation, sourceComponent, saveCommand);
return saveCommand.hasSaved();
}
boolean save(Reservation reservation,Component sourceComponent,Command saveCommand) throws RaplaException {
Collection<ReservationCheck> checkers = getContainer().lookupServicesFor(RaplaClientExtensionPoints.RESERVATION_SAVE_CHECK);
for (ReservationCheck check:checkers)
{
boolean successful= check.check(reservation, sourceComponent);
if ( !successful)
{
return false;
}
}
try {
saveCommand.execute();
return true;
} catch (Exception ex) {
showException(ex,sourceComponent);
return false;
}
}
class SaveCommand implements Command {
private final Reservation reservation;
boolean saved;
public SaveCommand(Reservation reservation) {
this.reservation = reservation;
}
public void execute() throws RaplaException {
getModification().store( reservation );
saved = true;
}
public boolean hasSaved() {
return saved;
}
}
@Override
public void exchangeAllocatable(final AppointmentBlock appointmentBlock,final Allocatable oldAllocatable,final Allocatable newAllocatable,final Date newStart,final Component sourceComponent, final Point point)
throws RaplaException
{
AllocatableExchangeCommand command = exchangeAllocatebleCmd( appointmentBlock, oldAllocatable, newAllocatable,newStart, sourceComponent, point);
if ( command != null)
{
CommandHistory commandHistory = getModification().getCommandHistory();
commandHistory.storeAndExecute( command );
}
}
protected AllocatableExchangeCommand exchangeAllocatebleCmd(AppointmentBlock appointmentBlock, final Allocatable oldAllocatable,final Allocatable newAllocatable, Date newStart,final Component sourceComponent, final Point point) throws RaplaException {
Map<Allocatable,Appointment[]> newRestrictions = new HashMap<Allocatable, Appointment[]>();
//Appointment appointment;
//Allocatable oldAllocatable;
//Allocatable newAllocatable;
boolean removeAllocatable = false;
boolean addAllocatable = false;
Appointment addAppointment = null;
List<Date> exceptionsAdded = new ArrayList<Date>();
Appointment appointment = appointmentBlock.getAppointment();
Reservation reservation = appointment.getReservation();
Date date = new Date(appointmentBlock.getStart());
Appointment copy = null;
Appointment[] restriction = reservation.getRestriction(oldAllocatable);
boolean includeEvent = restriction.length == 0;
DialogAction result = showDialog(appointmentBlock, "exchange_allocatables", includeEvent, sourceComponent, point);
if (result == DialogAction.CANCEL)
return null;
if (result == DialogAction.SINGLE && appointment.getRepeating() != null) {
copy = copyAppointment(appointment);
copy.setRepeatingEnabled(false);
Calendar cal = getRaplaLocale().createCalendar();
long start = appointment.getStart().getTime();
int hour = DateTools.getHourOfDay(start);
int minute = DateTools.getMinuteOfHour(start);
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY,hour);
cal.set(Calendar.MINUTE, minute);
copy.move(cal.getTime());
}
if (result == DialogAction.EVENT && includeEvent )
{
removeAllocatable = true;
//modifiableReservation.removeAllocatable( oldAllocatable);
if ( reservation.hasAllocated( newAllocatable))
{
newRestrictions.put( newAllocatable, Appointment.EMPTY_ARRAY);
//modifiableReservation.setRestriction( newAllocatable, Appointment.EMPTY_ARRAY);
}
else
{
addAllocatable = true;
//modifiableReservation.addAllocatable(newAllocatable);
}
}
else
{
Appointment[] apps = reservation.getAppointmentsFor(oldAllocatable);
if ( copy != null)
{
exceptionsAdded.add(date);
//Appointment existingAppointment = modifiableReservation.findAppointment( appointment);
//existingAppointment.getRepeating().addException( date );
//modifiableReservation.addAppointment( copy);
addAppointment = copy;
List<Allocatable> all =new ArrayList<Allocatable>(Arrays.asList(reservation.getAllocatablesFor(appointment)));
all.remove(oldAllocatable);
for ( Allocatable a:all)
{
Appointment[] restr = reservation.getRestriction( a);
if ( restr.length > 0)
{
List<Appointment> restrictions = new ArrayList<Appointment>( Arrays.asList( restr));
restrictions.add( copy );
newRestrictions.put(a, restrictions.toArray(Appointment.EMPTY_ARRAY));
//reservation.setRestriction(a, newRestrictions.toArray(new Appointment[] {}));
}
}
newRestrictions.put( oldAllocatable, apps);
//modifiableReservation.setRestriction(oldAllocatable,apps);
}
else
{
if ( apps.length == 1)
{
//modifiableReservation.removeAllocatable(oldAllocatable);
removeAllocatable = true;
}
else
{
List<Appointment> appointments = new ArrayList<Appointment>(Arrays.asList( apps));
appointments.remove( appointment);
newRestrictions.put(oldAllocatable , appointments.toArray(Appointment.EMPTY_ARRAY));
//modifiableReservation.setRestriction(oldAllocatable, appointments.toArray(Appointment.EMPTY_ARRAY));
}
}
Appointment app;
if ( copy != null)
{
app = copy;
}
else
{
app = appointment;
}
if ( reservation.hasAllocated( newAllocatable))
{
Appointment[] existingRestrictions =reservation.getRestriction(newAllocatable);
Collection<Appointment> restrictions = new LinkedHashSet<Appointment>( Arrays.asList(existingRestrictions));
if ( existingRestrictions.length ==0 || restrictions.contains( app))
{
// is already allocated, do nothing
}
else
{
restrictions.add(app);
}
newRestrictions.put( newAllocatable, restrictions.toArray(Appointment.EMPTY_ARRAY));
//modifiableReservation.setRestriction(newAllocatable, newRestrictions.toArray(Appointment.EMPTY_ARRAY));
}
else
{
addAllocatable = true;
//modifiableReservation.addAllocatable( newAllocatable);
if ( reservation.getAppointments().length > 1 || addAppointment != null)
{
newRestrictions.put( newAllocatable,new Appointment[] {app});
//modifiableReservation.setRestriction(newAllocatable, new Appointment[] {appointment});
}
}
}
if ( newStart != null)
{
long offset = newStart.getTime() - appointmentBlock.getStart();
Appointment app= addAppointment != null ? addAppointment : appointment;
newStart = new Date( app.getStart().getTime()+ offset);
}
AllocatableExchangeCommand command = new AllocatableExchangeCommand( appointment, oldAllocatable, newAllocatable,newStart, newRestrictions, removeAllocatable, addAllocatable, addAppointment, exceptionsAdded, sourceComponent);
return command;
}
class AllocatableExchangeCommand implements CommandUndo<RaplaException>
{
Appointment appointment;
Allocatable oldAllocatable;
Allocatable newAllocatable;
Map<Allocatable, Appointment[]> newRestrictions;
Map<Allocatable, Appointment[]> oldRestrictions;
boolean removeAllocatable;
boolean addAllocatable;
Appointment addAppointment;
List<Date> exceptionsAdded;
Date newStart;
boolean firstTimeCall = true;
Component sourceComponent;
AllocatableExchangeCommand(Appointment appointment, Allocatable oldAllocatable, Allocatable newAllocatable, Date newStart,Map<Allocatable, Appointment[]> newRestrictions, boolean removeAllocatable, boolean addAllocatable, Appointment addAppointment,
List<Date> exceptionsAdded, Component sourceComponent)
{
this.appointment = appointment;
this.oldAllocatable = oldAllocatable;
this.newAllocatable = newAllocatable;
this.newStart = newStart;
this.newRestrictions = newRestrictions;
this.removeAllocatable = removeAllocatable;
this.addAllocatable = addAllocatable;
this.addAppointment = addAppointment;
this.exceptionsAdded = exceptionsAdded;
this.sourceComponent = sourceComponent;
}
public boolean execute() throws RaplaException
{
Reservation modifiableReservation = getModifiedReservationForExecute();
if ( firstTimeCall)
{
firstTimeCall = false;
return save(modifiableReservation, sourceComponent);
}
else
{
getModification().store( modifiableReservation );
return true;
}
}
protected Reservation getModifiedReservationForExecute() throws RaplaException {
Reservation reservation = appointment.getReservation();
Reservation modifiableReservation = getModification().edit(reservation);
if ( addAppointment != null)
{
modifiableReservation.addAppointment( addAppointment);
}
Appointment existingAppointment = modifiableReservation.findAppointment( appointment);
if ( existingAppointment != null)
{
for ( Date exception: exceptionsAdded)
{
existingAppointment.getRepeating().addException( exception );
}
}
if ( removeAllocatable)
{
modifiableReservation.removeAllocatable( oldAllocatable);
}
if ( addAllocatable)
{
modifiableReservation.addAllocatable(newAllocatable);
}
oldRestrictions = new HashMap<Allocatable, Appointment[]>();
for ( Allocatable alloc: reservation.getAllocatables())
{
oldRestrictions.put( alloc, reservation.getRestriction( alloc));
}
for ( Allocatable alloc: newRestrictions.keySet())
{
Appointment[] restrictions = newRestrictions.get( alloc);
ArrayList<Appointment> foundAppointments = new ArrayList<Appointment>();
for ( Appointment app: restrictions)
{
Appointment found = modifiableReservation.findAppointment( app);
if ( found != null)
{
foundAppointments.add( found);
}
}
modifiableReservation.setRestriction(alloc, foundAppointments.toArray( Appointment.EMPTY_ARRAY));
}
if ( newStart != null)
{
if ( addAppointment != null)
{
addAppointment.move( newStart);
}
else if (existingAppointment != null)
{
existingAppointment.move( newStart);
}
}
// long startTime = (dialogResult == DialogAction.SINGLE) ? sourceStart.getTime() : ap.getStart().getTime();
//
// changeStart = new Date(startTime + offset);
//
// if (resizing) {
// changeEnd = new Date(changeStart.getTime() + (destEnd.getTime() - destStart.getTime()));
// ap.move(changeStart, changeEnd);
// } else {
// ap.move(changeStart);
// }
return modifiableReservation;
}
public boolean undo() throws RaplaException
{
Reservation modifiableReservation = getModifiedReservationForUndo();
getModification().store( modifiableReservation);
return true;
}
protected Reservation getModifiedReservationForUndo()
throws RaplaException {
Reservation persistant = getModification().getPersistant(appointment.getReservation());
Reservation modifiableReservation = getModification().edit(persistant);
if ( addAppointment != null)
{
Appointment found = modifiableReservation.findAppointment( addAppointment );
if ( found != null)
{
modifiableReservation.removeAppointment( found );
}
}
Appointment existingAppointment = modifiableReservation.findAppointment( appointment);
if ( existingAppointment != null)
{
for ( Date exception: exceptionsAdded)
{
existingAppointment.getRepeating().removeException( exception );
}
if ( newStart != null)
{
Date oldStart = appointment.getStart();
existingAppointment.move( oldStart);
}
}
if ( removeAllocatable)
{
modifiableReservation.addAllocatable( oldAllocatable);
}
if ( addAllocatable)
{
modifiableReservation.removeAllocatable(newAllocatable);
}
for ( Allocatable alloc: oldRestrictions.keySet())
{
Appointment[] restrictions = oldRestrictions.get( alloc);
ArrayList<Appointment> foundAppointments = new ArrayList<Appointment>();
for ( Appointment app: restrictions)
{
Appointment found = modifiableReservation.findAppointment( app);
if ( found != null)
{
foundAppointments.add( found);
}
}
modifiableReservation.setRestriction(alloc, foundAppointments.toArray( Appointment.EMPTY_ARRAY));
}
return modifiableReservation;
}
public String getCommandoName()
{
return getString("exchange_allocatables");
}
}
/**
* This class collects any information of an appointment that is resized or moved in any way
* in the calendar view.
* This is where undo/redo for moving or resizing of an appointment
* in the calendar view is realized.
* @author Jens Fritz
*
*/
//Erstellt und bearbeitet von Dominik Krickl-Vorreiter und Jens Fritz
class AppointmentResize implements CommandUndo<RaplaException> {
private final Date oldStart;
private final Date oldEnd;
private final Date newStart;
private final Date newEnd;
private final Appointment appointment;
private final Component sourceComponent;
private final DialogAction dialogResult;
private Appointment lastCopy;
private boolean firstTimeCall = true;
private boolean keepTime;
public AppointmentResize(Appointment appointment, Date oldStart, Date oldEnd, Date newStart, Date newEnd, Component sourceComponent, DialogAction dialogResult, boolean keepTime) {
this.oldStart = oldStart;
this.oldEnd = oldEnd;
this.newStart = newStart;
this.newEnd = newEnd;
this.appointment = appointment;
this.sourceComponent = sourceComponent;
this.dialogResult = dialogResult;
this.keepTime = keepTime;
lastCopy = null;
}
public boolean execute() throws RaplaException {
boolean resizing = newEnd != null;
Date sourceStart = oldStart;
Date destStart = newStart;
Date destEnd = newEnd;
return doMove(resizing, sourceStart, destStart, destEnd, false);
}
public boolean undo() throws RaplaException {
boolean resizing = newEnd != null;
Date sourceStart = newStart;
Date destStart = oldStart;
Date destEnd = oldEnd;
return doMove(resizing, sourceStart, destStart, destEnd, true);
}
private boolean doMove(boolean resizing, Date sourceStart,
Date destStart, Date destEnd, boolean undo) throws RaplaException {
Reservation reservation = appointment.getReservation();
Reservation mutableReservation = getModification().edit(reservation);
Appointment mutableAppointment = mutableReservation.findAppointment(appointment);
if (mutableAppointment == null) {
throw new IllegalStateException("Can't find the appointment: " + appointment);
}
long offset = getOffset(sourceStart, destStart, keepTime);
Collection<Appointment> appointments;
// Move the complete serie
switch (dialogResult) {
case SERIE:
// Wir wollen eine Serie (Appointment mit Wdh) verschieben
appointments = Collections.singleton(mutableAppointment);
break;
case EVENT:
// Wir wollen die ganze Reservation verschieben
appointments = Arrays.asList(mutableReservation.getAppointments());
break;
case SINGLE:
// Wir wollen nur ein Appointment aus einer Serie verschieben --> losl_sen von Serie
Repeating repeating = mutableAppointment.getRepeating();
if (repeating == null) {
appointments = Arrays.asList(mutableAppointment);
}
else
{
if (undo)
{
mutableReservation.removeAppointment(lastCopy);
repeating.removeException(oldStart);
lastCopy = null;
return save(mutableReservation, sourceComponent);
}
else
{
lastCopy = copyAppointment(mutableAppointment);
lastCopy.setRepeatingEnabled(false);
appointments = Arrays.asList(lastCopy);
}
}
break;
default:
throw new IllegalStateException("Dialog choice not supported "+ dialogResult ) ;
}
Date changeStart;
Date changeEnd;
for (Appointment ap : appointments) {
long startTime = (dialogResult == DialogAction.SINGLE) ? sourceStart.getTime() : ap.getStart().getTime();
changeStart = new Date(startTime + offset);
if (resizing) {
changeEnd = new Date(changeStart.getTime() + (destEnd.getTime() - destStart.getTime()));
ap.move(changeStart, changeEnd);
} else {
ap.move(changeStart);
}
}
if ( !undo)
{
if (dialogResult == DialogAction.SINGLE) {
Repeating repeating = mutableAppointment.getRepeating();
if (repeating != null) {
Allocatable[] restrictedAllocatables = mutableReservation.getRestrictedAllocatables(mutableAppointment);
mutableReservation.addAppointment(lastCopy);
mutableReservation.setRestriction(lastCopy, restrictedAllocatables);
repeating.addException(oldStart);
}
}
}
if ( firstTimeCall)
{
firstTimeCall = false;
return save(mutableReservation, sourceComponent);
}
else
{
getModification().store( mutableReservation );
return true;
}
}
public String getCommandoName() {
return getString("move");
}
}
/**
* This class collects any information of an appointment that is copied and pasted
* in the calendar view.
* This is where undo/redo for pasting an appointment
* in the calendar view is realized.
* @author Jens Fritz
*
*/
//Erstellt von Dominik Krickl-Vorreiter
class AppointmentPaste implements CommandUndo<RaplaException> {
private final Appointment fromAppointment;
private final Reservation fromReservation;
private final Allocatable[] restrictedAllocatables;
private final boolean asNewReservation;
private final boolean copyWholeReservation;
private final long offset;
private final Component sourceComponent;
private Reservation saveReservation = null;
private Appointment saveAppointment = null;
private boolean firstTimeCall = true;
public AppointmentPaste(Appointment fromAppointment, Reservation fromReservation, Allocatable[] restrictedAllocatables, boolean asNewReservation, boolean copyWholeReservation, long offset, Component sourceComponent) {
this.fromAppointment = fromAppointment;
this.fromReservation = fromReservation;
this.restrictedAllocatables = restrictedAllocatables;
this.asNewReservation = asNewReservation;
this.copyWholeReservation = copyWholeReservation;
this.offset = offset;
this.sourceComponent = sourceComponent;
assert !(!asNewReservation && copyWholeReservation);
}
public boolean execute() throws RaplaException {
Reservation mutableReservation = null;
if (asNewReservation) {
if (saveReservation == null) {
mutableReservation = getModification().clone(fromReservation);
} else {
mutableReservation = saveReservation;
}
// Alle anderen Appointments verschieben / entfernen
Appointment[] appointments = mutableReservation.getAppointments();
for (int i=0; i < appointments.length; i++) {
Appointment app = appointments[i];
if (copyWholeReservation) {
if (saveReservation == null) {
app.move(new Date(app.getStart().getTime() + offset));
}
} else {
mutableReservation.removeAppointment(app);
}
}
} else {
mutableReservation = getModification().edit(fromReservation);
}
if (!copyWholeReservation) {
if (saveAppointment == null) {
saveAppointment = copyAppointment(fromAppointment);
saveAppointment.move(new Date(saveAppointment.getStart().getTime() + offset));
}
mutableReservation.addAppointment(saveAppointment);
mutableReservation.setRestriction(saveAppointment, restrictedAllocatables);
}
saveReservation = mutableReservation;
if ( firstTimeCall)
{
firstTimeCall = false;
return save(mutableReservation, sourceComponent);
}
else
{
getModification().store( mutableReservation );
return true;
}
}
public boolean undo() throws RaplaException {
if (asNewReservation) {
Reservation mutableReservation = getModification().edit(saveReservation);
getModification().remove(mutableReservation);
return true;
} else {
Reservation mutableReservation = getModification().edit(saveReservation);
mutableReservation.removeAppointment(saveAppointment);
getModification().store(mutableReservation);
return true;
}
}
public String getCommandoName()
{
return getString("paste");
}
}
class ReservationPaste implements CommandUndo<RaplaException> {
private final Collection<Reservation> fromReservation;
Date start;
Reservation[] array;
public ReservationPaste(Collection<Reservation> fromReservation,Date start) {
this.fromReservation = fromReservation;
this.start = start;
}
public boolean execute() throws RaplaException {
List<Reservation> clones = copy(fromReservation,start);
array = clones.toArray(Reservation.RESERVATION_ARRAY);
getModification().storeAndRemove(array , Reservation.RESERVATION_ARRAY);
return true;
}
public boolean undo() throws RaplaException {
getModification().storeAndRemove(Reservation.RESERVATION_ARRAY,array );
return true;
}
public String getCommandoName()
{
return getString("paste");
}
}
/**
* This class collects any information of an appointment that is saved
* to the calendar view.
* This is where undo/redo for saving an appointment
* in the calendar view is realized.
* @author Jens Fritz
*
*/
//Erstellt von Dominik Krickl-Vorreiter
class ReservationSave extends SaveUndo<Reservation> {
private final Component sourceComponent;
Reservation newReservation;
public ReservationSave(Reservation newReservation, Reservation original, Component sourceComponent)
{
super(ReservationControllerImpl.this.getContext(),Collections.singletonList(newReservation), original != null ? Collections.singletonList(original): null);
this.sourceComponent = sourceComponent;
this.newReservation = newReservation;
}
public boolean execute() throws RaplaException
{
if ( firstTimeCall)
{
firstTimeCall = false;
return save(newReservation, sourceComponent, new SaveCommand(newReservation));
}
else
{
return super.execute();
}
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/reservation/ReservationControllerImpl.java | Java | gpl3 | 57,013 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.reservation;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.components.util.undo.CommandUndo;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.AppointmentStartComparator;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.framework.Disposable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.internal.edit.RaplaListEdit;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaWidget;
/** Default GUI for editing multiple appointments.*/
class AppointmentListEdit extends AbstractAppointmentEditor
implements
RaplaWidget
,Disposable
{
private AppointmentController appointmentController;
private RaplaListEdit<Appointment> listEdit;
private CommandHistory commandHistory;
private boolean disableInternSelectionListener = false;
protected Reservation mutableReservation;
private Listener listener = new Listener();
DefaultListModel model = new DefaultListModel();
// use sorted model to start with sorting
// respect dependencies ! on other components
@SuppressWarnings("rawtypes")
Comparator comp = new AppointmentStartComparator();
@SuppressWarnings("unchecked")
SortedListModel sortedModel = new SortedListModel(model, SortedListModel.SortOrder.ASCENDING,comp );
RaplaButton freeButtonNext = new RaplaButton();
@SuppressWarnings("unchecked")
AppointmentListEdit(RaplaContext sm, CommandHistory commandHistory)
throws RaplaException {
super(sm);
this.commandHistory = commandHistory;
appointmentController = new AppointmentController(sm, commandHistory);
listEdit = new RaplaListEdit<Appointment>(getI18n(),appointmentController.getComponent(), listener);
listEdit.getToolbar().add( freeButtonNext);
freeButtonNext.setText(getString("appointment.search_free"));
freeButtonNext.addActionListener( listener );
appointmentController.addChangeListener(listener);
// activate this as a first step
listEdit.getList().setModel(sortedModel);
//listEdit.getList().setModel(model);
listEdit.setColoredBackgroundEnabled(true);
listEdit.setMoveButtonVisible(false);
listEdit.getList().setCellRenderer(new AppointmentCellRenderer());
}
public RaplaListEdit<Appointment> getListEdit()
{
return listEdit;
}
@SuppressWarnings("unchecked")
private void addToModel(Appointment appointment) {
model.addElement( appointment);
}
public JComponent getComponent() {
return listEdit.getComponent();
}
public void setReservation(Reservation mutableReservation, Appointment mutableAppointment) {
this.mutableReservation = mutableReservation;
Appointment[] appointments = mutableReservation.getAppointments();
model.clear();
for (Appointment app:appointments) {
addToModel(app);
}
if ( mutableAppointment != null ) {
selectAppointment(mutableAppointment, false);
} else if ( appointments.length> 0 ){
selectAppointment(appointments[0], false);
}
}
private void selectAppointment(Appointment appointment,boolean disableListeners) {
if (disableListeners)
{
disableInternSelectionListener = true;
}
try {
boolean shouldScroll = true;
listEdit.getList().clearSelection();
listEdit.getList().setSelectedValue( appointment ,shouldScroll );
appointmentController.setAppointment( appointment );
} finally {
if (disableListeners)
{
disableInternSelectionListener = false;
}
}
}
public void dispose() {
appointmentController.dispose();
}
class AppointmentCellRenderer implements ListCellRenderer {
Border focusBorder = UIManager.getBorder("List.focusCellHighlightBorder");
Border emptyBorder = new EmptyBorder(1,1,1,1);
Color selectionBackground = UIManager.getColor("List.selectionBackground");
Color background = UIManager.getColor("List.background");
AppointmentRow row = new AppointmentRow();
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
row.setAppointment((Appointment) value,index);
row.setBackground((isSelected) ? selectionBackground : background);
row.setBorder((cellHasFocus) ? focusBorder : emptyBorder);
return row;
}
}
class AppointmentRow extends JPanel {
private static final long serialVersionUID = 1L;
JPanel content = new JPanel();
AppointmentIdentifier identifier = new AppointmentIdentifier();
AppointmentRow() {
double fill = TableLayout.FILL;
double pre = TableLayout.PREFERRED;
this.setLayout(new TableLayout(new double[][] {{pre,5,fill,10,pre},{1,fill,1}}));
this.add(identifier,"0,1,l,f");
this.add(content,"2,1,f,c");
this.setMaximumSize(new Dimension(500,40));
content.setOpaque(false);
identifier.setOpaque(true);
identifier.setBorder(null);
}
public void setAppointment(Appointment appointment,int index) {
identifier.setText(getRaplaLocale().formatNumber(index + 1));
identifier.setIndex(index);
content.setLayout(new BoxLayout(content,BoxLayout.Y_AXIS));
content.removeAll();
JLabel label1 = new JLabel(getAppointmentFormater().getSummary(appointment));
content.add( label1 );
if (appointment.getRepeating() != null) {
label1.setIcon( getIcon("icon.repeating") );
Repeating r = appointment.getRepeating();
List<Period> periods = getPeriodModel().getPeriodsFor(appointment.getStart());
String repeatingString = getAppointmentFormater().getSummary(r,periods);
content.add(new JLabel(repeatingString));
if ( r.hasExceptions() ) {
content.add(new JLabel( getAppointmentFormater().getExceptionSummary( r ) ) );
}
} else {
label1.setIcon( getIcon("icon.single") );
}
}
}
class Listener implements ActionListener, ChangeListener {
public void actionPerformed(ActionEvent evt) {
if ( evt.getSource() == freeButtonNext )
{
appointmentController.nextFreeAppointment();
}
if (evt.getActionCommand().equals("remove"))
{
@SuppressWarnings("deprecation")
Object[] objects = listEdit.getList().getSelectedValues();
RemoveAppointments command = new RemoveAppointments(
objects);
commandHistory.storeAndExecute(command);
}
else if (evt.getActionCommand().equals("new"))
{
try {
Appointment appointment = createAppointmentFromSelected();
NewAppointment command = new NewAppointment(appointment);
commandHistory.storeAndExecute(command);
} catch (RaplaException ex) {
showException(ex, getMainComponent());
}
}
else if (evt.getActionCommand().equals("split"))
{
AppointmentSplit command = new AppointmentSplit();
commandHistory.storeAndExecute(command);
}
else if (evt.getActionCommand().equals("edit")) {
Appointment newAppointment = (Appointment) listEdit.getList().getSelectedValue();
Appointment oldAppointment = appointmentController.getAppointment();
if (!disableInternSelectionListener)
{
if (oldAppointment!=null && !newAppointment.equals(oldAppointment) ) {
AppointmentSelectionChange appointmentCommand = new AppointmentSelectionChange(oldAppointment, newAppointment);
commandHistory.storeAndExecute(appointmentCommand);
}else {
appointmentController.setAppointment(newAppointment);
}
}
}
else if (evt.getActionCommand().equals("select"))
{
Collection<Appointment> appointments = new ArrayList<Appointment>();
@SuppressWarnings("deprecation")
Object[] values = listEdit.getList().getSelectedValues();
for ( Object value:values)
{
appointments.add( (Appointment)value);
}
freeButtonNext.setEnabled( appointments.size() == 1);
fireAppointmentSelected(appointments);
}
}
@SuppressWarnings("unchecked")
public void stateChanged(ChangeEvent evt) {
Appointment appointment = appointmentController.getAppointment();
@SuppressWarnings("deprecation")
Object[] values = listEdit.getList().getSelectedValues();
List<Object> selectedValues = Arrays.asList(values);
int indexOf = model.indexOf(appointment);
if ( indexOf >=0)
{
model.set(indexOf, appointment);
}
listEdit.updateSort( selectedValues);
fireAppointmentChanged(Collections.singleton(appointment));
}
}
public AppointmentController getAppointmentController() {
return appointmentController;
}
public void addAppointment(Appointment appointment)
{
NewAppointment newAppointment = new NewAppointment(appointment);
commandHistory.storeAndExecute( newAppointment);
}
/**
* This class collects any information of removed appointments in the edit view.
* This is where undo/redo for removing an appointment at the fields on the top-left
* of the edit view is realized.
* @author Jens Fritz
*
*/
public class RemoveAppointments implements CommandUndo<RuntimeException> {
private final Map<Appointment,Allocatable[]> list;
private int[] selectedAppointment;
public RemoveAppointments(Object[] list) {
this.list = new LinkedHashMap<Appointment,Allocatable[]>();
for ( Object obj:list)
{
Appointment appointment = (Appointment) obj;
Allocatable[] restrictedAllocatables = mutableReservation.getRestrictedAllocatables(appointment);
this.list.put ( appointment, restrictedAllocatables);
}
}
public boolean execute() {
selectedAppointment = listEdit.getList().getSelectedIndices();
Set<Appointment> appointmentList = list.keySet();
for (Appointment appointment:appointmentList) {
mutableReservation.removeAppointment(appointment);
}
model.clear();
for (Appointment app:mutableReservation.getAppointments()) {
addToModel(app);
}
fireAppointmentRemoved(appointmentList);
listEdit.getList().requestFocus();
return true;
}
public boolean undo() {
Set<Appointment> appointmentList = list.keySet();
for (Appointment appointment:appointmentList)
{
mutableReservation.addAppointment(appointment);
Allocatable[] removedAllocatables = list.get( appointment);
mutableReservation.setRestriction(appointment, removedAllocatables);
}
model.clear();
for (Appointment app:mutableReservation.getAppointments()) {
addToModel(app);
}
fireAppointmentAdded(appointmentList);
disableInternSelectionListener = true;
try {
listEdit.getList().setSelectedIndices(selectedAppointment);
} finally {
disableInternSelectionListener = false;
}
return true;
}
public String getCommandoName() {
return getString("remove")+ " " + getString("appointment");
}
}
protected Appointment createAppointmentFromSelected()
throws RaplaException {
Appointment[] appointments = mutableReservation.getAppointments();
Appointment appointment;
if (appointments.length == 0) {
Date start = new Date(DateTools.cutDate(new Date()).getTime()+ getCalendarOptions().getWorktimeStartMinutes() * DateTools.MILLISECONDS_PER_MINUTE);
Date end = new Date(start.getTime()+ DateTools.MILLISECONDS_PER_HOUR);
appointment = getModification().newAppointment(start, end);
} else {
// copy the selected appointment as template
// if no appointment is selected use the last
final int selectedIndex = listEdit.getSelectedIndex();
final int index = selectedIndex > -1 ? selectedIndex : appointments.length - 1;
final Appointment toClone = appointments[index];
// this allows each appointment as template
appointment = getReservationController().copyAppointment(toClone);
Repeating repeating = appointment.getRepeating();
if (repeating != null) {
repeating.clearExceptions();
}
}
return appointment;
}
/**
* This class collects any information of added appointments in the edit view.
* This is where undo/redo for adding an appointment at the fields on the top-left
* of the edit view is realized.
* @author Jens Fritz
*
*/
//Erstellt von Matthias Both
public class NewAppointment implements CommandUndo<RuntimeException> {
private Appointment newAppointment;
public NewAppointment( Appointment appointment) {
this.newAppointment = appointment;
}
public boolean execute() {
mutableReservation.addAppointment(newAppointment);
addToModel(newAppointment);
selectAppointment(newAppointment, true);
fireAppointmentAdded(Collections.singleton(newAppointment));
return true;
}
public boolean undo() {
model.removeElement(newAppointment);
mutableReservation.removeAppointment(newAppointment);
fireAppointmentRemoved(Collections.singleton(newAppointment));
return true;
}
public String getCommandoName() {
return getString("new_appointment");
}
}
/**
* This class collects any information of an appointment that is split from a repeating type
* into several single appointments in the edit view.
* This is where undo/redo for splitting an appointment at the fields on the top-right
* of the edit view is realized.
* @author Jens Fritz
*
*/
//Erstellt von Matthias Both
public class AppointmentSplit implements CommandUndo<RuntimeException>
{
Appointment wholeAppointment;
Allocatable[] allocatablesFor;
List<Appointment> splitAppointments;
public AppointmentSplit() {
}
public boolean execute() {
try {
// Generate time blocks from selected appointment
List<AppointmentBlock> splits = new ArrayList<AppointmentBlock>();
Appointment appointment = appointmentController.getAppointment();
appointment.createBlocks(appointment.getStart(), DateTools.fillDate(appointment.getMaxEnd()), splits);
allocatablesFor = mutableReservation.getAllocatablesFor(appointment);
wholeAppointment = appointment;
fireAppointmentRemoved(Collections.singleton(appointment));
splitAppointments = new ArrayList<Appointment>();
// Create single appointments for every time block
for (AppointmentBlock block: splits)
{
Appointment newApp = getModification().newAppointment(new Date(block.getStart()), new Date(block.getEnd()));
// Add appointment to list
splitAppointments.add( newApp );
mutableReservation.addAppointment(newApp);
}
for (Allocatable alloc:allocatablesFor)
{
Appointment[] restrictions =mutableReservation.getRestriction(alloc);
if ( restrictions.length > 0)
{
LinkedHashSet<Appointment> newRestrictions = new LinkedHashSet<Appointment>( Arrays.asList( restrictions));
newRestrictions.addAll(splitAppointments);
mutableReservation.setRestriction(alloc, newRestrictions.toArray(Appointment.EMPTY_ARRAY));
}
}
// we need to remove the appointment after splitting not before, otherwise allocatable connections could be lost
mutableReservation.removeAppointment( appointment);
model.removeElement( appointment);
for (Appointment newApp:splitAppointments)
{
addToModel(newApp);
}
fireAppointmentAdded(splitAppointments);
if (splitAppointments.size() > 0) {
Appointment app = splitAppointments.get(0);
selectAppointment( app, true);
}
return true;
} catch (RaplaException ex) {
showException(ex, getComponent());
return false;
}
}
public boolean undo() {
// Switch the type of the appointment to old type
mutableReservation.addAppointment(wholeAppointment);
for (Allocatable alloc : allocatablesFor) {
Appointment[] restrictions = mutableReservation.getRestriction(alloc);
if (restrictions.length > 0) {
LinkedHashSet<Appointment> newRestrictions = new LinkedHashSet<Appointment>(Arrays.asList(restrictions));
newRestrictions.removeAll(splitAppointments);
newRestrictions.add(wholeAppointment);
mutableReservation.setRestriction(alloc,newRestrictions.toArray(Appointment.EMPTY_ARRAY));
}
}
// same here we remove the split appointments after we add the old appointment so no allocatable connections gets lost
for (Appointment newApp : splitAppointments) {
mutableReservation.removeAppointment(newApp);
model.removeElement(newApp);
}
addToModel(wholeAppointment);
fireAppointmentAdded(Collections.singleton(wholeAppointment));
selectAppointment(wholeAppointment, true);
return true;
}
public String getCommandoName()
{
return getString("appointment.convert");
}
}
/**
* This class collects any information of which appointment is selected in the edit view.
* This is where undo/redo for selecting an appointment at the fields on the top-left
* of the edit view is realized.
* @author Jens Fritz
*
*/
//Erstellt von Dominick Krickl-Vorreiter
public class AppointmentSelectionChange implements CommandUndo<RuntimeException> {
private final Appointment oldAppointment;
private final Appointment newAppointment;
public AppointmentSelectionChange(Appointment oldAppointment, Appointment newAppointment) {
this.oldAppointment = oldAppointment;
this.newAppointment = newAppointment;
}
public boolean execute() {
setAppointment(newAppointment);
return oldAppointment != null;
}
public boolean undo() {
setAppointment(oldAppointment);
return true;
}
private void setAppointment(Appointment toAppointment) {
appointmentController.setAppointment(toAppointment);
selectAppointment(toAppointment, true);
}
public String getCommandoName() {
return getString("select") + " " + getString("appointment");
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/reservation/AppointmentListEdit.java | Java | gpl3 | 20,331 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.reservation;
import java.awt.Component;
import java.awt.Dimension;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.JTree;
import javax.swing.tree.TreeModel;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.Conflict;
import org.rapla.facade.internal.CalendarOptionsImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.ReservationCheck;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.internal.view.TreeFactoryImpl;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.RaplaTree;
public class ConflictReservationCheck extends RaplaGUIComponent implements ReservationCheck
{
public ConflictReservationCheck(RaplaContext context) {
super(context);
}
public boolean check(Reservation reservation, Component sourceComponent) throws RaplaException {
Conflict[] conflicts = getQuery().getConflicts(reservation);
if (conflicts.length == 0) {
return true;
}
boolean showWarning = getQuery().getPreferences().getEntryAsBoolean(CalendarOptionsImpl.SHOW_CONFLICT_WARNING, true);
User user = getUser();
if ( !showWarning && canCreateConflicts( conflicts, user))
{
return true;
}
JComponent content = getConflictPanel(conflicts);
DialogUI dialog = DialogUI.create(
getContext()
,sourceComponent
,true
,content
,new String[] {
getString("continue")
,getString("back")
}
);
dialog.setDefault(1);
dialog.setIcon(getIcon("icon.big_folder_conflicts"));
dialog.getButton(0).setIcon(getIcon("icon.save"));
dialog.getButton(1).setIcon(getIcon("icon.cancel"));
dialog.setTitle(getString("warning.conflict"));
dialog.start();
if (dialog.getSelectedIndex() == 0) {
try {
return true;
} catch (Exception ex) {
showException(ex,sourceComponent);
return false;
}
}
return false;
}
private boolean canCreateConflicts(Conflict[] conflicts, User user)
{
Set<Allocatable> allocatables = new HashSet<Allocatable>();
for (Conflict conflict:conflicts)
{
allocatables.add(conflict.getAllocatable());
}
for ( Allocatable allocatable:allocatables)
{
if ( !allocatable.canCreateConflicts( user))
{
return false;
}
}
return true;
}
private JComponent getConflictPanel(Conflict[] conflicts) throws RaplaException {
TreeFactory treeFactory = getService(TreeFactory.class);
TreeModel treeModel = treeFactory.createConflictModel( Arrays.asList( conflicts));
RaplaTree treeSelection = new RaplaTree();
JTree tree = treeSelection.getTree();
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
tree.setCellRenderer(((TreeFactoryImpl) treeFactory).createConflictRenderer());
treeSelection.exchangeTreeModel(treeModel);
treeSelection.expandAll();
treeSelection.setPreferredSize( new Dimension(400,200));
return treeSelection;
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/reservation/ConflictReservationCheck.java | Java | gpl3 | 4,523 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.reservation;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
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.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.rapla.components.calendar.DateChangeEvent;
import org.rapla.components.calendar.DateChangeListener;
import org.rapla.components.calendar.RaplaCalendar;
import org.rapla.components.calendar.RaplaNumber;
import org.rapla.components.calendar.RaplaTime;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.components.util.undo.CommandUndo;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.RepeatingEnding;
import org.rapla.entities.domain.RepeatingType;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.ReservationHelper;
import org.rapla.entities.domain.internal.AppointmentImpl;
import org.rapla.facade.CalendarOptions;
import org.rapla.framework.Disposable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.common.PeriodChooser;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.MonthChooser;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaWidget;
import org.rapla.gui.toolkit.WeekdayChooser;
/** GUI for editing a single Appointment. */
public class AppointmentController extends RaplaGUIComponent
implements
Disposable
,RaplaWidget
{
JPanel panel = new JPanel();
SingleEditor singleEditor = new SingleEditor();
JPanel repeatingContainer = new JPanel();
RepeatingEditor repeatingEditor = new RepeatingEditor();
Appointment appointment = null;
Repeating repeating;
RepeatingType savedRepeatingType = null;
ArrayList<ChangeListener> listenerList = new ArrayList<ChangeListener>();
JPanel repeatingType = new JPanel();
JRadioButton noRepeating = new JRadioButton();
JRadioButton weeklyRepeating = new JRadioButton();
JRadioButton dailyRepeating = new JRadioButton();
JRadioButton monthlyRepeating = new JRadioButton();
JRadioButton yearlyRepeating = new JRadioButton();
CardLayout repeatingCard = new CardLayout();
// Button for splitting appointments
RaplaButton convertButton = new RaplaButton();
private CommandHistory commandHistory;
Date selectedEditDate = null;
public AppointmentController(RaplaContext sm, CommandHistory commandHistory)
throws RaplaException {
super(sm);
this.commandHistory = commandHistory;
panel.setLayout(new BorderLayout());
panel.add(repeatingType, BorderLayout.NORTH);
repeatingType.setLayout(new BoxLayout(repeatingType, BoxLayout.X_AXIS));
repeatingType.add(noRepeating);
repeatingType.add(weeklyRepeating);
repeatingType.add(dailyRepeating);
repeatingType.add(monthlyRepeating);
repeatingType.add(yearlyRepeating);
repeatingType.add(Box.createHorizontalStrut(40));
repeatingType.add(convertButton);
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(noRepeating);
buttonGroup.add(weeklyRepeating);
buttonGroup.add(dailyRepeating);
buttonGroup.add(monthlyRepeating);
buttonGroup.add(yearlyRepeating);
panel.add(repeatingContainer, BorderLayout.CENTER);
Border emptyLineBorder = new Border() {
Insets insets = new Insets(1, 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(0, 0, c.getWidth(), 0);
}
public Insets getBorderInsets(Component c) {
return insets;
}
public boolean isBorderOpaque() {
return true;
}
};
Border outerBorder = (BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(0, 5, 0, 5)
// ,BorderFactory.createEmptyBorder()
, emptyLineBorder));
repeatingContainer.setBorder(BorderFactory.createCompoundBorder( outerBorder, BorderFactory.createEmptyBorder(10, 5, 10, 5)));
repeatingContainer.setLayout(repeatingCard);
repeatingContainer.add(singleEditor.getComponent(), "0");
repeatingContainer.add(repeatingEditor.getComponent(), "1");
singleEditor.initialize();
repeatingEditor.initialize();
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
switchRepeatings();
}
};
noRepeating.addActionListener(listener);
weeklyRepeating.addActionListener(listener);
monthlyRepeating.addActionListener(listener);
dailyRepeating.addActionListener(listener);
yearlyRepeating.addActionListener(listener);
noRepeating.setText(getString("no_repeating"));
weeklyRepeating.setText(getString("weekly"));
dailyRepeating.setText(getString("daily"));
monthlyRepeating.setText(getString("monthly"));
yearlyRepeating.setText(getString("yearly"));
// Rapla 1.4: Initialize the split appointment button
convertButton.setText(getString("appointment.convert"));
}
private void switchRepeatings() {
UndoRepeatingTypeChange repeatingCommand = new UndoRepeatingTypeChange(savedRepeatingType, getCurrentRepeatingType());
commandHistory.storeAndExecute(repeatingCommand);
}
public void setAppointment(Appointment appointment) {
this.appointment = appointment;
this.repeating = appointment.getRepeating();
if (appointment.getRepeating() != null) {
repeatingEditor.mapFromAppointment();
repeatingCard.show(repeatingContainer, "1");
if (repeating.isWeekly())
{
weeklyRepeating.setSelected(true);
}
else if (repeating.isDaily())
{
dailyRepeating.setSelected(true);
}
else if (repeating.isMonthly())
{
monthlyRepeating.setSelected(true);
}
else if (repeating.isYearly())
{
yearlyRepeating.setSelected(true);
}
} else {
singleEditor.mapFromAppointment();
repeatingCard.show(repeatingContainer, "0");
noRepeating.setSelected(true);
}
savedRepeatingType = getCurrentRepeatingType();
}
public Appointment getAppointment() {
return appointment;
}
public void setSelectedEditDate(Date selectedEditDate) {
this.selectedEditDate = selectedEditDate;
}
public Date getSelectedEditDate() {
return selectedEditDate;
}
public void dispose() {
singleEditor.dispose();
repeatingEditor.dispose();
}
public JComponent getComponent() {
return panel;
}
/**
* registers new ChangeListener for this component. An ChangeEvent will be
* fired to every registered ChangeListener when the appointment changes.
*
* @see javax.swing.event.ChangeListener
* @see javax.swing.event.ChangeEvent
*/
public void addChangeListener(ChangeListener listener) {
listenerList.add(listener);
}
/** removes a listener from this component. */
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(listener);
}
public ChangeListener[] getChangeListeners() {
return listenerList.toArray(new ChangeListener[] {});
}
protected void fireAppointmentChanged() {
if (listenerList.size() == 0)
return;
ChangeEvent evt = new ChangeEvent(this);
ChangeListener[] listeners = getChangeListeners();
for (int i = 0; i < listeners.length; i++) {
listeners[i].stateChanged(evt);
}
getLogger().debug("appointment changed: " + appointment);
}
static double ROW_SIZE = 21;
private void setToWholeDays(final boolean oneDayEvent) {
boolean wasSet = appointment.isWholeDaysSet();
appointment.setWholeDays(oneDayEvent);
if (wasSet && !oneDayEvent)
{
// BJO 00000070
CalendarOptions calenderOptions = getCalendarOptions();
int startMinutes = calenderOptions.getWorktimeStartMinutes();
int endMinutes = calenderOptions.getWorktimeEndMinutes();
Date start = new Date(appointment.getStart().getTime() + startMinutes * DateTools.MILLISECONDS_PER_MINUTE);
Date end = new Date(appointment.getEnd().getTime() - DateTools.MILLISECONDS_PER_DAY + endMinutes * DateTools.MILLISECONDS_PER_MINUTE);
// BJO 00000070
if ( end.before( start))
{
end =DateTools.addDay(end);
}
appointment.move(start, end);
}
}
class SingleEditor implements DateChangeListener, Disposable {
JPanel content = new JPanel();
JLabel startLabel = new JLabel();
RaplaCalendar startDate;
JLabel startTimeLabel = new JLabel();
RaplaTime startTime;
JLabel endLabel = new JLabel();
RaplaCalendar endDate;
JLabel endTimeLabel = new JLabel();
RaplaTime endTime;
JCheckBox oneDayEventCheckBox = new JCheckBox();
private boolean listenerEnabled = true;
public SingleEditor() {
double pre = TableLayout.PREFERRED;
double size[][] = { { pre, 5, pre, 10, pre, 5, pre, 5, pre }, // Columns
{ ROW_SIZE, 6, ROW_SIZE, 6, ROW_SIZE } }; // Rows
TableLayout tableLayout = new TableLayout(size);
content.setLayout(tableLayout);
}
public void initialize() {
startDate = createRaplaCalendar();
endDate = createRaplaCalendar();
startTime = createRaplaTime();
endTime = createRaplaTime();
content.add(startLabel, "0,0,r,f");
startLabel.setText(getString("start_date"));
startTimeLabel.setText(getString("time_at"));
endTimeLabel.setText(getString("time_at"));
content.add(startDate, "2,0,f,f");
content.add(startTimeLabel, "4,0,l,f");
content.add(startTime, "6,0,f,f");
content.add(endLabel, "0,2,r,f");
endLabel.setText(getString("end_date"));
content.add(endDate, "2,2,f,f");
content.add(endTimeLabel, "4,2,r,f");
content.add(endTime, "6,2,f,f");
oneDayEventCheckBox.setText(getString("all-day"));
content.add(oneDayEventCheckBox, "8,0");
oneDayEventCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent itemevent) {
boolean selected = itemevent.getStateChange() == ItemEvent.SELECTED;
setToWholeDays(selected);
processChange(itemevent.getSource());
}
});
startDate.addDateChangeListener(this);
startTime.addDateChangeListener(this);
endDate.addDateChangeListener(this);
endTime.addDateChangeListener(this);
}
public JComponent getComponent() {
return content;
}
public void dispose() {
}
public void dateChanged(DateChangeEvent evt) {
final Object source = evt.getSource();
processChange(source);
}
private void processChange(final Object source) {
if (!listenerEnabled)
return;
try {
listenerEnabled = false;
RaplaLocale raplaLocale = getRaplaLocale();
Date appStart = appointment.getStart();
Date appEnd = appointment.getEnd();
long duration = appEnd.getTime() - appStart.getTime();
boolean wholeDaysSet = appointment.isWholeDaysSet();
boolean oneDayEventSelected = oneDayEventCheckBox.isSelected();
if (source == startDate || source == startTime) {
Date date = startDate.getDate();
Date time = startTime.getTime();
Date newStart = raplaLocale.toDate(date, time);
Date newEnd = new Date(newStart.getTime() + duration);
if (newStart.equals(appStart) && newEnd.equals(appEnd))
return;
UndoSingleEditorChange command = new UndoSingleEditorChange(appStart, appEnd,wholeDaysSet, newStart, newEnd,oneDayEventSelected);
commandHistory.storeAndExecute(command);
}
if (source == endTime) {
Date newEnd = raplaLocale.toDate(endDate.getDate(), endTime.getTime());
if (appStart.after(newEnd))
{
newEnd = DateTools.addDay(newEnd);
}
if (newEnd.equals(appEnd))
return;
UndoSingleEditorChange command = new UndoSingleEditorChange(null, appEnd,wholeDaysSet, null, newEnd, oneDayEventSelected);
commandHistory.storeAndExecute(command);
}
if (source == endDate) {
Date newEnd = raplaLocale.toDate(DateTools.addDays(endDate.getDate(), oneDayEventSelected ? 1 : 0), endTime.getTime());
Date newStart = null;
if (appStart.after(newEnd) || (oneDayEventSelected && !appStart.before( newEnd))) {
long mod = duration % DateTools.MILLISECONDS_PER_DAY;
if ( mod != 0)
{
newStart = new Date(newEnd.getTime()- mod);
}
else
{
newStart = DateTools.addDays(newEnd,-1);
}
}
UndoSingleEditorChange command = new UndoSingleEditorChange(appStart, appEnd,wholeDaysSet, newStart, newEnd,oneDayEventSelected);
commandHistory.storeAndExecute(command);
}
if (source == oneDayEventCheckBox) {
Date date = startDate.getDate();
Date time = startTime.getTime();
Date oldStart = raplaLocale.toDate(date, time);
Date oldEnd = raplaLocale.toDate(endDate.getDate(), endTime.getTime());
UndoSingleEditorChange command = new UndoSingleEditorChange(oldStart, oldEnd,!oneDayEventSelected,appStart, appEnd,oneDayEventSelected);
commandHistory.storeAndExecute(command);
}
} finally {
listenerEnabled = true;
}
}
private void mapFromAppointment() {
listenerEnabled = false;
try {
final boolean wholeDaysSet = appointment.isWholeDaysSet();
Date start = appointment.getStart();
startDate.setDate(start);
Date end = appointment.getEnd();
endDate.setDate(DateTools.addDays(end,wholeDaysSet ? -1 : 0));
endTime.setDurationStart( DateTools.isSameDay( start, end) ? start: null);
startTime.setTime(start);
endTime.setTime(end);
oneDayEventCheckBox.setSelected(wholeDaysSet);
startTimeLabel.setVisible(!wholeDaysSet);
startTime.setVisible(!wholeDaysSet);
endTime.setVisible(!wholeDaysSet);
endTimeLabel.setVisible(!wholeDaysSet);
} finally {
listenerEnabled = true;
}
convertButton.setEnabled(false);
}
private void mapToAppointment() {
RaplaLocale raplaLocale = getRaplaLocale();
Date start = raplaLocale.toDate(startDate.getDate(),
startTime.getTime());
Date end = raplaLocale.toDate(endDate.getDate(), endTime.getTime());
if (oneDayEventCheckBox.isSelected()) {
end = raplaLocale.toDate(DateTools.addDay(endDate.getDate()),
endTime.getTime());
}
appointment.move(start, end);
fireAppointmentChanged();
}
/**
* This class collects any information of changes done in the fields when a single
* appointment is selected.
* This is where undo/redo for the fields within a single-appointment at right of the edit view
* is realized.
* @author Jens Fritz
*
*/
//Erstellt von Dominik Krickl-Vorreiter
public class UndoSingleEditorChange implements CommandUndo<RuntimeException> {
Date oldStart;
Date oldEnd;
boolean oldoneDay;
Date newStart;
Date newEnd;
boolean newoneDay;
public UndoSingleEditorChange(Date oldstart, Date oldend,
boolean oldoneDay, Date newstart, Date newend,
boolean newoneDay) {
this.oldStart = oldstart;
this.oldEnd = oldend;
this.oldoneDay = oldoneDay;
this.newStart = newstart;
this.newEnd = newend;
this.newoneDay = newoneDay;
}
public boolean execute() {
listenerEnabled = false;
if (newStart != null && oldStart != null) {
startTime.setTime(newStart);
startDate.setDate(newStart);
getLogger().debug("Starttime/-date adjusted");
}
if (newEnd != null && oldEnd != null) {
endTime.setTime(newEnd);
endDate.setDate(DateTools.addDays(newEnd, newoneDay ? -1
: 0));
getLogger().debug("Endtime/-date adjusted");
}
if (oldoneDay != newoneDay) {
startTime.setVisible(!newoneDay);
startTimeLabel.setVisible(!newoneDay);
endTime.setVisible(!newoneDay);
endTimeLabel.setVisible(!newoneDay);
oneDayEventCheckBox.setSelected(newoneDay);
getLogger().debug("Whole day adjusted");
}
mapToAppointment();
getLogger().debug("SingleEditor adjusted");
listenerEnabled = true;
return true;
}
public boolean undo() {
listenerEnabled = false;
if (oldStart != null && newStart != null) {
startTime.setTime(oldStart);
startDate.setDate(oldStart);
getLogger().debug("Starttime/-date undo");
}
if (oldEnd != null && newEnd != null) {
endTime.setTime(oldEnd);
endDate.setDate(oldEnd);
getLogger().debug("Endtime/-date undo");
}
if (oldoneDay != newoneDay) {
startTime.setVisible(!oldoneDay);
startTimeLabel.setVisible(!oldoneDay);
endTime.setVisible(!oldoneDay);
endTimeLabel.setVisible(!oldoneDay);
oneDayEventCheckBox.setSelected(oldoneDay);
getLogger().debug("Whole day undo");
}
mapToAppointment();
getLogger().debug("SingleEditor undo");
listenerEnabled = true;
return true;
}
public String getCommandoName()
{
return getString("change")+ " " + getString("appointment");
}
}
}
class RepeatingEditor implements ActionListener, DateChangeListener,
ChangeListener, Disposable {
JPanel content = new JPanel();
JPanel intervalPanel = new JPanel();
JPanel weekdayInMonthPanel = new JPanel();
JPanel dayInMonthPanel = new JPanel();
RaplaNumber interval = new RaplaNumber(null, RaplaNumber.ONE, null, false);
{
addCopyPaste( interval.getNumberField());
}
RaplaNumber weekdayInMonth = new RaplaNumber(null, RaplaNumber.ONE, new Integer(5), false);
{
addCopyPaste( weekdayInMonth.getNumberField());
}
RaplaNumber dayInMonth = new RaplaNumber(null, RaplaNumber.ONE, new Integer(31), false);
{
addCopyPaste( dayInMonth.getNumberField());
}
WeekdayChooser weekdayChooser = new WeekdayChooser();
JLabel dayLabel = new JLabel();
JLabel startTimeLabel = new JLabel();
RaplaTime startTime;
JCheckBox oneDayEventCheckBox = new JCheckBox();
JLabel endTimeLabel = new JLabel();
JPanel endTimePanel = new JPanel();
RaplaTime endTime;
public final int SAME_DAY = 0, NEXT_DAY = 1, X_DAYS = 2;
JComboBox dayChooser;
RaplaNumber days = new RaplaNumber(null, new Integer(2), null, false);
{
addCopyPaste( days.getNumberField());
}
JLabel startDateLabel = new JLabel();
RaplaCalendar startDate;
PeriodChooser startDatePeriod;
JComboBox endingChooser;
public final int REPEAT_UNTIL = 0, REPEAT_N_TIMES = 1, REPEAT_FOREVER = 2;
RaplaCalendar endDate;
JPanel numberPanel = new JPanel();
RaplaNumber number = new RaplaNumber(null, RaplaNumber.ONE, null, false);
{
addCopyPaste( number.getNumberField());
}
JPanel endDatePeriodPanel = new JPanel();
PeriodChooser endDatePeriod;
RaplaButton exceptionButton = new RaplaButton();
ExceptionEditor exceptionEditor;
DialogUI exceptionDlg;
MonthChooser monthChooser = new MonthChooser();
private boolean listenerEnabled = true;
public RepeatingEditor() throws RaplaException {
startDatePeriod = new PeriodChooser(getContext(), PeriodChooser.START_ONLY);
endDatePeriod = new PeriodChooser(getContext(), PeriodChooser.END_ONLY);
// Create a TableLayout for the frame
double pre = TableLayout.PREFERRED;
double fill = TableLayout.FILL;
double size[][] = {
{ pre, 5, pre, 5, fill }, // Columns
{ ROW_SIZE, 18, ROW_SIZE, 5, ROW_SIZE, 15, ROW_SIZE, 6,
ROW_SIZE, 0 } }; // Rows
TableLayout tableLayout = new TableLayout(size);
content.setLayout(tableLayout);
}
public Locale getLocale() {
return getI18n().getLocale();
}
public JComponent getComponent() {
return content;
}
public void initialize() {
// Interval / Weekday
interval.setColumns(2);
weekdayInMonth.setColumns(2);
dayInMonth.setColumns(2);
intervalPanel.setLayout(new BoxLayout(intervalPanel, BoxLayout.X_AXIS));
intervalPanel.add(new JLabel(getString("repeating.interval.pre") + " "));
intervalPanel.add(Box.createHorizontalStrut(3));
intervalPanel.add(interval);
intervalPanel.add(Box.createHorizontalStrut(3));
intervalPanel.add(new JLabel(getString("repeating.interval.post")));
dayInMonthPanel.setLayout(new BoxLayout(dayInMonthPanel, BoxLayout.X_AXIS));
// dayInMonthPanel.add(new JLabel("Am"));
dayInMonthPanel.add(Box.createHorizontalStrut(35));
dayInMonthPanel.add(dayInMonth);
dayInMonthPanel.add(Box.createHorizontalStrut(3));
dayInMonthPanel.add(new JLabel(getString("repeating.interval.post")));
weekdayInMonthPanel.setLayout(new BoxLayout(weekdayInMonthPanel, BoxLayout.X_AXIS));
// weekdayInMonthPanel.add(new JLabel("Am"));
weekdayInMonthPanel.add(Box.createHorizontalStrut(35));
weekdayInMonthPanel.add(weekdayInMonth);
weekdayInMonthPanel.add(Box.createHorizontalStrut(3));
weekdayInMonthPanel.add(new JLabel( getString("repeating.interval.post")));
interval.addChangeListener(this);
weekdayInMonth.addChangeListener(this);
dayInMonth.addChangeListener(this);
weekdayChooser.setLocale(getLocale());
weekdayChooser.addActionListener(this);
monthChooser.setLocale(getLocale());
monthChooser.addActionListener(this);
dayLabel.setText(getString("day") + " ");
dayLabel.setVisible(false);
// StartTime
startTimeLabel.setText(getString("start_time"));
startTime = createRaplaTime();
startTime.addDateChangeListener(this);
oneDayEventCheckBox.setText(getString("all-day"));
oneDayEventCheckBox.addActionListener(this);
// EndTime duration
endTimeLabel.setText(getString("end_time"));
endTime = createRaplaTime();
endTime.addDateChangeListener(this);
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(new String[] {
getString("appointment.same_day"),
getString("appointment.next_day"),
getString("appointment.day_x") });
dayChooser = jComboBox;
dayChooser.addActionListener(this);
days.setColumns(2);
endTimePanel.setLayout(new TableLayout(new double[][] {
{ TableLayout.PREFERRED, 5, TableLayout.PREFERRED,
TableLayout.FILL }, { ROW_SIZE } }));
// endTimePanel.add(endTime,"0,0,l,f");
endTimePanel.add(dayChooser, "0,0");
endTimePanel.add(days, "2,0");
days.setVisible(false);
days.addChangeListener(this);
// start-date (with period-box)
startDatePeriod.addActionListener(this);
startDateLabel.setText(getString("repeating.start_date"));
startDate = createRaplaCalendar();
startDate.addDateChangeListener(this);
// end-date (with period-box)/n-times/forever
endDatePeriod.addActionListener(this);
endDate = createRaplaCalendar();
endDate.addDateChangeListener(this);
@SuppressWarnings("unchecked")
JComboBox jComboBox2 = new JComboBox(new RepeatingEnding[] {
RepeatingEnding.END_DATE, RepeatingEnding.N_TIMES,
RepeatingEnding.FOREVEVER });
endingChooser = jComboBox2;
endingChooser.addActionListener(this);
number.setColumns(3);
number.setNumber(new Integer(1));
number.addChangeListener(this);
numberPanel.setLayout(new BorderLayout());
numberPanel.add(number, BorderLayout.WEST);
numberPanel.setVisible(false);
intervalPanel.setVisible(false);
weekdayInMonthPanel.setVisible(false);
dayInMonthPanel.setVisible(false);
// exception
exceptionButton.setText(getString("appointment.exceptions") + " (0)");
exceptionButton.addActionListener(this);
content.add(intervalPanel, "0,0,l,f");
content.add(weekdayInMonthPanel, "0,0,l,f");
content.add(dayInMonthPanel, "0,0,l,f");
content.add(weekdayChooser, "2,0,f,f");
content.add(monthChooser, "2,0,f,f");
content.add(dayLabel, "2,0,l,f");
content.add(startTimeLabel, "0,2,l,f");
content.add(startTime, "2,2,f,f");
content.add(oneDayEventCheckBox, "4,2");
content.add(exceptionButton, "4,0,r,t");
content.add(endTimeLabel, "0,4,l,f");
content.add(endTime, "2,4,f,f");
content.add(endTimePanel, "4,4,4,4,l,f");
content.add(startDateLabel, "0,6,l,f");
content.add(startDate, "2,6,l,f");
content.add(startDatePeriod, "4,6,f,f");
content.add(endingChooser, "0,8,l,f");
content.add(endDate, "2,8,l,f");
content.add(endDatePeriodPanel, "4,8,f,f");
// We must surround the endDatePeriod with a panel to
// separate visiblity of periods from visibility of the panel
endDatePeriodPanel.setLayout(new BorderLayout());
endDatePeriodPanel.add(endDatePeriod, BorderLayout.CENTER);
content.add(numberPanel, "2,8,f,f");
setRenderer(endingChooser,new ListRenderer());
// Rapla 1.4: Initialize the split appointment button
convertButton.addActionListener(this);
// content.add(exceptionLabel,"0,10,l,c");
// content.add(exceptionPanel,"2,10,4,10,l,c");
}
public void dispose() {
endDatePeriod.removeActionListener(this);
startDatePeriod.removeActionListener(this);
}
private Date getStart() {
Date start = getRaplaLocale().toDate(startDate.getDate(), startTime.getTime());
/*
* if (repeating.isWeekly() || repeating.isMonthly()) { Calendar
* calendar = getRaplaLocale().createCalendar();
* calendar.setTime(start); calendar.set(Calendar.DAY_OF_WEEK,
* weekdayChooser.getSelectedWeekday() ); if
* (calendar.getTime().before(start)) {
* calendar.add(Calendar.DAY_OF_WEEK,7); } start =
* calendar.getTime(); } if (repeating.isYearly()) { Calendar
* calendar = getRaplaLocale().createCalendar();
* calendar.setTime(start); calendar.set(Calendar.MONTH,
* monthChooser.getSelectedMonth() );
* calendar.set(Calendar.DAY_OF_MONTH,
* dayInMonth.getNumber().intValue() ); start = calendar.getTime();
*
* }
*/
return start;
}
private Date getEnd() {
Date end = getRaplaLocale().toDate(getStart(), endTime.getTime());
if (dayChooser.getSelectedIndex() == NEXT_DAY)
end = DateTools.addDay(end);
if (dayChooser.getSelectedIndex() == X_DAYS)
end = DateTools.addDays(end, days.getNumber().intValue());
return end;
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == exceptionButton) {
try {
showExceptionDlg();
} catch (RaplaException ex) {
showException(ex, content);
}
return;
}
if (!listenerEnabled)
return;
try {
listenerEnabled = false;
// Rapla 1.4: Split appointment button has been clicked
if (evt.getSource() == convertButton) {
// Notify registered listeners
ActionListener[] listeners = listenerList.toArray(new ActionListener[] {});
for (int i = 0; i < listeners.length; i++) {
listeners[i].actionPerformed(new ActionEvent(AppointmentController.this,ActionEvent.ACTION_PERFORMED, "split"));
}
return;
}
else if (evt.getSource() == endingChooser) {
// repeating has changed to UNTIL, the default endDate will
// be set
int index = endingChooser.getSelectedIndex();
if (index == REPEAT_UNTIL) {
Date slotDate = getSelectedEditDate();
if (slotDate != null)
endDate.setDate(slotDate);
}
} else if (evt.getSource() == weekdayChooser) {
Calendar calendar = getRaplaLocale().createCalendar();
calendar.setTime(startDate.getDate());
calendar.set(Calendar.DAY_OF_WEEK, weekdayChooser.getSelectedWeekday());
startDate.setDate(calendar.getTime());
} else if (evt.getSource() == monthChooser) {
Calendar calendar = getRaplaLocale().createCalendar();
calendar.setTime(startDate.getDate());
calendar.set(Calendar.MONTH, monthChooser.getSelectedMonth());
calendar.set(Calendar.DAY_OF_MONTH, dayInMonth.getNumber().intValue());
startDate.setDate(calendar.getTime());
} else if (evt.getSource() == dayChooser) {
if (dayChooser.getSelectedIndex() == SAME_DAY) {
if (getEnd().before(getStart())) {
endTime.setTime(getStart());
getLogger().debug("endtime adjusted");
}
}
} else if (evt.getSource() == startDatePeriod && startDatePeriod.getPeriod() != null) {
Calendar calendar = getRaplaLocale().createCalendar();
calendar.setTime(startDatePeriod.getPeriod().getStart());
if (repeating.isWeekly() || repeating.isMonthly()) {
calendar.set(Calendar.DAY_OF_WEEK, weekdayChooser.getSelectedWeekday());
if (calendar.getTime().before( startDatePeriod.getPeriod().getStart())) {
calendar.add(Calendar.DAY_OF_WEEK, 7);
}
}
getLogger().debug("startdate adjusted to period");
startDate.setDate(calendar.getTime());
endDatePeriod.setSelectedPeriod(startDatePeriod.getPeriod());
} else if (evt.getSource() == endDatePeriod && endDatePeriod.getDate() != null) {
endDate.setDate(DateTools.subDay(endDatePeriod.getDate()));
getLogger().debug("enddate adjusted to period");
}
doChanges();
} finally {
listenerEnabled = true;
}
}
public void stateChanged(ChangeEvent evt) {
if (!listenerEnabled)
return;
try {
listenerEnabled = false;
if (evt.getSource() == weekdayInMonth && repeating.isMonthly()) {
Number weekdayOfMonthValue = weekdayInMonth.getNumber();
if (weekdayOfMonthValue != null && repeating.isMonthly()) {
Calendar cal = getRaplaLocale().createCalendar();
cal.setTime(appointment.getStart());
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, weekdayOfMonthValue.intValue());
startDate.setDate(cal.getTime());
}
}
if (evt.getSource() == dayInMonth && repeating.isYearly()) {
Number dayOfMonthValue = dayInMonth.getNumber();
if (dayOfMonthValue != null && repeating.isYearly()) {
Calendar cal = getRaplaLocale().createCalendar();
cal.setTime(appointment.getStart());
cal.set(Calendar.DAY_OF_MONTH, dayOfMonthValue.intValue());
startDate.setDate(cal.getTime());
}
}
doChanges();
} finally {
listenerEnabled = true;
}
}
public void dateChanged(DateChangeEvent evt) {
if (!listenerEnabled)
return;
try {
listenerEnabled = false;
long duration = appointment.getEnd().getTime()- appointment.getStart().getTime();
if (evt.getSource() == startTime) {
Date newEnd = new Date(getStart().getTime() + duration);
endTime.setTime(newEnd);
getLogger().debug("endtime adjusted");
}
if (evt.getSource() == endTime) {
Date newEnd = getEnd();
if (getStart().after(newEnd)) {
newEnd = DateTools.addDay(newEnd);
endTime.setTime(newEnd);
getLogger().debug("enddate adjusted");
}
}
doChanges();
} finally {
listenerEnabled = true;
}
}
private void mapToAppointment() {
int index = endingChooser.getSelectedIndex();
Number intervalValue = interval.getNumber();
if (intervalValue != null)
{
repeating.setInterval(intervalValue.intValue());
}
else
{
repeating.setInterval(1);
}
if (index == REPEAT_UNTIL) {
if (DateTools.countDays(startDate.getDate(), endDate.getDate()) < 0)
{
endDate.setDate(startDate.getDate());
}
repeating.setEnd(DateTools.addDay(endDate.getDate()));
} else if (index == REPEAT_N_TIMES) {
Number numberValue = number.getNumber();
if (number != null)
{
repeating.setNumber(numberValue.intValue());
}
else
{
repeating.setNumber(1);
}
} else { // REPEAT_FOREVER
repeating.setEnd(null);
repeating.setNumber(-1);
}
appointment.move(getStart(), getEnd());
// We have todo the after the move to avoid reseting the dates
final boolean oneDayEvent = oneDayEventCheckBox.isSelected();
setToWholeDays(oneDayEvent);
}
private void updateExceptionCount() {
int count = repeating.getExceptions().length;
if (count > 0) {
exceptionButton.setForeground(Color.red);
} else {
exceptionButton.setForeground(UIManager.getColor("Label.foreground"));
}
String countValue = String.valueOf(count);
if (count < 9) {
countValue = " " + countValue + " ";
}
exceptionButton.setText(getString("appointment.exceptions") + " ("
+ countValue + ")");
}
private void showEnding(int index) {
if (index == REPEAT_UNTIL) {
endDate.setVisible(true);
endDatePeriodPanel.setVisible(isPeriodVisible());
numberPanel.setVisible(false);
}
if (index == REPEAT_N_TIMES) {
endDate.setVisible(false);
endDatePeriodPanel.setVisible(false);
numberPanel.setVisible(true);
}
if (index == REPEAT_FOREVER) {
endDate.setVisible(false);
endDatePeriodPanel.setVisible(false);
numberPanel.setVisible(false);
}
}
private void mapFromAppointment() {
// closing is not necessary as dialog is modal
// if (exceptionDlg != null && exceptionDlg.isVisible())
// exceptionDlg.dispose();
repeating = appointment.getRepeating();
if (repeating == null) {
return;
}
listenerEnabled = false;
try {
updateExceptionCount();
if (exceptionEditor != null)
exceptionEditor.mapFromAppointment();
interval.setNumber(new Integer(repeating.getInterval()));
Date start = appointment.getStart();
startDate.setDate(start);
startDatePeriod.setDate(start);
startTime.setTime(start);
Date end = appointment.getEnd();
endTime.setTime(end);
endTime.setDurationStart( DateTools.isSameDay( start, end) ? start: null);
weekdayInMonthPanel.setVisible(repeating.isMonthly());
intervalPanel.setVisible(repeating.isDaily() || repeating.isWeekly());
dayInMonthPanel.setVisible(repeating.isYearly());
if (repeating.getEnd() != null) {
endDate.setDate(DateTools.subDay(repeating.getEnd()));
endDatePeriod.setDate(DateTools.cutDate(endDate.getDate()));
number.setNumber(new Integer(repeating.getNumber()));
if (!repeating.isFixedNumber()) {
endingChooser.setSelectedIndex(REPEAT_UNTIL);
showEnding(REPEAT_UNTIL);
} else {
endingChooser.setSelectedIndex(REPEAT_N_TIMES);
showEnding(REPEAT_N_TIMES);
}
} else {
endingChooser.setSelectedIndex(REPEAT_FOREVER);
showEnding(REPEAT_FOREVER);
}
startDatePeriod.setVisible(isPeriodVisible() && (repeating.isDaily() || repeating.isWeekly()));
endDatePeriod.setVisible(repeating.isDaily() || repeating.isWeekly());
if (repeating.isWeekly() || repeating.isMonthly()) {
dayLabel.setVisible(false);
weekdayChooser.setVisible(true);
monthChooser.setVisible(false);
Calendar calendar = getRaplaLocale().createCalendar();
calendar.setTime(start);
weekdayChooser.selectWeekday(calendar.get(Calendar.DAY_OF_WEEK));
}
if (repeating.isYearly()) {
dayLabel.setVisible(false);
weekdayChooser.setVisible(false);
monthChooser.setVisible(true);
Calendar cal = getRaplaLocale().createCalendar();
cal.setTime(start);
monthChooser.selectMonth(cal.get(Calendar.MONTH));
int numb = cal.get(Calendar.DAY_OF_MONTH);
dayInMonth.setNumber(new Integer(numb));
}
if (repeating.isMonthly()) {
Calendar cal = getRaplaLocale().createCalendar();
cal.setTime(start);
int numb = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
weekdayInMonth.setNumber(new Integer(numb));
}
if (repeating.isDaily()) {
dayLabel.setVisible(true);
weekdayChooser.setVisible(false);
monthChooser.setVisible(false);
}
String typeString = repeating.getType().toString();
startDateLabel.setText(getString(typeString) + " " + getString("repeating.start_date"));
int daysBetween = (int) DateTools.countDays(
start, end);
if (daysBetween == 0) {
dayChooser.setSelectedIndex(SAME_DAY);
days.setVisible(false);
} else if (daysBetween == 1) {
dayChooser.setSelectedIndex(NEXT_DAY);
days.setVisible(false);
} else {
dayChooser.setSelectedIndex(X_DAYS);
days.setNumber(new Integer(daysBetween));
days.setVisible(true);
}
final boolean wholeDaysSet = appointment.isWholeDaysSet();
startTime.setEnabled(!wholeDaysSet);
endTime.setEnabled(!wholeDaysSet);
dayChooser.setEnabled(!wholeDaysSet);
days.setEnabled( !wholeDaysSet);
oneDayEventCheckBox.setSelected(wholeDaysSet);
} finally {
listenerEnabled = true;
}
convertButton.setEnabled(repeating.getEnd() != null);
getComponent().revalidate();
}
private boolean isPeriodVisible() {
try {
return getQuery().getPeriodModel().getSize() > 0;
} catch (RaplaException e) {
return false;
}
}
private void showExceptionDlg() throws RaplaException {
exceptionEditor = new ExceptionEditor();
exceptionEditor.initialize();
exceptionEditor.mapFromAppointment();
exceptionEditor.getComponent().setBorder( BorderFactory.createEmptyBorder(5, 5, 5, 5));
exceptionDlg = DialogUI.create(getContext(), getComponent(), true,
exceptionEditor.getComponent(),
new String[] { getString("close") });
exceptionDlg.setTitle(getString("appointment.exceptions"));
exceptionDlg.start();
updateExceptionCount();
}
private void doChanges(){
Appointment oldState = ((AppointmentImpl) appointment).clone();
mapToAppointment();
Appointment newState = ((AppointmentImpl) appointment).clone();
UndoDataChange changeDataCommand = new UndoDataChange(oldState, newState);
commandHistory.storeAndExecute(changeDataCommand);
}
}
class ExceptionEditor implements ActionListener, ListSelectionListener {
JPanel content = new JPanel();
RaplaCalendar exceptionDate;
RaplaButton addButton = new RaplaButton(RaplaButton.SMALL);
RaplaButton removeButton = new RaplaButton(RaplaButton.SMALL);
JList specialExceptions = new JList();
public ExceptionEditor() {
// Create a TableLayout for the frame
double pre = TableLayout.PREFERRED;
double min = TableLayout.MINIMUM;
double fill = TableLayout.FILL;
double yborder = 8;
double size[][] = { { pre, pre, 0.1, 50, 100, 0.9 }, // Columns
{ yborder, min, min, fill } }; // Rows
TableLayout tableLayout = new TableLayout(size);
content.setLayout(tableLayout);
}
public JComponent getComponent() {
return content;
}
public void initialize() {
addButton.setText(getString("add"));
addButton.setIcon(getIcon("icon.arrow_right"));
removeButton.setText(getString("remove"));
removeButton.setIcon(getIcon("icon.arrow_left"));
exceptionDate = createRaplaCalendar();
/*
* this.add(new JLabel(getString("appointment.exception.general") +
* " "),"0,1"); this.add(new JScrollPane(generalExceptions
* ,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
* ,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER) ,"1,1,1,3,t");
*/
JLabel label = new JLabel(getString("appointment.exception.days")
+ " ");
label.setHorizontalAlignment(SwingConstants.RIGHT);
content.add(label, "3,1,4,1,r,t");
content.add(exceptionDate, "5,1,l,t");
content.add(addButton, "4,2,f,t");
content.add(removeButton, "4,3,f,t");
content.add(new JScrollPane(specialExceptions,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), "5,2,5,3,t");
addButton.addActionListener(this);
removeButton.addActionListener(this);
specialExceptions.addListSelectionListener(this);
removeButton.setEnabled(false);
specialExceptions.setFixedCellWidth(200);
specialExceptions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
DefaultListCellRenderer cellRenderer = new DefaultListCellRenderer() {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
if (value instanceof Date)
value = getRaplaLocale().formatDateLong((Date) value);
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}
};
setRenderer(specialExceptions, cellRenderer);
specialExceptions.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() > 1) {
removeException();
}
}
});
}
@SuppressWarnings("unchecked")
public void mapFromAppointment() {
if (appointment.getRepeating() == null)
specialExceptions.setListData(new Object[0]);
else
specialExceptions.setListData(appointment.getRepeating().getExceptions());
// exceptionDate.setDate( appointment.getStart());
Date exceptDate = getSelectedEditDate();
if (exceptDate == null)
exceptionDate.setDate(appointment.getStart());
else
exceptionDate.setDate(exceptDate);
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == addButton) {
addException();
}
if (evt.getSource() == removeButton) {
removeException();
}
}
private void addException() {
Date date = exceptionDate.getDate();
if (appointment.getRepeating().isException(date.getTime()))
return;
UndoExceptionChange command = new UndoExceptionChange( addButton, date, null);
commandHistory.storeAndExecute(command);
}
@SuppressWarnings("deprecation")
private void removeException() {
if (specialExceptions.getSelectedValues() == null)
return;
Object[] selectedExceptions = specialExceptions.getSelectedValues();
UndoExceptionChange command = new UndoExceptionChange( removeButton, null, selectedExceptions);
commandHistory.storeAndExecute(command);
}
public void valueChanged(ListSelectionEvent e) {
if (e.getSource() == specialExceptions) {
removeButton.setEnabled(specialExceptions.getSelectedValue() != null);
}
}
/**
* This class collects any information of changes done to the exceptions
* of an appointment, if a repeating-type is selected.
* This is where undo/redo for the changes of the exceptions within a repeating-type-appointment
* at the right of the edit view is realized.
* @author Jens Fritz
*
*/
//Erstellt von Dominik Krickl-Vorreiter
public class UndoExceptionChange implements CommandUndo<RuntimeException> {
RaplaButton pressedButton;
Date exception;
Object[] selectedExceptions;
public UndoExceptionChange(RaplaButton pressedButton,
Date exception, Object[] selectedExceptions) {
this.pressedButton = pressedButton;
this.exception = exception;
this.selectedExceptions = selectedExceptions;
}
@SuppressWarnings("unchecked")
public boolean execute() {
Repeating repeating = appointment.getRepeating();
if (pressedButton == addButton) {
repeating.addException(exception);
specialExceptions.setListData(repeating.getExceptions());
fireAppointmentChanged();
}
if (pressedButton == removeButton) {
for (int i = 0; i < selectedExceptions.length; i++) {
repeating.removeException((Date) selectedExceptions[i]);
}
specialExceptions.setListData(repeating.getExceptions());
fireAppointmentChanged();
}
return true;
}
@SuppressWarnings("unchecked")
public boolean undo() {
Repeating repeating = appointment.getRepeating();
if (pressedButton == addButton) {
repeating.removeException(exception);
specialExceptions.setListData(repeating.getExceptions());
fireAppointmentChanged();
}
if (pressedButton == removeButton) {
for (int i = 0; i < selectedExceptions.length; i++) {
repeating.addException(
(Date) selectedExceptions[i]);
}
specialExceptions.setListData(repeating.getExceptions());
fireAppointmentChanged();
}
return true;
}
public String getCommandoName() {
return getString("change")+ " " + getString("appointment");
}
}
}
private class ListRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (value != null) {
setText(getString(value.toString()));
}
return this;
}
}
public RepeatingType getCurrentRepeatingType() {
if (noRepeating.isSelected()) {
return null;
}
RepeatingType repeatingType;
if (monthlyRepeating.isSelected())
{
repeatingType = RepeatingType.MONTHLY;
}
else if (yearlyRepeating.isSelected())
{
repeatingType = RepeatingType.YEARLY;
}
else if (dailyRepeating.isSelected())
{
repeatingType = RepeatingType.DAILY;
}
else
{
repeatingType = RepeatingType.WEEKLY;
}
return repeatingType;
}
public Repeating getRepeating() {
if (noRepeating.isSelected()) {
return null;
}
return repeating;
}
/**
* This class collects any information of changes done to the radiobuttons
* with which the repeating-type is selected.
* This is where undo/redo for the changes of the radiobuttons, with which the repeating-type of an appointment
* can be set, at the right of the edit view is realized.
* @author Jens Fritz
*
*/
//Erstellt von Dominik Krickl-Vorreiter
public class UndoRepeatingTypeChange implements CommandUndo<RuntimeException> {
private final RepeatingType oldRepeatingType;
private final RepeatingType newRepeatingType;
public UndoRepeatingTypeChange(RepeatingType oldRepeatingType, RepeatingType newRepeatingType) {
this.oldRepeatingType = oldRepeatingType;
this.newRepeatingType = newRepeatingType;
}
public boolean execute() {
setRepeatingType(newRepeatingType);
return true;
}
public boolean undo() {
setRepeatingType(oldRepeatingType);
return true;
}
private void setRepeatingType(RepeatingType repeatingType) {
if (repeatingType == null)
{
noRepeating.setSelected(true);
repeatingCard.show(repeatingContainer, "0");
singleEditor.mapFromAppointment();
appointment.setRepeatingEnabled(false);
}
else
{
if (repeatingType == RepeatingType.WEEKLY)
{
weeklyRepeating.setSelected(true);
}
else if (repeatingType == RepeatingType.DAILY)
{
dailyRepeating.setSelected(true);
}
else if (repeatingType == RepeatingType.MONTHLY)
{
monthlyRepeating.setSelected(true);
}
else if (repeatingType == RepeatingType.YEARLY)
{
yearlyRepeating.setSelected(true);
}
ReservationHelper.makeRepeatingForPeriod(getPeriodModel(), appointment, repeatingType,1);
repeatingEditor.mapFromAppointment();
repeatingCard.show(repeatingContainer, "1");
}
savedRepeatingType = repeatingType;
fireAppointmentChanged();
}
public String getCommandoName() {
return getString("change")+ " " + getString("repeating");
}
}
public void nextFreeAppointment() {
Reservation reservation = appointment.getReservation();
Allocatable[] allocatables = reservation.getAllocatablesFor( appointment);
try
{
CalendarOptions options = getCalendarOptions();
Date newStart = getQuery().getNextAllocatableDate(Arrays.asList(allocatables), appointment,options );
if ( newStart != null)
{
Appointment oldState = ((AppointmentImpl) appointment).clone();
appointment.move(newStart);
Appointment newState = ((AppointmentImpl) appointment).clone();
UndoDataChange changeDataCommand = new UndoDataChange(oldState, newState);
commandHistory.storeAndExecute(changeDataCommand);
}
else
{
showWarning("No free appointment found", getMainComponent());
}
}
catch (RaplaException ex)
{
showException( ex, getMainComponent());
}
}
public class UndoDataChange implements CommandUndo<RuntimeException> {
private final Appointment oldState;
private final Appointment newState;
public UndoDataChange(Appointment oldState, Appointment newState) {
this.oldState = oldState;
this.newState = newState;
}
public boolean execute() {
((AppointmentImpl) appointment).copy(newState);
if ( appointment.isRepeatingEnabled())
{
repeatingEditor.mapFromAppointment();
}
else
{
singleEditor.mapFromAppointment();
}
fireAppointmentChanged();
return true;
}
public boolean undo() {
((AppointmentImpl) appointment).copy(oldState);
if ( appointment.isRepeatingEnabled())
{
repeatingEditor.mapFromAppointment();
}
else
{
singleEditor.mapFromAppointment();
}
fireAppointmentChanged();
return true;
}
public String getCommandoName() {
return getString("change")+ " " + getString("appointment");
}
}
@SuppressWarnings("unchecked")
private void setRenderer(JComboBox cb, ListCellRenderer listRenderer) {
cb.setRenderer( listRenderer);
}
@SuppressWarnings("unchecked")
private void setRenderer(JList cb, ListCellRenderer listRenderer) {
cb.setCellRenderer( listRenderer);
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/reservation/AppointmentController.java | Java | gpl3 | 50,431 |
/*--------------------------------------------------------------------------*
| 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.internal.edit;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.ResourceAnnotations;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.EditField;
import org.rapla.gui.internal.edit.fields.BooleanField;
import org.rapla.gui.internal.edit.fields.ClassificationField;
import org.rapla.gui.internal.edit.fields.PermissionListField;
/****************************************************************
* This is the controller-class for the Resource-Edit-Panel *
****************************************************************/
class AllocatableEditUI extends AbstractEditUI<Allocatable> {
ClassificationField<Allocatable> classificationField;
PermissionListField permissionField;
BooleanField holdBackConflictsField;
boolean internal =false;
public AllocatableEditUI(RaplaContext contest, boolean internal) throws RaplaException {
super(contest);
this.internal = internal;
ArrayList<EditField> fields = new ArrayList<EditField>();
classificationField = new ClassificationField<Allocatable>(contest);
fields.add(classificationField );
permissionField = new PermissionListField(contest,getString("permissions"));
fields.add( permissionField );
if ( !internal)
{
holdBackConflictsField = new BooleanField(contest,getString("holdbackconflicts"));
fields.add(holdBackConflictsField );
}
setFields(fields);
}
public void mapToObjects() throws RaplaException {
classificationField.mapTo( objectList);
permissionField.mapTo( objectList);
if ( getName(objectList).length() == 0)
throw new RaplaException(getString("error.no_name"));
if ( !internal)
{
Boolean value = holdBackConflictsField.getValue();
if ( value != null)
{
for ( Allocatable alloc:objectList)
{
alloc.setAnnotation(ResourceAnnotations.KEY_CONFLICT_CREATION, value ? ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE : null);
}
}
}
}
protected void mapFromObjects() throws RaplaException {
classificationField.mapFrom( objectList);
permissionField.mapFrom( objectList);
Set<Boolean> values = new HashSet<Boolean>();
for ( Allocatable alloc:objectList)
{
String annotation = alloc.getAnnotation( ResourceAnnotations.KEY_CONFLICT_CREATION);
boolean holdBackConflicts = annotation != null && annotation.equals( ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE);
values.add(holdBackConflicts);
}
if ( !internal)
{
if ( values.size() == 1)
{
Boolean singleValue = values.iterator().next();
holdBackConflictsField.setValue( singleValue);
}
if ( values.size() > 1)
{
holdBackConflictsField.setFieldForMultipleValues();
}
}
classificationField.setTypeChooserVisible( !internal);
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/AllocatableEditUI.java | Java | gpl3 | 4,219 |
package org.rapla.gui.internal.edit.fields;
public interface EditFieldWithLayout {
EditFieldLayout getLayout();
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/EditFieldWithLayout.java | Java | gpl3 | 120 |
package org.rapla.gui.internal.edit.fields;
import java.util.Collection;
public interface SetGetCollectionField<T> {
void setValues(Collection<T> values);
Collection<T> getValues();
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/SetGetCollectionField.java | Java | gpl3 | 194 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class AllocatableSelectField extends AbstractSelectField<Allocatable>
{
DynamicType dynamicTypeConstraint;
public AllocatableSelectField(RaplaContext context, DynamicType dynamicTypeConstraint){
super( context);
this.dynamicTypeConstraint = dynamicTypeConstraint;
}
@Override
protected Allocatable getValue(Object valueObject) {
if ( valueObject instanceof Allocatable)
{
return (Allocatable) valueObject;
}
else
{
return null;
}
}
@Override
protected String getNodeName(Allocatable selectedAllocatable)
{
return selectedAllocatable.getName(getI18n().getLocale());
}
@Override
public TreeModel createModel() throws RaplaException {
Allocatable[] allocatables;
if (dynamicTypeConstraint !=null)
{
ClassificationFilter filter = dynamicTypeConstraint.newClassificationFilter();
ClassificationFilter[] filters = new ClassificationFilter[] {filter};
allocatables = getQuery().getAllocatables(filters);
}
else
{
allocatables = getQuery().getAllocatables();
}
TreeModel treeModel = getTreeFactory().createClassifiableModel(allocatables);
if (dynamicTypeConstraint !=null)
{
TreeNode child = ((TreeNode)treeModel.getRoot()).getChildAt(0);
treeModel = new DefaultTreeModel( child );
}
return treeModel;
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/AllocatableSelectField.java | Java | gpl3 | 2,715 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.toolkit.AWTColorUtil;
public class TextField extends AbstractEditField implements ActionListener,FocusListener,KeyListener, MultiEditField, SetGetField<String> {
JTextComponent field;
JComponent colorPanel;
JScrollPane scrollPane;
JButton colorChooserBtn ;
JPanel color;
Object oldValue;
Color currentColor;
boolean multipleValues = false; // indicator, shows if multiple different
// values are shown in this field
public final static int DEFAULT_LENGTH = 30;
public TextField(RaplaContext context)
{
this( context,"", 1, TextField.DEFAULT_LENGTH);
}
public TextField(RaplaContext context,String fieldName)
{
this( context,fieldName, 1, TextField.DEFAULT_LENGTH);
}
public TextField(RaplaContext sm,String fieldName, int rows, int columns)
{
super( sm);
setFieldName( fieldName );
if ( rows > 1 ) {
JTextArea area = new JTextArea();
field = area;
scrollPane = new JScrollPane( field, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
area.setColumns( columns);
area.setRows( rows );
area.setLineWrap( true);
} else {
field = new JTextField( columns);
}
addCopyPaste( field);
field.addFocusListener(this);
field.addKeyListener(this);
if (fieldName.equals("color"))
{
colorPanel = new JPanel();
color = new JPanel();
color.setPreferredSize(new Dimension(20,20));
color.setBorder( BorderFactory.createEtchedBorder());
colorPanel.setLayout(new BorderLayout());
colorPanel.add( field, BorderLayout.CENTER);
colorPanel.add( color, BorderLayout.WEST);
colorChooserBtn = new JButton();
if ( field instanceof JTextField)
{
((JTextField) field).setColumns( 7);
}
else
{
((JTextArea) field).setColumns( 7);
}
colorPanel.add( colorChooserBtn, BorderLayout.EAST);
colorChooserBtn.setText( getString("change") );
colorChooserBtn.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentColor = JColorChooser.showDialog(
colorPanel,
"Choose Background Color",
currentColor);
color.setBackground( currentColor );
if ( currentColor != null) {
field.setText( AWTColorUtil.getHexForColor( currentColor ));
}
fireContentChanged();
}
});
}
setValue("");
}
public String getValue() {
return field.getText().trim();
}
public void setValue(String string) {
if (string == null)
string = "";
field.setText(string);
oldValue = string;
if ( colorPanel != null) {
try
{
currentColor = AWTColorUtil.getColorForHex( string);
}
catch (NumberFormatException ex)
{
currentColor = null;
}
color.setBackground( currentColor );
}
}
public JComponent getComponent() {
if ( colorPanel!= null)
{
return colorPanel;
}
if ( scrollPane != null ) {
return scrollPane;
} else {
return field;
}
}
public void selectAll()
{
field.selectAll();
}
public void actionPerformed(ActionEvent evt) {
if (field.getText().equals(oldValue))
return;
oldValue = field.getText();
fireContentChanged();
}
public void focusLost(FocusEvent evt) {
if (field.getText().equals(oldValue))
return;
// checks if entry was executed
if (field.getText().equals("") && multipleValues)
// no set place holder for multiple values
setFieldForMultipleValues();
else
// yes: reset flag, because there is just one common entry
multipleValues = false;
oldValue = field.getText();
fireContentChanged();
}
public void focusGained(FocusEvent evt) {
Component focusedComponent = evt.getComponent();
Component parent = focusedComponent.getParent();
if(parent instanceof JPanel) {
((JPanel)parent).scrollRectToVisible(focusedComponent.getBounds(null));
}
// if the place holder shown for different values, the place holder
// should be deleted
if (multipleValues) {
setValue("");
// set font PLAIN (place holder is shown italic)
field.setFont(field.getFont().deriveFont(Font.PLAIN));
}
}
public void keyPressed(KeyEvent evt) {}
public void keyTyped(KeyEvent evt) {}
public void keyReleased(KeyEvent evt) {
if (field.getText().equals(oldValue))
return;
// reset flag, because there is just one common entry
if (multipleValues) {
multipleValues = false;
}
oldValue = field.getText();
fireContentChanged();
}
public void setFieldForMultipleValues() {
// set a place holder for multiple different values (italic)
field.setFont(field.getFont().deriveFont(Font.ITALIC));
field.setText(TextField.getOutputForMultipleValues());
multipleValues = true;
}
public boolean hasMultipleValues() {
return multipleValues;
}
static public String getOutputForMultipleValues() {
// place holder for mulitple different values
return "<multiple Values>";
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/TextField.java | Java | gpl3 | 7,398 |
package org.rapla.gui.internal.edit.fields;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.entities.Category;
import org.rapla.entities.User;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.toolkit.RaplaButton;
public class GroupListField extends AbstractEditField implements ChangeListener, ActionListener, EditFieldWithLayout {
DefaultListModel model = new DefaultListModel();
JPanel panel = new JPanel();
JToolBar toolbar = new JToolBar();
CategorySelectField newCategory;
RaplaButton removeButton = new RaplaButton(RaplaButton.SMALL);
RaplaButton newButton = new RaplaButton(RaplaButton.SMALL);
JList list = new JList();
Set<Category> notAllList = new HashSet<Category>();
/**
* @param context
* @throws RaplaException
*/
public GroupListField(RaplaContext context) throws RaplaException {
super(context);
final Category rootCategory = getQuery().getUserGroupsCategory();
if ( rootCategory == null )
return;
newCategory = new CategorySelectField(context, rootCategory );
newCategory.setUseNull( false);
toolbar.add( newButton );
toolbar.add( removeButton );
toolbar.setFloatable( false );
panel.setLayout( new BorderLayout() );
panel.add( toolbar, BorderLayout.NORTH );
final JScrollPane jScrollPane = new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jScrollPane.setPreferredSize( new Dimension( 300, 150 ) );
panel.add( jScrollPane, BorderLayout.CENTER );
newButton.setText( getString( "group" ) + " " + getString( "add" ) );
removeButton.setText( getString( "group" ) + " " + getString( "remove" ) );
newButton.setIcon( getIcon( "icon.new" ) );
removeButton.setIcon( getIcon( "icon.remove" ) );
newCategory.addChangeListener( this );
newButton.addActionListener( this );
removeButton.addActionListener( this );
DefaultListCellRenderer cellRenderer = new DefaultListCellRenderer() {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
Category category = (Category) value;
if ( value != null ) {
value = category.getPath( rootCategory
, getI18n().getLocale());
}
Component component = super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
if (notAllList.contains( category))
{
Font f =component.getFont().deriveFont(Font.ITALIC);
component.setFont(f);
}
return component;
}
};
setRenderer(cellRenderer);
}
@SuppressWarnings("unchecked")
private void setRenderer(DefaultListCellRenderer cellRenderer) {
list.setCellRenderer(cellRenderer );
}
public JComponent getComponent() {
return panel;
}
@Override
public EditFieldLayout getLayout() {
EditFieldLayout layout = new EditFieldLayout();
layout.setBlock( true);
layout.setVariableSized( false);
return layout;
}
public void mapFrom(List<User> users) {
Set<Category> categories = new LinkedHashSet<Category>();
// determination of the common categories/user groups
for (User user:users) {
categories.addAll(Arrays.asList(user.getGroups()));
}
Set<Category> notAll = new LinkedHashSet<Category>();
for ( Category group: categories)
{
for (User user:users)
{
if (!user.belongsTo( group))
{
notAll.add(group);
}
}
}
mapFromList(categories,notAll);
}
public void mapToList(Collection<Category> groups) {
groups.clear();
@SuppressWarnings({ "unchecked", "cast" })
Enumeration<Category> it = (Enumeration<Category>) model.elements();
while (it.hasMoreElements())
{
Category cat= it.nextElement();
groups.add( cat);
}
}
public void mapFromList(Collection<Category> groups) {
mapFromList(groups, new HashSet<Category>());
}
@SuppressWarnings("unchecked")
private void mapFromList(Collection<Category> groups,Set<Category> notToAll) {
model.clear();
this.notAllList = notToAll;
for ( Category cat:groups) {
model.addElement( cat );
}
list.setModel(model);
}
public void mapTo(List<User> users) {
for (User user:users)
{
for (Category cat : user.getGroups())
{
if (!model.contains( cat) && !notAllList.contains( cat))
{
user.removeGroup( cat);
}
}
@SuppressWarnings({ "unchecked", "cast" })
Enumeration<Category> it = (Enumeration<Category>) model.elements();
while (it.hasMoreElements())
{
Category cat= it.nextElement();
if ( !user.belongsTo( cat) && !notAllList.contains( cat))
{
user.addGroup( cat);
}
}
}
}
public void actionPerformed(ActionEvent evt) {
if ( evt.getSource() == newButton)
{
try {
newCategory.setValue( null );
newCategory.showDialog(newButton);
} catch (RaplaException ex) {
showException(ex,newButton);
}
}
if ( evt.getSource() == removeButton)
{
@SuppressWarnings("deprecation")
Object[] selectedValues = list.getSelectedValues();
for ( Object value: selectedValues)
{
Category group = (Category) value;
if (group != null) {
model.removeElement( group );
notAllList.remove( group);
fireContentChanged();
}
}
}
}
@SuppressWarnings("unchecked")
public void stateChanged(ChangeEvent evt) {
Collection<Category> newGroup = newCategory.getValues();
for ( Category group:newGroup)
{
notAllList.remove( group);
if ( ! model.contains( group ) ) {
model.addElement( group );
}
}
fireContentChanged();
list.repaint();
}
} | 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/GroupListField.java | Java | gpl3 | 7,395 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.Category;
import org.rapla.entities.User;
import org.rapla.entities.domain.Permission;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class PermissionField extends AbstractEditField implements ChangeListener, ActionListener {
SetGetField<Category> groupSelect;
ListField<User> userSelect;
JPanel panel = new JPanel();
JPanel reservationPanel;
Permission permission;
JComboBox startSelection = new JComboBox();
JComboBox endSelection = new JComboBox();
DateField startDate;
DateField endDate;
LongField minAdvance;
LongField maxAdvance;
ListField<Integer> accessField;
@SuppressWarnings("unchecked")
public PermissionField(RaplaContext context) throws RaplaException {
super( context);
panel.setBorder(BorderFactory.createEmptyBorder(5,8,5,8));
double pre =TableLayout.PREFERRED;
double fill =TableLayout.FILL;
panel.setLayout( new TableLayout( new double[][]
{{fill, 5}, // Columns
{pre,5,pre,5,pre}} // Rows
));
JPanel userPanel = new JPanel();
panel.add( userPanel , "0,0,f,f" );
userPanel.setLayout( new TableLayout( new double[][]
{{pre, 10, fill, 5}, // Columns
{pre,5,pre,5,pre}} // Rows
));
userSelect = new UserListField( context );
userPanel.add( new JLabel(getString("user") + ":"), "0,0,l,f" );
userPanel.add( userSelect.getComponent(),"2,0,l,f" );
Category rootCategory = getQuery().getUserGroupsCategory();
if ( rootCategory != null) {
AbstractEditField groupSelect;
if (rootCategory.getDepth() > 2) {
CategorySelectField field= new CategorySelectField(getContext(), rootCategory);
this.groupSelect = field;
groupSelect = field;
} else {
CategoryListField field = new CategoryListField(getContext(), rootCategory);
this.groupSelect = field;
groupSelect = field;
}
userPanel.add( new JLabel(getString("group") + ":"), "0,2,l,f" );
userPanel.add( groupSelect.getComponent(),"2,2,l,f" );
groupSelect.addChangeListener( this );
}
reservationPanel = new JPanel();
panel.add( reservationPanel , "0,2,f,f" );
reservationPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), getString("allocatable_in_timeframe") + ":" ));
reservationPanel.setLayout( new TableLayout( new double[][]
{{pre,3, pre, 5, pre, 5}, // Columns
{pre, 5, pre}} // Rows
));
reservationPanel.add( new JLabel( getString("start_date") + ":" ) , "0,0,l,f" );
reservationPanel.add( startSelection , "2,0,l,f" );
startSelection.setModel( createSelectionModel() );
startSelection.setSelectedIndex( 0 );
startDate = new DateField(context);
reservationPanel.add( startDate.getComponent() , "4,0,l,f" );
minAdvance = new LongField(context,new Long(0) );
reservationPanel.add( minAdvance.getComponent() , "4,0,l,f" );
reservationPanel.add( new JLabel( getString("end_date") + ":" ), "0,2,l,f" );
reservationPanel.add( endSelection , "2,2,l,f" );
endSelection.setModel( createSelectionModel() );
endSelection.setSelectedIndex( 0 );
endDate = new DateField(context);
reservationPanel.add( endDate.getComponent() , "4,2,l,f" );
maxAdvance = new LongField(context, new Long(1) );
reservationPanel.add( maxAdvance.getComponent() , "4,2,l,f" );
userPanel.add( new JLabel(getString("permission.access") + ":"), "0,4,f,f" );
Collection<Integer> vector = new ArrayList<Integer>();
for (Integer accessLevel:Permission.ACCESS_LEVEL_NAMEMAP.keySet())
{
vector.add( accessLevel ) ;
}
accessField = new ListField<Integer>(context, vector );
accessField.setRenderer( new DefaultListCellRenderer() {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value != null) {
String key = Permission.ACCESS_LEVEL_NAMEMAP.get( ((Integer) value).intValue() );
value = getI18n().getString("permission." + key );
}
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus );
}}
);
userPanel.add( accessField.getComponent(), "2,4,f,f" );
toggleVisibility();
userSelect.addChangeListener( this );
startSelection.addActionListener(this);
minAdvance.addChangeListener(this);
startDate.addChangeListener(this);
endSelection.addActionListener(this);
maxAdvance.addChangeListener(this);
endDate.addChangeListener(this);
accessField.addChangeListener(this);
panel.revalidate();
}
public JComponent getComponent() {
return panel;
}
@SuppressWarnings("unchecked")
private DefaultComboBoxModel createSelectionModel() {
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.addElement(getString( "open" ) );
model.addElement(getString( "fixed_date") );
model.addElement(getString( "x_days_advance") );
return model;
}
private void toggleVisibility() {
int level = accessField.getValue().intValue();
reservationPanel.setVisible( level >= Permission.ALLOCATE && level < Permission.ADMIN);
int i = startSelection.getSelectedIndex();
startDate.getComponent().setVisible( i == 1 );
minAdvance.getComponent().setVisible( i == 2 );
int j = endSelection.getSelectedIndex();
endDate.getComponent().setVisible( j == 1 );
maxAdvance.getComponent().setVisible( j == 2 );
}
boolean listenersDisabled = false;
public void setValue(Permission value) {
try {
listenersDisabled = true;
permission = value;
int startIndex = 0;
if ( permission.getStart() != null )
startIndex = 1;
if ( permission.getMinAdvance() != null )
startIndex = 2;
startSelection.setSelectedIndex( startIndex );
int endIndex = 0;
if ( permission.getEnd() != null )
endIndex = 1;
if ( permission.getMaxAdvance() != null )
endIndex = 2;
endSelection.setSelectedIndex( endIndex );
startDate.setValue( permission.getStart());
minAdvance.setValue( permission.getMinAdvance());
endDate.setValue(permission.getEnd() );
maxAdvance.setValue(permission.getMaxAdvance());
if ( groupSelect != null )
{
groupSelect.setValue( permission.getGroup());
}
userSelect.setValue(permission.getUser() );
accessField.setValue( permission.getAccessLevel() );
toggleVisibility();
} finally {
listenersDisabled = false;
}
}
public void actionPerformed(ActionEvent evt) {
if ( listenersDisabled )
return;
if (evt.getSource() == startSelection) {
int i = startSelection.getSelectedIndex();
if ( i == 0 ) {
permission.setStart( null );
permission.setMinAdvance( null );
}
if ( i == 1 ) {
Date today = getQuery().today();
permission.setStart( today );
startDate.setValue( today);
} if ( i == 2 ) {
permission.setMinAdvance( new Integer(0) );
minAdvance.setValue( new Integer(0 ));
}
}
if (evt.getSource() == endSelection) {
int i = endSelection.getSelectedIndex();
if ( i == 0 ) {
permission.setEnd( null );
permission.setMaxAdvance( null );
}
if ( i == 1 ) {
Date today = getQuery().today();
permission.setEnd( today );
endDate.setValue( today);
} if ( i == 2 ) {
permission.setMaxAdvance( new Integer( 30 ) );
maxAdvance.setValue( new Integer(30));
}
}
toggleVisibility();
fireContentChanged();
}
public Permission getValue() {
return permission;
}
public void stateChanged(ChangeEvent evt) {
if ( listenersDisabled )
return;
Permission perm = permission;
if (evt.getSource() == groupSelect) {
perm.setGroup(groupSelect.getValue() );
userSelect.setValue(perm.getUser()) ;
} else if (evt.getSource() == userSelect) {
perm.setUser( userSelect.getValue());
if ( groupSelect != null )
groupSelect.setValue(perm.getGroup());
} else if (evt.getSource() == startDate) {
perm.setStart(startDate.getValue() );
} else if (evt.getSource() == minAdvance) {
perm.setMinAdvance( minAdvance.getIntValue());
} else if (evt.getSource() == endDate) {
perm.setEnd(endDate.getValue());
} else if (evt.getSource() == maxAdvance) {
perm.setMaxAdvance(maxAdvance.getIntValue() );
} else if (evt.getSource() == accessField ) {
perm.setAccessLevel( accessField.getValue() );
toggleVisibility();
}
fireContentChanged();
}
class UserListField extends ListField<User> {
public UserListField(RaplaContext sm) throws RaplaException{
super(sm,true);
setVector(Arrays.asList(getQuery().getUsers() ));
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/PermissionField.java | Java | gpl3 | 11,867 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Reservation;
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.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.internal.common.NamedListCellRenderer;
import org.rapla.gui.internal.edit.ClassificationEditUI;
import org.rapla.gui.toolkit.RaplaListComboBox;
/****************************************************************
* This is the base-class for all Classification-Panels *
****************************************************************/
public class ClassificationField<T extends Classifiable> extends AbstractEditField
implements EditFieldWithLayout,
ActionListener
{
JPanel content = new JPanel();
RaplaListComboBox typeSelector;
ClassificationEditUI editUI;
DynamicType oldDynamicType;
List<Classification> oldClassifications; // enhancement to array
final String multipleValues = TextField.getOutputForMultipleValues();
public ClassificationField(RaplaContext context) {
super(context);
editUI = new ClassificationEditUI(context);
setFieldName("type");
content.setBorder(BorderFactory.createEmptyBorder(3, 2, 3, 2));
}
@Override
public EditFieldLayout getLayout() {
EditFieldLayout layout = new EditFieldLayout();
layout.setBlock( true);
layout.setVariableSized( true);
return layout;
}
public void mapTo(List<T> list) throws RaplaException {
List<Classification> classifications = editUI.getObjects();
for (int i = 0; i < list.size(); i++)
{
Classification classification = classifications.get( i );
Classifiable x = list.get(i);
x.setClassification(classification);
}
editUI.mapToObjects();
}
public void setTypeChooserVisible( boolean visible)
{
if ( typeSelector != null)
{
typeSelector.setVisible( visible);
}
}
@SuppressWarnings("unchecked")
public void mapFrom(List<T> list) throws RaplaException {
content.removeAll();
List<Classifiable> classifiables = new ArrayList<Classifiable>();
// read out Classifications from Classifiable
List<Classification> classifications = new ArrayList<Classification>();
for (Classifiable classifiable:list)
{
classifiables.add( classifiable);
Classification classification = classifiable.getClassification();
classifications.add(classification);
}
// commit Classifications to ClassificationEditUI
editUI.setObjects(classifications);
oldClassifications = classifications;
// checks unity from RaplaTypes of all Classifiables
Set<RaplaType> raplaTypes = new HashSet<RaplaType>();
for (Classifiable c : classifiables) {
raplaTypes.add(((RaplaObject) c).getRaplaType());
}
RaplaType raplaType;
// if there is an unitary type then set typ
if (raplaTypes.size() == 1) {
raplaType = raplaTypes.iterator().next();
} else {
return;
}
String classificationType = null;
if (Reservation.TYPE.equals(raplaType)) {
classificationType = DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION;
} else if (Allocatable.TYPE.equals(raplaType)) {
boolean arePersons = true;
// checks if Classifiables are person
for (Classifiable c : classifiables) {
if (!((Allocatable) c).isPerson()) {
arePersons = false;
}
}
if (arePersons) {
classificationType = DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON;
} else {
classificationType = DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE;
}
}
DynamicType[] types = getQuery().getDynamicTypes(classificationType);
// determine DynamicTypes of Classifications
Set<DynamicType> dynamicTypes = new HashSet<DynamicType>();
for (Classification c : classifications) {
dynamicTypes.add(c.getType());
}
DynamicType dynamicType;
// checks if there is a common DynamicType?
if (dynamicTypes.size() == 1)
// set dynamicTyp
dynamicType = dynamicTypes.iterator().next();
else
dynamicType = null;
oldDynamicType = dynamicType;
RaplaListComboBox jComboBox = new RaplaListComboBox(getContext(),types);
typeSelector = jComboBox;
typeSelector.setEnabled( types.length > 1);
if (dynamicType != null)
// set common dynamicType of the Classifications in ComboBox
typeSelector.setSelectedItem(dynamicType);
else {
// ... otherwise set place holder for the several values
typeSelector.addItem(multipleValues);
typeSelector.setSelectedItem(multipleValues);
}
typeSelector.setRenderer(new NamedListCellRenderer(getI18n().getLocale()));
typeSelector.addActionListener(this);
content.setLayout(new BorderLayout());
JPanel container = new JPanel();
container.setLayout(new BorderLayout());
container.add(typeSelector, BorderLayout.WEST);
content.add(container, BorderLayout.NORTH);
JComponent editComponent = editUI.getComponent();
JScrollPane scrollPane = new JScrollPane(editComponent,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setViewportView(editComponent);
scrollPane.setBorder(BorderFactory.createEtchedBorder());
scrollPane.setMinimumSize(new Dimension(300, 100));
scrollPane.setPreferredSize(new Dimension(500, 340));
scrollPane.getVerticalScrollBar().setUnitIncrement( 10);
content.add(scrollPane, BorderLayout.CENTER);
}
// The DynamicType has changed
public void actionPerformed(ActionEvent event) {
try {
Object source = event.getSource();
if (source == typeSelector) {
// checks if a DynamicType has been selected in ComboBox
if (typeSelector.getSelectedItem() instanceof DynamicType) {
// delete place holder for the several values
typeSelector.removeItem(multipleValues);
DynamicType dynamicType = (DynamicType) typeSelector
.getSelectedItem();
// checks if no new DynmicType has been selected
if (dynamicType.equals(oldDynamicType))
// yes: set last Classifications again
editUI.setObjects(oldClassifications);
else {
// no: set new Classifications
List<Classification> newClassifications = new ArrayList<Classification>();
List<Classification> classifications = editUI.getObjects();
for (int i = 0; i < classifications.size(); i++) {
Classification classification = classifications.get(i);
// checks if Classification hast already the new
// selected DynamicType
if (dynamicType.equals(classification .getType())) {
// yes: adopt Classification
newClassifications.add( classification );
} else {
// no: create new Classification
newClassifications.add( dynamicType.newClassification(classification));
}
}
// set new Classifications in ClassificationEditUI
editUI.setObjects(newClassifications);
}
}
}
} catch (RaplaException ex) {
showException(ex, content);
}
}
public JComponent getComponent() {
return content;
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/ClassificationField.java | Java | gpl3 | 8,583 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.toolkit.RaplaListComboBox;
public class ListField<T> extends AbstractEditField implements ActionListener,FocusListener, MultiEditField, SetGetField<T>, SetGetCollectionField<T> {
JPanel panel;
JComboBox field;
protected String nothingSelected;
Vector<Object> list;
boolean multipleValues = false; // indicator, shows if multiple different
// values are shown in this field
final String multipleValuesOutput = TextField.getOutputForMultipleValues();
boolean includeNothingSelected;
public ListField(RaplaContext context, Collection<T> v)
{
this(context, false);
setVector(v);
}
public ListField(RaplaContext sm, boolean includeNothingSelected)
{
super(sm);
this.includeNothingSelected = includeNothingSelected;
setFieldName(fieldName);
panel = new JPanel();
panel.setOpaque(false);
field = new RaplaListComboBox(sm);
field.addActionListener(this);
panel.setLayout(new BorderLayout());
panel.add(field, BorderLayout.WEST);
nothingSelected = getString("nothing_selected");
field.addFocusListener(this);
}
@SuppressWarnings("unchecked")
public void setVector(Collection<T> v) {
this.list = new Vector<Object>(v);
if ( includeNothingSelected)
{
list.insertElementAt(nothingSelected, 0);
}
DefaultComboBoxModel aModel = new DefaultComboBoxModel(list);
field.setModel(aModel);
}
@SuppressWarnings("unchecked")
public void setRenderer(ListCellRenderer renderer) {
field.setRenderer(renderer);
}
public Collection<T> getValues() {
Object value = field.getSelectedItem();
if (list.contains(nothingSelected) && nothingSelected.equals(value)) {
return Collections.emptyList();
} else {
@SuppressWarnings("unchecked")
T casted = (T) value;
return Collections.singletonList( casted);
}
}
public T getValue()
{
Collection<T> values = getValues();
if ( values.size() == 0)
{
return null;
}
else
{
T first = values.iterator().next();
return first;
}
}
public void setValue(T object)
{
List<T> list;
if ( object == null)
{
list = Collections.emptyList();
}
else
{
list = Collections.singletonList(object);
}
setValues(list);
}
public void setValues(Collection<T> value) {
if (list.contains(nothingSelected) && (value == null || value.size() == 0) ) {
field.setSelectedItem(nothingSelected);
} else {
if ( value != null && value.size() > 0)
{
T first = value.iterator().next();
field.setSelectedItem(first);
}
else
{
field.setSelectedItem(null);
}
}
}
public JComponent getComponent() {
return panel;
}
public void actionPerformed(ActionEvent evt) {
// checks if a new common value has been set
if (multipleValues && field.getSelectedItem() != multipleValuesOutput) {
// delete place holder for multiple different values
multipleValues = false;
field.removeItem(multipleValuesOutput);
}
fireContentChanged();
}
public void focusGained(FocusEvent evt) {
Component focusedComponent = evt.getComponent();
Component parent = focusedComponent.getParent();
if (parent instanceof JPanel) {
((JPanel) parent).scrollRectToVisible(focusedComponent
.getBounds(null));
}
}
public void focusLost(FocusEvent evt) {
}
// implementation of interface MultiEditField
public boolean hasMultipleValues() {
return multipleValues;
}
// implementation of interface MultiEditField
@SuppressWarnings("unchecked")
public void setFieldForMultipleValues() {
multipleValues = true;
// place holder for multiple different values
field.addItem(multipleValuesOutput);
field.setSelectedItem(multipleValuesOutput);
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/ListField.java | Java | gpl3 | 5,352 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import java.util.Vector;
import org.rapla.entities.Category;
import org.rapla.framework.RaplaContext;
public class CategoryListField extends ListField<Category> {
Category rootCategory;
public CategoryListField(RaplaContext context,Category rootCategory) {
super(context, true);
this.rootCategory = rootCategory;
Category[] obj = rootCategory.getCategories();
Vector<Category> list = new Vector<Category>();
for (int i=0;i<obj.length;i++)
list.add(obj[i]);
setVector(list);
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/CategoryListField.java | Java | gpl3 | 1,538 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import java.util.ArrayList;
import javax.swing.JComponent;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.EditField;
import org.rapla.gui.RaplaGUIComponent;
/** 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 abstract class AbstractEditField extends RaplaGUIComponent
implements EditField
{
String fieldName;
ArrayList<ChangeListener> listenerList = new ArrayList<ChangeListener>();
public AbstractEditField(RaplaContext context) {
super(context);
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(listener);
}
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(listener);
}
public ChangeListener[] getChangeListeners() {
return listenerList.toArray(new ChangeListener[]{});
}
protected void fireContentChanged() {
if (listenerList.size() == 0)
return;
ChangeEvent evt = new ChangeEvent(this);
ChangeListener[] listeners = getChangeListeners();
for (int i = 0;i<listeners.length; i++) {
listeners[i].stateChanged(evt);
}
}
abstract public JComponent getComponent();
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getFieldName() {
return this.fieldName;
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/AbstractEditField.java | Java | gpl3 | 2,610 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.components.calendar.RaplaNumber;
import org.rapla.framework.RaplaContext;
public class LongField extends AbstractEditField implements ChangeListener, FocusListener, MultiEditField, SetGetField<Long>{
JPanel panel = new JPanel();
RaplaNumber field;
boolean multipleValues = false; // indicator, shows if multiple different
// values are shown in this field
JLabel multipleValuesLabel = new JLabel();
public LongField(RaplaContext context, String fieldName) {
this(context, (Long)null);
setFieldName(fieldName);
}
public LongField(RaplaContext context) {
this(context, (Long)null);
}
public LongField(RaplaContext context, Long minimum)
{
super(context);
panel.setLayout(new BorderLayout());
panel.setOpaque(false);
field = new RaplaNumber(minimum, minimum, null, minimum == null);
addCopyPaste(field.getNumberField());
field.setColumns(8);
field.addChangeListener(this);
panel.add(field, BorderLayout.WEST);
panel.add(multipleValuesLabel, BorderLayout.CENTER);
field.addFocusListener(this);
}
public Long getValue() {
if (field.getNumber() != null)
return new Long(field.getNumber().longValue());
else
return null;
}
public Integer getIntValue() {
if (field.getNumber() != null)
return new Integer(field.getNumber().intValue());
else
return null;
}
public void setValue(Long object) {
if (object != null) {
field.setNumber( object);
} else {
field.setNumber(null);
}
}
public void setValue(Integer object) {
if (object != null) {
field.setNumber( object);
} else {
field.setNumber(null);
}
}
public void stateChanged(ChangeEvent evt) {
// if entry was executed: a common value has been set -> change flag, no
// place holder has to be shown anymore
if (multipleValues) {
multipleValues = false;
multipleValuesLabel.setText("");
}
fireContentChanged();
}
public JComponent getComponent() {
return panel;
}
public void focusGained(FocusEvent evt) {
Component focusedComponent = evt.getComponent();
Component parent = focusedComponent.getParent();
if (parent instanceof JPanel) {
((JPanel) parent).scrollRectToVisible(focusedComponent
.getBounds(null));
}
}
public void focusLost(FocusEvent evt) {
}
// implementation for interface MultiEditField
public boolean hasMultipleValues() {
return multipleValues;
}
// implementation for interface MultiEditField
public void setFieldForMultipleValues() {
multipleValues = true;
// place holder for multiple different values:
multipleValuesLabel.setText(TextField.getOutputForMultipleValues());
multipleValuesLabel.setFont(multipleValuesLabel.getFont().deriveFont(Font.ITALIC));
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/LongField.java | Java | gpl3 | 4,028 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import javax.swing.tree.TreeModel;
import org.rapla.entities.Category;
import org.rapla.framework.RaplaContext;
public class CategorySelectField extends AbstractSelectField<Category>
{
Category rootCategory;
public CategorySelectField(RaplaContext context,Category rootCategory){
this( context, rootCategory, null);
}
public CategorySelectField(RaplaContext context,Category rootCategory, Category defaultCategory) {
super( context, defaultCategory);
this.rootCategory = rootCategory;
}
@Override
protected String getNodeName(Category selectedCategory)
{
return selectedCategory.getPath(rootCategory,getI18n().getLocale());
}
@Override
public TreeModel createModel() {
return getTreeFactory().createModel(rootCategory);
}
public Category getRootCategory()
{
return rootCategory;
}
public void setRootCategory(Category rootCategory)
{
this.rootCategory = rootCategory;
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/CategorySelectField.java | Java | gpl3 | 1,979 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Permission;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.internal.edit.RaplaListEdit;
import org.rapla.gui.toolkit.EmptyLineBorder;
/**
* @author Christopher Kohlhaas
*/
public class PermissionListField extends AbstractEditField implements EditFieldWithLayout
{
JList permissionList = new JList();
JPanel jPanel = new JPanel();
PermissionField permissionField;
private RaplaListEdit<Permission> listEdit;
Listener listener = new Listener();
Allocatable firstAllocatable;
DefaultListModel model = new DefaultListModel();
Permission selectedPermission = null;
int selectedIndex = 0;
List<Permission> notAllList = new ArrayList<Permission>();
public PermissionListField(RaplaContext context, String fieldName) throws RaplaException {
super(context);
permissionField = new PermissionField(context);
super.setFieldName(fieldName);
jPanel.setLayout(new BorderLayout());
listEdit = new RaplaListEdit<Permission>(getI18n(), permissionField.getComponent(), listener);
jPanel.add(listEdit.getComponent(), BorderLayout.CENTER);
jPanel.setBorder(BorderFactory.createTitledBorder(new EmptyLineBorder(), getString("permissions")));
permissionField.addChangeListener(listener);
}
public JComponent getComponent() {
return jPanel;
}
public EditFieldLayout getLayout()
{
EditFieldLayout layout = new EditFieldLayout();
return layout;
}
public void mapTo(List<Allocatable> list) {
for (Allocatable allocatable :list)
{
for (Permission perm : allocatable.getPermissions())
{
if (!model.contains( perm) )
{
allocatable.removePermission(perm);
}
}
@SuppressWarnings({ "unchecked", "cast" })
Enumeration<Permission> it = (Enumeration<Permission>) model.elements();
while (it.hasMoreElements())
{
Permission perm= it.nextElement();
if ( !hasPermission(allocatable, perm) && !isNotForAll( perm))
{
allocatable.addPermission( perm);
}
}
}
}
private boolean hasPermission(Allocatable allocatable, Permission permission) {
for (Permission perm: allocatable.getPermissions())
{
if (perm.equals( permission))
{
return true;
}
}
return false;
}
@SuppressWarnings("unchecked")
public void mapFrom(List<Allocatable> list) {
model.clear();
firstAllocatable = list.size() > 0 ? list.get(0) : null;
Set<Permission> permissions = new LinkedHashSet<Permission>();
for (Allocatable allocatable :list)
{
List<Permission> permissionList = Arrays.asList(allocatable.getPermissions());
permissions.addAll(permissionList);
}
Set<Permission> set = new LinkedHashSet<Permission>();
for (Permission perm : permissions) {
model.addElement(perm);
for (Allocatable allocatable:list)
{
List<Permission> asList = Arrays.asList(allocatable.getPermissions());
if (!asList.contains(perm))
{
set.add( perm);
}
}
}
notAllList.clear();
for (Permission perm : set)
{
notAllList.add(perm);
}
listEdit.setListDimension(new Dimension(210, 90));
listEdit.setMoveButtonVisible(false);
listEdit.getList().setModel(model);
listEdit.getList().setCellRenderer(new DefaultListCellRenderer() {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
Permission p = (Permission) value;
if (p.getUser() != null) {
value = getString("user") + " " + p.getUser().getUsername();
} else if (p.getGroup() != null) {
value = getString("group") + " "
+ p.getGroup().getName(getI18n().getLocale());
} else {
value = getString("all_users");
}
value = (index + 1) + ") " + value;
Component component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
Font f;
if (isNotForAll( p))
{
f =component.getFont().deriveFont(Font.ITALIC);
}
else
{
f =component.getFont().deriveFont(Font.BOLD);
}
component.setFont(f);
return component;
}
});
}
// Check if permission is in notAllList. We need to check references as the equals method could also match another permission
private boolean isNotForAll( Permission p) {
for (Permission perm: notAllList)
{
if ( perm == p)
{
return true;
}
}
return false;
}
private void removePermission() {
for (Permission permission:listEdit.getSelectedValues())
{
model.removeElement(permission);
}
listEdit.getList().requestFocus();
}
@SuppressWarnings("unchecked")
private void createPermission() {
if ( firstAllocatable == null)
{
return;
}
Permission permission = firstAllocatable.newPermission();
model.addElement(permission);
}
class Listener implements ActionListener, ChangeListener {
public void actionPerformed(ActionEvent evt) {
if (evt.getActionCommand().equals("remove")) {
removePermission();
} else if (evt.getActionCommand().equals("new")) {
createPermission();
} else if (evt.getActionCommand().equals("edit")) {
// buffer selected Permission
selectedPermission = (Permission) listEdit.getList().getSelectedValue();
selectedIndex = listEdit.getList().getSelectedIndex();
// commit common Permissions (like the selected one) for
// processing
permissionField.setValue(selectedPermission);
}
}
@SuppressWarnings("unchecked")
public void stateChanged(ChangeEvent evt) {
// set processed selected Permission in the list
model.set(selectedIndex, selectedPermission);
// remove permission from notAllList we need to check references as the equals method could also match another permission
Iterator<Permission> it = notAllList.iterator();
while (it.hasNext())
{
Permission next = it.next();
if ( next == selectedPermission )
{
it.remove();
}
}
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/PermissionListField.java | Java | gpl3 | 7,736 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import javax.swing.AbstractCellEditor;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
import org.rapla.entities.MultiLanguageName;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.RaplaButton;
public class MultiLanguageField extends AbstractEditField implements ChangeListener, ActionListener,CellEditorListener, SetGetField<MultiLanguageName> {
JPanel panel = new JPanel();
TextField textField;
RaplaButton button = new RaplaButton(RaplaButton.SMALL);
MultiLanguageName name = new MultiLanguageName();
MultiLanguageEditorDialog editorDialog;
String[] availableLanguages;
public MultiLanguageField(RaplaContext context, String fieldName)
{
this(context);
setFieldName(fieldName);
}
public MultiLanguageField(RaplaContext context)
{
super( context);
textField = new TextField(context, "name");
availableLanguages = getRaplaLocale().getAvailableLanguages();
panel.setLayout( new BorderLayout() );
panel.add( textField.getComponent(), BorderLayout.CENTER );
panel.add( button, BorderLayout.EAST );
button.addActionListener( this );
button.setIcon( getIcon("icon.language-select") );
textField.addChangeListener( this );
}
public void requestFocus() {
textField.getComponent().requestFocus();
}
public void selectAll()
{
textField.selectAll();
}
public void stateChanged(ChangeEvent e) {
if (name != null) {
name.setName(getI18n().getLang(),textField.getValue());
fireContentChanged();
}
}
public void actionPerformed(ActionEvent evt) {
editorDialog = new MultiLanguageEditorDialog( button );
editorDialog.addCellEditorListener( this );
editorDialog.setEditorValue( name );
try {
editorDialog.show();
} catch (RaplaException ex) {
showException( ex, getComponent());
}
}
public void editingStopped(ChangeEvent e) {
setValue((MultiLanguageName) editorDialog.getEditorValue());
fireContentChanged();
}
public void editingCanceled(ChangeEvent e) {
}
public MultiLanguageName getValue() {
return this.name;
}
public void setValue(MultiLanguageName object) {
this.name = object;
textField.setValue(name.getName(getI18n().getLang()));
}
public JComponent getComponent() {
return panel;
}
class MultiLanguageEditorDialog extends AbstractCellEditor {
private static final long serialVersionUID = 1L;
JTable table = new JTable();
JLabel label = new JLabel();
JPanel comp = new JPanel();
MultiLanguageName editorValue;
Component owner;
MultiLanguageEditorDialog(JComponent owner) {
this.owner = owner;
table.setPreferredScrollableViewportSize(new Dimension(300, 200));
comp.setLayout(new BorderLayout());
comp.add(label,BorderLayout.NORTH);
comp.add(new JScrollPane(table),BorderLayout.CENTER);
}
public void setEditorValue(Object value) {
this.editorValue = (MultiLanguageName)value;
table.setModel(new TranslationTableModel(editorValue));
table.getColumnModel().getColumn(0).setPreferredWidth(30);
table.getColumnModel().getColumn(1).setPreferredWidth(200);
label.setText(getI18n().format("translation.format", editorValue));
}
public Object getEditorValue() {
return editorValue;
}
public Object getCellEditorValue() {
return getEditorValue();
}
public void show() throws RaplaException {
DialogUI dlg = DialogUI.create(getContext(),owner,true,comp,new String[] { getString("ok"),getString("cancel")});
dlg.setTitle(getString("translation"));
// Workaround for Bug ID 4480264 on developer.java.sun.com
if (table.getRowCount() > 0 ) {
table.editCellAt(0, 0);
table.editCellAt(0, 1);
}
dlg.start();
if (dlg.getSelectedIndex() == 0) {
for (int i=0;i<availableLanguages.length;i++) {
String value = (String)table.getValueAt(i,1);
if (value != null)
editorValue.setName(availableLanguages[i],value);
}
if (table.isEditing()) {
if (table.getEditingColumn() == 1) {
JTextField textField = (JTextField) table.getEditorComponent();
addCopyPaste( textField);
int row = table.getEditingRow();
String value = textField.getText();
editorValue.setName(availableLanguages[row],value);
}
}
fireEditingStopped();
} else {
fireEditingCanceled();
}
}
}
class TranslationTableModel extends DefaultTableModel {
private static final long serialVersionUID = 1L;
public TranslationTableModel(MultiLanguageName name) {
super();
addColumn(getString("language"));
addColumn(getString("translation"));
Collection<String> trans = name.getAvailableLanguages();
for (int i=0;i<availableLanguages.length;i++) {
String lang = availableLanguages[i];
String[] row = new String[2];
row[0] = lang;
row[1] = trans.contains(lang) ? name.getName(lang): "";
addRow(row);
}
}
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 1) {
return false;
} else {
return true;
}
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/MultiLanguageField.java | Java | gpl3 | 7,612 |
package org.rapla.gui.internal.edit.fields;
//Interface for one EditField; it is designed for showing multiple values at the same time
public interface MultiEditField {
// shows the field a place holder for different values or a common value for all objects?
public boolean hasMultipleValues();
// sets on a field a place holder for different values
public void setFieldForMultipleValues();
} | 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/MultiEditField.java | Java | gpl3 | 397 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import org.rapla.framework.RaplaContext;
public class BooleanField extends AbstractEditField implements ActionListener, FocusListener, MultiEditField, SetGetField<Boolean>
{
JPanel panel = new JPanel();
JRadioButton field1 = new JRadioButton();
JRadioButton field2 = new JRadioButton();
ButtonGroup group = new ButtonGroup();
boolean multipleValues; // indicator, shows if multiple different values are
// shown in this field
JLabel multipleValuesLabel = new JLabel();
public BooleanField(RaplaContext context,String fieldName)
{
this(context);
setFieldName( fieldName );
}
public BooleanField(RaplaContext context)
{
super( context);
field1.setOpaque( false );
field2.setOpaque( false );
panel.setOpaque( false );
panel.setLayout( new BoxLayout(panel,BoxLayout.X_AXIS) );
panel.add( field1 );
panel.add( field2 );
panel.add(multipleValuesLabel);
group.add( field1 );
group.add( field2 );
field2.setSelected( true );
field1.addActionListener(this);
field2.addActionListener(this);
field1.setText(getString("yes"));
field2.setText(getString("no"));
field1.addFocusListener(this);
}
public Boolean getValue() {
return field1.isSelected() ? Boolean.TRUE : Boolean.FALSE;
}
public void setValue(Boolean object) {
boolean selected = object!= null ? (object).booleanValue() :false;
field1.setSelected(selected);
field2.setSelected(!selected);
}
public void actionPerformed(ActionEvent evt) {
// once an action is executed, the field shows a common value
multipleValues = false;
multipleValuesLabel.setText("");
fireContentChanged();
}
public JComponent getComponent() {
return panel;
}
public void focusGained(FocusEvent evt) {
Component focusedComponent = evt.getComponent();
Component parent = focusedComponent.getParent();
if(parent instanceof JPanel) {
((JPanel)parent).scrollRectToVisible(focusedComponent.getBounds(null));
}
}
public void focusLost(FocusEvent evt) {
}
public void setFieldForMultipleValues() {
// if multiple different values should be shown, no RadioButton is
// activated (instead a place holder)
group.clearSelection();
multipleValues = true;
multipleValuesLabel.setText(TextField.getOutputForMultipleValues());
multipleValuesLabel.setFont(multipleValuesLabel.getFont().deriveFont(Font.ITALIC));
}
public boolean hasMultipleValues() {
return multipleValues;
}
} | 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/BooleanField.java | Java | gpl3 | 4,000 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
import org.rapla.entities.NamedComparator;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class AllocatableListField extends ListField<Allocatable> {
DynamicType dynamicTypeConstraint;
public AllocatableListField(RaplaContext context, DynamicType dynamicTypeConstraint) throws RaplaException{
super( context, true);
this.dynamicTypeConstraint = dynamicTypeConstraint;
ClassificationFilter filter = dynamicTypeConstraint.newClassificationFilter();
ClassificationFilter[] filters = new ClassificationFilter[] {filter};
Allocatable[] allocatables = getQuery().getAllocatables(filters);
Set<Allocatable> list = new TreeSet<Allocatable>(new NamedComparator<Allocatable>(getLocale()));
list.addAll( Arrays.asList( allocatables));
setVector(list);
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/AllocatableListField.java | Java | gpl3 | 2,074 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Date;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.rapla.components.calendar.DateChangeEvent;
import org.rapla.components.calendar.DateChangeListener;
import org.rapla.components.calendar.RaplaCalendar;
import org.rapla.framework.RaplaContext;
public class DateField extends AbstractEditField implements DateChangeListener, FocusListener, SetGetField<Date> ,MultiEditField{
RaplaCalendar field;
JPanel panel;
boolean multipleValues = false; // Indikator, ob mehrere verschiedene Werte ueber dieses Feld angezeigt werden
JLabel multipleValuesLabel = new JLabel();
public DateField(RaplaContext context,String fieldName) {
this( context);
setFieldName(fieldName);
}
public DateField(RaplaContext context) {
super( context);
panel = new JPanel();
field = createRaplaCalendar();
panel.setLayout(new BorderLayout());
panel.add(field,BorderLayout.WEST);
panel.add( multipleValuesLabel, BorderLayout.CENTER);
panel.setOpaque( false );
field.setNullValuePossible( true);
field.addDateChangeListener(this);
field.addFocusListener(this);
}
public Date getValue() {
return field.getDate();
}
public void setValue(Date date) {
// //check if standard-value exists and is a Date-Object
// if(object instanceof Date)
// date = (Date) object;
// //if it's not a Date-Object, set the current Date as Standart
// else
// date = new Date();
field.setDate(date);
}
public RaplaCalendar getCalendar() {
return field;
}
public void dateChanged(DateChangeEvent evt) {
// Eingabe wurde getaetigt: einheitlicher Werte wurde gesetzt => Flag aendern, da kein Platzhalter mehr angezeigt wird
if(multipleValues){
multipleValues = false;
}
fireContentChanged();
}
public JComponent getComponent() {
return panel;
}
public void focusGained(FocusEvent evt) {
Component focusedComponent = evt.getComponent();
Component parent = focusedComponent.getParent();
if(parent instanceof JPanel) {
((JPanel)parent).scrollRectToVisible(focusedComponent.getBounds(null));
}
}
public void focusLost(FocusEvent evt) {
}
// Implementierung fuer Interface MultiEditField
public boolean hasMultipleValues() {
return multipleValues;
}
// Implementierung fuer Interface MultiEditField
public void setFieldForMultipleValues() {
multipleValues = true;
multipleValuesLabel.setText(TextField.getOutputForMultipleValues());
multipleValuesLabel.setFont(multipleValuesLabel.getFont().deriveFont(Font.ITALIC));
field.setDate( null);
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/DateField.java | Java | gpl3 | 3,917 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import org.rapla.gui.EditField;
public interface SetGetField<T> extends EditField
{
T getValue();
void setValue(T value);
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/SetGetField.java | Java | gpl3 | 1,118 |
/*--------------------------------------------------------------------------*
| 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.internal.edit.fields;
import java.awt.BorderLayout;
import java.awt.Dimension;
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.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicTreeUI;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeSelectionModel;
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;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaTree.TreeIterator;
public abstract class AbstractSelectField<T> extends AbstractEditField implements MultiEditField, SetGetField<T>, SetGetCollectionField<T>
{
private RaplaButton selectButton = new RaplaButton(RaplaButton.SMALL);
JPanel panel = new JPanel();
JLabel selectText = new JLabel();
private Collection<T> selectedValues = new ArrayList<T>();
T defaultValue;
private boolean useDefault = true;
private boolean useNull = true;
boolean multipleValues = false;
boolean multipleSelectionPossible = false;
public RaplaButton getButton() {
return selectButton;
}
public AbstractSelectField(RaplaContext context){
this( context, null);
}
public AbstractSelectField(RaplaContext context, T defaultValue) {
super( context);
useDefault = defaultValue != null;
selectButton.setAction(new SelectionAction());
selectButton.setHorizontalAlignment(RaplaButton.LEFT);
selectButton.setText(getString("select"));
selectButton.setIcon(getIcon("icon.tree"));
panel.setLayout( new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add( selectButton);
panel.add( Box.createHorizontalStrut(10));
panel.add( selectText);
this.defaultValue = defaultValue;
}
public boolean isUseNull()
{
return useNull;
}
public void setUseNull(boolean useNull)
{
this.useNull = useNull;
}
public boolean isMultipleSelectionPossible() {
return multipleSelectionPossible;
}
public void setMultipleSelectionPossible(boolean multipleSelectionPossible) {
this.multipleSelectionPossible = multipleSelectionPossible;
}
public class SelectionAction extends AbstractAction
{
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
try {
showDialog(selectButton);
} catch (RaplaException ex) {
showException(ex,selectButton);
}
}
}
public T getValue()
{
Collection<T> values = getValues();
if ( values.size() == 0)
{
return null;
}
else
{
T first = values.iterator().next();
return first;
}
}
public Collection<T> getValues()
{
return selectedValues;
}
public void setValue(T object)
{
List<T> list;
if ( object == null)
{
list = Collections.emptyList();
}
else
{
list = Collections.singletonList(object);
}
setValues(list);
}
final protected TreeFactory getTreeFactory()
{
return getService(TreeFactory.class);
}
public void setValues(Collection<T> values)
{
selectedValues = new ArrayList<T>();
if ( values !=null)
{
selectedValues.addAll(values);
}
String text;
if (selectedValues.size() > 0)
{
text="";
T selectedCategory = selectedValues.iterator().next();
{
text +=getNodeName(selectedCategory);
}
if ( selectedValues.size() > 1)
{
text+= ", ...";
}
}
else
{
text = getString("nothing_selected");
}
selectText.setText(text);
}
protected abstract String getNodeName(T selectedCategory);
public class MultiSelectionTreeUI extends BasicTreeUI
{
@Override
protected boolean isToggleSelectionEvent( MouseEvent event )
{
return SwingUtilities.isLeftMouseButton( event );
}
}
@SuppressWarnings("serial")
public void showDialog(JComponent parent) throws RaplaException {
final DialogUI dialog;
final JTree tree;
if ( multipleSelectionPossible)
{
tree = new JTree()
{
public void setSelectionPath(TreePath path) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StackTraceElement caller = stackTrace[2];
String className = caller.getClassName();
String methodName = caller.getMethodName();
if ( className.contains("BasicTreeUI") && (methodName.contains("keyTyped") || methodName.contains("page")))
{
setLeadSelectionPath( path);
return;
}
setSelectionPath(path);
}
public void setSelectionInterval(int index0, int index1) {
if ( index0 >= 0)
{
TreePath path = getPathForRow(index0);
setLeadSelectionPath( path);
}
}
};
TreeSelectionModel model = new DefaultTreeSelectionModel();
tree.setUI( new MultiSelectionTreeUI() );
model.setSelectionMode( TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION );
tree.setSelectionModel(model );
}
else
{
tree = new JTree();
tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION );
}
tree.setCellRenderer(getTreeFactory().createRenderer());
//tree.setVisibleRowCount(15);
tree.setRootVisible( false );
tree.setShowsRootHandles(true);
TreeModel model = createModel();
tree.setModel(model);
selectCategory(tree,selectedValues);
JPanel panel = new JPanel();
panel.setLayout( new BorderLayout());
JScrollPane scrollPane = new JScrollPane(tree);
scrollPane.setMinimumSize(new Dimension(300, 200));
scrollPane.setPreferredSize(new Dimension(400, 260));
panel.add(scrollPane, BorderLayout.PAGE_START);
if (useDefault)
{
JButton defaultButton = new JButton(getString("defaultselection"));
panel.add( defaultButton, BorderLayout.CENTER);
defaultButton.setPreferredSize(new Dimension(100, 20));
defaultButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
selectCategory( tree, Collections.singletonList(defaultValue));
}
});
}
if (useNull)
{
JButton emptyButton = new JButton(getString("nothing_selected"));
panel.add( emptyButton, BorderLayout.PAGE_END);
emptyButton.setPreferredSize(new Dimension(100, 20));
emptyButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
List<T> emptyList = Collections.emptyList();
selectCategory(tree, emptyList );
}
});
}
dialog = DialogUI.create(getContext()
,parent
,true
,panel
,new String[] { getString("apply"),getString("cancel")});
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) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)selPath.getLastPathComponent();
if (node.isLeaf()) {
dialog.getButton(0).doClick();
}
}
}
});
dialog.setTitle(getString("select"));
dialog.setInitFocus( tree);
dialog.start();
if (dialog.getSelectedIndex() == 0) {
TreePath[] paths = tree.getSelectionPaths();
Collection<T> newValues = new ArrayList<T>();
if ( paths != null)
{
for (TreePath path:paths)
{
Object valueObject = ((DefaultMutableTreeNode)path.getLastPathComponent()).getUserObject();
T value = getValue(valueObject);
if ( value != null)
{
newValues.add(value);
}
}
}
if ( !newValues.equals(selectedValues))
{
setValues( newValues );
fireContentChanged();
}
}
}
protected T getValue(Object valueObject) {
@SuppressWarnings("unchecked")
T casted = (T) valueObject;
return casted;
}
public abstract TreeModel createModel() throws RaplaException;
private void selectCategory(JTree tree, Collection<T> categories) {
select(tree, categories);
//RecursiveNode.selectUserObjects(tree,path.toArray());
}
public void select(JTree jTree,Collection<?> selectedObjects) {
Collection<TreeNode> selectedNodes = new ArrayList<TreeNode>();
Iterator<TreeNode> it = new TreeIterator((TreeNode)jTree.getModel().getRoot());
while (it.hasNext()) {
TreeNode node = it.next();
if (node != null && selectedObjects.contains( getObject(node) ))
selectedNodes.add(node);
}
it = selectedNodes.iterator();
TreePath[] path = new TreePath[selectedNodes.size()];
int i=0;
while (it.hasNext()) {
path[i] = getPath(it.next());
jTree.expandPath(path[i]);
i++;
}
jTree.getSelectionModel().clearSelection();
jTree.setSelectionPaths(path);
}
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;
}
}
private TreePath getPath(TreeNode node) {
if (node.getParent() == null)
return new TreePath(node);
else
return getPath(node.getParent()).pathByAddingChild(node);
}
public JComponent getComponent() {
return panel;
}
// implementation for interface MultiEditField
public boolean hasMultipleValues() {
return multipleValues;
}
// implementation for interface MultiEditField
public void setFieldForMultipleValues() {
multipleValues = true;
// sets place holder for different values
selectText.setText(TextField.getOutputForMultipleValues());
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/AbstractSelectField.java | Java | gpl3 | 13,144 |
package org.rapla.gui.internal.edit.fields;
public class EditFieldLayout
{
private boolean block;
private boolean variableSized;
public boolean isBlock() {
return block;
}
public void setBlock(boolean block) {
this.block = block;
}
public boolean isVariableSized() {
return variableSized;
}
public void setVariableSized(boolean variableSized) {
this.variableSized = variableSized;
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/fields/EditFieldLayout.java | Java | gpl3 | 469 |
/*--------------------------------------------------------------------------*
| 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.internal.edit;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Reservation;
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.EditComponent;
import org.rapla.gui.EditController;
import org.rapla.gui.RaplaGUIComponent;
/** This class handles the edit-ui for all entities (except reservations). */
public class EditControllerImpl extends RaplaGUIComponent implements
EditController {
Collection<EditDialog<?>> editWindowList = new ArrayList<EditDialog<?>>();
public EditControllerImpl(RaplaContext sm){
super(sm);
}
void addEditDialog(EditDialog<?> editWindow) {
editWindowList.add(editWindow);
}
void removeEditDialog(EditDialog<?> editWindow) {
editWindowList.remove(editWindow);
}
public <T extends Entity> EditComponent<T> createUI(T obj) throws RaplaException
{
return createUI( obj,false);
}
/*
* (non-Javadoc)
*
* @see org.rapla.gui.edit.IEditController#createUI(org.rapla.entities.
* RaplaPersistant)
*/
@SuppressWarnings("unchecked")
public <T extends Entity> EditComponent<T> createUI(T obj, boolean createNew) throws RaplaException {
RaplaType type = obj.getRaplaType();
EditComponent<?> ui = null;
if (Allocatable.TYPE.equals(type)) {
boolean internal = isInternalType( (Allocatable)obj);
ui = new AllocatableEditUI(getContext(), internal);
} else if (DynamicType.TYPE.equals(type)) {
ui = new DynamicTypeEditUI(getContext());
} else if (User.TYPE.equals(type)) {
ui = new UserEditUI(getContext());
} else if (Category.TYPE.equals(type)) {
ui = new CategoryEditUI(getContext(), createNew);
} else if (Preferences.TYPE.equals(type)) {
ui = new PreferencesEditUI(getContext());
} else if (Reservation.TYPE.equals(type)) {
ui = new ReservationEditUI(getContext());
}
if (ui == null) {
throw new RuntimeException("Can't edit objects of type "
+ type.toString());
}
return (EditComponent<T>)ui;
}
private boolean isInternalType(Allocatable alloc) {
DynamicType type = alloc.getClassification().getType();
String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
return annotation != null && annotation.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE);
}
// enhancement of the method to deal with arrays
protected String guessTitle(Object obj) {
RaplaType raplaType = getRaplaType(obj);
String title = "";
if(raplaType != null) {
title = getString(raplaType.getLocalName());
}
return title;
}
// method for determining the consistent RaplaType from different objects
protected RaplaType getRaplaType(Object obj){
Set<RaplaType> types = new HashSet<RaplaType>();
// if the committed object is no array -> wrap object into array
if (!obj.getClass().isArray()) {
obj = new Object[] { obj };
}
// iterate all committed objects and store RaplayType of the objects in a Set
// identic typs aren't stored double because of Set
for (Object o : (Object[]) obj) {
if (o instanceof Entity) {
RaplaType type = ((Entity<?>) o).getRaplaType();
types.add(type);
}
}
// check if there is a explicit type, then return this type; otherwise return null
if (types.size() == 1)
return types.iterator().next();
else
return null;
}
public <T extends Entity> void edit(T obj, Component owner) throws RaplaException {
edit(obj, guessTitle(obj), owner);
}
public <T extends Entity> void editNew(T obj, Component owner)
throws RaplaException {
edit(obj, guessTitle(obj), owner, true);
}
public <T extends Entity> void edit(T[] obj, Component owner) throws RaplaException {
edit(obj, guessTitle(obj), owner);
}
/*
* (non-Javadoc)
*
* @see org.rapla.gui.edit.IEditController#edit(org.rapla.entities.Entity,
* java.lang.String, java.awt.Component)
*/
public <T extends Entity> void edit(T obj, String title, Component owner)
throws RaplaException {
edit(obj, title, owner, false);
}
protected <T extends Entity> void edit(T obj, String title, Component owner,boolean createNew )
throws RaplaException {
// Hack for 1.6 compiler compatibility
@SuppressWarnings("cast")
Entity<?> testObj = (Entity<?>) obj;
if ( testObj instanceof Reservation)
{
getReservationController().edit( (Reservation) testObj );
return;
}
// Lookup if the reservation is already beeing edited
EditDialog<?> c = null;
Iterator<EditDialog<?>> it = editWindowList.iterator();
while (it.hasNext()) {
c = it.next();
List<?> editObj = c.ui.getObjects();
if (editObj != null && editObj.size() == 1 )
{
Object first = editObj.get(0);
if (first instanceof Entity && ((Entity<?>) first).isIdentical(obj))
{
break;
}
}
c = null;
}
if (c != null) {
c.dlg.requestFocus();
c.dlg.toFront();
} else {
editAndOpenDialog( Collections.singletonList( obj),title, owner, createNew);
}
}
// method analog to edit(Entity obj, String title, Component owner)
// however for using with arrays
public <T extends Entity> void edit(T[] obj, String title, Component owner)
throws RaplaException {
// checks if all entities are from the same type; otherwise return
if(getRaplaType(obj) == null) return;
// if selektion contains only one object start usual Edit dialog
if(obj.length == 1){
edit(obj[0], title, owner);
}
else
{
editAndOpenDialog(Arrays.asList(obj), title, owner, false);
}
}
protected <T extends Entity> void editAndOpenDialog(List<T> list, String title, Component owner, boolean createNew) throws RaplaException {
// gets for all objects in array a modifiable version and add it to a set to avoid duplication
Collection<T> toEdit = getModification().edit( list);
if (toEdit.size() > 0) {
EditComponent<T> ui = createUI(toEdit.iterator().next(), createNew);
EditDialog<T> gui = new EditDialog<T>(getContext(), ui, false);
gui.start(toEdit, title, owner);
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/EditControllerImpl.java | Java | gpl3 | 7,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.gui.internal.edit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.rapla.components.util.Assert;
import org.rapla.entities.Category;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeAnnotations;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ConstraintIds;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.EditField;
import org.rapla.gui.internal.edit.fields.AllocatableSelectField;
import org.rapla.gui.internal.edit.fields.BooleanField;
import org.rapla.gui.internal.edit.fields.CategoryListField;
import org.rapla.gui.internal.edit.fields.CategorySelectField;
import org.rapla.gui.internal.edit.fields.DateField;
import org.rapla.gui.internal.edit.fields.LongField;
import org.rapla.gui.internal.edit.fields.MultiEditField;
import org.rapla.gui.internal.edit.fields.SetGetCollectionField;
import org.rapla.gui.internal.edit.fields.SetGetField;
import org.rapla.gui.internal.edit.fields.TextField;
public class ClassificationEditUI extends AbstractEditUI<Classification> {
public ClassificationEditUI(RaplaContext sm) {
super(sm);
}
// enhanced to an array, for administration of multiple classifications
private String getAttName(String key) {
// collection of all attribute-names for the deposited classifications
Set<String> attNames = new HashSet<String>();
for (Classification c : objectList) {
attNames.add(getName(c.getAttribute(key)));
}
// checks if there is a common attribute-name
if (attNames.size() == 1) {
// delivers this name
return attNames.iterator().next();
} else {
return "-";
}
}
protected Attribute getAttribute(int i) {
// collection of all attributes for the deposited classifications for a
// certain field
Set<Attribute> attributes = new HashSet<Attribute>();
for (Classification c : objectList) {
String key = getKey( fields.get(i));
Attribute attribute = c.getAttribute(key);
attributes.add(attribute);
}
// check if there is a common attribute
if (attributes.size() == 1) {
// delivers this attribute
return attributes.iterator().next();
} else {
return null;
}
}
protected void setAttValue(String key, Object value) {
// sets the attribute value for all deposited classifications
for (Classification c : objectList) {
Attribute attribute = c.getAttribute(key);
if ( value instanceof Collection<?>)
{
Collection<?> collection = (Collection<?>)value;
Boolean multiSelect = (Boolean)attribute.getConstraint(ConstraintIds.KEY_MULTI_SELECT);
if ( multiSelect != null && multiSelect==true)
{
c.setValues(attribute, collection);
}
else if ( collection.size() > 0)
{
c.setValue(attribute, collection.iterator().next());
}
else
{
c.setValue(attribute, null);
}
}
else
{
c.setValue(attribute, value);
}
}
}
public Set<Object> getUniqueAttValues(String key) {
// collection of all attribute values for a certain attribute
Set<Object> values = new LinkedHashSet<Object>();
for (Classification c : objectList) {
Attribute attribute = c.getAttribute(key);
Object value;
Boolean multiSelect = (Boolean) attribute.getConstraint(ConstraintIds.KEY_MULTI_SELECT);
if ( multiSelect != null && multiSelect == true)
{
value = c.getValues(attribute);
}
else
{
value = c.getValue(attribute);
}
values.add(value);
}
return values;
}
private SetGetField<?> createField(Attribute attribute) {
AttributeType type = attribute.getType();
String label = getAttName(attribute.getKey());
SetGetField<?> field = null;
RaplaContext context = getContext();
if (type.equals(AttributeType.STRING)) {
Integer rows = new Integer(attribute.getAnnotation( AttributeAnnotations.KEY_EXPECTED_ROWS, "1"));
Integer columns = new Integer(attribute.getAnnotation( AttributeAnnotations.KEY_EXPECTED_COLUMNS,String.valueOf(TextField.DEFAULT_LENGTH)));
field = new TextField(context, label, rows.intValue(),columns.intValue());
} else if (type.equals(AttributeType.INT)) {
field = new LongField(context, label);
} else if (type.equals(AttributeType.DATE)) {
field = new DateField(context, label);
} else if (type.equals(AttributeType.BOOLEAN)) {
field = new BooleanField(context, label);
} else if (type.equals(AttributeType.ALLOCATABLE)) {
DynamicType dynamicTypeConstraint = (DynamicType)attribute.getConstraint( ConstraintIds.KEY_DYNAMIC_TYPE);
Boolean multipleSelectionPossible = (Boolean) attribute.getConstraint(ConstraintIds.KEY_MULTI_SELECT);
// if (dynamicTypeConstraint == null || multipleSelectionPossible) {
AllocatableSelectField allocField = new AllocatableSelectField(context, dynamicTypeConstraint);
allocField.setFieldName(label);
allocField.setMultipleSelectionPossible( multipleSelectionPossible != null ? multipleSelectionPossible : false);
field = allocField;
// }else {
// AllocatableListField allocField = new AllocatableListField(context, key, dynamicTypeConstraint);
// field = allocField;
// }
} else if (type.equals(AttributeType.CATEGORY)) {
Category defaultCategory = (Category) attribute.defaultValue();
Category rootCategory = (Category) attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY);
boolean multipleSelectionPossible = attribute.getAnnotation(ConstraintIds.KEY_MULTI_SELECT, "false").equals("true");
if (rootCategory.getDepth() > 2 || multipleSelectionPossible) {
CategorySelectField catField = new CategorySelectField(context, rootCategory, defaultCategory);
catField.setMultipleSelectionPossible( multipleSelectionPossible);
catField.setFieldName( label );
field = catField;
} else {
CategoryListField catField = new CategoryListField(context, rootCategory);
catField.setFieldName( label );
field = catField;
}
}
Assert.notNull(field, "Unknown AttributeType");
return field;
}
Map<EditField,String> fieldKeyMap = new HashMap<EditField,String>();
public void setObjects(List<Classification> classificationList) throws RaplaException {
this.objectList = classificationList;
// determining of the DynmicTypes from the classifications
Set<DynamicType> types = new HashSet<DynamicType>();
for (Classification c : objectList) {
types.add(c.getType());
}
// checks if there is a common DynmicType
if (types.size() == 1) {
fieldKeyMap.clear();
// read out attributes for this DynmicType
Attribute[] attributes = types.iterator().next().getAttributes();
// create fields for attributes
List<SetGetField<?>> fields= new ArrayList<SetGetField<?>>();
for (Attribute attribute:attributes) {
SetGetField<?> field = createField(attribute);
//field.setUser(classificationList);
fields.add( field);
fieldKeyMap.put( field, attribute.getKey());
}
// show fields
setFields(fields);
}
mapFromObjects();
}
public void mapTo(SetGetField<?> field) {
// checks if the EditField shows a common value
if (field instanceof MultiEditField && ((MultiEditField) field).hasMultipleValues())
return;
// read out attribute value if the field shows a common value
String attKey = getKey(field);
if ( field instanceof SetGetCollectionField)
{
Collection<?> values = ((SetGetCollectionField<?>) field).getValues();
setAttValue(attKey, values);
}
else
{
setAttValue(attKey, field.getValue());
}
}
protected String getKey(EditField field)
{
String key = fieldKeyMap.get( field);
return key;
}
public <T> void mapFrom(SetGetField<T> field ) {
// read out attribute values
Set<Object> values = getUniqueAttValues(getKey(field));
// checks if there is a common value, otherwise a place holder has
// to be shown for this field
if ( values.size() > 1 && field instanceof MultiEditField)
{
// shows place holder
((MultiEditField) field).setFieldForMultipleValues();
}
else if ( values.size() == 1)
{
// set common value
Object first = values.iterator().next();
if ( first instanceof Collection)
{
@SuppressWarnings("unchecked")
Collection<T> list = (Collection<T>)first;
if ( field instanceof SetGetCollectionField)
{
@SuppressWarnings("unchecked")
SetGetCollectionField<T> setGetCollectionField = (SetGetCollectionField<T>)field;
setGetCollectionField.setValues(list);
}
else if ( list.size() > 0)
{
field.setValue( list.iterator().next());
}
else
{
field.setValue( null);
}
}
else
{
@SuppressWarnings("unchecked")
T casted = (T)first;
field.setValue( casted);
}
}
else
{
field.setValue(null);
}
}
public void mapToObjects() throws RaplaException
{
for (EditField field: fields)
{
SetGetField<?> f = (SetGetField<?>) field;
mapTo( f);
}
}
protected void mapFromObjects() throws RaplaException {
for (EditField field: fields)
{
SetGetField<?> f = (SetGetField<?>) field;
mapFrom( f);
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/ClassificationEditUI.java | Java | gpl3 | 11,198 |
/*--------------------------------------------------------------------------*
| 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.internal.edit;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.rapla.components.calendar.RaplaArrowButton;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.util.Tools;
import org.rapla.entities.Category;
import org.rapla.entities.CategoryAnnotations;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.EditComponent;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.internal.edit.fields.MultiLanguageField;
import org.rapla.gui.internal.edit.fields.TextField;
import org.rapla.gui.internal.view.TreeFactoryImpl.NamedNode;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaTree;
/**
* @author Christopher Kohlhaas
*/
public class CategoryEditUI extends RaplaGUIComponent
implements
EditComponent<Category>
{
JPanel panel = new JPanel();
JPanel toolbar = new JPanel();
RaplaButton newButton = new RaplaButton();
RaplaButton newSubButton = new RaplaButton();
RaplaButton removeButton = new RaplaButton();
RaplaArrowButton moveUpButton = new RaplaArrowButton('^', 25);
RaplaArrowButton moveDownButton = new RaplaArrowButton('v', 25);
Category rootCategory;
CategoryDetail detailPanel;
RaplaTreeEdit treeEdit;
TreeModel model;
boolean editKeys = true;
Listener listener = new Listener();
TreeCellRenderer iconRenderer;
boolean createNew;
public CategoryEditUI(RaplaContext context, boolean createNew) {
super( context);
this.createNew = createNew;
detailPanel = new CategoryDetail(context);
panel.setPreferredSize( new Dimension( 690,350 ) );
treeEdit = new RaplaTreeEdit( getI18n(),detailPanel.getComponent(), listener );
treeEdit.setListDimension( new Dimension( 250,100 ) );
toolbar.setLayout( new BoxLayout(toolbar, BoxLayout.X_AXIS));
toolbar.add(newButton);
toolbar.add(newSubButton);
toolbar.add( Box.createHorizontalStrut( 5 ));
toolbar.add(removeButton);
toolbar.add( Box.createHorizontalStrut( 5 ));
toolbar.add(moveUpButton);
toolbar.add(moveDownButton);
panel.setLayout( new BorderLayout() );
panel.add( toolbar, BorderLayout.NORTH );
panel.add( treeEdit.getComponent(), BorderLayout.CENTER );
newButton.addActionListener(listener);
newSubButton.addActionListener(listener);
removeButton.addActionListener(listener);
moveUpButton.addActionListener( listener );
moveDownButton.addActionListener( listener );
iconRenderer = getTreeFactory().createRenderer();
treeEdit.getTree().setCellRenderer( new TreeCellRenderer() {
public Component getTreeCellRendererComponent(JTree tree
,Object value
,boolean sel
,boolean expanded
,boolean leaf
,int row
,boolean hasFocus
) {
if ( value instanceof NamedNode) {
Category c = (Category) ((NamedNode)value).getUserObject();
value = c.getName(getRaplaLocale().getLocale());
if (editKeys) {
value = "{" + c.getKey() + "} " + value;
}
}
return iconRenderer.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus );
}
});
newButton.setText( getString("new_category") );
newButton.setIcon( getIcon("icon.new"));
newSubButton.setText( getString("new_sub-category") );
newSubButton.setIcon( getIcon("icon.new") );
removeButton.setText( getString("delete") );
removeButton.setIcon( getIcon("icon.delete") );
detailPanel.addChangeListener( listener );
detailPanel.setEditKeys( editKeys );
}
final private TreeFactory getTreeFactory() {
return getService(TreeFactory.class);
}
class Listener implements ActionListener,ChangeListener {
public void actionPerformed(ActionEvent evt) {
try {
if ( evt.getSource() == newButton ) {
createCategory( false );
} else if ( evt.getSource() == newSubButton ) {
createCategory( true );
} else if ( evt.getSource() == removeButton ) {
removeCategory();
} else if ( evt.getSource() == moveUpButton ) {
moveCategory( -1);
} else if ( evt.getSource() == moveDownButton ) {
moveCategory( 1);
} else if (evt.getActionCommand().equals("edit")) {
Category category = (Category) treeEdit.getSelectedValue();
detailPanel.mapFrom( category );
}
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
public void stateChanged(ChangeEvent e) {
try {
confirmEdits();
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
}
public JComponent getComponent() {
return panel;
}
public int getSelectedIndex() {
return treeEdit.getSelectedIndex();
}
public void setObjects(List<Category> o) throws RaplaException {
this.rootCategory = o.get(0);
updateModel();
}
public void processCreateNew() throws RaplaException {
if ( createNew )
{
createCategory( false);
}
}
private void createCategory(boolean bCreateSubCategory) throws RaplaException {
confirmEdits();
Category newCategory;
NamedNode parentNode;
TreePath path = treeEdit.getTree().getSelectionPath();
if (path == null) {
parentNode = (NamedNode)model.getRoot();
} else {
NamedNode selectedNode = (NamedNode) path.getLastPathComponent();
if (selectedNode.getParent() == null || bCreateSubCategory)
parentNode = selectedNode;
else
parentNode = (NamedNode)selectedNode.getParent();
}
newCategory = createNewNodeAt( parentNode );
updateModel();
NamedNode newNode = (NamedNode)((NamedNode)model.getRoot()).findNodeFor( newCategory );
TreePath selectionPath = new TreePath( newNode.getPath() );
treeEdit.getTree().setSelectionPath( selectionPath );
detailPanel.name.selectAll();
detailPanel.name.requestFocus();
}
private String createNewKey(Category[] subCategories) {
int max = 1;
for (int i=0;i<subCategories.length;i++) {
String key = subCategories[i].getKey();
if (key.length()>1
&& key.charAt(0) =='c'
&& Character.isDigit(key.charAt(1))
)
{
try {
int value = Integer.valueOf(key.substring(1)).intValue();
if (value >= max)
max = value + 1;
} catch (NumberFormatException ex) {
}
}
}
return "c" + (max);
}
// creates a new Category
private Category createNewNodeAt(NamedNode parentNode) throws RaplaException {
Category newCategory = getModification().newCategory();
Category parent = (Category) parentNode.getUserObject();
newCategory.setKey(createNewKey(parent.getCategories()));
newCategory.getName().setName(getI18n().getLang(), getString("new_category") );
parent.addCategory(newCategory);
getLogger().debug(" new category " + newCategory + " added to " + parent);
return newCategory;
}
private void removeCategory()
{
TreePath[] paths = treeEdit.getTree().getSelectionPaths();
if ( paths == null )
return;
NamedNode[] categoryNodes = new NamedNode[paths.length];
for (int i=0;i<paths.length;i++) {
categoryNodes[i] = (NamedNode) paths[i].getLastPathComponent();
}
removeNodes(categoryNodes);
updateModel();
}
private void moveCategory( int direction )
{
TreePath[] paths = treeEdit.getTree().getSelectionPaths();
if ( paths == null || paths.length == 0)
return;
NamedNode categoryNode = (NamedNode)paths[0].getLastPathComponent();
if ( categoryNode == null)
{
return;
}
Category selectedCategory = (Category)categoryNode.getUserObject();
Category parent = selectedCategory.getParent();
if ( parent == null || selectedCategory.equals( rootCategory))
return;
Category[] childs = parent.getCategories();
for ( int i=0;i<childs.length;i++)
{
parent.removeCategory( childs[i]);
}
if ( direction == -1)
{
Category last = null;
for ( int i=0;i<childs.length;i++)
{
Category current = childs[i];
if ( current.equals( selectedCategory)) {
parent.addCategory( current);
}
if ( last != null && !last.equals( selectedCategory))
{
parent.addCategory(last);
}
last = current;
}
if (last != null && !last.equals( selectedCategory)) {
parent.addCategory(last);
}
}
else
{
boolean insertNow = false;
for ( int i=0;i<childs.length;i++)
{
Category current = childs[i];
if ( !current.equals( selectedCategory)) {
parent.addCategory( current);
} else {
insertNow = true;
continue;
}
if ( insertNow)
{
insertNow = false;
parent.addCategory( selectedCategory);
}
}
if ( insertNow) {
parent.addCategory( selectedCategory);
}
}
updateModel();
}
public void removeNodes(NamedNode[] nodes) {
ArrayList<NamedNode> childList = new ArrayList<NamedNode>();
TreeNode[] path = null;
NamedNode parentNode = null;
for (int i=0;i<nodes.length;i++) {
if (parentNode == null) {
path= nodes[i].getPath();
parentNode = (NamedNode)nodes[i].getParent();
}
// dont't delete the root-node
if (parentNode == null)
continue;
int index = parentNode.getIndexOfUserObject(nodes[i].getUserObject());
if (index >= 0) {
childList.add(nodes[i]);
}
}
if (path != null) {
int size = childList.size();
NamedNode[] childs = new NamedNode[size];
for (int i=0;i<size;i++) {
childs[i] = childList.get(i);
}
for (int i=0;i<size;i++) {
Category subCategory = (Category)childs[i].getUserObject();
subCategory.getParent().removeCategory(subCategory);
getLogger().debug("category removed " + subCategory);
}
}
}
public void mapToObjects() throws RaplaException {
validate( this.rootCategory );
confirmEdits();
}
public List<Category> getObjects() {
return Collections.singletonList(this.rootCategory);
}
private void updateModel() {
model = getTreeFactory().createModel( rootCategory);
RaplaTree.exchangeTreeModel( model , treeEdit.getTree() );
}
public void confirmEdits() throws RaplaException {
if ( getSelectedIndex() < 0 )
return;
Category category = (Category) treeEdit.getSelectedValue();
detailPanel.mapTo ( category );
TreePath path = treeEdit.getTree().getSelectionPath();
if (path != null)
((DefaultTreeModel) model).nodeChanged((TreeNode)path.getLastPathComponent() );
}
private void validate(Category category) throws RaplaException {
checkKey( category.getKey() );
Category[] categories = category.getCategories();
for ( int i=0; i< categories.length;i++) {
validate( categories[i] );
}
}
private void checkKey(String key) throws RaplaException {
if (key.length() ==0)
throw new RaplaException(getString("error.no_key"));
if (!Tools.isKey(key) || key.length()>50)
{
Object[] param = new Object[3];
param[0] = key;
param[1] = "'-', '_'";
param[2] = "'_'";
throw new RaplaException(getI18n().format("error.invalid_key", param));
}
}
public void setEditKeys(boolean editKeys) {
detailPanel.setEditKeys(editKeys);
this.editKeys = editKeys;
}
}
class CategoryDetail extends RaplaGUIComponent
implements
ChangeListener
{
JPanel mainPanel = new JPanel();
Category currentCategory;
JPanel panel = new JPanel();
JLabel nameLabel = new JLabel();
JLabel keyLabel = new JLabel();
JLabel colorLabel = new JLabel();
MultiLanguageField name;
TextField key;
TextField colorTextField;
JPanel colorPanel = new JPanel();
RaplaArrowButton addButton = new RaplaArrowButton('>', 25);
RaplaArrowButton removeButton = new RaplaArrowButton('<', 25);
public CategoryDetail(RaplaContext context)
{
super( context);
name = new MultiLanguageField(context);
key = new TextField(context);
colorTextField = new TextField(context);
double fill = TableLayout.FILL;
double pre = TableLayout.PREFERRED;
panel.setLayout( new TableLayout( new double[][]
{{5, pre, 5, fill }, // Columns
{5, pre ,5, pre, 5, pre, 5}} // Rows
));
panel.add("1,1,l,f", nameLabel);
panel.add("3,1,f,f", name.getComponent() );
panel.add("1,3,l,f", keyLabel);
panel.add("3,3,f,f", key.getComponent() );
panel.add("1,5,l,f", colorLabel);
panel.add("3,5,f,f", colorPanel);
colorPanel.setLayout( new BorderLayout());
colorPanel.add( colorTextField.getComponent(), BorderLayout.CENTER );
nameLabel.setText(getString("name") + ":");
keyLabel.setText(getString("key") + ":");
colorLabel.setText( getString("color") + ":");
name.addChangeListener ( this );
key.addChangeListener ( this );
colorTextField.addChangeListener( this );
// Add everything to the MainPanel
mainPanel.setLayout(new BorderLayout());
mainPanel.add(panel, BorderLayout.NORTH);
}
class CategoryListCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
private boolean filterStyle;
public CategoryListCellRenderer(boolean filterStyle) {
this.filterStyle = filterStyle;
}
public CategoryListCellRenderer() {
this(false);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
if (filterStyle == true)
setFont((getFont().deriveFont(Font.PLAIN)));
if (value != null && value instanceof Category) {
setText(((Category) value).getName(getLocale()));
}
return this;
}
}
public void requestFocus() {
name.requestFocus();
}
public void setEditKeys(boolean editKeys) {
keyLabel.setVisible( editKeys );
key.getComponent().setVisible( editKeys );
colorLabel.setVisible( editKeys );
colorTextField.getComponent().setVisible( editKeys );
}
public JComponent getComponent() {
return mainPanel;
}
public void mapFrom(Category category) {
name.setValue( category.getName());
key.setValue( category.getKey());
String color = category.getAnnotation( CategoryAnnotations.KEY_NAME_COLOR);
if ( color != null)
{
colorTextField.setValue( color );
}
else
{
colorTextField.setValue( null );
}
currentCategory = category;
}
public void mapTo(Category category) throws RaplaException {
category.getName().setTo( name.getValue());
category.setKey( key.getValue());
String colorValue = colorTextField.getValue().toString().trim();
if ( colorValue.length() > 0) {
category.setAnnotation(CategoryAnnotations.KEY_NAME_COLOR, colorValue );
} else {
category.setAnnotation(CategoryAnnotations.KEY_NAME_COLOR, null );
}
}
public void stateChanged(ChangeEvent e) {
fireContentChanged();
}
ArrayList<ChangeListener> listenerList = new ArrayList<ChangeListener>();
public void addChangeListener(ChangeListener listener) {
listenerList.add(listener);
}
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(listener);
}
public ChangeListener[] getChangeListeners() {
return listenerList.toArray(new ChangeListener[]{});
}
protected void fireContentChanged() {
if (listenerList.size() == 0)
return;
ChangeEvent evt = new ChangeEvent(this);
ChangeListener[] listeners = getChangeListeners();
for (int i = 0;i<listeners.length; i++) {
listeners[i].stateChanged(evt);
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/CategoryEditUI.java | Java | gpl3 | 19,729 |
/*--------------------------------------------------------------------------*
| 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.internal.edit;
import java.awt.BorderLayout;
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.Iterator;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.rapla.entities.Category;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
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.EditField;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.internal.edit.fields.AbstractEditField;
import org.rapla.gui.internal.edit.fields.BooleanField;
import org.rapla.gui.internal.edit.fields.GroupListField;
import org.rapla.gui.internal.edit.fields.TextField;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaTree;
/****************************************************************
* This is the controller-class for the User-Edit-Panel *
****************************************************************/
/*User
1. username, string
2. name,string
3. email,string,
4. isadmin,boolean
*/
class UserEditUI extends AbstractEditUI<User> {
TextField usernameField;
PersonSelectField personSelect;
TextField nameField;
TextField emailField;
AdminBooleanField adminField;
GroupListField groupField;
/**
* @param context
* @throws RaplaException
*/
public UserEditUI(RaplaContext context) throws RaplaException {
super(context);
List<EditField> fields = new ArrayList<EditField>();
usernameField = new TextField(context,getString("username"));
fields.add(usernameField);
personSelect = new PersonSelectField(context);
fields.add(personSelect);
nameField = new TextField(context,getString("name"));
fields.add(nameField);
emailField = new TextField(context,getString("email"));
fields.add(emailField);
adminField = new AdminBooleanField(context,getString("admin"),getUser());
fields.add(adminField);
groupField = new GroupListField(context);
fields.add(groupField);
setFields(fields);
}
class AdminBooleanField extends BooleanField implements ChangeListener {
User user;
public AdminBooleanField(RaplaContext sm, String fieldName, User user) {
super(sm, fieldName);
this.user = user;
}
public void stateChanged(ChangeEvent e) {
}
public void actionPerformed(ActionEvent evt) {
if(evt.getActionCommand().equals(getString("no"))) {
try {
if(!isOneAdmin())
{
showWarning(getString("error.no_admin"), getComponent());
setValue(true);
}
}
catch (RaplaException ex)
{
showException(ex, getComponent());
}
}
return;
}
private Boolean isOneAdmin() throws RaplaException {
User[] userList = getQuery().getUsers();
for (final User user: userList)
{
if(!user.equals(this.user) && user.isAdmin())
{
return true;
}
}
return false;
}
}
class PersonSelectField extends AbstractEditField implements ChangeListener, ActionListener {
User user;
JPanel panel = new JPanel();
JToolBar toolbar = new JToolBar();
RaplaButton newButton = new RaplaButton(RaplaButton.SMALL);
RaplaButton removeButton = new RaplaButton(RaplaButton.SMALL);
/**
* @param sm
* @throws RaplaException
*/
public PersonSelectField(RaplaContext sm) throws RaplaException {
super(sm);
setFieldName( getString("person"));
final Category rootCategory = getQuery().getUserGroupsCategory();
if ( rootCategory == null )
return;
toolbar.add( newButton );
toolbar.add( removeButton );
toolbar.setFloatable( false );
panel.setLayout( new BorderLayout() );
panel.add( toolbar, BorderLayout.NORTH );
newButton.addActionListener( this );
removeButton.addActionListener( this );
removeButton.setText( getString("remove") );
removeButton.setIcon( getIcon( "icon.remove" ) );
newButton.setText( getString("bind_with_person") );
newButton.setIcon( getIcon( "icon.new" ) );
}
private void updateButton() {
final boolean personSet = user != null && user.getPerson() != null;
removeButton.setEnabled( personSet) ;
newButton.setEnabled( !personSet) ;
nameField.getComponent().setEnabled( !personSet);
emailField.getComponent().setEnabled( !personSet);
}
public JComponent getComponent() {
return panel;
}
public String getName()
{
return getString("bind_with_person");
}
public void setUser(User o){
user = o;
updateButton();
}
public void actionPerformed(ActionEvent evt) {
if ( evt.getSource() == newButton)
{
try {
showAddDialog();
} catch (RaplaException ex) {
showException(ex,newButton);
}
}
if ( evt.getSource() == removeButton)
{
try {
user.setPerson( null );
user.setEmail( null );
user.setName(null);
nameField.setValue( user.getName());
emailField.setValue( user.getEmail());
updateButton();
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
}
public void stateChanged(ChangeEvent evt) {
}
private void showAddDialog() throws RaplaException {
final DialogUI dialog;
RaplaTree treeSelection = new RaplaTree();
treeSelection.setMultiSelect(true);
final TreeFactory treeFactory = getTreeFactory();
treeSelection.getTree().setCellRenderer(treeFactory.createRenderer());
final DynamicType[] personTypes = getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON);
List<ClassificationFilter> filters = new ArrayList<ClassificationFilter>();
for (DynamicType personType: personTypes)
{
if ( personType.getAttribute("email") != null)
{
final ClassificationFilter filter = personType.newClassificationFilter();
filters.add( filter);
}
}
final Allocatable[] allocatables = getQuery().getAllocatables(filters.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY));
List<Allocatable> allocatablesWithEmail = new ArrayList<Allocatable>();
for ( Allocatable a: allocatables)
{
final Classification classification = a.getClassification();
final Attribute attribute = classification.getAttribute("email");
if ( attribute != null)
{
final String email = (String)classification.getValue(attribute);
if (email != null && email.length() > 0)
{
allocatablesWithEmail.add( a );
}
}
}
final Allocatable[] allocatableArray = allocatablesWithEmail.toArray(Allocatable.ALLOCATABLE_ARRAY);
treeSelection.exchangeTreeModel(treeFactory.createClassifiableModel(allocatableArray,true));
treeSelection.setMinimumSize(new java.awt.Dimension(300, 200));
treeSelection.setPreferredSize(new java.awt.Dimension(400, 260));
dialog = DialogUI.create(
getContext()
,getComponent()
,true
,treeSelection
,new String[] { getString("apply"),getString("cancel")});
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();
}
else if (selPath != null && e.getClickCount() == 1) {
final Object lastPathComponent = selPath.getLastPathComponent();
if (((TreeNode) lastPathComponent).isLeaf() )
dialog.getButton(0).setEnabled(true);
else
dialog.getButton(0).setEnabled(false);
}
}
});
dialog.setTitle(getName());
dialog.start();
if (dialog.getSelectedIndex() == 0) {
Iterator<?> it = treeSelection.getSelectedElements().iterator();
while (it.hasNext()) {
user.setPerson((Allocatable) it.next());
nameField.setValue( user.getName());
emailField.setValue( user.getEmail());
updateButton();
}
}
}
}
final private TreeFactory getTreeFactory() {
return getService(TreeFactory.class);
}
@Override
public void mapToObjects() throws RaplaException {
if (objectList == null)
return;
if (objectList.size() == 1 )
{
User user = objectList.iterator().next();
user.setName(nameField.getValue());
user.setEmail( emailField.getValue());
user.setUsername( usernameField.getValue());
user.setAdmin( adminField.getValue());
// personselect stays in sync
}
groupField.mapTo( objectList);
}
// overwriting of the method by AbstractEditUI
// goal: deactivation of the username-field in case of processing multiple
// objects, to avoid that usernames (identifier) are processed at the same
// time
// => multiple users would have the same username
@Override
protected void mapFromObjects() throws RaplaException {
boolean multiedit = objectList.size() > 1;
if (objectList.size() == 1 )
{
User user = objectList.iterator().next();
nameField.setValue(user.getName());
emailField.setValue(user.getEmail());
usernameField.setValue(user.getUsername( ));
adminField.setValue( user.isAdmin( ));
personSelect.setUser( user);
}
groupField.mapFrom( objectList);
for (EditField field:fields) {
// deactivation of the all fields except group for multiple objects
if (multiedit && !(field instanceof GroupListField ))
{
field.getComponent().setEnabled(false);
field.getComponent().setVisible(false);
}
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/UserEditUI.java | Java | gpl3 | 13,212 |
/*--------------------------------------------------------------------------*
| 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.internal.edit;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JPanel;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.IllegalAnnotationException;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.framework.Disposable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.EditComponent;
import org.rapla.gui.EditController;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.DisposingTool;
public class EditDialog<T extends Entity> extends RaplaGUIComponent implements ModificationListener,Disposable {
DialogUI dlg;
boolean bSaving = false;
EditComponent<T> ui;
boolean modal;
private Collection<T> originals;
public EditDialog(RaplaContext sm,EditComponent<T> ui,boolean modal){
super( sm);
this.ui = ui;
this.modal = modal;
}
public EditDialog(RaplaContext sm,EditComponent<T> ui) {
this(sm,ui,true);
}
final private EditControllerImpl getPrivateEditDialog() {
return (EditControllerImpl) getService(EditController.class);
}
public int start(Collection<T> editObjects,String title,Component owner)
throws
RaplaException
{
// sets for every object in this array an edit item in the logfile
originals= new ArrayList<T>();
Map<T, T> persistant = getModification().getPersistant( editObjects);
for (T entity : editObjects)
{
getLogger().debug("Editing Object: " + entity);
@SuppressWarnings("unchecked")
Entity<T> mementable = persistant.get( entity);
if ( mementable != null)
{
if ( originals == null)
{
throw new RaplaException("You cannot edit persistant and new entities in one operation");
}
originals.add( mementable.clone() );
}
else
{
if ( originals != null && !originals.isEmpty())
{
throw new RaplaException("You cannot edit persistant and new entities in one operation");
}
originals = null;
}
}
List<T> toEdit = new ArrayList<T>(editObjects);
ui.setObjects(toEdit);
JComponent editComponent = ui.getComponent();
JPanel panel = new JPanel();
panel.setLayout( new BorderLayout());
panel.add( editComponent, BorderLayout.CENTER);
editComponent.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));
dlg = DialogUI.create(getContext(),owner,modal,panel,new String[] {
getString("save")
,getString("cancel")
});
dlg.setAbortAction(new AbortAction());
dlg.getButton(0).setAction(new SaveAction());
dlg.getButton(1).setAction(new AbortAction());
dlg.getButton(0).setIcon(getIcon("icon.save"));
dlg.getButton(1).setIcon(getIcon("icon.cancel"));
dlg.setTitle(getI18n().format("edit.format",title));
getUpdateModule().addModificationListener(this);
dlg.addWindowListener(new DisposingTool(this));
dlg.start();
if (modal)
{
return dlg.getSelectedIndex();
}
else
{
getPrivateEditDialog().addEditDialog( this );
// to avoid java compiler error
EditComponent test = ui;
if ( test instanceof CategoryEditUI)
{
((CategoryEditUI)test).processCreateNew();
}
return -1;
}
}
protected boolean shouldCancelOnModification(ModificationEvent evt) {
List<T> objects = ui.getObjects();
for (T o:objects )
{
// TODO include timestamps in preferencepatches
if ( o instanceof Preferences && ((Preferences)o).getOwner() != null)
{
continue;
}
if (evt.hasChanged(o))
{
return true;
}
}
return false;
}
public void dataChanged(ModificationEvent evt) throws RaplaException {
if (bSaving || dlg == null || !dlg.isVisible() || ui == null)
return;
if (shouldCancelOnModification(evt)) {
getLogger().warn("Object has been changed outside.");
DialogUI warning =
DialogUI.create(getContext()
,ui.getComponent()
,true
,getString("warning")
,getI18n().format("warning.update",ui.getObjects())
);
warning.start();
getPrivateEditDialog().removeEditDialog( this );
dlg.close();
}
}
class SaveAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
try {
ui.mapToObjects();
bSaving = true;
// object which is processed by EditComponent
List<T> saveObjects = ui.getObjects();
Collection<T> entities = new ArrayList<T>();
entities.addAll(saveObjects);
boolean canUndo = true;
for ( T obj: saveObjects)
{
if ( obj instanceof Preferences || obj instanceof DynamicType || obj instanceof Category)
{
canUndo = false;
}
}
if ( canUndo)
{
@SuppressWarnings({ "unchecked", "rawtypes" })
SaveUndo<T> saveCommand = new SaveUndo(getContext(), entities, originals);
CommandHistory commandHistory = getModification().getCommandHistory();
commandHistory.storeAndExecute(saveCommand);
}
else
{
getModification().storeObjects( saveObjects.toArray( new Entity[] {}));
}
getPrivateEditDialog().removeEditDialog(EditDialog.this);
dlg.close();
} catch (IllegalAnnotationException ex) {
showWarning(ex.getMessage(), dlg);
} catch (RaplaException ex) {
showException(ex, dlg);
}
}
}
class AbortAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
getPrivateEditDialog().removeEditDialog( EditDialog.this );
dlg.close();
}
}
public void dispose() {
getUpdateModule().removeModificationListener(this);
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/EditDialog.java | Java | gpl3 | 8,462 |
package org.rapla.gui.internal.edit;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.rapla.components.calendar.NavButton;
import org.rapla.components.calendar.RaplaArrowButton;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.gui.toolkit.AWTColorUtil;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaWidget;
final public class RaplaListEdit<T> implements
RaplaWidget
{
boolean coloredBackground = false;
int[] oldIndex = new int[0];
JPanel mainPanel = new JPanel();
JPanel statusBar = new JPanel();
JPanel identifierPanel = new JPanel();
JLabel identifier = new JLabel();
JLabel nothingSelectedLabel = new JLabel();
JScrollPane scrollPane;
NavButton prev = new NavButton('^');
NavButton next = new NavButton('v');
RaplaArrowButton moveUpButton = new RaplaArrowButton('^', 25);
RaplaArrowButton moveDownButton = new RaplaArrowButton('v', 25);
Color selectionBackground = UIManager.getColor("List.selectionBackground");
Color background = UIManager.getColor("List.background");
JPanel jointPanel = new JPanel() {
private static final long serialVersionUID = 1L;
int xa[] = new int[4];
int ya[] = new int[4];
public void paint(Graphics g) {
super.paint(g);
Dimension dim = getSize();
int index = list.getSelectedIndex();
Rectangle rect = list.getCellBounds(index,index);
if (rect != null) {
int y = rect.y -scrollPane.getViewport().getViewPosition().y;
int y1= Math.min(dim.height,Math.max(0, y) + scrollPane.getLocation().y);
int y2= Math.min(dim.height,Math.max(0,y + rect.height) + scrollPane.getLocation().y);
xa[0]=0;
ya[0]=y1;
xa[1]=dim.width;
ya[1]=0;
xa[2]=dim.width;
ya[2]=dim.height;
xa[3]=0;
ya[3]=y2;
g.setColor(selectionBackground);
g.fillPolygon(xa,ya,4);
g.setColor(background);
g.drawLine(xa[0],ya[0],xa[1],ya[1]);
g.drawLine(xa[3],ya[3],xa[2],ya[2]);
}
}
};
JPanel content = new JPanel();
JPanel detailContainer = new JPanel();
JPanel editPanel = new JPanel();
JList list = new JList() {
private static final long serialVersionUID = 1L;
@SuppressWarnings("unchecked")
public void setModel(ListModel model) {
super.setModel( model );
model.addListDataListener(new ListDataListener() {
public void contentsChanged(ListDataEvent e) {
modelUpdate();
}
public void intervalAdded(ListDataEvent e) {
}
public void intervalRemoved(ListDataEvent e) {
}
});
}
};
public RaplaButton createNewButton = new RaplaButton();
public RaplaButton removeButton = new RaplaButton();
CardLayout cardLayout = new CardLayout();
private Listener listener = new Listener();
private ActionListener callback;
JPanel toolbar = new JPanel();
public RaplaListEdit(I18nBundle i18n, JComponent detailContent,ActionListener callback)
{
this.callback = callback;
toolbar.setLayout( new BoxLayout( toolbar, BoxLayout.X_AXIS));
toolbar.add(createNewButton);
toolbar.add(removeButton);
toolbar.add(Box.createHorizontalStrut(5));
toolbar.add(moveUpButton);
toolbar.add(moveDownButton);
mainPanel.setLayout(new TableLayout(new double[][] {
{TableLayout.PREFERRED,TableLayout.PREFERRED,TableLayout.FILL}
,{TableLayout.FILL}
}));
jointPanel.setPreferredSize(new Dimension(15,50));
mainPanel.add(content,"0,0");
mainPanel.add(jointPanel,"1,0");
mainPanel.add(editPanel,"2,0");
editPanel.setLayout(cardLayout);
editPanel.add(nothingSelectedLabel, "0");
editPanel.add(detailContainer, "1");
content.setLayout(new BorderLayout());
content.add(toolbar,BorderLayout.NORTH);
scrollPane = new JScrollPane(list
,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(310,80));
content.add(scrollPane, BorderLayout.CENTER);
content.add(statusBar, BorderLayout.SOUTH);
statusBar.setLayout( new FlowLayout(FlowLayout.LEFT));
detailContainer.setLayout(new BorderLayout());
editPanel.setBorder(BorderFactory.createRaisedBevelBorder());
detailContainer.add(identifierPanel,BorderLayout.WEST);
detailContainer.add(detailContent, BorderLayout.CENTER);
//mainPanel.setBorder(new LineBorder(Color.black));
identifierPanel.setLayout(new BorderLayout());
identifierPanel.add(prev,BorderLayout.NORTH);
identifierPanel.add(identifier,BorderLayout.CENTER);
identifierPanel.add(next,BorderLayout.SOUTH);
identifier.setBorder(new EmptyBorder(0,5,0,5));
next.addActionListener(listener);
prev.addActionListener(listener);
removeButton.addActionListener(listener);
createNewButton.addActionListener(listener);
moveUpButton.addActionListener(listener);
moveDownButton.addActionListener(listener);
scrollPane.getViewport().addChangeListener(listener);
// list.setDragEnabled(true);
list.addMouseListener(listener);
list.addListSelectionListener(listener);
modelUpdate();
createNewButton.setText(i18n.getString("new"));
createNewButton.setIcon(i18n.getIcon("icon.new"));
removeButton.setIcon(i18n.getIcon("icon.delete"));
removeButton.setText(i18n.getString("delete"));
nothingSelectedLabel.setHorizontalAlignment(JLabel.CENTER);
nothingSelectedLabel.setText(i18n.getString("nothing_selected"));
}
public JPanel getToolbar()
{
return toolbar;
}
public JComponent getComponent() {
return mainPanel;
}
public JPanel getStatusBar() {
return statusBar;
}
public JList getList() {
return list;
}
public void setListDimension(Dimension d) {
scrollPane.setPreferredSize(d);
}
public void setMoveButtonVisible(boolean visible) {
moveUpButton.setVisible(visible);
moveDownButton.setVisible(visible);
}
public int getSelectedIndex() {
return list.getSelectedIndex();
}
public void select(int index) {
list.setSelectedIndex(index);
if (index >=0) {
list.ensureIndexIsVisible(index);
}
}
public void setColoredBackgroundEnabled(boolean enable) {
coloredBackground = enable;
}
public boolean isColoredBackgroundEnabled() {
return coloredBackground;
}
private void modelUpdate() {
removeButton.setEnabled(list.getMinSelectionIndex() >=0);
moveUpButton.setEnabled(list.getMinSelectionIndex() > 0);
moveDownButton.setEnabled(list.getMinSelectionIndex() >= 0 &&
list.getMaxSelectionIndex() < (list.getModel().getSize() -1) );
jointPanel.repaint();
}
private void editSelectedEntry() {
Object selected = list.getSelectedValue();
if (selected == null) {
cardLayout.first(editPanel);
callback.actionPerformed(new ActionEvent(this
,ActionEvent.ACTION_PERFORMED
,"select"
)
);
return;
} else {
cardLayout.last(editPanel);
int index = getSelectedIndex();
next.setEnabled((index + 1)<list.getModel().getSize());
prev.setEnabled(index>0);
Color color = AWTColorUtil.getAppointmentColor(0);
if ( isColoredBackgroundEnabled() ) {
color = AWTColorUtil.getAppointmentColor(index);
}
identifierPanel.setBackground(color);
identifier.setText(String.valueOf(index + 1));
callback.actionPerformed(new ActionEvent(this
,ActionEvent.ACTION_PERFORMED
,"select"
)
);
callback.actionPerformed(new ActionEvent(this
,ActionEvent.ACTION_PERFORMED
,"edit"
)
);
}
}
private boolean disableListSelection;
public void updateSort(List<Object> selectedValues) {
ListModel model2 = list.getModel();
int[] index = new int[selectedValues.size()];
int j = 0;
for ( int i=0;i<model2.getSize();i++)
{
Object elementAt = model2.getElementAt( i);
if ( selectedValues.contains( elementAt ))
{
index[j++] = i;
}
}
disableListSelection = true;
list.setSelectedIndices( index);
disableListSelection = false;
}
class Listener extends MouseAdapter implements ListSelectionListener,ActionListener,ChangeListener {
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == next) {
select(Math.min(list.getModel().getSize()-1, getSelectedIndex() + 1));
} else if (evt.getSource() == prev) {
select(Math.max(0, getSelectedIndex()-1));
}
if (evt.getSource() == removeButton) {
callback.actionPerformed(new ActionEvent(RaplaListEdit.this
,ActionEvent.ACTION_PERFORMED
,"remove"
)
);
} else if (evt.getSource() == createNewButton) {
callback.actionPerformed(new ActionEvent(RaplaListEdit.this
,ActionEvent.ACTION_PERFORMED
,"new"
)
);
} else if (evt.getSource() == moveUpButton) {
callback.actionPerformed(new ActionEvent(RaplaListEdit.this
,ActionEvent.ACTION_PERFORMED
,"moveUp"
)
);
} else if (evt.getSource() == moveDownButton) {
callback.actionPerformed(new ActionEvent(RaplaListEdit.this
,ActionEvent.ACTION_PERFORMED
,"moveDown"
)
);
}
}
public void valueChanged(ListSelectionEvent evt) {
if ( disableListSelection )
{
return;
}
//if (evt.getValueIsAdjusting())
//return;
int[] index = list.getSelectedIndices();
if ( index == oldIndex)
{
return;
}
if ( index == null || oldIndex == null || !Arrays.equals( index, oldIndex))
{
oldIndex = index;
editSelectedEntry();
modelUpdate();
}
}
public void stateChanged(ChangeEvent evt) {
if (evt.getSource() == scrollPane.getViewport()) {
jointPanel.repaint();
}
}
}
@SuppressWarnings({ "unchecked", "deprecation" })
public Collection<T> getSelectedValues()
{
return (Collection<T>) Arrays.asList(list.getSelectedValues());
}
@SuppressWarnings("unchecked")
public T getSelectedValue() {
return (T) list.getSelectedValue();
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/edit/RaplaListEdit.java | Java | gpl3 | 13,528 |
/*--------------------------------------------------------------------------*
| 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.gui.internal;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JToolBar;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.User;
import org.rapla.entities.domain.Permission;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ModificationEvent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.action.SaveableToggleAction;
import org.rapla.gui.internal.common.InternMenus;
import org.rapla.gui.internal.common.MultiCalendarView;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaMenuItem;
import org.rapla.gui.toolkit.RaplaWidget;
import org.rapla.storage.UpdateResult;
final public class CalendarEditor extends RaplaGUIComponent implements RaplaWidget {
public static final TypedComponentRole<Boolean> SHOW_CONFLICTS_CONFIG_ENTRY = new TypedComponentRole<Boolean>("org.rapla.showConflicts");
public static final TypedComponentRole<Boolean> SHOW_SELECTION_CONFIG_ENTRY = new TypedComponentRole<Boolean>("org.rapla.showSelection");
public static final String SHOW_SELECTION_MENU_ENTRY = "show_resource_selection";
public static final String SHOW_CONFLICTS_MENU_ENTRY = "show_conflicts";
RaplaMenuItem ownReservationsMenu;
JSplitPane content = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
final private ResourceSelection resourceSelection;
final private SavedCalendarView savedViews;
final private ConflictSelection conflictsView;
final public MultiCalendarView calendarContainer;
final JToolBar minimized;
final JToolBar templatePanel;
final JPanel left;
boolean listenersDisabled = false;
public CalendarEditor(RaplaContext context, final CalendarSelectionModel model) throws RaplaException {
super(context);
calendarContainer = new MultiCalendarView(getContext(), model, this);
calendarContainer.addValueChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e) {
if ( listenersDisabled)
{
return;
}
try {
resourceSelection.updateMenu();
} catch (RaplaException e1) {
getLogger().error(e1.getMessage(), e1);
}
}
});
resourceSelection = new ResourceSelection(context, calendarContainer, model);
final ChangeListener treeListener = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if ( listenersDisabled)
{
return;
}
conflictsView.clearSelection();
}
};
final RaplaMenu viewMenu = getService( InternMenus.VIEW_MENU_ROLE);
ownReservationsMenu = new RaplaMenuItem("only_own_reservations");
ownReservationsMenu.setText( getString("only_own_reservations"));
ownReservationsMenu = new RaplaMenuItem("only_own_reservations");
ownReservationsMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean isSelected = model.isOnlyCurrentUserSelected();
// switch selection options
model.setOption( CalendarModel.ONLY_MY_EVENTS, isSelected ? "false":"true");
updateOwnReservationsSelected();
try {
Entity preferences = getQuery().getPreferences();
UpdateResult modificationEvt = new UpdateResult( getUser());
modificationEvt.addOperation( new UpdateResult.Change(preferences, preferences));
resourceSelection.dataChanged(modificationEvt);
calendarContainer.update(modificationEvt);
conflictsView.dataChanged( modificationEvt);
} catch (Exception ex) {
showException(ex, getComponent());
}
}
});
ownReservationsMenu.setText( getString("only_own_reservations"));
ownReservationsMenu.setIcon( getIcon("icon.unchecked"));
updateOwnReservationsSelected();
viewMenu.insertBeforeId( ownReservationsMenu, "show_tips" );
resourceSelection.getTreeSelection().addChangeListener( treeListener);
conflictsView = new ConflictSelection(context, calendarContainer, model);
left = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridheight = 1;
c.gridx = 1;
c.gridy = 1;
c.weightx = 0;
c.weighty = 0;
c.anchor = GridBagConstraints.EAST;
final JButton max = new JButton();
final JButton tree = new JButton();
tree.setEnabled( false );
minimized = new JToolBar(JToolBar.VERTICAL);
minimized.setFloatable( false);
minimized.add( max);
minimized.add( tree);
max.setIcon( UIManager.getDefaults().getIcon("InternalFrame.maximizeIcon"));
tree.setIcon( getIcon("icon.tree"));
JButton min = new RaplaButton(RaplaButton.SMALL);
ActionListener minmaxAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
savedViews.closeFilter();
int index = viewMenu.getIndexOfEntryWithId(SHOW_SELECTION_MENU_ENTRY);
JMenuItem component = (JMenuItem)viewMenu.getMenuComponent( index);
((SaveableToggleAction)component.getAction()).toggleCheckbox( component);
}
};
min.addActionListener( minmaxAction);
max.addActionListener( minmaxAction);
tree.addActionListener( minmaxAction);
templatePanel = new JToolBar(JToolBar.VERTICAL);
templatePanel.setFloatable( false);
final JButton exitTemplateEdit = new JButton();
//exitTemplateEdit.setIcon(getIcon("icon.close"));
exitTemplateEdit.setText(getString("close-template"));
templatePanel.add( exitTemplateEdit);
exitTemplateEdit.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
getModification().setTemplateName( null );
}
});
Icon icon = UIManager.getDefaults().getIcon("InternalFrame.minimizeIcon");
min.setIcon( icon) ;
//left.add(min, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridy = 1;
JPanel jp = new JPanel();
jp.setLayout( new BorderLayout());
savedViews = new SavedCalendarView(context, calendarContainer, resourceSelection,model);
jp.add( savedViews.getComponent(), BorderLayout.CENTER );
templatePanel.setVisible( false);
jp.add( templatePanel, BorderLayout.WEST );
JToolBar mintb =new JToolBar();
mintb.setFloatable( false);
// mintb.add( min);
min.setAlignmentY( JButton.TOP);
jp.add( min, BorderLayout.EAST);
left.add(jp, c);
c.fill = GridBagConstraints.BOTH;
c.gridy = 2;
c.weightx = 1;
c.weighty = 2.5;
left.add(resourceSelection.getComponent(), c);
c.weighty = 1.0;
c.gridy = 3;
left.add(conflictsView.getComponent(), c);
c.weighty = 0.0;
c.fill = GridBagConstraints.NONE;
c.gridy = 4;
c.anchor = GridBagConstraints.WEST;
left.add(conflictsView.getSummaryComponent(), c);
content.setRightComponent(calendarContainer.getComponent());
updateViews();
}
public void updateOwnReservationsSelected()
{
final CalendarSelectionModel model = resourceSelection.getModel();
boolean isSelected = model.isOnlyCurrentUserSelected();
ownReservationsMenu.setIcon(isSelected ? getIcon("icon.checked") : getIcon("icon.unchecked"));
ownReservationsMenu.setSelected(isSelected);
boolean canSeeEventsFromOthers = canSeeEventsFromOthers();
ownReservationsMenu.setEnabled( canSeeEventsFromOthers);
if ( !canSeeEventsFromOthers && !isSelected)
{
model.setOption(CalendarModel.ONLY_MY_EVENTS, "true");
}
}
private boolean canSeeEventsFromOthers() {
try {
Category category = getQuery().getUserGroupsCategory().getCategory(Permission.GROUP_CAN_READ_EVENTS_FROM_OTHERS);
if (category == null) {
return true;
}
User user = getUser();
return user.isAdmin() || user.belongsTo(category);
} catch (RaplaException ex) {
return false;
}
}
public void dataChanged(ModificationEvent evt) throws RaplaException {
listenersDisabled = true;
try
{
resourceSelection.dataChanged(evt);
calendarContainer.update(evt);
savedViews.update();
conflictsView.dataChanged(evt);
updateViews();
// this is done in calendarContainer update
//updateOwnReservationsSelected();
}
finally
{
listenersDisabled = false;
}
}
private void updateViews() throws RaplaException {
boolean showConflicts = getClientFacade().getPreferences().getEntryAsBoolean( SHOW_CONFLICTS_CONFIG_ENTRY, true);
boolean showSelection = getClientFacade().getPreferences().getEntryAsBoolean( SHOW_SELECTION_CONFIG_ENTRY, true);
conflictsView.getComponent().setVisible( showConflicts);
conflictsView.getSummaryComponent().setVisible( !showConflicts );
boolean templateMode = getModification().getTemplateName() != null;
if ( templateMode)
{
conflictsView.getComponent().setVisible(false);
conflictsView.getSummaryComponent().setVisible( false);
}
// if ( templateMode)
// {
// if ( content.getLeftComponent() != templatePanel)
// {
// content.setLeftComponent( templatePanel);
// content.setDividerSize(0);
// }
// }
// else
// {
if ( showSelection )
{
savedViews.getComponent().setVisible( !templateMode );
templatePanel.setVisible( templateMode);
resourceSelection.getFilterButton().setVisible( !templateMode );
if ( content.getLeftComponent() != left )
{
content.setLeftComponent( left);
content.setDividerSize( 5);
content.setDividerLocation(285);
}
}
else if ( content.getLeftComponent() != minimized)
{
content.setLeftComponent( minimized);
content.setDividerSize(0);
}
// }
}
public void start() {
calendarContainer.getSelectedCalendar().scrollToStart();
}
public JComponent getComponent() {
return content;
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/CalendarEditor.java | Java | gpl3 | 12,075 |
/*--------------------------------------------------------------------------*
| 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.internal;
import java.util.Locale;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.configuration.Preferences;
import org.rapla.facade.internal.CalendarOptionsImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.RaplaGUIComponent;
public class WarningsOption extends RaplaGUIComponent implements OptionPanel
{
JPanel panel = new JPanel();
Preferences preferences;
JCheckBox showConflictWarningsField = new JCheckBox();
public WarningsOption(RaplaContext sm) {
super( sm);
showConflictWarningsField.setText("");
double pre = TableLayout.PREFERRED;
panel.setLayout( new TableLayout(new double[][] {{pre, 5,pre}, {pre}}));
panel.add( new JLabel(getString("warning.conflict")),"0,0");
panel.add( showConflictWarningsField,"2,0");
}
public JComponent getComponent() {
return panel;
}
public String getName(Locale locale) {
return getString("warnings");
}
public void setPreferences( Preferences preferences) {
this.preferences = preferences;
}
public void show() throws RaplaException {
// get the options
boolean config = preferences.getEntryAsBoolean( CalendarOptionsImpl.SHOW_CONFLICT_WARNING, true);
showConflictWarningsField.setSelected( config);
}
public void commit() {
// Save the options
boolean selected = showConflictWarningsField.isSelected();
preferences.putEntry( CalendarOptionsImpl.SHOW_CONFLICT_WARNING, selected);
}
} | 04900db4-clienttest | src/org/rapla/gui/internal/WarningsOption.java | Java | gpl3 | 2,721 |
/*--------------------------------------------------------------------------*
| 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.internal;
import java.awt.Color;
import org.rapla.components.calendar.DateRenderer;
import org.rapla.components.calendar.WeekendHighlightRenderer;
import org.rapla.entities.domain.Period;
import org.rapla.facade.PeriodModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
public class RaplaDateRenderer extends RaplaComponent implements DateRenderer {
protected WeekendHighlightRenderer renderer = new WeekendHighlightRenderer();
protected Color periodColor = new Color(0xc5,0xda,0xdd);
protected PeriodModel periodModel;
public RaplaDateRenderer(RaplaContext sm) {
super(sm);
periodModel = getPeriodModel();
}
public RenderingInfo getRenderingInfo(int dayOfWeek,int day,int month, int year)
{
Period period = periodModel.getPeriodFor(getRaplaLocale().toRaplaDate(year,month,day));
if (period != null)
{
Color backgroundColor = periodColor;
Color foregroundColor = Color.BLACK;
String tooltipText = "<html>" + getString("period") + ":<br>" + period.getName(getI18n().getLocale()) + "</html>";
return new RenderingInfo(backgroundColor, foregroundColor, tooltipText);
}
return renderer.getRenderingInfo(dayOfWeek,day,month,year);
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/RaplaDateRenderer.java | Java | gpl3 | 2,272 |
/*--------------------------------------------------------------------------*
| 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.internal;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.MenuElement;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.rapla.client.ClientService;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.util.IOUtil;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.components.util.undo.CommandHistoryChangedListener;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.framework.internal.ConfigTools;
import org.rapla.gui.EditController;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.action.RestartRaplaAction;
import org.rapla.gui.internal.action.RestartServerAction;
import org.rapla.gui.internal.action.SaveableToggleAction;
import org.rapla.gui.internal.action.user.UserAction;
import org.rapla.gui.internal.common.InternMenus;
import org.rapla.gui.internal.edit.DeleteUndo;
import org.rapla.gui.internal.edit.reservation.SortedListModel;
import org.rapla.gui.internal.print.PrintAction;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.HTMLView;
import org.rapla.gui.toolkit.IdentifiableMenuEntry;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaFrame;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaMenuItem;
import org.rapla.gui.toolkit.RaplaSeparator;
import org.rapla.gui.toolkit.RaplaWidget;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
public class RaplaMenuBar extends RaplaGUIComponent
{
final JMenuItem exit;
final JMenuItem redo;
final JMenuItem undo;
JMenuItem templateEdit;
public RaplaMenuBar(RaplaContext context) throws RaplaException {
super(context);
RaplaMenu systemMenu = getService( InternMenus.FILE_MENU_ROLE );
systemMenu.setText( getString("file"));
RaplaMenu editMenu = getService( InternMenus.EDIT_MENU_ROLE );
editMenu.setText( getString("edit"));
RaplaMenu exportMenu = getService( InternMenus.EXPORT_MENU_ROLE );
exportMenu.setText( getString("export"));
RaplaMenu importMenu = getService( InternMenus.IMPORT_MENU_ROLE );
importMenu.setText( getString("import"));
JMenuItem newMenu = getService( InternMenus.NEW_MENU_ROLE );
newMenu.setText( getString("new"));
JMenuItem calendarSettings = getService( InternMenus.CALENDAR_SETTINGS );
calendarSettings.setText( getString("calendar"));
RaplaMenu extraMenu = getService( InternMenus.EXTRA_MENU_ROLE);
extraMenu.setText( getString("help"));
RaplaMenu adminMenu = getService( InternMenus.ADMIN_MENU_ROLE );
adminMenu.setText( getString("admin"));
RaplaMenu viewMenu = getService( InternMenus.VIEW_MENU_ROLE );
viewMenu.setText( getString("view"));
viewMenu.add( new RaplaSeparator("view_save"));
if ( getUser().isAdmin())
{
addPluginExtensions( RaplaClientExtensionPoints.ADMIN_MENU_EXTENSION_POINT, adminMenu);
}
addPluginExtensions( RaplaClientExtensionPoints.IMPORT_MENU_EXTENSION_POINT, importMenu);
addPluginExtensions( RaplaClientExtensionPoints.EXPORT_MENU_EXTENSION_POINT, exportMenu);
addPluginExtensions( RaplaClientExtensionPoints.HELP_MENU_EXTENSION_POINT, extraMenu);
addPluginExtensions( RaplaClientExtensionPoints.VIEW_MENU_EXTENSION_POINT,viewMenu);
addPluginExtensions( RaplaClientExtensionPoints.EDIT_MENU_EXTENSION_POINT, editMenu);
systemMenu.add( newMenu);
systemMenu.add( calendarSettings);
systemMenu.add( new JSeparator());
systemMenu.add( exportMenu );
systemMenu.add( importMenu );
systemMenu.add( adminMenu);
JSeparator printSep = new JSeparator();
printSep.setName(getString("calendar"));
systemMenu.add( printSep);
JMenuItem printMenu = new JMenuItem( getString("print"));
PrintAction printAction = new PrintAction(getContext());
printMenu.setAction( printAction );
printAction.setEnabled( true );
CalendarSelectionModel model = getService(CalendarSelectionModel.class);
printAction.setModel(model);
systemMenu.add( printMenu );
systemMenu.add( new JSeparator());
if ( getService(ClientService.class).canSwitchBack() ) {
JMenuItem switchBack = new JMenuItem();
switchBack.setAction( new UserAction(getContext(),null,null).setSwitchToUser());
adminMenu.add( switchBack );
}
boolean server = getUpdateModule().isClientForServer();
if ( server && isAdmin() ) {
JMenuItem restartServer = new JMenuItem();
restartServer.setAction( new RestartServerAction(getContext()));
adminMenu.add( restartServer );
}
Listener listener = new Listener();
JMenuItem restart = new JMenuItem();
restart.setAction( new RestartRaplaAction(getContext()));
systemMenu.add( restart );
systemMenu.setMnemonic('F');
exit = new JMenuItem(getString("exit"));
exit.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Q, ActionEvent.CTRL_MASK ) );
exit.setMnemonic('x');
exit.addActionListener( listener );
systemMenu.add( exit );
redo = new JMenuItem(getString("redo"));
undo = new JMenuItem(getString("undo"));
undo.setToolTipText(getString("undo"));
undo.setIcon(getIcon("icon.undo"));
redo.addActionListener( listener);
undo.addActionListener( listener);
redo.setToolTipText(getString("redo"));
redo.setIcon(getIcon("icon.redo"));
getModification().getCommandHistory().addCommandHistoryChangedListener(listener);
undo.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Z, ActionEvent.CTRL_MASK ) );
redo.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Y, ActionEvent.CTRL_MASK ) );
undo.setEnabled(false);
redo.setEnabled(false);
editMenu.insertBeforeId( undo,"EDIT_BEGIN");
editMenu.insertBeforeId( redo,"EDIT_BEGIN" );
RaplaMenuItem userOptions = new RaplaMenuItem("userOptions");
editMenu.add( userOptions );
if ( getQuery().canEditTemplats( getUser()))
{
templateEdit = new RaplaMenuItem("template");
updateTemplateText();
templateEdit.addActionListener( listener);
editMenu.add( templateEdit );
}
if ( isModifyPreferencesAllowed() ) {
userOptions.setAction( createOptionAction( getQuery().getPreferences( )));
} else {
userOptions.setVisible( false );
}
{
SaveableToggleAction action = new SaveableToggleAction( context, "show_tips",RaplaBuilder.SHOW_TOOLTIP_CONFIG_ENTRY);
RaplaMenuItem menu = action.createMenuItem();
viewMenu.insertBeforeId( menu, "view_save" );
}
{
SaveableToggleAction action = new SaveableToggleAction( context, CalendarEditor.SHOW_CONFLICTS_MENU_ENTRY,CalendarEditor.SHOW_CONFLICTS_CONFIG_ENTRY);
RaplaMenuItem menu = action.createMenuItem();
viewMenu.insertBeforeId( menu, "view_save" );
}
{
SaveableToggleAction action = new SaveableToggleAction( context, CalendarEditor.SHOW_SELECTION_MENU_ENTRY,CalendarEditor.SHOW_SELECTION_CONFIG_ENTRY);
RaplaMenuItem menu = action.createMenuItem();
viewMenu.insertBeforeId( menu, "view_save" );
}
if ( isAdmin() ) {
RaplaMenuItem adminOptions = new RaplaMenuItem("adminOptions");
adminOptions.setAction( createOptionAction( getQuery().getSystemPreferences()));
adminMenu.add( adminOptions );
}
RaplaMenuItem info = new RaplaMenuItem("info");
info.setAction( createInfoAction( ));
extraMenu.add( info );
// within the help menu we need another point for the license
RaplaMenuItem license = new RaplaMenuItem("license");
// give this menu item an action to perform on click
license.setAction(createLicenseAction());
// add the license dialog below the info entry
extraMenu.add(license);
adminMenu.setEnabled( adminMenu.getMenuComponentCount() != 0 );
exportMenu.setEnabled( exportMenu.getMenuComponentCount() != 0);
importMenu.setEnabled( importMenu.getMenuComponentCount() != 0);
getUpdateModule().addModificationListener( listener);
}
protected void updateTemplateText() {
if ( templateEdit == null)
{
return;
}
String editString = getString("edit-templates");
String exitString = getString("close-template");
templateEdit.setText(isTemplateEdit() ? exitString : editString);
}
protected boolean isTemplateEdit() {
return getModification().getTemplateName() != null;
}
class Listener implements ActionListener, CommandHistoryChangedListener, ModificationListener
{
public void historyChanged()
{
CommandHistory history = getModification().getCommandHistory();
redo.setEnabled(history.canRedo());
undo.setEnabled(history.canUndo());
redo.setText(getString("redo") + ": " + history.getRedoText());
undo.setText(getString("undo") + ": " + history.getUndoText());
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if ( source == exit)
{
RaplaFrame mainComponent = (RaplaFrame)getMainComponent();
mainComponent.close();
}
else if ( source == templateEdit)
{
if ( isTemplateEdit())
{
getModification().setTemplateName( null );
}
else
{
templateEdit();
}
}
else
{
CommandHistory commandHistory = getModification().getCommandHistory();
try {
if ( source == redo)
{
commandHistory.redo();
}
if ( source == undo)
{
commandHistory.undo();
}
} catch (Exception ex) {
showException(ex, getMainComponent());
}
}
}
public void dataChanged(ModificationEvent evt) throws RaplaException {
updateTemplateText();
}
}
private void addPluginExtensions(
TypedComponentRole<IdentifiableMenuEntry> extensionPoint,
RaplaMenu menu) throws RaplaContextException
{
Collection<IdentifiableMenuEntry> points = getContainer().lookupServicesFor( extensionPoint);
for (IdentifiableMenuEntry menuItem: points)
{
MenuElement menuElement = menuItem.getMenuElement();
menu.add( menuElement.getComponent());
}
}
private Action createOptionAction( final Preferences preferences) {
AbstractAction action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
try {
EditController editContrl = getService(EditController.class);
editContrl.edit( preferences, getMainComponent());
} catch (RaplaException ex) {
showException( ex, getMainComponent());
}
}
};
action.putValue( Action.SMALL_ICON, getIcon("icon.options") );
action.putValue( Action.NAME, getString("options"));
return action;
}
private Action createInfoAction( ) {
final String name = getString("info");
final Icon icon = getIcon("icon.info_small");
AbstractAction action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed( ActionEvent e )
{
try {
HTMLView infoText = new HTMLView();
infoText.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
String javaversion;
try {
javaversion = System.getProperty("java.version");
} catch (SecurityException ex) {
javaversion = "-";
getLogger().warn("Permission to system properties denied!");
}
boolean isSigned = IOUtil.isSigned();
String signed = getString( isSigned ? "yes": "no");
String mainText = getI18n().format("info.text",signed,javaversion);
StringBuffer completeText = new StringBuffer();
completeText.append( mainText);
URL librariesURL = null;
try {
Enumeration<URL> resources = ConfigTools.class.getClassLoader().getResources("META-INF/readme.txt");
if ( resources.hasMoreElements())
{
librariesURL = resources.nextElement();
}
} catch (IOException e1) {
}
if ( librariesURL != null)
{
completeText.append("<pre>\n\n\n");
BufferedReader bufferedReader = null;
try
{
bufferedReader = new BufferedReader( new InputStreamReader( librariesURL.openStream()));
while ( true)
{
String line = bufferedReader.readLine();
if ( line == null)
{
break;
}
completeText.append(line);
completeText.append("\n");
}
}
catch (IOException ex)
{
try {
if ( bufferedReader != null)
{
bufferedReader.close();
}
} catch (IOException e1) {
}
}
completeText.append("</pre>");
}
String body = completeText.toString();
infoText.setBody(body);
final JScrollPane content = new JScrollPane(infoText);
DialogUI dialog = DialogUI.create( getContext(),getMainComponent(),false, content, new String[] {getString("ok")});
dialog.setTitle( name);
dialog.setSize( 780, 580);
dialog.startNoPack();
SwingUtilities.invokeLater( new Runnable()
{
public void run() {
content.getViewport().setViewPosition( new Point(0,0));
}
});
} catch (RaplaException ex) {
showException( ex, getMainComponent());
}
}
};
action.putValue( Action.SMALL_ICON, icon );
action.putValue( Action.NAME, name);
return action;
}
/**
* the action to perform when someone clicks on the license entry in the
* help section of the menu bar
*
* this method is a modified version of the existing method createInfoAction()
*/
private Action createLicenseAction()
{
final String name = getString("licensedialog.title");
final Icon icon = getIcon("icon.info_small");
// overwrite the cass AbstractAction to design our own
AbstractAction action = new AbstractAction()
{
private static final long serialVersionUID = 1L;
// overwrite the actionPerformed method that is called on click
public void actionPerformed(ActionEvent e)
{
try
{
// we need a new instance of HTMLView to visualize the short
// version of the license text including the two links
HTMLView licenseText = new HTMLView();
// giving the gui element some borders
licenseText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
// we look up the text was originally meant for the welcome field
// and put it into a new instance of RaplaWidget
RaplaWidget welcomeField = getService(ClientService.WELCOME_FIELD);
// the following creates the dialog that pops up, when we click
// on the license entry within the help section of the menu bar
// we call the create Method of the DialogUI class and give it all necessary things
DialogUI dialog = DialogUI.create(getContext(), getMainComponent(), true, new JScrollPane(welcomeField.getComponent()), new String[] { getString("ok") });
// setting the dialog's title
dialog.setTitle(name);
// and the size of the popup window
dialog.setSize(550, 250);
// but I honestly have no clue what this startNoPack() does
dialog.startNoPack();
}
catch (RaplaException ex)
{
showException(ex, getMainComponent());
}
}
};
action.putValue(Action.SMALL_ICON, icon);
action.putValue(Action.NAME, name);
return action;
}
private void templateEdit() {
final Component parentComponent = getMainComponent();
try {
JPanel panel = new JPanel();
final JTextField textField = new JTextField(20);
addCopyPaste( textField);
panel.setPreferredSize( new Dimension(600,300));
panel.setLayout(new TableLayout( new double[][] {{TableLayout.PREFERRED,5,TableLayout.FILL, 5,TableLayout.PREFERRED},{TableLayout.PREFERRED,5,TableLayout.FILL, TableLayout.PREFERRED}}));
panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
panel.add(new JLabel("Templatename:"), "0,0");
panel.add(textField, "2,0");
addCopyPaste( textField);
final DefaultListModel model = new DefaultListModel();
@SuppressWarnings("unchecked")
final JList list = new JList(new SortedListModel(model));
Collection<String> templateNames= getQuery().getTemplateNames();
fillModel( model, templateNames);
final RaplaButton deleteButton = new RaplaButton(RaplaButton.SMALL);
deleteButton.setIcon(getIcon("icon.delete"));
panel.add( new JScrollPane(list), "0,2,2,1");
panel.add( deleteButton, "4,2,l,t");
//int selectedIndex = selectionBox.getSelectedIndex();
Object selectedItem = null;
list.setSelectedValue( selectedItem,true);
String templateName = getModification().getTemplateName();
if ( templateName != null)
{
textField.setText( templateName);
}
list.addListSelectionListener( new ListSelectionListener() {
public void valueChanged( ListSelectionEvent e )
{
String template = (String) list.getSelectedValue();
if ( template != null)
{
textField.setText( template );
}
deleteButton.setEnabled( template != null);
}
});
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if ( source == deleteButton)
{
String template = (String) list.getSelectedValue();
if ( template != null)
{
try {
Collection<Reservation> reservations = getQuery().getTemplateReservations(template);
DeleteUndo<Reservation> cmd = new DeleteUndo<Reservation>(getContext(), reservations);
getModification().getCommandHistory().storeAndExecute( cmd);
Collection<String> templateNames= getQuery().getTemplateNames();
fillModel( model, templateNames);
} catch (Exception ex) {
showException( ex, getMainComponent());
}
}
}
}
};
deleteButton.addActionListener( actionListener);
Collection<String> options = new ArrayList<String>();
options.add( getString("apply") );
options.add(getString("cancel"));
final DialogUI dlg = DialogUI.create(
getContext(),
parentComponent,true,panel,
options.toArray(new String[] {}));
dlg.setTitle(getString("edit-templates"));
dlg.getButton(options.size() - 1).setIcon(getIcon("icon.cancel"));
final AbstractAction action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
String template = textField.getText();
if ( template == null)
{
template = "";
}
template = template.trim();
if ( template.length() > 0)
{
String selectedTemplate = null;
Enumeration elements = model.elements();
while ( elements.hasMoreElements())
{
String test = (String)elements.nextElement();
if ( test.equals( template))
{
selectedTemplate = test;
break;
}
}
if (selectedTemplate == null)
{
selectedTemplate = template;
}
Date start = null;
if ( selectedTemplate != null)
{
try
{
Collection<Reservation> reservations = getQuery().getTemplateReservations(selectedTemplate);
for ( Reservation r:reservations)
{
Date firstDate = r.getFirstDate();
if ( start == null || firstDate.before(start ))
{
start = firstDate;
}
}
if ( start != null)
{
getService(CalendarSelectionModel.class).setSelectedDate( start);
}
}
catch (RaplaException ex)
{
showException( ex, getMainComponent());
}
}
getModification().setTemplateName( selectedTemplate);
}
else
{
getModification().setTemplateName( null);
}
dlg.close();
}
};
list.addMouseListener( new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if ( e.getClickCount() >=2)
{
action.actionPerformed( new ActionEvent( list, ActionEvent.ACTION_PERFORMED, "save"));
}
}
});
dlg.getButton(0).setAction( action);
dlg.getButton(0).setIcon(getIcon("icon.confirm"));
dlg.start();
updateTemplateText();
} catch (RaplaException ex) {
showException( ex, parentComponent);
}
}
@SuppressWarnings("unchecked")
private void fillModel(DefaultListModel model,Collection<String> templateNames) {
model.removeAllElements();
for ( String template:templateNames)
{
model.addElement( template);
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/RaplaMenuBar.java | Java | gpl3 | 25,294 |
/*--------------------------------------------------------------------------*
| 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.internal;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.gui.PublishExtension;
import org.rapla.gui.PublishExtensionFactory;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.toolkit.DialogUI;
/**
*/
public class PublishDialog extends RaplaGUIComponent
{
Collection<PublishExtensionFactory> extensionFactories;
PublishExtension addressCreator= null;
public PublishDialog(RaplaContext sm) throws RaplaException
{
super(sm);
if ( !isModifyPreferencesAllowed() ) {
extensionFactories = Collections.emptyList();
}
else
{
extensionFactories = getContainer().lookupServicesFor(RaplaClientExtensionPoints.PUBLISH_EXTENSION_OPTION);
}
}
public boolean hasPublishActions()
{
return extensionFactories.size() > 0;
}
String getAddress(String filename, String generator) {
try
{
StartupEnvironment env = getService( StartupEnvironment.class );
URL codeBase = env.getDownloadURL();
String pageParameters = "page="+generator+"&user=" + getUser().getUsername();
if ( filename != null)
{
pageParameters = pageParameters + "&file=" + URLEncoder.encode( filename, "UTF-8" );
}
final String urlExtension = pageParameters;
return new URL( codeBase,"rapla?" + urlExtension).toExternalForm();
}
catch (Exception ex)
{
return "Not in webstart mode. Exportname is " + filename ;
}
}
public void export(final CalendarSelectionModel model,final Component parentComponent,final String filename) throws RaplaException
{
JPanel panel = new JPanel();
panel.setPreferredSize( new Dimension(600,300));
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
final Collection<PublishExtension> extensions = new ArrayList<PublishExtension>();
addressCreator = null;
for ( PublishExtensionFactory entry:extensionFactories)
{
PublishExtensionFactory extensionFactory = entry;
PublishExtension extension = extensionFactory.creatExtension(model, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt)
{
updateAddress(filename, extensions);
}
});
JTextField urlField = extension.getURLField();
String generator = extension.getGenerator();
if ( urlField != null)
{
String address = getAddress(filename, generator);
urlField.setText(address);
}
if ( extension.hasAddressCreationStrategy())
{
if ( addressCreator != null)
{
getLogger().error("Only one address creator can be used. " + addressCreator.toString() + " will be ignored.");
}
addressCreator = extension;
}
extensions.add( extension);
JPanel extPanel = extension.getPanel();
if ( extPanel != null)
{
panel.add( extPanel);
}
}
updateAddress(filename, extensions);
final DialogUI dlg = DialogUI.create(
getContext(),
parentComponent,false,panel,
new String[] {
getString("save")
,getString("cancel")
});
dlg.setTitle(getString("publish"));
dlg.getButton(0).setIcon(getIcon("icon.save"));
dlg.getButton(1).setIcon(getIcon("icon.cancel"));
dlg.getButton(0).setAction( new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
dlg.close();
try
{
for (PublishExtension extension :extensions)
{
extension.mapOptionTo();
}
model.save( filename);
}
catch (RaplaException ex)
{
showException( ex, parentComponent);
}
}
});
dlg.start();
}
protected void updateAddress(final String filename,
final Collection<PublishExtension> extensions) {
for ( PublishExtension entry:extensions)
{
PublishExtension extension = entry;
JTextField urlField = extension.getURLField();
if ( urlField != null)
{
String generator = extension.getGenerator();
String address;
if ( addressCreator != null )
{
address = addressCreator.getAddress(filename, generator);
}
else
{
address = getAddress(filename, generator);
}
urlField.setText(address);
}
}
}
} | 04900db4-clienttest | src/org/rapla/gui/internal/PublishDialog.java | Java | gpl3 | 6,375 |
package org.rapla.gui.internal;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JWindow;
import javax.swing.event.ChangeListener;
import org.rapla.components.calendar.RaplaArrowButton;
import org.rapla.facade.ClassifiableFilter;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.edit.ClassifiableFilterEdit;
import org.rapla.gui.toolkit.DialogUI;
public class FilterEditButton extends RaplaGUIComponent
{
protected RaplaArrowButton filterButton;
JWindow popup;
ClassifiableFilterEdit ui;
public FilterEditButton(final RaplaContext context,final ClassifiableFilter filter, final ChangeListener listener, final boolean isResourceSelection)
{
super(context);
filterButton = new RaplaArrowButton('v');
filterButton.setText(getString("filter"));
filterButton.setSize(80,18);
filterButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e) {
if ( popup != null)
{
popup.setVisible(false);
popup= null;
filterButton.setChar('v');
return;
}
try {
if ( ui != null && listener != null)
{
ui.removeChangeListener( listener);
}
ui = new ClassifiableFilterEdit( context, isResourceSelection);
if ( listener != null)
{
ui.addChangeListener(listener);
}
ui.setFilter( filter);
final Point locationOnScreen = filterButton.getLocationOnScreen();
final int y = locationOnScreen.y + 18;
final int x = locationOnScreen.x;
if ( popup == null)
{
Component ownerWindow = DialogUI.getOwnerWindow(filterButton);
if ( ownerWindow instanceof Frame)
{
popup = new JWindow((Frame)ownerWindow);
}
else if ( ownerWindow instanceof Dialog)
{
popup = new JWindow((Dialog)ownerWindow);
}
}
JComponent content = ui.getComponent();
popup.setContentPane(content );
popup.setSize( content.getPreferredSize());
popup.setLocation( x, y);
//.getSharedInstance().getPopup( filterButton, ui.getComponent(), x, y);
popup.setVisible(true);
filterButton.setChar('^');
} catch (Exception ex) {
showException(ex, getMainComponent());
}
}
});
}
public ClassifiableFilterEdit getFilterUI()
{
return ui;
}
public RaplaArrowButton getButton()
{
return filterButton;
}
} | 04900db4-clienttest | src/org/rapla/gui/internal/FilterEditButton.java | Java | gpl3 | 3,331 |
/*--------------------------------------------------------------------------*
| 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.internal.action;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
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.facade.CalendarSelectionModel;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaAction;
import org.rapla.gui.ReservationController;
import org.rapla.gui.ReservationEdit;
public class AppointmentAction extends RaplaAction {
public final static int DELETE = 1;
public final static int COPY = 2;
public final static int PASTE = 3;
public final static int CUT = 4;
public final static int EDIT = 6;
public final static int VIEW = 7;
public final static int CHANGE_ALLOCATABLE = 8;
public final static int ADD_TO_RESERVATION = 9;
public final static int PASTE_AS_NEW = 10;
public final static int DELETE_SELECTION = 11;
private boolean keepTime = false;
Component parent;
Point point;
int type;
AppointmentBlock appointmentBlock;
ReservationEdit reservationEdit;
// ReservationWizard wizard;
private Collection<Allocatable> contextAllocatables;
public AppointmentAction(RaplaContext context,Component parent,Point point)
{
super( context);
this.parent = parent;
this.point = point;
}
public AppointmentAction setAddTo(ReservationEdit reservationEdit)
{
this.reservationEdit = reservationEdit;
this.type = ADD_TO_RESERVATION;
String name2 = getName(reservationEdit.getReservation());
String value = name2.trim().length() > 0 ? "'" + name2 + "'" : getString("new_reservation");
putValue(NAME, value);
putValue(SMALL_ICON, getIcon("icon.new"));
boolean canAllocate = canAllocate();
setEnabled( canAllocate);
return this;
}
public AppointmentAction setCopy(AppointmentBlock appointmentBlock, Collection<Allocatable> contextAllocatables) {
this.appointmentBlock = appointmentBlock;
this.type = COPY;
this.contextAllocatables = contextAllocatables;
putValue(NAME, getString("copy"));
putValue(SMALL_ICON, getIcon("icon.copy"));
setEnabled(canCreateReservation());
return this;
}
public AppointmentAction setPaste( boolean keepTime) {
this.type = PASTE;
this.keepTime = keepTime;
putValue(NAME, getString("paste_into_existing_event"));
putValue(SMALL_ICON, getIcon("icon.paste"));
setEnabled(isAppointmentOnClipboard() && canCreateReservation());
return this;
}
public AppointmentAction setPasteAsNew( boolean keepTime) {
this.keepTime = keepTime;
this.type = PASTE_AS_NEW;
putValue(NAME, getString("paste_as") + " " + getString( "new_reservation" ) );
putValue(SMALL_ICON, getIcon("icon.paste_new"));
setEnabled(isAppointmentOnClipboard() && canCreateReservation());
return this;
}
/**
* Context menu entry to delete an appointment.
*/
public AppointmentAction setDelete(AppointmentBlock appointmentBlock){
this.appointmentBlock = appointmentBlock;
Appointment appointment = appointmentBlock.getAppointment();
this.type = DELETE;
putValue(NAME, getI18n().format("delete.format", getString("appointment")));
putValue(SMALL_ICON, getIcon("icon.delete"));
setEnabled(canModify(appointment.getReservation()));
return this;
}
public AppointmentAction setDeleteSelection(Collection<AppointmentBlock> selection) {
this.type = DELETE_SELECTION;
putValue(NAME, getString("delete_selection"));
putValue(SMALL_ICON, getIcon("icon.delete"));
changeSelection( selection );
return this;
}
Collection<AppointmentBlock> blockList;
private void changeSelection(Collection<AppointmentBlock> blockList) {
this.blockList = blockList;
if (type == DELETE_SELECTION) {
boolean enabled = true;
if (blockList != null && blockList.size() > 0 ) {
Iterator<AppointmentBlock> it = blockList.iterator();
while (it.hasNext()) {
if (!canModify(it.next().getAppointment().getReservation())){
enabled = false;
break;
}
}
} else {
enabled = false;
}
setEnabled(enabled);
}
}
public AppointmentAction setView(AppointmentBlock appointmentBlock) {
this.appointmentBlock = appointmentBlock;
Appointment appointment = appointmentBlock.getAppointment();
this.type = VIEW;
putValue(NAME, getString("view"));
putValue(SMALL_ICON, getIcon("icon.help"));
try
{
User user = getUser();
boolean canRead = canRead(appointment, user);
setEnabled( canRead);
}
catch (RaplaException ex)
{
getLogger().error( "Can't get user",ex);
}
return this;
}
public AppointmentAction setEdit(AppointmentBlock appointmentBlock) {
this.appointmentBlock = appointmentBlock;
this.type = EDIT;
putValue(SMALL_ICON, getIcon("icon.edit"));
Appointment appointment = appointmentBlock.getAppointment();
boolean canExchangeAllocatables = getQuery().canExchangeAllocatables(appointment.getReservation());
boolean canModify = canModify(appointment.getReservation());
String text = !canModify && canExchangeAllocatables ? getString("exchange_allocatables") : getString("edit");
putValue(NAME, text);
setEnabled(canModify || canExchangeAllocatables );
return this;
}
public void actionPerformed(ActionEvent evt) {
try {
switch (type) {
case DELETE: delete();break;
case COPY: copy();break;
case PASTE: paste(false);break;
case PASTE_AS_NEW: paste( true);break;
// case NEW: newReservation();break;
case ADD_TO_RESERVATION: addToReservation();break;
case EDIT: edit();break;
case VIEW: view();break;
case DELETE_SELECTION: deleteSelection();break;
}
} catch (RaplaException ex) {
showException(ex,parent);
} // end of try-catch
}
private void deleteSelection() throws RaplaException {
if ( this.blockList == null){
return;
}
getReservationController().deleteBlocks(blockList,parent,point);
}
public void view() throws RaplaException {
Appointment appointment = appointmentBlock.getAppointment();
getInfoFactory().showInfoDialog(appointment.getReservation(),parent,point);
}
public void edit() throws RaplaException {
getReservationController().edit( appointmentBlock);
}
private void delete() throws RaplaException {
getReservationController().deleteAppointment(appointmentBlock,parent,point);
}
private void copy() throws RaplaException
{
getReservationController().copyAppointment(appointmentBlock,parent,point, contextAllocatables);
}
private void paste(boolean asNewReservation) throws RaplaException {
ReservationController reservationController = getReservationController();
CalendarSelectionModel model = getService( CalendarSelectionModel.class);
Date start = getStartDate(model);
reservationController.pasteAppointment( start
,parent
,point
,asNewReservation, keepTime);
}
private void addToReservation() throws RaplaException
{
CalendarSelectionModel model = getService( CalendarSelectionModel.class);
Date start = getStartDate(model);
Date end = getEndDate(model, start);
reservationEdit.addAppointment(start,end);
}
public boolean isAppointmentOnClipboard() {
return (getReservationController().isAppointmentOnClipboard());
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/action/AppointmentAction.java | Java | gpl3 | 9,329 |
/*--------------------------------------------------------------------------*
| 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.internal.action.user;
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import org.rapla.components.util.Tools;
import org.rapla.entities.User;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaAction;
import org.rapla.gui.toolkit.DialogUI;
public class PasswordChangeAction extends RaplaAction {
Object object;
Component parent;
public PasswordChangeAction(RaplaContext context,Component parent) {
super( context);
this.parent = parent;
putValue(NAME, getI18n().format("change.format",getString("password")));
}
public void changeObject(Object object) {
this.object = object;
update();
}
private void update() {
User user = null;
try {
user = getUser();
setEnabled(object != null && (isAdmin() || user.equals(object)));
} catch (RaplaException ex) {
setEnabled(false);
return;
}
}
public void actionPerformed(ActionEvent evt) {
try {
if (object == null)
return;
changePassword((User) object, !getUser().isAdmin());
} catch (RaplaException ex) {
showException(ex, this.parent);
}
}
public void changePassword(User user,boolean showOld) throws RaplaException{
new PasswordChangeActionA(user,showOld).start();
}
class PasswordChangeActionA extends AbstractAction {
private static final long serialVersionUID = 1L;
PasswordChangeUI ui;
DialogUI dlg;
User user;
boolean showOld;
PasswordChangeActionA(User user,boolean showOld) {
this.user = user;
this.showOld = showOld;
putValue(NAME, getString("change"));
}
public void start() throws RaplaException
{
ui = new PasswordChangeUI(getContext(),showOld);
dlg = DialogUI.create(getContext(),parent,true,ui.getComponent(),new String[] {getString("change"),getString("cancel")});
dlg.setDefault(0);
dlg.setTitle(getI18n().format("change.format",getString("password")));
dlg.getButton(0).setAction(this);
dlg.getButton(1).setIcon(getIcon("icon.cancel"));
dlg.start();
}
public void actionPerformed(ActionEvent evt) {
try {
char[] oldPassword = showOld ? ui.getOldPassword() : new char[0];
char[] p1= ui.getNewPassword();
char[] p2= ui.getPasswordVerification();
if (!Tools.match(p1,p2))
throw new RaplaException(getString("error.passwords_dont_match"));
getUserModule().changePassword(user , oldPassword, p1);
dlg.close();
} catch (RaplaException ex) {
showException(ex,dlg);
}
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/action/user/PasswordChangeAction.java | Java | gpl3 | 3,969 |
/*--------------------------------------------------------------------------*
| 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.internal.action.user;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import org.rapla.client.ClientService;
import org.rapla.entities.User;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.EditComponent;
import org.rapla.gui.RaplaAction;
import org.rapla.gui.internal.edit.EditDialog;
public class UserAction extends RaplaAction {
Object object;
Component parent;
public final int NEW = 1;
public final int SWITCH_TO_USER = 3;
int type = NEW;
Point point;
public UserAction(RaplaContext sm,Component parent,Point point) {
super( sm);
this.parent = parent;
this.point = point;
}
public UserAction setNew() {
type = NEW;
putValue(NAME, getString("user"));
putValue(SMALL_ICON, getIcon("icon.new"));
update();
return this;
}
public UserAction setSwitchToUser() {
type = SWITCH_TO_USER;
ClientService service = getService( ClientService.class);
if (service.canSwitchBack()) {
putValue(NAME, getString("switch_back"));
} else {
putValue(NAME, getString("switch_to"));
}
return this;
}
public void changeObject(Object object) {
this.object = object;
update();
}
private void update() {
User user = null;
try {
user = getUser();
if (type == NEW) {
setEnabled(isAdmin());
} else if (type == SWITCH_TO_USER) {
ClientService service = getService( ClientService.class);
setEnabled(service.canSwitchBack() ||
(object != null && isAdmin() && !user.equals(object )));
}
} catch (RaplaException ex) {
setEnabled(false);
return;
}
}
public void actionPerformed(ActionEvent evt) {
try {
if (type == SWITCH_TO_USER) {
ClientService service = getService( ClientService.class);
if (service.canSwitchBack()) {
service.switchTo(null);
//putValue(NAME, getString("switch_to"));
} else if ( object != null ){
service.switchTo((User) object);
// putValue(NAME, getString("switch_back"));
}
} else if (type == NEW) {
User newUser = getModification().newUser();
EditComponent<User> ui = getEditController().createUI( newUser);
EditDialog<User> gui = new EditDialog<User>(getContext(),ui);
List<User> singletonList = new ArrayList<User>();
singletonList.add(newUser);
if (gui.start( singletonList ,getString("user"), parent) == 0
&& getUserModule().canChangePassword() )
changePassword(newUser,false);
object = newUser;
}
} catch (RaplaException ex) {
showException(ex, this.parent);
}
}
public void changePassword(User user,boolean showOld) throws RaplaException{
new PasswordChangeAction(getContext(),parent).changePassword( user, showOld);
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/action/user/UserAction.java | Java | gpl3 | 4,319 |
/*--------------------------------------------------------------------------*
| 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.internal.action.user;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.toolkit.RaplaWidget;
public class PasswordChangeUI extends RaplaGUIComponent
implements
RaplaWidget
{
JPanel superPanel = new JPanel();
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
GridLayout gridLayout1 = new GridLayout();
// The Controller for this Dialog
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
JLabel label3 = new JLabel();
JPasswordField tf1 = new JPasswordField(10);
JPasswordField tf2 = new JPasswordField(10);
JPasswordField tf3 = new JPasswordField(10);
public PasswordChangeUI(RaplaContext sm) {
this(sm,true);
}
public PasswordChangeUI(RaplaContext sm,boolean askForOldPassword) {
super( sm);
superPanel.setLayout(new BoxLayout(superPanel, BoxLayout.Y_AXIS));
panel2.add(new JLabel(getString("password_change_info")));
panel.setLayout(gridLayout1);
gridLayout1.setRows(askForOldPassword ? 4 : 3);
gridLayout1.setColumns(2);
gridLayout1.setHgap(10);
gridLayout1.setVgap(10);
if (askForOldPassword) {
panel.add(label1);
panel.add(tf1);
}
panel.add(label2);
panel.add(tf2);
panel.add(label3);
panel.add(tf3);
label1.setText(getString("old_password") + ":");
label2.setText(getString("new_password") + ":");
label3.setText(getString("password_verification") + ":");
final JCheckBox showPassword = new JCheckBox(getString("show_password"));
panel.add( showPassword);
showPassword.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean show = showPassword.isSelected();
tf1.setEchoChar( show ? ((char) 0): '*');
tf2.setEchoChar( show ? ((char) 0): '*');
tf3.setEchoChar( show ? ((char) 0): '*');
}
});
superPanel.add(panel);
superPanel.add(panel2);
}
public JComponent getComponent() {
return superPanel;
}
public char[] getOldPassword() {
return tf1.getPassword();
}
public char[] getNewPassword() {
return tf2.getPassword();
}
public char[] getPasswordVerification() {
return tf3.getPassword();
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/action/user/PasswordChangeUI.java | Java | gpl3 | 3,624 |
<body>
Actions can be reused with menus, popups or buttons.
</body>
| 04900db4-clienttest | src/org/rapla/gui/internal/action/package.html | HTML | gpl3 | 71 |
/*--------------------------------------------------------------------------*
| 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.internal.action;
import java.awt.event.ActionEvent;
import org.rapla.client.ClientService;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaAction;
public class RestartRaplaAction extends RaplaAction{
public RestartRaplaAction(RaplaContext sm)
{
super(sm);
boolean logoutAvailable = getService(ClientService.class).isLogoutAvailable();
String string = getString("restart_client");
if (logoutAvailable)
{
string = getString("logout") +" / " + string;
}
putValue(NAME,string);
putValue(SMALL_ICON,getIcon("icon.restart"));
}
public void actionPerformed(ActionEvent arg0) {
boolean logoutAvailable = getService(ClientService.class).isLogoutAvailable();
if ( logoutAvailable)
{
getService(ClientService.class).logout();
}
else
{
getService(ClientService.class).restart();
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/action/RestartRaplaAction.java | Java | gpl3 | 1,932 |
/*--------------------------------------------------------------------------*
| 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.internal.action;
import java.awt.event.ActionEvent;
import javax.swing.SwingUtilities;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaAction;
import org.rapla.storage.dbrm.RestartServer;
public class RestartServerAction extends RaplaAction {
/**
* @param sm
* @throws RaplaException
*/
public RestartServerAction(RaplaContext sm) throws RaplaException {
super(sm);
putValue(NAME,getString("restart_server"));
putValue(SMALL_ICON,getIcon("icon.restart"));
}
public void actionPerformed(ActionEvent arg0) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
try {
RestartServer service = getService( RestartServer.class);
service.restartServer();
} catch (RaplaException ex) {
getLogger().error("Error restarting ", ex);
}
}
});
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/action/RestartServerAction.java | Java | gpl3 | 1,967 |
/*--------------------------------------------------------------------------*
| 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.internal.action;
import java.awt.Component;
import java.awt.Point;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class DynamicTypeAction extends RaplaObjectAction {
String classificationType;
public DynamicTypeAction(RaplaContext sm,Component parent) {
super(sm,parent);
}
public DynamicTypeAction(RaplaContext sm,Component parent,Point p) {
super(sm,parent,p);
}
public DynamicTypeAction setNewClassificationType(String classificationType) {
this.classificationType = classificationType;
super.setNew( null );
return this;
}
protected void newEntity() throws RaplaException {
DynamicType newDynamicType = getModification().newDynamicType(classificationType);
getEditController().edit(newDynamicType, parent);
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/action/DynamicTypeAction.java | Java | gpl3 | 1,858 |
/*--------------------------------------------------------------------------*
| 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.internal.action;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Reservation;
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.ModificationModule;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaAction;
import org.rapla.gui.internal.edit.DeleteUndo;
import org.rapla.gui.toolkit.DialogUI;
public class RaplaObjectAction extends RaplaAction {
public final static int DELETE = 1;
public final static int COPY = 2;
public final static int PASTE = 3;
public final static int CUT = 4;
public final static int NEW = 5;
public final static int EDIT = 6;
public final static int VIEW = 7;
public final static int DELETE_SELECTION = 8;
public final static int EDIT_SELECTION = 9; // new attribute to define a
// edit selection (several
// editable entities)
protected Component parent;
Point point;
protected int type;
boolean isPerson;
protected Entity<?> object;
Collection<Entity<?>> objectList;
protected RaplaType raplaType;
public RaplaObjectAction(RaplaContext sm) {
this(sm,null);
}
public RaplaObjectAction(RaplaContext sm,Component parent) {
this(sm,parent,null);
}
public RaplaObjectAction(RaplaContext sm,Component parent,Point point) {
super( sm);
this.parent = parent;
this.point = point;
}
public RaplaObjectAction setNew(RaplaType raplaType) {
this.raplaType = raplaType;
this.type = NEW;
putValue(NAME, getString("new"));
putValue(SMALL_ICON, getIcon("icon.new"));
update();
return this;
}
public RaplaObjectAction setDelete(Entity<?> object) {
this.type = DELETE;
putValue(NAME, getString("delete"));
putValue(SMALL_ICON, getIcon("icon.delete"));
changeObject(object);
return this;
}
public RaplaObjectAction setDeleteSelection(Collection<Entity<?>> selection) {
this.type = DELETE_SELECTION;
putValue(NAME, getString("delete_selection"));
putValue(SMALL_ICON, getIcon("icon.delete"));
this.objectList = new ArrayList<Entity<?>>(selection);
update();
return this;
}
public RaplaObjectAction setView(Entity<?> object) {
this.type = VIEW;
putValue(NAME, getString("view"));
putValue(SMALL_ICON, getIcon("icon.help"));
changeObject(object);
return this;
}
public RaplaObjectAction setEdit(Entity<?> object) {
this.type = EDIT;
putValue(NAME, getString("edit"));
putValue(SMALL_ICON, getIcon("icon.edit"));
changeObject(object);
return this;
}
// method for setting a selection as a editable selection
// (cf. setEdit() and setDeleteSelection())
public RaplaObjectAction setEditSelection(Collection<Entity<?>> selection) {
this.type = EDIT_SELECTION;
putValue(NAME, getString("edit"));
putValue(SMALL_ICON, getIcon("icon.edit"));
this.objectList = new ArrayList<Entity<?>>(selection);
update();
return this;
}
public void changeObject(Entity<?> object) {
this.object = object;
if (type == DELETE) {
if (object == null)
putValue(NAME, getString("delete"));
else
putValue(NAME, getI18n().format("delete.format",getName(object)));
}
update();
}
protected void update() {
boolean enabled = true;
if (type == EDIT || type == DELETE) {
enabled = canModify(object);
} else if (type == NEW ) {
enabled = (raplaType != null && raplaType.is(Allocatable.TYPE) && isRegisterer()) || isAdmin();
} else if (type == EDIT_SELECTION || type == DELETE_SELECTION) {
if (objectList != null && objectList.size() > 0 ) {
Iterator<Entity<?>> it = objectList.iterator();
while (it.hasNext()) {
if (!canModify(it.next())){
enabled = false;
break;
}
}
} else {
enabled = false;
}
}
setEnabled(enabled);
}
public void actionPerformed(ActionEvent evt) {
try {
switch (type) {
case DELETE: delete();break;
case DELETE_SELECTION: deleteSelection();break;
case EDIT: edit();break;
// EditSelection() as reaction of actionPerformed (click on the edit
// button)
case EDIT_SELECTION:editSelection();break;
case NEW: newEntity();break;
case VIEW: view();break;
}
} catch (RaplaException ex) {
showException(ex,parent);
} // end of try-catch
}
public void view() throws RaplaException {
getInfoFactory().showInfoDialog(object,parent);
}
protected Entity<? extends Entity<?>> newEntity(RaplaType raplaType) throws RaplaException {
ModificationModule m = getModification();
if ( Reservation.TYPE.is( raplaType ))
{
DynamicType type = guessType();
final Classification newClassification = type.newClassification();
Reservation newReservation = m.newReservation( newClassification );
return newReservation;
}
if ( Allocatable.TYPE.is( raplaType ))
{
DynamicType type = guessType();
final Classification newClassification = type.newClassification();
Allocatable allocatable = m.newAllocatable( newClassification );
return allocatable ;
}
if ( Category.TYPE.is( raplaType ))
return m.newCategory(); //will probably never happen
if ( User.TYPE.is( raplaType ))
return m.newUser();
if ( Period.TYPE.is( raplaType ))
return m.newPeriod();
throw new RaplaException("Can't create Entity for " + raplaType + "!");
}
/** guesses the DynamicType for the new object depending on the selected element.
<li>If the selected element is a DynamicType-Folder the DynamicType will be returned.
<li>If the selected element has a Classification the appropriatie DynamicType will be returned.
<li>else the first matching DynamicType for the passed classificationType will be returned.
<li>null if none of the above criterias matched.
*/
public DynamicType guessType() throws RaplaException {
DynamicType[] types = guessTypes();
if ( types.length > 0)
{
return types[0];
}
else
{
return null;
}
}
public DynamicType[] guessTypes() throws RaplaException {
DynamicType dynamicType = null;
getLogger().debug("Guessing DynamicType from " + object);
if (object instanceof DynamicType)
dynamicType = (DynamicType) object;
if (object instanceof Classifiable) {
Classification classification= ((Classifiable) object).getClassification();
dynamicType = classification.getType();
}
if (dynamicType != null)
{
return new DynamicType[] {dynamicType};
}
String classificationType = null;
if ( Reservation.TYPE.is( raplaType )) {
classificationType = DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION;
} else if ( Allocatable.TYPE.is( raplaType )) {
if ( isPerson ) {
classificationType = DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON;
} else {
classificationType = DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE;
}
}
DynamicType[] dynamicTypes = getQuery().getDynamicTypes( classificationType );
return dynamicTypes;
}
protected void newEntity() throws RaplaException {
if ( Category.TYPE.is( raplaType )) {
Category category = (Category)object;
getEditController().editNew(category, parent );
} else {
Entity<? extends Entity> obj = newEntity(raplaType);
getEditController().edit(obj, parent);
}
}
protected void edit() throws RaplaException {
getEditController().edit(object, parent);
}
protected void delete() throws RaplaException {
if (object == null)
return;
Entity<?>[] objects = new Entity[] { object};
DialogUI dlg = getInfoFactory().createDeleteDialog( objects, parent);
dlg.start();
if (dlg.getSelectedIndex() != 0)
return;
List<Entity<?>> singletonList = Arrays.asList( objects);
delete(singletonList);
}
protected void deleteSelection() throws RaplaException
{
if (objectList == null || objectList.size() == 0)
return;
DialogUI dlg = getInfoFactory().createDeleteDialog(objectList.toArray(), parent);
dlg.start();
if (dlg.getSelectedIndex() != 0)
return;
delete(objectList);
}
protected void delete(Collection<Entity<?>> objects) throws RaplaException
{
Collection<Entity<?>> entities = new ArrayList<Entity<?>>();
boolean undoable = true;
for ( Entity<?> obj: objects)
{
entities.add( obj);
RaplaType<?> raplaType = obj.getRaplaType();
if ( raplaType == User.TYPE || raplaType == DynamicType.TYPE)
{
undoable = false;
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
DeleteUndo<? extends Entity<?>> deleteCommand = new DeleteUndo(getContext(), entities);
if ( undoable)
{
getModification().getCommandHistory().storeAndExecute(deleteCommand);
}
else
{
deleteCommand.execute();
}
}
// action which is executed by clicking on the edit button (after
// actionPerformed)
// chances the selection list in an array and commits it on EditController
protected void editSelection() throws RaplaException {
if (objectList == null || objectList.size() == 0)
return;
Entity[] array = objectList.toArray(Entity.ENTITY_ARRAY);
getEditController().edit(array, parent);
}
public void setPerson(boolean b) {
isPerson = b;
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/action/RaplaObjectAction.java | Java | gpl3 | 11,906 |
/*--------------------------------------------------------------------------*
| 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.internal.action;
import java.awt.event.ActionEvent;
import javax.swing.JMenuItem;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.gui.RaplaAction;
import org.rapla.gui.toolkit.RaplaMenuItem;
public class SaveableToggleAction extends RaplaAction {
TypedComponentRole<Boolean> configEntry;
String name;
public SaveableToggleAction(RaplaContext context,String name,TypedComponentRole<Boolean> configEntry)
{
super( context );
this.name = name;
putValue( NAME, getString( name));
this.configEntry = configEntry;
//putValue(SMALL_ICON,getIcon("icon.unchecked"));
}
public RaplaMenuItem createMenuItem() throws RaplaException
{
RaplaMenuItem menu = new RaplaMenuItem(name);
menu.setAction( this);
final User user = getUser();
final Preferences preferences = getQuery().getPreferences( user );
boolean selected = preferences.getEntryAsBoolean( configEntry , true);
if(selected) {
menu.setSelected(true);
menu.setIcon(getIcon("icon.checked"));
}
else {
menu.setSelected(false);
menu.setIcon(getIcon("icon.unchecked"));
}
return menu;
}
public void actionPerformed(ActionEvent evt) {
toggleCheckbox((JMenuItem)evt.getSource());
}
public void toggleCheckbox(JMenuItem toolTip) {
boolean newSelected = !toolTip.isSelected();
if ( isModifyPreferencesAllowed())
{
try {
Preferences prefs = this.newEditablePreferences();
prefs.putEntry( configEntry, newSelected);
getModification().store( prefs);
} catch (Exception ex) {
showException( ex, null );
return;
}
}
toolTip.setSelected(newSelected);
javax.swing.ToolTipManager.sharedInstance().setEnabled(newSelected);
toolTip.setIcon(newSelected ? getIcon("icon.checked"):getIcon("icon.unchecked"));
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/action/SaveableToggleAction.java | Java | gpl3 | 3,159 |
/*--------------------------------------------------------------------------*
| 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.internal;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Window;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import org.rapla.RaplaMainContainer;
import org.rapla.client.ClientService;
import org.rapla.entities.User;
import org.rapla.facade.CalendarSelectionModel;
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.common.InternMenus;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.RaplaFrame;
public class MainFrame extends RaplaGUIComponent
implements
ModificationListener
{
RaplaMenuBar menuBar;
RaplaFrame frame = null;
Listener listener = new Listener();
CalendarEditor cal;
JLabel statusBar = new JLabel("");
public MainFrame(RaplaContext sm) throws RaplaException {
super(sm);
menuBar = new RaplaMenuBar(getContext());
frame = getService( ClientService.MAIN_COMPONENT );
String title = getQuery().getSystemPreferences().getEntryAsString(RaplaMainContainer.TITLE, getString("rapla.title"));
// CKO TODO Title should be set in config along with the facade used
frame.setTitle(title );
CalendarSelectionModel model = getService( CalendarSelectionModel.class);
cal = new CalendarEditor(sm,model);
getUpdateModule().addModificationListener(this);
JMenuBar menuBar = getService( InternMenus.MENU_BAR);
menuBar.add(Box.createHorizontalGlue());
menuBar.add(statusBar);
menuBar.add(Box.createHorizontalStrut(5));
frame.setJMenuBar( menuBar );
getContentPane().setLayout( new BorderLayout() );
// getContentPane().add ( statusBar, BorderLayout.SOUTH);
getContentPane().add( cal.getComponent() , BorderLayout.CENTER );
}
public void show() {
getLogger().debug("Creating Main-Frame");
createFrame();
//dataChanged(null);
setStatus();
cal.start();
frame.setIconImage(getI18n().getIcon("icon.rapla_small").getImage());
frame.setVisible(true);
getFrameList().setMainWindow(frame);
}
private JPanel getContentPane() {
return (JPanel) frame.getContentPane();
}
private void createFrame() {
Dimension dimension = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(new Dimension(
Math.min(dimension.width,1200)
,Math.min(dimension.height-20,900)
)
);
frame.addVetoableChangeListener(listener);
//statusBar.setBorder( BorderFactory.createEtchedBorder());
}
class Listener implements VetoableChangeListener {
public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
if (shouldExit())
close();
else
throw new PropertyVetoException("Don't close",evt);
}
}
public Window getFrame() {
return frame;
}
public JComponent getComponent() {
return (JComponent) frame.getContentPane();
}
public void dataChanged(ModificationEvent e) throws RaplaException {
cal.dataChanged( e );
new StatusFader(statusBar).updateStatus();
}
private void setStatus() {
statusBar.setMaximumSize( new Dimension(400,20));
final StatusFader runnable = new StatusFader(statusBar);
final Thread fadeThread = new Thread(runnable);
fadeThread.setDaemon( true);
fadeThread.start();
}
class StatusFader implements Runnable{
JLabel label;
StatusFader(JLabel label)
{
this.label=label;
}
public void run() {
try {
{
User user = getUser();
final boolean admin = user.isAdmin();
String name = user.getName();
if ( name == null || name.length() == 0 )
{
name = user.getUsername();
}
String message = getI18n().format("rapla.welcome",name);
if ( admin)
{
message = message + " " + getString("admin.login");
}
statusBar.setText(message);
fadeIn( statusBar );
}
Thread.sleep(2000);
{
fadeOut( statusBar);
if (getUserModule().isSessionActive())
{
updateStatus();
}
fadeIn( statusBar );
}
} catch (InterruptedException ex) {
//Logger.getLogger(Fader.class.getName()).log(Level.SEVERE, null, ex);
} catch (RaplaException e) {
}
}
public void updateStatus() throws RaplaException {
User user = getUser();
final boolean admin = user.isAdmin();
String message = getString("user") + " "+ user.toString();
String templateName = getModification().getTemplateName();
if ( templateName != null)
{
message = getString("edit-templates") + " [" + templateName + "] " + message;
}
statusBar.setText( message);
final Font boldFont = statusBar.getFont().deriveFont(Font.BOLD);
statusBar.setFont( boldFont);
if ( admin)
{
statusBar.setForeground( new Color(220,30,30));
}
else
{
statusBar.setForeground( new Color(30,30,30) );
}
}
private void fadeIn(JLabel label) throws InterruptedException {
int alpha=0;
Color c = label.getForeground();
while(alpha<=230){
alpha+=25;
final Color color = new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha);
label.setForeground(color);
label.repaint();
Thread.sleep(200);
}
}
private void fadeOut(JLabel label) throws InterruptedException {
int alpha=250;
Color c = label.getForeground();
while(alpha>0){
alpha-=25;
final Color color = new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha);
label.setForeground(color);
label.repaint();
Thread.sleep(200);
}
}
}
protected boolean shouldExit() {
try {
DialogUI dlg = DialogUI.create(getContext()
,frame.getRootPane()
,true
,getString("exit.title")
,getString("exit.question")
,new String[] {
getString("exit.ok")
,getString("exit.abort")
}
);
dlg.setIcon(getIcon("icon.question"));
//dlg.getButton(0).setIcon(getIcon("icon.confirm"));
dlg.getButton(0).setIcon(getIcon("icon.abort"));
dlg.setDefault(1);
dlg.start();
return (dlg.getSelectedIndex() == 0);
} catch (RaplaException e) {
getLogger().error( e.getMessage(), e);
return true;
}
}
public void close() {
getUpdateModule().removeModificationListener(this);
frame.close();
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/MainFrame.java | Java | gpl3 | 9,144 |
/*--------------------------------------------------------------------------*
| 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.internal;
import java.util.Locale;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.rapla.RaplaMainContainer;
import org.rapla.components.calendar.RaplaNumber;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.configuration.Preferences;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.UpdateModule;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.plugin.export2ical.ICalTimezones;
public class RaplaStartOption extends RaplaGUIComponent implements OptionPanel {
JPanel panel = new JPanel();
JTextField calendarName;
Preferences preferences;
private JComboBox cboTimezone;
ICalTimezones timezoneService;
private JCheckBox ownReservations;
RaplaNumber seconds = new RaplaNumber(new Double(10),new Double(10),null, false);
public RaplaStartOption(RaplaContext context, ICalTimezones timezoneService) throws RaplaException {
super( context );
double pre = TableLayout.PREFERRED;
panel.setLayout( new TableLayout(new double[][] {{pre, 5,pre, 5, pre}, {pre,5,pre, 5 , pre, 5, pre}}));
this.timezoneService = timezoneService;
calendarName = new JTextField();
addCopyPaste( calendarName);
calendarName.setColumns(20);
panel.add( new JLabel(getString("custom_applicationame")),"0,0" );
panel.add( calendarName,"2,0");
calendarName.setEnabled(true);
String[] timeZoneIDs = getTimeZonesFromResource();
panel.add(new JLabel(getString("timezone")), "0,2");
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(timeZoneIDs);
cboTimezone = jComboBox;
panel.add(cboTimezone, "2,2");
cboTimezone.setEditable(false);
panel.add(new JLabel( getString("defaultselection") + " '" + getString("only_own_reservations") +"'"), "0,4");
ownReservations = new JCheckBox();
panel.add(ownReservations, "2,4");
seconds.getNumberField().setBlockStepSize( 60);
seconds.getNumberField().setStepSize( 10);
panel.add( new JLabel(getString("seconds")),"4,6" );
panel.add( seconds,"2,6");
panel.add( new JLabel(getString("connection") + ": " + getI18n().format("interval.format", "","")),"0,6" );
addCopyPaste( seconds.getNumberField());
}
public JComponent getComponent() {
return panel;
}
public String getName(Locale locale) {
return getString("options");
}
public void setPreferences( Preferences preferences) {
this.preferences = preferences;
}
public void show() throws RaplaException {
String name = preferences.getEntryAsString( RaplaMainContainer.TITLE,"");
calendarName.setText(name);
try {
String timezoneId = preferences.getEntryAsString( RaplaMainContainer.TIMEZONE,timezoneService.getDefaultTimezone().get());
cboTimezone.setSelectedItem(timezoneId);
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
boolean selected= preferences.getEntryAsBoolean( CalendarModel.ONLY_MY_EVENTS_DEFAULT, true);
ownReservations.setSelected( selected);
int delay = preferences.getEntryAsInteger( UpdateModule.REFRESH_INTERVAL_ENTRY, UpdateModule.REFRESH_INTERVAL_DEFAULT);
seconds.setNumber( new Long(delay / 1000));
seconds.setEnabled(getClientFacade().isClientForServer());
}
public void commit() {
String title = calendarName.getText();
if ( title.trim().length() > 0)
{
preferences.putEntry( RaplaMainContainer.TITLE,title );
}
else
{
preferences.putEntry( RaplaMainContainer.TITLE, (String)null);
}
String timeZoneId = String.valueOf(cboTimezone.getSelectedItem());
preferences.putEntry( RaplaMainContainer.TIMEZONE, timeZoneId);
boolean selected= ownReservations.isSelected();
preferences.putEntry( CalendarModel.ONLY_MY_EVENTS_DEFAULT, selected);
int delay = seconds.getNumber().intValue() * 1000;
preferences.putEntry( UpdateModule.REFRESH_INTERVAL_ENTRY, delay );
}
/**
* Gets all the iCal4J supported TimeZones from the Resource File They are
* generated by trial-and error in the BUILD event.
*
* @return String[] of the TimeZones for direct use in the ComboBox
* @throws RaplaException
*/
private String[] getTimeZonesFromResource() throws RaplaException
{
try
{
String zoneString = timezoneService.getICalTimezones().get();
return zoneString.split(";");
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/RaplaStartOption.java | Java | gpl3 | 5,932 |
/*--------------------------------------------------------------------------*
| 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.internal;
import java.awt.Component;
import java.awt.FlowLayout;
import java.util.Calendar;
import java.util.Locale;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import org.rapla.components.calendar.DateChangeEvent;
import org.rapla.components.calendar.DateChangeListener;
import org.rapla.components.calendar.RaplaNumber;
import org.rapla.components.calendar.RaplaTime;
import org.rapla.components.calendarview.WeekdayMapper;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.facade.CalendarOptions;
import org.rapla.facade.internal.CalendarOptionsImpl;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.RaplaGUIComponent;
public class CalendarOption extends RaplaGUIComponent implements OptionPanel, DateChangeListener
{
JPanel panel = new JPanel();
JCheckBox showExceptionsField = new JCheckBox();
@SuppressWarnings("unchecked")
JComboBox colorBlocks = new JComboBox( new String[] {
CalendarOptionsImpl.COLOR_NONE
,CalendarOptionsImpl.COLOR_RESOURCES
, CalendarOptionsImpl.COLOR_EVENTS
, CalendarOptionsImpl.COLOR_EVENTS_AND_RESOURCES
}
);
RaplaNumber rowsPerHourField = new RaplaNumber(new Double(1),new Double(1),new Double(12), false);
Preferences preferences;
CalendarOptions options;
RaplaTime worktimeStart;
RaplaTime worktimeEnd;
JPanel excludeDaysPanel = new JPanel();
JCheckBox[] box = new JCheckBox[7];
WeekdayMapper mapper;
RaplaNumber nTimesField = new RaplaNumber(new Double(1),new Double(1),new Double(365), false);
@SuppressWarnings({ "unchecked" })
JComboBox nonFilteredEvents = new JComboBox( new String[]
{
CalendarOptionsImpl.NON_FILTERED_EVENTS_TRANSPARENT,
CalendarOptionsImpl.NON_FILTERED_EVENTS_HIDDEN
}
);
JLabel worktimeEndError;
@SuppressWarnings({ "unchecked" })
JComboBox minBlockWidth = new JComboBox( new Integer[] {0,50,100,200});
JComboBox firstDayOfWeek;
RaplaNumber daysInWeekview;
public CalendarOption(RaplaContext sm) {
super( sm);
daysInWeekview = new RaplaNumber(7, 3, 35, false);
mapper = new WeekdayMapper(getLocale());
worktimeStart = createRaplaTime();
worktimeStart.setRowsPerHour( 1 );
worktimeEnd = createRaplaTime();
worktimeEnd.setRowsPerHour( 1 );
double pre = TableLayout.PREFERRED;
double fill = TableLayout.FILL;
// rows = 8 columns = 4
panel.setLayout( new TableLayout(new double[][] {{pre, 5, pre, 5 , pre, 5, pre}, {pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,fill}}));
panel.add( new JLabel(getString("rows_per_hour")),"0,0" );
panel.add( rowsPerHourField,"2,0");
panel.add( new JLabel(getString("start_time")),"0,2" );
JPanel worktimeStartPanel = new JPanel();
worktimeStartPanel.add( worktimeStart);
panel.add( worktimeStartPanel, "2,2,l");
panel.add( new JLabel(getString("end_time")),"0,4" );
worktimeStart.addDateChangeListener(this);
JPanel worktimeEndPanel = new JPanel();
panel.add( worktimeEndPanel,"2,4,l");
worktimeEndPanel.add( worktimeEnd);
worktimeEndError = new JLabel(getString("appointment.next_day"));
worktimeEndPanel.add( worktimeEndError);
worktimeEnd.addDateChangeListener(this);
panel.add( new JLabel(getString("color")),"0,6" );
panel.add( colorBlocks,"2,6");
showExceptionsField.setText("");
panel.add( new JLabel(getString("display_exceptions")),"0,8");
panel.add( showExceptionsField,"2,8");
panel.add( new JLabel(getString("events_not_matched_by_filter")),"0,10");
panel.add( nonFilteredEvents,"2,10");
setRenderer();
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(mapper.getNames());
firstDayOfWeek = jComboBox;
panel.add( new JLabel(getString("day1week")),"0,12");
panel.add( firstDayOfWeek,"2,12");
panel.add( new JLabel(getString("daysInWeekview")),"0,14");
panel.add( daysInWeekview,"2,14");
panel.add( new JLabel(getString("minimumBlockWidth")),"0,16");
JPanel minWidthContainer = new JPanel();
minWidthContainer.setLayout( new FlowLayout(FlowLayout.LEFT));
minWidthContainer.add(minBlockWidth);
minWidthContainer.add(new JLabel("%"));
panel.add( minWidthContainer,"2,16");
panel.add( new JLabel(getString("exclude_days")),"0,22,l,t");
panel.add( excludeDaysPanel,"2,22");
excludeDaysPanel.setLayout( new BoxLayout( excludeDaysPanel,BoxLayout.Y_AXIS));
for ( int i=0;i<box.length;i++) {
int weekday = mapper.dayForIndex( i);
box[i] = new JCheckBox(mapper.getName(weekday));
excludeDaysPanel.add( box[i]);
}
}
@SuppressWarnings("unchecked")
private void setRenderer() {
ListRenderer listRenderer = new ListRenderer();
nonFilteredEvents.setRenderer( listRenderer );
colorBlocks.setRenderer( listRenderer );
}
public JComponent getComponent() {
return panel;
}
public String getName(Locale locale) {
return getString("calendar");
}
public void setPreferences( Preferences preferences) {
this.preferences = preferences;
}
public void show() throws RaplaException {
// get the options
RaplaConfiguration config = preferences.getEntry( CalendarOptionsImpl.CALENDAR_OPTIONS);
if ( config != null) {
options = new CalendarOptionsImpl( config );
} else {
options = getCalendarOptions();
}
if ( options.isEventColoring() && options.isResourceColoring())
{
colorBlocks.setSelectedItem( CalendarOptionsImpl.COLOR_EVENTS_AND_RESOURCES);
}
else if ( options.isEventColoring() )
{
colorBlocks.setSelectedItem( CalendarOptionsImpl.COLOR_EVENTS);
}
else if ( options.isResourceColoring())
{
colorBlocks.setSelectedItem( CalendarOptionsImpl.COLOR_RESOURCES);
}
else
{
colorBlocks.setSelectedItem( CalendarOptionsImpl.COLOR_NONE);
}
showExceptionsField.setSelected( options.isExceptionsVisible());
rowsPerHourField.setNumber( new Long(options.getRowsPerHour()));
Calendar calendar = getRaplaLocale().createCalendar();
int workTime = options.getWorktimeStartMinutes();
calendar.set( Calendar.HOUR_OF_DAY, workTime / 60);
calendar.set( Calendar.MINUTE, workTime % 60);
worktimeStart.setTime( calendar.getTime() );
workTime = options.getWorktimeEndMinutes();
calendar.set( Calendar.HOUR_OF_DAY, workTime / 60);
calendar.set( Calendar.MINUTE, workTime % 60);
worktimeEnd.setTime( calendar.getTime() );
for ( int i=0;i<box.length;i++) {
int weekday = mapper.dayForIndex( i);
box[i].setSelected( options.getExcludeDays().contains( new Integer( weekday)));
}
int firstDayOfWeek2 = options.getFirstDayOfWeek();
firstDayOfWeek.setSelectedIndex( mapper.indexForDay( firstDayOfWeek2));
daysInWeekview.setNumber( options.getDaysInWeekview());
minBlockWidth.setSelectedItem( new Integer(options.getMinBlockWidth()));
nonFilteredEvents.setSelectedItem( options.isNonFilteredEventsVisible() ? CalendarOptionsImpl.NON_FILTERED_EVENTS_TRANSPARENT : CalendarOptionsImpl.NON_FILTERED_EVENTS_HIDDEN);
}
public void commit() {
// Save the options
RaplaConfiguration calendarOptions = new RaplaConfiguration("calendar-options");
DefaultConfiguration worktime = new DefaultConfiguration(CalendarOptionsImpl.WORKTIME);
DefaultConfiguration excludeDays = new DefaultConfiguration(CalendarOptionsImpl.EXCLUDE_DAYS);
DefaultConfiguration rowsPerHour = new DefaultConfiguration(CalendarOptionsImpl.ROWS_PER_HOUR);
DefaultConfiguration exceptionsVisible = new DefaultConfiguration(CalendarOptionsImpl.EXCEPTIONS_VISIBLE);
DefaultConfiguration daysInWeekview = new DefaultConfiguration(CalendarOptionsImpl.DAYS_IN_WEEKVIEW);
DefaultConfiguration firstDayOfWeek = new DefaultConfiguration(CalendarOptionsImpl.FIRST_DAY_OF_WEEK);
DefaultConfiguration minBlockWidth = new DefaultConfiguration(CalendarOptionsImpl.MIN_BLOCK_WIDTH);
daysInWeekview.setValue( this.daysInWeekview.getNumber().intValue());
int selectedIndex = this.firstDayOfWeek.getSelectedIndex();
int weekday = mapper.dayForIndex(selectedIndex);
firstDayOfWeek.setValue( weekday);
DefaultConfiguration colorBlocks = new DefaultConfiguration(CalendarOptionsImpl.COLOR_BLOCKS);
String colorValue = (String) this.colorBlocks.getSelectedItem();
if ( colorValue != null )
{
colorBlocks.setValue( colorValue );
}
calendarOptions.addChild( colorBlocks );
Calendar calendar = getRaplaLocale().createCalendar();
calendar.setTime( worktimeStart.getTime());
int worktimeStartHour = calendar.get(Calendar.HOUR_OF_DAY) ;
int worktimeStartMinute = calendar.get(Calendar.MINUTE);
calendar.setTime( worktimeEnd.getTime());
int worktimeEndHour = calendar.get(Calendar.HOUR_OF_DAY) ;
int worktimeEndMinute = calendar.get(Calendar.MINUTE);
if ( worktimeStartMinute > 0 || worktimeEndMinute > 0)
{
worktime.setValue( worktimeStartHour + ":" + worktimeStartMinute + "-" + worktimeEndHour + ":" + worktimeEndMinute );
}
else
{
worktime.setValue( worktimeStartHour + "-" + worktimeEndHour );
}
calendarOptions.addChild( worktime);
exceptionsVisible.setValue( showExceptionsField.isSelected() );
calendarOptions.addChild( exceptionsVisible);
rowsPerHour.setValue( rowsPerHourField.getNumber().intValue());
StringBuffer days = new StringBuffer();
for ( int i=0;i<box.length;i++) {
if (box[i].isSelected()) {
if ( days.length() > 0)
days.append(",");
days.append( mapper.dayForIndex( i ));
}
}
calendarOptions.addChild( rowsPerHour);
excludeDays.setValue( days.toString());
calendarOptions.addChild( excludeDays);
calendarOptions.addChild(daysInWeekview);
calendarOptions.addChild(firstDayOfWeek);
Object selectedItem = this.minBlockWidth.getSelectedItem();
if ( selectedItem != null)
{
minBlockWidth.setValue( (Integer) selectedItem);
calendarOptions.addChild(minBlockWidth);
}
DefaultConfiguration nonFilteredEventsConfig = new DefaultConfiguration(CalendarOptionsImpl.NON_FILTERED_EVENTS);
nonFilteredEventsConfig.setValue( nonFilteredEvents.getSelectedItem().toString());
calendarOptions.addChild( nonFilteredEventsConfig);
preferences.putEntry( CalendarOptionsImpl.CALENDAR_OPTIONS, calendarOptions);
}
public void dateChanged(DateChangeEvent evt) {
Calendar calendar = getRaplaLocale().createCalendar();
calendar.setTime( worktimeStart.getTime());
int worktimeS = calendar.get(Calendar.HOUR_OF_DAY)*60 + calendar.get(Calendar.MINUTE);
calendar.setTime( worktimeEnd.getTime());
int worktimeE = calendar.get(Calendar.HOUR_OF_DAY)*60 + calendar.get(Calendar.MINUTE);
worktimeE = (worktimeE == 0)?24*60:worktimeE;
boolean overnight = worktimeS >= worktimeE|| worktimeE == 24*60;
worktimeEndError.setVisible( overnight);
}
private class ListRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(
//@SuppressWarnings("rawtypes")
JList list
,Object value, int index, boolean isSelected, boolean cellHasFocus) {
if ( value != null) {
setText(getString( value.toString()));
}
return this;
}
}
} | 04900db4-clienttest | src/org/rapla/gui/internal/CalendarOption.java | Java | gpl3 | 13,825 |
/*--------------------------------------------------------------------------*
| 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.gui.internal.common;
import java.awt.BorderLayout;
import java.awt.Color;
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.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.calendar.RaplaArrowButton;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ModificationEvent;
import org.rapla.framework.Disposable;
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;
import org.rapla.gui.internal.CalendarEditor;
import org.rapla.gui.internal.FilterEditButton;
import org.rapla.gui.internal.edit.ClassifiableFilterEdit;
import org.rapla.gui.toolkit.IdentifiableMenuEntry;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaMenuItem;
import org.rapla.gui.toolkit.RaplaWidget;
public class MultiCalendarView extends RaplaGUIComponent
implements
RaplaWidget, Disposable, ChangeListener
{
private final JPanel page = new JPanel();
private final JPanel header = new JPanel();
Map<String,RaplaMenuItem> viewMenuItems = new HashMap<String,RaplaMenuItem>();
JComboBox viewChooser;
List<ChangeListener> listeners = new ArrayList<ChangeListener>();
// Default view, when no plugin defined
String ERROR_NO_VIEW_DEFINED = "No views enabled. Please add a plugin in the menu admin/settings/plugins";
private SwingCalendarView defaultView = new SwingCalendarView() {
JLabel noViewDefined = new JLabel(ERROR_NO_VIEW_DEFINED);
JPanel test =new JPanel();
{
test.add( noViewDefined);
}
public JComponent getDateSelection()
{
return null;
}
public void scrollToStart()
{
}
public JComponent getComponent()
{
return test;
}
public void update( ) throws RaplaException
{
}
};
private SwingCalendarView currentView = defaultView;
String currentViewId;
private final CalendarSelectionModel model;
final Collection<SwingViewFactory> factoryList;
/** renderer for weekdays in month-view */
boolean editable = true;
boolean listenersEnabled = true;
FilterEditButton filter;
CalendarEditor calendarEditor;
public MultiCalendarView(RaplaContext context,CalendarSelectionModel model, CalendarEditor calendarEditor) throws RaplaException {
this( context, model, true);
this.calendarEditor = calendarEditor;
}
public MultiCalendarView(RaplaContext context,CalendarSelectionModel model, boolean editable) throws RaplaException {
super( context);
this.editable = editable;
factoryList = getContainer().lookupServicesFor(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION);
this.model = model;
String[] ids = getIds();
{
SwingViewFactory factory = findFactory( model.getViewId());
if ( factory == null)
{
if ( ids.length != 0 ) {
String firstId = ids[0];
model.setViewId( firstId );
factory = findFactory( firstId );
}
}
}
RaplaMenu view = getService( InternMenus.VIEW_MENU_ROLE);
if ( !view.hasId( "views") )
{
addMenu( model, ids, view );
}
addTypeChooser( ids );
header.setLayout(new BorderLayout());
header.add( viewChooser, BorderLayout.CENTER);
filter =new FilterEditButton(context,model, this, false);
final JPanel filterContainer = new JPanel();
filterContainer.setLayout( new BorderLayout());
filterContainer.add(filter.getButton(), BorderLayout.WEST);
header.add( filterContainer, BorderLayout.SOUTH);
page.setBackground( Color.white );
page.setLayout(new TableLayout( new double[][]{
{TableLayout.PREFERRED, TableLayout.FILL}
,{TableLayout.PREFERRED, TableLayout.FILL}}));
update(null);
}
public void dispose() {
}
@SuppressWarnings("unchecked")
private void addTypeChooser( String[] ids )
{
JComboBox jComboBox = new JComboBox( ids);
viewChooser = jComboBox;
viewChooser.setVisible( viewChooser.getModel().getSize() > 0);
viewChooser.setMaximumRowCount(ids.length);
viewChooser.setSelectedItem( getModel().getViewId() );
viewChooser.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if ( !listenersEnabled )
return;
String viewId = (String) ((JComboBox)evt.getSource()).getSelectedItem();
try {
selectView( viewId );
} catch (RaplaException ex) {
showException(ex, page);
}
}
}
);
viewChooser.setRenderer( new DefaultListCellRenderer() {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(JList arg0, Object selectedItem, int index, boolean arg3, boolean arg4) {
super.getListCellRendererComponent( arg0, selectedItem, index, arg3, arg4);
if ( selectedItem == null) {
setIcon( null );
} else {
SwingViewFactory factory = findFactory( (String)selectedItem);
setText( factory.getName() );
setIcon( factory.getIcon());
}
return this;
}
});
}
public void addValueChangeListener(ChangeListener changeListener) {
listeners .add( changeListener);
}
public void removeValueChangeListener(ChangeListener changeListener) {
listeners .remove( changeListener);
}
public RaplaArrowButton getFilterButton()
{
return filter.getButton();
}
public void stateChanged(ChangeEvent e) {
try {
ClassifiableFilterEdit filterUI = filter.getFilterUI();
if ( filterUI != null)
{
final ClassificationFilter[] filters = filterUI.getFilters();
model.setReservationFilter( filters );
update(null);
}
} catch (Exception ex) {
showException(ex, getComponent());
}
}
private void addMenu( CalendarSelectionModel model, String[] ids, RaplaMenu view )
{
RaplaMenu viewMenu = new RaplaMenu("views");
viewMenu.setText(getString("show_as"));
view.insertBeforeId( viewMenu, "show_tips");
ButtonGroup group = new ButtonGroup();
for (int i=0;i<ids.length;i++)
{
String id = ids[i];
RaplaMenuItem viewItem = new RaplaMenuItem( id);
if ( id.equals( model.getViewId()))
{
viewItem.setIcon( getIcon("icon.radio"));
}
else
{
viewItem.setIcon( getIcon("icon.empty"));
}
group.add( viewItem );
SwingViewFactory factory = findFactory( id );
viewItem.setText( factory.getName() );
viewMenu.add( viewItem );
viewItem.setSelected( id.equals( getModel().getViewId()));
viewMenuItems.put( id, viewItem );
viewItem.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if ( !listenersEnabled )
return;
String viewId = ((IdentifiableMenuEntry)evt.getSource()).getId();
try {
selectView( viewId );
} catch (RaplaException ex) {
showException(ex, page);
}
}
});
}
}
private SwingViewFactory findFactory(String id) {
for (Iterator<SwingViewFactory> it = factoryList.iterator();it.hasNext();) {
SwingViewFactory factory = it.next();
if ( factory.getViewId().equals( id ) ) {
return factory;
}
}
return null;
}
private void selectView(String viewId) throws RaplaException {
listenersEnabled = false;
try {
getModel().setViewId( viewId );
update(null);
getSelectedCalendar().scrollToStart();
if ( viewMenuItems.size() > 0) {
for ( Iterator<RaplaMenuItem> it = viewMenuItems.values().iterator();it.hasNext();)
{
RaplaMenuItem item = it.next();
item.setIcon( getIcon("icon.empty"));
}
RaplaMenuItem item = viewMenuItems.get( viewId );
item.setIcon( getIcon("icon.radio"));
}
for(ChangeListener listener:listeners)
{
listener.stateChanged( new ChangeEvent( this));
}
viewChooser.setSelectedItem( viewId );
} finally {
listenersEnabled = true;
}
}
private String[] getIds() {
List<SwingViewFactory> sortedList = new ArrayList<SwingViewFactory>(factoryList);
Collections.sort( sortedList, new Comparator<SwingViewFactory>() {
public int compare( SwingViewFactory arg0, SwingViewFactory arg1 )
{
SwingViewFactory f1 = arg0;
SwingViewFactory f2 = arg1;
return f1.getMenuSortKey().compareTo( f2.getMenuSortKey() );
}
});
List<String> list = new ArrayList<String>();
for (Iterator<SwingViewFactory> it = sortedList.iterator();it.hasNext();) {
SwingViewFactory factory = it.next();
list.add(factory.getViewId());
}
return list.toArray( RaplaObject.EMPTY_STRING_ARRAY);
}
public CalendarSelectionModel getModel() {
return model;
}
public void update(ModificationEvent evt) throws RaplaException {
try
{
// don't show filter button in template mode
filter.getButton().setVisible( getModification().getTemplateName() == null);
listenersEnabled = false;
String viewId = model.getViewId();
SwingViewFactory factory = findFactory( viewId );
if ( factory == null )
{
getLogger().error("View with id " + viewId + " not found. Selecting first view.");
if( factoryList.size() == 0)
{
getLogger().error(ERROR_NO_VIEW_DEFINED);
viewId =null;
}
else
{
factory = factoryList.iterator().next();
viewId = factory.getViewId();
}
}
if ( factory != null)
{
viewChooser.setSelectedItem( viewId );
}
else
{
viewId = "ERROR_VIEW";
}
if ( currentViewId == null || !currentViewId.equals( viewId) ) {
if ( factory != null)
{
currentView = factory.createSwingView( getContext(), model, editable);
currentViewId = viewId; }
else
{
currentView = defaultView;
currentViewId = "ERROR_VIEW";
}
page.removeAll();
page.add( header, "0,0,f,f");
JComponent dateSelection = currentView.getDateSelection();
if ( dateSelection != null)
page.add( dateSelection, "1,0,f,f" );
JComponent component = currentView.getComponent();
page.add( component, "0,1,1,1,f,f" );
component.setBorder( BorderFactory.createEtchedBorder());
page.setVisible(false);
page.invalidate();
page.setVisible( true);
} else {
boolean update = true;
if ( currentView instanceof VisibleTimeInterval)
{
TimeInterval visibleTimeInterval = ((VisibleTimeInterval) currentView).getVisibleTimeInterval();
if ( evt != null && !evt.isModified() && visibleTimeInterval != null)
{
TimeInterval invalidateInterval = evt.getInvalidateInterval();
if ( invalidateInterval != null && !invalidateInterval.overlaps( visibleTimeInterval))
{
update = false;
}
}
}
if ( update )
{
currentView.update( );
}
}
if ( calendarEditor != null)
{
calendarEditor.updateOwnReservationsSelected();
}
}
finally
{
listenersEnabled = true;
}
}
public SwingCalendarView getSelectedCalendar() {
return currentView;
}
public JComponent getComponent() {
return page;
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/common/MultiCalendarView.java | Java | gpl3 | 14,977 |
/*--------------------------------------------------------------------------*
| 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.internal.common;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentStartComparator;
import org.rapla.entities.domain.Reservation;
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;
public class RaplaClipboard extends RaplaGUIComponent implements ModificationListener
{
private Appointment appointment;
private Collection<Reservation> reservations = Collections.emptyList();
private boolean wholeReservation;
private Allocatable[] restrictedAllocatables;
private Collection<Allocatable> contextAllocatables = Collections.emptyList();
public RaplaClipboard( RaplaContext sm )
{
super( sm );
getUpdateModule().addModificationListener( this );
}
public void dataChanged( ModificationEvent evt ) throws RaplaException
{
if ( appointment == null )
return;
if ( evt.isRemoved( appointment) || evt.isRemoved( appointment.getReservation()))
{
clearAppointment();
}
}
private void clearAppointment()
{
this.appointment = null;
this.wholeReservation = false;
this.restrictedAllocatables = null;
this.reservations = Collections.emptyList();
this.contextAllocatables = Collections.emptyList();
}
public void setAppointment( Appointment appointment, boolean wholeReservation, Reservation destReservation, Allocatable[] restrictedAllocatables,Collection<Allocatable> contextAllocatables )
{
this.appointment = appointment;
this.wholeReservation = wholeReservation;
this.reservations = Collections.singleton(destReservation);
this.restrictedAllocatables = restrictedAllocatables;
this.contextAllocatables = contextAllocatables;
}
public void setReservation(Collection<Reservation> copyReservation, Collection<Allocatable> contextAllocatables)
{
ArrayList<Appointment> appointmentList = new ArrayList<Appointment>();
for (Reservation r:copyReservation)
{
appointmentList.addAll( Arrays.asList( r.getAppointments()));
}
Collections.sort( appointmentList, new AppointmentStartComparator());
appointment = appointmentList.get(0);
wholeReservation = true;
restrictedAllocatables = Allocatable.ALLOCATABLE_ARRAY;
reservations = copyReservation;
this.contextAllocatables = contextAllocatables;
}
public boolean isWholeReservation()
{
return wholeReservation;
}
public Appointment getAppointment()
{
return appointment;
}
public Allocatable[] getRestrictedAllocatables()
{
return restrictedAllocatables;
}
public Reservation getReservation()
{
if ( reservations == null || reservations.size() == 0)
{
return null;
}
return reservations.iterator().next();
}
public Collection<Reservation> getReservations()
{
return reservations;
}
public Collection<Allocatable> getConextAllocatables() {
return contextAllocatables;
}
public void setContextAllocatables(Collection<Allocatable> contextAllocatables) {
this.contextAllocatables = contextAllocatables;
}
}
/*
class AllocationData implements Transferable {
public static final DataFlavor allocationFlavor = new DataFlavor(java.util.Map.class, "Rapla Allocation");
private static DataFlavor[] flavors = new DataFlavor[] {allocationFlavor};
Map data;
AllocationData(Map data) {
this.data = data;
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (isDataFlavorSupported(flavor))
return data;
else
throw new UnsupportedFlavorException(flavor);
}
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(allocationFlavor);
}
}*/
| 04900db4-clienttest | src/org/rapla/gui/internal/common/RaplaClipboard.java | Java | gpl3 | 5,129 |
/*--------------------------------------------------------------------------*
| 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.internal.common;
import java.awt.Component;
import java.text.MessageFormat;
import java.util.Locale;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
import org.rapla.entities.Named;
public class NamedListCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
Locale locale;
MessageFormat format = null;
public NamedListCellRenderer(Locale locale) {
this.locale = locale;
}
public NamedListCellRenderer(Locale locale,String formatString) {
this(locale);
this.format = new MessageFormat(formatString);
}
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
if (value instanceof Named)
value = ((Named) value).getName(locale);
if (format != null)
value = format.format(new Object[] {value});
return super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/common/NamedListCellRenderer.java | Java | gpl3 | 2,195 |
package org.rapla.gui.internal.common;
import org.rapla.framework.TypedComponentRole;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaMenubar;
public interface InternMenus
{
public static final TypedComponentRole<RaplaMenubar> MENU_BAR = new TypedComponentRole<RaplaMenubar>("org.rapla.gui.MenuBar");
public static final TypedComponentRole<RaplaMenu> FILE_MENU_ROLE = new TypedComponentRole<RaplaMenu>("org.rapla.gui.SystemMenu");
public static final TypedComponentRole<RaplaMenu> EXTRA_MENU_ROLE = new TypedComponentRole<RaplaMenu>("org.rapla.gui.ExtraMenu");
public static final TypedComponentRole<RaplaMenu> VIEW_MENU_ROLE =new TypedComponentRole<RaplaMenu>("org.rapla.gui.ViewMenu");
public static final TypedComponentRole<RaplaMenu> EXPORT_MENU_ROLE = new TypedComponentRole<RaplaMenu>("org.rapla.gui.ExportMenu");
public static final TypedComponentRole<RaplaMenu> ADMIN_MENU_ROLE =new TypedComponentRole<RaplaMenu>("org.rapla.gui.AdminMenu");
public static final TypedComponentRole<RaplaMenu> EDIT_MENU_ROLE = new TypedComponentRole<RaplaMenu>("org.rapla.gui.EditMenu");
public static final TypedComponentRole<RaplaMenu> IMPORT_MENU_ROLE =new TypedComponentRole<RaplaMenu>("org.rapla.gui.ImportMenu");
public static final TypedComponentRole<RaplaMenu> NEW_MENU_ROLE =new TypedComponentRole<RaplaMenu>("org.rapla.gui.NewMenu");
public static final TypedComponentRole<RaplaMenu> CALENDAR_SETTINGS = new TypedComponentRole<RaplaMenu>("org.rapla.gui.CalendarSettings");
}
| 04900db4-clienttest | src/org/rapla/gui/internal/common/InternMenus.java | Java | gpl3 | 1,549 |
/*--------------------------------------------------------------------------*
| 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.internal.common;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.Date;
import java.util.List;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaAction;
import org.rapla.gui.toolkit.DisposingTool;
import org.rapla.gui.toolkit.RaplaFrame;
public class CalendarAction extends RaplaAction {
CalendarSelectionModel model;
List<?> objects;
Component parent;
Date start;
public CalendarAction(RaplaContext sm,Component parent,CalendarModel selectionModel)
{
super( sm);
this.model = (CalendarSelectionModel)selectionModel.clone();
this.parent = parent;
putValue(NAME,getString("calendar"));
putValue(SMALL_ICON,getIcon("icon.calendar"));
}
public void changeObjects(List<?> objects) {
this.objects = objects;
}
public void setStart(Date start) {
this.start = start;
}
public void actionPerformed(ActionEvent evt) {
try {
RaplaFrame frame = new RaplaFrame(getContext());
Dimension dimension = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(new Dimension(
Math.min(dimension.width,800)
,Math.min(dimension.height-10,630)
)
);
if (start != null)
model.setSelectedDate(start);
if (objects != null && objects.size() > 0)
model.setSelectedObjects( objects );
if ( model.getViewId( ).equals("table")) {
model.setViewId("week");
}
model.setOption( CalendarModel.ONLY_MY_EVENTS, "false");
model.setAllocatableFilter( null);
model.setReservationFilter( null);
frame.setTitle("Rapla " + getString("calendar"));
MultiCalendarView cal = new MultiCalendarView(getContext(),model, false );
frame.setContentPane(cal.getComponent());
frame.addWindowListener(new DisposingTool(cal));
boolean packFrame = false;
frame.place( true, packFrame );
frame.setVisible(true);
cal.getSelectedCalendar().scrollToStart();
} catch (Exception ex) {
showException(ex, parent);
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/common/CalendarAction.java | Java | gpl3 | 3,453 |
/*--------------------------------------------------------------------------*
| 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.internal.common;
import java.awt.Component;
import java.util.Calendar;
import java.util.Date;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JList;
import org.rapla.components.util.DateTools;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.domain.Period;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.PeriodModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.Disposable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class PeriodChooser extends JComboBox implements Disposable
{
private static final long serialVersionUID = 1L;
Date selectedDate = null;
Period selectedPeriod = null;
public static int START_ONLY = 1;
public static int START_AND_END = 0;
public static int END_ONLY = -1;
int visiblePeriods;
I18nBundle i18n;
PeriodModel periodModel;
private boolean listenersEnabled = true;
private boolean isWeekOfPeriodVisible = true;
public PeriodChooser( RaplaContext context) throws RaplaException {
this(context,START_AND_END);
}
public PeriodChooser(RaplaContext context,int visiblePeriods) throws RaplaException {
// super(RaplaButton.SMALL);
this.visiblePeriods = visiblePeriods;
i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
setPeriodModel( context.lookup(ClientFacade.class) .getPeriodModel());
}
@SuppressWarnings("unchecked")
public void setPeriodModel(PeriodModel model) {
this.periodModel = model;
if ( periodModel != null ) {
try {
listenersEnabled = false;
DefaultComboBoxModel aModel = new DefaultComboBoxModel(model.getAllPeriods());
this.setModel(aModel);
} finally {
listenersEnabled = true;
}
}
setRenderer(new PeriodListCellRenderer());
update();
}
public void dispose() {
listenersEnabled = false;
}
private String formatPeriod(Period period) {
if ( !isWeekOfPeriodVisible)
{
return period.getName();
}
int lastWeek = period.getWeeks();
int week = weekOf(period,selectedDate);
if (week != 1 && week >= lastWeek) {
return i18n.format(
"period.format.end"
,period.getName()
);
} else {
return i18n.format(
"period.format.week"
,String.valueOf(weekOf(period,selectedDate))
,period.getName()
);
}
}
public static int weekOf(Period period, Date date) {
Date start = period.getStart();
Calendar cal = Calendar.getInstance(DateTools.getTimeZone());
if (!period.contains(date) || start == null)
return -1;
long duration = date.getTime() - start.getTime();
long weeks = duration / (DateTools.MILLISECONDS_PER_WEEK);
// setTimeInMillis has protected access in JDK 1.3.1
cal.setTime(new Date(date.getTime() - weeks * DateTools.MILLISECONDS_PER_WEEK));
int week_of_year = cal.get(Calendar.WEEK_OF_YEAR);
cal.setTime(start);
return ((int)weeks) + 1
+ (((week_of_year) != cal.get(Calendar.WEEK_OF_YEAR))? 1 :0);
}
private String formatPeriodList(Period period) {
if (visiblePeriods == START_ONLY) {
return i18n.format(
"period.format.start"
,period.getName()
);
} else if (visiblePeriods == END_ONLY) {
return i18n.format(
"period.format.end"
,period.getName()
);
} else {
return period.getName();
}
}
public void setDate(Date date, Date endDate) {
try {
listenersEnabled = false;
if (date != selectedDate) // Compute period only on date change
{
selectedPeriod = getPeriod(date, endDate);
}
if ( selectedPeriod != null )
{
selectedDate = date;
setSelectedItem(selectedPeriod);
}
else
{
selectedDate = date;
setSelectedItem(null);
}
repaint();
revalidate();
} finally {
listenersEnabled = true;
}
}
public void setDate(Date date) {
setDate(date, null);
}
private String getSelectionText() {
Period period = selectedPeriod;
if ( period != null ) {
return formatPeriod(period);
} else {
return i18n.getString("period.not_set");
}
}
public void setSelectedPeriod(Period period) {
selectedPeriod = period; // EXCO
listenersEnabled = false;
setSelectedItem(period);
listenersEnabled = true;
if (visiblePeriods == END_ONLY) {
selectedDate = period.getEnd();
} else {
selectedDate = period.getStart();
}
}
public Period getPeriod() {
return selectedPeriod; // getPeriod(selectedDate);
}
private Period getPeriod(Date date, Date endDate) {
if (periodModel == null )
return null;
if ( visiblePeriods == END_ONLY) {
return periodModel.getNearestPeriodForEndDate(date);
} else {
return periodModel.getNearestPeriodForStartDate(date, endDate);
}
}
public Date getDate() {
return selectedDate;
}
private void update() {
setVisible(periodModel != null && periodModel.getSize() > 0);
setDate(getDate());
}
protected void fireActionEvent() {
if ( !listenersEnabled )
{
return ;
}
Period period = (Period) getSelectedItem();
selectedPeriod = period; // EXCO
if (period != null)
{
if (visiblePeriods == END_ONLY) {
selectedDate = period.getEnd();
} else {
selectedDate = period.getStart();
}
}
super.fireActionEvent();
}
class PeriodListCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
if (index == -1) {
value = getSelectionText();
} else {
Period period = (Period) value;
value = formatPeriodList(period);
}
return super.getListCellRendererComponent(list,
value,
index,
isSelected,
cellHasFocus);
}
}
public boolean isWeekOfPeriodVisible()
{
return isWeekOfPeriodVisible;
}
public void setWeekOfPeriodVisible( boolean isWeekOfPeriodVisible )
{
this.isWeekOfPeriodVisible = isWeekOfPeriodVisible;
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/common/PeriodChooser.java | Java | gpl3 | 8,837 |
/*--------------------------------------------------------------------------*
| 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.gui.internal.print;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.iolayer.ComponentPrinter;
import org.rapla.components.iolayer.IOInterface;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaDefaultContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.SwingCalendarView;
import org.rapla.gui.SwingViewFactory;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.ErrorDialog;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.plugin.abstractcalendar.MultiCalendarPrint;
public class CalendarPrintDialog extends DialogUI
{
private static final long serialVersionUID = 1L;
private JPanel titlePanel = new JPanel();
private JPanel southPanel = new JPanel();
private JLabel titleLabel = new JLabel();
private JLabel sizeLabel = new JLabel();
private JComboBox endDate;
private JTextField titleEdit = new JTextField();
private RaplaButton cancelbutton;
private RaplaButton formatbutton;
private RaplaButton printbutton;
private RaplaButton savebutton;
private JScrollPane scrollPane;
IOInterface printTool;
ExportServiceList exportServiceList;
// public static int[] sizes = new int[] {50,60,70,80,90,100,120,150,180,200};
public static double defaultBorder = 11.0; //11 mm defaultBorder
I18nBundle i18n;
Listener listener = new Listener();
PageFormat m_format;
protected SwingCalendarView currentView;
CalendarSelectionModel model;
Printable printable;
int curPage = 0;
JButton previousPage = new JButton("<");
JLabel pageLabel = new JLabel();
JButton nextPage = new JButton(">");
boolean updatePageCount = true;
int pageCount;
private JComponent page = new JComponent()
{
private static final long serialVersionUID = 1L;
public void paint(Graphics g)
{
try {
if ( updatePageCount )
{
pageCount = 0;
Graphics hidden = g.create();
while ( true )
{
int status = printable.print( hidden, m_format, pageCount);
boolean isNotExistant = status == Printable.NO_SUCH_PAGE;
if ( isNotExistant)
{
break;
}
pageCount++;
}
}
if ( curPage >= pageCount)
{
curPage = pageCount-1;
}
paintPaper( g, m_format );
printable.print( g, m_format, curPage);
pageLabel.setText(""+ (curPage +1) + "/" + pageCount);
boolean isLast = curPage >= pageCount -1;
nextPage.setEnabled( !isLast);
previousPage.setEnabled( curPage > 0);
savebutton.setEnabled(pageCount!=0);
} catch (PrinterException e) {
e.printStackTrace();
}
finally
{
updatePageCount = false;
}
}
protected void paintPaper(Graphics g, PageFormat format ) {
g.setColor(Color.white);
Rectangle rect = g.getClipBounds();
int paperHeight = (int)format.getHeight();
int paperWidth = (int)format.getWidth();
g.fillRect(rect.x, rect.y , Math.min(rect.width,Math.max(0,paperWidth-rect.x)), Math.min(rect.height, Math.max(0,paperHeight- rect.y)));
g.setColor(Color.black);
g.drawRect(1, 1 , paperWidth - 2, paperHeight - 2);
}
};
public static CalendarPrintDialog create(RaplaContext sm,Component owner,boolean modal,CalendarSelectionModel model,PageFormat format) throws RaplaException {
CalendarPrintDialog dlg;
Component topLevel = getOwnerWindow(owner);
if (topLevel instanceof Dialog)
dlg = new CalendarPrintDialog(sm,(Dialog)topLevel);
else
dlg = new CalendarPrintDialog(sm,(Frame)topLevel);
try {
dlg.init(modal,model,format);
} catch (Exception ex) {
throw new RaplaException( ex );
}
return dlg;
}
protected CalendarPrintDialog(RaplaContext context,Dialog owner) throws RaplaException {
super(context,owner);
init(context);
}
protected CalendarPrintDialog(RaplaContext context,Frame owner) throws RaplaException {
super(context,owner);
init(context);
}
private void init(RaplaContext context) throws RaplaException{
exportServiceList = new ExportServiceList( context);
}
private void init(boolean modal,CalendarSelectionModel model,PageFormat format) throws Exception {
super.init(modal,new JPanel(),new String[] {"print","format","print_to_file","cancel"});
this.model = model;
Map<String,SwingViewFactory> factoryMap = new HashMap<String, SwingViewFactory>();
for (SwingViewFactory fact: getContext().lookup(Container.class).lookupServicesFor(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION))
{
String id = fact.getViewId();
factoryMap.put( id , fact);
}
RaplaContext context = getContext();
printTool = context.lookup(IOInterface.class);
i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
m_format = format;
if (m_format == null) {
m_format = createPageFormat();
m_format.setOrientation(m_format.getOrientation());
}
SwingViewFactory factory = factoryMap.get( model.getViewId());
RaplaDefaultContext contextWithPrintInfo = new RaplaDefaultContext(context);
contextWithPrintInfo.put(SwingViewFactory.PRINT_CONTEXT, new Boolean(true));
currentView = factory.createSwingView( contextWithPrintInfo, model, false);
if ( currentView instanceof Printable)
{
printable = (Printable)currentView;
}
else
{
Component comp = currentView.getComponent();
printable = new ComponentPrinter( comp, comp.getPreferredSize());
}
String title = model.getTitle();
content.setLayout(new BorderLayout());
titlePanel.add(titleLabel);
titlePanel.add(titleEdit);
new RaplaGUIComponent( context).addCopyPaste(titleEdit);
if ( currentView instanceof MultiCalendarPrint)
{
MultiCalendarPrint multiPrint = (MultiCalendarPrint) currentView;
sizeLabel.setText(multiPrint.getCalendarUnit() + ":");
String[] blockSizes = new String[52];
for (int i=0;i<blockSizes.length;i++)
{
blockSizes[i] = String.valueOf(i+1);
}
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(blockSizes);
endDate= jComboBox;
endDate.setEditable(true);
endDate.setPreferredSize( new Dimension(40, 30));
titlePanel.add(Box.createHorizontalStrut(10));
titlePanel.add(sizeLabel);
titlePanel.add(endDate);
titlePanel.add(Box.createHorizontalStrut(10));
endDate.addActionListener(listener);
}
titlePanel.add(previousPage);
titlePanel.add(nextPage);
titlePanel.add(pageLabel);
titleEdit.setColumns(30);
titleEdit.setText(title);
content.add(titlePanel, BorderLayout.NORTH);
scrollPane =new JScrollPane( page );
scrollPane.setPreferredSize(new Dimension(730,450));
content.add(scrollPane, BorderLayout.CENTER);
content.add(southPanel, BorderLayout.SOUTH);
southPanel.setMaximumSize( new Dimension(1,1));
southPanel.setMinimumSize( new Dimension(1,1));
southPanel.setPreferredSize( new Dimension(1,1));
southPanel.setLayout( null);
southPanel.add( currentView.getComponent());
scrollPane.getVerticalScrollBar().setUnitIncrement(10);
scrollPane.getHorizontalScrollBar().setUnitIncrement(10);
updateSizes( m_format);
printbutton = getButton(0);
printbutton.setAction(listener);
formatbutton = getButton(1);
formatbutton.setAction(listener);
savebutton = getButton(2);
savebutton.setAction(listener);
cancelbutton = getButton(3);
savebutton.setVisible(exportServiceList.getServices().length>0);
//swingCalendar.setPrintView(true);
currentView.update();
//sizeLabel.setText("Endedatum:");
titleLabel.setText(i18n.getString("weekview.print.title_textfield")+":");
setTitle(i18n.getString("weekview.print.dialog_title"));
printbutton.setIcon(i18n.getIcon("icon.print"));
savebutton.setText(i18n.getString("print_to_file"));
savebutton.setIcon(i18n.getIcon("icon.pdf"));
printbutton.setText(i18n.getString("print"));
formatbutton.setText(i18n.getString("weekview.print.format_button"));
cancelbutton.setText(i18n.getString("cancel"));
cancelbutton.setIcon(i18n.getIcon("icon.cancel"));
pageLabel.setText(""+1);
/*
if (getSession().getValue(LAST_SELECTED_SIZE) != null)
weekview.setSlotSize(((Integer)getSession().getValue(LAST_SELECTED_SIZE)).intValue());
*/
// int columnSize = model.getSize();
// sizeChooser.setSelectedItem(String.valueOf(columnSize));
titleEdit.addActionListener(listener);
titleEdit.addKeyListener(listener);
nextPage.addActionListener( listener);
previousPage.addActionListener( listener);
}
private void updateSizes( @SuppressWarnings("unused") PageFormat format)
{
//double paperHeight = format.getHeight();
//int height = (int)paperHeight + 100;
int height = 2000;
int width = 900;
updatePageCount = true;
page.setPreferredSize( new Dimension( width,height));
}
private PageFormat createPageFormat() {
PageFormat format= (PageFormat) printTool.defaultPage().clone();
format.setOrientation(PageFormat.LANDSCAPE);
Paper paper = format.getPaper();
paper.setImageableArea(
defaultBorder * IOInterface.MM_TO_INCH * 72
,defaultBorder * IOInterface.MM_TO_INCH * 72
,paper.getWidth() - 2 * defaultBorder * IOInterface.MM_TO_INCH * 72
,paper.getHeight() - 2 * defaultBorder * IOInterface.MM_TO_INCH * 72
);
format.setPaper(paper);
return format;
}
public void start() {
super.start();
}
private class Listener extends AbstractAction implements KeyListener {
private static final long serialVersionUID = 1L;
public void keyReleased(KeyEvent evt) {
try {
processTitleChange();
} catch (Exception ex) {
showException(ex);
}
}
protected void processTitleChange() throws RaplaException {
String oldTitle = model.getTitle();
String newTitle = titleEdit.getText();
model.setTitle(newTitle);
// only update view if title is set or removed not on every keystroke
if ((( oldTitle == null || oldTitle.length() == 0) && (newTitle != null && newTitle.length() > 0))
|| ((oldTitle != null && oldTitle.length() > 0 ) && ( newTitle == null || newTitle.length() ==0))
)
{
currentView.update(); // BJO performance issue
}
scrollPane.invalidate();
scrollPane.repaint();
}
public void keyTyped(KeyEvent evt) {
}
public void keyPressed(KeyEvent evt) {
}
public void actionPerformed(ActionEvent evt) {
try {
if (evt.getSource()==endDate) {
try {
Object selectedItem = endDate.getSelectedItem();
if ( selectedItem != null )
{
try
{
Integer units = Integer.valueOf(selectedItem.toString());
((MultiCalendarPrint)currentView).setUnits( units);
}
catch (NumberFormatException ex)
{
}
}
updatePageCount = true;
} catch (Exception ex) {
return;
}
currentView.update();
scrollPane.invalidate();
scrollPane.repaint();
}
if (evt.getSource()==titleEdit) {
processTitleChange();
}
if (evt.getSource()==formatbutton) {
m_format= printTool.showFormatDialog(m_format);
scrollPane.invalidate();
scrollPane.repaint();
updateSizes( m_format);
}
if (evt.getSource()==nextPage) {
curPage++;
scrollPane.repaint();
}
if (evt.getSource()==previousPage) {
curPage = Math.max(0,curPage -1 );
scrollPane.repaint();
}
if (evt.getSource()==printbutton) {
if (printTool.print(printable, m_format, true))
{
// We can't close or otherwise it won't work under windows
//close();
}
}
if (evt.getSource()==savebutton) {
boolean success = exportServiceList.export(printable, m_format, scrollPane);
Component topLevel = getParent();
if(success )
{
if (confirmPrint(topLevel))
{
close();
}
}
}
} catch (Exception ex) {
showException(ex);
}
}
}
protected boolean confirmPrint(Component topLevel) {
try {
DialogUI dlg = DialogUI.create(
getContext()
,topLevel
,true
,i18n.getString("print")
,i18n.getString("file_saved")
,new String[] { i18n.getString("ok")}
);
dlg.setIcon(i18n.getIcon("icon.pdf"));
dlg.setDefault(0);
dlg.start();
return (dlg.getSelectedIndex() == 0);
} catch (RaplaException e) {
return true;
}
}
public void showException(Exception ex) {
ErrorDialog dialog;
try {
dialog = new ErrorDialog(getContext());
dialog.showExceptionDialog(ex,this);
} catch (RaplaException e) {
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/print/CalendarPrintDialog.java | Java | gpl3 | 16,772 |
/*--------------------------------------------------------------------------*
| 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.internal.print;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.util.Collection;
import java.util.HashMap;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import org.rapla.components.iolayer.IOInterface;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.common.NamedListCellRenderer;
import org.rapla.gui.toolkit.DialogUI;
public class ExportServiceList extends RaplaGUIComponent {
HashMap<Object,ExportService> exporters = new HashMap<Object,ExportService>();
/**
* @param sm
* @throws RaplaException
*/
public ExportServiceList(RaplaContext sm) throws RaplaException {
super(sm);
IOInterface printInterface = getService( IOInterface.class);
boolean applet =(getService(StartupEnvironment.class)).getStartupMode() == StartupEnvironment.APPLET;
if (printInterface.supportsPostscriptExport() && !applet) {
PSExportService exportService = new PSExportService(getContext());
addService("psexport",exportService);
}
if (!applet) {
PDFExportService exportService = new PDFExportService(getContext());
addService("pdf",exportService);
}
}
public boolean export(Printable printable,PageFormat pageFormat,Component parentComponent) throws Exception
{
Collection<ExportService> services = exporters.values();
Object[] serviceArray = services.toArray();
@SuppressWarnings("unchecked")
JList list = new JList(serviceArray);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
panel.add(new JLabel(getString("weekview.print.choose_export")),BorderLayout.NORTH);
panel.add(list,BorderLayout.CENTER);
setRenderer(list);
list.setSelectedIndex(0);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
DialogUI dlg = DialogUI.create(getContext(),parentComponent,true,panel,
new String[] {
getString("export")
,getString("cancel")
});
dlg.setTitle(getString("weekview.print.choose_export"));
dlg.getButton(0).setIcon(getIcon("icon.save"));
dlg.getButton(1).setIcon(getIcon("icon.cancel"));
dlg.start();
if (dlg.getSelectedIndex() != 0 || list.getSelectedIndex() == -1)
return false;
ExportService selectedService = (ExportService)serviceArray[list.getSelectedIndex()];
boolean result = selectedService.export(printable,pageFormat, parentComponent);
return result;
}
@SuppressWarnings("unchecked")
private void setRenderer(JList list) {
list.setCellRenderer(new NamedListCellRenderer(getI18n().getLocale()));
}
public void addService(Object policy,ExportService exportService) {
exporters.put(policy, exportService);
}
public void removeService(Object policy) {
exporters.remove(policy);
}
public ExportService select(Object policy) throws RaplaContextException {
ExportService result = exporters.get(policy);
if (result == null)
throw new RaplaContextException("Export Service not found for key " + policy);
return result;
}
public boolean isSelectable(Object policy) {
return exporters.get(policy) != null;
}
public ExportService[] getServices() {
return exporters.values().toArray(new ExportService[0]);
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/print/ExportServiceList.java | Java | gpl3 | 4,959 |
/*--------------------------------------------------------------------------*
| 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.internal.print;
import java.awt.Component;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.util.Locale;
import org.rapla.components.iolayer.IOInterface;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaGUIComponent;
public class PSExportService extends RaplaGUIComponent implements ExportService {
public final static String EXPORT_DIR = PSExportService.class.getName() + ".dir";
IOInterface printInterface;
public PSExportService(RaplaContext sm){
super(sm);
printInterface = getService(IOInterface.class);
}
public boolean export(Printable printable,PageFormat pageFormat,Component parentComponent) throws Exception
{
String dir = (String) getSessionMap().get(EXPORT_DIR);
boolean isPDF = false;
String file = printInterface.saveAsFileShowDialog
(
dir
,printable
,pageFormat
,false
,parentComponent
,isPDF
);
if (file != null)
{
getSessionMap().put(EXPORT_DIR,file);
return true;
}
else
{
return false;
}
}
public String getName(Locale locale) {
return getI18n().getString("weekview.print.postscript");
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/print/PSExportService.java | Java | gpl3 | 2,364 |
/*--------------------------------------------------------------------------*
| 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.gui.internal.print;
import java.awt.Component;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
public interface ExportService extends org.rapla.entities.Named {
boolean export(Printable printable,PageFormat pageFormat,Component parentComponent) throws Exception;
}
| 04900db4-clienttest | src/org/rapla/gui/internal/print/ExportService.java | Java | gpl3 | 1,247 |
/*--------------------------------------------------------------------------*
| 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.internal.print;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.print.PageFormat;
import javax.swing.SwingUtilities;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaAction;
public class PrintAction extends RaplaAction {
CalendarSelectionModel model;
PageFormat m_pageFormat;
public PrintAction(RaplaContext sm) {
super( sm);
setEnabled(false);
putValue(NAME,getString("print"));
putValue(SMALL_ICON,getIcon("icon.print"));
}
public void setModel(CalendarSelectionModel settings) {
this.model = settings;
setEnabled(settings != null);
}
public void setPageFormat(PageFormat pageFormat) {
m_pageFormat = pageFormat;
}
public void actionPerformed(ActionEvent evt) {
Component parent = getMainComponent();
try {
boolean modal = true;
final CalendarPrintDialog dialog = CalendarPrintDialog.create(getContext(),parent,modal, model, m_pageFormat);
final Dimension dimension = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
dialog.setSize(new Dimension(
Math.min(dimension.width,900)
,Math.min(dimension.height-10,700)
)
);
SwingUtilities.invokeLater( new Runnable() {
public void run()
{
dialog.setSize(new Dimension(
Math.min(dimension.width,900)
,Math.min(dimension.height-11,699)
)
);
}
}
);
dialog.startNoPack();
} catch (Exception ex) {
showException(ex, parent);
}
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/print/PrintAction.java | Java | gpl3 | 3,026 |
/*--------------------------------------------------------------------------*
| 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.internal.print;
import java.awt.Component;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.util.Locale;
import org.rapla.components.iolayer.IOInterface;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaGUIComponent;
public class PDFExportService extends RaplaGUIComponent implements ExportService {
public final static String EXPORT_DIR = PDFExportService.class.getName() + ".dir";
IOInterface printInterface;
public PDFExportService(RaplaContext sm) {
super(sm);
printInterface = getService(IOInterface.class);
}
public boolean export(Printable printable,PageFormat pageFormat,Component parentComponent) throws Exception
{
String dir = (String) getSessionMap().get(EXPORT_DIR);
boolean isPDF = true;
String file = printInterface.saveAsFileShowDialog
(
dir
,printable
,pageFormat
,false
,parentComponent
, isPDF
);
if (file != null)
{
getSessionMap().put(EXPORT_DIR,file);
return true;
}
return false;
}
public String getName(Locale locale) {
return "PDF";
}
}
| 04900db4-clienttest | src/org/rapla/gui/internal/print/PDFExportService.java | Java | gpl3 | 2,292 |
/*--------------------------------------------------------------------------*
| 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-clienttest | src/org/rapla/gui/EditField.java | Java | gpl3 | 1,793 |
package org.rapla;
import java.util.Arrays;
/** Object that encapsulates the login information.
* For admin users it is possible to connect as an other user.
*/
public class ConnectInfo {
String username;
char[] password;
String connectAs;
public ConnectInfo(String username, char[] password, String connectAs) {
this.username = username;
this.password = password;
this.connectAs = connectAs;
}
public ConnectInfo(String username, char[] password) {
this( username, password, null);
}
public String getUsername() {
return username;
}
public char[] getPassword() {
return password;
}
public String getConnectAs() {
return connectAs;
}
@Override
public String toString() {
return "ReconnectInfo [username=" + username + ", password=" + Arrays.toString(password) + ", connectAs=" + connectAs + "]";
}
}
| 04900db4-clienttest | src/org/rapla/ConnectInfo.java | Java | gpl3 | 976 |
package org.rapla.server;
import javax.servlet.http.HttpServletRequest;
import org.rapla.entities.User;
import org.rapla.framework.Configuration;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.servletpages.RaplaPageGenerator;
public interface ServerServiceContainer extends Container
{
<T> void addRemoteMethodFactory( Class<T> service, Class<? extends RemoteMethodFactory<T>> factory);
<T> void addRemoteMethodFactory( Class<T> service, Class<? extends RemoteMethodFactory<T>> factory, Configuration config);
/**
* You can add arbitrary serlvet pages to your rapla webapp.
*
* Example that adds a page with the name "my-page-name" and the class
* "org.rapla.plugin.myplugin.MyPageGenerator". You can call this page with <code>rapla?page=my-page-name</code>
* <p/>
* In the provideService Method of your PluginDescriptor do the following
<pre>
container.addContainerProvidedComponent( RaplaExtensionPoints.SERVLET_PAGE_EXTENSION, "org.rapla.plugin.myplugin.MyPageGenerator", "my-page-name", config);
</pre>
*@see org.rapla.servletpages.RaplaPageGenerator
*/
<T extends RaplaPageGenerator> void addWebpage(String pagename, Class<T> pageClass);
<T extends RaplaPageGenerator> void addWebpage(String pagename, Class<T> pageClass, Configuration config);
/** @return null when the server doesn't have the webpage
* @throws RaplaContextException */
RaplaPageGenerator getWebpage(String page);
public User getUser(HttpServletRequest request) throws RaplaException;
<T> T createWebservice(Class<T> role,HttpServletRequest request ) throws RaplaException;
boolean hasWebservice(String interfaceName);
}
| 04900db4-clienttest | src/org/rapla/server/ServerServiceContainer.java | Java | gpl3 | 1,800 |
package org.rapla.server;
import java.util.Collection;
import org.rapla.entities.User;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
public interface RaplaKeyStorage {
public String getRootKeyBase64();
public LoginInfo getSecrets(User user, TypedComponentRole<String> tagName) throws RaplaException;
public void storeLoginInfo(User user,TypedComponentRole<String> tagName,String login,String secret) throws RaplaException;
public void removeLoginInfo(User user, TypedComponentRole<String> tagName) throws RaplaException;
public void storeAPIKey(User user,String clientId,String apiKey) throws RaplaException;
public Collection<String> getAPIKeys(User user) throws RaplaException;
public void removeAPIKey(User user,String key) throws RaplaException;
public class LoginInfo
{
public String login;
public String secret;
}
}
| 04900db4-clienttest | src/org/rapla/server/RaplaKeyStorage.java | Java | gpl3 | 919 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.server;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.ConnectInfo;
import org.rapla.RaplaMainContainer;
import org.rapla.RaplaStartupEnvironment;
import org.rapla.client.ClientService;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientListenerAdapter;
import org.rapla.components.util.IOUtil;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.User;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaDefaultContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.ServiceListCreator;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.internal.ContainerImpl;
import org.rapla.framework.internal.RaplaJDKLoggingAdapter;
import org.rapla.framework.logger.Logger;
import org.rapla.server.internal.ServerServiceImpl;
import org.rapla.server.internal.ShutdownService;
import org.rapla.servletpages.RaplaPageGenerator;
import org.rapla.servletpages.ServletRequestPreprocessor;
import org.rapla.storage.ImportExportManager;
import org.rapla.storage.StorageOperator;
import org.rapla.storage.dbrm.RemoteMethodStub;
import org.rapla.storage.dbrm.WrongRaplaVersionException;
public class MainServlet extends HttpServlet {
private static final String RAPLA_RPC_PATH = "/rapla/rpc/";
private static final long serialVersionUID = 1L;
/** The default config filename is raplaserver.xconf*/
private ContainerImpl raplaContainer;
public final static String DEFAULT_CONFIG_NAME = "raplaserver.xconf";
private Logger logger = null;
private String startupMode =null;
private String startupUser = null;
private Integer port;
private String contextPath;
private String env_rapladatasource;
private String env_raplafile;
private Object env_rapladb;
private Object env_raplamail;
private Boolean env_development;
private String downloadUrl;
private String serverVersion;
private ServerServiceImpl server;
private Runnable shutdownCommand;
private Collection<ServletRequestPreprocessor> processors;
private ReadWriteLock restartLock = new ReentrantReadWriteLock();
// the following variables are only for non server startup
private Semaphore guiMutex = new Semaphore(1);
private ConnectInfo reconnect;
private URL getConfigFile(String entryName, String defaultName) throws ServletException,IOException {
String configName = getServletConfig().getInitParameter(entryName);
if (configName == null)
configName = defaultName;
if (configName == null)
throw new ServletException("Must specify " + entryName + " entry in web.xml !");
String realPath = getServletConfig().getServletContext().getRealPath("/WEB-INF/" + configName);
if (realPath != null)
{
File configFile = new File(realPath);
if (configFile.exists()) {
URL configURL = configFile.toURI().toURL();
return configURL;
}
}
URL configURL = getClass().getResource("/raplaserver.xconf");
if ( configURL == null)
{
String message = "ERROR: Config file not found " + configName;
throw new ServletException(message);
}
else
{
return configURL;
}
}
/**
* Initializes Servlet and creates a <code>RaplaMainContainer</code> instance
*
* @exception ServletException if an error occurs
*/
synchronized public void init()
throws ServletException
{
getLogger().info("Init RaplaServlet");
Collection<String> instanceCounter = null;
String selectedContextPath = null;
Context env;
try
{
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:comp");
env = (Context)envContext.lookup("env");
} catch (Exception e) {
env = null;
getLogger().warn("No JNDI Enivronment found under java:comp or java:/comp");
}
if ( env != null)
{
env_rapladatasource = lookupEnvString(env, "rapladatasource", true);
env_raplafile = lookupEnvString(env,"raplafile", true);
env_rapladb = lookupResource(env, "jdbc/rapladb", true);
getLogger().info("Passed JNDI Environment rapladatasource=" + env_rapladatasource + " env_rapladb="+env_rapladb + " env_raplafile="+ env_raplafile);
if ( env_rapladatasource == null || env_rapladatasource.trim().length() == 0 || env_rapladatasource.startsWith( "${"))
{
if ( env_rapladb != null)
{
env_rapladatasource = "rapladb";
}
else if ( env_raplafile != null)
{
env_rapladatasource = "raplafile";
}
else
{
getLogger().warn("Neither file nor database setup configured.");
}
}
env_raplamail = lookupResource(env, "mail/Session", false);
startupMode = lookupEnvString(env,"rapla_startup_mode", false);
env_development = (Boolean) lookupEnvVariable(env, "rapla_development", false);
@SuppressWarnings("unchecked")
Collection<String> instanceCounterLookup = (Collection<String>) lookup(env,"rapla_instance_counter", false);
instanceCounter = instanceCounterLookup;
selectedContextPath = lookupEnvString(env,"rapla_startup_context", false);
startupUser = lookupEnvString( env, "rapla_startup_user", false);
shutdownCommand = (Runnable) lookup(env,"rapla_shutdown_command", false);
port = (Integer) lookup(env,"rapla_startup_port", false);
downloadUrl = (String) lookup(env,"rapla_download_url", false);
}
if ( startupMode == null)
{
startupMode = "server";
}
contextPath = getServletContext().getContextPath();
if ( !contextPath.startsWith("/"))
{
contextPath = "/" + contextPath;
}
// don't startup server if contextPath is not selected
if ( selectedContextPath != null)
{
if( !contextPath.equals(selectedContextPath))
return;
}
else if ( instanceCounter != null)
{
instanceCounter.add( contextPath);
if ( instanceCounter.size() > 1)
{
String msg = ("Ignoring webapp ["+ contextPath +"]. Multiple context found in jetty container " + instanceCounter + " You can specify one via -Dorg.rapla.context=REPLACE_WITH_CONTEXT");
getLogger().error(msg);
return;
}
}
startServer(startupMode);
if ( startupMode.equals("standalone") || startupMode.equals("client"))
{
try {
guiMutex.acquire();
} catch (InterruptedException e) {
}
try
{
startGUI(startupMode);
}
catch (Exception ex)
{
exit();
throw new ServletException(ex);
}
}
}
private Object lookupResource(Context env, String lookupname, boolean log) {
String newLookupname = getServletContext().getInitParameter(lookupname);
if (newLookupname != null && newLookupname.length() > 0)
{
lookupname = newLookupname;
}
Object result = lookup(env,lookupname, log);
return result;
}
private String lookupEnvString(Context env, String lookupname, boolean log) {
Object result = lookupEnvVariable(env, lookupname, log);
return (String) result;
}
private Object lookupEnvVariable(Context env, String lookupname, boolean log) {
String newEnvname = getServletContext().getInitParameter(lookupname);
if ( newEnvname != null)
{
getLogger().info("Using contextparam for " + lookupname + ": " + newEnvname);
}
if (newEnvname != null && newEnvname.length() > 0 )
{
return newEnvname;
}
else
{
Object result = lookup(env,lookupname, log);
return result;
}
}
private Object lookup(Context env, String string, boolean warn) {
try {
Object result = env.lookup( string);
if ( result == null && warn)
{
getLogger().warn("JNDI Entry "+ string + " not found");
}
return result;
} catch (Exception e) {
if ( warn )
{
getLogger().warn("JNDI Entry "+ string + " not found");
}
return null;
}
}
private void startGUI(final String startupMode) throws ServletException {
ConnectInfo connectInfo = null;
if (startupMode.equals("standalone"))
{
try
{
String username = startupUser;
if ( username == null )
{
username = getFirstAdmin();
}
if ( username != null)
{
connectInfo = new ConnectInfo(username, "".toCharArray());
}
}
catch (RaplaException ex)
{
getLogger().error(ex.getMessage(),ex);
}
}
startGUI( startupMode, connectInfo);
if ( startupMode.equals("standalone") || startupMode.equals("client"))
{
try {
guiMutex.acquire();
while ( reconnect != null )
{
raplaContainer.dispose();
try {
if ( startupMode.equals("client"))
{
initContainer(startupMode);
}
else if ( startupMode.equals("standalone"))
{
startServer("standalone");
}
if ( startupMode.equals("standalone") && reconnect.getUsername() == null)
{
String username = getFirstAdmin();
if ( username != null)
{
reconnect= new ConnectInfo(username, "".toCharArray());
}
}
startGUI(startupMode, reconnect);
guiMutex.acquire();
} catch (Exception ex) {
getLogger().error("Error restarting client",ex);
exit();
return;
}
}
} catch (InterruptedException e) {
}
}
}
protected String getFirstAdmin() throws RaplaContextException, RaplaException {
String username = null;
StorageOperator operator = server.getContext().lookup(StorageOperator.class);
for (User u:operator.getUsers())
{
if ( u.isAdmin())
{
username = u.getUsername();
break;
}
}
return username;
}
public void startGUI( final String startupMode, ConnectInfo connectInfo) throws ServletException {
try
{
if ( startupMode.equals("standalone") || startupMode.equals("client"))
{
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
try
{
Thread.currentThread().setContextClassLoader( ClassLoader.getSystemClassLoader());
ClientServiceContainer clientContainer = raplaContainer.getContext().lookup(ClientServiceContainer.class );
ClientService client = clientContainer.getContext().lookup( ClientService.class);
client.addRaplaClientListener(new RaplaClientListenerAdapter() {
public void clientClosed(ConnectInfo reconnect) {
MainServlet.this.reconnect = reconnect;
if ( reconnect != null) {
guiMutex.release();
} else {
exit();
}
}
public void clientAborted()
{
exit();
}
});
clientContainer.start(connectInfo);
}
finally
{
Thread.currentThread().setContextClassLoader( contextClassLoader);
}
}
else if (!startupMode.equals("server"))
{
exit();
}
}
catch( Exception e )
{
getLogger().error("Could not start server", e);
if ( raplaContainer != null)
{
raplaContainer.dispose();
}
throw new ServletException( "Error during initialization see logs for details: " + e.getMessage(), e );
}
// log("Rapla Servlet started");
}
protected void startServer(final String startupMode)
throws ServletException {
try
{
initContainer(startupMode);
if ( startupMode.equals("import"))
{
ImportExportManager manager = raplaContainer.getContext().lookup(ImportExportManager.class);
manager.doImport();
exit();
}
else if (startupMode.equals("export"))
{
ImportExportManager manager = raplaContainer.getContext().lookup(ImportExportManager.class);
manager.doExport();
exit();
}
else if ( startupMode.equals("server") || startupMode.equals("standalone") )
{
String hint = serverContainerHint != null ? serverContainerHint :"*";
// Start the server via lookup
// We start the standalone server before the client to prevent jndi lookup failures
server = (ServerServiceImpl) raplaContainer.lookup( ServerServiceContainer.class, hint);
processors = server.lookupServicesFor(RaplaServerExtensionPoints.SERVLET_REQUEST_RESPONSE_PREPROCESSING_POINT);
final Logger logger = getLogger();
logger.info("Rapla server started");
if ( startupMode.equals("server"))
{
// if
setShutdownService(startupMode);
}
else
{
raplaContainer.addContainerProvidedComponentInstance(RemoteMethodStub.class, server);
}
}
}
catch( Exception e )
{
getLogger().error(e.getMessage(), e);
String message = "Error during initialization see logs for details: " + e.getMessage();
if ( raplaContainer != null)
{
raplaContainer.dispose();
}
if ( shutdownCommand != null)
{
shutdownCommand.run();
}
throw new ServletException( message,e);
}
}
protected void setShutdownService(final String startupMode) {
server.setShutdownService( new ShutdownService() {
public void shutdown(final boolean restart) {
Lock writeLock;
try
{
try
{
RaplaComponent.unlock( restartLock.readLock());
}
catch (IllegalMonitorStateException ex)
{
getLogger().error("Error unlocking read for restart " + ex.getMessage());
}
writeLock = RaplaComponent.lock( restartLock.writeLock(), 60);
}
catch (RaplaException ex)
{
getLogger().error("Can't restart server " + ex.getMessage());
return;
}
try
{
//acquired = requestCount.tryAcquire(maxRequests -1,10, TimeUnit.SECONDS);
logger.info( "Stopping Server");
stopServer();
if ( restart)
{
try {
logger.info( "Restarting Server");
MainServlet.this.startServer(startupMode);
} catch (Exception e) {
logger.error( "Error while restarting Server", e );
}
}
}
finally
{
RaplaComponent.unlock(writeLock);
}
}
});
}
protected void initContainer(String startupMode) throws ServletException, IOException,
MalformedURLException, Exception, RaplaContextException {
URL configURL = getConfigFile("config-file",DEFAULT_CONFIG_NAME);
//URL logConfigURL = getConfigFile("log-config-file","raplaserver.xlog").toURI().toURL();
RaplaStartupEnvironment env = new RaplaStartupEnvironment();
env.setStartupMode( StartupEnvironment.CONSOLE);
env.setConfigURL( configURL );
if ( startupMode.equals( "client"))
{
if ( port != null)
{
String url = downloadUrl;
if ( url == null)
{
url = "http://localhost:" + port+ contextPath;
if (! url.endsWith("/"))
{
url += "/";
}
}
env.setDownloadURL( new URL(url));
}
}
// env.setContextRootURL( contextRootURL );
//env.setLogConfigURL( logConfigURL );
RaplaDefaultContext context = new RaplaDefaultContext();
if ( env_rapladatasource != null)
{
context.put(RaplaMainContainer.ENV_RAPLADATASOURCE, env_rapladatasource);
}
if ( env_raplafile != null)
{
context.put(RaplaMainContainer.ENV_RAPLAFILE, env_raplafile);
}
if ( env_rapladb != null)
{
context.put(RaplaMainContainer.ENV_RAPLADB, env_rapladb);
}
if ( env_raplamail != null)
{
context.put(RaplaMainContainer.ENV_RAPLAMAIL, env_raplamail);
getLogger().info("Configured mail service via JNDI");
}
if ( env_development != null && env_development)
{
context.put(RaplaMainContainer.ENV_DEVELOPMENT, Boolean.TRUE);
}
raplaContainer = new RaplaMainContainer( env, context );
logger = raplaContainer.getContext().lookup(Logger.class);
if ( env_development != null && env_development)
{
addDevelopmentWarFolders();
}
serverVersion = raplaContainer.getContext().lookup(RaplaComponent.RAPLA_RESOURCES).getString("rapla.version");
}
// add the war folders of the plugins to jetty resource handler so that the files inside the war
// folders can be served from within jetty, even when they are not located in the same folder.
// The method will search the class path for plugin classes and then add the look for a war folder entry in the file hierarchy
// so a plugin allways needs a plugin class for this to work
@SuppressWarnings("unchecked")
private void addDevelopmentWarFolders()
{
Thread currentThread = Thread.currentThread();
ClassLoader classLoader = currentThread.getContextClassLoader();
ClassLoader parent = null;
try
{
Collection<File> webappFolders = ServiceListCreator.findPluginWebappfolders(logger);
if ( webappFolders.size() < 1)
{
return;
}
parent = classLoader.getParent();
if ( parent != null)
{
currentThread.setContextClassLoader( parent);
}
// first we need to access the necessary classes via reflection (are all loaded, because webapplication is already initialized)
final Class WebAppClassLoaderC = Class.forName("org.eclipse.jetty.webapp.WebAppClassLoader",false, parent);
final Class WebAppContextC = Class.forName("org.eclipse.jetty.webapp.WebAppContext",false, parent);
final Class ResourceCollectionC = Class.forName("org.eclipse.jetty.util.resource.ResourceCollection",false, parent);
final Class FileResourceC = Class.forName("org.eclipse.jetty.util.resource.FileResource",false, parent);
final Object webappContext = WebAppClassLoaderC.getMethod("getContext").invoke(classLoader);
if (webappContext == null)
{
return;
}
final Object baseResource = WebAppContextC.getMethod("getBaseResource").invoke( webappContext);
if ( baseResource != null && ResourceCollectionC.isInstance( baseResource) )
{
//Resource[] resources = ((ResourceCollection) baseResource).getResources();
final Object[] resources = (Object[])ResourceCollectionC.getMethod("getResources").invoke( baseResource);
Set list = new HashSet( Arrays.asList( resources));
for (File folder:webappFolders)
{
Object fileResource = FileResourceC.getConstructor( URL.class).newInstance( folder.toURI().toURL());
if ( !list.contains( fileResource))
{
list.add( fileResource);
getLogger().info("Adding " + fileResource + " to webapp folder");
}
}
Object[] array = list.toArray( resources);
//((ResourceCollection) baseResource).setResources( array);
ResourceCollectionC.getMethod("setResources", resources.getClass()).invoke( baseResource, new Object[] {array});
//ResourceCollectionC.getMethod(", parameterTypes)
}
}
catch (ClassNotFoundException ex)
{
getLogger().info("Development mode not in jetty so war finder will be disabled");
}
catch (Exception ex)
{
getLogger().error(ex.getMessage(), ex);
}
finally
{
if ( parent != null)
{
currentThread.setContextClassLoader( classLoader);
}
}
}
private void exit() {
MainServlet.this.reconnect = null;
guiMutex.release();
if ( shutdownCommand != null)
{
shutdownCommand.run();
}
}
public void service( HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException
{
RaplaPageGenerator servletPage;
Lock readLock = null;
try
{
try
{
readLock = RaplaComponent.lock( restartLock.readLock(), 25);
RaplaContext context = server.getContext();
for (ServletRequestPreprocessor preprocessor: processors)
{
final HttpServletRequest newRequest = preprocessor.handleRequest(context, getServletContext(), request, response);
if (newRequest != null)
request = newRequest;
if (response.isCommitted())
return;
}
}
catch (RaplaException e)
{
java.io.PrintWriter out = null;
try
{
response.setStatus( 500 );
out = response.getWriter();
out.println(IOUtil.getStackTraceAsString( e));
}
catch (Exception ex)
{
getLogger().error("Error writing exception back to client " + e.getMessage());
}
finally
{
if ( out != null)
{
out.close();
}
}
return;
}
String page = request.getParameter("page");
String requestURI =request.getRequestURI();
if ( page == null)
{
String raplaPrefix = "rapla/";
String contextPath = request.getContextPath();
String toParse;
if (requestURI.startsWith( contextPath))
{
toParse = requestURI.substring( contextPath.length());
}
else
{
toParse = requestURI;
}
int pageContextIndex = toParse.lastIndexOf(raplaPrefix);
if ( pageContextIndex>= 0)
{
page = toParse.substring( pageContextIndex + raplaPrefix.length());
int firstSeparator = page.indexOf('/');
if ( firstSeparator>1)
{
page = page.substring(0,firstSeparator );
}
}
}
//String servletPath = request.getServletPath();
if ( requestURI.indexOf(RAPLA_RPC_PATH) >= 0) {
handleOldRPCCall( request, response );
return;
}
// if ( requestURI.indexOf(RAPLA_JSON_PATH)>= 0) {
// handleJSONCall( request, response, requestURI );
// return;
// }
if ( page == null || page.trim().length() == 0) {
page = "index";
}
servletPage = server.getWebpage( page);
if ( servletPage == null)
{
response.setStatus( 404 );
java.io.PrintWriter out = null;
try
{
out = response.getWriter();
String message = "404: Page " + page + " not found in Rapla context";
out.print(message);
getLogger().getChildLogger("server.html.404").warn( message);
} finally
{
if ( out != null)
{
out.close();
}
}
return;
}
ServletContext servletContext = getServletContext();
servletPage.generatePage( servletContext, request, response);
}
finally
{
try
{
RaplaComponent.unlock( readLock );
}
catch (IllegalMonitorStateException ex)
{
// Released by the restarter
}
try
{
ServletOutputStream outputStream = response.getOutputStream();
outputStream.close();
}
catch (Exception ex)
{
}
}
}
/** serverContainerHint is useful when you have multiple server configurations in one config file e.g. in a test environment*/
public static String serverContainerHint = null;
private void stopServer() {
if ( raplaContainer == null)
{
return;
}
try {
raplaContainer.dispose();
} catch (Exception ex) {
String message = "Error while stopping server ";
getLogger().error(message + ex.getMessage());
}
}
/**
* Disposes of container manager and container instance.
*/
public void destroy()
{
stopServer();
}
public RaplaContext getContext()
{
return raplaContainer.getContext();
}
public Container getContainer()
{
return raplaContainer;
}
public void doImport() throws RaplaException {
ImportExportManager manager = raplaContainer.getContext().lookup(ImportExportManager.class);
manager.doImport();
}
public void doExport() throws RaplaException {
ImportExportManager manager = raplaContainer.getContext().lookup(ImportExportManager.class);
manager.doExport();
}
public Logger getLogger()
{
if ( logger == null)
{
return new RaplaJDKLoggingAdapter().get();
}
return logger;
}
// only for old rapla versions, will be removed in 2.0
private void handleOldRPCCall( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
String clientVersion = request.getParameter("v");
if ( clientVersion != null )
{
String message = getVersionErrorText(request, clientVersion);
response.addHeader("X-Error-Classname", WrongRaplaVersionException.class.getName());
response.addHeader("X-Error-Stacktrace", message );
response.setStatus( 500);
}
else
{
//if ( !serverVersion.equals( clientVersion ) )
String message = getVersionErrorText(request, "");
response.addHeader("X-Error-Stacktrace", message );
RaplaException e1= new RaplaException( message );
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ObjectOutputStream exout = new ObjectOutputStream( outStream);
exout.writeObject( e1);
exout.flush();
exout.close();
byte[] out = outStream.toByteArray();
ServletOutputStream outputStream = null;
try
{
outputStream = response.getOutputStream();
outputStream.write( out );
}
catch (Exception ex)
{
getLogger().error( " Error writing exception back to client " + ex.getMessage());
}
finally
{
if (outputStream != null)
{
outputStream.close();
}
}
response.setStatus( 500);
}
}
// only for old rapla versions, will be removed in 2.0
private String getVersionErrorText(HttpServletRequest request,String clientVersion)
{
String requestUrl = request.getRequestURL().toString();
int indexOf = requestUrl.indexOf( "rpc/");
if (indexOf>=0 )
{
requestUrl = requestUrl.substring( 0, indexOf) ;
}
String message;
try {
I18nBundle i18n = getContext().lookup(RaplaComponent.RAPLA_RESOURCES);
message = i18n.format("error.wrong_rapla_version", clientVersion, serverVersion, requestUrl);
} catch (Exception e) {
message = "Update client from " + clientVersion + " to " + serverVersion + " on " + requestUrl + ". Click on the webstart or applet to update.";
}
return message;
}
// private void handleRPCCall( HttpServletRequest request, HttpServletResponse response, String requestURI )
// {
// boolean dispatcherExceptionThrown = false;
// try
// {
// handleLogin(request, response, requestURI);
// final Map<String,String[]> originalMap = request.getParameterMap();
// final Map<String,String> parameterMap = makeSinglesAndRemoveVersion(originalMap);
// final ServerServiceContainer serverContainer = getServer();
// RemoteServiceDispatcher serviceDispater=serverContainer.getContext().lookup( RemoteServiceDispatcher.class);
// byte[] out;
// try
// {
// out =null;
// //out = serviceDispater.dispatch(remoteSession, methodName, parameterMap);
// }
// catch (Exception ex)
// {
// dispatcherExceptionThrown = true;
// throw ex;
// }
// //String test = new String( out);
// response.setContentType( "text/html; charset=utf-8");
// try
// {
// response.getOutputStream().write( out);
// response.flushBuffer();
// response.getOutputStream().close();
// }
// catch (Exception ex)
// {
// getLogger().error( " Error writing exception back to client " + ex.getMessage());
// }
// }
// catch (Exception e)
// {
// if ( !dispatcherExceptionThrown)
// {
// getLogger().error(e.getMessage(), e);
// }
// try
// {
// String message = e.getMessage();
// String name = e.getClass().getName();
// if ( message == null )
// {
// message = name;
// }
// response.addHeader("X-Error-Stacktrace", message );
// response.addHeader("X-Error-Classname", name);
//// String param = RemoteMethodSerialization.serializeExceptionParam( e);
//// if ( param != null)
//// {
//// response.addHeader("X-Error-Param", param);
//// }
// response.setStatus( 500);
// }
// catch (Exception ex)
// {
// getLogger().error( " Error writing exception back to client " + e.getMessage(), ex);
// }
// }
// }
// private boolean isClientVersionSupported(String clientVersion) {
// // add/remove supported client versions here
// return clientVersion.equals(serverVersion) || clientVersion.equals("@doc.version@") ;
// }
//
// private Map<String,String> makeSinglesAndRemoveVersion( Map<String, String[]> parameterMap )
// {
// TreeMap<String,String> singlesMap = new TreeMap<String,String>();
// for (Iterator<String> it = parameterMap.keySet().iterator();it.hasNext();)
// {
// String key = it.next();
// if ( key.toLowerCase().equals("v"))
// {
// continue;
// }
// String[] values = parameterMap.get( key);
// if ( values != null && values.length > 0 )
// {
// singlesMap.put( key,values[0]);
// }
// else
// {
// singlesMap.put( key,null);
// }
// }
//
// return singlesMap;
//
// }
}
| 04900db4-clienttest | src/org/rapla/server/MainServlet.java | Java | gpl3 | 33,053 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.server;
import org.rapla.entities.Category;
import org.rapla.entities.User;
import org.rapla.framework.RaplaException;
public interface AuthenticationStore {
/** returns, if the user can be authenticated. */
boolean authenticate(String username, String password) throws RaplaException;
/** returns the name of the store */
String getName();
/** Initializes a user entity with the values provided by the authentication store.
* @return <code>true</code> if the new user-object attributes (such as email, name, or groups) differ from the values stored before the method was executed, <code>false</code> otherwise. */
boolean initUser( User user, String username, String password, Category groupRootCategory) throws RaplaException;
}
| 04900db4-clienttest | src/org/rapla/server/AuthenticationStore.java | Java | gpl3 | 1,722 |
<body>
<p>
The server synchronizes and bundles the client requests and
maintains a single storage for all its clients. It also
provides the basic services for the server side plugins.
For instance the notification plugin notifies sends email on a reservation change.
</p>
<p>
The server is also responsible for enforcing
the access policies.
</p>
</body>
| 04900db4-clienttest | src/org/rapla/server/package.html | HTML | gpl3 | 358 |
package org.rapla.server;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
public class HTTPMethodOverrideFilter implements Filter
{
Collection<String> VALID_METHODS = Arrays.asList(new String[] {"GET","POST","DELETE","PUT","PATCH"});
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
MethodOverrideWrapper wrapper = new MethodOverrideWrapper( (HttpServletRequest) request);
chain.doFilter(wrapper, response);
HttpServletResponse hresponse = (HttpServletResponse) response;
hresponse.addHeader("Vary", "X-HTTP-Method-Override");
}
private class MethodOverrideWrapper extends HttpServletRequestWrapper
{
public MethodOverrideWrapper(HttpServletRequest request) {
super(request);
}
@Override
public String getMethod() {
String method = super.getMethod();
String newMethod = getHeader("X-HTTP-Method-Override");
if ("POST".equals(method) && newMethod != null && VALID_METHODS.contains(newMethod))
{
method = newMethod;
}
return method;
}
}
} | 04900db4-clienttest | src/org/rapla/server/HTTPMethodOverrideFilter.java | Java | gpl3 | 1,777 |
package org.rapla.server;
import java.util.Date;
import java.util.TimeZone;
public interface TimeZoneConverter
{
/**
returns the timezone configured via main options, this is per default the system timezon. This timezone is used for ical/exchange import/export
If Rapla will support timezones in the future, than this will be the default timezone for all times. Now its only used on import and export. It works as with system time above. 10:00am GMT+0 is converted to 10:00am of the configured timezone on export and on import all times are converted to GMT+0.
@see TimeZoneConverter#toRaplaTime(TimeZone, long)
*/
TimeZone getImportExportTimeZone();
long fromRaplaTime(TimeZone timeZone,long raplaTime);
long toRaplaTime(TimeZone timeZone,long time);
Date fromRaplaTime(TimeZone timeZone,Date raplaTime);
/**
* converts a common Date object into a Date object that
* assumes that the user (being in the given timezone) is in the
* UTC-timezone by adding the offset between UTC and the given timezone.
*
* <pre>
* Example: If you pass the Date "2013 Jan 15 11:00:00 UTC"
* and the TimeZone "GMT+1", this method will return a Date
* "2013 Jan 15 12:00:00 UTC" which is effectivly 11:00:00 GMT+1
* </pre>
*
* @param timeZone
* the orgin timezone
* @param time
* the Date object in the passed timezone
* @see fromRaplaTime
*/
Date toRaplaTime(TimeZone timeZone,Date time);
} | 04900db4-clienttest | src/org/rapla/server/TimeZoneConverter.java | Java | gpl3 | 1,507 |
package org.rapla.server;
import org.rapla.framework.RaplaContextException;
public interface RemoteMethodFactory<T> {
public T createService(final RemoteSession remoteSession) throws RaplaContextException;
}
| 04900db4-clienttest | src/org/rapla/server/RemoteMethodFactory.java | Java | gpl3 | 227 |
package org.rapla.server;
import org.rapla.framework.TypedComponentRole;
import org.rapla.gui.SwingViewFactory;
import org.rapla.plugin.abstractcalendar.server.HTMLViewFactory;
import org.rapla.servletpages.RaplaMenuGenerator;
import org.rapla.servletpages.ServletRequestPreprocessor;
/** Constant Pool of basic extension points of the Rapla server.
* You can add your extension in the provideService Method of your PluginDescriptor
* <pre>
* container.addContainerProvidedComponent( REPLACE_WITH_EXTENSION_POINT_NAME, REPLACE_WITH_CLASS_IMPLEMENTING_EXTENSION, config);
* </pre>
* @see org.rapla.framework.PluginDescriptor
*/
public class RaplaServerExtensionPoints {
/** add your own views to Rapla, by providing a org.rapla.gui.ViewFactory
* @see SwingViewFactory
* */
public static final Class<HTMLViewFactory> HTML_CALENDAR_VIEW_EXTENSION = HTMLViewFactory.class;
/** A server extension is started automaticaly when the server is up and running and connected to a data store. A class added as service doesn't need to implement a specific interface and is instanciated automaticaly after server start. You can add a RaplaContext parameter to your constructor to get access to the services of rapla.
* */
public static final Class<ServerExtension> SERVER_EXTENSION = ServerExtension.class;
/** you can add servlet pre processer to manipulate request and response before standard processing is
* done by rapla
*/
public static final Class<ServletRequestPreprocessor> SERVLET_REQUEST_RESPONSE_PREPROCESSING_POINT = ServletRequestPreprocessor.class;
/** you can add your own entries on the index page Just add a HTMLMenuEntry to the list
@see RaplaMenuGenerator
* */
public static final TypedComponentRole<RaplaMenuGenerator> HTML_MAIN_MENU_EXTENSION_POINT = new TypedComponentRole<RaplaMenuGenerator>("org.rapla.servletpages");
//public final static TypedComponentRole<List<PluginDescriptor<ServerServiceContainer>>> SERVER_PLUGIN_LIST = new TypedComponentRole<List<PluginDescriptor<ServerServiceContainer>>>("server-plugin-list");
} | 04900db4-clienttest | src/org/rapla/server/RaplaServerExtensionPoints.java | Java | gpl3 | 2,115 |
package org.rapla.server;
/**
* a class implementing server extension is started automatically when the server is up and running and connected to a data store.
*
*/
public interface ServerExtension {
}
| 04900db4-clienttest | src/org/rapla/server/ServerExtension.java | Java | gpl3 | 215 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.server;
import org.rapla.entities.User;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.logger.Logger;
/** An interface to access the SessionInformation. An implementation of
* RemoteSession gets passed to the creation RaplaRemoteService.*/
public interface RemoteSession
{
boolean isAuthentified();
User getUser() throws RaplaContextException;
Logger getLogger();
//String getAccessToken();
}
| 04900db4-clienttest | src/org/rapla/server/RemoteSession.java | Java | gpl3 | 1,385 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 ?, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.server;
import org.rapla.facade.ClientFacade;
import org.rapla.framework.RaplaContext;
/** Encapsulates a StorageOperator. This service is responsible for
<ul>
<li>synchronizing update and remove request from clients and passing
them to the storage-operator</li>
<li>authentification of the clients</li>
<li>notifying subscribed clients when the stored-data has
changed</li>
</ul>
*/
public interface ServerService {
ClientFacade getFacade();
RaplaContext getContext();
}
| 04900db4-clienttest | src/org/rapla/server/ServerService.java | Java | gpl3 | 1,449 |
package org.rapla.server.internal;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.RaplaMainContainer;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaContext;
import org.rapla.servletpages.RaplaPageGenerator;
public class RaplaConfPageGenerator extends RaplaComponent implements RaplaPageGenerator{
public RaplaConfPageGenerator(RaplaContext context) {
super(context);
}
public void generatePage( ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws IOException {
java.io.PrintWriter out = response.getWriter();
response.setContentType("application/xml;charset=utf-8");
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
out.println("<rapla-config>");
Configuration conf = getService(RaplaMainContainer.RAPLA_MAIN_CONFIGURATION);
//<!-- Use this to customize the rapla resources
//<default-bundle>org.rapla.MyResources</default-bundle>
//-->
Configuration localeConf = conf.getChild("locale");
if ( localeConf != null)
{
printConfiguration( out, localeConf);
}
Configuration[] bundles = conf.getChildren("default-bundle");
for ( Configuration bundle: bundles)
{
printConfiguration( out, bundle);
}
String remoteId = null;
Configuration[] clients = conf.getChildren("rapla-client");
for ( Configuration client: clients)
{
if ( client.getAttribute("id", "").equals( "client"))
{
remoteId = client.getChild("facade").getChild("store").getValue( "remote");
printConfiguration( out, client);
break;
}
}
if ( remoteId != null)
{
Configuration[] storages = conf.getChildren("remote-storage");
for ( Configuration storage: storages)
{
if ( storage.getAttribute("id", "").equals( remoteId))
{
printConfiguration( out, storage);
}
}
}
else
{
// Config not found use default
out.println("<rapla-client id=\"client\">");
out.println(" <facade id=\"facade\">");
out.println(" <store>remote</store>");
out.println(" </facade>");
out.println("</rapla-client>");
out.println(" ");
out.println("<remote-storage id=\"remote\">");
out.println(" <server>${download-url}</server>");
out.println("</remote-storage>");
}
out.println(" ");
out.println("</rapla-config>");
out.close();
}
private void printConfiguration(PrintWriter out, Configuration conf) throws IOException {
ConfigurationWriter configurationWriter = new ConfigurationWriter();
BufferedWriter writer = new BufferedWriter( out);
configurationWriter.setWriter( writer);
configurationWriter.printConfiguration( conf);
writer.flush();
}
class ConfigurationWriter extends org.rapla.components.util.xml.XMLWriter
{
private void printConfiguration(Configuration element) throws IOException {
LinkedHashMap<String, String> attr = new LinkedHashMap<String, String>();
String[] attrNames = element.getAttributeNames();
if( null != attrNames )
{
for( int i = 0; i < attrNames.length; i++ )
{
String key = attrNames[ i ];
String value = element.getAttribute( attrNames[ i ], "" );
attr.put(key,value);
}
}
String qName = element.getName();
openTag(qName);
att(attr);
Configuration[] children = element.getChildren();
if (children.length > 0)
{
closeTag();
for( int i = 0; i < children.length; i++ )
{
printConfiguration( children[ i ] );
}
closeElement(qName);
}
else
{
String value = element.getValue( null );
if (null == value)
{
closeElementTag();
}
else
{
closeTagOnLine();
print(value);
closeElementOnLine(qName);
println();
}
}
}
}
}
| 04900db4-clienttest | src/org/rapla/server/internal/RaplaConfPageGenerator.java | Java | gpl3 | 5,094 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.server.internal;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import javax.servlet.http.HttpServletRequest;
import net.fortuna.ical4j.model.TimeZoneRegistry;
import net.fortuna.ical4j.model.TimeZoneRegistryFactory;
import org.rapla.ConnectInfo;
import org.rapla.RaplaMainContainer;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.internal.UserImpl;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.RaplaComponent;
import org.rapla.facade.internal.FacadeImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.internal.ComponentInfo;
import org.rapla.framework.internal.ContainerImpl;
import org.rapla.framework.internal.RaplaLocaleImpl;
import org.rapla.framework.internal.RaplaMetaConfigInfo;
import org.rapla.framework.logger.Logger;
import org.rapla.plugin.export2ical.Export2iCalPlugin;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.rest.gwtjsonrpc.common.ResultImpl;
import org.rapla.rest.gwtjsonrpc.common.VoidResult;
import org.rapla.rest.gwtjsonrpc.server.SignedToken;
import org.rapla.rest.gwtjsonrpc.server.ValidToken;
import org.rapla.rest.gwtjsonrpc.server.XsrfException;
import org.rapla.rest.server.RaplaAPIPage;
import org.rapla.rest.server.RaplaAuthRestPage;
import org.rapla.rest.server.RaplaDynamicTypesRestPage;
import org.rapla.rest.server.RaplaEventsRestPage;
import org.rapla.rest.server.RaplaResourcesRestPage;
import org.rapla.server.AuthenticationStore;
import org.rapla.server.RaplaKeyStorage;
import org.rapla.server.RaplaServerExtensionPoints;
import org.rapla.server.RemoteMethodFactory;
import org.rapla.server.RemoteSession;
import org.rapla.server.ServerService;
import org.rapla.server.ServerServiceContainer;
import org.rapla.server.TimeZoneConverter;
import org.rapla.servletpages.DefaultHTMLMenuEntry;
import org.rapla.servletpages.RaplaAppletPageGenerator;
import org.rapla.servletpages.RaplaIndexPageGenerator;
import org.rapla.servletpages.RaplaJNLPPageGenerator;
import org.rapla.servletpages.RaplaPageGenerator;
import org.rapla.servletpages.RaplaStatusPageGenerator;
import org.rapla.servletpages.RaplaStorePage;
import org.rapla.storage.CachableStorageOperator;
import org.rapla.storage.RaplaSecurityException;
import org.rapla.storage.StorageOperator;
import org.rapla.storage.StorageUpdateListener;
import org.rapla.storage.UpdateResult;
import org.rapla.storage.dbrm.LoginCredentials;
import org.rapla.storage.dbrm.LoginTokens;
import org.rapla.storage.dbrm.RemoteConnectionInfo;
import org.rapla.storage.dbrm.RemoteMethodStub;
import org.rapla.storage.dbrm.RemoteServer;
import org.rapla.storage.dbrm.RemoteStorage;
import org.rapla.storage.impl.server.LocalAbstractCachableOperator;
/** Default implementation of StorageService.
* <p>Sample configuration 1:
<pre>
<storage id="storage" >
<store>file</store>
</storage>
</pre>
* The store value contains the id of a storage-component.
* Storage-Components are all components that implement the
* <code>CachableStorageOperator<code> interface.
*
* </p>
@see ServerService
*/
public class ServerServiceImpl extends ContainerImpl implements StorageUpdateListener, ServerServiceContainer, ServerService, ShutdownService, RemoteMethodFactory<RemoteServer>,RemoteMethodStub
{
@SuppressWarnings("rawtypes")
public static Class<RemoteMethodFactory> REMOTE_METHOD_FACTORY = RemoteMethodFactory.class;
static Class<RaplaPageGenerator> SERVLET_PAGE_EXTENSION = RaplaPageGenerator.class;
protected CachableStorageOperator operator;
protected I18nBundle i18n;
List<PluginDescriptor<ServerServiceContainer>> pluginList;
ClientFacade facade;
private AuthenticationStore authenticationStore;
SignedToken accessTokenSigner;
SignedToken refreshTokenSigner;
RemoteSessionImpl standaloneSession;
ShutdownService shutdownService;
// 5 Hours until the token expires
int accessTokenValiditySeconds = 300 * 60;
public ServerServiceImpl( RaplaContext parentContext, Configuration config, Logger logger) throws RaplaException
{
super( parentContext, config, logger );
addContainerProvidedComponent( TimeZoneConverter.class, TimeZoneConverterImpl.class);
i18n = parentContext.lookup( RaplaComponent.RAPLA_RESOURCES );
Configuration login = config.getChild( "login" );
String username = login.getChild( "username" ).getValue( null );
String password = login.getChild( "password" ).getValue( "" );
RaplaContext context = getContext();
if ( config.getChildren("facade").length >0 )
{
facade = m_context.lookup(ClientFacade.class);
}
else
{
// for old raplaserver.xconf
facade = new FacadeImpl( context, config, getLogger().getChildLogger("serverfacade") );
}
operator = (CachableStorageOperator) facade.getOperator();
addContainerProvidedComponentInstance( ServerService.class, this);
addContainerProvidedComponentInstance( ShutdownService.class, this);
addContainerProvidedComponentInstance( ServerServiceContainer.class, this);
addContainerProvidedComponentInstance( CachableStorageOperator.class, operator );
addContainerProvidedComponentInstance( StorageOperator.class, operator );
addContainerProvidedComponentInstance( ClientFacade.class, facade );
addContainerProvidedComponent( SecurityManager.class, SecurityManager.class );
addRemoteMethodFactory(RemoteStorage.class,RemoteStorageImpl.class, null);
addContainerProvidedComponentInstance( REMOTE_METHOD_FACTORY, this, RemoteServer.class.getName() );
// adds 5 basic pages to the webapplication
addWebpage( "server",RaplaStatusPageGenerator.class);
addWebpage( "json",RaplaAPIPage.class);
addWebpage( "resources",RaplaResourcesRestPage.class);
addWebpage( "events",RaplaEventsRestPage.class);
addWebpage( "dynamictypes",RaplaDynamicTypesRestPage.class);
addWebpage( "auth",RaplaAuthRestPage.class);
addWebpage( "index",RaplaIndexPageGenerator.class );
addWebpage( "raplaclient.jnlp",RaplaJNLPPageGenerator.class );
addWebpage( "raplaclient",RaplaJNLPPageGenerator.class );
addWebpage( "raplaapplet",RaplaAppletPageGenerator.class );
addWebpage( "store",RaplaStorePage.class);
addWebpage( "raplaclient.xconf",RaplaConfPageGenerator.class );
addWebpage( "raplaclient.xconf",RaplaConfPageGenerator.class);
I18nBundle i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
// Index page menu
addContainerProvidedComponentInstance( RaplaServerExtensionPoints.HTML_MAIN_MENU_EXTENSION_POINT, new DefaultHTMLMenuEntry(context,i18n.getString( "start_rapla_with_webstart" ),"rapla/raplaclient.jnlp") );
addContainerProvidedComponentInstance( RaplaServerExtensionPoints.HTML_MAIN_MENU_EXTENSION_POINT, new DefaultHTMLMenuEntry(context,i18n.getString( "start_rapla_with_applet" ),"rapla?page=raplaapplet") );
addContainerProvidedComponentInstance( RaplaServerExtensionPoints.HTML_MAIN_MENU_EXTENSION_POINT, new DefaultHTMLMenuEntry(context,i18n.getString( "server_status" ),"rapla?page=server") );
standaloneSession = new RemoteSessionImpl(getContext(), "session");
operator.addStorageUpdateListener( this );
if ( username != null )
operator.connect( new ConnectInfo(username, password.toCharArray()));
else
operator.connect();
Set<String> pluginNames;
//List<PluginDescriptor<ClientServiceContainer>> pluginList;
try {
pluginNames = context.lookup( RaplaMainContainer.PLUGIN_LIST);
} catch (RaplaContextException ex) {
throw new RaplaException (ex );
}
pluginList = new ArrayList<PluginDescriptor<ServerServiceContainer>>( );
Logger pluginLogger = getLogger().getChildLogger("plugin");
for ( String plugin:pluginNames)
{
try {
boolean found = false;
try {
Class<?> componentClass = ServerServiceImpl.class.getClassLoader().loadClass( plugin );
Method[] methods = componentClass.getMethods();
for ( Method method:methods)
{
if ( method.getName().equals("provideServices"))
{
Class<?> type = method.getParameterTypes()[0];
if (ServerServiceContainer.class.isAssignableFrom(type))
{
found = true;
}
}
}
} catch (ClassNotFoundException e1) {
} catch (Exception e1) {
getLogger().warn(e1.getMessage());
continue;
}
if ( found )
{
@SuppressWarnings("unchecked")
PluginDescriptor<ServerServiceContainer> descriptor = (PluginDescriptor<ServerServiceContainer>) instanciate(plugin, null, logger);
pluginList.add(descriptor);
pluginLogger.info("Installed plugin "+plugin);
}
} catch (RaplaContextException e) {
if (e.getCause() instanceof ClassNotFoundException) {
pluginLogger.error("Could not instanciate plugin "+ plugin, e);
}
}
}
addContainerProvidedComponent(RaplaKeyStorage.class, RaplaKeyStorageImpl.class);
try {
RaplaKeyStorage keyStorage = getContext().lookup( RaplaKeyStorage.class);
String secretKey = keyStorage.getRootKeyBase64();
accessTokenSigner = new SignedToken(accessTokenValiditySeconds , secretKey);
refreshTokenSigner = new SignedToken(-1 , secretKey);
} catch (Exception e) {
throw new RaplaException( e.getMessage(), e);
}
Preferences preferences = operator.getPreferences( null, true );
//RaplaConfiguration encryptionConfig = preferences.getEntry(EncryptionService.CONFIG);
//addRemoteMethodFactory( EncryptionService.class, EncryptionServiceFactory.class);
RaplaConfiguration entry = preferences.getEntry(RaplaComponent.PLUGIN_CONFIG);
String importExportTimeZone = TimeZone.getDefault().getID();
if ( entry != null)
{
Configuration find = entry.find("class", Export2iCalPlugin.PLUGIN_CLASS);
if ( find != null)
{
String timeZone = find.getChild("TIMEZONE").getValue( null);
if ( timeZone != null && !timeZone.equals("Etc/UTC"))
{
importExportTimeZone = timeZone;
}
}
}
String timezoneId = preferences.getEntryAsString(RaplaMainContainer.TIMEZONE, importExportTimeZone);
RaplaLocale raplaLocale = context.lookup(RaplaLocale.class);
TimeZoneConverter importExportLocale = context.lookup(TimeZoneConverter.class);
try {
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
TimeZone timeZone = registry.getTimeZone(timezoneId);
((RaplaLocaleImpl) raplaLocale).setImportExportTimeZone( timeZone);
((TimeZoneConverterImpl) importExportLocale).setImportExportTimeZone( timeZone);
if ( operator instanceof LocalAbstractCachableOperator)
{
((LocalAbstractCachableOperator) operator).setTimeZone( timeZone);
}
} catch (Exception rc) {
getLogger().error("Timezone " + timezoneId + " not found. " + rc.getMessage() + " Using system timezone " + importExportLocale.getImportExportTimeZone());
}
initializePlugins( pluginList, preferences );
if ( context.has( AuthenticationStore.class ) )
{
try
{
authenticationStore = context.lookup( AuthenticationStore.class );
getLogger().info( "Using AuthenticationStore " + authenticationStore.getName() );
}
catch ( RaplaException ex)
{
getLogger().error( "Can't initialize configured authentication store. Using default authentication." , ex);
}
}
// Provider<EntityStore> storeProvider = new Provider<EntityStore>()
// {
// public EntityStore get() {
// return new EntityStore(operator, operator.getSuperCategory());
// }
//
// };
}
@Override
protected Map<String,ComponentInfo> getComponentInfos() {
return new RaplaMetaConfigInfo();
}
public <T> void addRemoteMethodFactory(Class<T> role, Class<? extends RemoteMethodFactory<T>> factory) {
addRemoteMethodFactory(role, factory, null);
}
public <T> void addRemoteMethodFactory(Class<T> role, Class<? extends RemoteMethodFactory<T>> factory, Configuration configuration) {
addContainerProvidedComponent(REMOTE_METHOD_FACTORY,factory, role.getName(), configuration);
}
protected RemoteMethodFactory<?> getRemoteMethod(String interfaceName) throws RaplaContextException {
RemoteMethodFactory<?> factory = lookup( REMOTE_METHOD_FACTORY ,interfaceName);
return factory;
}
public <T extends RaplaPageGenerator> void addWebpage(String pagename,
Class<T> pageClass) {
addWebpage(pagename, pageClass, null);
}
public <T extends RaplaPageGenerator> void addWebpage(String pagename,
Class<T> pageClass, Configuration configuration) {
String lowerCase = pagename.toLowerCase();
addContainerProvidedComponent(SERVLET_PAGE_EXTENSION,pageClass, lowerCase, configuration);
}
public RaplaPageGenerator getWebpage(String page) {
try
{
String lowerCase = page.toLowerCase();
RaplaPageGenerator factory = lookup( SERVLET_PAGE_EXTENSION ,lowerCase);
return factory;
} catch (RaplaContextException ex)
{
Throwable cause = ex.getCause();
if ( cause != null)
{
getLogger().error(cause.getMessage(),cause);
}
return null;
}
}
public void updateError( RaplaException ex )
{
if ( getLogger() != null )
getLogger().error( ex.getMessage(), ex );
try
{
stop();
}
catch ( Exception e )
{
if ( getLogger() != null )
getLogger().error( e.getMessage() );
}
}
public void objectsUpdated(UpdateResult evt) {
}
/**
* @see org.rapla.server.ServerService#getFacade()
*/
public ClientFacade getFacade()
{
return facade;
}
protected void initializePlugins( List<PluginDescriptor<ServerServiceContainer>> pluginList, Preferences preferences ) throws RaplaException
{
RaplaConfiguration raplaConfig = preferences.getEntry( RaplaComponent.PLUGIN_CONFIG);
// Add plugin configs
for ( Iterator<PluginDescriptor<ServerServiceContainer>> it = pluginList.iterator(); it.hasNext(); )
{
PluginDescriptor<ServerServiceContainer> pluginDescriptor = it.next();
String pluginClassname = pluginDescriptor.getClass().getName();
Configuration pluginConfig = null;
if ( raplaConfig != null )
{
// TODO should be replaced with a more desciptve approach instead of looking for the config by guessing from the package name
pluginConfig = raplaConfig.find( "class", pluginClassname );
// If no plugin config for server is found look for plugin config for client plugin
if ( pluginConfig == null )
{
pluginClassname = pluginClassname.replaceAll("ServerPlugin", "Plugin");
pluginClassname = pluginClassname.replaceAll(".server.", ".client.");
pluginConfig = raplaConfig.find( "class", pluginClassname );
if ( pluginConfig == null)
{
pluginClassname = pluginClassname.replaceAll(".client.", ".");
pluginConfig = raplaConfig.find( "class", pluginClassname );
}
}
}
if ( pluginConfig == null )
{
pluginConfig = new DefaultConfiguration( "plugin" );
}
pluginDescriptor.provideServices( this, pluginConfig );
}
lookupServicesFor(RaplaServerExtensionPoints.SERVER_EXTENSION );
}
private void stop()
{
boolean wasConnected = operator.isConnected();
operator.removeStorageUpdateListener( this );
Logger logger = getLogger();
try
{
operator.disconnect();
}
catch (RaplaException e)
{
logger.error( "Could not disconnect operator " , e);
}
finally
{
}
if ( wasConnected )
{
logger.info( "Storage service stopped" );
}
}
public void dispose()
{
stop();
super.dispose();
}
public StorageOperator getOperator()
{
return operator;
}
public void storageDisconnected(String message)
{
try
{
stop();
}
catch ( Exception e )
{
if ( getLogger() != null )
getLogger().error( e.getMessage() );
}
}
// public byte[] dispatch(RemoteSession remoteSession, String methodName, Map<String,String> args ) throws Exception
// {
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// int indexRole = methodName.indexOf( "/" );
// String interfaceName = RemoteStorage.class.getName();
// if ( indexRole > 0 )
// {
// interfaceName = methodName.substring( 0, indexRole );
// methodName = methodName.substring( indexRole + 1 );
// }
// try
// {
// final Object serviceUncasted;
// {
// Logger debugLogger = getLogger().getChildLogger(interfaceName+"."+ methodName + ".arguments" );
// if ( debugLogger.isDebugEnabled())
// {
// debugLogger.debug(args.toString());
// }
// }
// RemoteMethodFactory<?> factory = getRemoteMethod(interfaceName);
// Class<?> interfaceClass = Class.forName( interfaceName);
//
// serviceUncasted = factory.createService( remoteSession);
// Method method = findMethod( interfaceClass, methodName, args);
// if ( method == null)
// {
// throw new RaplaException("Can't find method with name " + methodName);
// }
// Class<?>[] parameterTypes = method.getParameterTypes();
// Object[] convertedArgs = remoteMethodService.deserializeArguments(parameterTypes,args);
// Object result = null;
// try
// {
// result = method.invoke( serviceUncasted, convertedArgs);
// }
// catch (InvocationTargetException ex)
// {
// Throwable cause = ex.getCause();
// if (cause instanceof RaplaException)
// {
// throw (RaplaException)cause;
// }
// else
// {
// throw new RaplaException( cause.getMessage(), cause );
// }
// }
// User user = remoteSession.isAuthentified() ? remoteSession.getUser() : null;
//
// if ( result != null)
// {
// BufferedWriter outWriter = new BufferedWriter( new OutputStreamWriter( out,"utf-8"));
// Appendable appendable = outWriter;
// // we don't trasmit password settings in the general preference entry when the user is not an admin
// remoteMethodService.serializeReturnValue(user, result, appendable);
// outWriter.flush();
// }
// else
// {
//// BufferedWriter outWriter = new BufferedWriter( new OutputStreamWriter( out,"utf-8"));
//// outWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
//// outWriter.write("/n");
//// outWriter.write("<data/>");
//// outWriter.flush();
// }
// out.flush();
// }
// catch (EntityNotFoundException ex)
// {
// throw ex;
// }
// catch (DependencyException ex)
// {
// throw ex;
// }
// catch (RaplaNewVersionException ex)
// {
// throw ex;
// }
// catch (RaplaSecurityException ex)
// {
// getLogger().getChildLogger( interfaceName + "." + methodName).warn( ex.getMessage());
// throw ex;
// }
// catch ( Exception ex )
// {
// getLogger().getChildLogger( interfaceName + "." + methodName).error( ex.getMessage(), ex );
// throw ex;
// }
// out.close();
// return out.toByteArray();
// }
// private Method findMethod( Class inter,String methodName,Map<String,String> args)
// {
// Method[] methods = inter.getMethods();
// for ( Method method: methods)
// {
// if ( method.getName().equals( methodName) )
// {
// Class<?>[] parameterTypes = method.getParameterTypes();
// Annotation[][] parameterAnnotations = method.getParameterAnnotations();
// int length = parameterTypes.length;
// // Map
// //for ( int i=0;)
// if (parameterTypes.length == args.size())
// return method;
// }
// }
// return null;
// }
public RemoteServer createService(final RemoteSession session) {
return new RemoteServer() {
public Logger getLogger()
{
if ( session != null)
{
return session.getLogger();
}
else
{
return ServerServiceImpl.this.getLogger();
}
}
@Override
public void setConnectInfo(RemoteConnectionInfo info) {
}
@Override
public FutureResult<VoidResult> logout()
{
try
{
if ( session != null)
{
if ( session.isAuthentified())
{
User user = session.getUser();
if ( user != null)
{
getLogger().getChildLogger("login").info( "Request Logout " + user.getUsername());
}
((RemoteSessionImpl)session).logout();
}
}
}
catch (RaplaException ex)
{
return new ResultImpl<VoidResult>(ex);
}
return ResultImpl.VOID;
}
@Override
public FutureResult<LoginTokens> login( String username, String password, String connectAs )
{
LoginCredentials loginCredentials = new LoginCredentials(username,password,connectAs);
return auth(loginCredentials);
}
@Override
public FutureResult<LoginTokens> auth( LoginCredentials credentials )
{
try
{
User user;
String username = credentials.getUsername();
String password = credentials.getPassword();
String connectAs = credentials.getConnectAs();
boolean isStandalone = getContext().has( RemoteMethodStub.class);
if ( isStandalone)
{
String toConnect = connectAs != null && !connectAs.isEmpty() ? connectAs : username;
// don't check passwords in standalone version
user = operator.getUser( toConnect);
if ( user == null)
{
throw new RaplaSecurityException(i18n.getString("error.login"));
}
standaloneSession.setUser( user);
}
else
{
Logger logger = getLogger().getChildLogger("login");
user = authenticate(username, password, connectAs, logger);
((RemoteSessionImpl)session).setUser( user);
}
if ( connectAs != null && connectAs.length()> 0)
{
if (!operator.getUser( username).isAdmin())
{
throw new SecurityException("Non admin user is requesting change user permission!");
}
}
FutureResult<LoginTokens> generateAccessToken = generateAccessToken(user);
return generateAccessToken;
} catch (RaplaException ex) {
return new ResultImpl<LoginTokens>(ex);
}
}
private FutureResult<LoginTokens> generateAccessToken(User user) throws RaplaException {
try
{
String userId = user.getId();
Date now = operator.getCurrentTimestamp();
Date validUntil = new Date(now.getTime() + 1000 * accessTokenValiditySeconds);
String signedToken = accessTokenSigner.newToken( userId, now);
return new ResultImpl<LoginTokens>(new LoginTokens( signedToken, validUntil));
} catch (Exception e) {
throw new RaplaException(e.getMessage());
}
}
@Override
public FutureResult<String> getRefreshToken()
{
try
{
User user = getValidUser(session);
RaplaKeyStorage keyStore = getContext().lookup(RaplaKeyStorage.class);
Collection<String> apiKeys = keyStore.getAPIKeys(user);
String refreshToken;
if ( apiKeys.size() == 0)
{
refreshToken = null;
}
else
{
refreshToken = apiKeys.iterator().next();
}
return new ResultImpl<String>(refreshToken);
} catch (RaplaException ex) {
return new ResultImpl<String>(ex);
}
}
@Override
public FutureResult<String> regenerateRefreshToken()
{
try
{
User user = getValidUser(session);
RaplaKeyStorage keyStore = getContext().lookup(RaplaKeyStorage.class);
Date now = operator.getCurrentTimestamp();
String generatedAPIKey = refreshTokenSigner.newToken(user.getId(), now);
keyStore.storeAPIKey(user, "refreshToken",generatedAPIKey);
return new ResultImpl<String>(generatedAPIKey);
} catch (Exception ex) {
return new ResultImpl<String>(ex);
}
}
@Override
public FutureResult<LoginTokens> refresh(String refreshToken)
{
try
{
User user = getUser(refreshToken, refreshTokenSigner);
RaplaKeyStorage keyStore = getContext().lookup(RaplaKeyStorage.class);
Collection<String> apiKeys = keyStore.getAPIKeys(user);
if ( !apiKeys.contains( refreshToken))
{
throw new RaplaSecurityException("refreshToken not valid");
}
FutureResult<LoginTokens> generateAccessToken = generateAccessToken(user);
return generateAccessToken;
} catch (RaplaException ex) {
return new ResultImpl<LoginTokens>(ex);
}
}
public User getValidUser(final RemoteSession session) throws RaplaContextException, RaplaSecurityException {
User user = session.getUser();
if ( user == null)
{
throw new RaplaSecurityException(i18n.getString("error.login"));
}
return user;
}
};
}
public User authenticate(String username, String password,String connectAs, Logger logger) throws RaplaException,RaplaSecurityException {
User user;
String toConnect = connectAs != null && !connectAs.isEmpty() ? connectAs : username;
logger.info( "User '" + username + "' is requesting login." );
if ( authenticationStore != null )
{
logger.info("Checking external authentifiction for user " + username);
boolean authenticateExternal;
try
{
authenticateExternal = authenticationStore.authenticate( username, password );
}
catch (RaplaException ex)
{
authenticateExternal= false;
getLogger().error(ex.getMessage(), ex);
}
if (authenticateExternal)
{
logger.info("Successfull for " + username);
//@SuppressWarnings("unchecked")
user = operator.getUser( username );
if ( user == null )
{
logger.info("User not found in localstore. Creating new Rapla user " + username);
Date now = operator.getCurrentTimestamp();
UserImpl newUser = new UserImpl(now,now);
newUser.setId( operator.createIdentifier( User.TYPE,1 )[0] );
user = newUser;
}
else
{
Set<Entity>singleton = Collections.singleton((Entity)user);
Collection<Entity> editList = operator.editObjects( singleton, null );
user = (User)editList.iterator().next();
}
boolean initUser ;
try
{
Category groupCategory = operator.getSuperCategory().getCategory( Permission.GROUP_CATEGORY_KEY );
logger.info("Looking for update for rapla user '" + username + "' from external source.");
initUser = authenticationStore.initUser( (User) user, username, password, groupCategory );
} catch (RaplaSecurityException ex){
throw new RaplaSecurityException(i18n.getString("error.login"));
}
if ( initUser )
{
logger.info("Udating rapla user '" + username + "' from external source.");
List<Entity>storeList = new ArrayList<Entity>(1);
storeList.add( user);
List<Entity>removeList = Collections.emptyList();
operator.storeAndRemove( storeList, removeList, null );
}
else
{
logger.info("User '" + username + "' already up to date");
}
}
else
{
logger.info("Now trying to authenticate with local store '" + username + "'");
operator.authenticate( username, password );
}
// do nothing
} // if the authenticationStore can't authenticate the user is checked against the local database
else
{
logger.info("Check password for " + username);
operator.authenticate( username, password );
}
if ( connectAs != null && connectAs.length() > 0)
{
logger.info("Successfull login for '" + username +"' acts as user '" + connectAs + "'");
}
else
{
logger.info("Successfull login for '" + username + "'");
}
user = operator.getUser(toConnect);
if ( user == null)
{
throw new RaplaException("User with username '" + toConnect + "' not found");
}
return user;
}
public void setShutdownService(ShutdownService shutdownService) {
this.shutdownService = shutdownService;
}
public <T> T getWebserviceLocalStub(final Class<T> a) throws RaplaContextException {
@SuppressWarnings("unchecked")
RemoteMethodFactory<T> factory =lookup( REMOTE_METHOD_FACTORY ,a.getName());
T service = factory.createService( standaloneSession);
return service;
}
public void shutdown(boolean restart) {
if ( shutdownService != null)
{
shutdownService.shutdown(restart);
}
else
{
getLogger().error("Shutdown service not set");
}
}
public RemoteSession getRemoteSession(HttpServletRequest request) throws RaplaException {
User user = getUser(request);
RemoteSessionImpl remoteSession = new RemoteSessionImpl(getContext(), user != null ? user.getUsername() : "anonymous");
remoteSession.setUser( (User) user);
// remoteSession.setAccessToken( token );
return remoteSession;
}
public User getUser(HttpServletRequest request) throws RaplaException {
String token = request.getHeader("Authorization");
if ( token != null)
{
String bearerStr = "bearer";
int bearer = token.toLowerCase().indexOf(bearerStr);
if ( bearer >= 0)
{
token = token.substring( bearer + bearerStr.length()).trim();
}
}
else
{
token = request.getParameter("access_token");
}
User user = null;
if ( token == null)
{
String username = request.getParameter("username");
if ( username != null)
{
user = getUserWithoutPassword(username);
}
}
if ( user == null)
{
user = getUser( token, accessTokenSigner);
}
return user;
}
@SuppressWarnings("unchecked")
@Override
public <T> T createWebservice(Class<T> role, HttpServletRequest request) throws RaplaException
{
RemoteMethodFactory<T> remoteMethod = (RemoteMethodFactory<T>) getRemoteMethod( role.getName());
RemoteSession remoteSession = getRemoteSession(request);
return remoteMethod.createService(remoteSession);
}
@Override
public boolean hasWebservice(String interfaceName) {
try {
lookup( REMOTE_METHOD_FACTORY ,interfaceName);
} catch (RaplaContextException e) {
return false;
}
return true;
}
private User getUserWithoutPassword(String username) throws RaplaException
{
String connectAs = null;
User user = authenticate(username, "", connectAs, getLogger());
return user;
}
private User getUser(String tokenString,SignedToken tokenSigner) throws RaplaException
{
if ( tokenString == null)
{
return null;
}
final int s = tokenString.indexOf('$');
if (s <= 0) {
return null;
}
final String recvText = tokenString.substring(s + 1);
try {
Date now = operator.getCurrentTimestamp();
ValidToken checkToken = tokenSigner.checkToken(tokenString, recvText, now);
if ( checkToken == null)
{
throw new RaplaSecurityException(RemoteStorage.USER_WAS_NOT_AUTHENTIFIED + " InvalidToken " + tokenString);
}
} catch (XsrfException e) {
throw new RaplaSecurityException(e.getMessage(), e);
}
String userId = recvText;
User user = operator.resolve( userId, User.class);
return user;
}
}
| 04900db4-clienttest | src/org/rapla/server/internal/ServerServiceImpl.java | Java | gpl3 | 37,609 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.server.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import org.rapla.RaplaMainContainer;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.ParseDateException;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.components.util.TimeInterval;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.Category;
import org.rapla.entities.DependencyException;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.configuration.internal.PreferencesImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.internal.AppointmentImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.Classifiable;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.internal.DynamicTypeImpl;
import org.rapla.entities.storage.EntityReferencer;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.Conflict;
import org.rapla.facade.RaplaComponent;
import org.rapla.facade.internal.ConflictImpl;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.Disposable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.TypedComponentRole;
import org.rapla.framework.logger.Logger;
import org.rapla.plugin.mail.MailPlugin;
import org.rapla.plugin.mail.server.MailInterface;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.rest.gwtjsonrpc.common.ResultImpl;
import org.rapla.rest.gwtjsonrpc.common.VoidResult;
import org.rapla.server.AuthenticationStore;
import org.rapla.server.RemoteMethodFactory;
import org.rapla.server.RemoteSession;
import org.rapla.storage.CachableStorageOperator;
import org.rapla.storage.PreferencePatch;
import org.rapla.storage.RaplaNewVersionException;
import org.rapla.storage.RaplaSecurityException;
import org.rapla.storage.StorageOperator;
import org.rapla.storage.StorageUpdateListener;
import org.rapla.storage.UpdateEvent;
import org.rapla.storage.UpdateResult;
import org.rapla.storage.UpdateResult.Change;
import org.rapla.storage.UpdateResult.Remove;
import org.rapla.storage.dbrm.RemoteConnectionInfo;
import org.rapla.storage.dbrm.RemoteStorage;
import org.rapla.storage.impl.EntityStore;
/** Provides an adapter for each client-session to their shared storage operator
* Handles security and synchronizing aspects.
*/
public class RemoteStorageImpl implements RemoteMethodFactory<RemoteStorage>, StorageUpdateListener, Disposable {
CachableStorageOperator operator;
protected SecurityManager security;
RaplaContext context;
int cleanupPointVersion = 0;
protected AuthenticationStore authenticationStore;
Logger logger;
ClientFacade facade;
RaplaLocale raplaLocale;
//private Map<String,Long> updateMap = new HashMap<String,Long>();
//private Map<String,Long> removeMap = new HashMap<String,Long>();
public RemoteStorageImpl(RaplaContext context) throws RaplaException {
this.context = context;
this.logger = context.lookup( Logger.class);
facade = context.lookup( ClientFacade.class);
raplaLocale = context.lookup( RaplaLocale.class);
operator = (CachableStorageOperator)facade.getOperator();
operator.addStorageUpdateListener( this);
security = context.lookup( SecurityManager.class);
if ( context.has( AuthenticationStore.class ) )
{
try
{
authenticationStore = context.lookup( AuthenticationStore.class );
getLogger().info( "Using AuthenticationStore " + authenticationStore.getName() );
}
catch ( RaplaException ex)
{
getLogger().error( "Can't initialize configured authentication store. Using default authentication." , ex);
}
}
Long repositoryVersion = operator.getCurrentTimestamp().getTime();
// Invalidate all clients
for ( User user:operator.getUsers())
{
String userId = user.getId();
needResourceRefresh.put( userId, repositoryVersion);
needConflictRefresh.put( userId, repositoryVersion);
}
synchronized (invalidateMap)
{
invalidateMap.put( repositoryVersion, new TimeInterval( null, null));
}
}
public Logger getLogger() {
return logger;
}
public I18nBundle getI18n() throws RaplaException {
return context.lookup(RaplaComponent.RAPLA_RESOURCES);
}
static UpdateEvent createTransactionSafeUpdateEvent( UpdateResult updateResult )
{
User user = updateResult.getUser();
UpdateEvent saveEvent = new UpdateEvent();
if ( user != null )
{
saveEvent.setUserId( user.getId() );
}
{
Iterator<UpdateResult.Add> it = updateResult.getOperations( UpdateResult.Add.class );
while ( it.hasNext() )
{
Entity newEntity = (Entity) ( it.next() ).getNew();
saveEvent.putStore( newEntity );
}
}
{
Iterator<UpdateResult.Change> it = updateResult.getOperations( UpdateResult.Change.class );
while ( it.hasNext() )
{
Entity newEntity = (Entity) ( it.next() ).getNew();
saveEvent.putStore( newEntity );
}
}
{
Iterator<UpdateResult.Remove> it = updateResult.getOperations( UpdateResult.Remove.class );
while ( it.hasNext() )
{
Entity removeEntity = (Entity) (it.next() ).getCurrent();
saveEvent.putRemove( removeEntity );
}
}
return saveEvent;
}
private Map<String,Long> needConflictRefresh = new ConcurrentHashMap<String,Long>();
private Map<String,Long> needResourceRefresh = new ConcurrentHashMap<String,Long>();
private SortedMap<Long, TimeInterval> invalidateMap = Collections.synchronizedSortedMap(new TreeMap<Long,TimeInterval>());
// Implementation of StorageUpdateListener
public void objectsUpdated( UpdateResult evt )
{
long repositoryVersion = operator.getCurrentTimestamp().getTime();
// notify the client for changes
TimeInterval invalidateInterval = evt.calulateInvalidateInterval();
if ( invalidateInterval != null)
{
long oneHourAgo = repositoryVersion - DateTools.MILLISECONDS_PER_HOUR;
// clear the entries that are older than one hour and replace them with a clear_all
// that is set one hour in the past, to refresh all clients that have not been connected in the past hour on the next connect
synchronized ( invalidateMap)
{
SortedMap<Long, TimeInterval> headMap = invalidateMap.headMap( oneHourAgo);
if ( !headMap.isEmpty())
{
Set<Long> toDelete = new TreeSet<Long>(headMap.keySet());
for ( Long key:toDelete)
{
invalidateMap.remove(key);
}
invalidateMap.put(oneHourAgo, new TimeInterval( null, null));
}
invalidateMap.put(repositoryVersion, invalidateInterval);
}
}
UpdateEvent safeResultEvent = createTransactionSafeUpdateEvent( evt );
if ( getLogger().isDebugEnabled() )
getLogger().debug( "Storage was modified. Calling notify." );
boolean addAllUsersToConflictRefresh = false;
for ( Iterator<Entity>it = safeResultEvent.getStoreObjects().iterator(); it.hasNext(); )
{
Entity obj = it.next();
if (!isTransferedToClient(obj))
{
continue;
}
if ( obj instanceof Conflict)
{
addAllUsersToConflictRefresh = true;
}
if ( obj instanceof DynamicType)
{
addAllUsersToConflictRefresh = true;
}
// RaplaType<?> raplaType = obj.getRaplaType();
// if (raplaType == Conflict.TYPE)
// {
// String id = obj.getId();
// updateMap.remove( id );
// removeMap.remove( id );
// updateMap.put( id, new Long( repositoryVersion ) );
// }
}
// now we check if a the resources have changed in a way that a user needs to refresh all resources. That is the case, when
// someone changes the permissions on one or more resource and that affects the visibility of that resource to a user,
// so its either pushed to the client or removed from it.
Set<Permission> invalidatePermissions = new HashSet<Permission>();
boolean addAllUsersToResourceRefresh = false;
{
Iterator<Remove> operations = evt.getOperations(UpdateResult.Remove.class);
while ( operations.hasNext())
{
Remove operation = operations.next();
Entity obj = operation.getCurrent();
if ( obj instanceof User)
{
String userId = obj.getId();
needConflictRefresh.remove( userId);
needResourceRefresh.remove( userId);
}
if (!isTransferedToClient(obj))
{
continue;
}
if ( obj instanceof Allocatable)
{
Permission[] oldPermissions = ((Allocatable)obj).getPermissions();
invalidatePermissions.addAll( Arrays.asList( oldPermissions));
}
if ( obj instanceof DynamicType)
{
addAllUsersToResourceRefresh = true;
addAllUsersToConflictRefresh = true;
}
if ( obj instanceof Conflict)
{
addAllUsersToConflictRefresh = true;
}
// if ( obj instanceof Conflict)
// {
// String id = obj.getId();
// updateMap.remove( id );
// removeMap.remove( id );
// removeMap.put( id, new Long( repositoryVersion ) );
// }
}
}
if (addAllUsersToResourceRefresh || addAllUsersToConflictRefresh)
{
invalidateAll(repositoryVersion, addAllUsersToResourceRefresh,addAllUsersToConflictRefresh);
}
else
{
invalidate(evt, repositoryVersion, invalidatePermissions);
}
}
private void invalidateAll(long repositoryVersion, boolean resourceRefreh, boolean conflictRefresh) {
Collection<String> allUserIds = new ArrayList<String>();
try
{
Collection<User> allUsers = operator.getUsers();
for ( User user:allUsers)
{
String id = user.getId();
allUserIds.add( id);
}
}
catch (RaplaException ex)
{
getLogger().error( ex.getMessage(), ex);
// we stay with the old list.
// keySet iterator from concurrent hashmap is thread safe
Iterator<String> iterator = needResourceRefresh.keySet().iterator();
while ( iterator.hasNext())
{
String id = iterator.next();
allUserIds.add( id);
}
}
for ( String userId :allUserIds)
{
if (resourceRefreh )
{
needResourceRefresh.put( userId, repositoryVersion);
}
if ( conflictRefresh)
{
needConflictRefresh.put( userId, repositoryVersion);
}
}
}
private void invalidate(UpdateResult evt, long repositoryVersion, Set<Permission> invalidatePermissions) {
Collection<User> allUsers;
try {
allUsers = operator.getUsers();
} catch (RaplaException e) {
// we need to invalidate all on an exception
invalidateAll(repositoryVersion, true, true);
return;
}
// We also check if a permission on a reservation has changed, so that it is no longer or new in the conflict list of a certain user.
// If that is the case we trigger an invalidate of the conflicts for a user
Set<User> usersResourceRefresh = new HashSet<User>();
Category superCategory = operator.getSuperCategory();
Set<Category> groupsConflictRefresh = new HashSet<Category>();
Set<User> usersConflictRefresh = new HashSet<User>();
Iterator<Change> operations = evt.getOperations(UpdateResult.Change.class);
while ( operations.hasNext())
{
Change operation = operations.next();
Entity newObject = operation.getNew();
if ( newObject.getRaplaType().is( Allocatable.TYPE) && isTransferedToClient(newObject))
{
Allocatable newAlloc = (Allocatable) newObject;
Allocatable current = (Allocatable) operation.getOld();
Permission[] oldPermissions = current.getPermissions();
Permission[] newPermissions = newAlloc.getPermissions();
// we leave this condition for a faster equals check
if (oldPermissions.length == newPermissions.length)
{
for (int i=0;i<oldPermissions.length;i++)
{
Permission oldPermission = oldPermissions[i];
Permission newPermission = newPermissions[i];
if (!oldPermission.equals(newPermission))
{
invalidatePermissions.add( oldPermission);
invalidatePermissions.add( newPermission);
}
}
}
else
{
HashSet<Permission> newSet = new HashSet<Permission>(Arrays.asList(newPermissions));
HashSet<Permission> oldSet = new HashSet<Permission>(Arrays.asList(oldPermissions));
{
HashSet<Permission> changed = new HashSet<Permission>( newSet);
changed.removeAll( oldSet);
invalidatePermissions.addAll(changed);
}
{
HashSet<Permission> changed = new HashSet<Permission>(oldSet);
changed.removeAll( newSet);
invalidatePermissions.addAll(changed);
}
}
}
if ( newObject.getRaplaType().is( User.TYPE))
{
User newUser = (User) newObject;
User oldUser = (User) operation.getOld();
HashSet<Category> newGroups = new HashSet<Category>(Arrays.asList(newUser.getGroups()));
HashSet<Category> oldGroups = new HashSet<Category>(Arrays.asList(oldUser.getGroups()));
if ( !newGroups.equals( oldGroups) || newUser.isAdmin() != oldUser.isAdmin())
{
usersResourceRefresh.add( newUser);
}
}
if ( newObject.getRaplaType().is( Reservation.TYPE))
{
Reservation newEvent = (Reservation) newObject;
Reservation oldEvent = (Reservation) operation.getOld();
User newOwner = newEvent.getOwner();
User oldOwner = oldEvent.getOwner();
if ( newOwner != null && oldOwner != null && (newOwner.equals( oldOwner)) )
{
usersConflictRefresh.add( newOwner);
usersConflictRefresh.add( oldOwner);
}
Collection<Category> newGroup = RaplaComponent.getPermissionGroups( newEvent, superCategory, ReservationImpl.PERMISSION_MODIFY, false);
Collection<Category> oldGroup = RaplaComponent.getPermissionGroups( oldEvent, superCategory, ReservationImpl.PERMISSION_MODIFY, false);
if (newGroup != null && (oldGroup == null || !oldGroup.equals(newGroup)))
{
groupsConflictRefresh.addAll( newGroup);
}
if (oldGroup != null && (newGroup == null || !oldGroup.equals(newGroup)))
{
groupsConflictRefresh.addAll( oldGroup);
}
}
}
boolean addAllUsersToConflictRefresh = groupsConflictRefresh.contains( superCategory);
Set<Category> groupsResourceRefrsesh = new HashSet<Category>();
if ( !invalidatePermissions.isEmpty() || ! addAllUsersToConflictRefresh || !! groupsConflictRefresh.isEmpty())
{
for ( Permission permission:invalidatePermissions)
{
User user = permission.getUser();
if ( user != null)
{
usersResourceRefresh.add( user);
}
Category group = permission.getGroup();
if ( group != null)
{
groupsResourceRefrsesh.add( group);
}
if ( user == null && group == null)
{
usersResourceRefresh.addAll( allUsers);
break;
}
}
for ( User user:allUsers)
{
if ( usersResourceRefresh.contains( user))
{
continue;
}
for (Category group:user.getGroups())
{
if ( groupsResourceRefrsesh.contains( group))
{
usersResourceRefresh.add( user);
break;
}
if ( addAllUsersToConflictRefresh || groupsConflictRefresh.contains( group))
{
usersConflictRefresh.add( user);
break;
}
}
}
}
for ( User user:usersResourceRefresh)
{
String userId = user.getId();
needResourceRefresh.put( userId, repositoryVersion);
needConflictRefresh.put( userId, repositoryVersion);
}
for ( User user:usersConflictRefresh)
{
String userId = user.getId();
needConflictRefresh.put( userId, repositoryVersion);
}
}
private boolean isTransferedToClient(RaplaObject obj)
{
RaplaType<?> raplaType = obj.getRaplaType();
if (raplaType == Appointment.TYPE || raplaType == Reservation.TYPE)
{
return false;
}
if ( obj instanceof DynamicType)
{
if (!DynamicTypeImpl.isTransferedToClient(( DynamicType) obj))
{
return false;
}
}
if ( obj instanceof Classifiable)
{
if (!DynamicTypeImpl.isTransferedToClient(( Classifiable) obj))
{
return false;
}
}
return true;
}
@Override
public void dispose() {
}
public void updateError(RaplaException ex) {
}
public void storageDisconnected(String disconnectionMessage) {
}
public Class<RemoteStorage> getServiceClass() {
return RemoteStorage.class;
}
@Override
public RemoteStorage createService(final RemoteSession session) {
return new RemoteStorage() {
@Override
public void setConnectInfo(RemoteConnectionInfo info) {
// do nothing here
}
public FutureResult<UpdateEvent> getResources()
{
try
{
checkAuthentified();
User user = getSessionUser();
getLogger().debug ("A RemoteServer wants to get all resource-objects.");
Date serverTime = operator.getCurrentTimestamp();
Collection<Entity> visibleEntities = operator.getVisibleEntities(user);
UpdateEvent evt = new UpdateEvent();
evt.setUserId( user.getId());
for ( Entity entity: visibleEntities)
{
if ( isTransferedToClient(entity))
{
if ( entity instanceof Preferences)
{
Preferences preferences = (Preferences)entity;
User owner = preferences.getOwner();
if ( owner == null && !user.isAdmin())
{
entity = removeServerOnlyPreferences(preferences);
}
}
evt.putStore(entity);
}
}
evt.setLastValidated(serverTime);
return new ResultImpl<UpdateEvent>( evt);
}
catch (RaplaException ex )
{
return new ResultImpl<UpdateEvent>(ex );
}
}
private Preferences removeServerOnlyPreferences(Preferences preferences)
{
Preferences clone = preferences.clone();
{
//removeOldPluginConfigs(preferences, clone);
for (String role :((PreferencesImpl)preferences).getPreferenceEntries())
{
if ( role.contains(".server."))
{
clone.removeEntry(role);
}
}
}
return clone;
}
// private void removeOldPluginConfigs(Preferences preferences, Preferences clone) {
// List<String> adminOnlyPreferences = new ArrayList<String>();
// adminOnlyPreferences.add(MailPlugin.class.getCanonicalName());
// adminOnlyPreferences.add(JNDIPlugin.class.getCanonicalName());
//
// RaplaConfiguration entry = preferences.getEntry(RaplaComponent.PLUGIN_CONFIG);
// if ( entry != null)
// {
// RaplaConfiguration newConfig = entry.clone();
// for ( String className: adminOnlyPreferences)
// {
// DefaultConfiguration pluginConfig = (DefaultConfiguration)newConfig.find("class", className);
// if ( pluginConfig != null)
// {
// newConfig.removeChild( pluginConfig);
// boolean enabled = pluginConfig.getAttributeAsBoolean("enabled", false);
// RaplaConfiguration newPluginConfig = new RaplaConfiguration(pluginConfig.getName());
// newPluginConfig.setAttribute("enabled", enabled);
// newPluginConfig.setAttribute("class", className);
// newConfig.addChild( newPluginConfig);
// }
// }
// clone.putEntry(RaplaComponent.PLUGIN_CONFIG, newConfig);
// }
// }
public FutureResult<List<String>> getTemplateNames()
{
try
{
checkAuthentified();
Collection<String> templateNames = operator.getTemplateNames();
return new ResultImpl<List<String>>(new ArrayList<String>(templateNames));
}
catch (RaplaException ex )
{
return new ResultImpl<List<String>>(ex);
}
}
public FutureResult<UpdateEvent> getEntityRecursive(String... ids)
{
//synchronized (operator.getLock())
try
{
checkAuthentified();
Date repositoryVersion = operator.getCurrentTimestamp();
User sessionUser = getSessionUser();
ArrayList<Entity>completeList = new ArrayList<Entity>();
for ( String id:ids)
{
Entity entity = operator.resolve(id);
if ( entity instanceof Classifiable)
{
if (!DynamicTypeImpl.isTransferedToClient(( Classifiable) entity))
{
throw new RaplaSecurityException("Entity for id " + id + " is not transferable to the client");
}
}
if ( entity instanceof DynamicType)
{
if (!DynamicTypeImpl.isTransferedToClient(( DynamicType) entity))
{
throw new RaplaSecurityException("Entity for id " + id + " is not transferable to the client");
}
}
if ( entity instanceof Reservation)
{
entity = checkAndMakeReservationsAnonymous(sessionUser, entity);
}
if ( entity instanceof Preferences)
{
entity = removeServerOnlyPreferences((Preferences)entity);
}
security.checkRead(sessionUser, entity);
completeList.add( entity );
getLogger().debug("Get entity " + entity);
}
UpdateEvent evt = new UpdateEvent();
evt.setLastValidated(repositoryVersion);
for ( Entity entity: completeList)
{
evt.putStore(entity);
}
return new ResultImpl<UpdateEvent>( evt);
}
catch (RaplaException ex )
{
return new ResultImpl<UpdateEvent>(ex );
}
}
public FutureResult<List<ReservationImpl>> getReservations(String[] allocatableIds,Date start,Date end,Map<String,String> annotationQuery)
{
getLogger().debug ("A RemoteServer wants to reservations from ." + start + " to " + end);
try
{
checkAuthentified();
User sessionUser = getSessionUser();
User user = null;
// Reservations and appointments
ArrayList<ReservationImpl> list = new ArrayList<ReservationImpl>();
List<Allocatable> allocatables = new ArrayList<Allocatable>();
if ( allocatableIds != null )
{
for ( String id:allocatableIds)
{
Allocatable allocatable = operator.resolve(id, Allocatable.class);
security.checkRead(sessionUser, allocatable);
allocatables.add( allocatable);
}
}
ClassificationFilter[] classificationFilters = null;
Collection<Reservation> reservations = operator.getReservations(user,allocatables, start, end, classificationFilters,annotationQuery );
for (Reservation res:reservations)
{
if (isAllocatablesVisible(sessionUser, res))
{
ReservationImpl safeRes = checkAndMakeReservationsAnonymous(sessionUser, res);
list.add( safeRes);
}
}
// for (Reservation r:reservations)
// {
// Iterable<Entity>subEntities = ((ParentEntity)r).getSubEntities();
// for (Entity appointments:subEntities)
// {
// completeList.add( appointments);
// }
getLogger().debug("Get reservations " + start + " " + end + ": " + reservations.size() + "," + list.size());
return new ResultImpl<List<ReservationImpl>>(list);
}
catch (RaplaException ex )
{
return new ResultImpl<List<ReservationImpl>>(ex );
}
}
private ReservationImpl checkAndMakeReservationsAnonymous(User sessionUser,Entity entity) {
ReservationImpl reservation =(ReservationImpl) entity;
boolean canReadFromOthers = facade.canReadReservationsFromOthers(sessionUser);
boolean reservationVisible = RaplaComponent.canRead( reservation, sessionUser, canReadFromOthers);
// check if the user is allowed to read the reservation info
if ( !reservationVisible )
{
ReservationImpl clone = reservation.clone();
// we can safely change the reservation info here because we cloned it in transaction safe before
DynamicType anonymousReservationType = operator.getDynamicType( StorageOperator.ANONYMOUSEVENT_TYPE);
clone.setClassification( anonymousReservationType.newClassification());
clone.setReadOnly();
return clone;
}
else
{
return reservation;
}
}
protected boolean isAllocatablesVisible(User sessionUser, Reservation res) {
User owner = res.getOwner();
if (sessionUser.isAdmin() || owner == null || owner.equals(sessionUser) )
{
return true;
}
for (Allocatable allocatable: res.getAllocatables()) {
if (allocatable.canRead(sessionUser)) {
return true;
}
}
return true;
}
public FutureResult<VoidResult> restartServer() {
try
{
checkAuthentified();
if (!getSessionUser().isAdmin())
throw new RaplaSecurityException("Only admins can restart the server");
context.lookup(ShutdownService.class).shutdown( true);
return ResultImpl.VOID;
}
catch (RaplaException ex )
{
return new ResultImpl<VoidResult>(ex );
}
}
public FutureResult<UpdateEvent> dispatch(UpdateEvent event)
{
try
{
Date currentTimestamp = operator.getCurrentTimestamp();
Date lastSynced = event.getLastValidated();
if ( lastSynced == null)
{
throw new RaplaException("client sync time is missing");
}
if ( lastSynced.after( currentTimestamp))
{
long diff = lastSynced.getTime() - currentTimestamp.getTime();
getLogger().warn("Timestamp of client " +diff + " ms after server ");
lastSynced = currentTimestamp;
}
// LocalCache cache = operator.getCache();
// UpdateEvent event = createUpdateEvent( context,xml, cache );
User sessionUser = getSessionUser();
getLogger().info("Dispatching change for user " + sessionUser);
if ( sessionUser != null)
{
event.setUserId(sessionUser.getId());
}
dispatch_( event);
getLogger().info("Change for user " + sessionUser + " dispatched.");
UpdateEvent result = createUpdateEvent( lastSynced );
return new ResultImpl<UpdateEvent>(result );
}
catch (RaplaException ex )
{
return new ResultImpl<UpdateEvent>(ex );
}
}
public FutureResult<String> canChangePassword() {
try
{
checkAuthentified();
Boolean result = operator.canChangePassword();
return new ResultImpl<String>( result.toString());
}
catch (RaplaException ex )
{
return new ResultImpl<String>(ex );
}
}
public FutureResult<VoidResult> changePassword(String username
,String oldPassword
,String newPassword
)
{
try
{
checkAuthentified();
User sessionUser = getSessionUser();
if (!sessionUser.isAdmin()) {
if ( authenticationStore != null ) {
throw new RaplaSecurityException("Rapla can't change your password. Authentication handled by ldap plugin." );
}
operator.authenticate(username,new String(oldPassword));
}
User user = operator.getUser(username);
operator.changePassword(user,oldPassword.toCharArray(),newPassword.toCharArray());
return ResultImpl.VOID;
}
catch (RaplaException ex )
{
return new ResultImpl<VoidResult>(ex );
}
}
public FutureResult<VoidResult> changeName(String username,String newTitle,
String newSurename, String newLastname)
{
try
{
User changingUser = getSessionUser();
User user = operator.getUser(username);
if ( changingUser.isAdmin() || user.equals( changingUser) )
{
operator.changeName(user,newTitle,newSurename,newLastname);
}
else
{
throw new RaplaSecurityException("Not allowed to change email from other users");
}
return ResultImpl.VOID;
}
catch (RaplaException ex )
{
return new ResultImpl<VoidResult>(ex );
}
}
public FutureResult<VoidResult> changeEmail(String username,String newEmail)
{
try
{
User changingUser = getSessionUser();
User user = operator.getUser(username);
if ( changingUser.isAdmin() || user.equals( changingUser) )
{
operator.changeEmail(user,newEmail);
}
else
{
throw new RaplaSecurityException("Not allowed to change email from other users");
}
return ResultImpl.VOID;
}
catch (RaplaException ex )
{
return new ResultImpl<VoidResult>(ex );
}
}
public FutureResult<VoidResult> confirmEmail(String username,String newEmail)
{
try
{
User changingUser = getSessionUser();
User user = operator.getUser(username);
if ( changingUser.isAdmin() || user.equals( changingUser) )
{
String subject = getString("security_code");
Preferences prefs = operator.getPreferences( null, true );
String mailbody = "" + getString("send_code_mail_body_1") + user.getUsername() + ",\n\n"
+ getString("send_code_mail_body_2") + "\n\n" + getString("security_code") + Math.abs(user.getEmail().hashCode())
+ "\n\n" + getString("send_code_mail_body_3") + "\n\n" + "-----------------------------------------------------------------------------------"
+ "\n\n" + getString("send_code_mail_body_4") + prefs.getEntryAsString(RaplaMainContainer.TITLE, getString("rapla.title")) + " "
+ getString("send_code_mail_body_5");
final MailInterface mail = context.lookup(MailInterface.class);
final String defaultSender = prefs.getEntryAsString( MailPlugin.DEFAULT_SENDER_ENTRY, "");
mail.sendMail( defaultSender, newEmail,subject, "" + mailbody);
}
else
{
throw new RaplaSecurityException("Not allowed to change email from other users");
}
return ResultImpl.VOID;
}
catch (RaplaException ex )
{
return new ResultImpl<VoidResult>(ex );
}
}
private String getString(String key) throws RaplaException {
return getI18n().getString( key);
}
public FutureResult<List<String>> createIdentifier(String type, int count) {
try
{
RaplaType raplaType = RaplaType.find( type);
checkAuthentified();
//User user =
getSessionUser(); //check if authenified
String[] result =operator.createIdentifier(raplaType, count);
return new ResultImpl<List<String>>( Arrays.asList(result));
}
catch (RaplaException ex )
{
return new ResultImpl<List<String>>(ex );
}
}
public FutureResult<UpdateEvent> refresh(String lastSyncedTime)
{
try
{
checkAuthentified();
Date clientRepoVersion = SerializableDateTimeFormat.INSTANCE.parseTimestamp(lastSyncedTime);
UpdateEvent event = createUpdateEvent(clientRepoVersion);
return new ResultImpl<UpdateEvent>( event);
}
catch (RaplaException ex )
{
return new ResultImpl<UpdateEvent>(ex );
}
catch (ParseDateException e)
{
return new ResultImpl<UpdateEvent>(new RaplaException( e.getMessage()) );
}
}
public Logger getLogger()
{
return session.getLogger();
}
private void checkAuthentified() throws RaplaSecurityException {
if (!session.isAuthentified()) {
throw new RaplaSecurityException(RemoteStorage.USER_WAS_NOT_AUTHENTIFIED);
}
}
private User getSessionUser() throws RaplaException {
return session.getUser();
}
private void dispatch_(UpdateEvent evt) throws RaplaException {
checkAuthentified();
try {
User user;
if ( evt.getUserId() != null)
{
user = operator.resolve(evt.getUserId(), User.class);
}
else
{
user = session.getUser();
}
Collection<Entity>storeObjects = evt.getStoreObjects();
EntityStore store = new EntityStore(operator, operator.getSuperCategory());
store.addAll(storeObjects);
for (EntityReferencer references:evt.getEntityReferences( true))
{
references.setResolver( store);
}
for (Entity entity:storeObjects)
{
security.checkWritePermissions(user,entity);
}
List<PreferencePatch> preferencePatches = evt.getPreferencePatches();
for (PreferencePatch patch:preferencePatches)
{
security.checkWritePermissions(user,patch);
}
Collection<Entity>removeObjects = evt.getRemoveObjects();
for ( Entity entity:removeObjects)
{
security.checkWritePermissions(user,entity);
}
if (this.getLogger().isDebugEnabled())
this.getLogger().debug("Dispatching changes to " + operator.getClass());
operator.dispatch(evt);
if (this.getLogger().isDebugEnabled())
this.getLogger().debug("Changes dispatched returning result.");
} catch (DependencyException ex) {
throw ex;
} catch (RaplaNewVersionException ex) {
throw ex;
} catch (RaplaSecurityException ex) {
this.getLogger().warn(ex.getMessage());
throw ex;
} catch (RaplaException ex) {
this.getLogger().error(ex.getMessage(),ex);
throw ex;
} catch (Exception ex) {
this.getLogger().error(ex.getMessage(),ex);
throw new RaplaException(ex);
} catch (Error ex) {
this.getLogger().error(ex.getMessage(),ex);
throw ex;
}
}
private UpdateEvent createUpdateEvent( Date lastSynced ) throws RaplaException
{
Date currentTimestamp = operator.getCurrentTimestamp();
if ( lastSynced.after( currentTimestamp))
{
long diff = lastSynced.getTime() - currentTimestamp.getTime();
getLogger().warn("Timestamp of client " +diff + " ms after server ");
lastSynced = currentTimestamp;
}
User user = getSessionUser();
UpdateEvent safeResultEvent = new UpdateEvent();
safeResultEvent.setLastValidated( currentTimestamp);
TimeZone systemTimeZone = operator.getTimeZone();
int timezoneOffset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, currentTimestamp.getTime());
safeResultEvent.setTimezoneOffset( timezoneOffset );
//if ( lastSynced.before( currentTimestamp ))
{
String userId = user.getId();
TimeInterval invalidateInterval;
{
Long lastVersion = needConflictRefresh.get( userId );
if ( lastVersion != null && lastVersion > lastSynced.getTime())
{
invalidateInterval = new TimeInterval( null, null);
}
else
{
invalidateInterval = getInvalidateInterval( lastSynced.getTime() );
}
}
boolean resourceRefresh;
{
Long lastVersion = needResourceRefresh.get( userId);
resourceRefresh = ( lastVersion != null && lastVersion > lastSynced.getTime());
}
safeResultEvent.setNeedResourcesRefresh( resourceRefresh);
safeResultEvent.setInvalidateInterval( invalidateInterval);
}
if ( !safeResultEvent.isNeedResourcesRefresh())
{
Collection<Entity> updatedEntities = operator.getUpdatedEntities(lastSynced );
for ( Entity obj: updatedEntities )
{
processClientReadable( user, safeResultEvent, obj, false);
}
}
return safeResultEvent;
}
protected void processClientReadable(User user,UpdateEvent safeResultEvent, Entity obj, boolean remove) {
if ( !isTransferedToClient(obj))
{
return;
}
boolean clientStore = true;
if (user != null )
{
// we don't transmit preferences for other users
if ( obj instanceof Preferences)
{
Preferences preferences = (Preferences) obj;
User owner = preferences.getOwner();
if ( owner != null && !owner.equals( user))
{
clientStore = false;
}
else
{
obj = removeServerOnlyPreferences(preferences);
}
}
else if ( obj instanceof Allocatable)
{
Allocatable alloc = (Allocatable) obj;
if ( !alloc.canReadOnlyInformation(user))
{
clientStore = false;
}
}
else if ( obj instanceof Conflict)
{
Conflict conflict = (Conflict) obj;
if ( !ConflictImpl.canModify( conflict, user, operator) )
{
clientStore = false;
}
}
}
if ( clientStore)
{
if ( remove)
{
safeResultEvent.putRemove( obj );
}
else
{
safeResultEvent.putStore( obj );
}
}
}
// protected List<Entity>getDependentObjects(
// Appointment appointment) {
// List<Entity> toAdd = new ArrayList<Entity>();
// toAdd.add( (Entity)appointment);
// @SuppressWarnings("unchecked")
// ReservationImpl reservation = (ReservationImpl)appointment.getReservation();
// {
// toAdd.add(reservation);
// String id = reservation.getId();
// Entity inCache;
// try {
// inCache = operator.resolve( id);
// } catch (EntityNotFoundException e) {
// inCache = null;
// }
// if ( inCache != null && ((RefEntity)inCache).getVersion() > reservation.getVersion())
// {
// getLogger().error("Try to send an older version of the reservation to the client " + reservation.getName( raplaLocale.getLocale()));
// }
// for (Entity ref:reservation.getSubEntities())
// {
// toAdd.add( ref );
// }
// }
// if (!toAdd.contains(appointment))
// {
// getLogger().error(appointment.toString() + " at " + raplaLocale.formatDate(appointment.getStart()) + " does refer to reservation " + reservation.getName( raplaLocale.getLocale()) + " but the reservation does not refer back.");
// }
// return toAdd;
// }
//
private TimeInterval getInvalidateInterval( long clientRepositoryVersion)
{
TimeInterval interval = null;
synchronized (invalidateMap)
{
for ( TimeInterval current:invalidateMap.tailMap( clientRepositoryVersion).values())
{
if ( current != null)
{
interval = current.union( interval);
}
}
return interval;
}
}
public FutureResult<List<ConflictImpl>> getConflicts()
{
try
{
Set<Entity>completeList = new HashSet<Entity> ();
User sessionUser = getSessionUser();
Collection<Conflict> conflicts = operator.getConflicts( sessionUser);
List<ConflictImpl> result = new ArrayList<ConflictImpl>();
for ( Conflict conflict:conflicts)
{
result.add( (ConflictImpl) conflict);
Entity conflictRef = (Entity)conflict;
completeList.add(conflictRef);
//completeList.addAll( getDependentObjects(conflict.getAppointment1()));
//completeList.addAll( getDependentObjects(conflict.getAppointment2()));
}
//EntityList list = createList( completeList, repositoryVersion );
return new ResultImpl<List<ConflictImpl>>( result);
}
catch (RaplaException ex )
{
return new ResultImpl<List<ConflictImpl>>(ex );
}
}
@Override
public FutureResult<Date> getNextAllocatableDate( String[] allocatableIds, AppointmentImpl appointment,String[] reservationIds, Integer worktimestartMinutes, Integer worktimeendMinutes, Integer[] excludedDays, Integer rowsPerHour)
{
try
{
checkAuthentified();
List<Allocatable> allocatables = resolveAllocatables(allocatableIds);
Collection<Reservation> ignoreList = resolveReservations(reservationIds);
Date result = operator.getNextAllocatableDate(allocatables, appointment, ignoreList, worktimestartMinutes, worktimeendMinutes, excludedDays, rowsPerHour);
return new ResultImpl<Date>( result);
}
catch (RaplaException ex )
{
return new ResultImpl<Date>(ex );
}
}
@Override
public FutureResult<BindingMap> getFirstAllocatableBindings(String[] allocatableIds, List<AppointmentImpl> appointments, String[] reservationIds)
{
try
{
checkAuthentified();
//Integer[][] result = new Integer[allocatableIds.length][];
List<Allocatable> allocatables = resolveAllocatables(allocatableIds);
Collection<Reservation> ignoreList = resolveReservations(reservationIds);
List<Appointment> asList = cast(appointments);
Map<Allocatable, Collection<Appointment>> bindings = operator.getFirstAllocatableBindings(allocatables, asList, ignoreList);
Map<String,List<String>> result = new LinkedHashMap<String,List<String>>();
for ( Allocatable alloc:bindings.keySet())
{
Collection<Appointment> apps = bindings.get(alloc);
if ( apps == null)
{
apps = Collections.emptyList();
}
ArrayList<String> indexArray = new ArrayList<String>(apps.size());
for ( Appointment app: apps)
{
for (Appointment app2:appointments)
{
if (app2.equals(app ))
{
indexArray.add ( app.getId());
}
}
}
result.put(alloc.getId(), indexArray);
}
return new ResultImpl<BindingMap>(new BindingMap(result));
}
catch (RaplaException ex )
{
return new ResultImpl<BindingMap>(ex);
}
}
private List<Appointment> cast(List<AppointmentImpl> appointments) {
List<Appointment> result = new ArrayList<Appointment>(appointments.size());
for (Appointment app:appointments)
{
result.add( app);
}
return result;
}
public FutureResult<List<ReservationImpl>> getAllAllocatableBindings(String[] allocatableIds, List<AppointmentImpl> appointments, String[] reservationIds)
{
try
{
Set<ReservationImpl> result = new HashSet<ReservationImpl>();
checkAuthentified();
List<Allocatable> allocatables = resolveAllocatables(allocatableIds);
Collection<Reservation> ignoreList = resolveReservations(reservationIds);
List<Appointment> asList = cast(appointments);
Map<Allocatable, Map<Appointment, Collection<Appointment>>> bindings = operator.getAllAllocatableBindings(allocatables, asList, ignoreList);
for (Allocatable alloc:bindings.keySet())
{
Map<Appointment,Collection<Appointment>> appointmentBindings = bindings.get( alloc);
for (Appointment app: appointmentBindings.keySet())
{
Collection<Appointment> bound = appointmentBindings.get( app);
if ( bound != null)
{
for ( Appointment appointment: bound)
{
ReservationImpl reservation = (ReservationImpl) appointment.getReservation();
if ( reservation != null)
{
result.add( reservation);
}
}
}
}
}
return new ResultImpl<List<ReservationImpl>>(new ArrayList<ReservationImpl>(result));
}
catch (RaplaException ex)
{
return new ResultImpl<List<ReservationImpl>>(ex);
}
}
private List<Allocatable> resolveAllocatables(String[] allocatableIds) throws RaplaException,EntityNotFoundException, RaplaSecurityException
{
List<Allocatable> allocatables = new ArrayList<Allocatable>();
User sessionUser = getSessionUser();
for ( String id:allocatableIds)
{
Allocatable entity = operator.resolve(id, Allocatable.class);
allocatables.add( entity);
security.checkRead(sessionUser, entity);
}
return allocatables;
}
private Collection<Reservation> resolveReservations(String[] ignoreList) {
Set<Reservation> ignoreConflictsWith = new HashSet<Reservation>();
for (String reservationId: ignoreList)
{
try
{
Reservation entity = operator.resolve(reservationId, Reservation.class);
ignoreConflictsWith.add( entity);
}
catch (EntityNotFoundException ex)
{
// Do nothing reservation not found and assumed new
}
}
return ignoreConflictsWith;
}
// public void logEntityNotFound(String logMessage,String... referencedIds)
// {
// StringBuilder buf = new StringBuilder();
// buf.append("{");
// for (String id: referencedIds)
// {
// buf.append("{ id=");
// if ( id != null)
// {
// buf.append(id.toString());
// buf.append(": ");
// Entity refEntity = operator.tryResolve(id);
// if ( refEntity != null )
// {
// buf.append( refEntity.toString());
// }
// else
// {
// buf.append("NOT FOUND");
// }
// }
// else
// {
// buf.append( "is null");
// }
//
// buf.append("}, ");
// }
// buf.append("}");
// getLogger().error("EntityNotFoundFoundExceptionOnClient "+ logMessage + " " + buf.toString());
// //return ResultImpl.VOID;
// }
};
}
static public void convertToNewPluginConfig(RaplaContext context, String className, TypedComponentRole<RaplaConfiguration> newConfKey) throws RaplaContextException {
ClientFacade facade = context.lookup( ClientFacade.class);
// {
// RaplaConfiguration entry = facade.getPreferences().getEntry(RaplaComponent.PLUGIN_CONFIG,null);
// if ( entry == null )
// {
// return;
// }
// DefaultConfiguration pluginConfig = (DefaultConfiguration)entry.find("class", className);
// if ( pluginConfig == null)
// {
// return;
// }
// // only class and getEnabled
//
// }
try
{
PreferencesImpl clone = (PreferencesImpl) facade.edit( facade.getSystemPreferences());
RaplaConfiguration entry = clone.getEntry(RaplaComponent.PLUGIN_CONFIG,null);
RaplaConfiguration newPluginConfigEntry = entry.clone();
DefaultConfiguration pluginConfig = (DefaultConfiguration)newPluginConfigEntry.find("class", className);
// we split the config entry in the plugin config and the new config entry;
if ( pluginConfig != null)
{
context.lookup(Logger.class).info("Converting plugin conf " + className + " to preference entry " + newConfKey);
newPluginConfigEntry.removeChild( pluginConfig);
boolean enabled = pluginConfig.getAttributeAsBoolean("enabled", false);
RaplaConfiguration newPluginConfig = new RaplaConfiguration(pluginConfig.getName());
newPluginConfig.setAttribute("enabled", enabled);
newPluginConfig.setAttribute("class", className);
newPluginConfigEntry.addChild( newPluginConfig);
RaplaConfiguration newConfigEntry = new RaplaConfiguration( pluginConfig);
newConfigEntry.setAttribute("enabled", null);
newConfigEntry.setAttribute("class", null);
clone.putEntry(newConfKey, newConfigEntry);
clone.putEntry(RaplaComponent.PLUGIN_CONFIG, newPluginConfigEntry);
facade.store( clone);
}
}
catch (RaplaException ex)
{
if ( ex instanceof RaplaContextException)
{
throw (RaplaContextException)ex;
}
throw new RaplaContextException(ex.getMessage(),ex);
}
}
}
| 04900db4-clienttest | src/org/rapla/server/internal/RemoteStorageImpl.java | Java | gpl3 | 56,702 |
package org.rapla.server.internal;
import org.rapla.entities.User;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.logger.Logger;
import org.rapla.server.RemoteSession;
/** Implementation of RemoteStorage as a RemoteService
* @see org.rapla.storage.dbrm.RemoteStorage
*/
public class RemoteSessionImpl extends RaplaComponent implements RemoteSession {
/**
*
*/
User user;
Logger logger;
// private String accessToken;
public RemoteSessionImpl(RaplaContext context, String clientName) {
super( context );
logger = super.getLogger().getChildLogger(clientName);
}
public Logger getLogger() {
return logger;
}
@Override
public User getUser() throws RaplaContextException {
if (user == null)
throw new RaplaContextException("No user found in session.");
return user;
}
@Override
public boolean isAuthentified() {
return user != null;
}
public void setUser( User user)
{
this.user = user;
}
// public void setAccessToken( String token)
// {
// this.accessToken = token;
// }
//
// @Override
// public String getAccessToken() {
// return accessToken;
// }
public void logout() {
this.setUser( null);
}
} | 04900db4-clienttest | src/org/rapla/server/internal/RemoteSessionImpl.java | Java | gpl3 | 1,409 |
package org.rapla.server.internal;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.codec.binary.Base64;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.server.RaplaKeyStorage;
public class RaplaKeyStorageImpl extends RaplaComponent implements RaplaKeyStorage
{
//private static final String USER_KEYSTORE = "keystore";
private static final String ASYMMETRIC_ALGO = "RSA";
private static final TypedComponentRole<String> PUBLIC_KEY = new TypedComponentRole<String>("org.rapla.crypto.publicKey");
private static final TypedComponentRole<String> APIKEY = new TypedComponentRole<String>("org.rapla.crypto.server.refreshToken");
private static final TypedComponentRole<String> PRIVATE_KEY = new TypedComponentRole<String>("org.rapla.crypto.server.privateKey");
private String rootKey;
private String rootPublicKey;
private Base64 base64;
CryptoHandler cryptoHandler;
public String getRootKeyBase64()
{
return rootKey;
}
/**
* Initializes the Url encryption plugin.
* Checks whether an encryption key exists or not, reads an existing one from the configuration file
* or generates a new one. The decryption and encryption ciphers are also initialized here.
*
* @param context
* @param config
* @throws RaplaException
*/
public RaplaKeyStorageImpl(RaplaContext context) throws RaplaException {
super(context);
byte[] linebreake = {};
// we use an url safe encoder for the keys
this.base64 = new Base64(64, linebreake, true);
rootKey = getQuery().getSystemPreferences().getEntryAsString(PRIVATE_KEY, null);
rootPublicKey = getQuery().getSystemPreferences().getEntryAsString(PUBLIC_KEY, null);
if ( rootKey == null || rootPublicKey == null)
{
try {
generateRootKeyStorage();
} catch (NoSuchAlgorithmException e) {
throw new RaplaException( e.getMessage());
}
}
cryptoHandler = new CryptoHandler( context,rootKey);
}
public LoginInfo decrypt(String encrypted) throws RaplaException {
LoginInfo loginInfo = new LoginInfo();
String decrypt = cryptoHandler.decrypt(encrypted);
String[] split = decrypt.split(":",2);
loginInfo.login = split[0];
loginInfo.secret = split[1];
return loginInfo;
}
@Override
public void storeAPIKey(User user,String clientId, String newApiKey) throws RaplaException {
Preferences preferences = getQuery().getPreferences(user);
Preferences edit = getModification().edit( preferences);
edit.putEntry(APIKEY, newApiKey);
getModification().store( edit);
}
@Override
public Collection<String> getAPIKeys(User user) throws RaplaException {
String annotation = getQuery().getPreferences(user).getEntryAsString(APIKEY, null);
if (annotation == null)
{
return Collections.emptyList();
}
Collection<String> keyList = Collections.singleton( annotation );
return keyList;
}
@Override
public void removeAPIKey(User user, String apikey) throws RaplaException {
throw new UnsupportedOperationException();
// Allocatable key= getAllocatable(user);
// if ( key != null )
// {
// Collection<String> keyList = parseList(key.getAnnotation(APIKEY));
// if (keyList == null || !keyList.contains(apikey))
// {
// return;
// }
// key = getModification().edit( key );
// keyList.remove( apikey);
// if ( keyList.size() > 0)
// {
// key.setAnnotation(APIKEY, null);
// }
// else
// {
// key.setAnnotation(APIKEY, serialize(keyList));
// }
// // remove when no more annotations set
// if (key.getAnnotationKeys().length == 0)
// {
// getModification().remove( key);
// }
// else
// {
// getModification().store( key);
// }
// }
}
@Override
public LoginInfo getSecrets(User user, TypedComponentRole<String> tagName) throws RaplaException
{
String annotation = getQuery().getPreferences(user).getEntryAsString(tagName, null);
if ( annotation == null)
{
return null;
}
return decrypt(annotation);
}
@Override
public void storeLoginInfo(User user,TypedComponentRole<String> tagName,String login,String secret) throws RaplaException
{
Preferences preferences = getQuery().getPreferences(user);
Preferences edit = getModification().edit( preferences);
String loginPair = login +":" + secret;
String encrypted = cryptoHandler.encrypt( loginPair);
edit.putEntry(tagName, encrypted);
getModification().store( edit);
}
// public Allocatable getOrCreate(User user) throws RaplaException {
// Allocatable key= getAllocatable(user);
// if ( key == null)
// {
// DynamicType dynamicType = getQuery().getDynamicType( StorageOperator.CRYPTO_TYPE);
// Classification classification = dynamicType.newClassification();
// key = getModification().newAllocatable(classification, null );
// if ( user != null)
// {
// key.setOwner( user);
// }
// key.setClassification( classification);
// }
// else
// {
// key = getModification().edit( key);
// }
// return key;
// }
public void removeLoginInfo(User user, TypedComponentRole<String> tagName) throws RaplaException {
Preferences preferences = getQuery().getPreferences(user);
Preferences edit = getModification().edit( preferences);
edit.putEntry(tagName, null);
getModification().store( edit);
}
//
// Allocatable getAllocatable(User user) throws RaplaException
// {
// Collection<Allocatable> store = getAllocatables();
// if ( store.size() > 0)
// {
// for ( Allocatable all:store)
// {
// User owner = all.getOwner();
// if ( user == null)
// {
// if ( owner == null )
// {
// return all;
// }
// }
// else
// {
// if ( owner != null && user.equals( owner))
// {
// return all;
// }
// }
// }
// }
// return null;
// }
// public Collection<Allocatable> getAllocatables() throws RaplaException
// {
// StorageOperator operator = getClientFacade().getOperator();
// DynamicType dynamicType = operator.getDynamicType( StorageOperator.CRYPTO_TYPE);
// ClassificationFilter newClassificationFilter = dynamicType.newClassificationFilter();
// ClassificationFilter[] array = newClassificationFilter.toArray();
// Collection<Allocatable> store = operator.getAllocatables( array);
// return store;
// }
private void generateRootKeyStorage() throws NoSuchAlgorithmException, RaplaException {
getLogger().info("Generating new root key. This can take a while.");
//Classification newClassification = dynamicType.newClassification();
//newClassification.setValue("name", "root");
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance( ASYMMETRIC_ALGO );
keyPairGen.initialize( 2048);
KeyPair keyPair = keyPairGen.generateKeyPair();
getLogger().info("Root key generated");
PrivateKey privateKeyObj = keyPair.getPrivate();
this.rootKey = base64.encodeAsString(privateKeyObj.getEncoded());
PublicKey publicKeyObj = keyPair.getPublic();
this.rootPublicKey =base64.encodeAsString(publicKeyObj.getEncoded());
Preferences systemPreferences = getQuery().getSystemPreferences();
Preferences edit = getModification().edit( systemPreferences);
edit.putEntry(PRIVATE_KEY, rootKey);
edit.putEntry(PUBLIC_KEY, rootPublicKey);
getModification().store( edit);
}
}
| 04900db4-clienttest | src/org/rapla/server/internal/RaplaKeyStorageImpl.java | Java | gpl3 | 8,354 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.server.internal;
public interface ShutdownService
{
void shutdown( boolean restart);
}
| 04900db4-clienttest | src/org/rapla/server/internal/ShutdownService.java | Java | gpl3 | 1,049 |
package org.rapla.server.internal;
import java.util.Date;
import java.util.TimeZone;
import org.rapla.components.util.DateTools;
import org.rapla.server.TimeZoneConverter;
public class TimeZoneConverterImpl implements TimeZoneConverter
{
TimeZone zone;
TimeZone importExportTimeZone;
public TimeZoneConverterImpl()
{
zone = DateTools.getTimeZone();
TimeZone systemTimezone = TimeZone.getDefault();
importExportTimeZone = systemTimezone;
}
public TimeZone getImportExportTimeZone() {
return importExportTimeZone;
}
public void setImportExportTimeZone(TimeZone importExportTimeZone) {
this.importExportTimeZone = importExportTimeZone;
}
public long fromRaplaTime(TimeZone timeZone,long raplaTime)
{
long offset = TimeZoneConverterImpl.getOffset(zone,timeZone, raplaTime);
return raplaTime - offset;
}
public long toRaplaTime(TimeZone timeZone,long time)
{
long offset = TimeZoneConverterImpl.getOffset(zone,timeZone,time);
return time + offset;
}
public Date fromRaplaTime(TimeZone timeZone,Date raplaTime)
{
return new Date( fromRaplaTime(timeZone, raplaTime.getTime()));
}
public Date toRaplaTime(TimeZone timeZone,Date time)
{
return new Date( toRaplaTime(timeZone, time.getTime()));
}
public static int getOffset(TimeZone zone1,TimeZone zone2,long time) {
int offsetRapla = zone1.getOffset(time);
int offsetSystem = zone2.getOffset(time);
return offsetSystem - offsetRapla;
}
}
| 04900db4-clienttest | src/org/rapla/server/internal/TimeZoneConverterImpl.java | Java | gpl3 | 1,504 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Praktikum Gruppe2?, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.server.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.Ownable;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentFormater;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.Conflict;
import org.rapla.facade.RaplaComponent;
import org.rapla.facade.internal.FacadeImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.CachableStorageOperator;
import org.rapla.storage.PreferencePatch;
import org.rapla.storage.RaplaSecurityException;
/** checks if the client can store or delete an entity */
public class SecurityManager
{
I18nBundle i18n;
AppointmentFormater appointmentFormater;
CachableStorageOperator operator;
RaplaContext context;
Logger logger;
public SecurityManager(RaplaContext context) throws RaplaException {
logger = context.lookup( Logger.class);
operator = context.lookup( CachableStorageOperator.class);
i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
appointmentFormater = context.lookup(AppointmentFormater.class);
this.context = context;
}
void checkWritePermissions(User user,Entity entity) throws RaplaSecurityException {
if (user.isAdmin())
return;
Object id = entity.getId();
if (id == null)
throw new RaplaSecurityException("No id set");
boolean permitted = false;
@SuppressWarnings("unchecked")
Class<Entity> typeClass = entity.getRaplaType().getTypeClass();
Entity original = operator.tryResolve( entity.getId(), typeClass);
// flag indicates if a user only exchanges allocatables (needs to have admin-access on the allocatable)
boolean canExchange = false;
boolean ownable = entity instanceof Ownable;
if (ownable || entity instanceof Appointment) {
User entityOwner;
if ( ownable)
{
entityOwner = ((Ownable) entity).getOwner();
}
else
{
entityOwner = ((Appointment) entity).getOwner();
}
if (original == null) {
permitted = entityOwner != null && user.isIdentical(entityOwner);
if (getLogger().isDebugEnabled())
getLogger().debug("Permissions for new object " + entity
+ "\nUser check: " + user + " = " + entityOwner);
} else {
User originalOwner;
if ( ownable)
{
originalOwner = ((Ownable) original).getOwner();
}
else
{
originalOwner = ((Appointment) original).getOwner();
}
if (getLogger().isDebugEnabled())
getLogger().debug("Permissions for existing object " + entity
+ "\nUser check: " + user + " = " + entityOwner + " = " + originalOwner);
permitted = (originalOwner != null) && originalOwner.isIdentical(user) && originalOwner.isIdentical(entityOwner);
if ( !permitted ) {
canExchange = canExchange( user, entity, original );
permitted = canExchange;
}
}
}
if ( !permitted && entity instanceof Allocatable ){
if ( original == null ) {
permitted = isRegisterer(user);
} else {
permitted = ((Allocatable)original).canModify( user );
}
}
if ( !permitted && original != null)
{
permitted = RaplaComponent.checkClassifiableModifyPermissions(original, user);
}
if (!permitted && entity instanceof Appointment)
{
final Reservation reservation = ((Appointment)entity).getReservation();
Reservation originalReservation = operator.tryResolve(reservation.getId(), Reservation.class);
if ( originalReservation != null)
{
permitted = RaplaComponent.checkClassifiableModifyPermissions(originalReservation, user);
}
}
if (!permitted)
throw new RaplaSecurityException(i18n.format("error.modify_not_allowed", new Object []{ user.toString(),entity.toString()}));
// Check if the user can change the reservation
if ( Reservation.TYPE ==entity.getRaplaType() )
{
Reservation reservation = (Reservation) entity ;
Reservation originalReservation = (Reservation)original;
Allocatable[] all = reservation.getAllocatables();
if ( originalReservation != null && canExchange ) {
List<Allocatable> newAllocatabes = new ArrayList<Allocatable>( Arrays.asList(reservation.getAllocatables() ) );
newAllocatabes.removeAll( Arrays.asList( originalReservation.getAllocatables()));
all = newAllocatabes.toArray( Allocatable.ALLOCATABLE_ARRAY);
}
if ( originalReservation == null)
{
Category group = getUserGroupsCategory().getCategory( Permission.GROUP_CAN_CREATE_EVENTS);
if (group != null && !user.belongsTo(group))
{
throw new RaplaSecurityException(i18n.format("error.create_not_allowed", new Object []{ user.toString(),entity.toString()}));
}
}
checkPermissions( user, reservation, originalReservation , all);
}
}
private Logger getLogger()
{
return logger;
}
protected boolean isRegisterer(User user) throws RaplaSecurityException {
try {
Category registererGroup = getUserGroupsCategory().getCategory(Permission.GROUP_REGISTERER_KEY);
return user.belongsTo(registererGroup);
} catch (RaplaException ex) {
throw new RaplaSecurityException(ex );
}
}
public Category getUserGroupsCategory() throws RaplaSecurityException {
Category userGroups = operator.getSuperCategory().getCategory(Permission.GROUP_CATEGORY_KEY);
if ( userGroups == null) {
throw new RaplaSecurityException("No category '" + Permission.GROUP_CATEGORY_KEY + "' available");
}
return userGroups;
}
/** checks if the user just exchanges one allocatable or removes one. The user needs admin-access on the
* removed allocatable and the newly inserted allocatable */
private boolean canExchange(User user,Entity entity,Entity original) {
if ( Appointment.TYPE.equals( entity.getRaplaType() )) {
return ((Appointment) entity).matches( (Appointment) original );
} if ( Reservation.TYPE.equals( entity.getRaplaType() )) {
Reservation newReservation = (Reservation) entity;
Reservation oldReservation = (Reservation) original;
// We only need to check the length because we compare the appointments above.
if ( newReservation.getAppointments().length != oldReservation.getAppointments().length )
{
return false;
}
List<Allocatable> oldAllocatables = Arrays.asList(oldReservation.getAllocatables());
List<Allocatable> newAllocatables = Arrays.asList(newReservation.getAllocatables());
List<Allocatable> inserted = new ArrayList<Allocatable>(newAllocatables);
List<Allocatable> removed = new ArrayList<Allocatable>(oldAllocatables);
List<Allocatable> overlap = new ArrayList<Allocatable>(oldAllocatables);
inserted.removeAll( oldAllocatables );
removed.removeAll( newAllocatables );
overlap.retainAll( inserted );
if ( inserted.size() == 0 && removed.size() == 0)
{
return false;
}
// he must have admin rights on all inserted resources
Iterator<Allocatable> it = inserted.iterator();
while (it.hasNext()) {
if (!canAllocateForOthers(it.next(),user))
{
return false;
}
}
// and he must have admin rights on all the removed resources
it = removed.iterator();
while (it.hasNext()) {
if (!canAllocateForOthers(it.next(),user))
{
return false;
}
}
// He can't change appointments, only exchange allocatables he has admin-priviliges for
it = overlap.iterator();
while (it.hasNext()) {
Allocatable all = it.next();
Appointment[] r1 = newReservation.getRestriction( all );
Appointment[] r2 = oldReservation.getRestriction( all );
boolean changed = false;
if ( r1.length != r2.length ) {
changed = true;
} else {
for ( int i=0; i< r1.length; i++ ) {
if ( !r1[i].matches(r2[i]) ) {
changed = true;
}
}
}
if ( changed && !canAllocateForOthers( all, user )) {
return false;
}
}
return true;
}
return false;
}
/** for Thierry, we can make this configurable in the next version */
private boolean canAllocateForOthers(Allocatable allocatable, User user) {
// only admins, current behaviour
return allocatable.canModify( user);
// everyone who can allocate the resource anytime
//return allocatable.canAllocate( user, null, null, operator.today());
// everyone
//return true;
}
private void checkConflictsAllowed(User user, Allocatable allocatable, Conflict[] conflictsBefore, Conflict[] conflictsAfter) throws RaplaSecurityException {
int nConflictsBefore = 0;
int nConflictsAfter = 0;
if ( allocatable.canCreateConflicts( user ) ) {
return;
}
if ( conflictsBefore != null ) {
for ( int i = 0; i < conflictsBefore.length; i++ ) {
if ( conflictsBefore[i].getAllocatable().equals ( allocatable ) ) {
nConflictsBefore ++;
}
}
}
for ( int i = 0; i < conflictsAfter.length; i++ ) {
if ( conflictsAfter[i].getAllocatable().equals ( allocatable ) ) {
nConflictsAfter ++;
}
}
if ( nConflictsAfter > nConflictsBefore ) {
String all = allocatable.getName( i18n.getLocale() );
throw new RaplaSecurityException( i18n.format("warning.no_conflict_permission", all ) );
}
}
private void checkPermissions( User user, Reservation r, Reservation original, Allocatable[] allocatables ) throws RaplaSecurityException {
ClientFacade facade;
try {
facade = context.lookup(ClientFacade.class);
} catch (RaplaContextException e) {
throw new RaplaSecurityException(e.getMessage(), e);
}
Conflict[] conflictsBefore = null;
Conflict[] conflictsAfter = null;
try {
conflictsAfter = facade.getConflicts( r );
if ( original != null ) {
conflictsBefore = facade.getConflicts( original );
}
} catch ( RaplaException ex ) {
throw new RaplaSecurityException(" Can't check permissions due to:" + ex.getMessage(), ex );
}
Appointment[] appointments = r.getAppointments();
// ceck if the user has the permisson to add allocations in the given time
for (int i = 0; i < allocatables.length; i++ ) {
Allocatable allocatable = allocatables[i];
checkConflictsAllowed( user, allocatable, conflictsBefore, conflictsAfter );
for (int j = 0; j < appointments.length; j++ ) {
Appointment appointment = appointments[j];
Date today = operator.today();
if ( r.hasAllocated( allocatable, appointment ) &&
!FacadeImpl.hasPermissionToAllocate( user, appointment, allocatable, original,today ) ) {
String all = allocatable.getName( i18n.getLocale() );
String app = appointmentFormater.getSummary( appointment );
String error = i18n.format("warning.no_reserve_permission"
,all
,app);
throw new RaplaSecurityException( error );
}
}
}
if (original == null )
return;
Date today = operator.today();
// 1. calculate the deleted assignments from allocatable to appointments
// 2. check if they were allowed to change in the specified time
appointments = original.getAppointments();
allocatables = original.getAllocatables();
for (int i = 0; i < allocatables.length; i++ ) {
Allocatable allocatable = allocatables[i];
for (int j = 0; j < appointments.length; j++ ) {
Appointment appointment = appointments[j];
if ( original.hasAllocated( allocatable, appointment )
&& !r.hasAllocated( allocatable, appointment ) ) {
Date start = appointment.getStart();
Date end = appointment.getMaxEnd();
if ( !allocatable.canAllocate( user, start, end, today ) ) {
String all = allocatable.getName( i18n.getLocale() );
String app = appointmentFormater.getSummary( appointment );
String error = i18n.format("warning.no_reserve_permission"
,all
,app);
throw new RaplaSecurityException( error );
}
}
}
}
}
public void checkRead(User user,Entity entity) throws RaplaSecurityException, RaplaException {
RaplaType<?> raplaType = entity.getRaplaType();
if ( raplaType == Allocatable.TYPE)
{
Allocatable allocatable = (Allocatable) entity;
if ( !allocatable.canReadOnlyInformation( user))
{
throw new RaplaSecurityException(i18n.format("error.read_not_allowed",user, allocatable.getName( null)));
}
}
if ( raplaType == Preferences.TYPE)
{
Ownable ownable = (Preferences) entity;
User owner = ownable.getOwner();
if ( user != null && !user.isAdmin() && (owner == null || !user.equals( owner)))
{
throw new RaplaSecurityException(i18n.format("error.read_not_allowed", user, entity));
}
}
}
public void checkWritePermissions(User user, PreferencePatch patch) throws RaplaSecurityException
{
String ownerId = patch.getUserId();
if ( user != null && !user.isAdmin() && (ownerId == null || !user.getId().equals( ownerId)))
{
throw new RaplaSecurityException("User " + user + " can't modify preferences " + ownerId);
}
}
}
| 04900db4-clienttest | src/org/rapla/server/internal/SecurityManager.java | Java | gpl3 | 16,875 |