code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.client.internal;
import java.awt.Component;
import java.util.Locale;
import javax.swing.Action;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JList;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.logger.Logger;
import org.rapla.gui.toolkit.RaplaWidget;
final public class LanguageChooser implements RaplaWidget
{
JComboBox jComboBox;
String country;
RaplaContext context;
Logger logger;
public LanguageChooser(Logger logger,RaplaContext context) throws RaplaException {
this.logger = logger;
this.context = context;
final I18nBundle i18n = context.lookup( RaplaComponent.RAPLA_RESOURCES);
final RaplaLocale raplaLocale = context.lookup( RaplaLocale.class );
country = raplaLocale.getLocale().getCountry();
String[] languages = raplaLocale.getAvailableLanguages();
String[] entries = new String[languages.length + 1];
System.arraycopy( languages, 0, entries, 1, languages.length);
@SuppressWarnings("unchecked")
JComboBox jComboBox2 = new JComboBox(entries);
jComboBox = jComboBox2;
DefaultListCellRenderer aRenderer = new DefaultListCellRenderer() {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
if ( value != null)
{
value = new Locale( (String) value,country).getDisplayLanguage( raplaLocale.getLocale());
}
else
{
value = i18n.getString("default") + " " + i18n.getString("preferences");
}
return super.getListCellRendererComponent(list,
value,
index,
isSelected,
cellHasFocus);
}
};
setRenderer(aRenderer);
//jComboBox.setSelectedItem( raplaLocale.getLocale().getLanguage());
}
@SuppressWarnings("unchecked")
private void setRenderer(DefaultListCellRenderer aRenderer) {
jComboBox.setRenderer(aRenderer);
}
public JComponent getComponent() {
return jComboBox;
}
public void setSelectedLanguage(String lang) {
jComboBox.setSelectedItem(lang);
}
public String getSelectedLanguage()
{
return (String) jComboBox.getSelectedItem();
}
public void setChangeAction( Action languageChanged )
{
jComboBox.setAction( languageChanged );
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Frithjof Kurtz |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.client.internal;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.image.ImageObserver;
import java.beans.PropertyVetoException;
import java.net.URL;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.LocaleChangeEvent;
import org.rapla.components.xmlbundle.LocaleChangeListener;
import org.rapla.components.xmlbundle.LocaleSelector;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.toolkit.RaplaFrame;
public final class LoginDialog extends RaplaFrame implements LocaleChangeListener
{
private static final long serialVersionUID = -1887723833652617352L;
Container container;
JPanel upperpanel = new JPanel();
JPanel lowerpanel = new JPanel();
JLabel chooseLanguageLabel = new JLabel();
JPanel userandpassword = new JPanel();
JPanel buttonPanel = new JPanel();
JTextField username = new JTextField(15);
JPasswordField password = new JPasswordField(15);
JLabel usernameLabel = new JLabel();
JLabel passwordLabel = new JLabel();
JButton loginBtn = new JButton();
JButton exitBtn = new JButton();
I18nBundle i18n;
ImageObserver observer;
Image image;
JPanel canvas;
protected LocaleSelector localeSelector;
StartupEnvironment env;
// we have to add an extra gui component here because LoginDialog extends RaplaFrame and therefore can't extent RaplaGUIComponent
RaplaGUIComponent guiComponent;
public LoginDialog(RaplaContext context) throws RaplaException
{
super(context);
this.guiComponent = new RaplaGUIComponent(context);
env = context.lookup( StartupEnvironment.class );
i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
localeSelector = context.lookup(LocaleSelector.class);
localeSelector.addLocaleChangeListener(this);
}
public static LoginDialog create(RaplaContext sm, JComponent languageSelector) throws RaplaException
{
LoginDialog dlg = new LoginDialog(sm);
dlg.init(languageSelector);
return dlg;
}
Action exitAction;
public void setLoginAction(Action action)
{
loginBtn.setAction(action);
}
public void setExitAction(Action action)
{
exitAction = action;
exitBtn.setAction( action );
}
private void init(JComponent languageSelector)
{
container = getContentPane();
container.setLayout(new BorderLayout());
((JComponent) container).setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// ################## BEGIN LOGO ###################
observer = new ImageObserver()
{
public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h)
{
if ((flags & ALLBITS) != 0)
{
canvas.repaint();
}
return (flags & (ALLBITS | ABORT | ERROR)) == 0;
}
};
canvas = new JPanel()
{
private static final long serialVersionUID = 1L;
public void paint(Graphics g)
{
g.drawImage(image, 0, 0, observer);
}
};
Toolkit toolkit = Toolkit.getDefaultToolkit();
// creating an URL to the path of the picture
URL url = LoginDialog.class.getResource("/org/rapla/gui/images/tafel.png");
// getting it as image object
image = toolkit.createImage(url);
container.add(canvas, BorderLayout.CENTER);
MediaTracker mt = new MediaTracker(container);
mt.addImage(image, 0);
try
{
mt.waitForID(0);
}
catch (InterruptedException e)
{
}
// ################## END LOGO ###################
// ################## BEGIN LABELS AND TEXTFIELDS ###################
container.add(lowerpanel, BorderLayout.SOUTH);
lowerpanel.setLayout(new BorderLayout());
lowerpanel.add(userandpassword, BorderLayout.NORTH);
double pre = TableLayout.PREFERRED;
double fill = TableLayout.FILL;
double[][] sizes = { { pre, 10, fill }, { pre, 5, pre, 5, pre, 5 } };
TableLayout tableLayout = new TableLayout(sizes);
userandpassword.setLayout(tableLayout);
userandpassword.add(chooseLanguageLabel,"0,0");
userandpassword.add(languageSelector, "2,0");
userandpassword.add(usernameLabel, "0,2");
userandpassword.add(passwordLabel, "0,4");
userandpassword.add(username, "2,2");
userandpassword.add(password, "2,4");
username.setColumns(14);
password.setColumns(14);
Listener listener = new Listener();
password.addActionListener(listener);
languageSelector.addFocusListener(listener);
guiComponent.addCopyPaste( username);
guiComponent.addCopyPaste( password );
// ################## END LABELS AND TEXTFIELDS ###################
// ################## BEGIN BUTTONS ###################
// this is a separate JPanel for the buttons at the bottom
GridLayout gridLayout = new GridLayout(1, 2);
gridLayout.setHgap(20);
buttonPanel.setLayout(gridLayout);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// adding a button for exiting
buttonPanel.add(exitBtn);
// and to login
buttonPanel.add(loginBtn);
setLocale();
username.requestFocus();
int startupEnv = env.getStartupMode();
if( startupEnv != StartupEnvironment.WEBSTART && startupEnv != StartupEnvironment.APPLET) {
try
{
String userName = System.getProperty("user.name");
username.setText(userName);
username.selectAll();
}
catch (SecurityException ex)
{
// Not sure if it is needed, to catch this. I don't know if a custom system property is by default protected in a sandbox environment
}
}
lowerpanel.add(buttonPanel, BorderLayout.SOUTH);
// ################## END BUTTONS ###################
// ################## BEGIN FRAME ###################
// these are the dimensions of the rapla picture
int picturewidth = 362;
int pictureheight = 182;
// and a border around it
int border = 10;
// canvas.setBounds(0, 0, picturewidth, pictureheight);
this.getRootPane().setDefaultButton(loginBtn);
// with the picture dimensions as basis we determine the size
// of the frame, including some additional space below the picture
this.setSize(picturewidth + 2 * border, pictureheight + 210);
this.setResizable(false);
// ################## END FRAME ###################
}
boolean closeCalledFromOutside = false;
@Override
public void close() {
closeCalledFromOutside = true;
super.close();
}
protected void fireFrameClosing() throws PropertyVetoException {
super.fireFrameClosing();
if ( !closeCalledFromOutside && exitAction != null)
{
exitAction.actionPerformed( new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "exit"));
}
}
public String getUsername()
{
return username.getText();
}
public char[] getPassword()
{
return password.getPassword();
}
public void resetPassword() {
password.setText("");
}
/** overrides localeChanged from DialogUI */
public void localeChanged(LocaleChangeEvent evt)
{
setLocale();
}
private I18nBundle getI18n()
{
return i18n;
}
private void setLocale()
{
chooseLanguageLabel.setText(getI18n().getString("choose_language"));
exitBtn.setText(getI18n().getString("exit"));
loginBtn.setText(getI18n().getString("login"));
usernameLabel.setText(getI18n().getString("username") + ":");
passwordLabel.setText(getI18n().getString("password") + ":");
setTitle(getI18n().getString("logindialog.title"));
repaint();
}
public void dispose()
{
super.dispose();
localeSelector.removeLocaleChangeListener(this);
}
public void testEnter(String newUsername, String newPassword)
{
username.setText(newUsername);
password.setText(newPassword);
}
class Listener extends FocusAdapter implements ActionListener
{
boolean bInit = false;
public void focusGained(FocusEvent e)
{
if (!bInit)
{
username.requestFocus();
bInit = true;
}
}
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == password)
{
loginBtn.doClick();
return;
}
}
}
}
| Java |
/*--------------------------------------------------------------------------*
main.raplaContainer.dispose();
| 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.client.internal;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.Semaphore;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import org.rapla.ConnectInfo;
import org.rapla.RaplaMainContainer;
import org.rapla.client.ClientService;
import org.rapla.client.ClientServiceContainer;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.client.RaplaClientListener;
import org.rapla.components.calendar.DateRenderer;
import org.rapla.components.iolayer.DefaultIO;
import org.rapla.components.iolayer.IOInterface;
import org.rapla.components.iolayer.WebstartIO;
import org.rapla.components.util.Cancelable;
import org.rapla.components.util.Command;
import org.rapla.components.util.CommandScheduler;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.LocaleSelector;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ClientFacade;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.facade.RaplaComponent;
import org.rapla.facade.UpdateErrorListener;
import org.rapla.facade.UserModule;
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.StartupEnvironment;
import org.rapla.framework.internal.ComponentInfo;
import org.rapla.framework.internal.ContainerImpl;
import org.rapla.framework.internal.RaplaMetaConfigInfo;
import org.rapla.framework.logger.Logger;
import org.rapla.gui.AnnotationEditExtension;
import org.rapla.gui.EditController;
import org.rapla.gui.InfoFactory;
import org.rapla.gui.MenuFactory;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.ReservationController;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.images.Images;
import org.rapla.gui.internal.CalendarOption;
import org.rapla.gui.internal.MainFrame;
import org.rapla.gui.internal.MenuFactoryImpl;
import org.rapla.gui.internal.RaplaDateRenderer;
import org.rapla.gui.internal.RaplaStartOption;
import org.rapla.gui.internal.UserOption;
import org.rapla.gui.internal.WarningsOption;
import org.rapla.gui.internal.common.InternMenus;
import org.rapla.gui.internal.common.RaplaClipboard;
import org.rapla.gui.internal.edit.EditControllerImpl;
import org.rapla.gui.internal.edit.annotation.CategorizationAnnotationEdit;
import org.rapla.gui.internal.edit.annotation.ColorAnnotationEdit;
import org.rapla.gui.internal.edit.annotation.EmailAnnotationEdit;
import org.rapla.gui.internal.edit.annotation.ExpectedColumnsAnnotationEdit;
import org.rapla.gui.internal.edit.annotation.ExpectedRowsAnnotationEdit;
import org.rapla.gui.internal.edit.reservation.ConflictReservationCheck;
import org.rapla.gui.internal.edit.reservation.DefaultReservationCheck;
import org.rapla.gui.internal.edit.reservation.ReservationControllerImpl;
import org.rapla.gui.internal.view.InfoFactoryImpl;
import org.rapla.gui.internal.view.LicenseInfoUI;
import org.rapla.gui.internal.view.TreeFactoryImpl;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.FrameControllerList;
import org.rapla.gui.toolkit.RaplaFrame;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaMenubar;
import org.rapla.gui.toolkit.RaplaSeparator;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
import org.rapla.storage.StorageOperator;
import org.rapla.storage.dbrm.RemoteConnectionInfo;
import org.rapla.storage.dbrm.RemoteOperator;
import org.rapla.storage.dbrm.RestartServer;
import org.rapla.storage.dbrm.StatusUpdater;
/** Implementation of the ClientService.
*/
public class RaplaClientServiceImpl extends ContainerImpl implements ClientServiceContainer,ClientService,UpdateErrorListener
{
Vector<RaplaClientListener> listenerList = new Vector<RaplaClientListener>();
I18nBundle i18n;
boolean started;
boolean restartingGUI;
String facadeName;
boolean defaultLanguageChoosen;
FrameControllerList frameControllerList;
Configuration config;
boolean logoutAvailable;
ConnectInfo reconnectInfo;
static boolean lookAndFeelSet;
CommandScheduler commandQueueWrapper;
public RaplaClientServiceImpl(RaplaContext parentContext,Configuration config,Logger logger) throws RaplaException {
super(parentContext,config, logger);
this.config = config;
}
@Override
protected Map<String,ComponentInfo> getComponentInfos() {
return new RaplaMetaConfigInfo();
}
public static void setLookandFeel() {
if ( lookAndFeelSet )
{
return;
}
UIDefaults defaults = UIManager.getDefaults();
Font textFont = defaults.getFont("Label.font");
if ( textFont == null)
{
textFont = new Font("SansSerif", Font.PLAIN, 12);
}
else
{
textFont = textFont.deriveFont( Font.PLAIN );
}
defaults.put("Label.font", textFont);
defaults.put("Button.font", textFont);
defaults.put("Menu.font", textFont);
defaults.put("MenuItem.font", textFont);
defaults.put("RadioButton.font", textFont);
defaults.put("CheckBoxMenuItem.font", textFont);
defaults.put("CheckBox.font", textFont);
defaults.put("ComboBox.font", textFont);
defaults.put("Tree.expandedIcon",Images.getIcon("/org/rapla/gui/images/eclipse-icons/tree_minus.gif"));
defaults.put("Tree.collapsedIcon",Images.getIcon("/org/rapla/gui/images/eclipse-icons/tree_plus.gif"));
defaults.put("TitledBorder.font", textFont.deriveFont(Font.PLAIN,(float)10.));
lookAndFeelSet = true;
}
protected void init() throws RaplaException {
advanceLoading(false);
StartupEnvironment env = getContext().lookup(StartupEnvironment.class);
int startupMode = env.getStartupMode();
final Logger logger = getLogger();
if ( startupMode != StartupEnvironment.APPLET && startupMode != StartupEnvironment.WEBSTART)
{
try
{
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
logger.error("uncaught exception", e);
}
});
}
catch (Throwable ex)
{
logger.error("Can't set default exception handler-", ex);
}
}
setLookandFeel();
defaultLanguageChoosen = true;
getLogger().info("Starting gui ");
super.init( );
facadeName = m_config.getChild("facade").getValue("*");
addContainerProvidedComponent( WELCOME_FIELD, LicenseInfoUI.class );
addContainerProvidedComponent( MAIN_COMPONENT, RaplaFrame.class);
// overwrite commandqueue because we need to synchronize with swing
commandQueueWrapper = new AWTWrapper((DefaultScheduler)getContext().lookup(CommandScheduler.class));
addContainerProvidedComponentInstance( CommandScheduler.class, commandQueueWrapper);
addContainerProvidedComponent( RaplaClipboard.class, RaplaClipboard.class );
addContainerProvidedComponent( TreeFactory.class, TreeFactoryImpl.class );
addContainerProvidedComponent( MenuFactory.class, MenuFactoryImpl.class );
addContainerProvidedComponent( InfoFactory.class, InfoFactoryImpl.class );
addContainerProvidedComponent( EditController.class, EditControllerImpl.class );
addContainerProvidedComponent( ReservationController.class, ReservationControllerImpl.class );
addContainerProvidedComponent( RaplaClientExtensionPoints.USER_OPTION_PANEL_EXTENSION ,UserOption.class);
addContainerProvidedComponent( RaplaClientExtensionPoints.USER_OPTION_PANEL_EXTENSION , CalendarOption.class);
addContainerProvidedComponent( RaplaClientExtensionPoints.USER_OPTION_PANEL_EXTENSION , WarningsOption.class);
addContainerProvidedComponent( RaplaClientExtensionPoints.SYSTEM_OPTION_PANEL_EXTENSION, CalendarOption.class );
addContainerProvidedComponent( RaplaClientExtensionPoints.SYSTEM_OPTION_PANEL_EXTENSION, RaplaStartOption.class );
addContainerProvidedComponent( AnnotationEditExtension.ATTRIBUTE_ANNOTATION_EDIT, ColorAnnotationEdit.class);
addContainerProvidedComponent( AnnotationEditExtension.ATTRIBUTE_ANNOTATION_EDIT, CategorizationAnnotationEdit.class);
addContainerProvidedComponent( AnnotationEditExtension.ATTRIBUTE_ANNOTATION_EDIT, ExpectedRowsAnnotationEdit.class);
addContainerProvidedComponent( AnnotationEditExtension.ATTRIBUTE_ANNOTATION_EDIT, ExpectedColumnsAnnotationEdit.class);
addContainerProvidedComponent( AnnotationEditExtension.ATTRIBUTE_ANNOTATION_EDIT, EmailAnnotationEdit.class);
frameControllerList = new FrameControllerList(getLogger().getChildLogger("framelist"));
addContainerProvidedComponentInstance(FrameControllerList.class,frameControllerList);
RaplaMenubar menuBar = new RaplaMenubar();
RaplaMenu systemMenu = new RaplaMenu( InternMenus.FILE_MENU_ROLE.getId() );
RaplaMenu editMenu = new RaplaMenu( InternMenus.EDIT_MENU_ROLE.getId() );
RaplaMenu viewMenu = new RaplaMenu( InternMenus.VIEW_MENU_ROLE.getId() );
RaplaMenu helpMenu = new RaplaMenu( InternMenus.EXTRA_MENU_ROLE.getId() );
RaplaMenu newMenu = new RaplaMenu( InternMenus.NEW_MENU_ROLE.getId() );
RaplaMenu settingsMenu = new RaplaMenu( InternMenus.CALENDAR_SETTINGS.getId());
RaplaMenu adminMenu = new RaplaMenu( InternMenus.ADMIN_MENU_ROLE.getId() );
RaplaMenu importMenu = new RaplaMenu( InternMenus.IMPORT_MENU_ROLE.getId());
RaplaMenu exportMenu = new RaplaMenu( InternMenus.EXPORT_MENU_ROLE.getId());
menuBar.add( systemMenu );
menuBar.add( editMenu );
menuBar.add( viewMenu );
menuBar.add( helpMenu );
addContainerProvidedComponentInstance( SESSION_MAP, new HashMap<Object,Object>());
addContainerProvidedComponentInstance( InternMenus.MENU_BAR, menuBar);
addContainerProvidedComponentInstance( InternMenus.FILE_MENU_ROLE, systemMenu );
addContainerProvidedComponentInstance( InternMenus.EDIT_MENU_ROLE, editMenu);
addContainerProvidedComponentInstance( InternMenus.VIEW_MENU_ROLE, viewMenu);
addContainerProvidedComponentInstance( InternMenus.ADMIN_MENU_ROLE, adminMenu);
addContainerProvidedComponentInstance( InternMenus.IMPORT_MENU_ROLE, importMenu );
addContainerProvidedComponentInstance( InternMenus.EXPORT_MENU_ROLE, exportMenu );
addContainerProvidedComponentInstance( InternMenus.NEW_MENU_ROLE, newMenu );
addContainerProvidedComponentInstance( InternMenus.CALENDAR_SETTINGS, settingsMenu );
addContainerProvidedComponentInstance( InternMenus.EXTRA_MENU_ROLE, helpMenu );
editMenu.add( new RaplaSeparator("EDIT_BEGIN"));
editMenu.add( new RaplaSeparator("EDIT_END"));
addContainerProvidedComponent(RaplaClientExtensionPoints.RESERVATION_SAVE_CHECK, DefaultReservationCheck.class);
addContainerProvidedComponent(RaplaClientExtensionPoints.RESERVATION_SAVE_CHECK, ConflictReservationCheck.class);
boolean webstartEnabled =getContext().lookup(StartupEnvironment.class).getStartupMode() == StartupEnvironment.WEBSTART;
if (webstartEnabled) {
addContainerProvidedComponent( IOInterface.class,WebstartIO.class );
} else {
addContainerProvidedComponent( IOInterface.class,DefaultIO.class );
}
//Add this service to the container
addContainerProvidedComponentInstance(ClientService.class, this);
}
protected Runnable createTask(final Command command) {
Runnable timerTask = new Runnable() {
public void run() {
Runnable runnable = RaplaClientServiceImpl.super.createTask( command);
javax.swing.SwingUtilities.invokeLater(runnable);
}
public String toString()
{
return command.toString();
}
};
return timerTask;
}
/** override to synchronize tasks with the swing event queue*/
class AWTWrapper implements CommandScheduler
{
DefaultScheduler parent;
public AWTWrapper(DefaultScheduler parent) {
this.parent = parent;
}
@Override
public Cancelable schedule(Command command, long delay) {
Runnable task = createTask(command);
return parent.schedule(task, delay);
}
@Override
public Cancelable schedule(Command command, long delay, long period) {
Runnable task = createTask(command);
return parent.schedule(task, delay, period);
}
public String toString()
{
return parent.toString();
}
}
public ClientFacade getFacade() throws RaplaContextException {
return lookup(ClientFacade.class, facadeName);
}
public void start(ConnectInfo connectInfo) throws Exception {
if (started)
return;
try {
getLogger().debug("RaplaClient started");
i18n = getContext().lookup(RaplaComponent.RAPLA_RESOURCES );
ClientFacade facade = getFacade();
facade.addUpdateErrorListener(this);
StorageOperator operator = facade.getOperator();
if ( operator instanceof RemoteOperator)
{
RemoteConnectionInfo remoteConnection = ((RemoteOperator) operator).getRemoteConnectionInfo();
remoteConnection.setStatusUpdater( new StatusUpdater()
{
private Cursor waitCursor = new Cursor(Cursor.WAIT_CURSOR);
private Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR);
public void setStatus(Status status) {
Cursor cursor =( status == Status.BUSY) ? waitCursor: defaultCursor;
frameControllerList.setCursor( cursor);
}
}
);
}
advanceLoading(true);
logoutAvailable = true;
if ( connectInfo != null && connectInfo.getUsername() != null)
{
if (login( connectInfo))
{
beginRaplaSession();
return;
}
}
startLogin();
} catch (Exception ex) {
throw ex;
} finally {
}
}
protected void advanceLoading(boolean finish) {
try
{
Class<?> LoadingProgressC= null;
Object progressBar = null;
if ( getContext().lookup(StartupEnvironment.class).getStartupMode() == StartupEnvironment.CONSOLE)
{
LoadingProgressC = getClass().getClassLoader().loadClass("org.rapla.bootstrap.LoadingProgress");
progressBar = LoadingProgressC.getMethod("getInstance").invoke(null);
if ( finish)
{
LoadingProgressC.getMethod("close").invoke( progressBar);
}
else
{
LoadingProgressC.getMethod("advance").invoke( progressBar);
}
}
}
catch (Exception ex)
{
// Loading progress failure is not crucial to rapla excecution
}
}
/**
* @throws RaplaException
*
*/
private void beginRaplaSession() throws RaplaException {
initLanguage();
ClientFacade facade = getFacade();
addContainerProvidedComponentInstance( ClientFacade.class, facade);
final CalendarSelectionModel model = createCalendarModel();
addContainerProvidedComponentInstance( CalendarModel.class, model );
addContainerProvidedComponentInstance( CalendarSelectionModel.class, model );
StorageOperator operator = facade.getOperator();
if ( operator instanceof RestartServer)
{
addContainerProvidedComponentInstance(RestartServer.class, (RestartServer)operator);
}
((FacadeImpl)facade).addDirectModificationListener( new ModificationListener() {
public void dataChanged(ModificationEvent evt) throws RaplaException {
model.dataChanged( evt );
}
});
// if ( facade.isClientForServer() )
// {
// addContainerProvidedComponent (RaplaClientExtensionPoints.SYSTEM_OPTION_PANEL_EXTENSION , ConnectionOption.class);
// }
Set<String> pluginNames;
//List<PluginDescriptor<ClientServiceContainer>> pluginList;
try {
pluginNames = getContext().lookup( RaplaMainContainer.PLUGIN_LIST);
} catch (RaplaContextException ex) {
throw new RaplaException (ex );
}
List<PluginDescriptor<ClientServiceContainer>> pluginList = new ArrayList<PluginDescriptor<ClientServiceContainer>>( );
Logger logger = getLogger().getChildLogger("plugin");
for ( String plugin:pluginNames)
{
try {
boolean found = false;
try {
if ( plugin.toLowerCase().endsWith("serverplugin") || plugin.contains(".server."))
{
continue;
}
Class<?> componentClass = RaplaClientServiceImpl.class.getClassLoader().loadClass( plugin );
Method[] methods = componentClass.getMethods();
for ( Method method:methods)
{
if ( method.getName().equals("provideServices"))
{
Class<?> type = method.getParameterTypes()[0];
if (ClientServiceContainer.class.isAssignableFrom(type))
{
found = true;
}
}
}
} catch (ClassNotFoundException ex) {
continue;
} catch (NoClassDefFoundError ex) {
getLogger().error("Error loading plugin " + plugin + " " +ex.getMessage());
continue;
} catch (Exception e1) {
getLogger().error("Error loading plugin " + plugin + " " +e1.getMessage());
continue;
}
if ( found )
{
@SuppressWarnings("unchecked")
PluginDescriptor<ClientServiceContainer> descriptor = (PluginDescriptor<ClientServiceContainer>) instanciate(plugin, null, logger);
pluginList.add(descriptor);
logger.info("Installed plugin "+plugin);
}
} catch (RaplaContextException e) {
if (e.getCause() instanceof ClassNotFoundException) {
logger.error("Could not instanciate plugin "+ plugin, e);
}
}
}
addContainerProvidedComponentInstance(ClientServiceContainer.CLIENT_PLUGIN_LIST, pluginList);
initializePlugins( pluginList, facade.getSystemPreferences() );
// Add daterender if not provided by the plugins
if ( !getContext().has( DateRenderer.class))
{
addContainerProvidedComponent( DateRenderer.class, RaplaDateRenderer.class );
}
started = true;
User user = model.getUser();
boolean showToolTips = facade.getPreferences( user ).getEntryAsBoolean( RaplaBuilder.SHOW_TOOLTIP_CONFIG_ENTRY, true);
javax.swing.ToolTipManager.sharedInstance().setEnabled(showToolTips);
//javax.swing.ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);
javax.swing.ToolTipManager.sharedInstance().setInitialDelay( 1000 );
javax.swing.ToolTipManager.sharedInstance().setDismissDelay( 10000 );
javax.swing.ToolTipManager.sharedInstance().setReshowDelay( 0 );
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
RaplaFrame mainComponent = getContext().lookup( MAIN_COMPONENT );
mainComponent.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
try {
if ( !isRestartingGUI()) {
stop();
} else {
restartingGUI = false;
}
} catch (Exception ex) {
getLogger().error(ex.getMessage(),ex);
}
}
});
MainFrame mainFrame = new MainFrame( getContext());
fireClientStarted();
mainFrame.show();
}
private void initLanguage() throws RaplaException, RaplaContextException
{
ClientFacade facade = getFacade();
if ( !defaultLanguageChoosen)
{
Preferences prefs = facade.edit(facade.getPreferences());
RaplaLocale raplaLocale = getContext().lookup(RaplaLocale.class );
String currentLanguage = raplaLocale.getLocale().getLanguage();
prefs.putEntry( RaplaLocale.LANGUAGE_ENTRY, currentLanguage);
try
{
facade.store( prefs);
}
catch (Exception e)
{
getLogger().error("Can't store language change", e);
}
}
else
{
String language = facade.getPreferences().getEntryAsString( RaplaLocale.LANGUAGE_ENTRY, null);
if ( language != null)
{
LocaleSelector localeSelector = getContext().lookup(LocaleSelector.class);
localeSelector.setLanguage( language );
}
}
AttributeImpl.TRUE_TRANSLATION.setName(i18n.getLang(), i18n.getString("yes"));
AttributeImpl.FALSE_TRANSLATION.setName(i18n.getLang(), i18n.getString("no"));
}
protected void initializePlugins(List<PluginDescriptor<ClientServiceContainer>> pluginList, Preferences preferences) throws RaplaException {
RaplaConfiguration raplaConfig =preferences.getEntry(RaplaComponent.PLUGIN_CONFIG);
// Add plugin configs
for ( Iterator<PluginDescriptor<ClientServiceContainer>> it = pluginList.iterator(); it.hasNext(); ) {
PluginDescriptor<ClientServiceContainer> pluginDescriptor = it.next();
String pluginClassname = pluginDescriptor.getClass().getName();
Configuration pluginConfig = null;
if ( raplaConfig != null) {
pluginConfig = raplaConfig.find("class", pluginClassname);
}
if ( pluginConfig == null) {
pluginConfig = new DefaultConfiguration("plugin");
}
pluginDescriptor.provideServices( this, pluginConfig );
}
//Collection<?> clientPlugins = getAllServicesForThisContainer(RaplaExtensionPoints.CLIENT_EXTENSION);
// start plugins
getAllServicesForThisContainer(RaplaClientExtensionPoints.CLIENT_EXTENSION);
// for (Iterator<?> it = clientPlugins.iterator();it.hasNext();) {
// String hint = (String) it.next();
// try {
// getContext().lookup( RaplaExtensionPoints.CLIENT_EXTENSION , hint);
// getLogger().info( "Initialize " + hint );
// } catch (RaplaContextException ex ) {
// getLogger().error( "Can't initialize " + hint, ex );
// }
// }
}
public boolean isRestartingGUI()
{
return restartingGUI;
}
public void addRaplaClientListener(RaplaClientListener listener) {
listenerList.add(listener);
}
public void removeRaplaClientListener(RaplaClientListener listener) {
listenerList.remove(listener);
}
public RaplaClientListener[] getRaplaClientListeners() {
return listenerList.toArray(new RaplaClientListener[]{});
}
protected void fireClientClosed(ConnectInfo reconnect) {
RaplaClientListener[] listeners = getRaplaClientListeners();
for (int i=0;i<listeners.length;i++)
listeners[i].clientClosed(reconnect);
}
protected void fireClientStarted() {
RaplaClientListener[] listeners = getRaplaClientListeners();
for (int i=0;i<listeners.length;i++)
listeners[i].clientStarted();
}
protected void fireClientAborted() {
RaplaClientListener[] listeners = getRaplaClientListeners();
for (int i=0;i<listeners.length;i++)
listeners[i].clientAborted();
}
public boolean isRunning() {
return started;
}
public void switchTo(User user) throws RaplaException
{
ClientFacade facade = getFacade();
if ( user == null)
{
if ( reconnectInfo == null || reconnectInfo.getConnectAs() == null)
{
throw new RaplaException( "Can't switch back because there were no previous logins.");
}
final String oldUser = facade.getUser().getUsername();
String newUser = reconnectInfo.getUsername();
char[] password = reconnectInfo.getPassword();
getLogger().info("Login From:" + oldUser + " To:" + newUser);
ConnectInfo reconnectInfo = new ConnectInfo( newUser, password);
stop( reconnectInfo);
}
else
{
if ( reconnectInfo == null)
{
throw new RaplaException( "Can't switch to user, because admin login information not provided due missing login.");
}
if ( reconnectInfo.getConnectAs() != null)
{
throw new RaplaException( "Can't switch to user, because already switched.");
}
final String oldUser = reconnectInfo.getUsername();
final String newUser = user.getUsername();
getLogger().info("Login From:" + oldUser + " To:" + newUser);
ConnectInfo newInfo = new ConnectInfo( oldUser, reconnectInfo.getPassword(), newUser);
stop( newInfo);
}
// fireUpdateEvent(new ModificationEvent());
}
public boolean canSwitchBack() {
return reconnectInfo != null && reconnectInfo.getConnectAs() != null;
}
private void stop() {
stop( null );
}
private void stop(ConnectInfo reconnect) {
if (!started)
return;
try {
ClientFacade facade = getFacade();
facade.removeUpdateErrorListener( this);
if ( facade.isSessionActive())
{
facade.logout();
}
} catch (RaplaException ex) {
getLogger().error("Clean logout failed. " + ex.getMessage());
}
started = false;
fireClientClosed(reconnect);
}
public void dispose() {
if (frameControllerList != null)
frameControllerList.closeAll();
stop();
super.dispose();
getLogger().debug("RaplaClient disposed");
}
private void startLogin() throws Exception {
Command object = new Command()
{
public void execute() throws Exception {
startLoginInThread();
}
};
commandQueueWrapper.schedule( object, 0);
}
private void startLoginInThread() {
final Semaphore loginMutex = new Semaphore(1);
try {
final RaplaContext context = getContext();
final Logger logger = getLogger();
final LanguageChooser languageChooser = new LanguageChooser(logger, context);
final LoginDialog dlg = LoginDialog.create(context, languageChooser.getComponent());
Action languageChanged = new AbstractAction()
{
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
try {
String lang = languageChooser.getSelectedLanguage();
if (lang == null)
{
defaultLanguageChoosen = true;
}
else
{
defaultLanguageChoosen = false;
getLogger().debug("Language changing to " + lang );
LocaleSelector localeSelector = context.lookup( LocaleSelector.class );
localeSelector.setLanguage(lang);
getLogger().info("Language changed " + localeSelector.getLanguage() );
}
} catch (Exception ex) {
getLogger().error("Can't change language",ex);
}
}
};
languageChooser.setChangeAction( languageChanged);
//dlg.setIcon( i18n.getIcon("icon.rapla-small"));
Action loginAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
String username = dlg.getUsername();
char[] password = dlg.getPassword();
boolean success = false;
try {
String connectAs = null;
reconnectInfo = new ConnectInfo(username, password, connectAs);
success = login(reconnectInfo);
if ( !success )
{
dlg.resetPassword();
RaplaGUIComponent.showWarning(i18n.getString("error.login"), dlg,context,logger);
}
}
catch (RaplaException ex)
{
dlg.resetPassword();
RaplaGUIComponent.showException(ex, dlg, context, logger);
}
if ( success) {
dlg.close();
loginMutex.release();
try {
beginRaplaSession();
} catch (Throwable ex) {
RaplaGUIComponent.showException(ex, null, context, logger);
fireClientAborted();
}
} // end of else
}
};
Action exitAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
dlg.close();
loginMutex.release();
stop();
fireClientAborted();
}
};
loginAction.putValue(Action.NAME,i18n.getString("login"));
exitAction.putValue(Action.NAME,i18n.getString("exit"));
dlg.setIconImage(i18n.getIcon("icon.rapla_small").getImage());
dlg.setLoginAction( loginAction);
dlg.setExitAction( exitAction );
//dlg.setSize( 480, 270);
FrameControllerList.centerWindowOnScreen( dlg) ;
dlg.setVisible( true );
loginMutex.acquire();
} catch (Exception ex) {
getLogger().error("Error during Login ", ex);
stop();
fireClientAborted();
} finally {
loginMutex.release();
}
}
public void updateError(RaplaException ex) {
getLogger().error("Error updating data", ex);
}
/**
* @see org.rapla.facade.UpdateErrorListener#disconnected()
*/
public void disconnected(final String message) {
if ( started )
{
SwingUtilities.invokeLater( new Runnable() {
public void run() {
boolean modal = true;
String title = i18n.getString("restart_client");
try {
Component owner = frameControllerList.getMainWindow();
DialogUI dialog = DialogUI.create(getContext(), owner, modal, title, message);
Action action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
getLogger().warn("restart");
restart();
}
};
dialog.setAbortAction(action);
dialog.getButton(0).setAction( action);
dialog.start();
} catch (Throwable e) {
getLogger().error(e.getMessage(), e);
}
}
});
}
}
public void restart()
{
if ( reconnectInfo != null)
{
stop(reconnectInfo);
}
}
public void logout()
{
stop(new ConnectInfo(null, "".toCharArray()));
}
private boolean login(ConnectInfo connect) throws RaplaException
{
UserModule facade = getFacade();
if (facade.login(connect)) {
this.reconnectInfo = connect;
return true;
} else {
return false;
}
}
public boolean isLogoutAvailable()
{
return logoutAvailable;
}
private CalendarSelectionModel createCalendarModel() throws RaplaException {
User user = getFacade().getUser();
CalendarSelectionModel model = getFacade().newCalendarModel( user);
model.load( null );
return model;
}
}
| Java |
package org.rapla.client;
import java.util.List;
import org.rapla.ConnectInfo;
import org.rapla.framework.Container;
import org.rapla.framework.PluginDescriptor;
import org.rapla.framework.TypedComponentRole;
public interface ClientServiceContainer extends Container
{
TypedComponentRole<List<PluginDescriptor<ClientServiceContainer>>> CLIENT_PLUGIN_LIST = new TypedComponentRole<List<PluginDescriptor<ClientServiceContainer>>>("client-plugin-list");
void start(ConnectInfo connectInfo) throws Exception;
//void addCompontentOnClientStart(Class<ClientExtension> componentToStart);
boolean isRunning();
}
| Java |
package org.rapla.client;
/** classes implementing ClientExtension are started automaticaly when a user has successfully login into the Rapla system. A class added as service doesn't need to implement a specific interface and is instanciated automaticaly after client login. You can add a RaplaContext parameter to your constructor to get access to the services of rapla.
* Generally you don't need to start a client service. It is better to provide functionality through the RaplaClientExtensionPoints
*/
public interface ClientExtension {
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.facade.ModificationEvent;
public class UpdateResult implements ModificationEvent
{
private User user;
private List<UpdateOperation> operations = new ArrayList<UpdateOperation>();
Set<RaplaType> modified = new HashSet<RaplaType>();
boolean switchTemplateMode = false;
public UpdateResult(User user) {
this.user = user;
}
public void addOperation(final UpdateOperation operation) {
if ( operation == null)
throw new IllegalStateException( "Operation can't be null" );
operations.add(operation);
Entity current = operation.getCurrent();
if ( current != null)
{
RaplaType raplaType = current.getRaplaType();
modified.add( raplaType);
}
}
public User getUser() {
return user;
}
public Set<Entity> getRemoved() {
return getObject( Remove.class);
}
public Set<Entity> getChangeObjects() {
return getObject( Change.class);
}
public Set<Entity> getAddObjects() {
return getObject( Add.class);
}
@SuppressWarnings("unchecked")
public <T extends UpdateOperation> Iterator<T> getOperations( final Class<T> operationClass) {
Iterator<UpdateOperation> operationsIt = operations.iterator();
if ( operationClass == null)
throw new IllegalStateException( "OperationClass can't be null" );
List<T> list = new ArrayList<T>();
while ( operationsIt.hasNext() ) {
UpdateOperation obj = operationsIt.next();
if ( operationClass.equals( obj.getClass()))
{
list.add( (T)obj );
}
}
return list.iterator();
}
public Iterable<UpdateOperation> getOperations()
{
return Collections.unmodifiableCollection(operations);
}
protected <T extends UpdateOperation> Set<Entity> getObject( final Class<T> operationClass ) {
Set<Entity> set = new HashSet<Entity>();
if ( operationClass == null)
throw new IllegalStateException( "OperationClass can't be null" );
Iterator<? extends UpdateOperation> it= getOperations( operationClass);
while (it.hasNext() ) {
UpdateOperation next = it.next();
Entity current = next.getCurrent();
set.add( current);
}
return set;
}
static public class Add implements UpdateOperation {
Entity newObj; // the object in the state when it was added
public Add( Entity newObj) {
this.newObj = newObj;
}
public Entity getCurrent() {
return newObj;
}
public Entity getNew() {
return newObj;
}
public String toString()
{
return "Add " + newObj;
}
}
static public class Remove implements UpdateOperation {
Entity currentObj; // the actual represantation of the object
public Remove(Entity currentObj) {
this.currentObj = currentObj;
}
public Entity getCurrent() {
return currentObj;
}
public String toString()
{
return "Remove " + currentObj;
}
}
static public class Change implements UpdateOperation{
Entity newObj; // the object in the state when it was changed
Entity oldObj; // the object in the state before it was changed
public Change( Entity newObj, Entity oldObj) {
this.newObj = newObj;
this.oldObj = oldObj;
}
public Entity getCurrent() {
return newObj;
}
public Entity getNew() {
return newObj;
}
public Entity getOld() {
return oldObj;
}
public String toString()
{
return "Change " + oldObj + " to " + newObj;
}
}
TimeInterval timeInterval;
public void setInvalidateInterval(TimeInterval timeInterval)
{
this.timeInterval = timeInterval;
}
public TimeInterval getInvalidateInterval()
{
return timeInterval;
}
public TimeInterval calulateInvalidateInterval() {
TimeInterval currentInterval = null;
{
Iterator<Change> operations = getOperations( Change.class);
while (operations.hasNext())
{
Change change = operations.next();
currentInterval = expandInterval( change.getNew(), currentInterval);
currentInterval = expandInterval( change.getOld(), currentInterval);
}
}
{
Iterator<Add> operations = getOperations( Add.class);
while (operations.hasNext())
{
Add change = operations.next();
currentInterval = expandInterval( change.getNew(), currentInterval);
}
}
{
Iterator<Remove> operations = getOperations( Remove.class);
while (operations.hasNext())
{
Remove change = operations.next();
currentInterval = expandInterval( change.getCurrent(), currentInterval);
}
}
return currentInterval;
}
private TimeInterval expandInterval(RaplaObject obj,
TimeInterval currentInterval)
{
RaplaType type = obj.getRaplaType();
if ( type == Reservation.TYPE)
{
for ( Appointment app:((ReservationImpl)obj).getAppointmentList())
{
currentInterval = invalidateInterval( currentInterval, app);
}
}
return currentInterval;
}
private TimeInterval invalidateInterval(TimeInterval oldInterval,Appointment appointment)
{
Date start = appointment.getStart();
Date end = appointment.getMaxEnd();
TimeInterval interval = new TimeInterval(start, end).union( oldInterval);
return interval;
}
public boolean hasChanged(Entity object) {
return getChanged().contains(object);
}
public boolean isRemoved(Entity object) {
return getRemoved().contains( object);
}
public boolean isModified(Entity object)
{
return hasChanged(object) || isRemoved( object);
}
/** returns the modified objects from a given set.
* @deprecated use the retainObjects instead in combination with getChanged*/
public <T extends RaplaObject> Set<T> getChanged(Collection<T> col) {
return RaplaType.retainObjects(getChanged(),col);
}
/** returns the modified objects from a given set.
* @deprecated use the retainObjects instead in combination with getChanged*/
public <T extends RaplaObject> Set<T> getRemoved(Collection<T> col) {
return RaplaType.retainObjects(getRemoved(),col);
}
public Set<Entity> getChanged() {
Set<Entity> result = new HashSet<Entity>(getAddObjects());
result.addAll(getChangeObjects());
return result;
}
public boolean isModified(RaplaType raplaType)
{
return modified.contains( raplaType) ;
}
public boolean isModified() {
return !operations.isEmpty() || switchTemplateMode;
}
public boolean isEmpty() {
return !isModified() && timeInterval == null;
}
public void setSwitchTemplateMode(boolean b)
{
switchTemplateMode = b;
}
public boolean isSwitchTemplateMode() {
return switchTemplateMode;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage;
import org.rapla.framework.RaplaException;
public interface StorageUpdateListener
{
public void objectsUpdated(UpdateResult evt);
public void updateError(RaplaException ex);
public void storageDisconnected(String disconnectionMessage);
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
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.ParseDateException;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.components.util.TimeInterval;
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.configuration.internal.PreferencesImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.internal.DynamicTypeImpl;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.entities.internal.UserImpl;
import org.rapla.entities.storage.EntityReferencer;
import org.rapla.facade.Conflict;
import org.rapla.facade.internal.ConflictImpl;
public class UpdateEvent
{
transient Map listMap;// = new HashMap<Class, List<Entity>>();
List<CategoryImpl> categories = createList(Category.class);
List<DynamicTypeImpl> types = createList(DynamicType.class);
List<UserImpl> users = createList(User.class);
List<PreferencePatch> preferencesPatches = new ArrayList<PreferencePatch>();
List<PreferencesImpl> preferences = createList(Preferences.class);
List<AllocatableImpl> resources = createList(Allocatable.class);
List<ReservationImpl> reservations = createList(Reservation.class);
List<ConflictImpl> conflicts = createList(Conflict.class);
private Set<String> removeSet = new LinkedHashSet<String>();
private Set<String> storeSet = new LinkedHashSet<String>();
private String userId;
private boolean needResourcesRefresh = false;
private TimeInterval invalidateInterval;
private String lastValidated;
private int timezoneOffset;
public UpdateEvent() {
}
private <T> List<T> createList(@SuppressWarnings("unused") Class<? super T> clazz) {
ArrayList<T> list = new ArrayList<T>();
return list;
}
public void setUserId( String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
private void addRemove(Entity entity) {
removeSet.add( entity.getId());
add( entity);
}
private void addStore(Entity entity) {
storeSet.add( entity.getId());
add( entity);
}
@SuppressWarnings("unchecked")
public Map<Class, Collection<Entity>> getListMap() {
if ( listMap == null)
{
listMap = new HashMap<Class,Collection<Entity>>();
listMap.put( Preferences.class,preferences);
listMap.put( Allocatable.class,resources);
listMap.put(Category.class, categories);
listMap.put(User.class, users);
listMap.put(DynamicType.class, types);
listMap.put(Reservation.class, reservations);
listMap.put(Conflict.class, conflicts);
}
return listMap;
}
private void add(Entity entity) {
@SuppressWarnings("unchecked")
Class<? extends RaplaType> class1 = entity.getRaplaType().getTypeClass();
Collection<Entity> list = getListMap().get( class1);
if ( list == null)
{
//listMap.put( class1, list);
throw new IllegalArgumentException(entity.getRaplaType() + " can't be stored ");
}
list.add( entity);
}
public void putPatch(PreferencePatch patch)
{
preferencesPatches.add( patch);
}
public Collection<Entity> getRemoveObjects()
{
HashSet<Entity> objects = new LinkedHashSet<Entity>();
for ( Collection<Entity> list:getListMap().values())
{
for ( Entity entity:list)
{
if ( removeSet.contains( entity.getId()))
{
objects.add(entity);
}
}
}
return objects;
}
public Collection<Entity> getStoreObjects()
{
// Needs to be a linked hashset to keep the order of the entities
HashSet<Entity> objects = new LinkedHashSet<Entity>();
for ( Collection<Entity> list:getListMap().values())
{
for ( Entity entity:list)
{
if ( storeSet.contains( entity.getId()))
{
objects.add(entity);
}
}
}
return objects;
}
public Collection<EntityReferencer> getEntityReferences(boolean includeRemove)
{
HashSet<EntityReferencer> objects = new HashSet<EntityReferencer>();
for ( Collection<Entity> list:getListMap().values())
{
for ( Entity entity:list)
{
String id = entity.getId();
boolean contains = storeSet.contains( id) || (includeRemove && removeSet.contains( id));
if ( contains && entity instanceof EntityReferencer)
{
EntityReferencer references = (EntityReferencer)entity;
objects.add(references);
}
}
}
for ( PreferencePatch patch:preferencesPatches)
{
objects.add(patch);
}
return objects;
}
public List<PreferencePatch> getPreferencePatches()
{
return preferencesPatches;
}
/** use this method if you want to avoid adding the same Entity twice.*/
public void putStore(Entity entity) {
if (!storeSet.contains(entity.getId()))
addStore(entity);
}
/** use this method if you want to avoid adding the same Entity twice.*/
public void putRemove(Entity entity) {
if (!removeSet.contains(entity.getId()))
addRemove(entity);
}
/** find an entity in the update-event that matches the passed original. Returns null
* if no such entity is found. */
public Entity findEntity(Entity original) {
String originalId = original.getId();
if (!storeSet.contains( originalId))
{
if (!removeSet.contains( originalId))
{
return null;
}
}
for ( Collection<Entity> list:getListMap().values())
{
for ( Entity entity:list)
{
if ( entity.getId().equals( originalId))
{
return entity;
}
}
}
throw new IllegalStateException("Entity in store/remove set but not found in list");
}
public void setLastValidated( Date serverTime )
{
if ( serverTime == null)
{
this.lastValidated = null;
}
this.lastValidated = SerializableDateTimeFormat.INSTANCE.formatTimestamp(serverTime);
}
public void setInvalidateInterval(TimeInterval invalidateInterval)
{
this.invalidateInterval = invalidateInterval;
}
public TimeInterval getInvalidateInterval()
{
return invalidateInterval;
}
public boolean isNeedResourcesRefresh() {
return needResourcesRefresh;
}
public void setNeedResourcesRefresh(boolean needResourcesRefresh) {
this.needResourcesRefresh = needResourcesRefresh;
}
public Collection<Entity> getAllObjects() {
HashSet<Entity> objects = new HashSet<Entity>();
for ( Collection<Entity> list:getListMap().values())
{
for ( Entity entity:list)
{
objects.add(entity);
}
}
return objects;
}
public boolean isEmpty() {
boolean isEmpty = removeSet.isEmpty() && storeSet.isEmpty() && invalidateInterval == null;
return isEmpty;
}
public Date getLastValidated()
{
if ( lastValidated == null)
{
return null;
}
try {
return SerializableDateTimeFormat.INSTANCE.parseTimestamp(lastValidated);
} catch (ParseDateException e) {
throw new IllegalStateException(e.getMessage());
}
}
public int getTimezoneOffset()
{
return timezoneOffset;
}
public void setTimezoneOffset(int timezoneOffset)
{
this.timezoneOffset = timezoneOffset;
}
}
| Java |
package org.rapla.storage;
import java.util.LinkedHashSet;
import java.util.Set;
import org.rapla.entities.configuration.internal.RaplaMapImpl;
public class PreferencePatch extends RaplaMapImpl {
String userId;
Set<String> removedEntries = new LinkedHashSet<String>();
public void addRemove(String role) {
removedEntries.add( role);
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
public Set<String> getRemovedEntries()
{
return removedEntries;
}
@Override
public String toString() {
return "Patch for " + userId + " " + super.toString() + " Removed " + removedEntries.toString();
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbfile;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.concurrent.locks.Lock;
import org.rapla.ConnectInfo;
import org.rapla.components.util.IOUtil;
import org.rapla.components.util.xml.RaplaContentHandler;
import org.rapla.components.util.xml.RaplaErrorHandler;
import org.rapla.components.util.xml.RaplaSAXHandler;
import org.rapla.components.util.xml.XMLReaderAdapter;
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.facade.RaplaComponent;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.TypedComponentRole;
import org.rapla.framework.internal.ContextTools;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.LocalCache;
import org.rapla.storage.UpdateEvent;
import org.rapla.storage.UpdateResult;
import org.rapla.storage.impl.AbstractCachableOperator;
import org.rapla.storage.impl.EntityStore;
import org.rapla.storage.impl.server.LocalAbstractCachableOperator;
import org.rapla.storage.xml.IOContext;
import org.rapla.storage.xml.RaplaMainReader;
import org.rapla.storage.xml.RaplaMainWriter;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/** Use this Operator to keep the data stored in an XML-File.
* <p>Sample configuration:
<pre>
<file-storage id="file">
<file>data.xml</file>
<encoding>utf-8</encoding>
<validate>no</validate>
</facade>
</pre>
* <ul>
* <li>The file entry contains the path of the data file.
* If the path is not an absolute path it will be resolved
* relative to the location of the configuration file
* </li>
* <li>The encoding entry specifies the encoding of the xml-file.
* Currently only UTF-8 is tested.
* </li>
* <li>The validate entry specifies if the xml-file should be checked
* against a schema-file that is located under org/rapla/storage/xml/rapla.rng
* (Default is no)
* </li>
* </ul>
* </p>
* <p>Note: The xmloperator doesn't check passwords.</p>
@see AbstractCachableOperator
@see org.rapla.storage.StorageOperator
*/
final public class FileOperator extends LocalAbstractCachableOperator
{
private File storageFile;
private URL loadingURL;
private final String encoding;
protected boolean isConnected = false;
final boolean includeIds ;
public FileOperator( RaplaContext context,Logger logger, Configuration config ) throws RaplaException
{
super( context, logger );
StartupEnvironment env = context.lookup( StartupEnvironment.class );
URL contextRootURL = env.getContextRootURL();
String datasourceName = config.getChild("datasource").getValue(null);
if ( datasourceName != null)
{
String filePath;
try {
filePath = ContextTools.resolveContext(datasourceName, context );
} catch (RaplaContextException ex) {
filePath = "${context-root}/data.xml";
String message = "JNDI config raplafile is not found using '" + filePath + "' :"+ ex.getMessage() ;
getLogger().warn(message);
}
String resolvedPath = ContextTools.resolveContext(filePath, context);
try
{
storageFile = new File( resolvedPath);
loadingURL = storageFile.getCanonicalFile().toURI().toURL();
} catch (Exception e) {
throw new RaplaException("Error parsing file '" + resolvedPath + "' " + e.getMessage());
}
}
else
{
String fileName = config.getChild( "file" ).getValue( "data.xml" );
try
{
File file = new File( fileName );
if ( file.isAbsolute() )
{
storageFile = file;
loadingURL = storageFile.getCanonicalFile().toURI().toURL();
}
else
{
int startupEnv = env.getStartupMode();
if ( startupEnv == StartupEnvironment.WEBSTART || startupEnv == StartupEnvironment.APPLET )
{
loadingURL = new URL( contextRootURL, fileName );
}
else
{
File contextRootFile = IOUtil.getFileFrom( contextRootURL );
storageFile = new File( contextRootFile, fileName );
loadingURL = storageFile.getCanonicalFile().toURI().toURL();
}
}
getLogger().info("Data:" + loadingURL);
}
catch ( MalformedURLException ex )
{
throw new RaplaException( fileName + " is not an valid path " );
}
catch ( IOException ex )
{
throw new RaplaException( "Can't read " + storageFile + " " + ex.getMessage() );
}
}
encoding = config.getChild( "encoding" ).getValue( "utf-8" );
boolean validate = config.getChild( "validate" ).getValueAsBoolean( false );
if ( validate )
{
getLogger().error("Validation currently not supported");
}
includeIds = config.getChild( "includeIds" ).getValueAsBoolean( false );
}
public String getURL()
{
return loadingURL.toExternalForm();
}
public boolean supportsActiveMonitoring()
{
return false;
}
/** Sets the isConnected-flag and calls loadData.*/
final public User connect(ConnectInfo connectInfo) throws RaplaException
{
if ( isConnected )
return null;
getLogger().info("Connecting: " + getURL());
loadData();
initIndizes();
isConnected = true;
getLogger().debug("Connected");
return null;
}
final public boolean isConnected()
{
return isConnected;
}
final public void disconnect() throws RaplaException
{
boolean wasConnected = isConnected();
if ( wasConnected)
{
getLogger().info("Disconnecting: " + getURL());
cache.clearAll();
isConnected = false;
fireStorageDisconnected("");
getLogger().debug("Disconnected");
}
}
final public void refresh() throws RaplaException
{
getLogger().warn( "Incremental refreshs are not supported" );
}
final protected void loadData() throws RaplaException
{
try
{
cache.clearAll();
addInternalTypes(cache);
if ( getLogger().isDebugEnabled() )
getLogger().debug( "Reading data from file:" + loadingURL );
EntityStore entityStore = new EntityStore( cache, cache.getSuperCategory() );
RaplaContext inputContext = new IOContext().createInputContext( context, entityStore, this );
RaplaMainReader contentHandler = new RaplaMainReader( inputContext );
parseData( contentHandler );
Collection<Entity> list = entityStore.getList();
cache.putAll( list );
Preferences preferences = cache.getPreferencesForUserId( null);
if ( preferences != null)
{
TypedComponentRole<RaplaConfiguration> oldEntry = new TypedComponentRole<RaplaConfiguration>("org.rapla.plugin.export2ical");
if (preferences.getEntry(oldEntry, null) != null)
{
preferences.putEntry( oldEntry, null);
}
RaplaConfiguration entry = preferences.getEntry(RaplaComponent.PLUGIN_CONFIG, null);
if ( entry != null)
{
DefaultConfiguration pluginConfig = (DefaultConfiguration)entry.find("class", "org.rapla.export2ical.Export2iCalPlugin");
entry.removeChild( pluginConfig);
}
}
resolveInitial( list, this);
cache.getSuperCategory().setReadOnly();
for (User user:cache.getUsers())
{
String id = user.getId();
String password = entityStore.getPassword( id );
//System.out.println("Storing password in cache" + password);
cache.putPassword( id, password );
}
// contextualize all Entities
if ( getLogger().isDebugEnabled() )
getLogger().debug( "Entities contextualized" );
}
catch ( FileNotFoundException ex )
{
createDefaultSystem(cache);
}
catch ( IOException ex )
{
getLogger().warn( "Loading error: " + loadingURL);
throw new RaplaException( "Can't load file at " + loadingURL + ": " + ex.getMessage() );
}
catch ( RaplaException ex )
{
throw ex;
}
catch ( Exception ex )
{
throw new RaplaException( ex );
}
}
private void parseData( RaplaSAXHandler reader) throws RaplaException,IOException {
ContentHandler contentHandler = new RaplaContentHandler( reader);
try {
InputSource source = new InputSource( loadingURL.toString() );
XMLReader parser = XMLReaderAdapter.createXMLReader(false);
RaplaErrorHandler errorHandler = new RaplaErrorHandler(getLogger().getChildLogger( "reading" ));
parser.setContentHandler(contentHandler);
parser.setErrorHandler(errorHandler);
parser.parse(source);
} catch (SAXException ex) {
Throwable cause = ex.getCause();
while (cause != null && cause.getCause() != null) {
cause = cause.getCause();
}
if (ex instanceof SAXParseException) {
throw new RaplaException("Line: " + ((SAXParseException)ex).getLineNumber()
+ " Column: "+ ((SAXParseException)ex).getColumnNumber() + " "
+ ((cause != null) ? cause.getMessage() : ex.getMessage())
,(cause != null) ? cause : ex );
}
if (cause == null) {
throw new RaplaException( ex);
}
if (cause instanceof RaplaException)
throw (RaplaException) cause;
else
throw new RaplaException( cause);
}
/* End of Exception Handling */
}
public void dispatch( final UpdateEvent evt ) throws RaplaException
{
final UpdateResult result;
final Lock writeLock = writeLock();
try
{
preprocessEventStorage(evt);
// call of update must be first to update the cache.
// then saveData() saves all the data in the cache
result = update( evt);
saveData(cache, includeIds);
}
finally
{
unlock( writeLock );
}
fireStorageUpdated( result );
}
synchronized final public void saveData(LocalCache cache) throws RaplaException
{
saveData( cache, true);
}
synchronized final private void saveData(LocalCache cache, boolean includeIds) throws RaplaException
{
try
{
if ( storageFile == null )
{
return;
}
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
writeData( buffer,cache, includeIds );
byte[] data = buffer.toByteArray();
buffer.close();
File parentFile = storageFile.getParentFile();
if (!parentFile.exists())
{
getLogger().info("Creating directory " + parentFile.toString());
parentFile.mkdirs();
}
//String test = new String( data);
moveFile( storageFile, storageFile.getPath() + ".bak" );
OutputStream out = new FileOutputStream( storageFile );
out.write( data );
out.close();
}
catch ( IOException e )
{
throw new RaplaException( e.getMessage() );
}
}
private void writeData( OutputStream out, LocalCache cache, boolean includeIds ) throws IOException, RaplaException
{
RaplaContext outputContext = new IOContext().createOutputContext( context, cache.getSuperCategoryProvider(), includeIds );
RaplaMainWriter writer = new RaplaMainWriter( outputContext, cache );
writer.setEncoding( encoding );
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out,encoding));
writer.setWriter(w);
writer.printContent();
w.flush();
}
private void moveFile( File file, String newPath )
{
File backupFile = new File( newPath );
backupFile.delete();
file.renameTo( backupFile );
}
public String toString()
{
return "FileOpertator for " + getURL();
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbfile;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import org.rapla.components.util.xml.RaplaContentHandler;
import org.rapla.components.util.xml.RaplaErrorHandler;
import org.rapla.components.util.xml.RaplaSAXHandler;
import org.rapla.components.util.xml.XMLReaderAdapter;
import org.rapla.framework.RaplaException;
import org.rapla.framework.logger.Logger;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/** Reads the data in xml format from an InputSource into the
LocalCache and converts it to a newer version if necessary.
*/
public final class RaplaInput {
private Logger logger;
private URL fileSource;
private Reader reader;
private boolean wasConverted;
public RaplaInput(Logger logger) {
this.logger = logger;
}
protected Logger getLogger() {
return logger;
}
/** returns if the data was converted during read.*/
public boolean wasConverted() {
return wasConverted;
}
public void read(URL file, RaplaSAXHandler handler, boolean validate) throws RaplaException,IOException {
getLogger().debug("Parsing " + file.toString());
fileSource = file;
reader = null;
parseData( handler , validate);
}
private InputSource getNewSource() {
if ( fileSource != null ) {
return new InputSource( fileSource.toString() );
} else if ( reader != null ) {
return new InputSource( reader );
} else {
throw new IllegalStateException("fileSource or reader can't be null");
}
}
private void parseData( RaplaSAXHandler reader,boolean validate)
throws RaplaException
,IOException {
ContentHandler contentHandler = new RaplaContentHandler( reader);
try {
InputSource source = getNewSource();
if (validate) {
validate( source, "org/rapla/storage/xml/rapla.rng");
}
XMLReader parser = XMLReaderAdapter.createXMLReader(false);
RaplaErrorHandler errorHandler = new RaplaErrorHandler(logger);
parser.setContentHandler(contentHandler);
parser.setErrorHandler(errorHandler);
parser.parse(source);
} catch (SAXException ex) {
Throwable cause = ex.getCause();
while (cause != null && cause.getCause() != null) {
cause = cause.getCause();
}
if (ex instanceof SAXParseException) {
throw new RaplaException("Line: " + ((SAXParseException)ex).getLineNumber()
+ " Column: "+ ((SAXParseException)ex).getColumnNumber() + " "
+ ((cause != null) ? cause.getMessage() : ex.getMessage())
,(cause != null) ? cause : ex );
}
if (cause == null) {
throw new RaplaException( ex);
}
if (cause instanceof RaplaException)
throw (RaplaException) cause;
else
throw new RaplaException( cause);
}
/* End of Exception Handling */
}
/** uses the jing validator to validate a document against an relaxng schema.
* This method uses reflection API, to avoid compile-time dependencies on
* the jing.jar
* @param in
* @param schema
* @throws RaplaException
*/
private void validate(InputSource in, String schema) throws RaplaException {
try {
ErrorHandler errorHandler = new RaplaErrorHandler(getLogger());
/* // short version
* propMapBuilder = new com.thaiopensource.util.PropertyMapBuilder();
* propMapBuilder.put(com.thaiopensource.validate.ValidateProperty.ERROR_HANDLER, errorHandler);
* Object propMap = propMapBuilder.toPropertyMap();
* Object o =new com.thaiopensource.validate.ValidationDriver(propMap);
* o.loadSchema(schema);
* o.validate(in);
*/
// full reflection syntax
Class<?> validatorC = Class.forName("com.thaiopensource.validate.ValidationDriver");
Class<?> propIdC = Class.forName("com.thaiopensource.util.PropertyId");
Class<?> validatepropC = Class.forName("com.thaiopensource.validate.ValidateProperty");
Object errorHandlerId = validatepropC.getDeclaredField("ERROR_HANDLER").get( null );
Class<?> propMapC = Class.forName("com.thaiopensource.util.PropertyMap");
Class<?> propMapBuilderC = Class.forName("com.thaiopensource.util.PropertyMapBuilder");
Object propMapBuilder = propMapBuilderC.newInstance();
Method put = propMapBuilderC.getMethod("put", new Class[] {propIdC, Object.class} );
put.invoke( propMapBuilder, new Object[] {errorHandlerId, errorHandler});
Method topropMap = propMapBuilderC.getMethod("toPropertyMap", new Class[] {} );
Object propMap = topropMap.invoke( propMapBuilder, new Object[] {});
Constructor<?> validatorConst = validatorC.getConstructor( new Class[] { propMapC });
Object validator = validatorConst.newInstance( new Object[] {propMap});
Method loadSchema = validatorC.getMethod( "loadSchema", new Class[] {InputSource.class});
Method validate = validatorC.getMethod("validate", new Class[] {InputSource.class});
InputSource schemaSource = new InputSource( getResource( schema ).toString() );
loadSchema.invoke( validator, new Object[] {schemaSource} );
validate.invoke( validator, new Object[] {in});
} catch (ClassNotFoundException ex) {
throw new RaplaException( ex.getMessage() + ". Latest jing.jar is missing on the classpath. Please download from http://www.thaiopensource.com/relaxng/jing.html");
} catch (InvocationTargetException e) {
throw new RaplaException("Can't validate data due to the following error: " + e.getTargetException().getMessage(), e.getTargetException());
} catch (Exception ex) {
throw new RaplaException("Error invoking JING", ex);
}
}
private URL getResource(String name) throws RaplaException {
URL url = getClass().getClassLoader().getResource( name );
if ( url == null )
throw new RaplaException("Resource " + name + " not found");
return url;
}
}
| Java |
package org.rapla.storage;
import org.rapla.framework.RaplaException;
public class RaplaNewVersionException extends RaplaException {
private static final long serialVersionUID = 1L;
public RaplaNewVersionException(String text) {
super(text);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.rapla.components.util.Assert;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.internal.PreferencesImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.internal.DynamicTypeImpl;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.entities.internal.UserImpl;
import org.rapla.entities.storage.EntityResolver;
import org.rapla.entities.storage.ParentEntity;
import org.rapla.entities.storage.internal.SimpleEntity;
import org.rapla.framework.Provider;
public class LocalCache implements EntityResolver
{
Map<String,String> passwords = new HashMap<String,String>();
Map<String,Entity> entities;
Map<String,DynamicTypeImpl> dynamicTypes;
Map<String,UserImpl> users;
Map<String,AllocatableImpl> resources;
Map<String,ReservationImpl> reservations;
private String clientUserId;
public LocalCache() {
entities = new HashMap<String,Entity>();
// top-level-entities
reservations = new LinkedHashMap<String,ReservationImpl>();
users = new LinkedHashMap<String,UserImpl>();
resources = new LinkedHashMap<String,AllocatableImpl>();
dynamicTypes = new LinkedHashMap<String,DynamicTypeImpl>();
initSuperCategory();
}
public String getClientUserId() {
return clientUserId;
}
/** use this to prohibit reservations and preferences (except from system and current user) to be stored in the cache*/
public void setClientUserId(String clientUserId) {
this.clientUserId = clientUserId;
}
/** @return true if the entity has been removed and false if the entity was not found*/
public boolean remove(Entity entity) {
RaplaType raplaType = entity.getRaplaType();
boolean bResult = true;
String entityId = entity.getId();
bResult = entities.remove(entityId) != null;
Map<String,? extends Entity> entitySet = getMap(raplaType);
if (entitySet != null) {
if (entityId == null)
return false;
entitySet.remove( entityId );
}
if ( entity instanceof ParentEntity)
{
Collection<Entity> subEntities = ((ParentEntity) entity).getSubEntities();
for (Entity child:subEntities)
{
remove( child);
}
}
return bResult;
}
@SuppressWarnings("unchecked")
private Map<String,Entity> getMap(RaplaType type)
{
if ( type == Reservation.TYPE)
{
return (Map)reservations;
}
if ( type == Allocatable.TYPE)
{
return (Map)resources;
}
if ( type == DynamicType.TYPE)
{
return (Map)dynamicTypes;
}
if ( type == User.TYPE)
{
return (Map)users;
}
return null;
}
public void put(Entity entity) {
Assert.notNull(entity);
RaplaType raplaType = entity.getRaplaType();
String id = entity.getId();
if (id == null)
throw new IllegalStateException("ID can't be null");
String clientUserId = getClientUserId();
if ( clientUserId != null )
{
if (raplaType == Reservation.TYPE || raplaType == Appointment.TYPE )
{
throw new IllegalArgumentException("Can't store reservations or appointments in client cache");
}
if (raplaType == Preferences.TYPE )
{
String owner = ((PreferencesImpl)entity).getId("owner");
if ( owner != null && !owner.equals( clientUserId))
{
throw new IllegalArgumentException("Can't store non system preferences for other users in client cache");
}
}
}
// first remove the old children from the map
Entity oldEntity = entities.get( entity);
if (oldEntity != null && oldEntity instanceof ParentEntity)
{
Collection<Entity> subEntities = ((ParentEntity) oldEntity).getSubEntities();
for (Entity child:subEntities)
{
remove( child);
}
}
entities.put(id,entity);
Map<String,Entity> entitySet = getMap(raplaType);
if (entitySet != null) {
entitySet.put( entity.getId() ,entity);
}
else
{
//throw new RuntimeException("UNKNOWN TYPE. Can't store object in cache: " + entity.getRaplaType());
}
// then put the new children
if ( entity instanceof ParentEntity)
{
Collection<Entity> subEntities = ((ParentEntity) entity).getSubEntities();
for (Entity child:subEntities)
{
put( child);
}
}
}
public Entity get(Comparable id) {
if (id == null)
throw new RuntimeException("id is null");
return entities.get(id);
}
// @SuppressWarnings("unchecked")
// private <T extends Entity> Collection<T> getCollection(RaplaType type) {
// Map<String,? extends Entity> entities = entityMap.get(type);
//
// if (entities != null) {
// return (Collection<T>) entities.values();
// } else {
// throw new RuntimeException("UNKNOWN TYPE. Can't get collection: "
// + type);
// }
// }
//
// @SuppressWarnings("unchecked")
// private <T extends RaplaObject> Collection<T> getCollection(Class<T> clazz) {
// RaplaType type = RaplaType.get(clazz);
// Collection<T> collection = (Collection<T>) getCollection(type);
// return new LinkedHashSet(collection);
// }
public void clearAll() {
passwords.clear();
reservations.clear();
users.clear();
resources.clear();
dynamicTypes.clear();
entities.clear();
initSuperCategory();
}
private void initSuperCategory() {
CategoryImpl superCategory = new CategoryImpl(null, null);
superCategory.setId(Category.SUPER_CATEGORY_ID);
superCategory.setKey("supercategory");
superCategory.getName().setName("en", "Root");
entities.put (Category.SUPER_CATEGORY_ID, superCategory);
Category[] childs = superCategory.getCategories();
for (int i=0;i<childs.length;i++) {
superCategory.removeCategory( childs[i] );
}
}
public CategoryImpl getSuperCategory()
{
return (CategoryImpl) get(Category.SUPER_CATEGORY_ID);
}
public UserImpl getUser(String username) {
for (UserImpl user:users.values())
{
if (user.getUsername().equals(username))
return user;
}
for (UserImpl user:users.values())
{
if (user.getUsername().equalsIgnoreCase(username))
return user;
}
return null;
}
public PreferencesImpl getPreferencesForUserId(String userId) {
String preferenceId = PreferencesImpl.getPreferenceIdFromUser(userId);
PreferencesImpl pref = (PreferencesImpl) tryResolve( preferenceId, Preferences.class);
return pref;
}
public DynamicType getDynamicType(String elementKey) {
for (DynamicType dt:dynamicTypes.values()) {
if (dt.getKey().equals(elementKey))
return dt;
}
return null;
}
public List<Entity> getVisibleEntities(final User user) {
List<Entity> result = new ArrayList<Entity>();
result.add( getSuperCategory());
result.addAll(getDynamicTypes());
result.addAll(getUsers());
for (Allocatable alloc: getAllocatables())
{
if (user.isAdmin() || alloc.canReadOnlyInformation( user))
{
result.add( alloc);
}
}
// add system preferences
{
PreferencesImpl preferences = getPreferencesForUserId( null );
if ( preferences != null)
{
result.add( preferences);
}
}
// add user preferences
{
String userId = user.getId();
Assert.notNull( userId);
PreferencesImpl preferences = getPreferencesForUserId( userId );
if ( preferences != null)
{
result.add( preferences);
}
}
return result;
}
// Implementation of EntityResolver
@Override
public Entity resolve(String id) throws EntityNotFoundException {
return resolve(id, null);
}
public <T extends Entity> T resolve(String id,Class<T> entityClass) throws EntityNotFoundException {
T entity = tryResolve(id, entityClass);
SimpleEntity.checkResolveResult(id, entityClass, entity);
return entity;
}
@Override
public Entity tryResolve(String id) {
return tryResolve(id, null);
}
@Override
public <T extends Entity> T tryResolve(String id,Class<T> entityClass) {
if (id == null)
throw new RuntimeException("id is null");
Entity entity = entities.get(id);
@SuppressWarnings("unchecked")
T casted = (T) entity;
return casted;
}
public String getPassword(String userId) {
return passwords.get(userId);
}
public void putPassword(String userId, String password) {
passwords.put(userId,password);
}
public void putAll( Collection<? extends Entity> list )
{
for ( Entity entity: list)
{
put( entity);
}
}
public Provider<Category> getSuperCategoryProvider() {
return new Provider<Category>() {
public Category get() {
return getSuperCategory();
}
};
}
@SuppressWarnings("unchecked")
public Collection<User> getUsers() {
return (Collection)users.values();
}
@SuppressWarnings("unchecked")
public Collection<Allocatable> getAllocatables() {
return (Collection)resources.values();
}
@SuppressWarnings("unchecked")
public Collection<Reservation> getReservations() {
return (Collection)reservations.values();
}
@SuppressWarnings("unchecked")
public Collection<DynamicType> getDynamicTypes() {
return (Collection)dynamicTypes.values();
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
/** A StorageOperator that operates on a LocalCache-Object.
*/
package org.rapla.storage;
import java.util.Collection;
import java.util.Date;
import java.util.TimeZone;
import org.rapla.entities.Entity;
import org.rapla.entities.User;
import org.rapla.framework.RaplaException;
public interface CachableStorageOperator extends StorageOperator {
void runWithReadLock(CachableStorageOperatorCommand cmd) throws RaplaException;
void dispatch(UpdateEvent evt) throws RaplaException;
String authenticate(String username,String password) throws RaplaException;
void saveData(LocalCache cache) throws RaplaException;
public Collection<Entity> getVisibleEntities(final User user) throws RaplaException;
public Collection<Entity> getUpdatedEntities(Date timestamp) throws RaplaException;
TimeZone getTimeZone();
//DynamicType getUnresolvedAllocatableType();
//DynamicType getAnonymousReservationType();
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.Classifiable;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.internal.ClassificationImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
class DynAttReader extends RaplaXMLReader {
Classifiable classifiable;
ClassificationImpl classification;
Attribute attribute;
public DynAttReader(RaplaContext context) throws RaplaException {
super(context);
}
public void setClassifiable(Classifiable classifiable) {
this.classifiable = classifiable;
}
@Override
public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts)
throws RaplaSAXParseException
{
if (level == entryLevel) {
DynamicType dynamicType;
String id = atts.getValue("idref");
if ( id!= null) {
dynamicType = resolve(DynamicType.TYPE,id);
} else {
String typeName = Namespaces.EXTENSION_NS.equals(namespaceURI) ? "rapla:" + localName : localName;
if ( typeName.equals("rapla:crypto"))
{
return;
}
dynamicType = getDynamicType(typeName);
if (dynamicType == null)
throw createSAXParseException( "Dynanic type with name '" + typeName + "' not found." );
}
Classification newClassification = dynamicType.newClassification(false);
classification = (ClassificationImpl)newClassification;
classifiable.setClassification(classification);
classification.setResolver( store);
}
if (level > entryLevel) {
String id = atts.getValue("idref");
if ( id != null) {
attribute = resolve(Attribute.TYPE,id);
} else {
attribute = classification.getAttribute(localName);
}
if (attribute == null) //ignore attributes not found in the classification
return;
startContent();
}
}
@Override
public void processEnd(String namespaceURI,String localName)
throws RaplaSAXParseException
{
if (level > entryLevel) {
String content = readContent();
if (content != null) {
Object value = parseAttributeValue(attribute, content);
classification.addValue( attribute, value);
}
}
}
} | Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.util.Date;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.storage.StorageOperator;
public class PeriodReader extends DynAttReader {
public PeriodReader(RaplaContext context) throws RaplaException {
super(context);
}
static int idCount = 0 ;
@Override
public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts)
throws RaplaSAXParseException
{
if (namespaceURI.equals(RAPLA_NS) && localName.equals("period")) {
AllocatableImpl period = new AllocatableImpl(new Date(), new Date());
Classification classification = store.getDynamicType(StorageOperator.PERIOD_TYPE).newClassification();
classification.setValue("name", getString(atts,"name"));
classification.setValue("start",parseDate(getString(atts,"start"),false));
classification.setValue("end",parseDate(getString(atts,"end"),true));
period.setClassification( classification);
Permission newPermission = period.newPermission();
newPermission.setAccessLevel( Permission.READ);
period.addPermission( newPermission);
String id = atts.getValue("id");
if ( id != null)
{
period.setId(id);
}
else
{
period.setId("period_"+idCount);
idCount++;
}
add(period);
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.components.util.xml.XMLWriter;
import org.rapla.entities.Annotatable;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.MultiLanguageName;
import org.rapla.entities.Ownable;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.Timestamp;
import org.rapla.entities.User;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.ConstraintIds;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.framework.Provider;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.logger.Logger;
/** Stores the data from the local cache in XML-format to a print-writer.*/
abstract public class RaplaXMLWriter extends XMLWriter
implements Namespaces
{
//protected NamespaceSupport namespaceSupport = new NamespaceSupport();
private boolean isPrintId;
private Map<String,RaplaType> localnameMap;
Logger logger;
Map<RaplaType,RaplaXMLWriter> writerMap;
protected RaplaContext context;
protected SerializableDateTimeFormat dateTimeFormat = SerializableDateTimeFormat.INSTANCE;
Provider<Category> superCategory;
public RaplaXMLWriter( RaplaContext context) throws RaplaException {
this.context = context;
enableLogging( context.lookup( Logger.class));
this.writerMap =context.lookup( PreferenceWriter.WRITERMAP );
this.localnameMap = context.lookup(PreferenceReader.LOCALNAMEMAPENTRY);
this.isPrintId = context.has(IOContext.PRINTID);
this.superCategory = context.lookup( IOContext.SUPERCATEGORY);
// namespaceSupport.pushContext();
// for (int i=0;i<NAMESPACE_ARRAY.length;i++) {
// String prefix = NAMESPACE_ARRAY[i][1];
// String uri = NAMESPACE_ARRAY[i][0];
// if ( prefix != null) {
// namespaceSupport.declarePrefix(prefix, uri);
// }
// }
}
public Category getSuperCategory()
{
return superCategory.get();
}
public void enableLogging(Logger logger) {
this.logger = logger;
}
protected Logger getLogger() {
return logger;
}
protected void printTimestamp(Timestamp stamp) throws IOException {
final Date createTime = stamp.getCreateTime();
final Date lastChangeTime = stamp.getLastChanged();
if ( createTime != null)
{
att("created-at", SerializableDateTimeFormat.INSTANCE.formatTimestamp( createTime));
}
if ( lastChangeTime != null)
{
att("last-changed", SerializableDateTimeFormat.INSTANCE.formatTimestamp( lastChangeTime));
}
User user = stamp.getLastChangedBy();
if ( user != null)
{
att("last-changed-by", getId(user));
}
}
protected void printTranslation(MultiLanguageName name) throws IOException {
Iterator<String> it= name.getAvailableLanguages().iterator();
while (it.hasNext()) {
String lang = it.next();
String value = name.getName(lang);
openTag("doc:name");
att("lang",lang);
closeTagOnLine();
printEncode(value);
closeElementOnLine("doc:name");
println();
}
}
protected void printAnnotations(Annotatable annotatable, boolean includeTags) throws IOException{
String[] keys = annotatable.getAnnotationKeys();
if ( keys.length == 0 )
return;
if ( includeTags)
{
openElement("doc:annotations");
}
for (String key:keys) {
String value = annotatable.getAnnotation(key);
openTag("rapla:annotation");
att("key", key);
closeTagOnLine();
printEncode(value);
closeElementOnLine("rapla:annotation");
println();
}
if ( includeTags)
{
closeElement("doc:annotations");
}
}
protected void printAnnotations(Annotatable annotatable) throws IOException{
printAnnotations(annotatable, true);
}
protected void printAttributeValue(Attribute attribute, Object value) throws IOException,RaplaException {
if ( value == null)
{
return;
}
AttributeType type = attribute.getType();
if (type.equals(AttributeType.ALLOCATABLE))
{
print(getId((Entity)value));
}
else if (type.equals(AttributeType.CATEGORY))
{
CategoryImpl rootCategory = (CategoryImpl) attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY);
if ( !(value instanceof Category))
{
throw new RaplaException("Wrong attribute value Category expected but was " + value.getClass());
}
Category categoryValue = (Category)value;
if (rootCategory == null)
{
getLogger().error("root category missing for attriubte " + attribute);
}
else
{
String keyPathString = getKeyPath(rootCategory, categoryValue);
print( keyPathString);
}
}
else if (type.equals(AttributeType.DATE) )
{
final Date date;
if ( value instanceof Date)
date = (Date)value;
else
date = null;
printEncode( dateTimeFormat.formatDate( date ) );
}
else
{
printEncode( value.toString() );
}
}
private String getKeyPath(CategoryImpl rootCategory, Category categoryValue) throws EntityNotFoundException {
List<String> pathForCategory = rootCategory.getPathForCategory(categoryValue, true );
String keyPathString = CategoryImpl.getKeyPathString(pathForCategory);
return keyPathString;
}
protected void printOwner(Ownable obj) throws IOException {
User user = obj.getOwner();
if (user == null)
return;
att("owner", getId(user));
}
protected void printReference(Entity entity) throws IOException, EntityNotFoundException {
String localName = entity.getRaplaType().getLocalName();
openTag("rapla:" + localName);
if ( entity.getRaplaType() == DynamicType.TYPE ) {
att("keyref", ((DynamicType)entity).getKey());
}
else if ( entity.getRaplaType() == Category.TYPE && !isPrintId())
{
String path = getKeyPath( (CategoryImpl)getSuperCategory(), (Category) entity);
att("keyref", path);
}
else
{
att("idref",getId( entity));
}
closeElementTag();
}
protected String getId(Entity entity) {
Comparable id2 = entity.getId();
return id2.toString();
}
protected RaplaXMLWriter getWriterFor(RaplaType raplaType) throws RaplaException {
RaplaXMLWriter writer = writerMap.get(raplaType);
if ( writer == null) {
throw new RaplaException("No writer for type " + raplaType);
}
writer.setIndentLevel( getIndentLevel());
writer.setWriter( getWriter());
return writer;
}
protected void printId(Entity entity) throws IOException {
att("id", getId( entity ));
}
protected void printIdRef(Entity entity) throws IOException {
att("idref", getId( entity ) );
}
/** Returns if the ids should be saved, even when keys are
* available. */
public boolean isPrintId() {
return isPrintId;
}
/**
* @throws IOException
*/
public void writeObject(@SuppressWarnings("unused") RaplaObject object) throws IOException, RaplaException {
throw new RaplaException("Method not implemented by subclass " + this.getClass().getName());
}
public String getLocalNameForType(RaplaType raplaType) throws RaplaException{
for (Iterator<Map.Entry<String,RaplaType>> it = localnameMap.entrySet().iterator();it.hasNext();) {
Map.Entry<String,RaplaType> entry =it.next();
if (entry.getValue().equals( raplaType)) {
return entry.getKey();
}
}
throw new RaplaException("No writer declared for Type " + raplaType );
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.entities.configuration.internal.RaplaMapImpl;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class RaplaMapReader extends RaplaXMLReader {
String key;
RaplaMapImpl entityMap;
RaplaXMLReader childReader;
public RaplaMapReader(RaplaContext sm) throws RaplaException {
super(sm);
}
@Override
public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts)
throws RaplaSAXParseException
{
if ( !RAPLA_NS.equals(namespaceURI))
return;
if (localName.equals(RaplaMap.TYPE.getLocalName())) {
entityMap = new RaplaMapImpl();
return;
}
if (localName.equals("mapentry")) {
key= getString(atts, "key");
String value = getString( atts, "value", null);
if ( value != null)
{
try
{
entityMap.putPrivate( key, value );
}
catch (ClassCastException ex)
{
getLogger().error("Mixed maps are currently not supported.", ex);
}
}
return;
}
String refid = getString( atts, "idref", null);
String keyref = getString( atts, "keyref", null);
RaplaType raplaType = getTypeForLocalName( localName );
if ( refid != null) {
childReader = null;
// We ignore the old references from 1.7
if ( entityMap.isTypeSupportedAsLink(raplaType)) {
return;
}
String id = getId( raplaType, refid);
entityMap.putIdPrivate( key, id, raplaType);
} else if ( keyref != null) {
childReader = null;
DynamicType type = getDynamicType( keyref );
if ( type != null) {
String id = ((Entity) type).getId();
entityMap.putIdPrivate( key, id, DynamicType.TYPE);
}
} else {
childReader = getChildHandlerForType( raplaType );
delegateElement( childReader, namespaceURI, localName, atts);
}
}
@Override
public void processEnd(String namespaceURI,String localName)
throws RaplaSAXParseException
{
if ( !RAPLA_NS.equals(namespaceURI) )
return;
if ( childReader != null ) {
RaplaObject type = childReader.getType();
try
{
entityMap.putPrivate( key, type);
}
catch (ClassCastException ex)
{
getLogger().error("Mixed maps are currently not supported.", ex);
}
}
childReader = null;
}
public RaplaMap getEntityMap() {
return entityMap;
}
public RaplaObject getType() {
//reservation.getReferenceHandler().put()
return getEntityMap();
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.configuration.CalendarModelConfiguration;
import org.rapla.entities.configuration.internal.CalendarModelConfigurationImpl;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class RaplaCalendarSettingsReader extends RaplaXMLReader {
CalendarModelConfiguration settings;
String title;
String view;
Date selectedDate;
Date startDate;
Date endDate;
boolean resourceRootSelected;
ClassificationFilter[] filter;
RaplaMapReader optionMapReader;
ClassificationFilterReader classificationFilterHandler;
List<String> idList;
List<RaplaType> idTypeList;
Map<String,String> optionMap;
public RaplaCalendarSettingsReader(RaplaContext context) throws RaplaException {
super( context );
optionMapReader= new RaplaMapReader(context);
classificationFilterHandler = new ClassificationFilterReader(context);
addChildHandler( optionMapReader );
addChildHandler( classificationFilterHandler );
}
@Override
public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts)
throws RaplaSAXParseException
{
if (localName.equals("calendar")) {
filter = null;
classificationFilterHandler.clear();
title = getString( atts,"title");
view = getString( atts,"view");
selectedDate = getDate( atts, "date");
startDate = getDate( atts, "startdate");
endDate = getDate( atts, "enddate");
resourceRootSelected = getString(atts, "rootSelected", "false").equalsIgnoreCase("true");
idList = Collections.emptyList();
idTypeList = Collections.emptyList();
optionMap = Collections.emptyMap();
}
if (localName.equals("selected")) {
idList = new ArrayList<String>();
idTypeList = new ArrayList<RaplaType>();
}
if (localName.equals("options")) {
delegateElement( optionMapReader, namespaceURI, localName, atts);
}
if (localName.equals("filter"))
{
classificationFilterHandler.clear();
delegateElement( classificationFilterHandler, namespaceURI, localName, atts);
}
String refid = getString( atts, "idref", null);
String keyref = getString( atts, "keyref", null);
if ( refid != null)
{
RaplaType raplaType = getTypeForLocalName( localName );
String id = getId( raplaType, refid);
idList.add( id);
idTypeList.add( raplaType);
}
else if ( keyref != null)
{
DynamicType type = getDynamicType( keyref );
idList.add( type.getId());
idTypeList.add( DynamicType.TYPE);
}
}
private Date getDate(RaplaSAXAttributes atts, String key ) throws RaplaSAXParseException {
String dateString = getString( atts,key, null);
if ( dateString != null) {
return parseDate( dateString, false );
} else {
return null;
}
}
@Override
public void processEnd(String namespaceURI,String localName)
{
if (localName.equals("calendar")) {
boolean defaultResourceTypes = classificationFilterHandler.isDefaultResourceTypes();
boolean defaultEventTypes = classificationFilterHandler.isDefaultEventTypes();
settings = new CalendarModelConfigurationImpl( idList,idTypeList, resourceRootSelected,filter, defaultResourceTypes, defaultEventTypes,title,startDate, endDate, selectedDate, view, optionMap);
}
if (localName.equals("selected")) {
}
if (localName.equals("options")) {
@SuppressWarnings("unchecked")
Map<String,String> entityMap = optionMapReader.getEntityMap();
optionMap = entityMap;
}
if (localName.equals("filter")) {
filter = classificationFilterHandler.getFilters();
}
}
public RaplaObject getType() {
//reservation.getReferenceHandler().put()
return settings;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.entities.Category;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.facade.Conflict;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class RaplaMainReader extends RaplaXMLReader
{
private Map<String,RaplaXMLReader> localnameTable = new HashMap<String,RaplaXMLReader>();
public final static String INPUT_FILE_VERSION = RaplaMainWriter.OUTPUT_FILE_VERSION;
private TimeInterval invalidateInterval = null;
private boolean resourcesRefresh = false;
public RaplaMainReader( RaplaContext context ) throws RaplaException
{
super( context );
// Setup the delegation classes
localnameTable.put( "grammar", readerMap.get( DynamicType.TYPE ) );
localnameTable.put( "element", readerMap.get( DynamicType.TYPE ) );
localnameTable.put( "user", readerMap.get( User.TYPE ) );
localnameTable.put( "category", readerMap.get( Category.TYPE ) );
localnameTable.put( "preferences", readerMap.get( Preferences.TYPE ) );
localnameTable.put( "resource", readerMap.get( Allocatable.TYPE ) );
localnameTable.put( "person", readerMap.get( Allocatable.TYPE ) );
localnameTable.put( "extension", readerMap.get( Allocatable.TYPE ) );
localnameTable.put( "period", readerMap.get( Period.TYPE ) );
localnameTable.put( "reservation", readerMap.get( Reservation.TYPE ) );
localnameTable.put( "conflict", readerMap.get( Conflict.TYPE ) );
localnameTable.put( "remove", readerMap.get( "remove") );
localnameTable.put( "store", readerMap.get( "store") );
localnameTable.put( "reference", readerMap.get( "reference") );
addChildHandler( readerMap.values() );
}
private void addChildHandler( Collection<? extends DelegationHandler> collection )
{
Iterator<? extends DelegationHandler> it = collection.iterator();
while (it.hasNext())
addChildHandler( it.next() );
}
/** checks the version of the input-file. throws
WrongVersionException if the file-version is not supported by
the reader.
*/
private void processHead(
String uri,
String name,
RaplaSAXAttributes atts ) throws RaplaSAXParseException
{
try
{
String version = null;
getLogger().debug( "Getting version." );
if (name.equals( "data" ) && uri.equals( RAPLA_NS ))
{
version = atts.getValue( "version" );
if (version == null)
throw createSAXParseException( "Could not get Version" );
}
String start = atts.getValue( "startDate");
String end = atts.getValue( "endDate");
if ( start != null || end != null)
{
Date startDate = start!= null ? parseDate(start, false) : null;
Date endDate = end!= null ? parseDate(end, true) : null;
if ( startDate != null && startDate.getTime() < DateTools.MILLISECONDS_PER_DAY)
{
startDate = null;
}
invalidateInterval = new TimeInterval(startDate, endDate);
}
String resourcesRefresh = atts.getValue( "resourcesRefresh");
if ( resourcesRefresh != null)
{
this.resourcesRefresh = Boolean.parseBoolean( resourcesRefresh);
}
if (name.equals( "DATA" ))
{
version = atts.getValue( "version" );
if (version == null)
{
version = "0.1";
}
}
if (version == null)
throw createSAXParseException( "Invalid Format. Could not read data." );
if (!version.equals( INPUT_FILE_VERSION ))
{
double versionNr;
try {
versionNr = new Double(version).doubleValue();
} catch (NumberFormatException ex) {
throw new RaplaException("Invalid version tag (double-value expected)!");
}
// get the version number of the data-schema
if (versionNr > new Double(RaplaMainReader.INPUT_FILE_VERSION).doubleValue())
throw new RaplaException("This version of Rapla cannot read files with a version-number"
+ " greater than " + RaplaMainReader.INPUT_FILE_VERSION
+ ", try out the latest version.");
getLogger().warn( "Older version detected. " );
}
getLogger().debug( "Found compatible version-number." );
// We've got the right version. We can proceed.
}
catch (Exception ex)
{
throw createSAXParseException(ex.getMessage(),ex);
}
}
@Override
public void processElement(
String namespaceURI,
String localName,
RaplaSAXAttributes atts ) throws RaplaSAXParseException
{
if (level == 1)
{
processHead( namespaceURI, localName, atts );
return;
}
if ( !namespaceURI.equals(RAPLA_NS) && !namespaceURI.equals(RELAXNG_NS))
{
// Ignore unknown namespace
return;
}
// lookup delegation-handler for the localName
DelegationHandler handler = localnameTable.get( localName );
// Ignore unknown elements
if (handler != null)
{
delegateElement( handler, namespaceURI, localName, atts );
}
}
public TimeInterval getInvalidateInterval()
{
return invalidateInterval;
}
public boolean isResourcesRefresh() {
return resourcesRefresh;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.io.IOException;
import java.util.Map;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.internal.PreferencesImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
public class PreferenceWriter extends RaplaXMLWriter {
public static final TypedComponentRole<Map<RaplaType,RaplaXMLWriter>> WRITERMAP = new TypedComponentRole<Map<RaplaType,RaplaXMLWriter>>( "org.rapla.storage.xml.writerMap");
public PreferenceWriter(RaplaContext sm) throws RaplaException {
super(sm);
}
protected void printPreferences(Preferences preferences) throws IOException,RaplaException {
if ( preferences != null && !preferences.isEmpty()) {
openTag("rapla:preferences");
//printTimestamp( preferences);
closeTag();
PreferencesImpl impl = (PreferencesImpl)preferences;
for (String role:impl.getPreferenceEntries())
{
Object entry = impl.getEntry(role);
if ( entry instanceof String) {
openTag("rapla:entry");
att("key", role );
att("value", (String)entry);
closeElementTag();
} if ( entry instanceof RaplaObject) {
openTag("rapla:entry");
att("key", role );
closeTag();
RaplaObject raplaObject = (RaplaObject)entry;
RaplaType raplaType = raplaObject.getRaplaType();
RaplaXMLWriter writer = getWriterFor( raplaType);
writer.writeObject( raplaObject );
closeElement("rapla:entry");
}
}
closeElement("rapla:preferences");
}
}
public void writeObject(RaplaObject object) throws IOException, RaplaException {
printPreferences( (Preferences) object);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.io.IOException;
import org.rapla.entities.Category;
import org.rapla.entities.RaplaObject;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class CategoryWriter extends RaplaXMLWriter {
public CategoryWriter(RaplaContext sm) throws RaplaException {
super(sm);
}
public void printRaplaType(RaplaObject type) throws RaplaException, IOException {
printCategory( (Category) type);
}
public void printCategory(Category category) throws IOException,RaplaException {
printCategory( category, true);
}
public void printCategory(Category category,boolean printSubcategories) throws IOException,RaplaException {
openTag("rapla:category");
printTimestamp( category);
if (isPrintId())
{
printId(category);
Category parent = category.getParent();
if ( parent != null)
{
att("parentid", getId( parent));
}
}
att("key",category.getKey());
closeTag();
printTranslation(category.getName());
printAnnotations( category, false);
if ( printSubcategories )
{
Category[] categories = category.getCategories();
for (int i=0;i<categories.length;i++)
printCategory(categories[i]);
}
closeElement("rapla:category");
}
public void writeObject(RaplaObject persistant) throws RaplaException, IOException {
printCategory( (Category) persistant, false);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.io.IOException;
import java.util.Collection;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.internal.DynamicTypeImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
class ClassifiableWriter extends RaplaXMLWriter {
public ClassifiableWriter(RaplaContext sm) throws RaplaException {
super(sm);
}
protected void printClassification(Classification classification) throws IOException,RaplaException {
if (classification == null)
return;
DynamicType dynamicType = classification.getType();
boolean internal = ((DynamicTypeImpl)dynamicType).isInternal();
String namespacePrefix = internal ? "ext:" : "dynatt:";
String elementKey = dynamicType.getKey();
if ( internal )
{
if (!elementKey.startsWith("rapla:"))
{
throw new RaplaException("keys for internal type must start with rapla:");
}
elementKey = elementKey.substring("rapla:".length() );
}
else
{
if (elementKey.startsWith("rapla:"))
{
throw new RaplaException("keys for non internal type can't start with rapla:");
}
}
String elementName = namespacePrefix + elementKey;
Attribute[] attributes = classification.getAttributes();
if ( attributes.length == 0)
{
openTag(elementName);
}
else
{
openElement(elementName);
}
for (int i=0;i<attributes.length;i++) {
Attribute attribute = attributes[i];
Collection<?> values = classification.getValues(attribute);
for ( Object value:values)
{
String attributeName = namespacePrefix + attribute.getKey();
openElementOnLine(attributeName);
printAttributeValue(attribute, value);
closeElementOnLine(attributeName);
println();
}
}
if ( attributes.length == 0)
{
closeElementTag();
}
else
{
closeElement(elementName);
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.entities.configuration.internal.RaplaMapImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class RaplaMapWriter extends RaplaXMLWriter {
public RaplaMapWriter(RaplaContext sm) throws RaplaException {
super(sm);
}
public void writeObject(RaplaObject type) throws IOException, RaplaException {
writeMap_((RaplaMapImpl) type );
}
private void writeMap_(RaplaMapImpl map ) throws IOException, RaplaException {
openElement("rapla:" + RaplaMap.TYPE.getLocalName());
for (Iterator<String> it = map.keySet().iterator();it.hasNext();) {
Object key = it.next();
Object obj = map.get( key);
printEntityReference( key, obj);
}
closeElement("rapla:" + RaplaMap.TYPE.getLocalName());
}
public void writeMap(Map<String,String> map ) throws IOException {
openElement("rapla:" + RaplaMap.TYPE.getLocalName());
for (Map.Entry<String,String> entry:map.entrySet()) {
String key = entry.getKey();
String obj = entry.getValue();
openTag("rapla:mapentry");
att("key", key.toString());
if ( obj instanceof String)
{
String value = (String) obj;
att("value", value);
closeElementTag();
}
}
closeElement("rapla:" + RaplaMap.TYPE.getLocalName());
}
private void printEntityReference(Object key,Object obj) throws RaplaException, IOException {
if (obj == null)
{
getLogger().warn( "Map contains empty value under key " + key );
return;
}
int start = getIndentLevel();
openTag("rapla:mapentry");
att("key", key.toString());
if ( obj instanceof String)
{
String value = (String) obj;
att("value", value);
closeElementTag();
return;
}
closeTag();
if ( obj instanceof Entity ) {
printReference( (Entity) obj);
} else {
RaplaObject raplaObj = (RaplaObject) obj;
getWriterFor( raplaObj.getRaplaType()).writeObject( raplaObj );
}
setIndentLevel( start+1 );
closeElement("rapla:mapentry");
setIndentLevel( start );
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.util.Map;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXParseException;
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.internal.PreferencesImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
public class PreferenceReader extends RaplaXMLReader {
public static final TypedComponentRole<Map<String,RaplaType>> LOCALNAMEMAPENTRY = new TypedComponentRole<Map<String,RaplaType>>("org.rapla.storage.xml.localnameMap");
public static final TypedComponentRole<Map<RaplaType,RaplaXMLReader>> READERMAP = new TypedComponentRole<Map<RaplaType,RaplaXMLReader>>("org.rapla.storage.xml.readerMap");
PreferencesImpl preferences;
String configRole;
User owner;
RaplaXMLReader childReader;
String stringValue = null;
public PreferenceReader(RaplaContext sm) throws RaplaException {
super(sm);
}
public void setUser( User owner) {
this.owner = owner;
}
@Override
public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts)
throws RaplaSAXParseException
{
if ( RAPLA_NS.equals(namespaceURI) && localName.equals("data")) {
return;
}
if (localName.equals("preferences")) {
TimestampDates ts = readTimestamps(atts);
preferences = new PreferencesImpl(ts.createTime, ts.changeTime);
preferences.setResolver( store);
if ( owner == null )
{
preferences.setId( Preferences.SYSTEM_PREFERENCES_ID);
}
else
{
preferences.setOwner( owner );
preferences.setId( Preferences.ID_PREFIX + owner.getId());
}
return;
}
if (localName.equals("entry")) {
configRole = getString(atts,"key");
stringValue = getString(atts,"value", null);
// ignore old entry
if ( stringValue != null) {
preferences.putEntryPrivate( configRole,stringValue );
}
return;
}
RaplaType raplaTypeName = getTypeForLocalName(localName );
childReader = getChildHandlerForType( raplaTypeName );
delegateElement(childReader,namespaceURI,localName,atts);
}
public Preferences getPreferences() {
return preferences;
}
public RaplaObject getChildType() throws RaplaSAXParseException {
return childReader.getType();
}
@Override
public void processEnd(String namespaceURI,String localName)
throws RaplaSAXParseException
{
if (!namespaceURI.equals(RAPLA_NS))
return;
if (localName.equals("preferences")) {
add(preferences);
}
if (localName.equals("entry") && stringValue == null) {
RaplaObject type = childReader.getType();
preferences.putEntryPrivate(configRole, type);
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
public interface Namespaces {
String RAPLA_NS = "http://rapla.sourceforge.net/rapla";
String RELAXNG_NS = "http://relaxng.org/ns/structure/1.0";
String DYNATT_NS = "http://rapla.sourceforge.net/dynamictype";
String EXTENSION_NS = "http://rapla.sourceforge.net/extension";
String ANNOTATION_NS = "http://rapla.sourceforge.net/annotation";
String[][] NAMESPACE_ARRAY = {
{RAPLA_NS,"rapla"}
,{RELAXNG_NS,"relax"}
,{DYNATT_NS,"dynatt"}
,{EXTENSION_NS,"ext"}
,{ANNOTATION_NS,"doc"}
};
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
public class WrongXMLVersionException extends Exception {
private static final long serialVersionUID = 1L;
String version;
public WrongXMLVersionException(String version) {
super("Wrong Version Exception " + version);
this.version = version;
}
public String getVersion() {
return version;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.util.ArrayList;
import java.util.Collection;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.entities.dynamictype.Attribute;
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;
class ClassificationFilterReader extends RaplaXMLReader {
DynamicType dynamicType;
ClassificationFilter filter;
Attribute attribute;
String operator;
Collection<ClassificationFilter> filterList = new ArrayList<ClassificationFilter>();
Collection<Object[]> conditions = new ArrayList<Object[]>();
int ruleCount;
private boolean defaultResourceTypes = true;
private boolean defaultEventTypes = true;
public ClassificationFilterReader(RaplaContext sm) throws RaplaException {
super(sm);
}
public void clear() {
filterList.clear();
defaultResourceTypes = true;
defaultEventTypes = true;
}
public ClassificationFilter[] getFilters() {
return
filterList.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY);
}
@Override
public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts)
throws RaplaSAXParseException
{
if (localName.equals("classificationfilter"))
{
String id = atts.getValue("dynamictypeidref");
if ( id != null) {
dynamicType = resolve(DynamicType.TYPE,id);
} else {
String typeName = getString(atts,"dynamictype");
dynamicType = getDynamicType( typeName );
if (dynamicType == null) {
getLogger().error("Error reading filter with " + DynamicType.TYPE.getLocalName() + " " + typeName,null);
return;
}
}
final String annotation = dynamicType.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
boolean eventType = annotation != null && annotation.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
if (eventType )
{
defaultEventTypes = false;
}
else
{
defaultResourceTypes = false;
}
filter = dynamicType.newClassificationFilter();
ruleCount = 0;
filterList.add(filter);
}
if (localName.equals("rule"))
{
String id = atts.getValue("attributeidref");
if ( id != null) {
attribute = resolve(Attribute.TYPE, id);
} else {
String attributeName = getString(atts,"attribute");
attribute = dynamicType.getAttribute(attributeName);
if (attribute == null) {
getLogger().error("Error reading filter with " + dynamicType +" Attribute: " + attributeName,null);
return;
}
}
conditions.clear();
}
if (localName.equals("orCond"))
{
operator = getString(atts,"operator");
startContent();
}
}
@Override
public void processEnd(String namespaceURI,String localName)
throws RaplaSAXParseException
{
if (localName.equals("rule") && filter != null)
{
final Object[][] array = conditions.toArray(new Object[][] {} );
filter.setRule(ruleCount ++
,attribute
,array
);
}
if (localName.equals("orCond") && attribute!= null)
{
Object value = parseAttributeValue(attribute, readContent().trim());
conditions.add(new Object[] {operator,value});
}
}
public boolean isDefaultResourceTypes()
{
return defaultResourceTypes;
}
public boolean isDefaultEventTypes()
{
return defaultEventTypes;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.io.IOException;
import org.rapla.entities.Category;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class UserWriter extends RaplaXMLWriter {
public UserWriter(RaplaContext sm) throws RaplaException {
super(sm);
}
public void printUser(User user, String password, Preferences preferences) throws IOException,RaplaException {
openTag("rapla:user");
printId(user);
printTimestamp( user);
att("username",user.getUsername());
if ( password != null )
{
att("password",password);
}
att("name",user.getName());
att("email",user.getEmail());
// Allocatable person = user.getPerson();
// if ( person != null)
// {
// att("person", person.getId());
// }
att("isAdmin",String.valueOf(user.isAdmin()));
closeTag();
Category[] groups = user.getGroups();
for ( int i = 0; i < groups.length; i++ ) {
Category group = groups[i];
String groupPath = getGroupPath( group );
try
{
openTag("rapla:group");
att( "key", groupPath );
closeElementTag();
}
catch (Exception ex)
{
getLogger().error(ex.getMessage(), ex);
}
}
if ( preferences != null) {
PreferenceWriter preferenceWriter = (PreferenceWriter) getWriterFor(Preferences.TYPE);
preferenceWriter.setIndentLevel( getIndentLevel() );
preferenceWriter.printPreferences(preferences);
}
closeElement("rapla:user");
}
public void writeObject(RaplaObject object) throws IOException, RaplaException {
printUser( (User) object,null,null);
}
private String getGroupPath( Category category) throws EntityNotFoundException {
Category rootCategory = getSuperCategory().getCategory(Permission.GROUP_CATEGORY_KEY);
return ((CategoryImpl) rootCategory ).getPathForCategory(category);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.io.IOException;
import org.rapla.entities.Category;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class AllocatableWriter extends ClassifiableWriter {
public AllocatableWriter(RaplaContext sm) throws RaplaException {
super(sm);
}
public void printAllocatable(Allocatable allocatable) throws IOException,RaplaException {
String tagName;
DynamicType type = allocatable.getClassification().getType();
String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
if ( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON.equals(annotation))
{
tagName = "rapla:person";
}
else if( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE.equals(annotation))
{
tagName = "rapla:resource";
}
else if( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE.equals(annotation))
{
tagName = "rapla:extension";
}
else
{
throw new RaplaException("No or unknown classification type '" + annotation + "' set for " + allocatable.toString() + " ignoring ");
}
openTag(tagName);
printId(allocatable);
printOwner(allocatable);
printTimestamp(allocatable );
closeTag();
printAnnotations( allocatable);
printClassification(allocatable.getClassification());
Permission[] permissions = allocatable.getPermissions();
for ( int i = 0; i < permissions.length; i++ ){
printPermission(permissions[i]);
}
closeElement(tagName);
}
public void writeObject(RaplaObject object) throws IOException, RaplaException {
printAllocatable( (Allocatable) object);
}
protected void printPermission(Permission p) throws IOException,RaplaException {
openTag("rapla:permission");
if ( p.getUser() != null ) {
att("user", getId( p.getUser() ));
} else if ( p.getGroup() != null ) {
att( "group", getGroupPath( p.getGroup() ) );
}
if ( p.getMinAdvance() != null ) {
att ( "min-advance", p.getMinAdvance().toString() );
}
if ( p.getMaxAdvance() != null ) {
att ( "max-advance", p.getMaxAdvance().toString() );
}
if ( p.getStart() != null ) {
att ( "start-date", dateTimeFormat.formatDate( p.getStart() ) );
}
if ( p.getEnd() != null ) {
att ( "end-date", dateTimeFormat.formatDate( p.getEnd() ) );
}
if ( p.getAccessLevel() != Permission.ALLOCATE_CONFLICTS ) {
att("access", Permission.ACCESS_LEVEL_NAMEMAP.get( p.getAccessLevel() ) );
}
closeElementTag();
}
private String getGroupPath( Category category) throws EntityNotFoundException {
Category rootCategory = getSuperCategory().getCategory(Permission.GROUP_CATEGORY_KEY);
return ((CategoryImpl) rootCategory ).getPathForCategory(category);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.io.IOException;
import java.util.LinkedHashMap;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.framework.Configuration;
import org.rapla.framework.ConfigurationException;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class RaplaConfigurationWriter extends RaplaXMLWriter {
public RaplaConfigurationWriter(RaplaContext sm) throws RaplaException {
super(sm);
}
public void writeObject(RaplaObject type) throws IOException, RaplaException {
RaplaConfiguration raplaConfig = (RaplaConfiguration) type ;
openElement("rapla:" + RaplaConfiguration.TYPE.getLocalName());
try {
printConfiguration(raplaConfig );
} catch (ConfigurationException ex) {
throw new RaplaException( ex );
}
closeElement("rapla:" + RaplaConfiguration.TYPE.getLocalName());
}
/**
* Serialize each Configuration element. This method is called recursively.
* Original code for this method is taken from the org.apache.framework.configuration.DefaultConfigurationSerializer class
* @throws ConfigurationException if an error occurs
* @throws IOException if an error occurs
*/
private void printConfiguration(final Configuration element ) throws ConfigurationException, RaplaException, IOException {
LinkedHashMap<String, String> attr = new LinkedHashMap<String, String>();
String[] attrNames = element.getAttributeNames();
if( null != attrNames )
{
for( int i = 0; i < attrNames.length; i++ )
{
String key = attrNames[ i ];
String value = element.getAttribute( attrNames[ i ], "" );
attr.put( key, value);
}
}
String qName = element.getName();
openTag(qName);
att(attr);
Configuration[] children = element.getChildren();
if (children.length > 0)
{
closeTag();
for( int i = 0; i < children.length; i++ )
{
printConfiguration( children[ i ] );
}
closeElement(qName);
}
else
{
String value = element.getValue( null );
if (null == value)
{
closeElementTag();
}
else
{
closeTagOnLine();
print(value);
closeElementOnLine(qName);
println();
}
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 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.storage.xml;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.entities.Category;
import org.rapla.entities.internal.UserImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class UserReader extends RaplaXMLReader
{
UserImpl user;
PreferenceReader preferenceHandler;
public UserReader( RaplaContext context ) throws RaplaException
{
super( context );
preferenceHandler = new PreferenceReader( context );
addChildHandler( preferenceHandler );
}
@Override
public void processElement(
String namespaceURI,
String localName,
RaplaSAXAttributes atts ) throws RaplaSAXParseException
{
if (!namespaceURI.equals( RAPLA_NS ))
return;
if (localName.equals( "user" ))
{
TimestampDates ts = readTimestamps( atts);
user = new UserImpl(ts.createTime, ts.changeTime);
String id = setId( user, atts );
// String idString = getString(atts, "person",null);
// if ( idString != null)
// {
// String personId = getId(Allocatable.TYPE,idString);
// user.putId("person",personId);
// }
user.setUsername( getString( atts, "username", "" ) );
user.setName( getString( atts, "name", "" ) );
user.setEmail( getString( atts, "email", "" ) );
user.setAdmin( getString( atts, "isAdmin", "false" ).equals( "true" ) );
String password = getString( atts, "password", null );
preferenceHandler.setUser( user );
if ( password != null)
{
putPassword( id, password );
}
}
if (localName.equals( "group" ))
{
String groupId = atts.getValue( "idref" );
if (groupId !=null)
{
String newGroupId = getId(Category.TYPE, groupId);
user.addId("groups",newGroupId);
}
else
{
String groupKey = getString( atts, "key" );
Category group = getGroup( groupKey);
if (group != null)
{
user.addGroup( group );
}
}
}
if (localName.equals( "preferences" ))
{
delegateElement(
preferenceHandler,
namespaceURI,
localName,
atts );
}
}
@Override
public void processEnd( String namespaceURI, String localName ) throws RaplaSAXParseException
{
if (!namespaceURI.equals( RAPLA_NS ))
return;
if (localName.equals( "user" ))
{
preferenceHandler.setUser( null );
add( user );
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.util.Stack;
import org.rapla.components.util.Assert;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.entities.Annotatable;
import org.rapla.entities.Category;
import org.rapla.entities.IllegalAnnotationException;
import org.rapla.entities.MultiLanguageName;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class CategoryReader extends RaplaXMLReader
{
MultiLanguageName currentName = null;
Annotatable currentAnnotatable = null;
String currentLang = null;
Stack<CategoryImpl> categoryStack = new Stack<CategoryImpl>();
CategoryImpl superCategory;
String annotationKey = null;
CategoryImpl lastProcessedCategory = null;
boolean readOnlyThisCategory;
public CategoryReader( RaplaContext context ) throws RaplaException
{
super( context );
superCategory = getSuperCategory();
currentName = superCategory.getName();
}
public void setReadOnlyThisCategory( boolean enable )
{
readOnlyThisCategory = enable;
}
@Override
public void processElement(
String namespaceURI,
String localName,
RaplaSAXAttributes atts ) throws RaplaSAXParseException
{
if (localName.equals( "category" ) && namespaceURI.equals( RAPLA_NS ))
{
String key = atts.getValue( "key" );
Assert.notNull( key );
TimestampDates ts = readTimestamps( atts);
CategoryImpl category = new CategoryImpl(ts.createTime, ts.changeTime );
category.setKey( key );
currentName = category.getName();
currentAnnotatable = category;
if (atts.getValue( "id" )!=null)
{
setId( category, atts );
}
else
{
setNewId( category );
}
if (!readOnlyThisCategory)
{
if ( !categoryStack.empty() )
{
Category parent = categoryStack.peek();
parent.addCategory( category);
}
else
{
String parentId = atts.getValue( "parentid");
if ( parentId!= null)
{
if (parentId.equals(Category.SUPER_CATEGORY_ID)) {
if ( !superCategory.isReadOnly())
{
superCategory.addCategory( category);
}
category.putEntity("parent", superCategory);
} else {
String parentIdN = getId( Category.TYPE, parentId);
category.putId("parent", parentIdN);
}
}
else
{
if (atts.getValue( "id" )==null)
{
superCategory.addCategory( category);
}
else
{
// It is the super categorycategory.getReferenceHandler().put("parent", superCategory);
}
}
}
}
categoryStack.push( category );
/*
Category test = category;
String output = "";
while (test != null)
{
output = "/" + test.getKey() + output;
test = test.getParent();
}
// System.out.println("Storing category " + output );
*/
}
if (localName.equals( "name" ) && namespaceURI.equals( ANNOTATION_NS ))
{
startContent();
currentLang = atts.getValue( "lang" );
Assert.notNull( currentLang );
}
if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS ))
{
annotationKey = atts.getValue( "key" );
Assert.notNull( annotationKey, "key attribute cannot be null" );
startContent();
}
}
@Override
public void processEnd( String namespaceURI, String localName )
throws RaplaSAXParseException
{
if (localName.equals( "category" ))
{
// Test Namespace uris here for possible xerces bug
if (namespaceURI.equals( "" ))
{
throw createSAXParseException( " category namespace empty. Possible Xerces Bug. Download a newer version of xerces." );
}
CategoryImpl category = categoryStack.pop();
setCurrentTranslations( category.getName());
if (!readOnlyThisCategory)
{
add( category );
}
lastProcessedCategory = category;
}
else if (localName.equals( "name" ) && namespaceURI.equals( ANNOTATION_NS ))
{
String translation = readContent();
currentName.setName( currentLang, translation );
}
else if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS ))
{
try
{
String annotationValue = readContent().trim();
currentAnnotatable.setAnnotation( annotationKey, annotationValue );
}
catch (IllegalAnnotationException ex)
{
}
}
}
public CategoryImpl getCurrentCategory()
{
return lastProcessedCategory;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.rapla.components.util.Assert;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.entities.Annotatable;
import org.rapla.entities.Category;
import org.rapla.entities.IllegalAnnotationException;
import org.rapla.entities.MultiLanguageName;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.entities.dynamictype.internal.DynamicTypeImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class DynamicTypeReader extends RaplaXMLReader
{
DynamicTypeImpl dynamicType;
MultiLanguageName currentName = null;
String currentLang = null;
String constraintKey = null;
AttributeImpl attribute = null;
String annotationKey = null;
boolean isAttributeActive = false;
boolean isDynamictypeActive = false;
HashMap<String,String> typeAnnotations = new LinkedHashMap<String,String>();
HashMap<String,String> attributeAnnotations = new LinkedHashMap<String,String>();
private HashMap<String, Map<Attribute,String>> unresolvedDynamicTypeConstraints = new HashMap<String, Map<Attribute,String>>();
public DynamicTypeReader( RaplaContext context ) throws RaplaException
{
super( context );
unresolvedDynamicTypeConstraints.clear();
}
@Override
public void processElement(
String namespaceURI,
String localName,
RaplaSAXAttributes atts ) throws RaplaSAXParseException
{
if (localName.equals( "element" ))
{
String qname = getString( atts, "name" );
String name = qname.substring( qname.indexOf( ":" ) + 1 );
Assert.notNull( name );
//System.out.println("NAME: " + qname + " Level " + level + " Entry " + entryLevel);
if (!isDynamictypeActive)
{
isDynamictypeActive = true;
typeAnnotations.clear();
TimestampDates ts = readTimestamps( atts);
dynamicType = new DynamicTypeImpl(ts.createTime, ts.changeTime);
if (atts.getValue( "id" )!=null)
{
setId( dynamicType, atts );
}
else
{
setNewId( dynamicType );
}
currentName = dynamicType.getName();
dynamicType.setKey( name );
// because the dynamic types refered in the constraints could be loaded after their first reference we resolve all prior unresolved constraint bindings to that type when the type is loaded
Map<Attribute,String> constraintMap = unresolvedDynamicTypeConstraints.get( name );
if ( constraintMap != null)
{
for (Map.Entry<Attribute,String> entry: constraintMap.entrySet())
{
Attribute att = entry.getKey();
String constraintKey = entry.getValue();
// now set the unresolved constraint, we need to ignore readonly check, because the type may be already closed
((AttributeImpl)att).setContraintWithoutWritableCheck(constraintKey, dynamicType);
}
}
unresolvedDynamicTypeConstraints.remove( name);
}
else
{
isAttributeActive = true;
attribute = new AttributeImpl();
currentName = attribute.getName();
attribute.setKey( name );
Assert.notNull( name, "key attribute cannot be null" );
if (atts.getValue("id") != null)
{
setId( attribute, atts );
}
else
{
setNewId( attribute );
}
attributeAnnotations.clear();
}
}
if (localName.equals( "constraint" ) && namespaceURI.equals( RAPLA_NS ))
{
constraintKey = atts.getValue( "name" );
startContent();
}
if (localName.equals( "default" ))
{
startContent();
}
// if no attribute type is set
if (localName.equals( "data" ) && namespaceURI.equals( RELAXNG_NS ) && attribute.getType().equals(
AttributeImpl.DEFAULT_TYPE ))
{
String typeName = atts.getValue( "type" );
if (typeName == null)
throw createSAXParseException( "element relax:data is requiered!" );
AttributeType type = AttributeType.findForString( typeName );
if (type == null)
{
getLogger().error( "AttributeType '" + typeName + "' not found. Using string.");
type = AttributeType.STRING;
}
attribute.setType( type );
}
if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS ))
{
annotationKey = atts.getValue( "key" );
Assert.notNull( annotationKey, "key attribute cannot be null" );
startContent();
}
if (localName.equals( "name" ) && namespaceURI.equals( ANNOTATION_NS ))
{
startContent();
currentLang = atts.getValue( "lang" );
Assert.notNull( currentLang );
}
}
private void addAnnotations( Annotatable annotatable, Map<String,String> annotations )
{
for (Iterator<Map.Entry<String,String>> it = annotations.entrySet().iterator(); it.hasNext();)
{
Map.Entry<String,String> entry = it.next();
String key = entry.getKey();
String annotation = entry.getValue();
try
{
annotatable.setAnnotation( key, annotation );
}
catch (IllegalAnnotationException e)
{
getLogger().error("Can't parse annotation " + e.getMessage(), e);
//throw createSAXParseException( e.getMessage() );
}
}
}
@Override
public void processEnd( String namespaceURI, String localName )
throws RaplaSAXParseException
{
if (localName.equals( "element" ))
{
if (!isAttributeActive)
{
addAnnotations( dynamicType, typeAnnotations );
setCurrentTranslations(dynamicType.getName());
dynamicType.setResolver( store);
add( dynamicType );
// We ensure the dynamic type is not modified anymore
dynamicType.setReadOnly( );
isDynamictypeActive = false;
}
else
{
addAnnotations( attribute, attributeAnnotations );
//System.out.println("Adding attribute " + attribute + " to " + dynamicType);
setCurrentTranslations(attribute.getName());
dynamicType.addAttribute( attribute );
add( attribute );
isAttributeActive = false;
}
}
else if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS ))
{
String annotationValue = readContent().trim();
if (isAttributeActive)
{
attributeAnnotations.put( annotationKey, annotationValue );
}
else
{
typeAnnotations.put( annotationKey, annotationValue );
}
}
else if (localName.equals( "optional" ) && namespaceURI.equals( RELAXNG_NS ))
{
attribute.setOptional( true );
}
else if (localName.equals( "name" ) && namespaceURI.equals( ANNOTATION_NS ))
{
Assert.notNull( currentName );
currentName.setName( currentLang, readContent() );
}
else if (localName.equals( "constraint" ) && namespaceURI.equals( RAPLA_NS ))
{
String content = readContent().trim();
Object constraint = null;
if (attribute.getConstraintClass( constraintKey ) == Category.class)
{
@SuppressWarnings("deprecation")
boolean idContent = org.rapla.storage.OldIdMapping.isTextId(Category.TYPE, content );
if (idContent)
{
String id = getId( Category.TYPE, content );
constraint = store.tryResolve( id, Category.class );
if ( constraint == null)
{
getLogger().error("Can't resolve root category for " + dynamicType.getKey() + "." + attribute.getKey() + " id is " + id + " (" + content + ")");
}
}
else
{
constraint = getCategoryFromPath( content );
}
}
else if (attribute.getConstraintClass( constraintKey ) == DynamicType.class)
{
@SuppressWarnings("deprecation")
boolean idContent = org.rapla.storage.OldIdMapping.isTextId( DynamicType.TYPE, content );
if (idContent)
{
constraint = content.trim();
}
else
{
String elementKey = content;
// check if the dynamic type refers to itself
if (elementKey.equals( dynamicType.getKey()))
{
constraint = dynamicType;
}
else
{
// this only works if the dynamic type is already loaded
constraint = getDynamicType(elementKey);
// so we cache the contraint attributes in a map to be filled when the types are loaded
if (constraint == null)
{
Map<Attribute,String> collection = unresolvedDynamicTypeConstraints.get( elementKey);
if ( collection == null)
{
collection = new HashMap<Attribute,String>();
unresolvedDynamicTypeConstraints.put( elementKey, collection);
}
collection.put( attribute, constraintKey);
}
}
}
}
else if (attribute.getConstraintClass( constraintKey ) == Integer.class)
{
constraint = parseLong( content );
}
else if (attribute.getConstraintClass( constraintKey ) == Boolean.class)
{
constraint = parseBoolean( content );
}
else
{
constraint = content;
}
attribute.setConstraint( constraintKey, constraint );
}
if (localName.equals( "default" ) && namespaceURI.equals( RAPLA_NS ))
{
String content = readContent().trim();
final Object defaultValue;
final AttributeType type = attribute.getType();
if (type == AttributeType.CATEGORY)
{
@SuppressWarnings("deprecation")
boolean idContent = org.rapla.storage.OldIdMapping.isTextId(Category.TYPE, content );
if (idContent)
{
defaultValue = resolve( Category.TYPE, content );
}
else
{
defaultValue = getCategoryFromPath( content );
}
}
else
{
Object value;
try
{
value = parseAttributeValue(attribute, content);
}
catch (RaplaException e)
{
value = null;
}
defaultValue = value;
}
attribute.setDefaultValue(defaultValue );
}
}
}
| Java |
package org.rapla.storage.xml;
import java.util.HashMap;
import java.util.Map;
import org.rapla.entities.Category;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.configuration.CalendarModelConfiguration;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.facade.Conflict;
import org.rapla.framework.Provider;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaDefaultContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.storage.IdCreator;
import org.rapla.storage.impl.EntityStore;
public class IOContext
{
protected Map<String,RaplaType> getLocalnameMap() {
//WARNING We can't use RaplaType.getRegisteredTypes() because the class could not be registered on load time
Map<String,RaplaType> localnameMap = new HashMap<String,RaplaType>();
localnameMap.put( Reservation.TYPE.getLocalName(), Reservation.TYPE);
localnameMap.put( Appointment.TYPE.getLocalName(), Appointment.TYPE);
localnameMap.put( Allocatable.TYPE.getLocalName(), Allocatable.TYPE);
localnameMap.put( User.TYPE.getLocalName(), User.TYPE);
localnameMap.put( Preferences.TYPE.getLocalName(), Preferences.TYPE);
localnameMap.put( Period.TYPE.getLocalName(), Period.TYPE);
localnameMap.put( Category.TYPE.getLocalName(), Category.TYPE);
localnameMap.put( DynamicType.TYPE.getLocalName(), DynamicType.TYPE);
localnameMap.put( Attribute.TYPE.getLocalName(), Attribute.TYPE);
localnameMap.put( RaplaConfiguration.TYPE.getLocalName(), RaplaConfiguration.TYPE);
localnameMap.put( RaplaMap.TYPE.getLocalName(), RaplaMap.TYPE);
localnameMap.put( CalendarModelConfiguration.TYPE.getLocalName(), CalendarModelConfiguration.TYPE);
localnameMap.put( Conflict.TYPE.getLocalName(), Conflict.TYPE);
return localnameMap;
}
protected void addReaders(Map<RaplaType,RaplaXMLReader> readerMap,RaplaContext context) throws RaplaException {
readerMap.put( Category.TYPE,new CategoryReader( context));
readerMap.put( Preferences.TYPE, new PreferenceReader(context) );
readerMap.put( DynamicType.TYPE, new DynamicTypeReader(context) );
readerMap.put( User.TYPE, new UserReader(context));
readerMap.put( Allocatable.TYPE, new AllocatableReader(context) );
readerMap.put( Period.TYPE, new PeriodReader(context) );
readerMap.put( Reservation.TYPE,new ReservationReader(context));
readerMap.put( RaplaConfiguration.TYPE, new RaplaConfigurationReader(context));
readerMap.put( RaplaMap.TYPE, new RaplaMapReader(context));
readerMap.put( CalendarModelConfiguration.TYPE, new RaplaCalendarSettingsReader(context) );
}
protected void addWriters(Map<RaplaType,RaplaXMLWriter> writerMap,RaplaContext context) throws RaplaException {
writerMap.put( Category.TYPE,new CategoryWriter(context));
writerMap.put( Preferences.TYPE,new PreferenceWriter(context) );
writerMap.put( DynamicType.TYPE,new DynamicTypeWriter(context));
writerMap.put( User.TYPE, new UserWriter(context) );
writerMap.put( Allocatable.TYPE, new AllocatableWriter(context) );
writerMap.put( Reservation.TYPE,new ReservationWriter(context));
writerMap.put( RaplaConfiguration.TYPE,new RaplaConfigurationWriter(context) );
writerMap.put( RaplaMap.TYPE, new RaplaMapWriter(context) );
writerMap.put( Preferences.TYPE, new PreferenceWriter(context) );
writerMap.put( CalendarModelConfiguration.TYPE, new RaplaCalendarSettingsWriter(context) );
}
public RaplaDefaultContext createInputContext(RaplaContext parentContext, EntityStore store, IdCreator idTable) throws RaplaException {
RaplaDefaultContext ioContext = new RaplaDefaultContext( parentContext);
ioContext.put(EntityStore.class, store);
ioContext.put(IdCreator.class,idTable);
ioContext.put(PreferenceReader.LOCALNAMEMAPENTRY, getLocalnameMap());
Map<RaplaType,RaplaXMLReader> readerMap = new HashMap<RaplaType,RaplaXMLReader>();
ioContext.put(PreferenceReader.READERMAP, readerMap);
addReaders( readerMap, ioContext);
return ioContext;
}
public static TypedComponentRole<Boolean> PRINTID = new TypedComponentRole<Boolean>( IOContext.class.getName() + ".idonly");
public static TypedComponentRole<Provider<Category>> SUPERCATEGORY = new TypedComponentRole<Provider<Category>>( IOContext.class.getName() + ".supercategory");
public RaplaDefaultContext createOutputContext(RaplaContext parentContext, Provider<Category> superCategory,boolean includeIds) throws RaplaException {
RaplaDefaultContext ioContext = new RaplaDefaultContext( parentContext);
if ( includeIds)
{
ioContext.put(PRINTID, Boolean.TRUE);
}
if ( superCategory != null)
{
ioContext.put( SUPERCATEGORY, superCategory);
}
ioContext.put(PreferenceReader.LOCALNAMEMAPENTRY, getLocalnameMap());
Map<RaplaType,RaplaXMLWriter> writerMap = new HashMap<RaplaType,RaplaXMLWriter>();
ioContext.put(PreferenceWriter.WRITERMAP, writerMap);
addWriters( writerMap, ioContext );
return ioContext;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.io.IOException;
import java.util.Iterator;
import org.rapla.components.util.Assert;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.ClassificationFilterRule;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
class ClassificationFilterWriter extends RaplaXMLWriter {
public ClassificationFilterWriter(RaplaContext sm) throws RaplaException {
super(sm);
}
public void printClassificationFilter(ClassificationFilter f) throws IOException,RaplaException {
openTag("rapla:classificationfilter");
att("dynamictype", f.getType().getKey());
closeTag();
for (Iterator<? extends ClassificationFilterRule> it = f.ruleIterator();it.hasNext();) {
ClassificationFilterRule rule = it.next();
printClassificationFilterRule(rule);
}
closeElement("rapla:classificationfilter");
}
private void printClassificationFilterRule(ClassificationFilterRule rule) throws IOException,RaplaException {
Attribute attribute = rule.getAttribute();
Assert.notNull( attribute );
String[] operators = rule.getOperators();
Object[] values = rule.getValues();
openTag("rapla:rule");
att("attribute", attribute.getKey());
closeTag();
for (int i=0;i<operators.length;i++) {
openTag("rapla:orCond");
att("operator", operators[i]);
closeTagOnLine();
if (values[i] != null)
printAttributeValue(attribute, values[i]);
closeElementOnLine("rapla:orCond");
println();
}
closeElement("rapla:rule");
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.util.Date;
import org.rapla.components.util.Assert;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.entities.Annotatable;
import org.rapla.entities.IllegalAnnotationException;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.RepeatingType;
import org.rapla.entities.domain.internal.AppointmentImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class ReservationReader extends RaplaXMLReader {
ReservationImpl reservation;
private String allocatableId = null;
private AppointmentImpl appointment = null;
private Repeating repeating = null;
private DynAttReader dynAttHandler;
private String annotationKey;
private Annotatable currentAnnotatable;
public ReservationReader( RaplaContext context) throws RaplaException {
super( context);
dynAttHandler = new DynAttReader( context);
addChildHandler(dynAttHandler);
}
@Override
public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts)
throws RaplaSAXParseException
{
if (namespaceURI.equals( DYNATT_NS ) || namespaceURI.equals( EXTENSION_NS ))
{
dynAttHandler.setClassifiable(reservation);
delegateElement(dynAttHandler,namespaceURI,localName,atts);
return;
}
if (!namespaceURI.equals(RAPLA_NS))
return;
if ( localName.equals( "reservation" ) )
{
TimestampDates ts = readTimestamps( atts);
reservation = new ReservationImpl( ts.createTime, ts.changeTime );
reservation.setResolver( store );
currentAnnotatable = reservation;
setId(reservation, atts);
setLastChangedBy( reservation, atts);
setOwner(reservation, atts);
}
if (localName.equals("appointment"))
{
String id = atts.getValue("id");
String startDate=atts.getValue("start-date");
String endDate= atts.getValue("end-date");
if (endDate == null)
endDate = startDate;
String startTime = atts.getValue("start-time");
String endTime = atts.getValue("end-time");
Date start;
Date end;
if (startTime != null && endTime != null)
{
start = parseDateTime(startDate,startTime);
end = parseDateTime(endDate,endTime);
}
else
{
start = parseDate(startDate,false);
end = parseDate(endDate,true);
}
appointment= new AppointmentImpl(start,end);
appointment.setWholeDays(startTime== null && endTime==null);
if (id!=null)
{
setId(appointment, atts);
}
else
{
setNewId(appointment);
}
addAppointment(appointment);
}
if (localName.equals("repeating")) {
String type =atts.getValue("type");
String interval =atts.getValue("interval");
String enddate =atts.getValue("end-date");
String number =atts.getValue("number");
appointment.setRepeatingEnabled(true);
repeating = appointment.getRepeating();
repeating.setType( RepeatingType.findForString( type));
if (interval != null)
{
repeating.setInterval(Integer.valueOf(interval).intValue());
}
if (enddate != null)
{
repeating.setEnd(parseDate(enddate,true));
}
else if (number != null)
{
repeating.setNumber(Integer.valueOf(number).intValue());
}
else
{
repeating.setEnd(null);
}
/*
if (getLogger().enabled(6))
getLogger().log(6, "Repeating " + repeating.toString() );
*/
}
if (localName.equals("allocate")) {
String id = getString( atts, "idref" );
allocatableId = getId( Allocatable.TYPE, id);
reservation.addId("resources", allocatableId );
if ( appointment != null )
{
reservation.addRestrictionForId( allocatableId, appointment.getId());
}
}
if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS ))
{
annotationKey = atts.getValue( "key" );
Assert.notNull( annotationKey, "key attribute cannot be null" );
startContent();
}
if (localName.equals("exception")) {
}
if (localName.equals("date")) {
String dateString =atts.getValue("date");
if (dateString != null && repeating != null)
repeating.addException(parseDate(dateString,false));
}
}
protected void addAppointment(Appointment appointment) {
reservation.addAppointment(appointment);
}
@Override
public void processEnd(String namespaceURI,String localName) throws RaplaSAXParseException
{
if (!namespaceURI.equals(RAPLA_NS))
return;
if (localName.equals("appointment") && appointment != null )
{
add(appointment);
appointment = null;
}
if (localName.equals("reservation"))
{
add(reservation);
}
if (localName.equals( "annotation" ) && namespaceURI.equals( RAPLA_NS ))
{
try
{
String annotationValue = readContent().trim();
currentAnnotatable.setAnnotation( annotationKey, annotationValue );
}
catch (IllegalAnnotationException ex)
{
}
}
}
}
| Java |
package org.rapla.storage.xml;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import org.rapla.entities.Category;
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.domain.Allocatable;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.DynamicType;
public class RaplaEntityComparator implements Comparator<RaplaObject>
{
Map<RaplaType,Integer> ordering = new HashMap<RaplaType,Integer>();
public RaplaEntityComparator()
{
int i=0;
ordering.put( Category.TYPE,new Integer(i++));
ordering.put( DynamicType.TYPE, new Integer(i++));
ordering.put( User.TYPE,new Integer(i++));
ordering.put( Allocatable.TYPE, new Integer(i++));
ordering.put( Preferences.TYPE,new Integer(i++) );
ordering.put( Period.TYPE, new Integer(i++) );
ordering.put( Reservation.TYPE,new Integer(i++));
}
public int compare( RaplaObject o1, RaplaObject o2)
{
RaplaObject r1 = o1;
RaplaObject r2 = o2;
RaplaType t1 = r1.getRaplaType();
RaplaType t2 = r2.getRaplaType();
Integer ord1 = ordering.get( t1);
Integer ord2 = ordering.get( t2);
if ( o1 == o2)
{
return 0;
}
if ( ord1 != null && ord2 != null)
{
if (ord1.intValue()>ord2.intValue())
{
return 1;
}
if (ord1.intValue()<ord2.intValue())
{
return -1;
}
}
if ( ord1 != null && ord2 == null)
{
return -1;
}
if ( ord2 != null && ord1 == null)
{
return 1;
}
if ( o1.hashCode() > o2.hashCode())
{
return 1;
}
else
{
return -1;
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.util.Collection;
import java.util.HashSet;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXHandler;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.xml.sax.SAXException;
class DelegationHandler implements RaplaSAXHandler
{
StringBuffer currentText = null;
DelegationHandler parent = null;
DelegationHandler delegate = null;
int level = 0;
int entryLevel = 0;
Collection<DelegationHandler> childHandlers;
private void setParent( DelegationHandler parent )
{
this.parent = parent;
}
public void addChildHandler( DelegationHandler childHandler )
{
if (childHandlers == null)
childHandlers = new HashSet<DelegationHandler>();
childHandlers.add( childHandler );
childHandler.setParent( this );
}
public void startElement(String namespaceURI, String localName,
RaplaSAXAttributes atts) throws RaplaSAXParseException {
//printToSystemErr( localName, atts );
if (delegate != null)
{
delegate.startElement( namespaceURI, localName, atts );
}
else
{
level++;
processElement( namespaceURI, localName, atts );
}
}
// protected void printToSystemErr( String localName, Attributes atts )
// {
// int len = atts.getLength();
// StringBuffer buf = new StringBuffer();
// for ( int i = 0; i<len;i++)
// {
// buf.append( " ");
// buf.append( atts.getLocalName( i ));
// buf.append( "=");
// buf.append( atts.getValue( i ));
//
// }
// System.err.println(localName + buf.toString());
// }
final public void endElement(
String namespaceURI,
String localName
) throws RaplaSAXParseException
{
if (delegate != null)
{
delegate.endElement( namespaceURI, localName);
//After this call the delegate can be null again.
}
if (delegate == null)
{
processEnd( namespaceURI, localName );
//Check if end of delegation reached
if (entryLevel == level && parent != null)
{
parent.stopDelegation();
}
level--;
}
}
final public void characters( char[] ch, int start, int length )
{
if (delegate != null)
{
delegate.characters( ch, start, length );
}
else
{
processCharacters( ch, start, length );
}
}
/**
* @param namespaceURI
* @param localName
* @param atts
* @throws RaplaSAXParseException
*/
public void processElement(
String namespaceURI,
String localName,
RaplaSAXAttributes atts ) throws RaplaSAXParseException
{
}
/**
* @param namespaceURI
* @param localName
* @throws RaplaSAXParseException
*/
public void processEnd( String namespaceURI, String localName )
throws RaplaSAXParseException
{
}
/* Call this method to delegate the processessing of the encountered element with
all its subelements to another DelegationHandler.
*/
public final void delegateElement(
DelegationHandler child,
String namespaceURI,
String localName,
RaplaSAXAttributes atts ) throws RaplaSAXParseException
{
//System.out.println("Start delegation for " + localName);
delegate = child;
delegate.setDelegateLevel( level );
delegate.processElement( namespaceURI, localName, atts );
}
private void stopDelegation()
{
delegate = null;
}
private void setDelegateLevel( int level )
{
this.entryLevel = level;
this.level = level;
}
public void startContent()
{
currentText = new StringBuffer();
}
public String readContent()
{
if (currentText == null)
return null;
String result = currentText.toString();
currentText = null;
return result;
}
public RaplaSAXParseException createSAXParseException( String message )
{
return createSAXParseException( message, null);
}
public RaplaSAXParseException createSAXParseException( String message,Exception cause )
{
return new RaplaSAXParseException( message, cause);
}
/**
* @throws SAXException
*/
public void processCharacters( char ch[], int start, int length )
{
if (currentText != null)
currentText.append( ch, start, length );
}
}
| Java |
/*--------------------------------------------------------------------------*
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.rapla.components.util.Assert;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.Category;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.internal.PreferencesImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.internal.DynamicTypeImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.storage.LocalCache;
/** Stores the data from the local cache in XML-format to a print-writer.*/
public class RaplaMainWriter extends RaplaXMLWriter
{
protected final static String OUTPUT_FILE_VERSION="1.1";
String encoding = "utf-8";
protected LocalCache cache;
public RaplaMainWriter(RaplaContext context, LocalCache cache) throws RaplaException {
super(context);
this.cache = cache;
Assert.notNull(cache);
}
public void setWriter( Appendable writer ) {
super.setWriter( writer );
for ( RaplaXMLWriter xmlWriter: writerMap.values()) {
xmlWriter.setWriter( writer );
}
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public void printContent() throws IOException,RaplaException {
printHeader( 0, null, false );
printCategories();
println();
printDynamicTypes();
println();
((PreferenceWriter)getWriterFor(Preferences.TYPE)).printPreferences( cache.getPreferencesForUserId( null ));
println();
printUsers();
println();
printAllocatables();
println();
printReservations();
println();
closeElement("rapla:data");
}
public void printDynamicTypes() throws IOException,RaplaException {
openElement("relax:grammar");
DynamicTypeWriter dynamicTypeWriter = (DynamicTypeWriter)getWriterFor(DynamicType.TYPE);
for( DynamicType type:cache.getDynamicTypes()) {
if ((( DynamicTypeImpl) type).isInternal())
{
continue;
}
dynamicTypeWriter.printDynamicType(type);
println();
}
printStartPattern();
closeElement("relax:grammar");
}
private void printStartPattern() throws IOException {
openElement("relax:start");
openElement("relax:choice");
for( DynamicType type:cache.getDynamicTypes())
{
if ((( DynamicTypeImpl) type).isInternal())
{
continue;
}
openTag("relax:ref");
att("name",type.getKey());
closeElementTag();
}
closeElement("relax:choice");
closeElement("relax:start");
}
public void printCategories() throws IOException,RaplaException {
openElement("rapla:categories");
CategoryWriter categoryWriter = (CategoryWriter)getWriterFor(Category.TYPE);
Category[] categories = cache.getSuperCategory().getCategories();
for (int i=0;i<categories.length;i++) {
categoryWriter.printCategory(categories[i]);
}
closeElement("rapla:categories");
}
public void printUsers() throws IOException,RaplaException {
openElement("rapla:users");
UserWriter userWriter = (UserWriter)getWriterFor(User.TYPE);
println("<!-- Users of the system -->");
for (User user:cache.getUsers()) {
String userId = user.getId();
PreferencesImpl preferences = cache.getPreferencesForUserId( userId);
String password = cache.getPassword(userId);
userWriter.printUser( user, password, preferences);
}
closeElement("rapla:users");
}
public void printAllocatables() throws IOException,RaplaException {
openElement("rapla:resources");
println("<!-- resources -->");
// Print all resources that are not persons
AllocatableWriter allocatableWriter = (AllocatableWriter)getWriterFor(Allocatable.TYPE);
Collection<Allocatable> allAllocatables = cache.getAllocatables();
Map<String,List<Allocatable>> map = new LinkedHashMap<String,List<Allocatable>>();
for (DynamicType type:cache.getDynamicTypes()) {
map.put( type.getId(), new ArrayList<Allocatable>());
}
for (Allocatable allocatable:allAllocatables) {
Classification classification = allocatable.getClassification();
String id = classification.getType().getId();
List<Allocatable> list = map.get( id);
list.add( allocatable);
}
// Print all Persons
for ( String id : map.keySet())
{
List<Allocatable> list = map.get( id);
for (Allocatable allocatable:list) {
allocatableWriter.printAllocatable(allocatable);
}
}
println();
closeElement("rapla:resources");
}
void printReservations() throws IOException, RaplaException {
openElement("rapla:reservations");
ReservationWriter reservationWriter = (ReservationWriter)getWriterFor(Reservation.TYPE);
for (Reservation reservation: cache.getReservations()) {
reservationWriter.printReservation( reservation );
}
closeElement("rapla:reservations");
}
private void printHeader(long repositoryVersion, TimeInterval invalidateInterval, boolean resourcesRefresh) throws IOException
{
println("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?><!--*- coding: " + encoding + " -*-->");
openTag("rapla:data");
for (int i=0;i<NAMESPACE_ARRAY.length;i++) {
String prefix = NAMESPACE_ARRAY[i][1];
String uri = NAMESPACE_ARRAY[i][0];
if ( prefix == null) {
att("xmlns", uri);
} else {
att("xmlns:" + prefix, uri);
}
println();
}
att("version", RaplaMainWriter.OUTPUT_FILE_VERSION);
if ( repositoryVersion > 0)
{
att("repositoryVersion", String.valueOf(repositoryVersion));
}
if ( resourcesRefresh)
{
att("resourcesRefresh", "true");
}
if ( invalidateInterval != null)
{
Date startDate = invalidateInterval.getStart();
Date endDate = invalidateInterval.getEnd();
String start;
if ( startDate == null)
{
startDate = new Date(0);
}
start = dateTimeFormat.formatDate( startDate);
att("startDate", start);
if ( endDate != null)
{
String end = dateTimeFormat.formatDate( endDate);
att("endDate", end);
}
}
closeTag();
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.configuration.CalendarModelConfiguration;
import org.rapla.entities.configuration.RaplaMap;
import org.rapla.entities.configuration.internal.CalendarModelConfigurationImpl;
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.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class RaplaCalendarSettingsWriter extends ClassificationFilterWriter {
/**
* @param sm
* @throws RaplaException
*/
public RaplaCalendarSettingsWriter(RaplaContext sm) throws RaplaException {
super(sm);
}
public void writeObject(RaplaObject type) throws IOException, RaplaException {
CalendarModelConfigurationImpl calendar = (CalendarModelConfigurationImpl) type ;
openTag("rapla:" + CalendarModelConfiguration.TYPE.getLocalName());
att("title", calendar.getTitle());
att("view", calendar.getView());
Map<String,String> extensionMap = calendar.getOptionMap();
final String saveDate = extensionMap != null ? extensionMap.get( CalendarModel.SAVE_SELECTED_DATE) : "false" ;
boolean saveDateActive = saveDate != null && saveDate.equals("true");
if ( calendar.getSelectedDate() != null && saveDateActive) {
att("date", dateTimeFormat.formatDate( calendar.getSelectedDate()));
}
if ( calendar.getStartDate() != null && saveDateActive) {
att("startdate", dateTimeFormat.formatDate( calendar.getStartDate()));
}
if ( calendar.getEndDate() != null && saveDateActive) {
att("enddate", dateTimeFormat.formatDate( calendar.getEndDate()));
}
if ( calendar.isResourceRootSelected())
{
att("rootSelected","true");
}
closeTag();
Collection<Entity> selectedObjects = calendar.getSelected();
if (selectedObjects != null && selectedObjects.size() > 0)
{
openElement("selected");
for ( Entity entity:selectedObjects)
{
printReference( entity);
}
closeElement("selected");
}
if (extensionMap != null && extensionMap.size() > 0)
{
openElement("options");
RaplaMapWriter writer = (RaplaMapWriter)getWriterFor( RaplaMap.TYPE);
writer.writeMap( extensionMap);
closeElement("options");
}
ClassificationFilter[] filter =calendar.getFilter() ;
if ( filter.length> 0)
{
openElement("filter");
for (ClassificationFilter f:filter)
{
final DynamicType dynamicType = f.getType();
final String annotation = dynamicType.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
boolean eventType = annotation != null && annotation.equals( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
if (( eventType && !calendar.isDefaultEventTypes())
|| (!eventType && !calendar.isDefaultResourceTypes())
)
{
printClassificationFilter( f );
}
}
closeElement("filter");
}
closeElement("rapla:" + CalendarModelConfiguration.TYPE.getLocalName());
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.io.IOException;
import java.util.Date;
import org.rapla.entities.Category;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
/** Stores the data from the local cache in XML-format to a print-writer.*/
public class DynamicTypeWriter extends RaplaXMLWriter
{
public DynamicTypeWriter(RaplaContext sm) throws RaplaException {
super(sm);
}
public void printDynamicType(DynamicType type) throws IOException,RaplaException {
openTag("relax:define");
att("name",type.getKey());
closeTag();
openTag("relax:element");
att("name","dynatt:" + type.getKey());
if (isPrintId())
{
att("id",getId(type));
}
printTimestamp( type );
closeTag();
printTranslation(type.getName());
printAnnotations(type);
Attribute att[] = type.getAttributes();
for (int i = 0; i< att.length; i ++) {
printAttribute(att[i]);
}
closeElement("relax:element");
closeElement("relax:define");
}
public void writeObject(RaplaObject type) throws IOException, RaplaException {
printDynamicType( (DynamicType) type );
}
private String getCategoryPath( Category category) throws EntityNotFoundException {
Category rootCategory = getSuperCategory();
if ( category != null && rootCategory.equals( category) )
{
return "";
}
return ((CategoryImpl) rootCategory ).getPathForCategory(category);
}
protected void printAttribute(Attribute attribute) throws IOException,RaplaException {
if (attribute.isOptional())
openElement("relax:optional");
openTag("relax:element");
att("name",attribute.getKey());
// if (isPrintId())
// att("id",getId(attribute));
AttributeType type = attribute.getType();
closeTag();
printTranslation( attribute.getName() );
printAnnotations( attribute );
String[] constraintKeys = attribute.getConstraintKeys();
openTag("relax:data");
att("type", type.toString());
closeElementTag();
for (int i = 0; i<constraintKeys.length; i++ ) {
String key = constraintKeys[i];
Object constraint = attribute.getConstraint( key );
// constraint not set
if (constraint == null)
continue;
openTag("rapla:constraint");
att("name", key );
closeTagOnLine();
if ( constraint instanceof Category) {
Category category = (Category) constraint;
print( getCategoryPath( category ) );
}
else if ( constraint instanceof DynamicType) {
DynamicType dynamicType = (DynamicType) constraint;
print( dynamicType.getKey() );
}
else if ( constraint instanceof Date) {
final String formatDate = dateTimeFormat.formatDate( (Date) constraint);
print( formatDate);
} else {
print( constraint.toString());
}
closeElementOnLine("rapla:constraint");
println();
}
Object defaultValue = attribute.defaultValue();
if ( defaultValue != null)
{
openTag("rapla:default");
closeTagOnLine();
if ( defaultValue instanceof Category) {
Category category = (Category) defaultValue;
print( getCategoryPath( category ) );
} else if ( defaultValue instanceof Date) {
final String formatDate = dateTimeFormat.formatDate( (Date) defaultValue);
print( formatDate);
} else {
print( defaultValue.toString());
}
closeElementOnLine("rapla:default");
println();
}
closeElement("relax:element");
if (attribute.isOptional())
closeElement("relax:optional");
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.framework.Configuration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.internal.SAXConfigurationHandler;
public class RaplaConfigurationReader extends RaplaXMLReader {
boolean delegating = false;
public RaplaConfigurationReader(RaplaContext context) throws RaplaException {
super(context);
}
SAXConfigurationHandler configurationHandler = new SAXConfigurationHandler();
@Override
public void processElement(String namespaceURI,String localName,RaplaSAXAttributes atts)
throws RaplaSAXParseException
{
if ( RAPLA_NS.equals(namespaceURI) && localName.equals("config"))
return;
delegating = true;
configurationHandler.startElement(namespaceURI,localName, atts);
}
@Override
public void processEnd(String namespaceURI,String localName)
throws RaplaSAXParseException
{
if ( RAPLA_NS.equals(namespaceURI) && localName.equals("config"))
{
return;
}
configurationHandler.endElement(namespaceURI, localName);
delegating = false;
}
@Override
public void processCharacters(char[] ch,int start,int length)
{
if ( delegating ){
configurationHandler.characters(ch,start,length);
}
}
public RaplaObject getType() {
return new RaplaConfiguration(getConfiguration());
}
private Configuration getConfiguration() {
Configuration conf = configurationHandler.getConfiguration();
return conf;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.util.Date;
import java.util.Map;
import org.rapla.components.util.ParseDateException;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.MultiLanguageName;
import org.rapla.entities.Ownable;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.Classifiable;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.entities.storage.internal.SimpleEntity;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.IdCreator;
import org.rapla.storage.impl.EntityStore;
public class RaplaXMLReader extends DelegationHandler implements Namespaces
{
EntityStore store;
Logger logger;
IdCreator idTable;
RaplaContext context;
Map<String,RaplaType> localnameMap;
Map<RaplaType,RaplaXMLReader> readerMap;
SerializableDateTimeFormat dateTimeFormat;
I18nBundle i18n;
Date now;
public static class TimestampDates
{
public Date createTime;
public Date changeTime;
}
public RaplaXMLReader( RaplaContext context ) throws RaplaException
{
logger = context.lookup( Logger.class );
this.context = context;
this.i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
this.store = context.lookup( EntityStore.class);
this.idTable = context.lookup( IdCreator.class );
RaplaLocale raplaLocale = context.lookup( RaplaLocale.class );
dateTimeFormat = raplaLocale.getSerializableFormat();
this.localnameMap = context.lookup( PreferenceReader.LOCALNAMEMAPENTRY );
this.readerMap = context.lookup( PreferenceReader.READERMAP );
now = new Date();
}
public TimestampDates readTimestamps(RaplaSAXAttributes atts) throws RaplaSAXParseException
{
String createdAt = atts.getValue( "", "created-at");
String lastChanged = atts.getValue( "", "last-changed");
Date createTime = null;
Date changeTime = createTime;
if (createdAt != null)
{
createTime = parseTimestamp( createdAt);
}
else
{
createTime = now;
}
if (lastChanged != null)
{
changeTime = parseTimestamp( lastChanged);
}
else
{
changeTime = createTime;
}
if ( changeTime.after( now) )
{
getLogger().warn("Last changed is in the future " +lastChanged + ". Taking current time as new timestamp.");
changeTime = now;
}
if ( createTime.after( now) )
{
getLogger().warn("Create time is in the future " +createTime + ". Taking current time as new timestamp.");
createTime = now;
}
TimestampDates result = new TimestampDates();
result.createTime = createTime;
result.changeTime = changeTime;
return result;
}
public RaplaType getTypeForLocalName( String localName )
throws RaplaSAXParseException
{
RaplaType type = localnameMap.get( localName );
if (type == null)
throw createSAXParseException( "No type declared for localname " + localName );
return type;
}
/**
* @param raplaType
* @throws RaplaSAXParseException
*/
protected RaplaXMLReader getChildHandlerForType( RaplaType raplaType )
throws RaplaSAXParseException
{
RaplaXMLReader childReader = readerMap.get( raplaType );
if (childReader == null)
{
throw createSAXParseException( "No Reader declared for type " + raplaType );
}
addChildHandler( childReader );
return childReader;
}
protected Logger getLogger()
{
return logger;
}
public I18nBundle getI18n()
{
return i18n;
}
public Long parseLong( String text ) throws RaplaSAXParseException
{
try
{
return new Long( text );
}
catch (NumberFormatException ex)
{
throw createSAXParseException( "No valid number format: " + text );
}
}
public Boolean parseBoolean( String text )
{
return new Boolean( text );
}
public Date parseDate( String date, boolean fillDate ) throws RaplaSAXParseException
{
try
{
return dateTimeFormat.parseDate( date, fillDate );
}
catch (ParseDateException ex)
{
throw createSAXParseException( ex.getMessage() );
}
}
public Date parseDateTime( String date, String time ) throws RaplaSAXParseException
{
try
{
return dateTimeFormat.parseDateTime( date, time );
}
catch (ParseDateException ex)
{
throw createSAXParseException( ex.getMessage() );
}
}
public Date parseTimestamp( String timestamp ) throws RaplaSAXParseException
{
try
{
return dateTimeFormat.parseTimestamp(timestamp);
}
catch (ParseDateException ex)
{
throw createSAXParseException( ex.getMessage() );
}
}
protected String getString(
RaplaSAXAttributes atts,
String key,
String defaultString )
{
String str = atts.getValue( "", key );
return (str != null) ? str : defaultString;
}
protected String getString( RaplaSAXAttributes atts, String key )
throws RaplaSAXParseException
{
String str = atts.getValue( "", key );
if (str == null)
throw createSAXParseException( "Attribute " + key + " not found!" );
return str;
}
/** return the new id */
protected String setId( Entity entity, RaplaSAXAttributes atts )
throws RaplaSAXParseException
{
String idString = atts.getValue( "id" );
String id = getId( entity.getRaplaType(), idString );
((SimpleEntity)entity).setId( id );
return id;
}
/** return the new id */
protected Object setNewId( Entity entity ) throws RaplaSAXParseException
{
try
{
String id = idTable.createId( entity.getRaplaType() );
((SimpleEntity)entity).setId( id );
return id;
}
catch (RaplaException ex)
{
throw createSAXParseException( ex.getMessage() );
}
}
protected <T extends SimpleEntity&Ownable> void setOwner( T ownable, RaplaSAXAttributes atts )
throws RaplaSAXParseException
{
String ownerString = atts.getValue( "owner" );
if (ownerString != null)
{
ownable.putId("owner", getId( User.TYPE, ownerString ) );
}
// No else case as no owner should still be possible and there should be no default owner
}
protected void setLastChangedBy(SimpleEntity entity, RaplaSAXAttributes atts) {
String lastChangedBy = atts.getValue( "last-changed-by");
if ( lastChangedBy != null)
{
try
{
User user = resolve(User.TYPE,lastChangedBy );
entity.setLastChangedBy( user );
}
catch (RaplaSAXParseException ex)
{
getLogger().warn("Can't find user " + lastChangedBy + " in entity " + entity.getId());
}
}
}
@SuppressWarnings("deprecation")
protected String getId( RaplaType type, String str ) throws RaplaSAXParseException
{
try
{
final String id;
if ( str.equals(Category.SUPER_CATEGORY_ID))
{
id = Category.SUPER_CATEGORY_ID;
}
else if (org.rapla.storage.OldIdMapping.isTextId(type, str))
{
id = idTable.createId(type, str);
}
else
{
id = str;
}
return id;
}
catch (RaplaException ex)
{
ex.printStackTrace();
throw createSAXParseException( ex.getMessage() );
}
}
void throwEntityNotFound( String type, Integer id ) throws RaplaSAXParseException
{
throw createSAXParseException( type + " with id '" + id + "' not found." );
}
public RaplaObject getType() throws RaplaSAXParseException
{
throw createSAXParseException( "Method getType() not implemented by subclass " + this.getClass().getName() );
}
protected CategoryImpl getSuperCategory()
{
return store.getSuperCategory();
}
public DynamicType getDynamicType( String keyref )
{
return store.getDynamicType( keyref);
}
protected <T extends Entity> T resolve( RaplaType<T> type, String str ) throws RaplaSAXParseException
{
try
{
String id = getId( type, str );
Class<T> typeClass = type.getTypeClass();
T resolved = store.resolve( id, typeClass );
return resolved;
}
catch (EntityNotFoundException ex)
{
throw createSAXParseException(ex.getMessage() , ex);
}
}
protected Object parseAttributeValue( Attribute attribute, String text ) throws RaplaSAXParseException
{
try
{
AttributeType type = attribute.getType();
if ( type == AttributeType.CATEGORY )
{
text = getId(Category.TYPE, text);
}
else if ( type == AttributeType.ALLOCATABLE )
{
text = getId(Allocatable.TYPE, text);
}
return AttributeImpl.parseAttributeValue( attribute, text);
}
catch (RaplaException ex)
{
throw createSAXParseException( ex.getMessage() );
}
}
public void add(Entity entity) throws RaplaSAXParseException{
if ( entity instanceof Classifiable)
{
if ((( Classifiable) entity).getClassification() == null)
{
throw createSAXParseException("Classification can't be null");
}
}
store.put(entity);
}
protected Category getCategoryFromPath( String path ) throws RaplaSAXParseException
{
try
{
return getSuperCategory().getCategoryFromPath( path );
}
catch (Exception ex)
{
throw createSAXParseException( ex.getMessage() );
}
}
protected Category getGroup(String groupKey) throws RaplaSAXParseException{
CategoryImpl groupCategory = (CategoryImpl) getSuperCategory().getCategory(
Permission.GROUP_CATEGORY_KEY );
if (groupCategory == null)
{
throw createSAXParseException( Permission.GROUP_CATEGORY_KEY + " category not found" );
}
try
{
return groupCategory.getCategoryFromPath( groupKey );
}
catch (Exception ex)
{
throw createSAXParseException( ex.getMessage(),ex );
}
}
protected void putPassword( String userid, String password )
{
store.putPassword( userid, password);
}
protected void setCurrentTranslations(MultiLanguageName name) {
String lang = i18n.getLang();
boolean contains = name.getAvailableLanguages().contains( lang);
if (!contains)
{
try
{
String translation = i18n.getString( name.getName("en"));
name.setName( lang, translation);
}
catch (Exception ex)
{
}
}
}
static public String wrapRaplaDataTag(String xml) {
StringBuilder dataElement = new StringBuilder();
dataElement.append("<rapla:data ");
for (int i=0;i<RaplaXMLWriter.NAMESPACE_ARRAY.length;i++) {
String prefix = RaplaXMLWriter.NAMESPACE_ARRAY[i][1];
String uri = RaplaXMLWriter.NAMESPACE_ARRAY[i][0];
if ( prefix == null) {
dataElement.append("xmlns=");
} else {
dataElement.append("xmlns:" + prefix + "=");
}
dataElement.append("\"");
dataElement.append( uri );
dataElement.append("\" ");
}
dataElement.append(">");
dataElement.append( xml );
dataElement.append( "</rapla:data>");
String xmlWithNamespaces = dataElement.toString();
return xmlWithNamespaces;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import java.io.IOException;
import java.util.Date;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class ReservationWriter extends ClassifiableWriter {
public ReservationWriter(RaplaContext sm) throws RaplaException {
super(sm);
}
protected void printReservation(Reservation r) throws IOException,RaplaException {
openTag("rapla:reservation");
printId(r);
printOwner(r);
printTimestamp(r);
closeTag();
printAnnotations( r, false);
// System.out.println(((Entity)r).getId() + " Name: " + r.getName() +" User: " + r.getUser());
printClassification(r.getClassification());
{
Appointment[] appointments = r.getAppointments();
for (int i = 0; i< appointments.length; i ++) {
printAppointment(appointments[i], true);
}
}
Allocatable[] allocatables = r.getAllocatables();
// Print allocatables that dont have a restriction
for (int i=0; i< allocatables.length; i ++) {
Allocatable allocatable = allocatables[i];
if (r.getRestriction( allocatable ).length > 0 )
{
continue;
}
openTag("rapla:allocate");
printIdRef( allocatable );
closeElementTag();
}
closeElement("rapla:reservation");
}
public void writeObject( RaplaObject object ) throws IOException, RaplaException
{
printReservation( (Reservation) object);
}
public void printAppointment(Appointment appointment, boolean includeAllocations) throws IOException {
openTag("rapla:appointment");
// always print the id
//if (isPrintId()) {
printId( appointment );
//}
att("start-date",dateTimeFormat.formatDate( appointment.getStart()));
if (appointment.isWholeDaysSet()) {
boolean bCut = appointment.getEnd().after(appointment.getStart());
att("end-date",dateTimeFormat.formatDate(appointment.getEnd(),bCut));
} else {
att("start-time",dateTimeFormat.formatTime( appointment.getStart()));
att("end-date",dateTimeFormat.formatDate( appointment.getEnd()));
att("end-time",dateTimeFormat.formatTime( appointment.getEnd()));
}
Reservation reservation = appointment.getReservation();
Allocatable[] allocatables;
if ( reservation != null)
{
allocatables = reservation.getRestrictedAllocatables(appointment);
}
else
{
allocatables = Allocatable.ALLOCATABLE_ARRAY;
}
if (appointment.getRepeating() == null && allocatables.length == 0)
{
closeElementTag();
}
else
{
closeTag();
if (appointment.getRepeating() != null) {
printRepeating(appointment.getRepeating());
}
if ( includeAllocations)
{
for (int i=0; i< allocatables.length; i ++) {
Allocatable allocatable = allocatables[i];
openTag("rapla:allocate");
printIdRef( allocatable );
closeElementTag();
}
}
closeElement("rapla:appointment");
}
}
private void printRepeating(Repeating r) throws IOException {
openTag("rapla:repeating");
if (r.getInterval()!=1)
att("interval",String.valueOf(r.getInterval()));
att("type",r.getType().toString());
if (r.isFixedNumber()) {
att("number",String.valueOf(r.getNumber()));
} else {
if (r.getEnd() != null)
att("end-date"
,dateTimeFormat.formatDate(r.getEnd(),true));
}
Date[] exceptions = r.getExceptions();
if (exceptions.length==0) {
closeElementTag();
return;
}
closeTag();
for (int i=0;i<exceptions.length;i++) {
openElement("rapla:exception");
openTag("rapla:date");
att("date",dateTimeFormat.formatDate( exceptions[i]));
closeElementTag();
closeElement("rapla:exception");
}
closeElement("rapla:repeating");
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.xml;
import org.rapla.components.util.Assert;
import org.rapla.components.util.xml.RaplaSAXAttributes;
import org.rapla.components.util.xml.RaplaSAXParseException;
import org.rapla.entities.Annotatable;
import org.rapla.entities.Category;
import org.rapla.entities.IllegalAnnotationException;
import org.rapla.entities.User;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.domain.ResourceAnnotations;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.domain.internal.PermissionImpl;
import org.rapla.entities.storage.internal.ReferenceHandler;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class AllocatableReader extends RaplaXMLReader
{
private DynAttReader dynAttHandler;
private AllocatableImpl allocatable;
private String annotationKey;
private Annotatable currentAnnotatable;
public AllocatableReader( RaplaContext context ) throws RaplaException
{
super( context );
dynAttHandler = new DynAttReader( context );
addChildHandler( dynAttHandler );
}
@Override
public void processElement(
String namespaceURI,
String localName,
RaplaSAXAttributes atts ) throws RaplaSAXParseException
{
if (namespaceURI.equals( DYNATT_NS ) || namespaceURI.equals( EXTENSION_NS ))
{
if ( localName.equals("rapla:crypto"))
{
return;
}
dynAttHandler.setClassifiable( allocatable );
delegateElement(
dynAttHandler,
namespaceURI,
localName,
atts );
return;
}
if (!namespaceURI.equals( RAPLA_NS ))
return;
if (localName.equals( "permission" ))
{
PermissionImpl permission = new PermissionImpl();
permission.setResolver( store );
// process user
String userString = atts.getValue( "user" );
ReferenceHandler referenceHandler = permission.getReferenceHandler();
if (userString != null)
{
referenceHandler.putId("user", getId(User.TYPE,userString));
}
// process group
String groupId = atts.getValue( "groupidref" );
if (groupId != null)
{
referenceHandler.putId("group", getId(Category.TYPE,groupId));
}
else
{
String groupName = atts.getValue( "group" );
if (groupName != null)
{
Category group= getGroup( groupName);
permission.setGroup( group);
}
}
String startDate = getString( atts, "start-date", null );
if (startDate != null)
{
permission.setStart( parseDate( startDate, false ) );
}
String endDate = getString( atts, "end-date", null );
if (endDate != null)
{
permission.setEnd( parseDate( endDate, false ) );
}
String minAdvance = getString( atts, "min-advance", null );
if (minAdvance != null)
{
permission.setMinAdvance( parseLong( minAdvance ).intValue() );
}
String maxAdvance = getString( atts, "max-advance", null );
if (maxAdvance != null)
{
permission.setMaxAdvance( parseLong( maxAdvance ).intValue() );
}
String accessLevel = getString(
atts,
"access",
Permission.ACCESS_LEVEL_NAMEMAP.get( Permission.ALLOCATE_CONFLICTS ) );
Integer matchingLevel = Permission.ACCESS_LEVEL_NAMEMAP.findAccessLevel( accessLevel );
if (matchingLevel == null)
{
throw createSAXParseException( "Unknown access level '" + accessLevel + "'" );
}
permission.setAccessLevel( matchingLevel );
allocatable.addPermission( permission );
}
else if (localName.equals( "annotation" ) )
{
annotationKey = atts.getValue( "key" );
Assert.notNull( annotationKey, "key attribute cannot be null" );
startContent();
}
else
{
TimestampDates ts = readTimestamps( atts);
allocatable = new AllocatableImpl(ts.createTime, ts.changeTime);
allocatable.setResolver( store );
currentAnnotatable = allocatable;
setId( allocatable, atts );
// support old holdback conflicts behaviour
{
String holdBackString = getString( atts, "holdbackconflicts", "false" );
if ( Boolean.valueOf( holdBackString ) )
{
try {
allocatable.setAnnotation(ResourceAnnotations.KEY_CONFLICT_CREATION, ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE);
} catch (IllegalAnnotationException e) {
throw createSAXParseException(e.getMessage(),e);
}
}
}
setLastChangedBy(allocatable, atts);
setOwner(allocatable, atts);
}
}
@Override
public void processEnd( String namespaceURI, String localName ) throws RaplaSAXParseException
{
if (!namespaceURI.equals( RAPLA_NS ))
return;
if (localName.equals( "resource" ) || localName.equals( "person" ) )
{
if (allocatable.getPermissions().length == 0)
allocatable.addPermission( new PermissionImpl() );
add( allocatable );
}
else if (localName.equals( "extension" ) )
{
if ( allocatable.getClassification() != null)
{
add( allocatable );
}
}
else if (localName.equals( "annotation" ) )
{
try
{
String annotationValue = readContent().trim();
currentAnnotatable.setAnnotation( annotationKey, annotationValue );
}
catch (IllegalAnnotationException ex)
{
}
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage;
import org.rapla.entities.RaplaType;
import org.rapla.framework.RaplaException;
public interface IdCreator {
public String createId(RaplaType raplaType) throws RaplaException;
public String createId(RaplaType type, String seed) throws RaplaException;
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
/** A Facade Interface for manipulating the stored data.
* This abstraction allows Rapla to store the data
* in many ways. <BR>
* Currently implemented are the storage in an XML-File
* ,the storage in an SQL-DBMS and storage over a
* network connection.
* @see org.rapla.storage.dbsql.DBOperator
* @see org.rapla.storage.dbfile.XMLOperator
* @see org.rapla.storage.dbrm.RemoteOperator
* @author Christopher Kohlhaas
*/
package org.rapla.storage;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import org.rapla.ConnectInfo;
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.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.storage.EntityResolver;
import org.rapla.facade.Conflict;
import org.rapla.framework.RaplaException;
public interface StorageOperator extends EntityResolver {
public static final int MAX_DEPENDENCY = 20;
public final static String UNRESOLVED_RESOURCE_TYPE = "rapla:unresolvedResource";
public final static String ANONYMOUSEVENT_TYPE = "rapla:anonymousEvent";
public final static String SYNCHRONIZATIONTASK_TYPE = "rapla:synchronizationTask";
public final static String DEFAUTL_USER_TYPE = "rapla:defaultUser";
public final static String PERIOD_TYPE = "rapla:period";
User connect() throws RaplaException;
User connect(ConnectInfo connectInfo) throws RaplaException;
boolean isConnected();
/** Refreshes the data. This could be helpful if the storage
* operator uses a cache and does not support "Active Monitoring"
* of the original data */
void refresh() throws RaplaException;
void disconnect() throws RaplaException;
/** should return a clone of the object. <strong>Never</strong> edit the
original, <strong>always</strong> edit the object returned by editObject.*/
Collection<Entity> editObjects(Collection<Entity> obj, User user) throws RaplaException;
Map<String,Entity> getFromId(Collection<String> idSet, boolean throwEntityNotFound) throws RaplaException;
Map<Entity,Entity> getPersistant(Collection<? extends Entity> entity) throws RaplaException;
/** Stores and/or removes entities and specifies a user that is responsible for the changes.
* Notifies all registered StorageUpdateListeners after a successful
storage.*/
void storeAndRemove(Collection<Entity> storeObjects,Collection<Entity> removeObjects,User user) throws RaplaException;
String[] createIdentifier(RaplaType raplaType, int count) throws RaplaException;
Collection<User> getUsers() throws RaplaException;
Collection<DynamicType> getDynamicTypes() throws RaplaException;
/** returns the user or null if a user with the given username was not found. */
User getUser(String username) throws RaplaException;
Preferences getPreferences(User user, boolean createIfNotNull) throws RaplaException;
/** returns the reservations of the specified user, sorted by name.
* @param allocatables
* @param reservationFilters
* @param annotationQuery */
Collection<Reservation> getReservations(User user,Collection<Allocatable> allocatables, Date start,Date end, ClassificationFilter[] reservationFilters, Map<String, String> annotationQuery) throws RaplaException;
Collection<Allocatable> getAllocatables(ClassificationFilter[] filters) throws RaplaException;
Category getSuperCategory();
/** changes the password for the user */
void changePassword(User user,char[] oldPassword,char[] newPassword) throws RaplaException;
/** changes the name for the passed user. If a person is connected then all three fields are used. Otherwise only lastname is used*/
void changeName(User user,String title, String firstname, String surname) throws RaplaException;
/** changes the name for the user */
void changeEmail(User user,String newEmail) throws RaplaException;
void confirmEmail(User user, String newEmail) throws RaplaException;
boolean canChangePassword() throws RaplaException;
void addStorageUpdateListener(StorageUpdateListener updateListener);
void removeStorageUpdateListener(StorageUpdateListener updateListener);
/** returns the beginning of the current day. Uses getCurrentTimstamp. */
Date today();
/** returns the date and time in seconds for creation. Server time will be used if in client/server mode. Note that this is always the utc time */
Date getCurrentTimestamp();
boolean supportsActiveMonitoring();
Map<Allocatable,Collection<Appointment>> getFirstAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException;
Map<Allocatable, Map<Appointment,Collection<Appointment>>> getAllAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException;
Date getNextAllocatableDate(Collection<Allocatable> allocatables,Appointment appointment, Collection<Reservation> ignoreList, Integer worktimeStartMinutes,Integer worktimeEndMinutes, Integer[] excludedDays, Integer rowsPerHour) throws RaplaException;
Collection<Conflict> getConflicts(User user) throws RaplaException;
Collection<String> getTemplateNames() throws RaplaException;
} | Java |
package org.rapla.storage;
import org.rapla.entities.Entity;
public interface UpdateOperation {
public Entity getCurrent();
} | Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbsql;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import javax.sql.DataSource;
import org.rapla.ConnectInfo;
import org.rapla.components.util.xml.RaplaNonValidatedInput;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.framework.Configuration;
import org.rapla.framework.ConfigurationException;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaDefaultContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.internal.ContextTools;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.CachableStorageOperator;
import org.rapla.storage.CachableStorageOperatorCommand;
import org.rapla.storage.IdCreator;
import org.rapla.storage.ImportExportManager;
import org.rapla.storage.LocalCache;
import org.rapla.storage.UpdateEvent;
import org.rapla.storage.UpdateResult;
import org.rapla.storage.impl.EntityStore;
import org.rapla.storage.impl.server.LocalAbstractCachableOperator;
import org.rapla.storage.xml.IOContext;
import org.rapla.storage.xml.RaplaMainWriter;
/** This Operator is used to store the data in a SQL-DBMS.*/
public class DBOperator extends LocalAbstractCachableOperator
{
private String driverClassname;
protected String datasourceName;
protected String user;
protected String password;
protected String dbURL;
protected Driver dbDriver;
protected boolean isConnected;
Properties dbProperties = new Properties();
boolean bSupportsTransactions = false;
boolean hsqldb = false;
private String backupEncoding;
private String backupFileName;
Object lookup;
String connectionName;
public DBOperator(RaplaContext context, Logger logger,Configuration config) throws RaplaException {
super( context, logger);
String backupFile = config.getChild("backup").getValue("");
if (backupFile != null)
backupFileName = ContextTools.resolveContext( backupFile, context);
backupEncoding = config.getChild( "encoding" ).getValue( "utf-8" );
datasourceName = config.getChild("datasource").getValue(null);
// dont use datasource (we have to configure a driver )
if ( datasourceName == null)
{
try
{
driverClassname = config.getChild("driver").getValue();
dbURL = ContextTools.resolveContext( config.getChild("url").getValue(), context);
getLogger().info("Data:" + dbURL);
}
catch (ConfigurationException e)
{
throw new RaplaException( e );
}
dbProperties.setProperty("user", config.getChild("user").getValue("") );
dbProperties.setProperty("password", config.getChild("password").getValue("") );
hsqldb = config.getChild("hsqldb-shutdown").getValueAsBoolean( false );
try
{
dbDriver = (Driver) getClass().getClassLoader().loadClass(driverClassname).newInstance();
}
catch (ClassNotFoundException e)
{
throw new RaplaException("DB-Driver not found: " + driverClassname +
"\nCheck classpath!");
}
catch (Exception e)
{
throw new RaplaException("Could not instantiate DB-Driver: " + driverClassname, e);
}
}
else
{
try {
lookup = ContextTools.resolveContextObject(datasourceName, context );
} catch (RaplaContextException ex) {
throw new RaplaDBException("Datasource " + datasourceName + " not found");
}
}
}
public boolean supportsActiveMonitoring() {
return false;
}
public String getConnectionName()
{
if ( connectionName != null)
{
return connectionName;
}
if ( datasourceName != null)
{
return datasourceName;
}
return dbURL;
}
public Connection createConnection() throws RaplaException {
boolean withTransactionSupport = true;
return createConnection(withTransactionSupport);
}
public Connection createConnection(boolean withTransactionSupport) throws RaplaException {
Connection connection = null;
try {
//datasource lookup
Object source = lookup;
// if ( lookup instanceof String)
// {
// InitialContext ctx = new InitialContext();
// source = ctx.lookup("java:comp/env/"+ lookup);
// }
// else
// {
// source = lookup;
// }
if ( source != null)
{
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
try
{
try
{
Thread.currentThread().setContextClassLoader(source.getClass().getClassLoader());
}
catch (Exception ex)
{
}
try
{
DataSource ds = (DataSource) source;
connection = ds.getConnection();
}
catch (ClassCastException ex)
{
String text = "Datasource object " + source.getClass() + " does not implement a datasource interface.";
getLogger().error( text);
throw new RaplaDBException(text);
}
}
finally
{
try
{
Thread.currentThread().setContextClassLoader(contextClassLoader);
}
catch (Exception ex)
{
}
}
}
// or driver initialization
else
{
connection = dbDriver.connect(dbURL, dbProperties);
connectionName = dbURL;
if (connection == null)
{
throw new RaplaDBException("No driver found for: " + dbURL + "\nCheck url!");
}
}
if ( withTransactionSupport)
{
bSupportsTransactions = connection.getMetaData().supportsTransactions();
if (bSupportsTransactions)
{
connection.setAutoCommit( false );
}
else
{
getLogger().warn("No Transaction support");
}
}
else
{
connection.setAutoCommit( true );
}
//connection.createStatement().execute( "ALTER TABLE RESOURCE RENAME TO RAPLA_RESOURCE");
// connection.commit();
return connection;
} catch (Throwable ex) {
if ( connection != null)
{
close(connection);
}
if ( ex instanceof RaplaDBException)
{
throw (RaplaDBException) ex;
}
throw new RaplaDBException("DB-Connection aborted",ex);
}
}
synchronized public User connect(ConnectInfo connectInfo) throws RaplaException {
if (isConnected())
{
return null;
}
getLogger().debug("Connecting: " + getConnectionName());
loadData();
initIndizes();
isConnected = true;
getLogger().debug("Connected");
return null;
}
public boolean isConnected() {
return isConnected;
}
final public void refresh() throws RaplaException {
getLogger().warn("Incremental refreshs are not supported");
}
synchronized public void disconnect() throws RaplaException
{
if (!isConnected())
return;
backupData();
getLogger().info("Disconnecting: " + getConnectionName());
cache.clearAll();
//idTable.setCache( cache );
// HSQLDB Special
if ( hsqldb )
{
String sql ="SHUTDOWN COMPACT";
try
{
Connection connection = createConnection();
Statement statement = connection.createStatement();
statement.execute(sql);
statement.close();
}
catch (SQLException ex)
{
throw new RaplaException( ex);
}
}
isConnected = false;
fireStorageDisconnected("");
getLogger().info("Disconnected");
}
public final void loadData() throws RaplaException {
Connection c = null;
Lock writeLock = writeLock();
try {
c = createConnection();
connectionName = c.getMetaData().getURL();
getLogger().info("Using datasource " + c.getMetaData().getDatabaseProductName() +": " + connectionName);
if (upgradeDatabase(c))
{
close( c);
c = null;
c = createConnection();
}
cache.clearAll();
addInternalTypes(cache);
loadData( c, cache );
if ( getLogger().isDebugEnabled())
getLogger().debug("Entities contextualized");
if ( getLogger().isDebugEnabled())
getLogger().debug("All ConfigurationReferences resolved");
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException( ex);
}
finally
{
unlock(writeLock);
close ( c );
c = null;
}
}
@SuppressWarnings("deprecation")
private boolean upgradeDatabase(Connection c) throws SQLException, RaplaException, RaplaContextException {
Map<String, TableDef> schema = loadDBSchema(c);
TableDef dynamicTypeDef = schema.get("DYNAMIC_TYPE");
boolean empty = false;
int oldIdColumnCount = 0;
int unpatchedTables = 0;
if ( dynamicTypeDef != null)
{
PreparedStatement prepareStatement = null;
ResultSet set = null;
try
{
prepareStatement = c.prepareStatement("select * from DYNAMIC_TYPE");
set = prepareStatement.executeQuery();
empty = !set.next();
}
finally
{
if ( set != null)
{
set.close();
}
if ( prepareStatement != null)
{
prepareStatement.close();
}
}
{
org.rapla.storage.dbsql.pre18.RaplaPre18SQL raplaSQLOutput = new org.rapla.storage.dbsql.pre18.RaplaPre18SQL(createOutputContext(cache));
Map<String,String> idColumnMap = raplaSQLOutput.getIdColumns();
oldIdColumnCount = idColumnMap.size();
for ( Map.Entry<String, String> entry:idColumnMap.entrySet())
{
String table = entry.getKey();
String idColumnName = entry.getValue();
TableDef tableDef = schema.get(table);
if ( tableDef != null)
{
ColumnDef idColumn = tableDef.getColumn(idColumnName);
if ( idColumn == null)
{
throw new RaplaException("Id column not found");
}
if ( idColumn.isIntType())
{
unpatchedTables++;
// else if ( type.toLowerCase().contains("varchar"))
// {
// patchedTables++;
// }
}
}
}
}
}
else
{
empty = true;
}
if ( !empty && (unpatchedTables == oldIdColumnCount && unpatchedTables > 0))
{
getLogger().warn("Old database schema detected. Initializing conversion!");
org.rapla.storage.dbsql.pre18.RaplaPre18SQL raplaSQLOutput = new org.rapla.storage.dbsql.pre18.RaplaPre18SQL(createOutputContext(cache));
raplaSQLOutput.createOrUpdateIfNecessary( c, schema);
CachableStorageOperator sourceOperator = context.lookup(ImportExportManager.class).getSource();
if ( sourceOperator == this)
{
throw new RaplaException("Can't export old db data, because no data export is set.");
}
LocalCache cache =new LocalCache();
cache.clearAll();
addInternalTypes(cache);
loadOldData(c, cache );
getLogger().info("Old database loaded in memory. Now exporting to xml: " + sourceOperator);
sourceOperator.saveData(cache);
getLogger().info("XML export done.");
//close( c);
}
if ( empty || unpatchedTables > 0 )
{
CachableStorageOperator sourceOperator = context.lookup(ImportExportManager.class).getSource();
if ( sourceOperator == this)
{
throw new RaplaException("Can't import, because db is configured as source.");
}
if ( unpatchedTables > 0)
{
getLogger().info("Reading data from xml.");
}
else
{
getLogger().warn("Empty database. Importing data from " + sourceOperator);
}
sourceOperator.connect();
if ( unpatchedTables > 0)
{
org.rapla.storage.dbsql.pre18.RaplaPre18SQL raplaSQLOutput = new org.rapla.storage.dbsql.pre18.RaplaPre18SQL(createOutputContext(cache));
getLogger().warn("Dropping database tables and reimport from " + sourceOperator);
raplaSQLOutput.dropAll(c);
// we need to load the new schema after dropping
schema = loadDBSchema(c);
}
{
RaplaSQL raplaSQLOutput = new RaplaSQL(createOutputContext(cache));
raplaSQLOutput.createOrUpdateIfNecessary( c, schema);
}
close( c);
c = null;
c = createConnection();
final Connection conn = c;
sourceOperator.runWithReadLock( new CachableStorageOperatorCommand() {
@Override
public void execute(LocalCache cache) throws RaplaException {
try
{
saveData(conn, cache);
}
catch (SQLException ex)
{
throw new RaplaException(ex.getMessage(),ex);
}
}
});
return true;
}
return false;
}
private Map<String, TableDef> loadDBSchema(Connection c)
throws SQLException {
Map<String,TableDef> tableMap = new LinkedHashMap<String,TableDef>();
List<String> catalogList = new ArrayList<String>();
DatabaseMetaData metaData = c.getMetaData();
{
ResultSet set = metaData.getCatalogs();
try
{
while (set.next())
{
String name = set.getString("TABLE_CAT");
catalogList.add( name);
}
}
finally
{
set.close();
}
}
List<String> schemaList = new ArrayList<String>();
{
ResultSet set = metaData.getSchemas();
try
{
while (set.next())
{
String name = set.getString("TABLE_SCHEM");
String cat = set.getString("TABLE_CATALOG");
schemaList.add( name);
if ( cat != null)
{
catalogList.add( name);
}
}
}
finally
{
set.close();
}
}
if ( catalogList.isEmpty())
{
catalogList.add( null);
}
Map<String,Set<String>> tables = new LinkedHashMap<String, Set<String>>();
for ( String cat: catalogList)
{
LinkedHashSet<String> tableSet = new LinkedHashSet<String>();
String[] types = new String[] {"TABLE"};
tables.put( cat, tableSet);
{
ResultSet set = metaData.getTables(cat, null, null, types);
try
{
while (set.next())
{
String name = set.getString("TABLE_NAME");
tableSet.add( name);
}
}
finally
{
set.close();
}
}
}
for ( String cat: catalogList)
{
Set<String> tableNameSet = tables.get( cat);
for ( String tableName: tableNameSet )
{
ResultSet set = metaData.getColumns(null, null,tableName, null);
try
{
while (set.next())
{
String table = set.getString("TABLE_NAME").toUpperCase(Locale.ENGLISH);
TableDef tableDef = tableMap.get( table);
if ( tableDef == null )
{
tableDef = new TableDef(table);
tableMap.put( table,tableDef );
}
ColumnDef columnDef = new ColumnDef( set);
tableDef.addColumn( columnDef);
}
}
finally
{
set.close();
}
}
}
return tableMap;
}
public void dispatch(UpdateEvent evt) throws RaplaException {
UpdateResult result;
Lock writeLock = writeLock();
try
{
preprocessEventStorage(evt);
Connection connection = createConnection();
try {
executeEvent(connection,evt);
if (bSupportsTransactions) {
getLogger().debug("Commiting");
connection.commit();
}
} catch (Exception ex) {
try {
if (bSupportsTransactions) {
connection.rollback();
getLogger().error("Doing rollback for: " + ex.getMessage());
throw new RaplaDBException(getI18n().getString("error.rollback"),ex);
} else {
String message = getI18n().getString("error.no_rollback");
getLogger().error(message);
forceDisconnect();
throw new RaplaDBException(message,ex);
}
} catch (SQLException sqlEx) {
String message = "Unrecoverable error while storing";
getLogger().error(message, sqlEx);
forceDisconnect();
throw new RaplaDBException(message,sqlEx);
}
} finally {
close( connection );
}
result = super.update(evt);
}
finally
{
unlock( writeLock );
}
fireStorageUpdated(result);
}
/**
* @param evt
* @throws RaplaException
*/
protected void executeEvent(Connection connection,UpdateEvent evt) throws RaplaException, SQLException {
// execute updates
RaplaSQL raplaSQLOutput = new RaplaSQL(createOutputContext(cache));
Collection<Entity> storeObjects = evt.getStoreObjects();
raplaSQLOutput.store( connection, storeObjects);
raplaSQLOutput.storePatches( connection, evt.getPreferencePatches());
Collection<Entity> removeObjects = evt.getRemoveObjects();
for (Entity entityStore: removeObjects) {
Comparable id = entityStore.getId();
Entity entity = cache.get(id);
if (entity != null)
raplaSQLOutput.remove( connection, entity);
}
}
public void removeAll() throws RaplaException {
Connection connection = createConnection();
try {
RaplaSQL raplaSQLOutput = new RaplaSQL(createOutputContext(cache));
raplaSQLOutput.removeAll( connection );
connection.commit();
// do something here
getLogger().info("DB cleared");
}
catch (SQLException ex)
{
throw new RaplaException(ex);
}
finally
{
close( connection );
}
}
public synchronized void saveData(LocalCache cache) throws RaplaException {
Connection connection = createConnection();
try {
Map<String, TableDef> schema = loadDBSchema(connection);
RaplaSQL raplaSQLOutput = new RaplaSQL(createOutputContext(cache));
raplaSQLOutput.createOrUpdateIfNecessary( connection, schema);
saveData(connection, cache);
}
catch (SQLException ex)
{
throw new RaplaException(ex);
}
finally
{
close( connection );
}
}
protected void saveData(Connection connection, LocalCache cache) throws RaplaException, SQLException {
String connectionName = getConnectionName();
getLogger().info("Importing Data into " + connectionName);
RaplaSQL raplaSQLOutput = new RaplaSQL(createOutputContext(cache));
// if (dropOldTables)
// {
// getLogger().info("Droping all data from " + connectionName);
// raplaSQLOutput.dropAndRecreate( connection );
// }
// else
{
getLogger().info("Deleting all old Data from " + connectionName);
raplaSQLOutput.removeAll( connection );
}
getLogger().info("Inserting new Data into " + connectionName);
raplaSQLOutput.createAll( connection );
if ( !connection.getAutoCommit())
{
connection.commit();
}
// do something here
getLogger().info("Import complete for " + connectionName);
}
private void close(Connection connection)
{
if ( connection == null)
{
return;
}
try
{
getLogger().debug("Closing " + connection);
connection.close();
}
catch (SQLException e)
{
getLogger().error( "Can't close connection to database ", e);
}
}
protected void loadData(Connection connection, LocalCache cache) throws RaplaException, SQLException {
EntityStore entityStore = new EntityStore(cache, cache.getSuperCategory());
RaplaSQL raplaSQLInput = new RaplaSQL(createInputContext(entityStore, this));
raplaSQLInput.loadAll( connection );
Collection<Entity> list = entityStore.getList();
cache.putAll( list);
resolveInitial( list, this);
cache.getSuperCategory().setReadOnly();
for (User user:cache.getUsers())
{
String id = user.getId();
String password = entityStore.getPassword( id);
cache.putPassword(id, password);
}
}
@SuppressWarnings("deprecation")
protected void loadOldData(Connection connection, LocalCache cache) throws RaplaException, SQLException {
EntityStore entityStore = new EntityStore(cache, cache.getSuperCategory());
IdCreator idCreator = new IdCreator() {
@Override
public String createId(RaplaType type, String seed) throws RaplaException {
String id = org.rapla.storage.OldIdMapping.getId(type, seed);
return id;
}
@Override
public String createId(RaplaType raplaType) throws RaplaException {
throw new RaplaException("Can't create new ids in " + getClass().getName() + " this class is import only for old data ");
}
};
RaplaDefaultContext inputContext = createInputContext(entityStore, idCreator);
org.rapla.storage.dbsql.pre18.RaplaPre18SQL raplaSQLInput = new org.rapla.storage.dbsql.pre18.RaplaPre18SQL(inputContext);
raplaSQLInput.loadAll( connection );
Collection<Entity> list = entityStore.getList();
cache.putAll( list);
resolveInitial( list, cache);
cache.getSuperCategory().setReadOnly();
for (User user:cache.getUsers())
{
String id = user.getId();
String password = entityStore.getPassword( id);
cache.putPassword(id, password);
}
}
private RaplaDefaultContext createInputContext( EntityStore store, IdCreator idCreator) throws RaplaException {
RaplaDefaultContext inputContext = new IOContext().createInputContext(context, store, idCreator);
RaplaNonValidatedInput xmlAdapter = context.lookup(RaplaNonValidatedInput.class);
inputContext.put(RaplaNonValidatedInput.class,xmlAdapter);
return inputContext;
}
private RaplaDefaultContext createOutputContext(LocalCache cache) throws RaplaException {
RaplaDefaultContext outputContext = new IOContext().createOutputContext(context, cache.getSuperCategoryProvider(),true);
outputContext.put( LocalCache.class, cache);
return outputContext;
}
//implement backup at disconnect
final public void backupData() throws RaplaException {
try {
if (backupFileName.length()==0)
return;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
writeData(buffer);
byte[] data = buffer.toByteArray();
buffer.close();
OutputStream out = new FileOutputStream(backupFileName);
out.write(data);
out.close();
getLogger().info("Backup data to: " + backupFileName);
} catch (IOException e) {
getLogger().error("Backup error: " + e.getMessage());
throw new RaplaException(e.getMessage());
}
}
private void writeData( OutputStream out ) throws IOException, RaplaException
{
RaplaContext outputContext = new IOContext().createOutputContext( context,cache.getSuperCategoryProvider(), true );
RaplaMainWriter writer = new RaplaMainWriter( outputContext, cache );
writer.setEncoding(backupEncoding);
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out,backupEncoding));
writer.setWriter(w);
writer.printContent();
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbsql;
import org.rapla.framework.RaplaException;
public class RaplaDBException extends RaplaException {
private static final long serialVersionUID = 1L;
public RaplaDBException(String text) {
super(text);
}
public RaplaDBException(Throwable throwable) {
super(throwable);
}
public RaplaDBException(String text,Throwable ex) {
super(text,ex);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, of which license fullfill the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbsql;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.rapla.components.util.Assert;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.xml.RaplaNonValidatedInput;
import org.rapla.entities.Annotatable;
import org.rapla.entities.Category;
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.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.Repeating;
import org.rapla.entities.domain.RepeatingType;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.domain.internal.AppointmentImpl;
import org.rapla.entities.domain.internal.PermissionImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.Classifiable;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.entities.dynamictype.internal.ClassificationImpl;
import org.rapla.entities.dynamictype.internal.DynamicTypeImpl;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.entities.internal.UserImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.PreferencePatch;
import org.rapla.storage.xml.CategoryReader;
import org.rapla.storage.xml.PreferenceReader;
import org.rapla.storage.xml.RaplaXMLReader;
import org.rapla.storage.xml.RaplaXMLWriter;
class RaplaSQL {
private final List<RaplaTypeStorage> stores = new ArrayList<RaplaTypeStorage>();
private final Logger logger;
RaplaContext context;
PreferenceStorage preferencesStorage;
RaplaSQL( RaplaContext context) throws RaplaException{
this.context = context;
logger = context.lookup( Logger.class);
// The order is important. e.g. appointments can only be loaded if the reservation they are refering to are already loaded.
stores.add(new CategoryStorage( context));
stores.add(new DynamicTypeStorage( context));
stores.add(new UserStorage( context));
stores.add(new AllocatableStorage( context));
preferencesStorage = new PreferenceStorage( context);
stores.add(preferencesStorage);
ReservationStorage reservationStorage = new ReservationStorage( context);
stores.add(reservationStorage);
AppointmentStorage appointmentStorage = new AppointmentStorage( context);
stores.add(appointmentStorage);
// now set delegate because reservation storage should also use appointment storage
reservationStorage.setAppointmentStorage( appointmentStorage);
}
private List<Storage<?>> getStoresWithChildren()
{
List<Storage<?>> storages = new ArrayList<Storage<?>>();
for ( RaplaTypeStorage store:stores)
{
storages.add( store);
@SuppressWarnings("unchecked")
Collection<Storage<?>> subStores = store.getSubStores();
storages.addAll( subStores);
}
return storages;
}
protected Logger getLogger() {
return logger;
}
/***************************************************
* Create everything *
***************************************************/
synchronized public void createAll(Connection con)
throws SQLException,RaplaException
{
for (RaplaTypeStorage storage: stores) {
storage.setConnection(con);
try
{
storage.insertAll();
}
finally
{
storage.setConnection( null);
}
}
}
synchronized public void removeAll(Connection con)
throws SQLException
{
for (RaplaTypeStorage storage: stores) {
storage.setConnection(con);
try
{
storage.deleteAll();
}
finally
{
storage.setConnection( null);
}
}
}
synchronized public void loadAll(Connection con) throws SQLException,RaplaException {
for (Storage storage:stores)
{
storage.setConnection(con);
try
{
storage.loadAll();
}
finally
{
storage.setConnection( null);
}
}
}
@SuppressWarnings("unchecked")
synchronized public void remove(Connection con,Entity entity) throws SQLException,RaplaException {
if ( Attribute.TYPE == entity.getRaplaType() )
return;
for (RaplaTypeStorage storage:stores) {
if (storage.canStore(entity)) {
storage.setConnection(con);
try
{
List<Entity>list = new ArrayList<Entity>();
list.add( entity);
storage.deleteEntities(list);
}
finally
{
storage.setConnection(null);
}
return;
}
}
throw new RaplaException("No Storage-Sublass matches this object: " + entity.getClass());
}
@SuppressWarnings("unchecked")
synchronized public void store(Connection con, Collection<Entity>entities) throws SQLException,RaplaException {
Map<Storage,List<Entity>> store = new LinkedHashMap<Storage, List<Entity>>();
for ( Entity entity:entities)
{
if ( Attribute.TYPE == entity.getRaplaType() )
continue;
boolean found = false;
for ( RaplaTypeStorage storage: stores)
{
if (storage.canStore(entity)) {
List<Entity>list = store.get( storage);
if ( list == null)
{
list = new ArrayList<Entity>();
store.put( storage, list);
}
list.add( entity);
found = true;
}
}
if (!found)
{
throw new RaplaException("No Storage-Sublass matches this object: " + entity.getClass());
}
}
for ( Storage storage: store.keySet())
{
storage.setConnection(con);
try
{
List<Entity>list = store.get( storage);
storage.save(list);
}
finally
{
storage.setConnection( null);
}
}
}
public void createOrUpdateIfNecessary(Connection con, Map<String, TableDef> schema) throws SQLException, RaplaException {
// Upgrade db if necessary
for (Storage<?> storage:getStoresWithChildren())
{
storage.setConnection(con);
try
{
storage.createOrUpdateIfNecessary( schema);
}
finally
{
storage.setConnection( null);
}
}
}
public void storePatches(Connection connection, List<PreferencePatch> preferencePatches) throws SQLException, RaplaException {
PreferenceStorage storage = preferencesStorage;
storage.setConnection( connection);
try
{
preferencesStorage.storePatches( preferencePatches);
}
finally
{
storage.setConnection( null);
}
}
}
abstract class RaplaTypeStorage<T extends Entity<T>> extends EntityStorage<T> {
RaplaType raplaType;
RaplaTypeStorage( RaplaContext context, RaplaType raplaType, String tableName, String[] entries) throws RaplaException {
super( context,tableName, entries );
this.raplaType = raplaType;
}
boolean canStore(Entity entity) {
return entity.getRaplaType() == raplaType;
}
abstract void insertAll() throws SQLException,RaplaException;
protected String getXML(RaplaObject type) throws RaplaException {
RaplaXMLWriter dynamicTypeWriter = getWriterFor( type.getRaplaType());
StringWriter stringWriter = new StringWriter();
BufferedWriter bufferedWriter = new BufferedWriter(stringWriter);
dynamicTypeWriter.setWriter( bufferedWriter );
dynamicTypeWriter.setSQL( true );
try {
dynamicTypeWriter.writeObject(type);
bufferedWriter.flush();
} catch (IOException ex) {
throw new RaplaException( ex);
}
return stringWriter.getBuffer().toString();
}
protected RaplaXMLReader processXML(RaplaType type, String xml) throws RaplaException {
RaplaXMLReader reader = getReaderFor( type);
if ( xml== null || xml.trim().length() <= 10) {
throw new RaplaException("Can't load " + type);
}
String xmlWithNamespaces = RaplaXMLReader.wrapRaplaDataTag(xml);
RaplaNonValidatedInput parser = getReader();
parser.read(xmlWithNamespaces, reader, logger);
return reader;
}
}
class CategoryStorage extends RaplaTypeStorage<Category> {
Map<Category,Integer> orderMap = new HashMap<Category,Integer>();
Map<Category,String> categoriesWithoutParent = new TreeMap<Category,String>(new Comparator<Category>()
{
public int compare( Category o1, Category o2 )
{
if ( o1.equals( o2))
{
return 0;
}
int ordering1 = ( orderMap.get( o1 )).intValue();
int ordering2 = (orderMap.get( o2 )).intValue();
if ( ordering1 < ordering2)
{
return -1;
}
if ( ordering1 > ordering2)
{
return 1;
}
if (o1.hashCode() > o2.hashCode())
{
return -1;
}
else
{
return 1;
}
}
}
);
public CategoryStorage(RaplaContext context) throws RaplaException {
super(context,Category.TYPE, "CATEGORY",new String[] {"ID VARCHAR(255) NOT NULL PRIMARY KEY","PARENT_ID VARCHAR(255) KEY","CATEGORY_KEY VARCHAR(255) NOT NULL","DEFINITION TEXT NOT NULL","PARENT_ORDER INTEGER"});
}
@Override
public void deleteEntities(Iterable<Category> entities) throws SQLException,RaplaException {
Set<String> idList = new HashSet<String>();
for ( Category cat:entities)
{
idList.addAll( getIds( cat.getId()));
}
deleteIds(idList);
}
@Override
public void insert(Iterable<Category> entities) throws SQLException, RaplaException {
Set<Category> transitiveCategories = new LinkedHashSet<Category>();
for ( Category cat: entities)
{
transitiveCategories.add( cat);
transitiveCategories.addAll(getAllChilds( cat ));
}
super.insert(transitiveCategories);
}
private Collection<Category> getAllChilds(Category cat) {
Set<Category> allChilds = new LinkedHashSet<Category>();
allChilds.add( cat);
for ( Category child: cat.getCategories())
{
allChilds.addAll(getAllChilds( child ));
}
return allChilds;
}
private Collection<String> getIds(String parentId) throws SQLException, RaplaException {
Set<String> childIds = new HashSet<String>();
String sql = "SELECT ID FROM CATEGORY WHERE PARENT_ID=?";
PreparedStatement stmt = null;
ResultSet rset = null;
try {
stmt = con.prepareStatement(sql);
setString(stmt,1, parentId);
rset = stmt.executeQuery();
while (rset.next ()) {
String id = readId(rset, 1, Category.class);
childIds.add( id);
}
} finally {
if (rset != null)
rset.close();
if (stmt!=null)
stmt.close();
}
Set<String> result = new HashSet<String>();
for (String childId : childIds)
{
result.addAll( getIds( childId));
}
result.add( parentId);
return result;
}
@Override
protected int write(PreparedStatement stmt,Category category) throws SQLException, RaplaException {
Category root = getSuperCategory();
if ( category.equals( root ))
return 0;
setId( stmt,1, category);
setId( stmt,2, category.getParent());
int order = getOrder( category);
String xml = getXML( category );
setString(stmt,3, category.getKey());
setText(stmt,4, xml);
setInt( stmt,5, order);
stmt.addBatch();
return 1;
}
private int getOrder( Category category )
{
Category parent = category.getParent();
if ( parent == null)
{
return 0;
}
Category[] childs = parent.getCategories();
for ( int i=0;i<childs.length;i++)
{
if ( childs[i].equals( category))
{
return i;
}
}
getLogger().error("Category not found in parent");
return 0;
}
public RaplaXMLReader getReaderFor( RaplaType type) throws RaplaException {
RaplaXMLReader reader = super.getReaderFor( type );
if ( type.equals( Category.TYPE ) ) {
((CategoryReader) reader).setReadOnlyThisCategory( true);
}
return reader;
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
String id = readId(rset, 1, Category.class);
String parentId = readId(rset, 2, Category.class, true);
String xml = getText( rset, 4 );
Integer order = getInt(rset, 5 );
CategoryImpl category;
if ( xml != null && xml.length() > 10 )
{
category = ((CategoryReader)processXML( Category.TYPE, xml )).getCurrentCategory();
//cache.remove( category );
}
else
{
getLogger().warn("Category has empty xml field. Ignoring.");
return;
}
category.setId( id);
put( category );
orderMap.put( category, order);
// parentId can also be null
categoriesWithoutParent.put( category, parentId);
}
@Override
public void loadAll() throws RaplaException, SQLException {
categoriesWithoutParent.clear();
super.loadAll();
// then we rebuild the hierarchy
Iterator<Map.Entry<Category,String>> it = categoriesWithoutParent.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Category,String> entry = it.next();
String parentId = entry.getValue();
Category category = entry.getKey();
Category parent;
Assert.notNull( category );
if ( parentId != null) {
parent = entityStore.resolve( parentId ,Category.class);
} else {
parent = getSuperCategory();
}
Assert.notNull( parent );
parent.addCategory( category );
}
}
@Override
void insertAll() throws SQLException, RaplaException {
CategoryImpl superCategory = cache.getSuperCategory();
Set<Category> childs = new HashSet<Category>();
addChildren(childs, superCategory);
insert( childs);
}
private void addChildren(Collection<Category> list, Category category) {
for (Category child:category.getCategories())
{
list.add( child );
addChildren(list, child);
}
}
}
class AllocatableStorage extends RaplaTypeStorage<Allocatable> {
Map<String,Classification> classificationMap = new HashMap<String,Classification>();
Map<String,Allocatable> allocatableMap = new HashMap<String,Allocatable>();
AttributeValueStorage<Allocatable> resourceAttributeStorage;
PermissionStorage permissionStorage;
public AllocatableStorage(RaplaContext context ) throws RaplaException {
super(context,Allocatable.TYPE,"RAPLA_RESOURCE",new String [] {"ID VARCHAR(255) NOT NULL PRIMARY KEY","TYPE_KEY VARCHAR(255) NOT NULL","OWNER_ID VARCHAR(255)","CREATION_TIME TIMESTAMP","LAST_CHANGED TIMESTAMP","LAST_CHANGED_BY VARCHAR(255) DEFAULT NULL"});
resourceAttributeStorage = new AttributeValueStorage<Allocatable>(context,"RESOURCE_ATTRIBUTE_VALUE", "RESOURCE_ID",classificationMap, allocatableMap);
permissionStorage = new PermissionStorage( context, allocatableMap);
addSubStorage(resourceAttributeStorage);
addSubStorage(permissionStorage );
}
@Override
void insertAll() throws SQLException, RaplaException {
insert( cache.getAllocatables());
}
@Override
protected int write(PreparedStatement stmt,Allocatable entity) throws SQLException,RaplaException {
AllocatableImpl allocatable = (AllocatableImpl) entity;
String typeKey = allocatable.getClassification().getType().getKey();
setId(stmt, 1, entity);
setString(stmt,2, typeKey );
org.rapla.entities.Timestamp timestamp = allocatable;
setId(stmt,3, allocatable.getOwner() );
setTimestamp(stmt, 4,timestamp.getCreateTime() );
setTimestamp(stmt, 5,timestamp.getLastChanged() );
setId( stmt,6,timestamp.getLastChangedBy() );
stmt.addBatch();
return 1;
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
String id= readId(rset,1, Allocatable.class);
String typeKey = getString(rset,2 , null);
final Date createDate = getTimestampOrNow( rset, 4);
final Date lastChanged = getTimestampOrNow( rset, 5);
AllocatableImpl allocatable = new AllocatableImpl(createDate, lastChanged);
allocatable.setLastChangedBy( resolveFromId(rset, 6, User.class) );
allocatable.setId( id);
allocatable.setResolver( entityStore);
DynamicType type = null;
if ( typeKey != null)
{
type = getDynamicType(typeKey );
}
if ( type == null)
{
getLogger().error("Allocatable with id " + id + " has an unknown type " + typeKey + ". Try ignoring it");
return;
}
allocatable.setOwner( resolveFromId(rset, 3, User.class) );
Classification classification = type.newClassification(false);
allocatable.setClassification( classification );
classificationMap.put( id, classification );
allocatableMap.put( id, allocatable);
put( allocatable );
}
@Override
public void loadAll() throws RaplaException, SQLException {
classificationMap.clear();
super.loadAll();
}
}
class ReservationStorage extends RaplaTypeStorage<Reservation> {
Map<String,Classification> classificationMap = new HashMap<String,Classification>();
Map<String,Reservation> reservationMap = new HashMap<String,Reservation>();
AttributeValueStorage<Reservation> attributeValueStorage;
// appointmentstorage is not a sub store but a delegate
AppointmentStorage appointmentStorage;
public ReservationStorage(RaplaContext context) throws RaplaException {
super(context,Reservation.TYPE, "EVENT",new String [] {"ID VARCHAR(255) NOT NULL PRIMARY KEY","TYPE_KEY VARCHAR(255) NOT NULL","OWNER_ID VARCHAR(255) NOT NULL","CREATION_TIME TIMESTAMP","LAST_CHANGED TIMESTAMP","LAST_CHANGED_BY VARCHAR(255) DEFAULT NULL"});
attributeValueStorage = new AttributeValueStorage<Reservation>(context,"EVENT_ATTRIBUTE_VALUE","EVENT_ID", classificationMap, reservationMap);
addSubStorage(attributeValueStorage);
}
public void setAppointmentStorage(AppointmentStorage appointmentStorage)
{
this.appointmentStorage = appointmentStorage;
}
@Override
void insertAll() throws SQLException, RaplaException {
insert( cache.getReservations());
}
@Override
public void save(Iterable<Reservation> entities) throws RaplaException, SQLException {
super.save(entities);
Collection<Appointment> appointments = new ArrayList<Appointment>();
for (Reservation r: entities)
{
appointments.addAll( Arrays.asList(r.getAppointments()));
}
appointmentStorage.insert( appointments );
}
@Override
public void setConnection(Connection con) throws SQLException {
super.setConnection(con);
appointmentStorage.setConnection(con);
}
@Override
protected int write(PreparedStatement stmt,Reservation event) throws SQLException,RaplaException {
String typeKey = event.getClassification().getType().getKey();
setId(stmt,1, event );
setString(stmt,2, typeKey );
setId(stmt,3, event.getOwner() );
org.rapla.entities.Timestamp timestamp = event;
setTimestamp( stmt,4,timestamp.getCreateTime());
setTimestamp( stmt,5,timestamp.getLastChanged());
setId(stmt, 6, timestamp.getLastChangedBy());
stmt.addBatch();
return 1;
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
final Date createDate = getTimestampOrNow(rset,4);
final Date lastChanged = getTimestampOrNow(rset,5);
ReservationImpl event = new ReservationImpl(createDate, lastChanged);
String id = readId(rset,1,Reservation.class);
event.setId( id);
event.setResolver( entityStore);
String typeKey = getString(rset,2,null);
DynamicType type = null;
if ( typeKey != null)
{
type = getDynamicType(typeKey );
}
if ( type == null)
{
getLogger().error("Reservation with id " + id + " has an unknown type " + typeKey + ". Try ignoring it");
return;
}
User user = resolveFromId(rset, 3, User.class);
if ( user == null )
{
return;
}
event.setOwner( user );
event.setLastChangedBy( resolveFromId(rset, 6, User.class) );
Classification classification = type.newClassification(false);
event.setClassification( classification );
classificationMap.put( id, classification );
reservationMap.put( id, event );
put( event );
}
@Override
public void loadAll() throws RaplaException, SQLException {
classificationMap.clear();
super.loadAll();
}
@Override
public void deleteEntities(Iterable<Reservation> entities)
throws SQLException, RaplaException {
super.deleteEntities(entities);
deleteAppointments(entities);
}
private void deleteAppointments(Iterable<Reservation> entities)
throws SQLException, RaplaException {
Set<String> ids = new HashSet<String>();
String sql = "SELECT ID FROM APPOINTMENT WHERE EVENT_ID=?";
for (Reservation entity:entities)
{
PreparedStatement stmt = null;
ResultSet rset = null;
try {
stmt = con.prepareStatement(sql);
String eventId = entity.getId();
setString(stmt,1, eventId);
rset = stmt.executeQuery();
while (rset.next ()) {
String appointmentId = readId(rset, 1, Appointment.class);
ids.add( appointmentId);
}
} finally {
if (rset != null)
rset.close();
if (stmt!=null)
stmt.close();
}
}
// and delete them
appointmentStorage.deleteIds( ids);
}
}
class AttributeValueStorage<T extends Entity<T>> extends EntityStorage<T> {
Map<String,Classification> classificationMap;
Map<String,? extends Annotatable> annotableMap;
final String foreignKeyName;
// TODO Write conversion script to update all old entries to new entries
public final static String OLD_ANNOTATION_PREFIX = "annotation:";
public final static String ANNOTATION_PREFIX = "rapla:";
public AttributeValueStorage(RaplaContext context,String tablename, String foreignKeyName, Map<String,Classification> classificationMap, Map<String, ? extends Annotatable> annotableMap) throws RaplaException {
super(context, tablename, new String[]{foreignKeyName + " VARCHAR(255) NOT NULL KEY","ATTRIBUTE_KEY VARCHAR(255)","ATTRIBUTE_VALUE VARCHAR(20000)"});
this.foreignKeyName = foreignKeyName;
this.classificationMap = classificationMap;
this.annotableMap = annotableMap;
}
@Override
protected int write(PreparedStatement stmt,T classifiable) throws EntityNotFoundException, SQLException {
Classification classification = ((Classifiable)classifiable).getClassification();
Attribute[] attributes = classification.getAttributes();
int count =0;
for (int i=0;i<attributes.length;i++) {
Attribute attribute = attributes[i];
Collection<Object> values = classification.getValues( attribute );
for (Object value: values)
{
String valueAsString;
if ( value instanceof Category || value instanceof Allocatable)
{
Entity casted = (Entity) value;
valueAsString = casted.getId();
}
else
{
valueAsString = AttributeImpl.attributeValueToString( attribute, value, true);
}
setId(stmt,1, classifiable);
setString(stmt,2, attribute.getKey());
setString(stmt,3, valueAsString);
stmt.addBatch();
count++;
}
}
Annotatable annotatable = (Annotatable)classifiable;
for ( String key: annotatable.getAnnotationKeys())
{
String valueAsString = annotatable.getAnnotation( key);
setId(stmt,1, classifiable);
setString(stmt,2, ANNOTATION_PREFIX + key);
setString(stmt,3, valueAsString);
stmt.addBatch();
count++;
}
return count;
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
Class<? extends Entity> idClass = foreignKeyName.indexOf("RESOURCE")>=0 ? Allocatable.class : Reservation.class;
String classifiableId = readId(rset, 1, idClass);
String attributekey = rset.getString( 2 );
boolean annotationPrefix = attributekey.startsWith(ANNOTATION_PREFIX);
boolean oldAnnotationPrefix = attributekey.startsWith(OLD_ANNOTATION_PREFIX);
if ( annotationPrefix || oldAnnotationPrefix)
{
String annotationKey = attributekey.substring( annotationPrefix ? ANNOTATION_PREFIX.length() : OLD_ANNOTATION_PREFIX.length());
Annotatable annotatable = annotableMap.get(classifiableId);
if (annotatable != null)
{
String valueAsString = rset.getString( 3);
if ( rset.wasNull() || valueAsString == null)
{
annotatable.setAnnotation(annotationKey, null);
}
else
{
annotatable.setAnnotation(annotationKey, valueAsString);
}
}
else
{
getLogger().warn("No resource or reservation found for the id " + classifiableId + " ignoring.");
}
}
else
{
ClassificationImpl classification = (ClassificationImpl) classificationMap.get(classifiableId);
if ( classification == null) {
getLogger().warn("No resource or reservation found for the id " + classifiableId + " ignoring.");
return;
}
Attribute attribute = classification.getType().getAttribute( attributekey );
if ( attribute == null) {
getLogger().error("DynamicType '" +classification.getType() +"' doesnt have an attribute with the key " + attributekey + " Current allocatable/reservation Id " + classifiableId + ". Ignoring attribute.");
return;
}
String valueAsString = rset.getString( 3);
if ( valueAsString != null )
{
Object value = AttributeImpl.parseAttributeValue(attribute, valueAsString);
classification.addValue( attribute, value);
}
}
}
}
class PermissionStorage extends EntityStorage<Allocatable> {
Map<String,Allocatable> allocatableMap;
public PermissionStorage(RaplaContext context,Map<String,Allocatable> allocatableMap) throws RaplaException {
super(context,"PERMISSION",new String[] {"RESOURCE_ID VARCHAR(255) NOT NULL KEY","USER_ID VARCHAR(255)","GROUP_ID VARCHAR(255)","ACCESS_LEVEL INTEGER NOT NULL","MIN_ADVANCE INTEGER","MAX_ADVANCE INTEGER","START_DATE DATETIME","END_DATE DATETIME"});
this.allocatableMap = allocatableMap;
}
protected int write(PreparedStatement stmt, Allocatable allocatable) throws SQLException, RaplaException {
int count = 0;
for (Permission s:allocatable.getPermissions()) {
setId(stmt,1,allocatable);
setId(stmt,2,s.getUser());
setId(stmt,3,s.getGroup());
setInt(stmt,4, s.getAccessLevel());
setInt( stmt,5, s.getMinAdvance());
setInt( stmt,6, s.getMaxAdvance());
setDate(stmt,7, s.getStart());
setDate(stmt,8, s.getEnd());
stmt.addBatch();
count ++;
}
return count;
}
protected void load(ResultSet rset) throws SQLException, RaplaException {
String allocatableIdInt = readId(rset, 1, Allocatable.class);
Allocatable allocatable = allocatableMap.get(allocatableIdInt);
if ( allocatable == null)
{
getLogger().warn("Could not find resource object with id "+ allocatableIdInt + " for permission. Maybe the resource was deleted from the database.");
return;
}
PermissionImpl permission = new PermissionImpl();
permission.setUser( resolveFromId(rset, 2, User.class));
permission.setGroup( resolveFromId(rset, 3, Category.class));
Integer accessLevel = getInt( rset, 4);
// We multiply the access levels to add a more access levels between.
if ( accessLevel !=null)
{
if ( accessLevel < 5)
{
accessLevel *= 100;
}
permission.setAccessLevel( accessLevel );
}
permission.setMinAdvance( getInt(rset,5));
permission.setMaxAdvance( getInt(rset,6));
permission.setStart(getDate(rset, 7));
permission.setEnd(getDate(rset, 8));
// We need to add the permission at the end to ensure its unique. Permissions are stored in a set and duplicates are removed during the add method
allocatable.addPermission( permission );
}
}
class AppointmentStorage extends RaplaTypeStorage<Appointment> {
AppointmentExceptionStorage appointmentExceptionStorage;
AllocationStorage allocationStorage;
public AppointmentStorage(RaplaContext context) throws RaplaException {
super(context, Appointment.TYPE,"APPOINTMENT",new String [] {"ID VARCHAR(255) NOT NULL PRIMARY KEY","EVENT_ID VARCHAR(255) NOT NULL KEY","APPOINTMENT_START DATETIME NOT NULL","APPOINTMENT_END DATETIME NOT NULL","REPETITION_TYPE VARCHAR(255)","REPETITION_NUMBER INTEGER","REPETITION_END DATETIME","REPETITION_INTERVAL INTEGER"});
appointmentExceptionStorage = new AppointmentExceptionStorage(context);
allocationStorage = new AllocationStorage( context);
addSubStorage(appointmentExceptionStorage);
addSubStorage(allocationStorage);
}
@Override
void insertAll() throws SQLException, RaplaException {
Collection<Reservation> reservations = cache.getReservations();
Collection<Appointment> appointments = new LinkedHashSet<Appointment>();
for (Reservation r: reservations)
{
appointments.addAll( Arrays.asList(r.getAppointments()));
}
insert( appointments);
}
@Override
protected int write(PreparedStatement stmt,Appointment appointment) throws SQLException,RaplaException {
setId( stmt, 1, appointment);
setId( stmt, 2, appointment.getReservation());
setDate(stmt, 3, appointment.getStart());
setDate(stmt, 4, appointment.getEnd());
Repeating repeating = appointment.getRepeating();
if ( repeating == null) {
setString( stmt,5, null);
setInt( stmt,6, null);
setDate( stmt,7, null);
setInt( stmt,8, null);
} else {
setString( stmt,5, repeating.getType().toString());
int number = repeating.getNumber();
setInt(stmt, 6, number >= 0 ? number : null);
setDate(stmt, 7, repeating.getEnd());
setInt(stmt,8, repeating.getInterval());
}
stmt.addBatch();
return 1;
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
String id = readId(rset, 1, Appointment.class);
Reservation event = resolveFromId(rset, 2, Reservation.class);
if ( event == null)
{
return;
}
Date start = getDate(rset,3);
Date end = getDate(rset,4);
boolean wholeDayAppointment = start.getTime() == DateTools.cutDate( start.getTime()) && end.getTime() == DateTools.cutDate( end.getTime());
AppointmentImpl appointment = new AppointmentImpl(start, end);
appointment.setId( id);
appointment.setWholeDays( wholeDayAppointment);
event.addAppointment( appointment );
String repeatingType = getString( rset,5, null);
if ( repeatingType != null ) {
appointment.setRepeatingEnabled( true );
Repeating repeating = appointment.getRepeating();
repeating.setType( RepeatingType.findForString( repeatingType ) );
Date repeatingEnd = getDate(rset, 7);
if ( repeatingEnd != null ) {
repeating.setEnd( repeatingEnd);
} else {
Integer number = getInt( rset, 6);
if ( number != null) {
repeating.setNumber( number);
} else {
repeating.setEnd( null );
}
}
Integer interval = getInt( rset,8);
if ( interval != null)
repeating.setInterval( interval);
}
put( appointment );
}
}
class AllocationStorage extends EntityStorage<Appointment> {
public AllocationStorage(RaplaContext context) throws RaplaException
{
super(context,"ALLOCATION",new String [] {"APPOINTMENT_ID VARCHAR(255) NOT NULL KEY", "RESOURCE_ID VARCHAR(255) NOT NULL", "PARENT_ORDER INTEGER"});
}
@Override
protected int write(PreparedStatement stmt, Appointment appointment) throws SQLException, RaplaException {
Reservation event = appointment.getReservation();
int count = 0;
for (Allocatable allocatable: event.getAllocatablesFor(appointment)) {
setId(stmt,1, appointment);
setId(stmt,2, allocatable);
stmt.setObject(3, null);
stmt.addBatch();
count++;
}
return count;
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
Appointment appointment =resolveFromId(rset,1, Appointment.class);
if ( appointment == null)
{
return;
}
ReservationImpl event = (ReservationImpl) appointment.getReservation();
Allocatable allocatable = resolveFromId(rset, 2, Allocatable.class);
if ( allocatable == null)
{
return;
}
if ( !event.hasAllocated( allocatable ) ) {
event.addAllocatable( allocatable );
}
Appointment[] appointments = event.getRestriction( allocatable );
Appointment[] newAppointments = new Appointment[ appointments.length+ 1];
System.arraycopy(appointments,0, newAppointments, 0, appointments.length );
newAppointments[ appointments.length] = appointment;
if (event.getAppointmentList().size() > newAppointments.length ) {
event.setRestriction( allocatable, newAppointments );
} else {
event.setRestriction( allocatable, new Appointment[] {} );
}
}
}
class AppointmentExceptionStorage extends EntityStorage<Appointment> {
public AppointmentExceptionStorage(RaplaContext context) throws RaplaException {
super(context,"APPOINTMENT_EXCEPTION",new String [] {"APPOINTMENT_ID VARCHAR(255) NOT NULL KEY","EXCEPTION_DATE DATETIME NOT NULL"});
}
@Override
protected int write(PreparedStatement stmt, Appointment entity) throws SQLException, RaplaException {
Repeating repeating = entity.getRepeating();
int count = 0;
if ( repeating == null) {
return count;
}
for (Date exception: repeating.getExceptions()) {
setId( stmt, 1, entity );
setDate( stmt,2, exception);
stmt.addBatch();
count++;
}
return count;
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
Appointment appointment = resolveFromId( rset, 1, Appointment.class);
if ( appointment == null)
{
return;
}
Repeating repeating = appointment.getRepeating();
if ( repeating != null) {
Date date = getDate(rset,2 );
repeating.addException( date );
}
}
}
class DynamicTypeStorage extends RaplaTypeStorage<DynamicType> {
public DynamicTypeStorage(RaplaContext context) throws RaplaException {
super(context, DynamicType.TYPE,"DYNAMIC_TYPE", new String [] {"ID VARCHAR(255) NOT NULL PRIMARY KEY","TYPE_KEY VARCHAR(255) NOT NULL","DEFINITION TEXT NOT NULL"});//, "CREATION_TIME TIMESTAMP","LAST_CHANGED TIMESTAMP","LAST_CHANGED_BY INTEGER DEFAULT NULL"});
}
@Override
protected int write(PreparedStatement stmt, DynamicType type) throws SQLException, RaplaException {
if (((DynamicTypeImpl) type).isInternal())
{
return 0;
}
setId(stmt,1,type);
setString(stmt,2, type.getKey());
setText(stmt,3, getXML( type) );
// setDate(stmt, 4,timestamp.getCreateTime() );
// setDate(stmt, 5,timestamp.getLastChanged() );
// setId( stmt,6,timestamp.getLastChangedBy() );
stmt.addBatch();
return 1;
}
@Override
void insertAll() throws SQLException, RaplaException {
insert( cache.getDynamicTypes());
}
protected void load(ResultSet rset) throws SQLException,RaplaException {
String xml = getText(rset,3);
processXML( DynamicType.TYPE, xml );
// final Date createDate = getDate( rset, 4);
// final Date lastChanged = getDate( rset, 5);
//
// AllocatableImpl allocatable = new AllocatableImpl(createDate, lastChanged);
// allocatable.setLastChangedBy( resolveFromId(rset, 6, User.class) );
}
}
class PreferenceStorage extends RaplaTypeStorage<Preferences>
{
public PreferenceStorage(RaplaContext context) throws RaplaException {
super(context,Preferences.TYPE,"PREFERENCE",
new String [] {"USER_ID VARCHAR(255) KEY","ROLE VARCHAR(255) NOT NULL","STRING_VALUE VARCHAR(10000)","XML_VALUE TEXT"});
}
class PatchEntry
{
String userId;
String role;
}
public void storePatches(List<PreferencePatch> preferencePatches) throws RaplaException, SQLException
{
for ( PreferencePatch patch:preferencePatches)
{
String userId = patch.getUserId();
PreparedStatement stmt = null;
try {
String deleteSqlWithRole = deleteSql + " and role=?";
stmt = con.prepareStatement(deleteSqlWithRole);
for ( String role: patch.getRemovedEntries())
{
setId(stmt, 1, userId);
setString(stmt,2,role);
stmt.addBatch();
}
for ( String role: patch.keySet())
{
setId(stmt, 1, userId);
setString(stmt,2,role);
stmt.addBatch();
}
} finally {
if (stmt!=null)
stmt.close();
}
}
PreparedStatement stmt = null;
try {
stmt = con.prepareStatement(insertSql);
int count = 0;
for ( PreferencePatch patch:preferencePatches)
{
String userId = patch.getUserId();
for ( String role:patch.keySet())
{
Object entry = patch.get( role);
insterEntry(stmt, userId, role, entry);
count++;
}
}
if ( count > 0)
{
stmt.executeBatch();
}
} catch (SQLException ex) {
throw ex;
} finally {
if (stmt!=null)
stmt.close();
}
}
@Override
void insertAll() throws SQLException, RaplaException {
List<Preferences> preferences = new ArrayList<Preferences>();
{
PreferencesImpl systemPrefs = cache.getPreferencesForUserId(null);
if ( systemPrefs != null)
{
preferences.add( systemPrefs);
}
}
Collection<User> users = cache.getUsers();
for ( User user:users)
{
String userId = user.getId();
PreferencesImpl userPrefs = cache.getPreferencesForUserId(userId);
if ( userPrefs != null)
{
preferences.add( userPrefs);
}
}
insert( preferences);
}
@Override
protected int write(PreparedStatement stmt, Preferences entity) throws SQLException, RaplaException {
PreferencesImpl preferences = (PreferencesImpl) entity;
User user = preferences.getOwner();
String userId = user != null ? user.getId():null;
int count = 0;
for (String role:preferences.getPreferenceEntries()) {
Object entry = preferences.getEntry(role);
insterEntry(stmt, userId, role, entry);
count++;
}
return count;
}
private void insterEntry(PreparedStatement stmt, String userId, String role, Object entry) throws SQLException, RaplaException {
setString( stmt, 1, userId);
setString( stmt,2, role);
String xml;
String entryString;
if ( entry instanceof String) {
entryString = (String) entry;
xml = null;
} else {
//System.out.println("Role " + role + " CHILDREN " + conf.getChildren().length);
entryString = null;
xml = getXML( (RaplaObject)entry);
}
setString( stmt,3, entryString);
setText(stmt, 4, xml);
stmt.addBatch();
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
//findPreferences
//check if value set
// yes read value
// no read xml
String userId = readId(rset, 1,User.class, true);
User owner;
if ( userId == null || userId.equals(Preferences.SYSTEM_PREFERENCES_ID) )
{
owner = null;
}
else
{
User user = entityStore.tryResolve( userId,User.class);
if ( user != null)
{
owner = user;
}
else
{
getLogger().warn("User with id " + userId + " not found ingnoring preference entry.");
return;
}
}
String configRole = getString( rset, 2, null);
String preferenceId = PreferencesImpl.getPreferenceIdFromUser(userId);
if ( configRole == null)
{
getLogger().warn("Configuration role for " + preferenceId + " is null. Ignoring preference entry.");
return;
}
String value = getString( rset,3, null);
// if (PreferencesImpl.isServerEntry(configRole))
// {
// entityStore.putServerPreferences(owner,configRole, value);
// return;
// }
PreferencesImpl preferences = preferenceId != null ? (PreferencesImpl) entityStore.tryResolve( preferenceId, Preferences.class ): null;
if ( preferences == null)
{
Date now =getCurrentTimestamp();
preferences = new PreferencesImpl(now,now);
preferences.setId(preferenceId);
preferences.setOwner(owner);
put( preferences );
}
if ( value!= null) {
preferences.putEntryPrivate(configRole, value);
} else {
String xml = getText(rset, 4);
if ( xml != null && xml.length() > 0)
{
PreferenceReader contentHandler = (PreferenceReader) processXML( Preferences.TYPE, xml );
RaplaObject type = contentHandler.getChildType();
preferences.putEntryPrivate(configRole, type);
}
}
}
@Override
public void deleteEntities( Iterable<Preferences> entities) throws SQLException {
PreparedStatement stmt = null;
boolean deleteNullUserPreference = false;
try {
stmt = con.prepareStatement(deleteSql);
boolean empty = true;
for ( Preferences preferences: entities)
{
User user = preferences.getOwner();
if ( user == null) {
deleteNullUserPreference = true;
}
empty = false;
setId( stmt,1, user);
stmt.addBatch();
}
if ( !empty)
{
stmt.executeBatch();
}
} finally {
if (stmt!=null)
stmt.close();
}
if ( deleteNullUserPreference )
{
PreparedStatement deleteNullStmt = con.prepareStatement("DELETE FROM " + tableName + " WHERE USER_ID IS NULL OR USER_ID=0");
deleteNullStmt.execute();
}
}
}
class UserStorage extends RaplaTypeStorage<User> {
UserGroupStorage groupStorage;
public UserStorage(RaplaContext context) throws RaplaException {
super( context,User.TYPE, "RAPLA_USER",
new String [] {"ID VARCHAR(255) NOT NULL PRIMARY KEY","USERNAME VARCHAR(255) NOT NULL","PASSWORD VARCHAR(255)","NAME VARCHAR(255) NOT NULL","EMAIL VARCHAR(255) NOT NULL","ISADMIN INTEGER NOT NULL", "CREATION_TIME TIMESTAMP", "LAST_CHANGED TIMESTAMP"});
groupStorage = new UserGroupStorage( context );
addSubStorage( groupStorage );
}
@Override
void insertAll() throws SQLException, RaplaException {
insert( cache.getUsers());
}
@Override
protected int write(PreparedStatement stmt,User user) throws SQLException, RaplaException {
setId(stmt, 1, user);
setString(stmt,2,user.getUsername());
String password = cache.getPassword(user.getId());
setString(stmt,3,password);
//setId(stmt,4,user.getPerson());
setString(stmt,4,user.getName());
setString(stmt,5,user.getEmail());
stmt.setInt(6,user.isAdmin()?1:0);
setTimestamp(stmt, 7, user.getCreateTime() );
setTimestamp(stmt, 8, user.getLastChanged() );
stmt.addBatch();
return 1;
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
String userId = readId(rset,1, User.class );
String username = getString(rset,2, null);
if ( username == null)
{
getLogger().warn("Username is null for " + userId + " Ignoring user.");
}
String password = getString(rset,3, null);
//String personId = readId(rset,4, Allocatable.class, true);
String name = getString(rset,4,"");
String email = getString(rset,5,"");
boolean isAdmin = rset.getInt(6) == 1;
Date createDate = getTimestampOrNow( rset, 7);
Date lastChanged = getTimestampOrNow( rset, 8);
UserImpl user = new UserImpl(createDate, lastChanged);
// if ( personId != null)
// {
// user.putId("person", personId);
// }
user.setId( userId );
user.setUsername( username );
user.setName( name );
user.setEmail( email );
user.setAdmin( isAdmin );
if ( password != null) {
putPassword(userId,password);
}
put(user);
}
}
class UserGroupStorage extends EntityStorage<User> {
public UserGroupStorage(RaplaContext context) throws RaplaException {
super(context,"RAPLA_USER_GROUP", new String [] {"USER_ID VARCHAR(255) NOT NULL KEY","CATEGORY_ID VARCHAR(255) NOT NULL"});
}
@Override
protected int write(PreparedStatement stmt, User entity) throws SQLException, RaplaException {
setId( stmt,1, entity);
int count = 0;
for (Category category:entity.getGroups()) {
setId(stmt, 2, category);
stmt.addBatch();
count++;
}
return count;
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
User user = resolveFromId(rset, 1,User.class);
if ( user == null)
{
return;
}
Category category = resolveFromId(rset, 2, Category.class);
if ( category == null)
{
return;
}
user.addGroup( category);
}
}
| Java |
package org.rapla.storage.dbsql;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
public class ColumnDef
{
String name;
boolean key;
boolean primary;
boolean notNull;
String type;
String defaultValue;
public ColumnDef(String unparsedEntry) {
// replace all double " " with single " "
while (true)
{
String replaceAll = unparsedEntry.replaceAll(" ", " ").trim();
if ( replaceAll.equals( unparsedEntry))
{
break;
}
unparsedEntry = replaceAll;
}
String[] split = unparsedEntry.split(" ");
name = split[0];
type = split[1];
for ( int i=2;i< split.length;i++)
{
String s = split[i];
if ( s.equalsIgnoreCase("KEY"))
{
key = true;
}
if ( s.equalsIgnoreCase("PRIMARY"))
{
primary = true;
}
if ( s.equalsIgnoreCase("NOT") && i<split.length -1 && split[i+1].equals("NULL"))
{
notNull = true;
}
if ( s.equalsIgnoreCase("DEFAULT") && i<split.length -1)
{
defaultValue = split[i+1];
}
}
}
public ColumnDef(ResultSet set) throws SQLException {
name = set.getString("COLUMN_NAME").toUpperCase(Locale.ENGLISH);
type = set.getString("TYPE_NAME").toUpperCase(Locale.ENGLISH);
int nullableInt = set.getInt( "NULLABLE");
notNull = nullableInt <=0;
int charLength = set.getInt("CHAR_OCTET_LENGTH");
if ( type.equals("VARCHAR") && charLength>0)
{
type +="("+charLength+")";
}
/*
int nullbable = set.
COLUMN_NAME String => column name
DATA_TYPE int => SQL type from java.sql.Types
TYPE_NAME String => Data source dependent type name, for a UDT the type name is fully qualified
COLUMN_SIZE int => column size.
BUFFER_LENGTH is not used.
DECIMAL_DIGITS int => the number of fractional digits. Null is returned for data types where DECIMAL_DIGITS is not applicable.
NUM_PREC_RADIX int => Radix (typically either 10 or 2)
NULLABLE int => is NULL allowed.
*/
}
public String getName() {
return name;
}
public boolean isKey() {
return key;
}
public boolean isPrimary() {
return primary;
}
public boolean isNotNull() {
return notNull;
}
public String getType() {
return type;
}
public String getDefaultValue() {
return defaultValue;
}
@Override
public String toString() {
return "Column [name=" + name + ", key=" + key + ", primary="
+ primary + ", notNull=" + notNull + ", type=" + type
+ ", defaultValue=" + defaultValue + "]";
}
public boolean isIntType()
{
if ( type == null)
{
return false;
}
String lowerCase = type.toLowerCase();
return (lowerCase.contains("int"));
}
} | Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbsql;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TimeZone;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.xml.RaplaNonValidatedInput;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.RaplaType;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.storage.EntityResolver;
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.server.internal.TimeZoneConverterImpl;
import org.rapla.storage.LocalCache;
import org.rapla.storage.impl.EntityStore;
import org.rapla.storage.xml.PreferenceReader;
import org.rapla.storage.xml.PreferenceWriter;
import org.rapla.storage.xml.RaplaXMLReader;
import org.rapla.storage.xml.RaplaXMLWriter;
abstract class EntityStorage<T extends Entity<T>> implements Storage<T> {
String insertSql;
String updateSql;
String deleteSql;
String selectSql;
String deleteAllSql;
//String searchForIdSql;
RaplaContext context;
protected LocalCache cache;
protected EntityStore entityStore;
private RaplaLocale raplaLocale;
Collection<Storage<T>> subStores = new ArrayList<Storage<T>>();
protected Connection con;
int lastParameterIndex; /** first paramter is 1 */
protected final String tableName;
protected Logger logger;
String dbProductName = "";
protected Map<String,ColumnDef> columns = new LinkedHashMap<String,ColumnDef>();
Calendar datetimeCal;
protected EntityStorage( RaplaContext context, String table,String[] entries) throws RaplaException {
this.context = context;
if ( context.has( EntityStore.class))
{
this.entityStore = context.lookup( EntityStore.class);
}
if ( context.has( LocalCache.class))
{
this.cache = context.lookup( LocalCache.class);
}
this.raplaLocale = context.lookup( RaplaLocale.class);
datetimeCal =Calendar.getInstance( getSystemTimeZone());
logger = context.lookup( Logger.class);
lastParameterIndex = entries.length;
tableName = table;
for ( String unparsedEntry: entries)
{
ColumnDef col = new ColumnDef(unparsedEntry);
columns.put( col.getName(), col);
}
createSQL(columns.values());
if (getLogger().isDebugEnabled()) {
getLogger().debug(insertSql);
getLogger().debug(updateSql);
getLogger().debug(deleteSql);
getLogger().debug(selectSql);
getLogger().debug(deleteAllSql);
}
}
protected Date getDate( ResultSet rset,int column) throws SQLException
{
java.sql.Timestamp timestamp = rset.getTimestamp( column, datetimeCal);
if (rset.wasNull() || timestamp == null)
{
return null;
}
long time = timestamp.getTime();
TimeZone systemTimeZone = getSystemTimeZone();
long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time);
Date returned = new Date(time + offset);
return returned;
}
// Always use gmt for storing timestamps
protected Date getTimestampOrNow(ResultSet rset, int column) throws SQLException {
Date currentTimestamp = getCurrentTimestamp();
java.sql.Timestamp timestamp = rset.getTimestamp( column, datetimeCal);
if (rset.wasNull() || timestamp == null)
{
return currentTimestamp;
}
Date date = new Date( timestamp.getTime());
if ( date != null)
{
if ( date.after( currentTimestamp))
{
getLogger().error("Timestamp in table " + tableName + " in the future. Ignoring.");
}
else
{
return date;
}
}
return currentTimestamp;
}
public Date getCurrentTimestamp() {
long time = System.currentTimeMillis();
return new Date( time);
}
public String getIdColumn() {
for (Map.Entry<String, ColumnDef> entry:columns.entrySet())
{
String column = entry.getKey();
ColumnDef def = entry.getValue();
if ( def.isPrimary())
{
return column;
}
}
return null;
}
public String getTableName() {
return tableName;
}
protected TimeZone getSystemTimeZone() {
return TimeZone.getDefault();
}
protected void setDate(PreparedStatement stmt,int column, Date time) throws SQLException {
if ( time != null)
{
TimeZone systemTimeZone = getSystemTimeZone();
// same as TimeZoneConverterImpl.fromRaplaTime
long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time.getTime());
long timeInMillis = time.getTime() - offset;
stmt.setTimestamp( column, new java.sql.Timestamp( timeInMillis), datetimeCal);
}
else
{
stmt.setObject(column, null, Types.TIMESTAMP);
}
}
protected void setTimestamp(PreparedStatement stmt,int column, Date time) throws SQLException {
if ( time != null)
{
TimeZone systemTimeZone = getSystemTimeZone();
// same as TimeZoneConverterImpl.fromRaplaTime
long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time.getTime());
long timeInMillis = time.getTime() - offset;
stmt.setTimestamp( column, new java.sql.Timestamp( timeInMillis), datetimeCal);
}
else
{
stmt.setObject(column, null, Types.TIMESTAMP);
}
}
protected void setId(PreparedStatement stmt, int column, Entity<?> entity) throws SQLException {
setId( stmt, column, entity != null ? entity.getId() : null);
}
protected void setId(PreparedStatement stmt, int column, String id) throws SQLException {
if ( id != null) {
stmt.setString( column, id );
} else {
stmt.setObject(column, null, Types.VARCHAR);
}
}
protected String readId(ResultSet rset, int column, Class<? extends Entity> class1) throws SQLException, RaplaException {
return readId(rset, column, class1, false);
}
protected String readId(ResultSet rset, int column, @SuppressWarnings("unused") Class<? extends Entity> class1, boolean nullAllowed) throws SQLException, RaplaException {
String id = rset.getString( column );
if ( rset.wasNull() || id == null )
{
if ( nullAllowed )
{
return null;
}
throw new RaplaException("Id can't be null for " + tableName );
}
return id;
}
protected <S extends Entity> S resolveFromId(ResultSet rset, int column, Class<S> class1) throws SQLException
{
String id = rset.getString( column );
if (rset.wasNull() || id == null)
{
return null;
}
try {
Entity resolved = entityStore.resolve(id, class1);
@SuppressWarnings("unchecked")
S casted = (S) resolved;
return casted;
}
catch ( EntityNotFoundException ex)
{
getLogger().warn("Could not find " + class1.getName() +" with id "+ id + " in the " + tableName + " table. Ignoring." );
return null;
}
}
protected void setInt(PreparedStatement stmt, int column, Integer number) throws SQLException {
if ( number != null) {
stmt.setInt( column, number.intValue() );
} else {
stmt.setObject(column, null, Types.INTEGER);
}
}
protected String getString(ResultSet rset,int index, String defaultString) throws SQLException {
String value = rset.getString(index);
if (rset.wasNull() || value == null)
{
return defaultString;
}
return value;
}
protected Integer getInt( ResultSet rset,int column) throws SQLException
{
Integer value = rset.getInt( column);
if (rset.wasNull() || value == null)
{
return null;
}
return value;
}
protected void setLong(PreparedStatement stmt, int column, Long number) throws SQLException {
if ( number != null) {
stmt.setLong( column, number.longValue() );
} else {
stmt.setObject(column, null, Types.BIGINT);
}
}
protected void setString(PreparedStatement stmt, int column, String object) throws SQLException {
if ( object == null)
{
stmt.setObject( column, null, Types.VARCHAR);
}
else
{
stmt.setString( column, object);
}
}
protected Logger getLogger() {
return logger;
}
public List<String> getCreateSQL()
{
List<String> createSQL = new ArrayList<String>();
StringBuffer buf = new StringBuffer();
String table = tableName;
buf.append("CREATE TABLE " + table + " (");
List<String> keyCreates = new ArrayList<String>();
boolean first= true;
for (ColumnDef col: columns.values())
{
if (first)
{
first = false;
}
else
{
buf.append( ", ");
}
boolean includePrimaryKey = true;
boolean includeDefaults = false;
String colSql = getColumnCreateStatemet(col, includePrimaryKey, includeDefaults);
buf.append(colSql);
if ( col.isKey() && !col.isPrimary())
{
String colName = col.getName();
String keyCreate = createKeySQL(table, colName);
keyCreates.add(keyCreate);
}
}
buf.append(")");
String sql = buf.toString();
createSQL.add( sql);
createSQL.addAll( keyCreates);
return createSQL;
}
protected void createSQL(Collection<ColumnDef> entries) {
String idString = entries.iterator().next().getName();
String table = tableName;
selectSql = "select " + getEntryList(entries) + " from " + table ;
deleteSql = "delete from " + table + " where " + idString + "= ?";
String valueString = " (" + getEntryList(entries) + ")";
insertSql = "insert into " + table + valueString + " values (" + getMarkerList(entries.size()) + ")";
updateSql = "update " + table + " set " + getUpdateList(entries) + " where " + idString + "= ?";
deleteAllSql = "delete from " + table;
//searchForIdSql = "select id from " + table + " where id = ?";
}
//CREATE INDEX KEY_ALLOCATION_APPOINTMENT ON ALLOCATION(APPOINTMENT_ID);
private String createKeySQL(String table, String colName) {
return "create index KEY_"+ table + "_" + colName + " on " + table + "(" + colName +")";
}
public void createOrUpdateIfNecessary( Map<String,TableDef> schema) throws SQLException, RaplaException
{
String tablename = tableName;
if (schema.get (tablename) != null )
{
return;
}
getLogger().info("Creating table " + tablename);
for (String createSQL : getCreateSQL())
{
Statement stmt = con.createStatement();
try
{
stmt.execute(createSQL );
}
finally
{
stmt.close();
}
con.commit();
}
schema.put( tablename, new TableDef(tablename,columns.values()));
}
protected ColumnDef getColumn(String name)
{
return columns.get( name);
}
protected void checkAndAdd(Map<String, TableDef> schema, String columnName) throws SQLException {
ColumnDef col = getColumn(columnName);
if ( col == null)
{
throw new IllegalArgumentException("Column " + columnName + " not found in table schema " + tableName);
}
String name = col.getName();
TableDef tableDef = schema.get(tableName);
if (tableDef.getColumn(name) == null)
{
getLogger().warn("Patching Database for table " + tableName + " adding column "+ name);
{
String sql = "ALTER TABLE " + tableName + " ADD COLUMN ";
sql += getColumnCreateStatemet( col, true, true);
Statement stmt = con.createStatement();
try
{
stmt.execute( sql);
}
finally
{
stmt.close();
}
con.commit();
}
if ( col.isKey() && !col.isPrimary())
{
String sql = createKeySQL(tableName, name);
getLogger().info("Adding index for " + name);
Statement stmt = con.createStatement();
try
{
stmt.execute( sql);
}
finally
{
stmt.close();
}
con.commit();
}
}
}
protected String getDatabaseProductType(String type) {
if ( type.equals("TEXT"))
{
if ( isHsqldb())
{
return "VARCHAR(16777216)";
}
if ( isMysql())
{
return "LONGTEXT";
}
if ( isH2())
{
return "CLOB";
}
}
if ( type.equals("DATETIME"))
{
if ( !isH2() && !isMysql())
{
return "TIMESTAMP";
}
}
return type;
}
protected void checkAndRename( Map<String, TableDef> schema, String oldColumnName,
String newColumnName) throws SQLException
{
String errorPrefix = "Can't rename " + oldColumnName + " " + newColumnName + " in table " + tableName;
TableDef tableDef = schema.get(tableName);
if (tableDef.getColumn( newColumnName) != null )
{
return;
}
ColumnDef oldColumn = tableDef.getColumn( oldColumnName);
if (oldColumn == null)
{
throw new SQLException(errorPrefix + " old column " + oldColumnName + " not found.");
}
ColumnDef newCol = getColumn(newColumnName);
if ( newCol == null)
{
throw new IllegalArgumentException("Column " + newColumnName + " not found in table schema " + tableName);
}
getLogger().warn("Patching Database for table " + tableName + " renaming column "+ oldColumnName + " to " + newColumnName);
String sql = "ALTER TABLE " + tableName + " RENAME COLUMN " + oldColumnName + " TO " + newColumnName;
if ( isMysql())
{
sql = "ALTER TABLE " + tableName + " CHANGE COLUMN " +oldColumnName + " ";
String columnSql = getColumnCreateStatemet(newCol, false, true);
sql+= columnSql;
}
Statement stmt = con.createStatement();
try
{
stmt.execute( sql);
}
finally
{
stmt.close();
}
con.commit();
tableDef.removeColumn( oldColumnName);
tableDef.addColumn( newCol);
}
protected void checkAndRetype(Map<String, TableDef> schema, String columnName) throws RaplaException
{
TableDef tableDef = schema.get(tableName);
ColumnDef oldDef = tableDef.getColumn( columnName);
ColumnDef newDef = getColumn(columnName);
if (oldDef == null || newDef == null)
{
throw new RaplaException("Can't retype column " + columnName + " it is not found");
}
boolean includePrimaryKey = false;
boolean includeDefaults = false;
String stmt1 = getColumnCreateStatemet(oldDef, includePrimaryKey, includeDefaults);
String stmt2 = getColumnCreateStatemet(newDef, includePrimaryKey, includeDefaults);
if ( stmt1.equals( stmt2))
{
return;
}
String columnSql = getColumnCreateStatemet(newDef, false, true);
getLogger().warn("Column "+ tableName + "."+ columnName + " change from '" + stmt1+ "' to new type '" + columnSql + "'");
getLogger().warn("You should patch the database accordingly.");
// We do not autopatch colum types yet
// String sql = "ALTER TABLE " + tableName + " ALTER COLUMN " ;
// sql+= columnSql;
// con.createStatement().execute(sql);
}
protected String getColumnCreateStatemet(ColumnDef col, boolean includePrimaryKey, boolean includeDefaults) {
StringBuffer buf = new StringBuffer();
String colName = col.getName();
buf.append(colName);
String type = getDatabaseProductType(col.getType());
buf.append(" " + type);
if ( col.isNotNull())
{
buf.append(" NOT NULL");
}
else
{
buf.append(" NULL");
}
if ( includeDefaults)
{
if ( type.equals("TIMESTAMP"))
{
if ( !isHsqldb() && !isH2())
{
buf.append( " DEFAULT " + "'2000-01-01 00:00:00'");
}
}
else if ( col.getDefaultValue() != null)
{
buf.append( " DEFAULT " + col.getDefaultValue());
}
}
if (includePrimaryKey && col.isPrimary())
{
buf.append(" PRIMARY KEY");
}
String columnSql =buf.toString();
return columnSql;
}
protected boolean isMysql() {
boolean result = dbProductName.indexOf("mysql") >=0;
return result;
}
protected boolean isHsqldb() {
boolean result = dbProductName.indexOf("hsql") >=0;
return result;
}
protected boolean isPostgres() {
boolean result = dbProductName.indexOf("postgres") >=0;
return result;
}
protected boolean isH2() {
boolean result = dbProductName.indexOf("h2") >=0;
return result;
}
protected void checkRenameTable( Map<String, TableDef> tableMap, String oldTableName) throws SQLException
{
boolean isOldTableName = false;
if ( tableMap.get( oldTableName) != null)
{
isOldTableName = true;
}
if ( tableMap.get(tableName) != null)
{
isOldTableName = false;
}
if ( isOldTableName)
{
getLogger().warn("Table " + tableName + " not found. Patching Database : Renaming " + oldTableName + " to "+ tableName);
String sql = "ALTER TABLE " + oldTableName + " RENAME TO " + tableName + "";
Statement stmt = con.createStatement();
try
{
stmt.execute( sql);
}
finally
{
stmt.close();
}
con.commit();
tableMap.put( tableName, tableMap.get( oldTableName));
tableMap.remove( oldTableName);
}
}
protected void checkAndDrop(Map<String, TableDef> schema, String columnName) throws SQLException {
TableDef tableDef = schema.get(tableName);
if (tableDef.getColumn(columnName) != null)
{
String sql = "ALTER TABLE " + tableName + " DROP COLUMN " + columnName;
Statement stmt = con.createStatement();
try
{
stmt.execute( sql);
}
finally
{
stmt.close();
}
}
con.commit();
}
@Override
public void dropTable() throws SQLException
{
getLogger().info("Dropping table " + tableName);
String sql = "DROP TABLE " + tableName ;
Statement stmt = con.createStatement();
try
{
stmt.execute( sql);
}
finally
{
stmt.close();
}
con.commit();
}
protected void addSubStorage(Storage<T> subStore) {
subStores.add(subStore);
}
public Collection<Storage<T>> getSubStores() {
return subStores;
}
public void setConnection(Connection con) throws SQLException {
this.con= con;
for (Storage<T> subStore: subStores) {
subStore.setConnection(con);
}
if ( con != null)
{
String databaseProductName = con.getMetaData().getDatabaseProductName();
if ( databaseProductName != null)
{
Locale locale = Locale.ENGLISH;
dbProductName = databaseProductName.toLowerCase(locale);
}
}
}
public Locale getLocale() {
return raplaLocale.getLocale();
}
protected String getEntryList(Collection<ColumnDef> entries) {
StringBuffer buf = new StringBuffer();
for (ColumnDef col: entries) {
if (buf.length() > 0 )
{
buf.append(", ");
}
buf.append(col.getName());
}
return buf.toString();
}
protected String getMarkerList(int length) {
StringBuffer buf = new StringBuffer();
for (int i=0;i<length; i++) {
buf.append('?');
if (i < length - 1)
{
buf.append(',');
}
}
return buf.toString();
}
protected String getUpdateList(Collection<ColumnDef> entries) {
StringBuffer buf = new StringBuffer();
for (ColumnDef col: entries) {
if (buf.length() > 0 )
{
buf.append(", ");
}
buf.append(col.getName());
buf.append("=? ");
}
return buf.toString();
}
public static void executeBatchedStatement(Connection con,String sql) throws SQLException {
Statement stmt = null;
try {
stmt = con.createStatement();
StringTokenizer tokenizer = new StringTokenizer(sql,";");
while (tokenizer.hasMoreTokens())
stmt.executeUpdate(tokenizer.nextToken());
} finally {
if (stmt!=null)
stmt.close();
}
}
public void loadAll() throws SQLException,RaplaException {
Statement stmt = null;
ResultSet rset = null;
try {
stmt = con.createStatement();
rset = stmt.executeQuery(selectSql);
while (rset.next ()) {
load(rset);
}
} finally {
if (rset != null)
rset.close();
if (stmt!=null)
stmt.close();
}
for (Storage storage: subStores) {
storage.loadAll();
}
}
public void insert(Iterable<T> entities) throws SQLException,RaplaException {
for (Storage<T> storage: subStores)
{
storage.insert(entities);
}
PreparedStatement stmt = null;
try {
stmt = con.prepareStatement(insertSql);
int count = 0;
for ( T entity: entities)
{
count+= write(stmt, entity);
}
if ( count > 0)
{
stmt.executeBatch();
}
} catch (SQLException ex) {
throw ex;
} finally {
if (stmt!=null)
stmt.close();
}
}
// public void update(Collection<Entity>> entities ) throws SQLException,RaplaException {
// for (Storage<T> storage: subStores) {
// storage.delete( entities );
// storage.insert( entities);
// }
// PreparedStatement stmt = null;
// try {
// stmt = con.prepareStatement( updateSql);
// int count = 0;
// for (Entity entity: entities)
// {
// int id = getId( entity );
// stmt.setInt( lastParameterIndex + 1,id );
// count+=write(stmt, entity);
// }
// if ( count > 0)
// {
// stmt.executeBatch();
// }
// } finally {
// if (stmt!=null)
// stmt.close();
// }
// }
// public void save(Collection<Entity>> entities) throws SQLException,RaplaException {
// Collection<Entity>> toUpdate = new ArrayList<Entity>>();
// Collection<Entity>> toInsert = new ArrayList<Entity>>();
// for (Entity entity:entities)
// {
//
// if (cache.tryResolve( entity.getId())!= null) {
// toUpdate.add( entity );
// } else {
// toInsert.add( entity );
// }
// }
// if ( !toInsert.isEmpty())
// {
// insert( toInsert);
// }
// if ( !toUpdate.isEmpty())
// {
// update( toUpdate);
// }
// }
public void save( Iterable<T> entities ) throws RaplaException, SQLException{
deleteEntities( entities );
insert( entities );
}
public void deleteEntities(Iterable<T> entities) throws SQLException, RaplaException {
Set<String> ids = new HashSet<String>();
for ( T entity: entities)
{
ids.add( entity.getId());
}
deleteIds(ids);
}
public void deleteIds(Collection<String> ids) throws SQLException, RaplaException {
for (Storage<T> storage: subStores) {
storage.deleteIds( ids);
}
PreparedStatement stmt = null;
try {
stmt = con.prepareStatement(deleteSql);
for ( String id: ids)
{
stmt.setString(1,id);
stmt.addBatch();
}
if ( ids.size() > 0)
{
stmt.executeBatch();
}
} finally {
if (stmt!=null)
stmt.close();
}
}
public void deleteAll() throws SQLException {
for (Storage<T> subStore: subStores)
{
subStore.deleteAll();
}
executeBatchedStatement(con,deleteAllSql);
}
abstract protected int write(PreparedStatement stmt,T entity) throws SQLException,RaplaException;
abstract protected void load(ResultSet rs) throws SQLException,RaplaException;
public RaplaNonValidatedInput getReader() throws RaplaException {
return lookup( RaplaNonValidatedInput.class);
}
public RaplaXMLReader getReaderFor( RaplaType type) throws RaplaException {
Map<RaplaType,RaplaXMLReader> readerMap = lookup( PreferenceReader.READERMAP);
return readerMap.get( type);
}
public RaplaXMLWriter getWriterFor( RaplaType type) throws RaplaException {
Map<RaplaType,RaplaXMLWriter> writerMap = lookup( PreferenceWriter.WRITERMAP );
return writerMap.get( type);
}
protected <S> S lookup( TypedComponentRole<S> role) throws RaplaException {
try {
return context.lookup( role);
} catch (RaplaContextException e) {
throw new RaplaException( e);
}
}
protected <S> S lookup( Class<S> role) throws RaplaException {
try {
return context.lookup( role);
} catch (RaplaContextException e) {
throw new RaplaException( e);
}
}
protected void put( Entity entity)
{
entityStore.put( entity);
}
protected EntityResolver getResolver()
{
return entityStore;
}
protected void putPassword( String userId, String password )
{
entityStore.putPassword( userId, password);
}
protected DynamicType getDynamicType( String typeKey )
{
return entityStore.getDynamicType( typeKey);
}
protected Category getSuperCategory()
{
if ( cache != null)
{
return cache.getSuperCategory();
}
return entityStore.getSuperCategory();
}
protected void setText(PreparedStatement stmt, int columIndex, String xml)
throws SQLException {
if ( isHsqldb() || isH2())
{
if (xml != null)
{
Clob clob = con.createClob();
clob.setString(1, xml);
stmt.setClob( columIndex, clob);
}
else
{
stmt.setObject( columIndex, null, Types.CLOB);
}
}
else
{
stmt.setString( columIndex, xml);
}
}
protected String getText(ResultSet rset, int columnIndex)
throws SQLException {
String xml = null;
if ( isMysql())
{
Clob clob = rset.getClob( columnIndex );
if ( clob!= null)
{
int length = (int)clob.length();
if ( length > 0)
{
xml = clob.getSubString(1, length);
// String xml = rset.getString( 4);
}
}
}
else
{
xml = rset.getString(columnIndex);
}
return xml;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbsql.pre18;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TimeZone;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.xml.RaplaNonValidatedInput;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.RaplaType;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.storage.EntityResolver;
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.server.internal.TimeZoneConverterImpl;
import org.rapla.storage.LocalCache;
import org.rapla.storage.OldIdMapping;
import org.rapla.storage.dbsql.ColumnDef;
import org.rapla.storage.dbsql.TableDef;
import org.rapla.storage.impl.EntityStore;
import org.rapla.storage.xml.PreferenceReader;
import org.rapla.storage.xml.PreferenceWriter;
import org.rapla.storage.xml.RaplaXMLReader;
import org.rapla.storage.xml.RaplaXMLWriter;
@Deprecated
public abstract class OldEntityStorage<T extends Entity<T>> {
String insertSql;
String updateSql;
String deleteSql;
String selectSql;
String deleteAllSql;
//String searchForIdSql;
RaplaContext context;
protected LocalCache cache;
protected EntityStore entityStore;
private RaplaLocale raplaLocale;
Collection<OldEntityStorage<T>> subStores = new ArrayList<OldEntityStorage<T>>();
protected Connection con;
int lastParameterIndex; /** first paramter is 1 */
protected final String tableName;
protected Logger logger;
String dbProductName = "";
protected Map<String,ColumnDef> columns = new LinkedHashMap<String,ColumnDef>();
Calendar datetimeCal;
protected OldEntityStorage( RaplaContext context, String table,String[] entries) throws RaplaException {
this.context = context;
if ( context.has( EntityStore.class))
{
this.entityStore = context.lookup( EntityStore.class);
}
if ( context.has( LocalCache.class))
{
this.cache = context.lookup( LocalCache.class);
}
this.raplaLocale = context.lookup( RaplaLocale.class);
datetimeCal =Calendar.getInstance( getSystemTimeZone());
logger = context.lookup( Logger.class);
lastParameterIndex = entries.length;
tableName = table;
for ( String unparsedEntry: entries)
{
ColumnDef col = new ColumnDef(unparsedEntry);
columns.put( col.getName(), col);
}
createSQL(columns.values());
if (getLogger().isDebugEnabled()) {
getLogger().debug(insertSql);
getLogger().debug(updateSql);
getLogger().debug(deleteSql);
getLogger().debug(selectSql);
getLogger().debug(deleteAllSql);
}
}
protected Date getDate( ResultSet rset,int column) throws SQLException
{
java.sql.Timestamp timestamp = rset.getTimestamp( column, datetimeCal);
if (rset.wasNull() || timestamp == null)
{
return null;
}
long time = timestamp.getTime();
TimeZone systemTimeZone = getSystemTimeZone();
long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time);
Date returned = new Date(time + offset);
return returned;
}
// Always use gmt for storing timestamps
protected Date getTimestampOrNow(ResultSet rset, int column) throws SQLException {
Date currentTimestamp = getCurrentTimestamp();
java.sql.Timestamp timestamp = rset.getTimestamp( column, datetimeCal);
if (rset.wasNull() || timestamp == null)
{
return currentTimestamp;
}
Date date = new Date( timestamp.getTime());
if ( date != null)
{
if ( date.after( currentTimestamp))
{
getLogger().error("Timestamp in table " + tableName + " in the future. Ignoring.");
}
else
{
return date;
}
}
return currentTimestamp;
}
public Date getCurrentTimestamp() {
long time = System.currentTimeMillis();
return new Date( time);
}
public String getIdColumn() {
for (Map.Entry<String, ColumnDef> entry:columns.entrySet())
{
String column = entry.getKey();
ColumnDef def = entry.getValue();
if ( def.isPrimary())
{
return column;
}
}
return null;
}
public String getTableName() {
return tableName;
}
protected TimeZone getSystemTimeZone() {
return TimeZone.getDefault();
}
protected void setDate(PreparedStatement stmt,int column, Date time) throws SQLException {
if ( time != null)
{
TimeZone systemTimeZone = getSystemTimeZone();
// same as TimeZoneConverterImpl.fromRaplaTime
long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time.getTime());
long timeInMillis = time.getTime() - offset;
stmt.setTimestamp( column, new java.sql.Timestamp( timeInMillis), datetimeCal);
}
else
{
stmt.setObject(column, null, Types.TIMESTAMP);
}
}
protected void setTimestamp(PreparedStatement stmt,int column, Date time) throws SQLException {
if ( time != null)
{
TimeZone systemTimeZone = getSystemTimeZone();
// same as TimeZoneConverterImpl.fromRaplaTime
long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time.getTime());
long timeInMillis = time.getTime() - offset;
stmt.setTimestamp( column, new java.sql.Timestamp( timeInMillis), datetimeCal);
}
else
{
stmt.setObject(column, null, Types.TIMESTAMP);
}
}
protected void setId(PreparedStatement stmt, int column, Entity<?> entity) throws SQLException {
if ( entity != null) {
int groupId = getId( (Entity) entity);
stmt.setInt( column, groupId );
} else {
stmt.setObject(column, null, Types.INTEGER);
}
}
protected String readId(ResultSet rset, int column, Class<? extends Entity> class1) throws SQLException, RaplaException {
return readId(rset, column, class1, false);
}
protected String readId(ResultSet rset, int column, Class<? extends Entity> class1, boolean nullAllowed) throws SQLException, RaplaException {
RaplaType type = RaplaType.get( class1);
Integer id = rset.getInt( column );
if ( rset.wasNull() || id == null )
{
if ( nullAllowed )
{
return null;
}
throw new RaplaException("Id can't be null for " + tableName);
}
return OldIdMapping.getId(type,id);
}
protected <S extends Entity> S resolveFromId(ResultSet rset, int column, Class<S> class1) throws SQLException
{
RaplaType type = RaplaType.get( class1);
Integer id = rset.getInt( column );
if (rset.wasNull() || id == null)
{
return null;
}
try {
Entity resolved = entityStore.resolve(OldIdMapping.getId(type,id), class1);
@SuppressWarnings("unchecked")
S casted = (S) resolved;
return casted;
}
catch ( EntityNotFoundException ex)
{
getLogger().warn("Could not find " + type +" with id "+ id + " in the " + tableName + " table. Ignoring." );
return null;
}
}
protected void setInt(PreparedStatement stmt, int column, Integer number) throws SQLException {
if ( number != null) {
stmt.setInt( column, number.intValue() );
} else {
stmt.setObject(column, null, Types.INTEGER);
}
}
protected String getString(ResultSet rset,int index, String defaultString) throws SQLException {
String value = rset.getString(index);
if (rset.wasNull() || value == null)
{
return defaultString;
}
return value;
}
protected Integer getInt( ResultSet rset,int column) throws SQLException
{
Integer value = rset.getInt( column);
if (rset.wasNull() || value == null)
{
return null;
}
return value;
}
protected void setLong(PreparedStatement stmt, int column, Long number) throws SQLException {
if ( number != null) {
stmt.setLong( column, number.longValue() );
} else {
stmt.setObject(column, null, Types.BIGINT);
}
}
protected void setString(PreparedStatement stmt, int column, String object) throws SQLException {
if ( object == null)
{
stmt.setObject( column, null, Types.VARCHAR);
}
else
{
stmt.setString( column, object);
}
}
protected Logger getLogger() {
return logger;
}
public List<String> getCreateSQL()
{
List<String> createSQL = new ArrayList<String>();
StringBuffer buf = new StringBuffer();
String table = tableName;
buf.append("CREATE TABLE " + table + " (");
List<String> keyCreates = new ArrayList<String>();
boolean first= true;
for (ColumnDef col: columns.values())
{
if (first)
{
first = false;
}
else
{
buf.append( ", ");
}
boolean includePrimaryKey = true;
boolean includeDefaults = false;
String colSql = getColumnCreateStatemet(col, includePrimaryKey, includeDefaults);
buf.append(colSql);
if ( col.isKey() && !col.isPrimary())
{
String colName = col.getName();
String keyCreate = createKeySQL(table, colName);
keyCreates.add(keyCreate);
}
}
buf.append(")");
String sql = buf.toString();
createSQL.add( sql);
createSQL.addAll( keyCreates);
return createSQL;
}
protected void createSQL(Collection<ColumnDef> entries) {
String idString = entries.iterator().next().getName();
String table = tableName;
selectSql = "select " + getEntryList(entries) + " from " + table ;
deleteSql = "delete from " + table + " where " + idString + "= ?";
String valueString = " (" + getEntryList(entries) + ")";
insertSql = "insert into " + table + valueString + " values (" + getMarkerList(entries.size()) + ")";
updateSql = "update " + table + " set " + getUpdateList(entries) + " where " + idString + "= ?";
deleteAllSql = "delete from " + table;
//searchForIdSql = "select id from " + table + " where id = ?";
}
//CREATE INDEX KEY_ALLOCATION_APPOINTMENT ON ALLOCATION(APPOINTMENT_ID);
private String createKeySQL(String table, String colName) {
return "create index KEY_"+ table + "_" + colName + " on " + table + "(" + colName +")";
}
/**
* @throws RaplaException
*/
public void createOrUpdateIfNecessary( Map<String,TableDef> schema) throws SQLException, RaplaException
{
String tablename = tableName;
if (schema.get (tablename) != null )
{
return;
}
getLogger().info("Creating table " + tablename);
for (String createSQL : getCreateSQL())
{
Statement stmt = con.createStatement();
try
{
stmt.execute(createSQL );
}
finally
{
stmt.close();
}
con.commit();
}
schema.put( tablename, new TableDef(tablename,columns.values()));
}
protected ColumnDef getColumn(String name)
{
return columns.get( name);
}
protected void checkAndAdd(Map<String, TableDef> schema, String columnName) throws SQLException {
ColumnDef col = getColumn(columnName);
if ( col == null)
{
throw new IllegalArgumentException("Column " + columnName + " not found in table schema " + tableName);
}
String name = col.getName();
TableDef tableDef = schema.get(tableName);
if (tableDef.getColumn(name) == null)
{
getLogger().warn("Patching Database for table " + tableName + " adding column "+ name);
{
String sql = "ALTER TABLE " + tableName + " ADD COLUMN ";
sql += getColumnCreateStatemet( col, true, true);
Statement stmt = con.createStatement();
try
{
stmt.execute( sql);
}
finally
{
stmt.close();
}
con.commit();
}
if ( col.isKey() && !col.isPrimary())
{
String sql = createKeySQL(tableName, name);
getLogger().info("Adding index for " + name);
Statement stmt = con.createStatement();
try
{
stmt.execute( sql);
}
finally
{
stmt.close();
}
con.commit();
}
}
}
protected String getDatabaseProductType(String type) {
if ( isHsqldb())
{
if ( type.equals("TEXT"))
{
return "VARCHAR(16777216)";
}
}
if ( isMysql())
{
if ( type.equals("TEXT"))
{
return "LONGTEXT";
}
}
if ( isH2())
{
if ( type.equals("TEXT"))
{
return "CLOB";
}
}
else
{
if ( type.equals("DATETIME"))
{
return "TIMESTAMP";
}
}
return type;
}
protected void checkAndRename( Map<String, TableDef> schema, String oldColumnName,
String newColumnName) throws SQLException
{
String errorPrefix = "Can't rename " + oldColumnName + " " + newColumnName + " in table " + tableName;
TableDef tableDef = schema.get(tableName);
if (tableDef.getColumn( newColumnName) != null )
{
return;
}
ColumnDef oldColumn = tableDef.getColumn( oldColumnName);
if (oldColumn == null)
{
throw new SQLException(errorPrefix + " old column " + oldColumnName + " not found.");
}
ColumnDef newCol = getColumn(newColumnName);
if ( newCol == null)
{
throw new IllegalArgumentException("Column " + newColumnName + " not found in table schema " + tableName);
}
getLogger().warn("Patching Database for table " + tableName + " renaming column "+ oldColumnName + " to " + newColumnName);
String sql = "ALTER TABLE " + tableName + " RENAME COLUMN " + oldColumnName + " TO " + newColumnName;
if ( isMysql())
{
sql = "ALTER TABLE " + tableName + " CHANGE COLUMN " +oldColumnName + " ";
String columnSql = getColumnCreateStatemet(newCol, false, true);
sql+= columnSql;
}
Statement stmt = con.createStatement();
try
{
stmt.execute( sql);
}
finally
{
stmt.close();
}
con.commit();
tableDef.removeColumn( oldColumnName);
tableDef.addColumn( newCol);
}
protected void checkAndRetype(Map<String, TableDef> schema, String columnName) throws RaplaException
{
TableDef tableDef = schema.get(tableName);
ColumnDef oldDef = tableDef.getColumn( columnName);
ColumnDef newDef = getColumn(columnName);
if (oldDef == null || newDef == null)
{
throw new RaplaException("Can't retype column " + columnName + " it is not found");
}
boolean includePrimaryKey = false;
boolean includeDefaults = false;
String stmt1 = getColumnCreateStatemet(oldDef, includePrimaryKey, includeDefaults);
String stmt2 = getColumnCreateStatemet(newDef, includePrimaryKey, includeDefaults);
if ( stmt1.equals( stmt2))
{
return;
}
String columnSql = getColumnCreateStatemet(newDef, false, true);
getLogger().warn("Column "+ tableName + "."+ columnName + " change from '" + stmt1+ "' to new type '" + columnSql + "'");
getLogger().warn("You should patch the database accordingly.");
// We do not autopatch colum types yet
// String sql = "ALTER TABLE " + tableName + " ALTER COLUMN " ;
// sql+= columnSql;
// con.createStatement().execute(sql);
}
protected String getColumnCreateStatemet(ColumnDef col, boolean includePrimaryKey, boolean includeDefaults) {
StringBuffer buf = new StringBuffer();
String colName = col.getName();
buf.append(colName);
String type = getDatabaseProductType(col.getType());
buf.append(" " + type);
if ( col.isNotNull())
{
buf.append(" NOT NULL");
}
else
{
buf.append(" NULL");
}
if ( includeDefaults)
{
if ( type.equals("TIMESTAMP"))
{
if ( !isHsqldb() && !isH2())
{
buf.append( " DEFAULT " + "'2000-01-01 00:00:00'");
}
}
else if ( col.getDefaultValue() != null)
{
buf.append( " DEFAULT " + col.getDefaultValue());
}
}
if (includePrimaryKey && col.isPrimary())
{
buf.append(" PRIMARY KEY");
}
String columnSql =buf.toString();
return columnSql;
}
protected boolean isMysql() {
boolean result = dbProductName.indexOf("mysql") >=0;
return result;
}
protected boolean isHsqldb() {
boolean result = dbProductName.indexOf("hsql") >=0;
return result;
}
protected boolean isPostgres() {
boolean result = dbProductName.indexOf("postgres") >=0;
return result;
}
protected boolean isH2() {
boolean result = dbProductName.indexOf("h2") >=0;
return result;
}
protected void checkRenameTable( Map<String, TableDef> tableMap, String oldTableName) throws SQLException
{
boolean isOldTableName = false;
if ( tableMap.get( oldTableName) != null)
{
isOldTableName = true;
}
if ( tableMap.get(tableName) != null)
{
isOldTableName = false;
}
if ( isOldTableName)
{
getLogger().warn("Table " + tableName + " not found. Patching Database : Renaming " + oldTableName + " to "+ tableName);
String sql = "ALTER TABLE " + oldTableName + " RENAME TO " + tableName + "";
Statement stmt = con.createStatement();
try
{
stmt.execute( sql);
}
finally
{
stmt.close();
}
con.commit();
tableMap.put( tableName, tableMap.get( oldTableName));
tableMap.remove( oldTableName);
}
}
protected void checkAndDrop(Map<String, TableDef> schema, String columnName) throws SQLException {
TableDef tableDef = schema.get(tableName);
if (tableDef.getColumn(columnName) != null)
{
String sql = "ALTER TABLE " + tableName + " DROP COLUMN " + columnName;
Statement stmt = con.createStatement();
try
{
stmt.execute( sql);
}
finally
{
stmt.close();
}
}
con.commit();
}
public void dropTable() throws SQLException
{
getLogger().info("Dropping table " + tableName);
String sql = "DROP TABLE " + tableName ;
Statement stmt = con.createStatement();
try
{
stmt.execute( sql);
}
finally
{
stmt.close();
}
con.commit();
}
protected void addSubStorage(OldEntityStorage<T> subStore) {
subStores.add(subStore);
}
public Collection<OldEntityStorage<T>> getSubStores() {
return subStores;
}
public void setConnection(Connection con) throws SQLException {
this.con= con;
for (OldEntityStorage<T> subStore: subStores) {
subStore.setConnection(con);
}
if ( con != null)
{
String databaseProductName = con.getMetaData().getDatabaseProductName();
if ( databaseProductName != null)
{
Locale locale = Locale.ENGLISH;
dbProductName = databaseProductName.toLowerCase(locale);
}
}
}
public Locale getLocale() {
return raplaLocale.getLocale();
}
protected String getEntryList(Collection<ColumnDef> entries) {
StringBuffer buf = new StringBuffer();
for (ColumnDef col: entries) {
if (buf.length() > 0 )
{
buf.append(", ");
}
buf.append(col.getName());
}
return buf.toString();
}
protected String getMarkerList(int length) {
StringBuffer buf = new StringBuffer();
for (int i=0;i<length; i++) {
buf.append('?');
if (i < length - 1)
{
buf.append(',');
}
}
return buf.toString();
}
protected String getUpdateList(Collection<ColumnDef> entries) {
StringBuffer buf = new StringBuffer();
for (ColumnDef col: entries) {
if (buf.length() > 0 )
{
buf.append(", ");
}
buf.append(col.getName());
buf.append("=? ");
}
return buf.toString();
}
public static void executeBatchedStatement(Connection con,String sql) throws SQLException {
Statement stmt = null;
try {
stmt = con.createStatement();
StringTokenizer tokenizer = new StringTokenizer(sql,";");
while (tokenizer.hasMoreTokens())
stmt.executeUpdate(tokenizer.nextToken());
} finally {
if (stmt!=null)
stmt.close();
}
}
public static int getId(Entity entity) {
String id = (String) entity.getId();
return OldIdMapping.parseId(id);
}
public void loadAll() throws SQLException,RaplaException {
Statement stmt = null;
ResultSet rset = null;
try {
stmt = con.createStatement();
rset = stmt.executeQuery(selectSql);
while (rset.next ()) {
load(rset);
}
} finally {
if (rset != null)
rset.close();
if (stmt!=null)
stmt.close();
}
for (OldEntityStorage storage: subStores) {
storage.loadAll();
}
}
abstract protected void load(ResultSet rs) throws SQLException,RaplaException;
public RaplaNonValidatedInput getReader() throws RaplaException {
return lookup( RaplaNonValidatedInput.class);
}
public RaplaXMLReader getReaderFor( RaplaType type) throws RaplaException {
Map<RaplaType,RaplaXMLReader> readerMap = lookup( PreferenceReader.READERMAP);
return readerMap.get( type);
}
public RaplaXMLWriter getWriterFor( RaplaType type) throws RaplaException {
Map<RaplaType,RaplaXMLWriter> writerMap = lookup( PreferenceWriter.WRITERMAP );
return writerMap.get( type);
}
protected <S> S lookup( TypedComponentRole<S> role) throws RaplaException {
try {
return context.lookup( role);
} catch (RaplaContextException e) {
throw new RaplaException( e);
}
}
protected <S> S lookup( Class<S> role) throws RaplaException {
try {
return context.lookup( role);
} catch (RaplaContextException e) {
throw new RaplaException( e);
}
}
protected void put( Entity entity)
{
entityStore.put( entity);
}
protected EntityResolver getResolver()
{
return entityStore;
}
protected void putPassword( String userId, String password )
{
entityStore.putPassword( userId, password);
}
protected DynamicType getDynamicType( String typeKey )
{
return entityStore.getDynamicType( typeKey);
}
protected Category getSuperCategory()
{
if ( cache != null)
{
return cache.getSuperCategory();
}
return entityStore.getSuperCategory();
}
protected String getText(ResultSet rset, int columnIndex)
throws SQLException {
String xml = null;
if ( isMysql())
{
Clob clob = rset.getClob( columnIndex );
if ( clob!= null)
{
int length = (int)clob.length();
if ( length > 0)
{
xml = clob.getSubString(1, length);
// String xml = rset.getString( 4);
}
}
}
else
{
xml = rset.getString(columnIndex);
}
return xml;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org . |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, of which license fullfill the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbsql.pre18;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.rapla.components.util.Assert;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.xml.RaplaNonValidatedInput;
import org.rapla.entities.Annotatable;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
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.internal.PreferencesImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.RepeatingType;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.ResourceAnnotations;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.domain.internal.AppointmentImpl;
import org.rapla.entities.domain.internal.PeriodImpl;
import org.rapla.entities.domain.internal.PermissionImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.entities.dynamictype.internal.ClassificationImpl;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.entities.internal.UserImpl;
import org.rapla.entities.storage.EntityResolver;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.OldIdMapping;
import org.rapla.storage.StorageOperator;
import org.rapla.storage.dbsql.TableDef;
import org.rapla.storage.xml.CategoryReader;
import org.rapla.storage.xml.PreferenceReader;
import org.rapla.storage.xml.RaplaXMLReader;
import org.rapla.storage.xml.RaplaXMLWriter;
@Deprecated
public class RaplaPre18SQL {
private final List<RaplaTypeStorage> stores = new ArrayList<RaplaTypeStorage>();
private final Logger logger;
RaplaContext context;
PreferenceStorage preferencesStorage;
PeriodStorage periodStorage;
public RaplaPre18SQL( RaplaContext context) throws RaplaException{
this.context = context;
logger = context.lookup( Logger.class);
// The order is important. e.g. appointments can only be loaded if the reservation they are refering to are already loaded.
stores.add(new CategoryStorage( context));
stores.add(new DynamicTypeStorage( context));
stores.add(new UserStorage( context));
stores.add(new AllocatableStorage( context));
stores.add(new PreferenceStorage( context));
ReservationStorage reservationStorage = new ReservationStorage( context);
stores.add(reservationStorage);
AppointmentStorage appointmentStorage = new AppointmentStorage( context);
stores.add(appointmentStorage);
// now set delegate because reservation storage should also use appointment storage
reservationStorage.setAppointmentStorage( appointmentStorage);
periodStorage = new PeriodStorage(context);
}
private List<OldEntityStorage<?>> getStoresWithChildren()
{
List<OldEntityStorage<?>> storages = new ArrayList<OldEntityStorage<?>>();
for ( RaplaTypeStorage store:stores)
{
storages.add( store);
@SuppressWarnings("unchecked")
Collection<OldEntityStorage<?>> subStores = store.getSubStores();
storages.addAll( subStores);
}
return storages;
}
protected Logger getLogger() {
return logger;
}
synchronized public void loadAll(Connection con) throws SQLException,RaplaException {
for (OldEntityStorage storage:stores)
{
load(con, storage);
}
load(con,periodStorage);
for (Map.Entry<String,PeriodImpl> entry:periodStorage.getPeriods().entrySet())
{
Period value = entry.getValue();
AllocatableImpl period = new AllocatableImpl(new Date(), new Date());
EntityResolver cache = periodStorage.getCache();
Classification classification = cache.getDynamicType(StorageOperator.PERIOD_TYPE).newClassification();
classification.setValue("name", value.getName());
classification.setValue("start",value.getStart());
classification.setValue("end",value.getEnd());
period.setClassification( classification);
Permission newPermission = period.newPermission();
newPermission.setAccessLevel( Permission.READ);
period.addPermission( newPermission);
String id = entry.getKey();
period.setId(id);
}
}
protected void load(Connection con, OldEntityStorage storage) throws SQLException, RaplaException {
storage.setConnection(con);
try
{
storage.loadAll();
}
finally
{
storage.setConnection( null);
}
}
public void createOrUpdateIfNecessary(Connection con, Map<String, TableDef> schema) throws SQLException, RaplaException {
// Upgrade db if necessary
for (OldEntityStorage<?> storage:getStoresWithChildren())
{
storage.setConnection(con);
try
{
storage.createOrUpdateIfNecessary( schema);
}
finally
{
storage.setConnection( null);
}
}
}
public Map<String, String> getIdColumns() {
Map<String,String> idColumns = new LinkedHashMap<String,String>();
for (OldEntityStorage<?> storage:getStoresWithChildren())
{
String tableName = storage.getTableName();
String idColumn =storage.getIdColumn();
if (idColumn != null)
{
idColumns.put(tableName, idColumn);
}
}
return idColumns;
}
public void dropAll(Connection con) throws SQLException {
List<OldEntityStorage<?>> storesWithChildren = getStoresWithChildren();
for (OldEntityStorage<?> storage:storesWithChildren)
{
storage.setConnection(con);
try
{
storage.dropTable();
}
finally
{
storage.setConnection( null);
}
}
}
}
@Deprecated
abstract class RaplaTypeStorage<T extends Entity<T>> extends OldEntityStorage<T> {
RaplaType raplaType;
RaplaTypeStorage( RaplaContext context, RaplaType raplaType, String tableName, String[] entries) throws RaplaException {
super( context,tableName, entries );
this.raplaType = raplaType;
}
boolean canStore(Entity entity) {
return entity.getRaplaType() == raplaType;
}
protected String getXML(RaplaObject type) throws RaplaException {
RaplaXMLWriter dynamicTypeWriter = getWriterFor( type.getRaplaType());
StringWriter stringWriter = new StringWriter();
BufferedWriter bufferedWriter = new BufferedWriter(stringWriter);
dynamicTypeWriter.setWriter( bufferedWriter );
dynamicTypeWriter.setSQL( true );
try {
dynamicTypeWriter.writeObject(type);
bufferedWriter.flush();
} catch (IOException ex) {
throw new RaplaException( ex);
}
return stringWriter.getBuffer().toString();
}
protected RaplaXMLReader processXML(RaplaType type, String xml) throws RaplaException {
RaplaXMLReader reader = getReaderFor( type);
if ( xml== null || xml.trim().length() <= 10) {
throw new RaplaException("Can't load " + type);
}
String xmlWithNamespaces = RaplaXMLReader.wrapRaplaDataTag(xml);
RaplaNonValidatedInput parser = getReader();
parser.read(xmlWithNamespaces, reader, logger);
return reader;
}
}
@Deprecated
class PeriodStorage extends OldEntityStorage {
Map<String,PeriodImpl> result = new LinkedHashMap<String,PeriodImpl>();
public PeriodStorage(RaplaContext context) throws RaplaException {
super(context,"PERIOD",new String[] {"ID INTEGER NOT NULL PRIMARY KEY","NAME VARCHAR(255) NOT NULL","PERIOD_START DATETIME NOT NULL","PERIOD_END DATETIME NOT NULL"});
}
public EntityResolver getCache() {
return cache;
}
@Override
protected void load(ResultSet rset) throws SQLException {
String id = OldIdMapping.getId(Period.TYPE, rset.getInt(1));
String name = getString(rset,2, null);
if ( name == null)
{
getLogger().warn("Name is null for " + id + ". Ignored");
}
java.util.Date von = getDate(rset,3);
java.util.Date bis = getDate(rset,4);
PeriodImpl period = new PeriodImpl(name,von,bis);
result.put(id, period);
}
Map<String,PeriodImpl> getPeriods()
{
return result;
}
}
@Deprecated
class CategoryStorage extends RaplaTypeStorage<Category> {
Map<Category,Integer> orderMap = new HashMap<Category,Integer>();
Map<Category,String> categoriesWithoutParent = new TreeMap<Category,String>(new Comparator<Category>()
{
public int compare( Category o1, Category o2 )
{
if ( o1.equals( o2))
{
return 0;
}
int ordering1 = ( orderMap.get( o1 )).intValue();
int ordering2 = (orderMap.get( o2 )).intValue();
if ( ordering1 < ordering2)
{
return -1;
}
if ( ordering1 > ordering2)
{
return 1;
}
if (o1.hashCode() > o2.hashCode())
{
return -1;
}
else
{
return 1;
}
}
}
);
public CategoryStorage(RaplaContext context) throws RaplaException {
super(context,Category.TYPE, "CATEGORY",new String[] {"ID INTEGER NOT NULL PRIMARY KEY","PARENT_ID INTEGER KEY","CATEGORY_KEY VARCHAR(100) NOT NULL","DEFINITION TEXT NOT NULL","PARENT_ORDER INTEGER"});
}
@Override
public void createOrUpdateIfNecessary(Map<String, TableDef> schema) throws SQLException, RaplaException
{
super.createOrUpdateIfNecessary( schema);
checkAndAdd(schema, "DEFINITION");
checkAndAdd(schema, "PARENT_ORDER");
checkAndRetype(schema, "DEFINITION");
}
public RaplaXMLReader getReaderFor( RaplaType type) throws RaplaException {
RaplaXMLReader reader = super.getReaderFor( type );
if ( type.equals( Category.TYPE ) ) {
((CategoryReader) reader).setReadOnlyThisCategory( true);
}
return reader;
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
String id = readId(rset, 1, Category.class);
String parentId = readId(rset, 2, Category.class, true);
String xml = getText( rset, 4 );
Integer order = getInt(rset, 5 );
CategoryImpl category;
if ( xml != null && xml.length() > 10 )
{
category = ((CategoryReader)processXML( Category.TYPE, xml )).getCurrentCategory();
//cache.remove( category );
}
else
{
getLogger().warn("Category has empty xml field. Ignoring.");
return;
}
category.setId( id);
put( category );
orderMap.put( category, order);
// parentId can also be null
categoriesWithoutParent.put( category, parentId);
}
@Override
public void loadAll() throws RaplaException, SQLException {
categoriesWithoutParent.clear();
super.loadAll();
// then we rebuild the hierarchy
Iterator<Map.Entry<Category,String>> it = categoriesWithoutParent.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Category,String> entry = it.next();
String parentId = entry.getValue();
Category category = entry.getKey();
Category parent;
Assert.notNull( category );
if ( parentId != null) {
parent = entityStore.resolve( parentId ,Category.class);
} else {
parent = getSuperCategory();
}
Assert.notNull( parent );
parent.addCategory( category );
}
}
}
@Deprecated
class AllocatableStorage extends RaplaTypeStorage<Allocatable> {
Map<String,Classification> classificationMap = new HashMap<String,Classification>();
Map<String,Allocatable> allocatableMap = new HashMap<String,Allocatable>();
AttributeValueStorage<Allocatable> resourceAttributeStorage;
PermissionStorage permissionStorage;
public AllocatableStorage(RaplaContext context ) throws RaplaException {
super(context,Allocatable.TYPE,"RAPLA_RESOURCE",new String [] {"ID INTEGER NOT NULL PRIMARY KEY","TYPE_KEY VARCHAR(100) NOT NULL","OWNER_ID INTEGER","CREATION_TIME TIMESTAMP","LAST_CHANGED TIMESTAMP","LAST_CHANGED_BY INTEGER DEFAULT NULL"});
resourceAttributeStorage = new AttributeValueStorage<Allocatable>(context,"RESOURCE_ATTRIBUTE_VALUE", "RESOURCE_ID",classificationMap, allocatableMap);
permissionStorage = new PermissionStorage( context, allocatableMap);
addSubStorage(resourceAttributeStorage);
addSubStorage(permissionStorage );
}
@Override
public void createOrUpdateIfNecessary( Map<String, TableDef> schema) throws SQLException, RaplaException
{
checkRenameTable( schema,"RESOURCE");
super.createOrUpdateIfNecessary( schema);
checkAndAdd( schema, "OWNER_ID");
checkAndAdd( schema, "CREATION_TIME");
checkAndAdd( schema, "LAST_CHANGED");
checkAndAdd( schema, "LAST_CHANGED_BY");
checkAndConvertIgnoreConflictsField(schema);
}
protected void checkAndConvertIgnoreConflictsField(Map<String, TableDef> schema) throws SQLException, RaplaException {
TableDef tableDef = schema.get(tableName);
String columnName = "IGNORE_CONFLICTS";
if (tableDef.getColumn(columnName) != null)
{
getLogger().warn("Patching Database for table " + tableName + " converting " + columnName + " column to conflictCreation annotation in RESOURCE_ATTRIBUTE_VALUE");
Map<String, Boolean> map = new HashMap<String,Boolean>();
{
String sql = "SELECT ID," + columnName +" from " + tableName ;
Statement stmt = null;
ResultSet rset = null;
try {
stmt = con.createStatement();
rset = stmt.executeQuery(sql);
while (rset.next ()) {
String id= readId(rset,1, Allocatable.class);
Boolean ignoreConflicts = getInt( rset, 2 ) == 1;
map.put( id, ignoreConflicts);
}
} finally {
if (rset != null)
rset.close();
if (stmt!=null)
stmt.close();
}
}
{
PreparedStatement stmt = null;
try {
String valueString = " (RESOURCE_ID,ATTRIBUTE_KEY,ATTRIBUTE_VALUE)";
String table = "RESOURCE_ATTRIBUTE_VALUE";
String insertSql = "insert into " + table + valueString + " values (" + getMarkerList(3) + ")";
stmt = con.prepareStatement(insertSql);
int count = 0;
for ( String id:map.keySet())
{
Boolean entry = map.get( id);
if ( entry != null && entry == true)
{
int idInt = OldIdMapping.parseId(id);
stmt.setInt( 1, idInt );
setString(stmt,2, AttributeValueStorage.ANNOTATION_PREFIX + ResourceAnnotations.KEY_CONFLICT_CREATION);
setString(stmt,3, ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE);
stmt.addBatch();
count++;
}
}
if ( count > 0)
{
stmt.executeBatch();
}
} catch (SQLException ex) {
throw ex;
} finally {
if (stmt!=null)
stmt.close();
}
}
con.commit();
}
checkAndDrop(schema,columnName);
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
String id= readId(rset,1, Allocatable.class);
String typeKey = getString(rset,2 , null);
final Date createDate = getTimestampOrNow( rset, 4);
final Date lastChanged = getTimestampOrNow( rset, 5);
AllocatableImpl allocatable = new AllocatableImpl(createDate, lastChanged);
allocatable.setLastChangedBy( resolveFromId(rset, 6, User.class) );
allocatable.setId( id);
allocatable.setResolver( entityStore);
DynamicType type = null;
if ( typeKey != null)
{
type = getDynamicType(typeKey );
}
if ( type == null)
{
getLogger().error("Allocatable with id " + id + " has an unknown type " + typeKey + ". Try ignoring it");
return;
}
allocatable.setOwner( resolveFromId(rset, 3, User.class) );
Classification classification = type.newClassification(false);
allocatable.setClassification( classification );
classificationMap.put( id, classification );
allocatableMap.put( id, allocatable);
put( allocatable );
}
@Override
public void loadAll() throws RaplaException, SQLException {
classificationMap.clear();
super.loadAll();
}
}
@Deprecated
class ReservationStorage extends RaplaTypeStorage<Reservation> {
Map<String,Classification> classificationMap = new HashMap<String,Classification>();
Map<String,Reservation> reservationMap = new HashMap<String,Reservation>();
AttributeValueStorage<Reservation> attributeValueStorage;
// appointmentstorage is not a sub store but a delegate
AppointmentStorage appointmentStorage;
public ReservationStorage(RaplaContext context) throws RaplaException {
super(context,Reservation.TYPE, "EVENT",new String [] {"ID INTEGER NOT NULL PRIMARY KEY","TYPE_KEY VARCHAR(100) NOT NULL","OWNER_ID INTEGER NOT NULL","CREATION_TIME TIMESTAMP","LAST_CHANGED TIMESTAMP","LAST_CHANGED_BY INTEGER DEFAULT NULL"});
attributeValueStorage = new AttributeValueStorage<Reservation>(context,"EVENT_ATTRIBUTE_VALUE","EVENT_ID", classificationMap, reservationMap);
addSubStorage(attributeValueStorage);
}
public void setAppointmentStorage(AppointmentStorage appointmentStorage)
{
this.appointmentStorage = appointmentStorage;
}
@Override
public void createOrUpdateIfNecessary( Map<String, TableDef> schema) throws SQLException, RaplaException
{
super.createOrUpdateIfNecessary( schema);
checkAndAdd(schema, "LAST_CHANGED_BY");
}
@Override
public void setConnection(Connection con) throws SQLException {
super.setConnection(con);
appointmentStorage.setConnection(con);
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
final Date createDate = getTimestampOrNow(rset,4);
final Date lastChanged = getTimestampOrNow(rset,5);
ReservationImpl event = new ReservationImpl(createDate, lastChanged);
String id = readId(rset,1,Reservation.class);
event.setId( id);
event.setResolver( entityStore);
String typeKey = getString(rset,2,null);
DynamicType type = null;
if ( typeKey != null)
{
type = getDynamicType(typeKey );
}
if ( type == null)
{
getLogger().error("Reservation with id " + id + " has an unknown type " + typeKey + ". Try ignoring it");
return;
}
User user = resolveFromId(rset, 3, User.class);
if ( user == null )
{
return;
}
event.setOwner( user );
event.setLastChangedBy( resolveFromId(rset, 6, User.class) );
Classification classification = type.newClassification(false);
event.setClassification( classification );
classificationMap.put( id, classification );
reservationMap.put( id, event );
put( event );
}
@Override
public void loadAll() throws RaplaException, SQLException {
classificationMap.clear();
super.loadAll();
}
}
@Deprecated
class AttributeValueStorage<T extends Entity<T>> extends OldEntityStorage<T> {
Map<String,Classification> classificationMap;
Map<String,? extends Annotatable> annotableMap;
final String foreignKeyName;
// TODO Write conversion script to update all old entries to new entries
public final static String OLD_ANNOTATION_PREFIX = "annotation:";
public final static String ANNOTATION_PREFIX = "rapla:";
public AttributeValueStorage(RaplaContext context,String tablename, String foreignKeyName, Map<String,Classification> classificationMap, Map<String, ? extends Annotatable> annotableMap) throws RaplaException {
super(context, tablename, new String[]{foreignKeyName + " INTEGER NOT NULL KEY","ATTRIBUTE_KEY VARCHAR(100)","ATTRIBUTE_VALUE VARCHAR(20000)"});
this.foreignKeyName = foreignKeyName;
this.classificationMap = classificationMap;
this.annotableMap = annotableMap;
}
@Override
public void createOrUpdateIfNecessary( Map<String, TableDef> schema) throws SQLException, RaplaException
{
super.createOrUpdateIfNecessary( schema);
checkAndRename( schema, "VALUE", "ATTRIBUTE_VALUE");
checkAndRetype(schema, "ATTRIBUTE_VALUE");
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
Class<? extends Entity> idClass = foreignKeyName.indexOf("RESOURCE")>=0 ? Allocatable.class : Reservation.class;
String classifiableId = readId(rset, 1, idClass);
String attributekey = rset.getString( 2 );
boolean annotationPrefix = attributekey.startsWith(ANNOTATION_PREFIX);
boolean oldAnnotationPrefix = attributekey.startsWith(OLD_ANNOTATION_PREFIX);
if ( annotationPrefix || oldAnnotationPrefix)
{
String annotationKey = attributekey.substring( annotationPrefix ? ANNOTATION_PREFIX.length() : OLD_ANNOTATION_PREFIX.length());
Annotatable annotatable = annotableMap.get(classifiableId);
if (annotatable != null)
{
String valueAsString = rset.getString( 3);
if ( rset.wasNull() || valueAsString == null)
{
annotatable.setAnnotation(annotationKey, null);
}
else
{
annotatable.setAnnotation(annotationKey, valueAsString);
}
}
else
{
getLogger().warn("No resource or reservation found for the id " + classifiableId + " ignoring.");
}
}
else
{
ClassificationImpl classification = (ClassificationImpl) classificationMap.get(classifiableId);
if ( classification == null) {
getLogger().warn("No resource or reservation found for the id " + classifiableId + " ignoring.");
return;
}
Attribute attribute = classification.getType().getAttribute( attributekey );
if ( attribute == null) {
getLogger().error("DynamicType '" +classification.getType() +"' doesnt have an attribute with the key " + attributekey + " Current allocatable/reservation Id " + classifiableId + ". Ignoring attribute.");
return;
}
String valueAsString = rset.getString( 3);
if ( valueAsString != null )
{
Object value = AttributeImpl.parseAttributeValue(attribute, valueAsString);
classification.addValue( attribute, value);
}
}
}
}
@Deprecated
class PermissionStorage extends OldEntityStorage<Allocatable> {
Map<String,Allocatable> allocatableMap;
public PermissionStorage(RaplaContext context,Map<String,Allocatable> allocatableMap) throws RaplaException {
super(context,"PERMISSION",new String[] {"RESOURCE_ID INTEGER NOT NULL KEY","USER_ID INTEGER","GROUP_ID INTEGER","ACCESS_LEVEL INTEGER NOT NULL","MIN_ADVANCE INTEGER","MAX_ADVANCE INTEGER","START_DATE DATETIME","END_DATE DATETIME"});
this.allocatableMap = allocatableMap;
}
protected void load(ResultSet rset) throws SQLException, RaplaException {
String allocatableIdInt = readId(rset, 1, Allocatable.class);
Allocatable allocatable = allocatableMap.get(allocatableIdInt);
if ( allocatable == null)
{
getLogger().warn("Could not find resource object with id "+ allocatableIdInt + " for permission. Maybe the resource was deleted from the database.");
return;
}
PermissionImpl permission = new PermissionImpl();
permission.setUser( resolveFromId(rset, 2, User.class));
permission.setGroup( resolveFromId(rset, 3, Category.class));
Integer accessLevel = getInt( rset, 4);
// We multiply the access levels to add a more access levels between.
if ( accessLevel !=null)
{
if ( accessLevel < 5)
{
accessLevel *= 100;
}
permission.setAccessLevel( accessLevel );
}
permission.setMinAdvance( getInt(rset,5));
permission.setMaxAdvance( getInt(rset,6));
permission.setStart(getDate(rset, 7));
permission.setEnd(getDate(rset, 8));
// We need to add the permission at the end to ensure its unique. Permissions are stored in a set and duplicates are removed during the add method
allocatable.addPermission( permission );
}
}
@Deprecated
class AppointmentStorage extends RaplaTypeStorage<Appointment> {
AppointmentExceptionStorage appointmentExceptionStorage;
AllocationStorage allocationStorage;
public AppointmentStorage(RaplaContext context) throws RaplaException {
super(context, Appointment.TYPE,"APPOINTMENT",new String [] {"ID INTEGER NOT NULL PRIMARY KEY","EVENT_ID INTEGER NOT NULL KEY","APPOINTMENT_START DATETIME NOT NULL","APPOINTMENT_END DATETIME NOT NULL","REPETITION_TYPE VARCHAR(255)","REPETITION_NUMBER INTEGER","REPETITION_END DATETIME","REPETITION_INTERVAL INTEGER"});
appointmentExceptionStorage = new AppointmentExceptionStorage(context);
allocationStorage = new AllocationStorage( context);
addSubStorage(appointmentExceptionStorage);
addSubStorage(allocationStorage);
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
String id = readId(rset, 1, Appointment.class);
Reservation event = resolveFromId(rset, 2, Reservation.class);
if ( event == null)
{
return;
}
Date start = getDate(rset,3);
Date end = getDate(rset,4);
boolean wholeDayAppointment = start.getTime() == DateTools.cutDate( start.getTime()) && end.getTime() == DateTools.cutDate( end.getTime());
AppointmentImpl appointment = new AppointmentImpl(start, end);
appointment.setId( id);
appointment.setWholeDays( wholeDayAppointment);
event.addAppointment( appointment );
String repeatingType = getString( rset,5, null);
if ( repeatingType != null ) {
appointment.setRepeatingEnabled( true );
Repeating repeating = appointment.getRepeating();
repeating.setType( RepeatingType.findForString( repeatingType ) );
Date repeatingEnd = getDate(rset, 7);
if ( repeatingEnd != null ) {
repeating.setEnd( repeatingEnd);
} else {
Integer number = getInt( rset, 6);
if ( number != null) {
repeating.setNumber( number);
} else {
repeating.setEnd( null );
}
}
Integer interval = getInt( rset,8);
if ( interval != null)
repeating.setInterval( interval);
}
put( appointment );
}
}
@Deprecated
class AllocationStorage extends OldEntityStorage<Appointment> {
public AllocationStorage(RaplaContext context) throws RaplaException
{
super(context,"ALLOCATION",new String [] {"APPOINTMENT_ID INTEGER NOT NULL KEY", "RESOURCE_ID INTEGER NOT NULL", "OPTIONAL INTEGER"});
}
@Override
public void createOrUpdateIfNecessary(
Map<String, TableDef> schema) throws SQLException, RaplaException {
super.createOrUpdateIfNecessary( schema);
checkAndAdd( schema, "OPTIONAL");
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
Appointment appointment =resolveFromId(rset,1, Appointment.class);
if ( appointment == null)
{
return;
}
ReservationImpl event = (ReservationImpl) appointment.getReservation();
Allocatable allocatable = resolveFromId(rset, 2, Allocatable.class);
if ( allocatable == null)
{
return;
}
if ( !event.hasAllocated( allocatable ) ) {
event.addAllocatable( allocatable );
}
Appointment[] appointments = event.getRestriction( allocatable );
Appointment[] newAppointments = new Appointment[ appointments.length+ 1];
System.arraycopy(appointments,0, newAppointments, 0, appointments.length );
newAppointments[ appointments.length] = appointment;
if (event.getAppointmentList().size() > newAppointments.length ) {
event.setRestriction( allocatable, newAppointments );
} else {
event.setRestriction( allocatable, new Appointment[] {} );
}
}
}
@Deprecated
class AppointmentExceptionStorage extends OldEntityStorage<Appointment> {
public AppointmentExceptionStorage(RaplaContext context) throws RaplaException {
super(context,"APPOINTMENT_EXCEPTION",new String [] {"APPOINTMENT_ID INTEGER NOT NULL KEY","EXCEPTION_DATE DATETIME NOT NULL"});
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
Appointment appointment = resolveFromId( rset, 1, Appointment.class);
if ( appointment == null)
{
return;
}
Repeating repeating = appointment.getRepeating();
if ( repeating != null) {
Date date = getDate(rset,2 );
repeating.addException( date );
}
}
@Override
public void dropTable() throws SQLException {
super.dropTable();
}
}
@Deprecated
class DynamicTypeStorage extends RaplaTypeStorage<DynamicType> {
public DynamicTypeStorage(RaplaContext context) throws RaplaException {
super(context, DynamicType.TYPE,"DYNAMIC_TYPE", new String [] {"ID INTEGER NOT NULL PRIMARY KEY","TYPE_KEY VARCHAR(100) NOT NULL","DEFINITION TEXT NOT NULL"});
}
@Override
public void createOrUpdateIfNecessary(Map<String, TableDef> schema)
throws SQLException, RaplaException {
super.createOrUpdateIfNecessary(schema);
checkAndRetype(schema, "DEFINITION");
}
protected void load(ResultSet rset) throws SQLException,RaplaException {
String xml = getText(rset,3);
processXML( DynamicType.TYPE, xml );
}
}
@Deprecated
class PreferenceStorage extends RaplaTypeStorage<Preferences>
{
public PreferenceStorage(RaplaContext context) throws RaplaException {
super(context,Preferences.TYPE,"PREFERENCE",
new String [] {"USER_ID INTEGER KEY","ROLE VARCHAR(255) NOT NULL","STRING_VALUE VARCHAR(10000)","XML_VALUE TEXT"});
}
@Override
public void createOrUpdateIfNecessary(Map<String, TableDef> schema)
throws SQLException, RaplaException {
super.createOrUpdateIfNecessary(schema);
checkAndRetype(schema, "STRING_VALUE");
checkAndRetype(schema, "XML_VALUE");
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
//findPreferences
//check if value set
// yes read value
// no read xml
String userId = readId(rset, 1,User.class, true);
User owner ;
if ( userId == null || userId.equals(OldIdMapping.getId(User.TYPE, 0)) )
{
userId = null;
owner = null;
}
else
{
User user = entityStore.tryResolve( userId, User.class);
if ( user != null)
{
owner = user;
}
else
{
getLogger().warn("User with id " + userId + " not found ingnoring preference entry.");
return;
}
}
String configRole = getString( rset, 2, null);
String preferenceId = PreferencesImpl.getPreferenceIdFromUser(userId);
if ( configRole == null)
{
getLogger().warn("Configuration role for " + preferenceId + " is null. Ignoring preference entry.");
return;
}
String value = getString( rset,3, null);
// if (PreferencesImpl.isServerEntry(configRole))
// {
// entityStore.putServerPreferences(owner,configRole, value);
// return;
// }
PreferencesImpl preferences = preferenceId != null ? (PreferencesImpl) entityStore.tryResolve( preferenceId, Preferences.class ): null;
if ( preferences == null)
{
Date now =getCurrentTimestamp();
preferences = new PreferencesImpl(now,now);
preferences.setId(preferenceId);
preferences.setOwner(owner);
put( preferences );
}
if ( value!= null) {
preferences.putEntryPrivate(configRole, value);
} else {
String xml = getText(rset, 4);
if ( xml != null && xml.length() > 0)
{
PreferenceReader contentHandler = (PreferenceReader) processXML( Preferences.TYPE, xml );
RaplaObject type = contentHandler.getChildType();
preferences.putEntryPrivate(configRole, type);
}
}
}
}
@Deprecated
class UserStorage extends RaplaTypeStorage<User> {
UserGroupStorage groupStorage;
public UserStorage(RaplaContext context) throws RaplaException {
super( context,User.TYPE, "RAPLA_USER",
new String [] {"ID INTEGER NOT NULL PRIMARY KEY","USERNAME VARCHAR(100) NOT NULL","PASSWORD VARCHAR(100)","NAME VARCHAR(255) NOT NULL","EMAIL VARCHAR(255) NOT NULL","ISADMIN INTEGER NOT NULL"});
groupStorage = new UserGroupStorage( context );
addSubStorage( groupStorage );
}
@Override
public void createOrUpdateIfNecessary(Map<String, TableDef> schema) throws SQLException, RaplaException {
super.createOrUpdateIfNecessary(schema);
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
String userId = readId(rset,1, User.class );
String username = getString(rset,2, null);
if ( username == null)
{
getLogger().warn("Username is null for " + userId + " Ignoring user.");
}
String name = getString(rset,4,"");
String email = getString(rset,5,"");
boolean isAdmin = rset.getInt(6) == 1;
Date currentTimestamp = getCurrentTimestamp();
Date createDate = currentTimestamp;
Date lastChanged = currentTimestamp;
UserImpl user = new UserImpl(createDate, lastChanged);
user.setId( userId );
user.setUsername( username );
user.setName( name );
user.setEmail( email );
user.setAdmin( isAdmin );
String password = getString(rset,3, null);
if ( password != null) {
putPassword(userId,password);
}
put(user);
}
}
@Deprecated
class UserGroupStorage extends OldEntityStorage<User> {
public UserGroupStorage(RaplaContext context) throws RaplaException {
super(context,"RAPLA_USER_GROUP", new String [] {"USER_ID INTEGER NOT NULL KEY","CATEGORY_ID INTEGER NOT NULL"});
}
@Override
protected void load(ResultSet rset) throws SQLException, RaplaException {
User user = resolveFromId(rset, 1,User.class);
if ( user == null)
{
return;
}
Category category = resolveFromId(rset, 2, Category.class);
if ( category == null)
{
return;
}
user.addGroup( category);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbsql;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.rapla.entities.Entity;
import org.rapla.framework.RaplaException;
interface Storage<T extends Entity<T>> {
void loadAll() throws SQLException,RaplaException;
void deleteAll() throws SQLException;
void setConnection(Connection con) throws SQLException;
void save( Iterable<T> entities) throws SQLException,RaplaException ;
void insert( Iterable<T> entities) throws SQLException,RaplaException ;
// void update( Collection<Entity>> entities) throws SQLException,RaplaException ;
void deleteIds(Collection<String> ids) throws SQLException,RaplaException ;
public List<String> getCreateSQL();
void createOrUpdateIfNecessary( Map<String, TableDef> schema) throws SQLException, RaplaException;
void dropTable() throws SQLException;
}
| Java |
package org.rapla.storage.dbsql;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
public class TableDef
{
public TableDef(String table)
{
this.tablename = table;
}
Map<String,ColumnDef> columns = new LinkedHashMap<String,ColumnDef>();
String tablename;
public void addColumn(ColumnDef column)
{
columns.put( column.getName(), column);
}
public TableDef(String tablename, Collection<ColumnDef> columns) {
this.tablename = tablename;
for ( ColumnDef def: columns){
addColumn( def);
}
}
public ColumnDef getColumn(String name)
{
ColumnDef columnDef = columns.get( name.toUpperCase(Locale.ENGLISH));
return columnDef;
}
public String toString() {
return "TableDef [columns=" + columns + ", tablename=" + tablename + "]";
}
public void removeColumn(String oldColumnName)
{
columns.remove( oldColumnName);
}
} | Java |
package org.rapla.storage;
import org.rapla.entities.RaplaType;
import org.rapla.framework.RaplaException;
@Deprecated
public class OldIdMapping {
static public String getId(RaplaType type,String str) throws RaplaException {
if (str == null)
throw new RaplaException("Id string for " + type + " can't be null");
int index = str.lastIndexOf("_") + 1;
if (index>str.length())
throw new RaplaException("invalid rapla-id '" + str + "'");
try {
return getId(type,Integer.parseInt(str.substring(index)));
} catch (NumberFormatException ex) {
throw new RaplaException("invalid rapla-id '" + str + "'");
}
}
static public boolean isTextId( RaplaType type,String content )
{
if ( content == null)
{
return false;
}
content = content.trim();
if ( isNumeric( content))
{
return true;
}
String KEY_START = type.getLocalName() + "_";
boolean idContent = (content.indexOf( KEY_START ) >= 0 && content.length() > 0);
return idContent;
}
static private boolean isNumeric(String text)
{
int length = text.length();
if ( length == 0)
{
return false;
}
for ( int i=0;i<length;i++)
{
char ch = text.charAt(i);
if (!Character.isDigit(ch))
{
return false;
}
}
return true;
}
public static int parseId(String id) {
int indexOf = id.indexOf("_");
String keyPart = id.substring( indexOf + 1);
return Integer.parseInt(keyPart);
}
static public String getId(RaplaType type,int id)
{
return type.getLocalName() + "_" + id;
}
static public boolean isId( RaplaType type,Object object) {
if (object instanceof String)
{
return ((String)object).startsWith(type.getLocalName());
}
return false;
}
static public Integer getKey(RaplaType type,String id) {
String keyPart = id.substring(type.getLocalName().length()+1);
Integer key = Integer.parseInt( keyPart );
return key;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage;
import org.rapla.framework.RaplaException;
/** Imports the content of on store into another.
Export does an import with source and destination exchanged.
*/
public interface ImportExportManager {
void doImport() throws RaplaException;
void doExport() throws RaplaException;
CachableStorageOperator getSource() throws RaplaException;
CachableStorageOperator getDestination() throws RaplaException;
}
| Java |
package org.rapla.storage.dbrm;
import java.io.FileNotFoundException;
import java.lang.reflect.Method;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.rapla.entities.DependencyException;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaSynchronizationException;
import org.rapla.rest.client.HTTPJsonConnector;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.rest.gwtjsonrpc.common.JSONParserWrapper;
import org.rapla.rest.gwtjsonrpc.common.ResultImpl;
import org.rapla.rest.gwtjsonrpc.common.ResultType;
import org.rapla.storage.RaplaNewVersionException;
import org.rapla.storage.RaplaSecurityException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class RaplaHTTPConnector extends HTTPJsonConnector
{
//private String clientVersion;
public RaplaHTTPConnector() {
// clientVersion = i18n.getString("rapla.version");
}
private JsonArray serializeArguments(Class<?>[] parameterTypes, Object[] args)
{
final GsonBuilder gb = JSONParserWrapper.defaultGsonBuilder().disableHtmlEscaping();
JsonArray params = new JsonArray();
Gson serializer = gb.disableHtmlEscaping().create();
for ( int i=0;i< parameterTypes.length;i++)
{
Class<?> type = parameterTypes[i];
Object arg = args[i];
JsonElement jsonTree = serializer.toJsonTree(arg, type);
params.add( jsonTree);
}
return params;
}
private Gson createJsonMapper() {
Gson gson = JSONParserWrapper.defaultGsonBuilder().disableHtmlEscaping().create();
return gson;
}
private Object deserializeReturnValue(Class<?> returnType, JsonElement element) {
Gson gson = createJsonMapper();
Object result = gson.fromJson(element, returnType);
return result;
}
private List deserializeReturnList(Class<?> returnType, JsonArray list) {
Gson gson = createJsonMapper();
List<Object> result = new ArrayList<Object>();
for (JsonElement element:list )
{
Object obj = gson.fromJson(element, returnType);
result.add( obj);
}
return result;
}
private Set deserializeReturnSet(Class<?> returnType, JsonArray list) {
Gson gson = createJsonMapper();
Set<Object> result = new LinkedHashSet<Object>();
for (JsonElement element:list )
{
Object obj = gson.fromJson(element, returnType);
result.add( obj);
}
return result;
}
private Map deserializeReturnMap(Class<?> returnType, JsonObject map) {
Gson gson = createJsonMapper();
Map<String,Object> result = new LinkedHashMap<String,Object>();
for (Entry<String, JsonElement> entry:map.entrySet() )
{
String key = entry.getKey();
JsonElement element = entry.getValue();
Object obj = gson.fromJson(element, returnType);
result.put(key,obj);
}
return result;
}
private RaplaException deserializeExceptionObject(JsonObject result) {
JsonObject errorElement = result.getAsJsonObject("error");
JsonObject data = errorElement.getAsJsonObject("data");
JsonElement message = errorElement.get("message");
@SuppressWarnings("unused")
JsonElement code = errorElement.get("code");
if ( data != null)
{
JsonArray paramObj = (JsonArray) data.get("params");
JsonElement jsonElement = data.get("exception");
JsonElement stacktrace = data.get("stacktrace");
if ( jsonElement != null)
{
String classname = jsonElement.getAsString();
List<String> params = new ArrayList<String>();
if ( paramObj != null)
{
for ( JsonElement param:paramObj)
{
params.add(param.toString());
}
}
RaplaException ex = deserializeException(classname, message.toString(), params);
try
{
if ( stacktrace != null)
{
List<StackTraceElement> trace = new ArrayList<StackTraceElement>();
for (JsonElement element:stacktrace.getAsJsonArray())
{
StackTraceElement ste = createJsonMapper().fromJson( element, StackTraceElement.class);
trace.add( ste);
}
ex.setStackTrace( trace.toArray( new StackTraceElement[] {}));
}
}
catch (Exception ex3)
{
// Can't get stacktrace
}
return ex;
}
}
return new RaplaException( message.toString());
}
private JsonObject sendCall_(String requestMethod, URL methodURL, JsonElement jsonObject, String authenticationToken) throws Exception
{
try
{
return sendCall(requestMethod, methodURL, jsonObject, authenticationToken);
}
catch (SocketException ex)
{
throw new RaplaConnectException( ex);
}
catch (UnknownHostException ex)
{
throw new RaplaConnectException( ex);
}
catch (FileNotFoundException ex)
{
throw new RaplaConnectException( ex);
}
}
public FutureResult call(Class<?> service, String methodName, Object[] args,final RemoteConnectionInfo serverInfo) throws Exception
{
String serviceUrl =service.getName();
Method method = findMethod(service, methodName);
String serverURL = serverInfo.getServerURL();
if ( !serverURL.endsWith("/"))
{
serverURL+="/";
}
URL baseUrl = new URL(serverURL);
URL methodURL = new URL(baseUrl,"rapla/json/" + serviceUrl );
boolean loginCmd = methodURL.getPath().endsWith("login") || methodName.contains("login");
JsonObject element = serializeCall(method, args);
FutureResult<String> authExpiredCommand = serverInfo.getReAuthenticateCommand();
String accessToken = loginCmd ? null: serverInfo.getAccessToken();
JsonObject resultMessage = sendCall_("POST",methodURL, element, accessToken);
JsonElement errorElement = resultMessage.get("error");
if ( errorElement != null)
{
RaplaException ex = deserializeExceptionObject(resultMessage);
// if authorization expired
String message = ex.getMessage();
boolean b = message != null && message.indexOf( RemoteStorage.USER_WAS_NOT_AUTHENTIFIED)>=0 && !loginCmd;
if ( !b || authExpiredCommand == null )
{
throw ex;
}
// try to get a new one
String newAuthCode;
try {
newAuthCode = authExpiredCommand.get();
} catch (RaplaException e) {
throw e;
} catch (Exception e)
{
throw new RaplaException(e.getMessage(), e);
}
// try the same call again with the new result, this time with no auth code failed fallback
resultMessage = sendCall_( "POST", methodURL, element, newAuthCode);
}
JsonElement resultElement = resultMessage.get("result");
Class resultType;
Object resultObject;
ResultType resultTypeAnnotation = method.getAnnotation(ResultType.class);
if ( resultTypeAnnotation != null)
{
resultType = resultTypeAnnotation.value();
Class container = resultTypeAnnotation.container();
if ( List.class.equals(container) )
{
if ( !resultElement.isJsonArray())
{
throw new RaplaException("Array expected as json result in " + service + "." + methodName);
}
resultObject = deserializeReturnList(resultType, resultElement.getAsJsonArray());
}
else if ( Set.class.equals(container) )
{
if ( !resultElement.isJsonArray())
{
throw new RaplaException("Array expected as json result in " + service + "." + methodName);
}
resultObject = deserializeReturnSet(resultType, resultElement.getAsJsonArray());
}
else if ( Map.class.equals( container) )
{
if ( !resultElement.isJsonObject())
{
throw new RaplaException("JsonObject expected as json result in " + service + "." + methodName);
}
resultObject = deserializeReturnMap(resultType, resultElement.getAsJsonObject());
}
else if ( Object.class.equals( container) )
{
resultObject = deserializeReturnValue(resultType, resultElement);
}
else
{
throw new RaplaException("Array expected as json result in " + service + "." + methodName);
}
}
else
{
resultType = method.getReturnType();
resultObject = deserializeReturnValue(resultType, resultElement);
}
@SuppressWarnings("unchecked")
ResultImpl result = new ResultImpl(resultObject);
return result;
}
public Method findMethod(Class<?> service, String methodName) throws RaplaException {
Method method = null;
for (Method m:service.getMethods())
{
if ( m.getName().equals( methodName))
{
method = m;
}
}
if ( method == null)
{
throw new RaplaException("Method "+ methodName + " not found in " + service.getClass() );
}
return method;
}
public JsonObject serializeCall(Method method, Object[] args) {
Class<?>[] parameterTypes = method.getParameterTypes();
JsonElement params = serializeArguments(parameterTypes, args);
JsonObject element = new JsonObject();
element.addProperty("jsonrpc", "2.0");
element.addProperty("method", method.getName());
element.add("params",params);
element.addProperty("id", "1");
return element;
}
public RaplaException deserializeException(String classname, String message, List<String> params)
{
String error = "";
if ( message != null)
{
error+=message;
}
if ( classname != null)
{
if ( classname.equals( WrongRaplaVersionException.class.getName()))
{
return new WrongRaplaVersionException( message);
}
else if ( classname.equals(RaplaNewVersionException.class.getName()))
{
return new RaplaNewVersionException( message);
}
else if ( classname.equals( RaplaSecurityException.class.getName()))
{
return new RaplaSecurityException( message);
}
else if ( classname.equals( RaplaSynchronizationException.class.getName()))
{
return new RaplaSynchronizationException( message);
}
else if ( classname.equals( RaplaConnectException.class.getName()))
{
return new RaplaConnectException( message);
}
else if ( classname.equals( EntityNotFoundException.class.getName()))
{
// if ( param != null)
// {
// String id = (String)convertFromString( String.class, param);
// return new EntityNotFoundException( message, id);
// }
return new EntityNotFoundException( message);
}
else if ( classname.equals( DependencyException.class.getName()))
{
if ( params != null)
{
return new DependencyException( message,params);
}
//Collection<String> depList = Collections.emptyList();
return new DependencyException( message, new String[] {});
}
else
{
error = classname + " " + error;
}
}
return new RaplaException( error);
}
// private void addParams(Appendable writer, Map<String,String> args ) throws IOException
// {
// writer.append( "v="+URLEncoder.encode(clientVersion,"utf-8"));
// for (Iterator<String> it = args.keySet().iterator();it.hasNext();)
// {
// writer.append( "&");
// String key = it.next();
// String value= args.get( key);
// {
// String pair = key;
// writer.append( pair);
// if ( value != null)
// {
// writer.append("="+ URLEncoder.encode(value,"utf-8"));
// }
// }
//
// }
// }
}
| Java |
package org.rapla.storage.dbrm;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
public class RemoteConnectionInfo
{
String accessToken;
FutureResult<String> reAuthenticateCommand;
String serverURL;
StatusUpdater statusUpdater;
public void setStatusUpdater(StatusUpdater statusUpdater) {
this.statusUpdater = statusUpdater;
}
public StatusUpdater getStatusUpdater() {
return statusUpdater;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public void setServerURL(String serverURL) {
this.serverURL = serverURL;
}
public String get()
{
return serverURL;
}
public void setReAuthenticateCommand(FutureResult<String> reAuthenticateCommand) {
this.reAuthenticateCommand = reAuthenticateCommand;
}
public String getRefreshToken() throws Exception {
return reAuthenticateCommand.get();
}
public FutureResult<String> getReAuthenticateCommand()
{
return reAuthenticateCommand;
}
public String getAccessToken() {
return accessToken;
}
public String getServerURL() {
return serverURL;
}
} | Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 ?, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbrm;
import javax.jws.WebParam;
import javax.jws.WebService;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.rest.gwtjsonrpc.common.RemoteJsonService;
import org.rapla.rest.gwtjsonrpc.common.ResultType;
import org.rapla.rest.gwtjsonrpc.common.VoidResult;
@WebService
public interface RemoteServer extends RemoteJsonService {
@ResultType(LoginTokens.class)
FutureResult<LoginTokens> login(@WebParam(name="username") String username,@WebParam(name="password") String password,@WebParam(name="connectAs") String connectAs);
@ResultType(LoginTokens.class)
FutureResult<LoginTokens> auth(@WebParam(name="credentials") LoginCredentials credentials);
@ResultType(VoidResult.class)
FutureResult<VoidResult> logout();
@ResultType(String.class)
FutureResult<String> getRefreshToken();
@ResultType(String.class)
FutureResult<String> regenerateRefreshToken();
@ResultType(String.class)
FutureResult<LoginTokens> refresh(@WebParam(name="refreshToken") String refreshToken);
void setConnectInfo(RemoteConnectionInfo info);
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Praktikum Gruppe2?, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbrm;
import org.rapla.framework.RaplaException;
public interface RestartServer
{
public void restartServer() throws RaplaException;
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 ?, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbrm;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.jws.WebParam;
import javax.jws.WebService;
import org.rapla.entities.domain.internal.AppointmentImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.facade.internal.ConflictImpl;
import org.rapla.framework.RaplaException;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.rest.gwtjsonrpc.common.RemoteJsonService;
import org.rapla.rest.gwtjsonrpc.common.ResultType;
import org.rapla.rest.gwtjsonrpc.common.VoidResult;
import org.rapla.storage.UpdateEvent;
@WebService
public interface RemoteStorage extends RemoteJsonService {
final String USER_WAS_NOT_AUTHENTIFIED = "User was not authentified";
@ResultType(String.class)
FutureResult<String> canChangePassword();
@ResultType(VoidResult.class)
FutureResult<VoidResult> changePassword(String username,String oldPassword,String newPassword);
@ResultType(VoidResult.class)
FutureResult<VoidResult> changeName(String username, String newTitle,String newSurename,String newLastname);
@ResultType(VoidResult.class)
FutureResult<VoidResult> changeEmail(String username,String newEmail);
@ResultType(VoidResult.class)
FutureResult<VoidResult> confirmEmail(String username,String newEmail);
@ResultType(UpdateEvent.class)
FutureResult<UpdateEvent> getResources() throws RaplaException;
/** delegates the corresponding method in the StorageOperator.
* @param annotationQuery */
@ResultType(value=ReservationImpl.class,container=List.class)
FutureResult<List<ReservationImpl>> getReservations(@WebParam(name="resources")String[] allocatableIds,@WebParam(name="start")Date start,@WebParam(name="end")Date end, @WebParam(name="annotations")Map<String, String> annotationQuery);
@ResultType(UpdateEvent.class)
FutureResult<UpdateEvent> getEntityRecursive(String... id);
@ResultType(UpdateEvent.class)
FutureResult<UpdateEvent> refresh(String clientRepoVersion);
@ResultType(VoidResult.class)
FutureResult<VoidResult> restartServer();
@ResultType(UpdateEvent.class)
FutureResult<UpdateEvent> dispatch(UpdateEvent event);
@ResultType(value=String.class,container=List.class)
FutureResult<List<String>> getTemplateNames();
@ResultType(value=String.class,container=List.class)
FutureResult<List<String>> createIdentifier(String raplaType, int count);
@ResultType(value=ConflictImpl.class,container=List.class)
FutureResult<List<ConflictImpl>> getConflicts();
@ResultType(BindingMap.class)
FutureResult<BindingMap> getFirstAllocatableBindings(String[] allocatableIds, List<AppointmentImpl> appointments, String[] reservationIds);
@ResultType(value=ReservationImpl.class,container=List.class)
FutureResult<List<ReservationImpl>> getAllAllocatableBindings(String[] allocatables, List<AppointmentImpl> appointments, String[] reservationIds);
@ResultType(Date.class)
FutureResult<Date> getNextAllocatableDate(String[] allocatableIds, AppointmentImpl appointment,String[] reservationIds, Integer worktimeStartMinutes, Integer worktimeEndMinutes, Integer[] excludedDays, Integer rowsPerHour);
//void logEntityNotFound(String logMessage,String... referencedIds) throws RaplaException;
public static class BindingMap
{
Map<String,List<String>> bindings;
BindingMap() {
}
public BindingMap(Map<String,List<String>> bindings)
{
this.bindings = bindings;
}
public Map<String,List<String>> get() {
return bindings;
}
}
void setConnectInfo(RemoteConnectionInfo info);
}
| Java |
package org.rapla.storage.dbrm;
public class LoginCredentials {
private String username;
private String password;
private String connectAs;
public LoginCredentials(String username, String password, String connectAs) {
super();
this.username = username;
this.password = password;
this.connectAs = connectAs;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getConnectAs() {
return connectAs;
}
}
| Java |
package org.rapla.storage.dbrm;
import java.util.Date;
public class LoginTokens {
String accessToken;
Date validUntil;
@SuppressWarnings("unused")
private LoginTokens() {
}
public LoginTokens(String accessToken, Date validUntil) {
this.accessToken = accessToken;
this.validUntil = validUntil;
}
public String getAccessToken()
{
return accessToken;
}
public Date getValidUntil()
{
return validUntil;
}
}
| Java |
package org.rapla.storage.dbrm;
public interface StatusUpdater {
enum Status
{
READY,
BUSY
}
void setStatus( Status status);
}
| Java |
package org.rapla.storage.dbrm;
import org.rapla.framework.RaplaException;
public class RaplaConnectException extends RaplaException {
private static final long serialVersionUID = 1L;
public RaplaConnectException(String text) {
super(text, null);
}
public RaplaConnectException( Throwable cause) {
super(cause.getMessage(), cause);
}
}
| Java |
package org.rapla.storage.dbrm;
import org.rapla.framework.RaplaException;
public class WrongRaplaVersionException extends RaplaException {
private static final long serialVersionUID = 1L;
public WrongRaplaVersionException(String text) {
super(text);
}
}
| Java |
package org.rapla.storage.dbrm;
public class RaplaRestartingException extends RaplaConnectException {
private static final long serialVersionUID = 1L;
public RaplaRestartingException() {
super("Connection to server aborted. Restarting client.");
}
}
| Java |
package org.rapla.storage.dbrm;
import org.rapla.framework.RaplaContextException;
public interface RemoteMethodStub {
<T> T getWebserviceLocalStub(Class<T> role) throws RaplaContextException;
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbrm;
import org.rapla.framework.RaplaContextException;
/** provides a mechanism to invoke a remote service on the server.
* The server must provide a RemoteService for the specified serviceName.
* The RemoteOperator provides the Service RemoteServiceCaller
* @request the webservices in the constructor instead. see RemoteOperator for an example*/
public interface RemoteServiceCaller {
<T> T getRemoteMethod(Class<T> a ) throws RaplaContextException;
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.dbrm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.locks.Lock;
import org.rapla.ConnectInfo;
import org.rapla.components.util.Assert;
import org.rapla.components.util.Cancelable;
import org.rapla.components.util.Command;
import org.rapla.components.util.CommandScheduler;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.components.util.TimeInterval;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentStartComparator;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.domain.internal.AppointmentImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.storage.EntityResolver;
import org.rapla.facade.Conflict;
import org.rapla.facade.UpdateModule;
import org.rapla.facade.internal.ConflictImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.Disposable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.internal.ContextTools;
import org.rapla.framework.logger.Logger;
import org.rapla.rest.gwtjsonrpc.common.AsyncCallback;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.storage.RaplaSecurityException;
import org.rapla.storage.UpdateEvent;
import org.rapla.storage.UpdateResult;
import org.rapla.storage.impl.AbstractCachableOperator;
/** This operator can be used to modify and access data over the
* network. It needs an server-process providing the StorageService
* (usually this is the default rapla-server).
* <p>Sample configuration:
<pre>
<remote-storage id="web">
</remote-storate>
</pre>
*/
public class RemoteOperator extends AbstractCachableOperator implements RestartServer,Disposable
{
private boolean bSessionActive = false;
String userId;
RemoteServer remoteServer;
RemoteStorage remoteStorage;
protected CommandScheduler commandQueue;
Date lastSyncedTimeLocal;
Date lastSyncedTime;
int timezoneOffset;
ConnectInfo connectInfo;
Configuration config;
RemoteConnectionInfo connectionInfo;
public RemoteOperator(RaplaContext context, Logger logger, Configuration config, RemoteServer remoteServer, RemoteStorage remoteStorage) throws RaplaException {
super( context, logger );
this.config = config;
this.remoteServer = remoteServer;
this.remoteStorage = remoteStorage;
commandQueue = context.lookup( CommandScheduler.class);
this.connectionInfo = new RemoteConnectionInfo();
remoteStorage.setConnectInfo( connectionInfo );
remoteServer.setConnectInfo( connectionInfo );
if ( config != null)
{
String serverConfig = config.getChild("server").getValue("${downloadServer}");
final String serverURL= ContextTools.resolveContext(serverConfig, context );
connectionInfo.setServerURL(serverURL);
}
}
public RemoteConnectionInfo getRemoteConnectionInfo()
{
return connectionInfo;
}
synchronized public User connect(ConnectInfo connectInfo) throws RaplaException {
if ( connectInfo == null)
{
throw new RaplaException("RemoteOperator doesn't support anonymous connect");
}
if (isConnected())
return null;
getLogger().info("Connecting to server and starting login..");
Lock writeLock = writeLock();
try
{
User user = loginAndLoadData(connectInfo);
connectionInfo.setReAuthenticateCommand(new FutureResult<String>() {
@Override
public String get() throws Exception {
getLogger().info("Refreshing access token.");
return loginWithoutDisconnect();
}
@Override
public String get(long wait) throws Exception {
return get();
}
@Override
public void get(AsyncCallback<String> callback) {
try {
String string = get();
callback.onSuccess(string);
} catch (Exception e) {
callback.onFailure(e);
}
}
});
initRefresh();
return user;
}
finally
{
unlock(writeLock);
}
}
private User loginAndLoadData(ConnectInfo connectInfo) throws RaplaException {
this.connectInfo = connectInfo;
String username = this.connectInfo.getUsername();
login();
getLogger().info("login successfull");
User user = loadData(username);
bSessionActive = true;
return user;
}
protected String login() throws RaplaException {
try {
return loginWithoutDisconnect();
} catch (RaplaException ex){
disconnect();
throw ex;
} catch (Exception ex){
disconnect();
throw new RaplaException(ex);
}
}
private String loginWithoutDisconnect() throws Exception, RaplaSecurityException {
String connectAs = this.connectInfo.getConnectAs();
String password = new String( this.connectInfo.getPassword());
String username = this.connectInfo.getUsername();
RemoteServer serv1 = getRemoteServer();
LoginTokens loginToken = serv1.login(username,password, connectAs).get();
String accessToken = loginToken.getAccessToken();
if ( accessToken != null)
{
connectionInfo.setAccessToken( accessToken);
return accessToken;
}
else
{
throw new RaplaSecurityException("Invalid Access token");
}
}
public Date getCurrentTimestamp() {
if (lastSyncedTime == null)
{
return new Date(System.currentTimeMillis());
}
// no matter what the client clock says we always sync to the server clock
long passedMillis = System.currentTimeMillis()- lastSyncedTimeLocal.getTime();
if ( passedMillis < 0)
{
passedMillis = 0;
}
long correctTime = this.lastSyncedTime.getTime() + passedMillis;
Date date = new Date(correctTime);
return date;
}
public Date today() {
long time = getCurrentTimestamp().getTime();
Date raplaTime = new Date(time + timezoneOffset);
return DateTools.cutDate( raplaTime);
}
Cancelable timerTask;
int intervalLength;
private final void initRefresh()
{
Command refreshTask = new Command() {
public void execute() {
try {
// test if the remote operator is writable
// if not we skip until the next update cycle
Lock writeLock = lock.writeLock();
boolean tryLock = writeLock.tryLock();
if ( tryLock)
{
writeLock.unlock();
}
if (isConnected() && tryLock) {
refresh();
}
} catch (RaplaConnectException e) {
getLogger().error("Error connecting " + e.getMessage());
} catch (RaplaException e) {
getLogger().error("Error refreshing.", e);
}
}
};
intervalLength = UpdateModule.REFRESH_INTERVAL_DEFAULT;
if (isConnected()) {
try {
intervalLength = getPreferences(null, true).getEntryAsInteger(UpdateModule.REFRESH_INTERVAL_ENTRY, UpdateModule.REFRESH_INTERVAL_DEFAULT);
} catch (RaplaException e) {
getLogger().error("Error refreshing.", e);
}
}
if ( timerTask != null)
{
timerTask.cancel();
}
timerTask = commandQueue.schedule(refreshTask, 0, intervalLength);
}
public void dispose()
{
if ( timerTask != null)
{
timerTask.cancel();
}
}
// public String getConnectionName() {
// if ( connector != null)
// {
// return connector.getInfo();
// }
// else
// {
// return "standalone";
// }
// }
//
// private void doConnect() throws RaplaException {
// boolean bFailed = true;
// try {
// bFailed = false;
// } catch (Exception e) {
// throw new RaplaException(i18n.format("error.connect",getConnectionName()),e);
// } finally {
// if (bFailed)
// disconnect();
// }
// }
public boolean isConnected() {
return bSessionActive;
}
public boolean supportsActiveMonitoring() {
return true;
}
synchronized public void refresh() throws RaplaException {
String clientRepoVersion = getClientRepoVersion();
RemoteStorage serv = getRemoteStorage();
try
{
UpdateEvent evt = serv.refresh( clientRepoVersion).get();
refresh( evt);
}
catch (EntityNotFoundException ex)
{
getLogger().error("Refreshing all resources due to " + ex.getMessage(), ex);
refreshAll();
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
private String getClientRepoVersion() {
return SerializableDateTimeFormat.INSTANCE.formatTimestamp(lastSyncedTime);
}
synchronized public void restartServer() throws RaplaException {
getLogger().info("Restart in progress ...");
String message = i18n.getString("restart_server");
// isRestarting = true;
try
{
RemoteStorage serv = getRemoteStorage();
serv.restartServer().get();
fireStorageDisconnected(message);
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
synchronized public void disconnect() throws RaplaException {
connectionInfo.setAccessToken( null);
this.connectInfo = null;
connectionInfo.setReAuthenticateCommand(null);
disconnect("Disconnection from Server initiated");
}
/** disconnect from the server */
synchronized public void disconnect(String message) throws RaplaException {
boolean wasConnected = bSessionActive;
getLogger().info("Disconnecting from server");
try {
bSessionActive = false;
cache.clearAll();
} catch (Exception e) {
throw new RaplaException("Could not disconnect", e);
}
if ( wasConnected)
{
RemoteServer serv1 = getRemoteServer();
try
{
serv1.logout().get();
}
catch (RaplaConnectException ex)
{
getLogger().warn( ex.getMessage());
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
fireStorageDisconnected(message);
}
}
@Override
protected void setResolver(Collection<? extends Entity> entities) throws RaplaException {
// don't resolve entities in standalone mode
if (context.has(RemoteMethodStub.class))
{
return;
}
super.setResolver(entities);
}
@Override
protected void testResolve(Collection<? extends Entity> entities) throws EntityNotFoundException {
// don't resolve entities in standalone mode
if (context.has(RemoteMethodStub.class))
{
return;
}
super.testResolve(entities);
}
private User loadData(String username) throws RaplaException {
getLogger().debug("Getting Data..");
RemoteStorage serv = getRemoteStorage();
try
{
UpdateEvent evt = serv.getResources().get();
this.userId = evt.getUserId();
if ( userId != null)
{
cache.setClientUserId( userId);
}
updateTimestamps(evt);
Collection<Entity> storeObjects = evt.getStoreObjects();
cache.clearAll();
testResolve( storeObjects);
setResolver( storeObjects );
for( Entity entity:storeObjects)
{
cache.put(entity);
}
getLogger().debug("Data flushed");
if ( username != null)
{
if ( userId == null)
{
throw new EntityNotFoundException("User with username "+ username + " not found in result");
}
User user = cache.resolve( userId, User.class);
return user;
}
else
{
return null;
}
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
public void updateTimestamps(UpdateEvent evt) throws RaplaException {
if ( evt.getLastValidated() == null)
{
throw new RaplaException("Server sync time is missing");
}
lastSyncedTimeLocal = new Date(System.currentTimeMillis());
lastSyncedTime = evt.getLastValidated();
timezoneOffset = evt.getTimezoneOffset();
//long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time);
}
protected void checkConnected() throws RaplaException {
if ( !bSessionActive ) {
throw new RaplaException("Not logged in or connection closed!");
}
}
public void dispatch(UpdateEvent evt) throws RaplaException {
checkConnected();
// Store on server
if (getLogger().isDebugEnabled()) {
Iterator<Entity>it =evt.getStoreObjects().iterator();
while (it.hasNext()) {
Entity entity = it.next();
getLogger().debug("dispatching store for: " + entity);
}
it =evt.getRemoveObjects().iterator();
while (it.hasNext()) {
Entity entity = it.next();
getLogger().debug("dispatching remove for: " + entity);
}
}
RemoteStorage serv = getRemoteStorage();
evt.setLastValidated(lastSyncedTime);
try
{
UpdateEvent serverClosure =serv.dispatch( evt ).get();
refresh(serverClosure);
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
public String[] createIdentifier(RaplaType raplaType, int count) throws RaplaException {
RemoteStorage serv = getRemoteStorage();
try
{
List<String> id = serv.createIdentifier(raplaType.getLocalName(), count).get();
return id.toArray(new String[] {});
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
private RemoteStorage getRemoteStorage() {
return remoteStorage;
}
private RemoteServer getRemoteServer() {
return remoteServer;
}
public boolean canChangePassword() throws RaplaException {
RemoteStorage remoteMethod = getRemoteStorage();
try
{
String canChangePassword = remoteMethod.canChangePassword().get();
boolean result = canChangePassword != null && canChangePassword.equalsIgnoreCase("true");
return result;
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
@Override
public void changePassword(User user,char[] oldPassword,char[] newPassword) throws RaplaException {
try {
RemoteStorage remoteMethod = getRemoteStorage();
String username = user.getUsername();
remoteMethod.changePassword(username, new String(oldPassword),new String(newPassword)).get();
refresh();
}
catch (RaplaSecurityException ex)
{
throw new RaplaSecurityException(i18n.getString("error.wrong_password"));
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
@Override
public void changeEmail(User user, String newEmail) throws RaplaException
{
try
{
RemoteStorage remoteMethod = getRemoteStorage();
String username = user.getUsername();
remoteMethod.changeEmail(username,newEmail).get();
refresh();
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
@Override
public void confirmEmail(User user, String newEmail) throws RaplaException
{
try
{
RemoteStorage remoteMethod = getRemoteStorage();
String username = user.getUsername();
remoteMethod.confirmEmail(username,newEmail).get();
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
@Override
public void changeName(User user, String newTitle, String newFirstname, String newSurname) throws RaplaException
{
try
{
RemoteStorage remoteMethod = getRemoteStorage();
String username = user.getUsername();
remoteMethod.changeName(username,newTitle, newFirstname, newSurname).get();
refresh();
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
public Map<String,Entity> getFromId(Collection<String> idSet, boolean throwEntityNotFound) throws RaplaException
{
RemoteStorage serv = getRemoteStorage();
String[] array = idSet.toArray(new String[] {});
Map<String,Entity> result = new HashMap<String,Entity>();
try
{
UpdateEvent entityList = serv.getEntityRecursive( array).get();
Collection<Entity> list = entityList.getStoreObjects();
Lock lock = readLock();
try
{
testResolve( list);
setResolver( list );
}
finally
{
unlock(lock);
}
for (Entity entity:list)
{
String id = entity.getId();
if ( idSet.contains( id ))
{
result.put( id, entity);
}
}
}
catch (EntityNotFoundException ex)
{
if ( throwEntityNotFound)
{
throw ex;
}
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
return result;
}
@Override
protected <T extends Entity> T tryResolve(EntityResolver resolver,String id,Class<T> entityClass) {
Assert.notNull( id);
T entity = super.tryResolve(resolver,id, entityClass);
if ( entity != null)
{
return entity;
}
if ( entityClass != null && Allocatable.class.isAssignableFrom(entityClass))
{
AllocatableImpl unresolved = new AllocatableImpl(null, null);
unresolved.setId( id);
unresolved.setClassification( getDynamicType(UNRESOLVED_RESOURCE_TYPE).newClassification());
@SuppressWarnings("unchecked")
T casted = (T) unresolved;
return casted;
}
return null;
}
public List<Reservation> getReservations(User user,Collection<Allocatable> allocatables,Date start,Date end,ClassificationFilter[] filters, Map<String,String> annotationQuery) throws RaplaException {
RemoteStorage serv = getRemoteStorage();
// if a refresh is due, we assume the system went to sleep so we refresh before we continue
if ( intervalLength > 0 && lastSyncedTime != null && (lastSyncedTime.getTime() + intervalLength * 2) < getCurrentTimestamp().getTime())
{
getLogger().info("cache not uptodate. Refreshing first.");
refresh();
}
String[] allocatableId = getIdList(allocatables);
try
{
List<ReservationImpl> list =serv.getReservations(allocatableId,start, end, annotationQuery).get();
Lock lock = readLock();
try
{
testResolve( list);
setResolver( list );
}
finally
{
unlock(lock);
}
List<Reservation> result = new ArrayList<Reservation>();
Iterator it = list.iterator();
while ( it.hasNext())
{
Object object = it.next();
Reservation next = (Reservation)object;
result.add( next);
}
removeFilteredClassifications(result, filters);
return result;
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
public List<String> getTemplateNames() throws RaplaException {
checkConnected();
RemoteStorage serv = getRemoteStorage();
try
{
List<String> result = serv.getTemplateNames().get();
return result;
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
protected String[] getIdList(Collection<? extends Entity> entities) {
List<String> idList = new ArrayList<String>();
if ( entities != null )
{
for ( Entity entity:entities)
{
if (entity != null)
idList.add( ((Entity)entity).getId().toString());
}
}
String[] ids = idList.toArray(new String[] {});
return ids;
}
synchronized private void refresh(UpdateEvent evt) throws RaplaException
{
updateTimestamps(evt);
if ( evt.isNeedResourcesRefresh())
{
refreshAll();
return;
}
UpdateResult result = null;
testResolve(evt.getStoreObjects());
setResolver(evt.getStoreObjects());
// we don't test the references of the removed objects
setResolver(evt.getRemoveObjects());
if ( bSessionActive && !evt.isEmpty() )
{
getLogger().debug("Objects updated!");
Lock writeLock = writeLock();
try
{
result = update(evt);
}
finally
{
unlock(writeLock);
}
}
if ( result != null && !result.isEmpty())
{
fireStorageUpdated(result);
}
}
protected void refreshAll() throws RaplaException,EntityNotFoundException {
UpdateResult result;
Collection<Entity> oldEntities;
Lock readLock = readLock();
try
{
User user = cache.resolve( userId, User.class);
oldEntities = cache.getVisibleEntities(user);
}
finally
{
unlock(readLock);
}
Lock writeLock = writeLock();
try
{
loadData(null);
}
finally
{
unlock(writeLock);
}
Collection<Entity> newEntities;
readLock = readLock();
try
{
User user = cache.resolve( userId, User.class);
newEntities = cache.getVisibleEntities(user);
}
finally
{
unlock(readLock);
}
HashSet<Entity> updated = new HashSet<Entity>(newEntities);
Set<Entity> toRemove = new HashSet<Entity>(oldEntities);
Set<Entity> toUpdate = new HashSet<Entity>(oldEntities);
toRemove.removeAll(newEntities);
updated.removeAll( toRemove);
toUpdate.retainAll(newEntities);
HashMap<Entity,Entity> oldEntityMap = new HashMap<Entity,Entity>();
for ( Entity update: toUpdate)
{
@SuppressWarnings("unchecked")
Class<? extends Entity> typeClass = update.getRaplaType().getTypeClass();
Entity newEntity = cache.tryResolve( update.getId(), typeClass);
if ( newEntity != null)
{
oldEntityMap.put( newEntity, update);
}
}
TimeInterval invalidateInterval = new TimeInterval( null,null);
result = createUpdateResult(oldEntityMap, updated, toRemove, invalidateInterval, userId);
fireStorageUpdated(result);
}
@Override
public Map<Allocatable, Collection<Appointment>> getFirstAllocatableBindings( Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException {
checkConnected();
RemoteStorage serv = getRemoteStorage();
String[] allocatableIds = getIdList(allocatables);
//AppointmentImpl[] appointmentArray = appointments.toArray( new AppointmentImpl[appointments.size()]);
String[] reservationIds = getIdList(ignoreList);
List<AppointmentImpl> appointmentList = new ArrayList<AppointmentImpl>();
Map<String,Appointment> appointmentMap= new HashMap<String,Appointment>();
for ( Appointment app: appointments)
{
appointmentList.add( (AppointmentImpl) app);
appointmentMap.put( app.getId(), app);
}
try
{
Map<String, List<String>> resultMap = serv.getFirstAllocatableBindings(allocatableIds, appointmentList, reservationIds).get().get();
HashMap<Allocatable, Collection<Appointment>> result = new HashMap<Allocatable, Collection<Appointment>>();
for ( Allocatable alloc:allocatables)
{
List<String> list = resultMap.get( alloc.getId());
if ( list != null)
{
Collection<Appointment> appointmentBinding = new ArrayList<Appointment>();
for ( String id:list)
{
Appointment e = appointmentMap.get( id);
if ( e != null)
{
appointmentBinding.add( e);
}
}
result.put( alloc, appointmentBinding);
}
}
return result;
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
@Override
public Map<Allocatable, Map<Appointment, Collection<Appointment>>> getAllAllocatableBindings( Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException {
checkConnected();
RemoteStorage serv = getRemoteStorage();
String[] allocatableIds = getIdList(allocatables);
List<AppointmentImpl> appointmentArray = Arrays.asList(appointments.toArray( new AppointmentImpl[]{}));
String[] reservationIds = getIdList(ignoreList);
List<ReservationImpl> serverResult;
try
{
serverResult = serv.getAllAllocatableBindings(allocatableIds, appointmentArray, reservationIds).get();
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
testResolve( serverResult);
setResolver( serverResult );
SortedSet<Appointment> allAppointments = new TreeSet<Appointment>(new AppointmentStartComparator());
for ( ReservationImpl reservation: serverResult)
{
allAppointments.addAll(reservation.getAppointmentList());
}
Map<Allocatable, Map<Appointment,Collection<Appointment>>> result = new HashMap<Allocatable, Map<Appointment,Collection<Appointment>>>();
for ( Allocatable alloc:allocatables)
{
Map<Appointment,Collection<Appointment>> appointmentBinding = new HashMap<Appointment, Collection<Appointment>>();
for (Appointment appointment: appointments)
{
SortedSet<Appointment> appointmentSet = getAppointments(alloc, allAppointments );
boolean onlyFirstConflictingAppointment = false;
Set<Appointment> conflictingAppointments = AppointmentImpl.getConflictingAppointments(appointmentSet, appointment, ignoreList, onlyFirstConflictingAppointment);
appointmentBinding.put( appointment, conflictingAppointments);
}
result.put( alloc, appointmentBinding);
}
return result;
}
@Override
public Date getNextAllocatableDate(Collection<Allocatable> allocatables,Appointment appointment, Collection<Reservation> ignoreList, Integer worktimeStartMinutes,Integer worktimeEndMinutes, Integer[] excludedDays, Integer rowsPerHour) throws RaplaException
{
checkConnected();
RemoteStorage serv = getRemoteStorage();
String[] allocatableIds = getIdList(allocatables);
String[] reservationIds = getIdList(ignoreList);
try
{
Date result = serv.getNextAllocatableDate(allocatableIds, (AppointmentImpl)appointment, reservationIds, worktimeStartMinutes, worktimeEndMinutes, excludedDays, rowsPerHour).get();
return result;
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
static private SortedSet<Appointment> getAppointments(Allocatable alloc, SortedSet<Appointment> allAppointments)
{
SortedSet<Appointment> result = new TreeSet<Appointment>(new AppointmentStartComparator());
for ( Appointment appointment:allAppointments)
{
Reservation reservation = appointment.getReservation();
if ( reservation.hasAllocated( alloc, appointment))
{
result.add( appointment);
}
}
return result;
}
@Override
public Collection<Conflict> getConflicts(User user) throws RaplaException {
checkConnected();
RemoteStorage serv = getRemoteStorage();
try
{
List<ConflictImpl> list = serv.getConflicts().get();
testResolve( list);
setResolver( list);
List<Conflict> result = new ArrayList<Conflict>();
Iterator it = list.iterator();
while ( it.hasNext())
{
Object object = it.next();
if ( object instanceof Conflict)
{
Conflict next = (Conflict)object;
result.add( next);
}
}
return result;
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
// @Override
// protected void logEntityNotFound(Entity obj, EntityNotFoundException ex) {
// RemoteStorage serv = getRemoteStorage();
// Comparable id = ex.getId();
// try {
// if ( obj instanceof ConflictImpl)
// {
// Iterable<String> referencedIds = ((ConflictImpl)obj).getReferencedIds();
// List<String> ids = new ArrayList<String>();
// for (String refId:referencedIds)
// {
// ids.add( refId);
// }
// serv.logEntityNotFound( id + " not found in conflict :",ids.toArray(new String[0]));
// }
// else if ( id != null )
// {
// serv.logEntityNotFound("Not found", id.toString() );
// }
// } catch (Exception e) {
// getLogger().error("Can't call server logging for " + ex.getMessage() + " due to " + e.getMessage(), e);
// }
// }
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.impl;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import org.rapla.components.util.Assert;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.entities.storage.EntityResolver;
import org.rapla.entities.storage.internal.SimpleEntity;
public class EntityStore implements EntityResolver {
HashMap<String,Entity> entities = new LinkedHashMap<String,Entity>();
HashMap<String,DynamicType> dynamicTypes = new HashMap<String,DynamicType>();
HashMap<String,String> passwordList = new HashMap<String,String>();
CategoryImpl superCategory;
EntityResolver parent;
public EntityStore(EntityResolver parent,Category superCategory) {
this.parent = parent;
this.superCategory = (CategoryImpl) superCategory;
}
public void addAll(Collection<? extends Entity>collection) {
Iterator<? extends Entity>it = collection.iterator();
while (it.hasNext())
{
put(it.next());
}
}
public void put(Entity entity) {
String id = entity.getId();
Assert.notNull(id);
if ( entity.getRaplaType() == DynamicType.TYPE)
{
DynamicType dynamicType = (DynamicType) entity;
dynamicTypes.put ( dynamicType.getKey(), dynamicType);
}
if ( entity.getRaplaType() == Category.TYPE)
{
for (Category child:((Category)entity).getCategories())
{
put( child);
}
}
entities.put(id,entity);
}
public DynamicType getDynamicType(String key)
{
DynamicType type = dynamicTypes.get( key);
if ( type == null && parent != null)
{
type = parent.getDynamicType( key);
}
return type;
}
public Collection<Entity>getList() {
return entities.values();
}
public CategoryImpl getSuperCategory()
{
return superCategory;
}
public void putPassword( String userid, String password )
{
passwordList.put(userid, password);
}
public String getPassword( String userid)
{
return passwordList.get(userid);
}
public Entity resolve(String id) throws EntityNotFoundException {
return resolve(id, null);
}
public <T extends Entity> T resolve(String id,Class<T> entityClass) throws EntityNotFoundException {
T entity = tryResolve(id, entityClass);
SimpleEntity.checkResolveResult(id, entityClass, entity);
return entity;
}
@Override
public Entity tryResolve(String id) {
return tryResolve(id, null);
}
@Override
public <T extends Entity> T tryResolve(String id,Class<T> entityClass) {
Assert.notNull( id);
Entity entity = entities.get(id);
if (entity != null) {
@SuppressWarnings("unchecked")
T casted = (T) entity;
return casted;
}
if ( id.equals( superCategory.getId()) && (entityClass == null || Category.class.isAssignableFrom( entityClass)))
{
@SuppressWarnings("unchecked")
T casted = (T) superCategory;
return casted;
}
if (parent != null)
{
return parent.tryResolve(id, entityClass);
}
return null;
}
} | Java |
package org.rapla.storage.impl.server;
import java.util.HashSet;
import java.util.Set;
import org.rapla.entities.domain.Appointment;
class AllocationChange
{
public Set<Appointment> toChange = new HashSet<Appointment>();
public Set<Appointment> toRemove= new HashSet<Appointment>();
public String toString()
{
return "toChange="+toChange.toString() + ";toRemove=" + toRemove.toString();
}
} | Java |
package org.rapla.storage.impl.server;
import java.util.Collection;
import java.util.SortedSet;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
public interface AllocationMap {
SortedSet<Appointment> getAppointments(Allocatable allocatable);
Collection<Allocatable> getAllocatables();
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.impl.server;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import org.rapla.components.util.Cancelable;
import org.rapla.components.util.Command;
import org.rapla.components.util.CommandScheduler;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.components.util.TimeInterval;
import org.rapla.components.util.Tools;
import org.rapla.components.util.iterator.IteratorChain;
import org.rapla.entities.Category;
import org.rapla.entities.DependencyException;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.MultiLanguageName;
import org.rapla.entities.Named;
import org.rapla.entities.Ownable;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.Timestamp;
import org.rapla.entities.UniqueKeyException;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.internal.PreferencesImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentStartComparator;
import org.rapla.entities.domain.Permission;
import org.rapla.entities.domain.RaplaObjectAnnotations;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.ResourceAnnotations;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.domain.internal.AppointmentImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.Classifiable;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.entities.dynamictype.internal.ClassificationImpl;
import org.rapla.entities.dynamictype.internal.DynamicTypeImpl;
import org.rapla.entities.internal.CategoryImpl;
import org.rapla.entities.internal.ModifiableTimestamp;
import org.rapla.entities.internal.UserImpl;
import org.rapla.entities.storage.CannotExistWithoutTypeException;
import org.rapla.entities.storage.DynamicTypeDependant;
import org.rapla.entities.storage.EntityReferencer;
import org.rapla.entities.storage.EntityReferencer.ReferenceInfo;
import org.rapla.entities.storage.EntityResolver;
import org.rapla.entities.storage.RefEntity;
import org.rapla.entities.storage.internal.SimpleEntity;
import org.rapla.facade.Conflict;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.Disposable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.logger.Logger;
import org.rapla.server.internal.TimeZoneConverterImpl;
import org.rapla.storage.CachableStorageOperator;
import org.rapla.storage.CachableStorageOperatorCommand;
import org.rapla.storage.IdCreator;
import org.rapla.storage.LocalCache;
import org.rapla.storage.RaplaNewVersionException;
import org.rapla.storage.RaplaSecurityException;
import org.rapla.storage.UpdateEvent;
import org.rapla.storage.UpdateOperation;
import org.rapla.storage.UpdateResult;
import org.rapla.storage.impl.AbstractCachableOperator;
import org.rapla.storage.impl.EntityStore;
public abstract class LocalAbstractCachableOperator extends AbstractCachableOperator implements Disposable, CachableStorageOperator, IdCreator {
/**
* set encryption if you want to enable password encryption. Possible values
* are "sha" or "md5".
*/
private String encryption = "sha-1";
private ConflictFinder conflictFinder;
private Map<String,SortedSet<Appointment>> appointmentMap;
private SortedSet<Timestamp> timestampSet;
private TimeZone systemTimeZone = TimeZone.getDefault();
private CommandScheduler scheduler;
private Cancelable cleanConflictsTask;
MessageDigest md;
protected void addInternalTypes(LocalCache cache) throws RaplaException
{
{
DynamicTypeImpl type = new DynamicTypeImpl();
String key = UNRESOLVED_RESOURCE_TYPE;
type.setKey(key);
type.setId( key);
type.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{"+key + "}");
type.getName().setName("en", "anonymous");
type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON);
type.setResolver( this);
type.setReadOnly( );
cache.put( type);
}
{
DynamicTypeImpl type = new DynamicTypeImpl();
String key = ANONYMOUSEVENT_TYPE;
type.setKey(key);
type.setId( key);
type.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{"+key + "}");
type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION);
type.getName().setName("en", "anonymous");
type.setResolver( this);
cache.put( type);
}
{
DynamicTypeImpl type = new DynamicTypeImpl();
String key = DEFAUTL_USER_TYPE;
type.setKey(key);
type.setId( key);
type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE);
//type.setAnnotation(DynamicTypeAnnotations.KEY_TRANSFERED_TO_CLIENT, DynamicTypeAnnotations.VALUE_TRANSFERED_TO_CLIENT_NEVER);
addAttributeWithInternalId(type,"surname", AttributeType.STRING);
addAttributeWithInternalId(type,"firstname", AttributeType.STRING);
addAttributeWithInternalId(type,"email", AttributeType.STRING);
type.setResolver( this);
type.setReadOnly();
cache.put( type);
}
{
DynamicTypeImpl type = new DynamicTypeImpl();
String key = PERIOD_TYPE;
type.setKey(key);
type.setId( key);
type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE);
type.setAnnotation(DynamicTypeAnnotations.KEY_TRANSFERED_TO_CLIENT, null);
addAttributeWithInternalId(type,"name", AttributeType.STRING);
addAttributeWithInternalId(type,"start", AttributeType.DATE);
addAttributeWithInternalId(type,"end", AttributeType.DATE);
type.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}");
type.setResolver( this);
type.setReadOnly();
cache.put( type);
}
{
DynamicTypeImpl type = new DynamicTypeImpl();
String key = SYNCHRONIZATIONTASK_TYPE;
type.setKey(key);
type.setId( key);
type.setAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE, DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RAPLATYPE);
type.setAnnotation(DynamicTypeAnnotations.KEY_TRANSFERED_TO_CLIENT, DynamicTypeAnnotations.VALUE_TRANSFERED_TO_CLIENT_NEVER);
addAttributeWithInternalId(type,"objectId", AttributeType.STRING);
addAttributeWithInternalId(type,"externalObjectId",AttributeType.STRING);
addAttributeWithInternalId(type,"status",AttributeType.STRING);
addAttributeWithInternalId(type,"retries", AttributeType.STRING);
type.setResolver( this);
type.setReadOnly();
cache.put( type);
}
}
public LocalAbstractCachableOperator(RaplaContext context, Logger logger) throws RaplaException {
super( context, logger);
scheduler = context.lookup( CommandScheduler.class);
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RaplaException( e.getMessage() ,e);
}
}
public void runWithReadLock(CachableStorageOperatorCommand cmd) throws RaplaException
{
Lock readLock = readLock();
try
{
cmd.execute( cache );
}
finally
{
unlock( readLock);
}
}
public List<Reservation> getReservations(User user, Collection<Allocatable> allocatables, Date start, Date end, ClassificationFilter[] filters,Map<String,String> annotationQuery) throws RaplaException {
boolean excludeExceptions = false;
HashSet<Reservation> reservationSet = new HashSet<Reservation>();
if (allocatables == null || allocatables.size() ==0)
{
allocatables = Collections.singleton( null);
}
for ( Allocatable allocatable: allocatables)
{
Lock readLock = readLock();
SortedSet<Appointment> appointments;
try
{
appointments = getAppointments( allocatable);
}
finally
{
unlock( readLock);
}
SortedSet<Appointment> appointmentSet = AppointmentImpl.getAppointments(appointments,user,start,end, excludeExceptions);
for (Appointment appointment:appointmentSet)
{
Reservation reservation = appointment.getReservation();
if ( !match(reservation, annotationQuery) )
{
continue;
} // Ignore Templates if not explicitly requested
// FIXME this special case should be refactored, so one can get all reservations in one method
else if ( RaplaComponent.isTemplate( reservation) && (annotationQuery == null || !annotationQuery.containsKey(RaplaObjectAnnotations.KEY_TEMPLATE) ))
{
continue;
}
if ( !reservationSet.contains( reservation))
{
reservationSet.add( reservation );
}
}
}
ArrayList<Reservation> result = new ArrayList<Reservation>(reservationSet);
removeFilteredClassifications(result, filters);
return result;
}
public boolean match(Reservation reservation, Map<String, String> annotationQuery) {
if ( annotationQuery != null)
{
for (String key : annotationQuery.keySet())
{
String annotationParam = annotationQuery.get( key);
String annotation = reservation.getAnnotation( key);
if ( annotation == null || annotationParam == null)
{
if (annotationParam!= null)
{
return false;
}
}
else
{
if ( !annotation.equals(annotationParam))
{
return false;
}
}
}
}
return true;
}
public Collection<String> getTemplateNames() throws RaplaException {
Lock readLock = readLock();
Collection<? extends Reservation> reservations;
try
{
reservations = cache.getReservations();
}
finally
{
unlock(readLock);
}
//Reservation[] reservations = cache.getReservations(user, start, end, filters.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY));
Set<String> templates = new LinkedHashSet<String>();
for ( Reservation r:reservations)
{
String templateName = r.getAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE);
if ( templateName != null)
{
templates.add( templateName);
}
}
return templates;
}
@Override
public String createId(RaplaType raplaType) throws RaplaException {
return UUID.randomUUID().toString();
}
public String createId(RaplaType raplaType,String seed) throws RaplaException {
byte[] data = new byte[16];
data = md.digest( seed.getBytes());
if ( data.length != 16 )
{
throw new RaplaException("Wrong algorithm");
}
data[6] &= 0x0f; /* clear version */
data[6] |= 0x40; /* set to version 4 */
data[8] &= 0x3f; /* clear variant */
data[8] |= 0x80; /* set to IETF variant */
long msb = 0;
long lsb = 0;
for (int i=0; i<8; i++)
msb = (msb << 8) | (data[i] & 0xff);
for (int i=8; i<16; i++)
lsb = (lsb << 8) | (data[i] & 0xff);
long mostSigBits = msb;
long leastSigBits = lsb;
UUID uuid = new UUID( mostSigBits, leastSigBits);
return uuid.toString();
}
public String[] createIdentifier(RaplaType raplaType, int count) throws RaplaException {
String[] ids = new String[ count];
for ( int i=0;i<count;i++)
{
ids[i] = createId(raplaType);
}
return ids;
}
public Date today() {
long time = getCurrentTimestamp().getTime();
long offset = TimeZoneConverterImpl.getOffset( DateTools.getTimeZone(), systemTimeZone, time);
Date raplaTime = new Date(time + offset);
return DateTools.cutDate( raplaTime);
}
public Date getCurrentTimestamp() {
long time = System.currentTimeMillis();
return new Date( time);
}
public void setTimeZone( TimeZone timeZone)
{
systemTimeZone = timeZone;
}
public TimeZone getTimeZone()
{
return systemTimeZone;
}
public String authenticate(String username, String password)
throws RaplaException {
Lock readLock = readLock();
try {
getLogger().info("Check password for User " + username);
User user = cache.getUser(username);
if (user != null)
{
String userId = user.getId();
if (checkPassword(userId, password))
{
return userId;
}
}
getLogger().warn("Login failed for " + username);
throw new RaplaSecurityException(i18n.getString("error.login"));
}
finally
{
unlock( readLock );
}
}
public boolean canChangePassword() throws RaplaException {
return true;
}
public void changePassword(User user, char[] oldPassword,char[] newPassword) throws RaplaException {
getLogger().info("Change password for User " + user.getUsername());
String userId = user.getId();
String password = new String(newPassword);
if (encryption != null)
password = encrypt(encryption, password);
Lock writeLock = writeLock( );
try
{
cache.putPassword(userId, password);
}
finally
{
unlock( writeLock );
}
User editObject = editObject(user, null);
List<Entity> editList = new ArrayList<Entity>(1);
editList.add(editObject);
Collection<Entity>removeList = Collections.emptyList();
// synchronization will be done in the dispatch method
storeAndRemove(editList, removeList, user);
}
public void changeName(User user, String title,String firstname, String surname) throws RaplaException {
User editableUser = editObject(user, user);
Allocatable personReference = editableUser.getPerson();
if (personReference == null) {
editableUser.setName(surname);
storeUser(editableUser);
} else {
Allocatable editablePerson = editObject(personReference, null);
Classification classification = editablePerson.getClassification();
{
Attribute attribute = classification.getAttribute("title");
if (attribute != null) {
classification.setValue(attribute, title);
}
}
{
Attribute attribute = classification.getAttribute("firstname");
if (attribute != null) {
classification.setValue(attribute, firstname);
}
}
{
Attribute attribute = classification.getAttribute("surname");
if (attribute != null) {
classification.setValue(attribute, surname);
}
}
ArrayList<Entity> arrayList = new ArrayList<Entity>();
arrayList.add(editableUser);
arrayList.add(editablePerson);
Collection<Entity> storeObjects = arrayList;
Collection<Entity> removeObjects = Collections.emptySet();
// synchronization will be done in the dispatch method
storeAndRemove(storeObjects, removeObjects, null);
}
}
public void changeEmail(User user, String newEmail) throws RaplaException {
User editableUser = user.isReadOnly() ? editObject(user, (User) user) : user;
Allocatable personReference = editableUser.getPerson();
ArrayList<Entity>arrayList = new ArrayList<Entity>();
Collection<Entity>storeObjects = arrayList;
Collection<Entity>removeObjects = Collections.emptySet();
storeObjects.add(editableUser);
if (personReference == null) {
editableUser.setEmail(newEmail);
} else {
Allocatable editablePerson = editObject(personReference, null);
Classification classification = editablePerson.getClassification();
classification.setValue("email", newEmail);
storeObjects.add(editablePerson);
}
storeAndRemove(storeObjects, removeObjects, null);
}
protected void resolveInitial(Collection<? extends Entity> entities,EntityResolver resolver) throws RaplaException {
testResolve(entities);
for (Entity entity: entities) {
if ( entity instanceof EntityReferencer)
{
((EntityReferencer)entity).setResolver(resolver);
}
}
processUserPersonLink(entities);
// It is important to do the read only later because some resolve might involve write to referenced objects
for (Entity entity: entities) {
((RefEntity)entity).setReadOnly();
}
}
protected void processUserPersonLink(Collection<? extends Entity> entities) throws RaplaException {
// resolve emails
Map<String,Allocatable> resolvingMap = new HashMap<String,Allocatable>();
for (Entity entity: entities)
{
if ( entity instanceof Allocatable)
{
Allocatable allocatable = (Allocatable) entity;
final Classification classification = allocatable.getClassification();
final Attribute attribute = classification.getAttribute("email");
if ( attribute != null)
{
final String email = (String)classification.getValue(attribute);
if ( email != null )
{
resolvingMap.put( email, allocatable);
}
}
}
}
for ( Entity entity: entities)
{
if ( entity.getRaplaType().getTypeClass() == User.class)
{
User user = (User)entity;
String email = user.getEmail();
if ( email != null && email.trim().length() > 0)
{
Allocatable person = resolvingMap.get(email);
if ( person != null)
{
user.setPerson(person);
}
}
}
}
}
public void confirmEmail(User user, String newEmail) throws RaplaException {
throw new RaplaException("Email confirmation must be done in the remotestorage class");
}
public Collection<Conflict> getConflicts(User user) throws RaplaException
{
Lock readLock = readLock();
try
{
return conflictFinder.getConflicts( user);
}
finally
{
unlock( readLock );
}
}
boolean disposing;
public void dispose() {
// prevent reentrance in dispose
synchronized ( this)
{
if ( disposing)
{
getLogger().warn("Disposing is called twice",new RaplaException(""));
return;
}
disposing = true;
}
try
{
if ( cleanConflictsTask != null)
{
cleanConflictsTask.cancel();
}
forceDisconnect();
}
finally
{
disposing = false;
}
}
protected void forceDisconnect() {
try
{
disconnect();
}
catch (Exception ex)
{
getLogger().error("Error during disconnect ", ex);
}
}
/** performs Integrity constraints check */
protected void check(final UpdateEvent evt, final EntityStore store) throws RaplaException {
Set<Entity> storeObjects = new HashSet<Entity>(evt.getStoreObjects());
//Set<Entity> removeObjects = new HashSet<Entity>(evt.getRemoveObjects());
checkConsistency(evt, store);
checkUnique(evt,store);
checkReferences(evt, store);
checkNoDependencies(evt, store);
checkVersions(storeObjects);
}
protected void updateLastChanged(UpdateEvent evt) throws RaplaException {
Date currentTime = getCurrentTimestamp();
String userId = evt.getUserId();
User lastChangedBy = ( userId != null) ? resolve(userId,User.class) : null;
for ( Entity e: evt.getStoreObjects())
{
if ( e instanceof ModifiableTimestamp)
{
ModifiableTimestamp modifiableTimestamp = (ModifiableTimestamp)e;
Date lastChangeTime = modifiableTimestamp.getLastChanged();
if ( lastChangeTime != null && lastChangeTime.equals( currentTime))
{
// wait 1 ms to increase timestamp
try {
Thread.sleep(1);
} catch (InterruptedException e1) {
throw new RaplaException( e1.getMessage(), e1);
}
currentTime = getCurrentTimestamp();
}
modifiableTimestamp.setLastChanged( currentTime);
modifiableTimestamp.setLastChangedBy( lastChangedBy );
}
}
}
class TimestampComparator implements Comparator<Timestamp>
{
public int compare(Timestamp o1, Timestamp o2) {
if ( o1 == o2)
{
return 0;
}
Date d1 = o1.getLastChanged();
Date d2 = o2.getLastChanged();
// if d1 is null and d2 is not then d1 is before d2
if ( d1 == null && d2 != null )
{
return -1;
}
// if d2 is null and d1 is not then d2 is before d1
if ( d1 != null && d2 == null)
{
return 1;
}
if ( d1 != null && d2 != null)
{
int result = d1.compareTo( d2);
if ( result != 0)
{
return result;
}
}
String id1 = (o1 instanceof Entity) ? ((Entity)o1).getId() : o1.toString();
String id2 = (o2 instanceof Entity) ? ((Entity)o2).getId() : o2.toString();
if ( id1 == null)
{
if ( id2 == null)
{
throw new IllegalStateException("Can't compare two entities without ids");
}
else
{
return -1;
}
}
else if ( id2 == null)
{
return 1;
}
return id1.compareTo( id2 );
}
}
protected void initIndizes() {
timestampSet = new TreeSet<Timestamp>(new TimestampComparator());
timestampSet.addAll( cache.getDynamicTypes());
timestampSet.addAll( cache.getReservations());
timestampSet.addAll( cache.getAllocatables());
timestampSet.addAll( cache.getUsers());
// The appointment map
appointmentMap = new HashMap<String, SortedSet<Appointment>>();
for ( Reservation r: cache.getReservations())
{
for ( Appointment app:((ReservationImpl)r).getAppointmentList())
{
Reservation reservation = app.getReservation();
Allocatable[] allocatables = reservation.getAllocatablesFor(app);
{
Collection<Appointment> list = getAndCreateList(appointmentMap,null);
list.add( app);
}
for ( Allocatable alloc:allocatables)
{
Collection<Appointment> list = getAndCreateList(appointmentMap,alloc);
list.add( app);
}
}
}
Date today2 = today();
AllocationMap allocationMap = new AllocationMap() {
public SortedSet<Appointment> getAppointments(Allocatable allocatable)
{
return LocalAbstractCachableOperator.this.getAppointments(allocatable);
}
@SuppressWarnings("unchecked")
public Collection<Allocatable> getAllocatables()
{
return (Collection)cache.getAllocatables();
}
};
// The conflict map
conflictFinder = new ConflictFinder(allocationMap, today2, getLogger(), this);
long delay = DateTools.MILLISECONDS_PER_HOUR;
long period = DateTools.MILLISECONDS_PER_HOUR;
Command cleanUpConflicts = new Command() {
@Override
public void execute() throws Exception {
removeOldConflicts();
}
};
cleanConflictsTask = scheduler.schedule( cleanUpConflicts, delay, period);
}
/** updates the bindings of the resources and returns a map with all processed allocation changes*/
private void updateIndizes(UpdateResult result) {
Map<Allocatable,AllocationChange> toUpdate = new HashMap<Allocatable,AllocationChange>();
List<Allocatable> removedAllocatables = new ArrayList<Allocatable>();
for (UpdateOperation operation: result.getOperations())
{
Entity current = operation.getCurrent();
RaplaType raplaType = current.getRaplaType();
if ( raplaType == Reservation.TYPE )
{
if ( operation instanceof UpdateResult.Remove)
{
Reservation old = (Reservation) current;
for ( Appointment app: old.getAppointments() )
{
updateBindings( toUpdate, old, app, true);
}
}
if ( operation instanceof UpdateResult.Add)
{
Reservation newReservation = (Reservation) ((UpdateResult.Add) operation).getNew();
for ( Appointment app: newReservation.getAppointments() )
{
updateBindings( toUpdate, newReservation,app, false);
}
}
if ( operation instanceof UpdateResult.Change)
{
Reservation oldReservation = (Reservation) ((UpdateResult.Change) operation).getOld();
Reservation newReservation =(Reservation) ((UpdateResult.Change) operation).getNew();
Appointment[] oldAppointments = oldReservation.getAppointments();
for ( Appointment oldApp: oldAppointments)
{
updateBindings( toUpdate, oldReservation, oldApp, true);
}
Appointment[] newAppointments = newReservation.getAppointments();
for ( Appointment newApp: newAppointments)
{
updateBindings( toUpdate, newReservation, newApp, false);
}
}
}
if ( raplaType == Allocatable.TYPE )
{
if ( operation instanceof UpdateResult.Remove)
{
Allocatable old = (Allocatable) current;
removedAllocatables.add( old);
}
}
if (raplaType == Allocatable.TYPE || raplaType == Reservation.TYPE || raplaType == DynamicType.TYPE || raplaType == User.TYPE || raplaType == Preferences.TYPE || raplaType == Category.TYPE )
{
if ( operation instanceof UpdateResult.Remove)
{
Timestamp old = (Timestamp) current;
timestampSet.remove( old);
}
if ( operation instanceof UpdateResult.Add)
{
Timestamp newEntity = (Timestamp) ((UpdateResult.Add) operation).getNew();
timestampSet.add( newEntity);
}
if ( operation instanceof UpdateResult.Change)
{
Timestamp newEntity = (Timestamp) ((UpdateResult.Change) operation).getNew();
Timestamp oldEntity = (Timestamp) ((UpdateResult.Change) operation).getOld();
timestampSet.remove( oldEntity);
timestampSet.add( newEntity);
}
}
}
for ( Allocatable alloc: removedAllocatables)
{
SortedSet<Appointment> sortedSet = appointmentMap.get( alloc);
if ( sortedSet != null && !sortedSet.isEmpty())
{
getLogger().error("Removing non empty appointment map for resource " + alloc + " Appointments:" + sortedSet);
}
appointmentMap.remove( alloc);
}
Date today = today();
// processes the conflicts and adds the changes to the result
conflictFinder.updateConflicts(toUpdate,result, today, removedAllocatables);
checkAbandonedAppointments();
}
@Override
public Collection<Entity> getUpdatedEntities(final Date timestamp) throws RaplaException {
Timestamp fromElement = new Timestamp() {
@Override
public User getLastChangedBy() {
return null;
}
@Override
public Date getLastChanged() {
return timestamp;
}
@Override
public Date getLastChangeTime() {
return getLastChanged();
}
@Override
public Date getCreateTime()
{
return timestamp;
}
};
Lock lock = readLock();
Collection<Entity> result = new ArrayList<Entity>();
try
{
SortedSet<Timestamp> tailSet = timestampSet.tailSet(fromElement);
for ( Timestamp entry : tailSet)
{
result.add( (Entity) entry );
}
}
finally
{
unlock(lock);
}
return result;
}
protected void updateBindings(Map<Allocatable, AllocationChange> toUpdate,Reservation reservation,Appointment app, boolean remove) {
Set<Allocatable> allocatablesToProcess = new HashSet<Allocatable>();
allocatablesToProcess.add( null);
if ( reservation != null)
{
Allocatable[] allocatablesFor = reservation.getAllocatablesFor( app);
allocatablesToProcess.addAll( Arrays.asList(allocatablesFor));
// This double check is very imperformant and will be removed in the future, if it doesnt show in test runs
// if ( remove)
// {
// Collection<Allocatable> allocatables = cache.getCollection(Allocatable.class);
// for ( Allocatable allocatable:allocatables)
// {
// SortedSet<Appointment> appointmentSet = this.appointmentMap.get( allocatable.getId());
// if ( appointmentSet == null)
// {
// continue;
// }
// for (Appointment app1:appointmentSet)
// {
// if ( app1.equals( app))
// {
// if ( !allocatablesToProcess.contains( allocatable))
// {
// getLogger().error("Old reservation " + reservation.toString() + " has not the correct allocatable information. Using full search for appointment " + app + " and resource " + allocatable ) ;
// allocatablesToProcess.add(allocatable);
// }
// }
// }
// }
// }
}
else
{
getLogger().error("Appointment without reservation found " + app + " ignoring.");
}
for ( Allocatable allocatable: allocatablesToProcess)
{
AllocationChange updateSet;
if ( allocatable != null)
{
updateSet = toUpdate.get( allocatable);
if ( updateSet == null)
{
updateSet = new AllocationChange();
toUpdate.put(allocatable, updateSet);
}
}
else
{
updateSet = null;
}
if ( remove)
{
Collection<Appointment> appointmentSet = getAndCreateList(appointmentMap,allocatable);
// binary search could fail if the appointment has changed since the last add, which should not
// happen as we only put and search immutable objects in the map. But the method is left here as a failsafe
// with a log messaget
if (!appointmentSet.remove( app))
{
getLogger().error("Appointent has changed, so its not found in indexed binding map. Removing via full search");
// so we need to traverse all appointment
Iterator<Appointment> it = appointmentSet.iterator();
while (it.hasNext())
{
if (app.equals(it.next())) {
it.remove();
break;
}
}
}
if ( updateSet != null)
{
updateSet.toRemove.add( app);
}
}
else
{
SortedSet<Appointment> appointmentSet = getAndCreateList(appointmentMap, allocatable);
appointmentSet.add(app);
if ( updateSet != null)
{
updateSet.toChange.add( app);
}
}
}
}
static final SortedSet<Appointment> EMPTY_SORTED_SET = Collections.unmodifiableSortedSet( new TreeSet<Appointment>());
protected SortedSet<Appointment> getAppointments(Allocatable allocatable)
{
String allocatableId = allocatable != null ? allocatable.getId() : null;
SortedSet<Appointment> s = appointmentMap.get( allocatableId);
if ( s == null)
{
return EMPTY_SORTED_SET;
}
return Collections.unmodifiableSortedSet(s);
}
private SortedSet<Appointment> getAndCreateList(Map<String,SortedSet<Appointment>> appointmentMap,Allocatable alloc) {
String allocationId = alloc != null ? alloc.getId() : null;
SortedSet<Appointment> set = appointmentMap.get( allocationId);
if ( set == null)
{
set = new TreeSet<Appointment>(new AppointmentStartComparator());
appointmentMap.put(allocationId, set);
}
return set;
}
@Override
protected UpdateResult update(UpdateEvent evt) throws RaplaException {
UpdateResult update = super.update(evt);
updateIndizes(update);
return update;
}
public void removeOldConflicts() throws RaplaException
{
Map<Entity,Entity> oldEntities = new LinkedHashMap<Entity,Entity>();
Collection<Entity>updatedEntities = new LinkedHashSet<Entity>();
Collection<Entity>toRemove = new LinkedHashSet<Entity>();
TimeInterval invalidateInterval = null;
String userId = null;
UpdateResult result = createUpdateResult(oldEntities, updatedEntities, toRemove, invalidateInterval, userId);
//Date today = getCurrentTimestamp();
Date today = today();
Lock readLock = readLock();
try
{
conflictFinder.removeOldConflicts(result, today);
}
finally
{
unlock( readLock);
}
fireStorageUpdated( result );
}
protected void preprocessEventStorage(final UpdateEvent evt) throws RaplaException {
EntityStore store = new EntityStore(this, this.getSuperCategory());
Collection<Entity>storeObjects = evt.getStoreObjects();
store.addAll(storeObjects);
for (Entity entity:storeObjects) {
if (getLogger().isDebugEnabled())
getLogger().debug("Contextualizing " + entity);
((EntityReferencer)entity).setResolver( store);
// add all child categories to store
if ( entity instanceof Category)
{
Set<Category> children = getAllCategories( (Category)entity);
store.addAll(children);
}
}
Collection<Entity>removeObjects = evt.getRemoveObjects();
store.addAll( removeObjects );
for ( Entity entity:removeObjects)
{
((EntityReferencer)entity).setResolver( store);
}
// add transitve changes to event
addClosure( evt, store );
// check event for inconsistencies
check( evt, store);
// update last changed date
updateLastChanged( evt );
}
/**
* Create a closure for all objects that should be updated. The closure
* contains all objects that are sub-entities of the entities and all
* objects and all other objects that are affected by the update: e.g.
* Classifiables when the DynamicType changes. The method will recursivly
* proceed with all discovered objects.
*/
protected void addClosure(final UpdateEvent evt,EntityStore store) throws RaplaException {
Collection<Entity> storeObjects = new ArrayList<Entity>(evt.getStoreObjects());
Collection<Entity> removeObjects = new ArrayList<Entity>(evt.getRemoveObjects());
for (Entity entity: storeObjects)
{
addStoreOperationsToClosure(evt, store,entity);
}
for (Entity entity: storeObjects) {
// update old classifiables, that may not been update before via a change event
// that could be the case if an old reservation is restored via undo but the dynamic type changed in between.
// The undo cache does not notice the change in type
if ( entity instanceof Classifiable && entity instanceof Timestamp)
{
Date lastChanged = ((Timestamp) entity).getLastChanged();
ClassificationImpl classification = (ClassificationImpl) ((Classifiable) entity).getClassification();
DynamicTypeImpl dynamicType = classification.getType();
Date typeLastChanged = dynamicType.getLastChanged();
if ( typeLastChanged != null && lastChanged != null && typeLastChanged.after( lastChanged))
{
if (classification.needsChange(dynamicType))
{
addChangedDependencies(evt, store, dynamicType, entity, false);
}
}
}
// TODO add conversion of classification filters or other dynamictypedependent that are stored in preferences
// for (PreferencePatch patch:evt.getPreferencePatches())
// {
// for (String key: patch.keySet())
// {
// Object object = patch.get( key);
// if ( object instanceof DynamicTypeDependant)
// {
//
// }
// }
// }
}
for (Entity object: removeObjects)
{
addRemoveOperationsToClosure(evt, store, object);
}
Set<Entity> deletedCategories = getDeletedCategories(storeObjects);
for (Entity entity: deletedCategories)
{
evt.putRemove(entity);
}
}
protected void addStoreOperationsToClosure(UpdateEvent evt, EntityStore store,Entity entity) throws RaplaException
{
if (getLogger().isDebugEnabled() && !evt.getStoreObjects().contains(entity)) {
getLogger().debug("Adding " + entity + " to store closure");
}
evt.putStore(entity);
if (DynamicType.TYPE == entity.getRaplaType()) {
DynamicTypeImpl dynamicType = (DynamicTypeImpl) entity;
addChangedDynamicTypeDependant(evt,store, dynamicType, false);
}
}
private void addRemoveOperationsToClosure(UpdateEvent evt,EntityStore store,Entity entity) throws RaplaException {
if (getLogger().isDebugEnabled() && !evt.getRemoveObjects().contains(entity)) {
getLogger().debug("Adding " + entity + " to remove closure");
}
evt.putRemove(entity);
if (DynamicType.TYPE == entity.getRaplaType()) {
DynamicTypeImpl dynamicType = (DynamicTypeImpl) entity;
addChangedDynamicTypeDependant(evt, store,dynamicType, true);
}
// If entity is a user, remove the preference object
if (User.TYPE == entity.getRaplaType()) {
addRemovedUserDependant(evt, store,(User) entity);
}
}
// protected void setCache(final LocalCache cache) {
// super.setCache( cache);
// if ( idTable == null)
// {
// idTable = new IdTable();
// }
// idTable.setCache(cache);
// }
//
protected void addChangedDynamicTypeDependant(UpdateEvent evt, EntityStore store,DynamicTypeImpl type, boolean toRemove) throws RaplaException {
List<Entity> referencingEntities = getReferencingEntities( type, store);
Iterator<Entity>it = referencingEntities.iterator();
while (it.hasNext()) {
Entity entity = it.next();
if (!(entity instanceof DynamicTypeDependant)) {
continue;
}
DynamicTypeDependant dependant = (DynamicTypeDependant) entity;
// Classifiables need update?
if (!dependant.needsChange(type) && !toRemove)
continue;
if (getLogger().isDebugEnabled())
getLogger().debug("Classifiable " + entity + " needs change!");
// Classifiables are allready on the store list
addChangedDependencies(evt, store, type, entity, toRemove);
}
}
private void addChangedDependencies(UpdateEvent evt,EntityStore store, DynamicTypeImpl type, Entity entity,boolean toRemove) throws EntityNotFoundException, RaplaException {
DynamicTypeDependant dependant;
if (evt.getStoreObjects().contains(entity)) {
dependant = (DynamicTypeDependant) evt.findEntity(entity);
} else {
// no, then create a clone of the classfiable object and add to list
User user = null;
if (evt.getUserId() != null) {
user = resolve(cache,evt.getUserId(), User.class);
}
@SuppressWarnings("unchecked")
Class<Entity> entityType = entity.getRaplaType().getTypeClass();
Entity persistant = store.tryResolve(entity.getId(), entityType);
dependant = (DynamicTypeDependant) editObject( entity, persistant, user);
// replace or add the modified entity
addStoreOperationsToClosure(evt, store,(Entity) dependant);
}
if (toRemove) {
try {
dependant.commitRemove(type);
} catch (CannotExistWithoutTypeException ex) {
// getLogger().warn(ex.getMessage(),ex);
}
} else {
dependant.commitChange(type);
}
}
protected void addRemovedUserDependant(UpdateEvent evt, EntityStore store,User user) throws RaplaException {
PreferencesImpl preferences = cache.getPreferencesForUserId(user.getId());
if (preferences != null)
{
evt.putRemove(preferences);
}
List<Entity>referencingEntities = getReferencingEntities( user, store);
Iterator<Entity>it = referencingEntities.iterator();
while (it.hasNext()) {
Entity entity = it.next();
// Remove internal resources automatically if the owner is deleted
if ( entity instanceof Classifiable && entity instanceof Ownable)
{
DynamicType type = ((Classifiable) entity).getClassification().getType();
if (((DynamicTypeImpl)type).isInternal())
{
User owner = ((Ownable)entity).getOwner();
if ( owner != null && owner.equals( user))
{
evt.putRemove( entity);
continue;
}
}
}
if (entity instanceof Timestamp) {
Timestamp timestamp = (Timestamp) entity;
User lastChangedBy = timestamp.getLastChangedBy();
if ( lastChangedBy == null || !lastChangedBy.equals( user) )
{
continue;
}
if ( entity instanceof Ownable )
{
User owner = ((Ownable)entity).getOwner();
// we do nothing if the user is also owner, that dependencies need to be resolved manually
if ( owner != null && owner.equals(user))
{
continue;
}
}
if (evt.getStoreObjects().contains(entity))
{
((SimpleEntity)evt.findEntity(entity)).setLastChangedBy(null);
}
else
{
@SuppressWarnings("unchecked")
Class<? extends Entity> typeClass = entity.getRaplaType().getTypeClass();
Entity persistant= cache.tryResolve( entity.getId(), typeClass);
Entity dependant = editObject( entity, persistant, user);
((SimpleEntity)dependant).setLastChangedBy( null );
addStoreOperationsToClosure(evt, store, dependant);
}
}
}
}
/**
* returns all entities that depend one the passed entities. In most cases
* one object depends on an other object if it has a reference to it.
*
* @param entity
*/
final protected Set<Entity> getDependencies(Entity entity, EntityStore store) {
RaplaType type = entity.getRaplaType();
final Collection<Entity>referencingEntities;
if (Category.TYPE == type || DynamicType.TYPE == type || Allocatable.TYPE == type || User.TYPE == type) {
HashSet<Entity> dependencyList = new HashSet<Entity>();
referencingEntities = getReferencingEntities(entity, store);
dependencyList.addAll(referencingEntities);
return dependencyList;
}
return Collections.emptySet();
}
protected List<Entity> getReferencingEntities(Entity entity, EntityStore store) {
List<Entity> result = new ArrayList<Entity>();
addReferers(cache.getReservations(), entity, result);
addReferers(cache.getAllocatables(), entity, result);
addReferers(cache.getUsers(), entity, result);
addReferers(cache.getDynamicTypes(), entity, result);
Iterable<Preferences> preferenceList = getPreferences(store);
addReferers(preferenceList, entity, result);
return result;
}
private Iterable<Preferences> getPreferences(EntityStore store) {
List<Preferences> preferenceList = new ArrayList<Preferences>();
for ( User user:cache.getUsers())
{
PreferencesImpl preferences = cache.getPreferencesForUserId( user.getId() );
if ( preferences != null)
{
preferenceList.add( preferences);
}
}
PreferencesImpl systemPreferences = cache.getPreferencesForUserId( null);
if ( systemPreferences != null)
{
preferenceList.add( systemPreferences );
}
return preferenceList;
}
private void addReferers(Iterable<? extends Entity> refererList,Entity object, List<Entity> result) {
for ( Entity referer: refererList)
{
if (referer != null && !referer.isIdentical(object) )
{
for (ReferenceInfo info:((EntityReferencer)referer).getReferenceInfo())
{
if (info.isReferenceOf(object) )
{
result.add(referer);
}
}
}
}
}
private int countDynamicTypes(Collection<? extends RaplaObject> entities, String classificationType) throws RaplaException {
Iterator<? extends RaplaObject> it = entities.iterator();
int count = 0;
while (it.hasNext()) {
RaplaObject entity = it.next();
if (DynamicType.TYPE != entity.getRaplaType())
continue;
DynamicType type = (DynamicType) entity;
String annotation = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
if ( annotation == null)
{
throw new RaplaException(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE + " not set for " + type);
}
if (annotation.equals( classificationType)) {
count++;
}
}
return count;
}
// Count dynamic-types to ensure that there is least one dynamic type left
private void checkDynamicType(Collection<Entity>entities, String[] classificationTypes) throws RaplaException {
int count = 0;
for ( String classificationType: classificationTypes)
{
count += countDynamicTypes(entities, classificationType);
}
Collection<? extends DynamicType> allTypes = cache.getDynamicTypes();
int countAll = 0;
for ( String classificationType: classificationTypes)
{
countAll = countDynamicTypes(allTypes, classificationType);
}
if (count >= 0 && count >= countAll) {
throw new RaplaException(i18n.getString("error.one_type_requiered"));
}
}
/**
* Check if the references of each entity refers to an object in cache or in
* the passed collection.
*/
final protected void checkReferences(UpdateEvent evt, EntityStore store) throws RaplaException {
for (EntityReferencer entity: evt.getEntityReferences(false)) {
for (ReferenceInfo info: entity.getReferenceInfo())
{
String id = info.getId();
// Reference in cache or store?
if (store.tryResolve(id, info.getType()) != null)
continue;
throw new EntityNotFoundException(i18n.format("error.reference_not_stored", info.getType() + ":" + id));
}
}
}
/**
* check if we find an object with the same name. If a different object
* (different id) with the same unique attributes is found a
* UniqueKeyException will be thrown.
*/
final protected void checkUnique(final UpdateEvent evt, final EntityStore store) throws RaplaException {
for (Entity entity : evt.getStoreObjects()) {
String name = "";
Entity entity2 = null;
if (DynamicType.TYPE == entity.getRaplaType()) {
DynamicType type = (DynamicType) entity;
name = type.getKey();
entity2 = (Entity) store.getDynamicType(name);
if (entity2 != null && !entity2.equals(entity))
throwNotUnique(name);
}
if (Category.TYPE == entity.getRaplaType()) {
Category category = (Category) entity;
Category[] categories = category.getCategories();
for (int i = 0; i < categories.length; i++) {
String key = categories[i].getKey();
for (int j = i + 1; j < categories.length; j++) {
String key2 = categories[j].getKey();
if (key == key2 || (key != null && key.equals(key2)) ) {
throwNotUnique(key);
}
}
}
}
if (User.TYPE == entity.getRaplaType()) {
name = ((User) entity).getUsername();
if (name == null || name.trim().length() == 0) {
String message = i18n.format("error.no_entry_for", getString("username"));
throw new RaplaException(message);
}
// FIXME Replace with store.getUser for the rare case that two users with the same username are stored in one operation
entity2 = cache.getUser(name);
if (entity2 != null && !entity2.equals(entity))
throwNotUnique(name);
}
}
}
private void throwNotUnique(String name) throws UniqueKeyException {
throw new UniqueKeyException(i18n.format("error.not_unique", name));
}
/**
* compares the version of the cached entities with the versions of the new
* entities. Throws an Exception if the newVersion != cachedVersion
*/
protected void checkVersions(Collection<Entity>entities) throws RaplaException {
for (Entity entity: entities) {
// Check Versions
Entity persistantVersion = findPersistant(entity);
// If the entities are newer, everything is o.k.
if (persistantVersion != null && persistantVersion != entity)
{
if (( persistantVersion instanceof Timestamp))
{
Date lastChangeTimePersistant = ((Timestamp)persistantVersion).getLastChanged();
Date lastChangeTime = ((Timestamp)entity).getLastChanged();
if ( lastChangeTimePersistant != null && lastChangeTime != null && lastChangeTimePersistant.after( lastChangeTime) )
{
getLogger().warn(
"There is a newer version for: " + entity.getId()
+ " stored version :"
+ SerializableDateTimeFormat.INSTANCE.formatTimestamp(lastChangeTimePersistant)
+ " version to store :" + SerializableDateTimeFormat.INSTANCE.formatTimestamp(lastChangeTime));
throw new RaplaNewVersionException(getI18n().format(
"error.new_version", entity.toString()));
}
}
}
}
}
/** Check if the objects are consistent, so that they can be safely stored. */
protected void checkConsistency(UpdateEvent evt, EntityStore store) throws RaplaException {
for (EntityReferencer referencer : evt.getEntityReferences(false)) {
for (ReferenceInfo referenceInfo:referencer.getReferenceInfo())
{
Entity reference = store.resolve( referenceInfo.getId(), referenceInfo.getType());
if (reference instanceof Preferences
|| reference instanceof Conflict
|| reference instanceof Reservation
|| reference instanceof Appointment
)
{
throw new RaplaException("The current version of Rapla doesn't allow references to objects of type " + reference.getRaplaType());
}
}
}
for (Entity entity : evt.getStoreObjects()) {
CategoryImpl superCategory = store.getSuperCategory();
if (Category.TYPE == entity.getRaplaType()) {
if (entity.equals(superCategory)) {
// Check if the user group is missing
Category userGroups = ((Category) entity).getCategory(Permission.GROUP_CATEGORY_KEY);
if (userGroups == null) {
throw new RaplaException("The category with the key '"
+ Permission.GROUP_CATEGORY_KEY
+ "' is missing.");
}
} else {
// check if the category to be stored has a parent
Category category = (Category) entity;
Category parent = category.getParent();
if (parent == null) {
throw new RaplaException("The category " + category
+ " needs a parent.");
}
else
{
int i = 0;
while ( true)
{
if ( parent == null)
{
throw new RaplaException("Category needs to be a child of super category.");
}
else if ( parent.equals( superCategory))
{
break;
}
parent = parent.getParent();
i++;
if ( i>80)
{
throw new RaplaException("infinite recursion detection for category " + category);
}
}
}
}
}
}
}
protected void checkNoDependencies(final UpdateEvent evt, final EntityStore store) throws RaplaException {
Collection<Entity> removeEntities = evt.getRemoveObjects();
Collection<Entity> storeObjects = new HashSet<Entity>(evt.getStoreObjects());
HashSet<Entity> dep = new HashSet<Entity>();
Set<Entity> deletedCategories = getDeletedCategories(storeObjects);
IteratorChain<Entity> iteratorChain = new IteratorChain<Entity>( deletedCategories,removeEntities);
for (Entity entity : iteratorChain) {
// First we add the dependencies from the stored object list
for (Entity obj : storeObjects) {
if ( obj instanceof EntityReferencer)
{
if (isRefering((EntityReferencer)obj, entity )) {
dep.add(obj);
}
}
}
// we check if the user deletes himself
if ( entity instanceof User)
{
String eventUserId = evt.getUserId();
if (eventUserId != null && eventUserId.equals( entity.getId()))
{
List<String> emptyList = Collections.emptyList();
throw new DependencyException("User can't delete himself", emptyList);
}
}
// Than we add the dependencies from the cache. It is important that
// we don't add the dependencies from the stored object list here,
// because a dependency could be removed in a stored object
Set<Entity> dependencies = getDependencies(entity, store);
for (Entity dependency : dependencies) {
if (!storeObjects.contains(dependency) && !removeEntities.contains( dependency)) {
// only add the first 21 dependencies;
if (dep.size() > MAX_DEPENDENCY )
{
break;
}
dep.add(dependency);
}
}
}
// CKO We skip this check as the admin should have the possibility to deny a user read to allocatables objects even if he has reserved it prior
// for (Entity entity : storeObjects) {
// if ( entity.getRaplaType() == Allocatable.TYPE)
// {
// Allocatable alloc = (Allocatable) entity;
// for (Entity reference:getDependencies(entity))
// {
// if ( reference instanceof Ownable)
// {
// User user = ((Ownable) reference).getOwner();
// if (user != null && !alloc.canReadOnlyInformation(user))
// {
// throw new DependencyException( "User " + user.getUsername() + " refers to " + getName(alloc) + ". Read permission is required.", Collections.singleton( getDependentName(reference)));
// }
// }
// }
// }
// }
if (dep.size() > 0) {
Collection<String> names = new ArrayList<String>();
for (Entity obj: dep)
{
String string = getDependentName(obj);
names.add(string);
}
throw new DependencyException(getString("error.dependencies"),names.toArray( new String[]{}));
}
// Count dynamic-types to ensure that there is least one dynamic type
// for reservations and one for resources or persons
checkDynamicType(removeEntities, new String[] {DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION});
checkDynamicType(removeEntities, new String[] {DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE,DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON});
}
private boolean isRefering(EntityReferencer referencer, Entity entity) {
for (ReferenceInfo info : referencer.getReferenceInfo())
{
if ( info.isReferenceOf(entity))
{
return true;
}
}
return false;
}
private Set<Entity> getDeletedCategories(Iterable<Entity> storeObjects) {
Set<Entity> deletedCategories = new HashSet<Entity>();
for (Entity entity : storeObjects) {
if ( entity.getRaplaType() == Category.TYPE)
{
Category newCat = (Category) entity;
Category old = tryResolve(entity.getId(), Category.class);
if ( old != null)
{
Set<Category> oldSet = getAllCategories( old);
Set<Category> newSet = getAllCategories( newCat);
oldSet.removeAll( newSet);
deletedCategories.addAll( oldSet );
}
}
}
return deletedCategories;
}
private Set<Category> getAllCategories(Category old) {
HashSet<Category> result = new HashSet<Category>();
result.add( old);
for (Category child : old.getCategories())
{
result.addAll( getAllCategories(child));
}
return result;
}
protected String getDependentName(Entity obj) {
StringBuffer buf = new StringBuffer();
if (obj instanceof Reservation) {
buf.append(getString("reservation"));
} else if (obj instanceof Preferences) {
buf.append(getString("preferences"));
} else if (obj instanceof Category) {
buf.append(getString("categorie"));
} else if (obj instanceof Allocatable) {
buf.append(getString("resources_persons"));
} else if (obj instanceof User) {
buf.append(getString("user"));
} else if (obj instanceof DynamicType) {
buf.append(getString("dynamictype"));
}
if (obj instanceof Named) {
Locale locale = i18n.getLocale();
final String string = ((Named) obj).getName(locale);
buf.append(": " + string);
} else {
buf.append(obj.toString());
}
if (obj instanceof Reservation) {
Reservation reservation = (Reservation)obj;
Appointment[] appointments = reservation.getAppointments();
if ( appointments.length > 0)
{
buf.append(" ");
Date start = appointments[0].getStart();
buf.append(raplaLocale.formatDate(start));
}
String template = reservation.getAnnotation(RaplaObjectAnnotations.KEY_TEMPLATE);
if ( template != null)
{
buf.append(" in template " + template);
}
}
final Object idFull = obj.getId();
if (idFull != null) {
String idShort = idFull.toString();
int dot = idShort.lastIndexOf('.');
buf.append(" (" + idShort.substring(dot + 1) + ")");
}
String string = buf.toString();
return string;
}
private void storeUser(User refUser) throws RaplaException {
ArrayList<Entity> arrayList = new ArrayList<Entity>();
arrayList.add(refUser);
Collection<Entity> storeObjects = arrayList;
Collection<Entity> removeObjects = Collections.emptySet();
storeAndRemove(storeObjects, removeObjects, null);
}
protected String encrypt(String encryption, String password) throws RaplaException {
MessageDigest md;
try {
md = MessageDigest.getInstance(encryption);
} catch (NoSuchAlgorithmException ex) {
throw new RaplaException(ex);
}
synchronized (md)
{
md.reset();
md.update(password.getBytes());
return encryption + ":" + Tools.convert(md.digest());
}
}
private boolean checkPassword(String userId, String password) throws RaplaException {
if (userId == null)
return false;
String correct_pw = cache.getPassword(userId);
if (correct_pw == null) {
return false;
}
if (correct_pw.equals(password)) {
return true;
}
int columIndex = correct_pw.indexOf(":");
if (columIndex > 0 && correct_pw.length() > 20) {
String encryptionGuess = correct_pw.substring(0, columIndex);
if (encryptionGuess.contains("sha") || encryptionGuess.contains("md5")) {
password = encrypt(encryptionGuess, password);
if (correct_pw.equals(password)) {
return true;
}
}
}
return false;
}
@Override
public Map<Allocatable,Collection<Appointment>> getFirstAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException {
Lock readLock = readLock();
Map<Allocatable, Map<Appointment, Collection<Appointment>>> allocatableBindings;
try
{
allocatableBindings = getAllocatableBindings(allocatables, appointments, ignoreList,true);
}
finally
{
unlock( readLock);
}
Map<Allocatable, Collection<Appointment>> map = new HashMap<Allocatable, Collection<Appointment>>();
for ( Map.Entry<Allocatable, Map<Appointment, Collection<Appointment>>> entry: allocatableBindings.entrySet())
{
Allocatable alloc = entry.getKey();
Collection<Appointment> list = entry.getValue().keySet();
map.put( alloc, list);
}
return map;
}
@Override
public Map<Allocatable, Map<Appointment,Collection<Appointment>>> getAllAllocatableBindings(Collection<Allocatable> allocatables, Collection<Appointment> appointments, Collection<Reservation> ignoreList) throws RaplaException
{
Lock readLock = readLock();
try
{
return getAllocatableBindings( allocatables, appointments, ignoreList, false);
}
finally
{
unlock( readLock );
}
}
public Map<Allocatable, Map<Appointment,Collection<Appointment>>> getAllocatableBindings(Collection<Allocatable> allocatables,Collection<Appointment> appointments, Collection<Reservation> ignoreList, boolean onlyFirstConflictingAppointment) {
Map<Allocatable, Map<Appointment,Collection<Appointment>>> map = new HashMap<Allocatable, Map<Appointment,Collection<Appointment>>>();
for ( Allocatable allocatable:allocatables)
{
String annotation = allocatable.getAnnotation( ResourceAnnotations.KEY_CONFLICT_CREATION);
boolean holdBackConflicts = annotation != null && annotation.equals( ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE);
if ( holdBackConflicts)
{
continue;
}
SortedSet<Appointment> appointmentSet = getAppointments( allocatable);
if ( appointmentSet == null)
{
continue;
}
map.put(allocatable, new HashMap<Appointment,Collection<Appointment>>() );
for (Appointment appointment:appointments)
{
Set<Appointment> conflictingAppointments = AppointmentImpl.getConflictingAppointments(appointmentSet, appointment, ignoreList, onlyFirstConflictingAppointment);
if ( conflictingAppointments.size() > 0)
{
Map<Appointment,Collection<Appointment>> appMap = map.get( allocatable);
if ( appMap == null)
{
appMap = new HashMap<Appointment, Collection<Appointment>>();
map.put( allocatable, appMap);
}
appMap.put( appointment, conflictingAppointments);
}
}
}
return map;
}
@Override
public Date getNextAllocatableDate(Collection<Allocatable> allocatables,Appointment appointment,Collection<Reservation> ignoreList,Integer worktimeStartMinutes,Integer worktimeEndMinutes, Integer[] excludedDays, Integer rowsPerHour) throws RaplaException {
Lock readLock = readLock();
try
{
Appointment newState = appointment;
Date firstStart = appointment.getStart();
boolean startDateExcluded = isExcluded(excludedDays, firstStart);
boolean wholeDay = appointment.isWholeDaysSet();
boolean inWorktime = inWorktime(appointment, worktimeStartMinutes,worktimeEndMinutes);
if ( rowsPerHour == null || rowsPerHour <=1)
{
rowsPerHour = 1;
}
for ( int i=0;i<366*24 *rowsPerHour ;i++)
{
newState = ((AppointmentImpl) newState).clone();
Date start = newState.getStart();
long millisToAdd = wholeDay ? DateTools.MILLISECONDS_PER_DAY : (DateTools.MILLISECONDS_PER_HOUR / rowsPerHour );
Date newStart = new Date(start.getTime() + millisToAdd);
if (!startDateExcluded && isExcluded(excludedDays, newStart))
{
continue;
}
newState.move( newStart );
if ( !wholeDay && inWorktime && !inWorktime(newState, worktimeStartMinutes, worktimeEndMinutes))
{
continue;
}
if (!isAllocated(allocatables, newState, ignoreList))
{
return newStart;
}
}
return null;
}
finally
{
unlock( readLock );
}
}
private boolean inWorktime(Appointment appointment,
Integer worktimeStartMinutes, Integer worktimeEndMinutes) {
long start = appointment.getStart().getTime();
int minuteOfDayStart = DateTools.getMinuteOfDay( start );
long end = appointment.getEnd().getTime();
int minuteOfDayEnd = DateTools.getMinuteOfDay( end ) + (int) DateTools.countDays(start, end) * 24 * 60;
boolean inWorktime = (worktimeStartMinutes == null || worktimeStartMinutes<= minuteOfDayStart) && ( worktimeEndMinutes == null || worktimeEndMinutes >= minuteOfDayEnd);
return inWorktime;
}
private boolean isExcluded(Integer[] excludedDays, Date date) {
Integer weekday = DateTools.getWeekday( date);
if (excludedDays != null)
{
for ( Integer day:excludedDays)
{
if ( day.equals( weekday))
{
return true;
}
}
}
return false;
}
private boolean isAllocated(Collection<Allocatable> allocatables,
Appointment appointment, Collection<Reservation> ignoreList) throws RaplaException
{
Map<Allocatable, Collection<Appointment>> firstAllocatableBindings = getFirstAllocatableBindings(allocatables, Collections.singleton( appointment) , ignoreList);
for (Map.Entry<Allocatable, Collection<Appointment>> entry: firstAllocatableBindings.entrySet())
{
if (entry.getValue().size() > 0)
{
return true;
}
}
return false;
}
public Collection<Entity> getVisibleEntities(final User user)throws RaplaException {
Lock readLock = readLock();
try
{
return cache.getVisibleEntities(user);
}
finally
{
unlock(readLock);
}
}
// this check is only there to detect rapla bugs in the conflict api and can be removed if it causes performance issues
private void checkAbandonedAppointments() {
Collection<? extends Allocatable> allocatables = cache.getAllocatables();
Logger logger = getLogger().getChildLogger("appointmentcheck");
try
{
for ( Allocatable allocatable:allocatables)
{
SortedSet<Appointment> appointmentSet = this.appointmentMap.get( allocatable.getId());
if ( appointmentSet == null)
{
continue;
}
for (Appointment app:appointmentSet)
{
{
SimpleEntity original = (SimpleEntity)app;
String id = original.getId();
if ( id == null )
{
logger.error( "Empty id for " + original);
continue;
}
Appointment persistant = cache.tryResolve( id, Appointment.class );
if ( persistant == null )
{
logger.error( "appointment not stored in cache " + original );
continue;
}
}
Reservation reservation = app.getReservation();
if (reservation == null)
{
logger.error("Appointment without a reservation stored in cache " + app );
appointmentSet.remove( app);
continue;
}
else if (!reservation.hasAllocated( allocatable, app))
{
logger.error("Allocation is not stored correctly for " + reservation + " " + app + " " + allocatable + " removing binding for " + app);
appointmentSet.remove( app);
continue;
}
else
{
{
Reservation original = reservation;
String id = original.getId();
if ( id == null )
{
logger.error( "Empty id for " + original);
continue;
}
Reservation persistant = cache.tryResolve( id, Reservation.class );
if ( persistant != null )
{
Date lastChanged = original.getLastChanged();
Date persistantLastChanged = persistant.getLastChanged();
if (persistantLastChanged != null && !persistantLastChanged.equals(lastChanged))
{
logger.error( "Reservation stored in cache is not the same as in allocation store " + original );
continue;
}
}
else
{
logger.error( "Reservation not stored in cache " + original + " removing binding for " + app);
appointmentSet.remove( app);
continue;
}
}
}
}
}
}
catch (Exception ex)
{
logger.error(ex.getMessage(), ex);
}
}
protected void createDefaultSystem(LocalCache cache) throws RaplaException
{
EntityStore store = new EntityStore( null, cache.getSuperCategory() );
DynamicTypeImpl resourceType = newDynamicType(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE,"resource");
setName(resourceType.getName(), "resource");
add(store, resourceType);
DynamicTypeImpl personType = newDynamicType(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON,"person");
setName(personType.getName(), "person");
add(store, personType);
DynamicTypeImpl eventType = newDynamicType(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION, "event");
setName(eventType.getName(), "event");
add(store, eventType);
String[] userGroups = new String[] {Permission.GROUP_REGISTERER_KEY, Permission.GROUP_MODIFY_PREFERENCES_KEY,Permission.GROUP_CAN_READ_EVENTS_FROM_OTHERS, Permission.GROUP_CAN_CREATE_EVENTS, Permission.GROUP_CAN_EDIT_TEMPLATES};
Date now = getCurrentTimestamp();
CategoryImpl groupsCategory = new CategoryImpl(now,now);
groupsCategory.setKey("user-groups");
setName( groupsCategory.getName(), groupsCategory.getKey());
setNew( groupsCategory);
store.put( groupsCategory);
for ( String catName: userGroups)
{
CategoryImpl group = new CategoryImpl(now,now);
group.setKey( catName);
setNew(group);
setName( group.getName(), group.getKey());
groupsCategory.addCategory( group);
store.put( group);
}
cache.getSuperCategory().addCategory( groupsCategory);
UserImpl admin = new UserImpl(now,now);
admin.setUsername("admin");
admin.setAdmin( true);
setNew(admin);
store.put( admin);
Collection<Entity> list = store.getList();
cache.putAll( list );
testResolve( list);
setResolver( list);
UserImpl user = cache.getUser("admin");
String password ="";
cache.putPassword( user.getId(), password );
cache.getSuperCategory().setReadOnly();
AllocatableImpl allocatable = new AllocatableImpl(now, now);
allocatable.setResolver( this);
allocatable.addPermission(allocatable.newPermission());
Classification classification = cache.getDynamicType("resource").newClassification();
allocatable.setClassification(classification);
setNew(allocatable);
classification.setValue("name", getString("test_resource"));
allocatable.setOwner( user);
cache.put( allocatable);
}
private void add(EntityStore list, DynamicTypeImpl type) {
list.put( type);
for (Attribute att:type.getAttributes())
{
list.put((Entity) att);
}
}
private Attribute createStringAttribute(String key, String name) throws RaplaException {
Attribute attribute = newAttribute(AttributeType.STRING, null);
attribute.setKey(key);
setName(attribute.getName(), name);
return attribute;
}
private void addAttributeWithInternalId(DynamicType dynamicType,String key, AttributeType type) throws RaplaException {
String id = "rapla_"+ dynamicType.getKey() + "_" +key;
Attribute attribute = newAttribute(type, id);
attribute.setKey(key);
setName(attribute.getName(), key);
dynamicType.addAttribute( attribute);
}
private DynamicTypeImpl newDynamicType(String classificationType, String key) throws RaplaException {
DynamicTypeImpl dynamicType = new DynamicTypeImpl();
dynamicType.setAnnotation("classification-type", classificationType);
dynamicType.setKey(key);
setNew(dynamicType);
if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE)) {
dynamicType.addAttribute(createStringAttribute("name", "name"));
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}");
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS,"automatic");
} else if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION)) {
dynamicType.addAttribute(createStringAttribute("name","eventname"));
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT,"{name}");
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS, null);
} else if (classificationType.equals(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON)) {
dynamicType.addAttribute(createStringAttribute("surname", "surname"));
dynamicType.addAttribute(createStringAttribute("firstname", "firstname"));
dynamicType.addAttribute(createStringAttribute("email", "email"));
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT, "{surname} {firstname}");
dynamicType.setAnnotation(DynamicTypeAnnotations.KEY_COLORS, null);
}
dynamicType.setResolver( this);
return dynamicType;
}
private Attribute newAttribute(AttributeType attributeType,String id) throws RaplaException {
AttributeImpl attribute = new AttributeImpl(attributeType);
if ( id == null)
{
setNew(attribute);
}
else
{
((RefEntity)attribute).setId(id);
}
attribute.setResolver( this);
return attribute;
}
private <T extends Entity> void setNew(T entity)
throws RaplaException {
RaplaType raplaType = entity.getRaplaType();
String id = createIdentifier(raplaType,1)[0];
((RefEntity)entity).setId(id);
}
private void setName(MultiLanguageName name, String to)
{
String currentLang = i18n.getLang();
name.setName("en", to);
try
{
String translation = i18n.getString( to);
name.setName(currentLang, translation);
}
catch (Exception ex)
{
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2013 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.impl.server;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.rapla.components.util.DateTools;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.AppointmentBlockEndComparator;
import org.rapla.entities.domain.AppointmentBlockStartComparator;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.ResourceAnnotations;
import org.rapla.entities.domain.internal.AppointmentImpl;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.storage.EntityResolver;
import org.rapla.facade.Conflict;
import org.rapla.facade.RaplaComponent;
import org.rapla.facade.internal.ConflictImpl;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.UpdateResult;
import org.rapla.storage.UpdateResult.Change;
class ConflictFinder {
AllocationMap allocationMap;
Map<Allocatable,Set<Conflict>> conflictMap;
Logger logger;
EntityResolver resolver;
public ConflictFinder( AllocationMap allocationMap, Date today, Logger logger, EntityResolver resolver) {
this.logger = logger;
this.allocationMap = allocationMap;
conflictMap = new HashMap<Allocatable, Set<Conflict>>();
long startTime = System.currentTimeMillis();
int conflictSize = 0;
for (Allocatable allocatable:allocationMap.getAllocatables())
{
Set<Conflict> conflictList = Collections.emptySet();
Set<Conflict> newConflicts = updateConflicts(allocatable, null, today, conflictList);
conflictMap.put( allocatable, newConflicts);
conflictSize+= newConflicts.size();
}
logger.info("Conflict initialization found " + conflictSize + " conflicts and took " + (System.currentTimeMillis()- startTime) + "ms. " );
this.resolver = resolver;
}
private Set<Conflict> updateConflicts(Allocatable allocatable,AllocationChange change, Date today, Set<Conflict> oldList )
{
if ( isConflictIgnored(allocatable))
{
return Collections.emptySet();
}
Set<Appointment> allAppointments = allocationMap.getAppointments(allocatable);
Set<Appointment> changedAppointments;
Set<Appointment> removedAppointments;
if ( change == null)
{
changedAppointments = allAppointments;
removedAppointments = new TreeSet<Appointment>();
}
else
{
changedAppointments = change.toChange;
removedAppointments = change.toRemove;
}
Set<String> foundConflictIds = new HashSet<String>();
Set<Conflict> conflictList = new HashSet<Conflict>( );//conflictMap.get(allocatable);
{
Set<String> idList1 = getIds( removedAppointments);
Set<String> idList2 = getIds( changedAppointments);
for ( Conflict conflict:oldList)
{
if (endsBefore(conflict, today) || contains(conflict, idList1) || contains(conflict, idList2))
{
continue;
}
conflictList.add( conflict );
}
}
{
SortedSet<AppointmentBlock> allAppointmentBlocksSortedByStartDescending = null;//new TreeSet<AppointmentBlock>(new InverseComparator<AppointmentBlock>(new AppointmentBlockStartComparator()));
SortedSet<AppointmentBlock> allAppointmentBlocks = createBlocks(today,allAppointments, new AppointmentBlockEndComparator(), allAppointmentBlocksSortedByStartDescending);
SortedSet<AppointmentBlock> appointmentBlocks = createBlocks(today,changedAppointments, new AppointmentBlockStartComparator(), null);
// Check the conflicts for each time block
for (AppointmentBlock appBlock:appointmentBlocks)
{
final Appointment appointment1 = appBlock.getAppointment();
long start = appBlock.getStart();
long end = appBlock.getEnd();
/*
* Shrink the set of all time blocks down to those with a start date which is
* later than or equal to the start date of the block
*/
AppointmentBlock compareBlock = new AppointmentBlock(start, start, appointment1,false);
final SortedSet<AppointmentBlock> tailSet = allAppointmentBlocks.tailSet(compareBlock);
// Check all time blocks which start after or at the same time as the block which is being checked
for (AppointmentBlock appBlock2:tailSet)
{
// If the start date of the compared block is after the end date of the block, skip the appointment
if (appBlock2.getStart() > end)
{
break;
}
final Appointment appointment2 = appBlock2.getAppointment();
// we test that in the next step
if ( appBlock == appBlock2 || appBlock2.includes( appBlock) || appointment1.equals( appointment2) )
{
continue;
}
// Check if the corresponding appointments of both blocks overlap each other
if (!appointment2.equals( appointment1) && appointment2.overlaps(appointment1))
{
String id = ConflictImpl.createId(allocatable.getId(), appointment1.getId(), appointment2.getId());
if ( foundConflictIds.contains(id ))
{
continue;
}
// Add appointments to conflict list
if (ConflictImpl.isConflictWithoutCheck(appointment1, appointment2, today))
{
final ConflictImpl conflict = new ConflictImpl(allocatable,appointment1, appointment2, today, id);
conflictList.add(conflict);
foundConflictIds.add( id);
}
}
}
// we now need to check overlaps with appointments that start before and end after the appointment
//AppointmentBlock compareBlock2 = new AppointmentBlock(end, end, appointment1,false);
//SortedSet<AppointmentBlock> descending = allAppointmentBlocksSortedByStartDescending.tailSet(compareBlock);
for (AppointmentBlock appBlock2:tailSet)
{
final Appointment appointment2 = appBlock2.getAppointment();
if ( appBlock == appBlock2 || !appBlock2.includes( appBlock) || appointment2.equals( appointment1) )
{
continue;
}
String id = ConflictImpl.createId(allocatable.getId(), appointment1.getId(), appointment2.getId());
if ( foundConflictIds.contains(id ))
{
continue;
}
if (ConflictImpl.isConflictWithoutCheck(appointment1, appointment2, today))
{
final ConflictImpl conflict = new ConflictImpl(allocatable,appointment1, appointment2, today, id);
conflictList.add(conflict);
foundConflictIds.add( id);
}
}
}
}
if ( conflictList.isEmpty())
{
return Collections.emptySet();
}
return conflictList;
}
public Set<String> getIds(Collection<? extends Entity> list) {
if ( list.isEmpty())
{
return Collections.emptySet();
}
Set<String> idList = new HashSet<String>();
for ( Entity entity:list)
{
idList.add( entity.getId());
}
return idList;
}
private boolean isConflictIgnored(Allocatable allocatable)
{
String annotation = allocatable.getAnnotation(ResourceAnnotations.KEY_CONFLICT_CREATION);
if ( annotation != null && annotation.equals(ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE))
{
return true;
}
return false;
}
private boolean contains(Conflict conflict, Set<String> idList)
{
String appointment1 = conflict.getAppointment1();
String appointment2 = conflict.getAppointment2();
return( idList.contains( appointment1) || idList.contains( appointment2));
}
private SortedSet<AppointmentBlock> createBlocks(Date today, Set<Appointment> appointmentSet,final Comparator<AppointmentBlock> comparator, SortedSet<AppointmentBlock> additionalSet) {
// overlaps will be checked 260 weeks (5 years) from now on
long maxCheck = System.currentTimeMillis() + DateTools.MILLISECONDS_PER_WEEK * 260;
// Create a new set of time blocks, ordered by their start dates
SortedSet<AppointmentBlock> allAppointmentBlocks = new TreeSet<AppointmentBlock>(comparator);
if ( appointmentSet.isEmpty())
{
return allAppointmentBlocks;
}
//Appointment last = appointmentSet.last();
// Get all time blocks of all appointments
for (Appointment appointment:appointmentSet)
{
// Get the end date of the appointment (if repeating, end date of last occurence)
Date maxEnd = appointment.getMaxEnd();
// Check if the appointment is repeating forever
if ( maxEnd == null || maxEnd.getTime() > maxCheck)
{
// If the repeating has no end, set the end to the start of the last appointment in the set + 100 weeks (~2 years)
maxEnd = new Date(maxCheck);
}
if ( maxEnd.before( today))
{
continue;
}
if ( RaplaComponent.isTemplate(appointment.getReservation()))
{
continue;
}
Reservation r1 = appointment.getReservation();
DynamicType type1 = r1 != null ? r1.getClassification().getType() : null;
String annotation1 = ConflictImpl.getConflictAnnotation( type1);
if ( ConflictImpl.isNoConflicts( annotation1 ) )
{
continue;
}
/*
* If the appointment has a repeating, get all single time blocks of it. If it is no
* repeating, this will just create one block, which is equal to the appointment
* itself.
*/
Date start = appointment.getStart();
if ( start.before( today))
{
start = today;
}
((AppointmentImpl)appointment).createBlocks(start, DateTools.fillDate(maxEnd), allAppointmentBlocks,additionalSet);
}
return allAppointmentBlocks;
}
/**
* Determines all conflicts which occur after a given start date.
* if user is passed then only returns conflicts the user can modify
*
* @param allocatables
*/
public Collection<Conflict> getConflicts( User user)
{
Collection<Conflict> conflictList = new HashSet<Conflict>();
for ( Allocatable allocatable: conflictMap.keySet())
{
Set<Conflict> set = conflictMap.get( allocatable);
if ( set != null)
{
for ( Conflict conflict: set)
{
if (ConflictImpl.canModify(conflict,user,resolver))
{
conflictList.add(conflict);
}
}
}
}
return conflictList;
}
private boolean endsBefore(Conflict conflict,Date date )
{
Appointment appointment1 = getAppointment( conflict.getAppointment1());
Appointment appointment2 = getAppointment( conflict.getAppointment2());
if ( appointment1 == null || appointment2 == null)
{
return false;
}
boolean result = ConflictImpl.endsBefore( appointment1, appointment2, date);
return result;
}
private Appointment getAppointment(String id)
{
return resolver.tryResolve(id, Appointment.class);
}
public void updateConflicts(Map<Allocatable, AllocationChange> toUpdate,UpdateResult evt, Date today,Collection<Allocatable> removedAllocatables)
{
Iterator<Change> it = evt.getOperations(UpdateResult.Change.class);
while (it.hasNext())
{
Change next = it.next();
RaplaObject current = next.getNew();
if ( current.getRaplaType() == Allocatable.TYPE)
{
Allocatable old = (Allocatable) next.getOld();
Allocatable newAlloc = (Allocatable) next.getNew();
if ( old != null && newAlloc != null )
{
if (isConflictIgnored(old) != isConflictIgnored(newAlloc))
{
// add an recalculate all if holdbackconflicts changed
toUpdate.put( newAlloc, null);
}
}
}
}
for ( Allocatable alloc: removedAllocatables)
{
Set<Conflict> sortedSet = conflictMap.get( alloc);
if ( sortedSet != null && !sortedSet.isEmpty())
{
logger.error("Removing non empty conflict map for resource " + alloc + " Appointments:" + sortedSet);
}
conflictMap.remove( alloc);
}
Set<Conflict> added = new HashSet<Conflict>();
// this will recalculate the conflicts for that resource and the changed appointments
for ( Map.Entry<Allocatable, AllocationChange> entry:toUpdate.entrySet())
{
Allocatable allocatable = entry.getKey();
AllocationChange changedAppointments = entry.getValue();
if ( changedAppointments == null)
{
conflictMap.remove( allocatable);
}
Set<Conflict> conflictListBefore = conflictMap.get(allocatable);
if ( conflictListBefore == null)
{
conflictListBefore = new LinkedHashSet<Conflict>();
}
Set<Conflict> conflictListAfter = updateConflicts( allocatable, changedAppointments, today, conflictListBefore);
conflictMap.put( allocatable, conflictListAfter);
//User user = evt.getUser();
for ( Conflict conflict: conflictListBefore)
{
boolean isRemoved = !conflictListAfter.contains(conflict);
if ( isRemoved )
{
evt.addOperation( new UpdateResult.Remove(conflict));
}
}
for ( Conflict conflict: conflictListAfter)
{
boolean isNew = !conflictListBefore.contains(conflict);
if ( isNew )
{
evt.addOperation( new UpdateResult.Add(conflict));
added.add( conflict);
}
}
}
// so now we have the new conflicts, but what if a reservation or appointment changed without affecting the allocation but still
// the conflict is still the same but the name could change, so we must somehow indicate the clients displaying that conflict, that they need to refresh the name,
// because the involving reservations are not automatically pushed to the client
// first we create a list with all changed appointments. Notice if a reservation is changed all the appointments will change to
Map<Allocatable, Set<String>> appointmentUpdateMap = new LinkedHashMap<Allocatable, Set<String>>();
for (@SuppressWarnings("rawtypes") RaplaObject obj:evt.getChanged())
{
if ( obj.getRaplaType().equals( Reservation.TYPE))
{
Reservation reservation = (Reservation) obj;
for (Appointment app: reservation.getAppointments())
{
for ( Allocatable alloc:reservation.getAllocatablesFor( app))
{
Set<String> set = appointmentUpdateMap.get( alloc);
if ( set == null)
{
set = new HashSet<String>();
appointmentUpdateMap.put(alloc, set);
}
set.add( app.getId());
}
}
}
}
// then we create a map and look for any conflict that has changed appointment. This could still contain old appointment references
Map<Conflict,Conflict> toUpdateConflicts = new LinkedHashMap<Conflict, Conflict>();
for ( Allocatable alloc: appointmentUpdateMap.keySet())
{
Set<String> changedAppointments = appointmentUpdateMap.get( alloc);
Set<Conflict> conflicts = conflictMap.get( alloc);
if ( conflicts != null)
{
for ( Conflict conflict:conflicts)
{
String appointment1Id = conflict.getAppointment1();
String appointment2Id = conflict.getAppointment2();
boolean contains1 = changedAppointments.contains( appointment1Id);
boolean contains2 = changedAppointments.contains( appointment2Id);
if ( contains1 || contains2)
{
Conflict oldConflict = conflict;
Appointment appointment1 = getAppointment( appointment1Id);
Appointment appointment2 = getAppointment( appointment2Id);
Conflict newConflict = new ConflictImpl( alloc, appointment1, appointment2, today);
toUpdateConflicts.put( oldConflict, newConflict);
}
}
}
}
// we update the conflict with the new appointment references
ArrayList<Conflict> updateList = new ArrayList<Conflict>( toUpdateConflicts.keySet());
for ( Conflict oldConflict:updateList)
{
Conflict newConflict = toUpdateConflicts.get( oldConflict);
Set<Conflict> conflicts = conflictMap.get( oldConflict.getAllocatable());
conflicts.remove( oldConflict);
conflicts.add( newConflict);
// we add a change operation
// TODO Note that this list also contains the NEW conflicts, but the UpdateResult.NEW could still contain the old conflicts
//if ( added.contains( oldConflict))
{
evt.addOperation( new UpdateResult.Change( newConflict, oldConflict));
}
}
}
// private SortedSet<Appointment> getAndCreateListId(Map<Allocatable,SortedSet<Appointment>> appointmentMap,Allocatable alloc) {
// SortedSet<Appointment> set = appointmentMap.get( alloc);
// if ( set == null)
// {
// set = new TreeSet<Appointment>();
// appointmentMap.put(alloc, set);
// }
// return set;
// }
// private Appointment getAppointment(
// SortedSet<Appointment> changedAppointments, Appointment appointment) {
// Appointment foundAppointment = changedAppointments.tailSet( appointment).iterator().next();
// return foundAppointment;
// }
public void removeOldConflicts(UpdateResult result, Date today)
{
for (Set<Conflict> sortedSet: conflictMap.values())
{
Iterator<Conflict> it = sortedSet.iterator();
while (it.hasNext())
{
Conflict conflict = it.next();
if ( endsBefore( conflict,today))
{
it.remove();
result.addOperation( new UpdateResult.Remove(conflict));
}
}
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.impl.server;
import org.rapla.framework.Configuration;
import org.rapla.framework.ConfigurationException;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.CachableStorageOperator;
import org.rapla.storage.CachableStorageOperatorCommand;
import org.rapla.storage.ImportExportManager;
import org.rapla.storage.LocalCache;
/** Imports the content of on store into another.
Export does an import with source and destination exchanged.
<p>Configuration:</p>
<pre>
<importexport id="importexport" activation="request">
<source>raplafile</source>
<dest>rapladb</dest>
</importexport>
</pre>
*/
public class ImportExportManagerImpl implements ImportExportManager {
Container container;
String sourceString;
String destString;
Logger logger;
public ImportExportManagerImpl(RaplaContext context,Configuration configuration) throws RaplaException
{
this.logger = context.lookup( Logger.class);
this.container = context.lookup( Container.class);
try {
sourceString = configuration.getChild("source").getValue();
destString = configuration.getChild("dest").getValue();
} catch (ConfigurationException e) {
throw new RaplaException( e);
}
}
protected Logger getLogger() {
return logger.getChildLogger("importexport");
}
/* Import the source into dest. */
public void doImport() throws RaplaException {
Logger logger = getLogger();
logger.info("Import from " + sourceString + " into " + destString);
CachableStorageOperator source = getSource();
source.connect();
CachableStorageOperator destination = getDestination();
doConvert(source,destination);
logger.info("Import completed");
}
/* Export the dest into source. */
public void doExport() throws RaplaException {
Logger logger = getLogger();
logger.info("Export from " + destString + " into " + sourceString);
CachableStorageOperator destination = getDestination();
destination.connect();
CachableStorageOperator source = getSource();
doConvert(destination,source);
logger.info("Export completed");
}
private void doConvert(final CachableStorageOperator cachableStorageOperator1,final CachableStorageOperator cachableStorageOperator2) throws RaplaException {
cachableStorageOperator1.runWithReadLock( new CachableStorageOperatorCommand() {
public void execute(LocalCache cache) throws RaplaException {
cachableStorageOperator2.saveData(cache);
}
});
}
@Override
public CachableStorageOperator getSource() throws RaplaException
{
CachableStorageOperator lookup = container.lookup(CachableStorageOperator.class, sourceString);
return lookup;
}
@Override
public CachableStorageOperator getDestination() throws RaplaException
{
CachableStorageOperator lookup = container.lookup(CachableStorageOperator.class, destString);
return lookup;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.rapla.components.util.Assert;
import org.rapla.components.util.TimeInterval;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.Named;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.internal.PreferencesImpl;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.dynamictype.Attribute;
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.internal.CategoryImpl;
import org.rapla.entities.internal.ModifiableTimestamp;
import org.rapla.entities.storage.EntityReferencer;
import org.rapla.entities.storage.EntityReferencer.ReferenceInfo;
import org.rapla.entities.storage.EntityResolver;
import org.rapla.entities.storage.RefEntity;
import org.rapla.entities.storage.internal.SimpleEntity;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.logger.Logger;
import org.rapla.storage.LocalCache;
import org.rapla.storage.PreferencePatch;
import org.rapla.storage.StorageOperator;
import org.rapla.storage.StorageUpdateListener;
import org.rapla.storage.UpdateEvent;
import org.rapla.storage.UpdateResult;
/**
* An abstract implementation of the StorageOperator-Interface. It operates on a
* LocalCache-Object and doesn't implement connect, isConnected, refresh,
* createIdentifier and disconnect. <b>!!WARNING!!</b> This operator is not
* thread-safe. {@link org.rapla.server.internal.ServerServiceImpl} for an
* example of an thread-safe wrapper around this storageoperator.
*
* @see LocalCache
*/
public abstract class AbstractCachableOperator implements StorageOperator {
protected RaplaLocale raplaLocale;
final List<StorageUpdateListener> storageUpdateListeners = new Vector<StorageUpdateListener>();
Map<String,String> createdPreferenceIds = new HashMap<String,String>();
protected LocalCache cache;
protected I18nBundle i18n;
protected RaplaContext context;
Logger logger;
protected ReadWriteLock lock = new ReentrantReadWriteLock();
public AbstractCachableOperator(RaplaContext context, Logger logger) throws RaplaException {
this.logger = logger;
this.context = context;
raplaLocale = context.lookup(RaplaLocale.class);
i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
Assert.notNull(raplaLocale.getLocale());
cache = new LocalCache();
}
public Logger getLogger() {
return logger;
}
public User connect() throws RaplaException {
return connect(null);
}
// Implementation of StorageOperator
public <T extends Entity> T editObject(T o, User user)throws RaplaException {
Set<Entity>singleton = Collections.singleton( (Entity)o);
Collection<Entity> list = editObjects( singleton, user);
Entity first = list.iterator().next();
@SuppressWarnings("unchecked")
T casted = (T) first;
return casted;
}
public Collection<Entity> editObjects(Collection<Entity>list, User user)throws RaplaException {
checkConnected();
Collection<Entity> toEdit = new LinkedHashSet<Entity>();
// read lock
Map<Entity,Entity> persistantMap = getPersistant(list);
// read unlock
for (Entity o:list)
{
Entity persistant = persistantMap.get(o);
Entity refEntity = editObject(o, persistant, user);
toEdit.add( refEntity);
}
return toEdit;
}
protected Entity editObject(Entity newObj, Entity persistant, User user) {
final SimpleEntity clone;
if ( persistant != null)
{
clone = (SimpleEntity) persistant.clone();
}
else
{
clone = (SimpleEntity) newObj.clone();
}
SimpleEntity refEntity = clone;
if (refEntity instanceof ModifiableTimestamp) {
((ModifiableTimestamp) refEntity).setLastChangedBy(user);
}
return (Entity) refEntity;
}
public void storeAndRemove(final Collection<Entity> storeObjects, final Collection<Entity>removeObjects, final User user) throws RaplaException {
checkConnected();
UpdateEvent evt = new UpdateEvent();
if (user != null) {
evt.setUserId(user.getId());
}
for (Entity obj : storeObjects) {
if ( obj instanceof Preferences)
{
PreferencePatch patch = ((PreferencesImpl)obj).getPatch();
evt.putPatch( patch);
}
else
{
evt.putStore(obj);
}
}
for (Entity entity : removeObjects) {
RaplaType type = entity.getRaplaType();
if (Appointment.TYPE ==type || Category.TYPE == type || Attribute.TYPE == type) {
String name = getName( entity);
throw new RaplaException(getI18n().format("error.remove_object",name));
}
evt.putRemove(entity);
}
dispatch(evt);
}
/**
* implement this method to implement the persistent mechanism. By default it
* calls <li>check()</li> <li>update()</li> <li>fireStorageUpdate()</li> <li>
* fireTriggerEvents()</li> You should not call dispatch directly from the
* client. Use storeObjects and removeObjects instead.
*/
public abstract void dispatch(UpdateEvent evt) throws RaplaException;
public Collection<User> getUsers() throws RaplaException {
checkConnected();
Lock readLock = readLock();
try
{
Collection<User> collection = cache.getUsers();
// We return a clone to avoid synchronization Problems
return new LinkedHashSet<User>(collection);
}
finally
{
unlock(readLock);
}
}
public Collection<DynamicType> getDynamicTypes() throws RaplaException {
checkConnected();
Lock readLock = readLock();
try
{
Collection<DynamicType> collection = cache.getDynamicTypes();
// We return a clone to avoid synchronization Problems
return new ArrayList<DynamicType>( collection);
}
finally
{
unlock(readLock);
}
}
public Collection<Allocatable> getAllocatables(ClassificationFilter[] filters) throws RaplaException
{
Collection<Allocatable> allocatables = new LinkedHashSet<Allocatable>();
checkConnected();
Lock readLock = readLock();
try
{
Collection<Allocatable> collection = cache.getAllocatables();
// We return a clone to avoid synchronization Problems
allocatables.addAll(collection);
}
finally
{
unlock(readLock);
}
removeFilteredClassifications(allocatables, filters);
return allocatables;
}
protected void removeFilteredClassifications( Collection<? extends Classifiable> list, ClassificationFilter[] filters) {
if (filters == null)
{
// remove internal types if not specified in filters to remain backwards compatibility
Iterator<? extends Classifiable> it = list.iterator();
while (it.hasNext()) {
Classifiable classifiable = it.next();
if ( DynamicTypeImpl.isInternalType(classifiable) )
{
it.remove();
}
}
return;
}
Iterator<? extends Classifiable> it = list.iterator();
while (it.hasNext()) {
Classifiable classifiable = it.next();
if (!ClassificationFilter.Util.matches(filters, classifiable))
{
it.remove();
}
}
}
public User getUser(final String username) throws RaplaException {
checkConnected();
Lock readLock = readLock();
try
{
return cache.getUser(username);
}
finally
{
unlock(readLock);
}
}
Map<String,PreferencesImpl> emptyPreferencesProxy = new ConcurrentHashMap<String, PreferencesImpl>();
public Preferences getPreferences(final User user, boolean createIfNotNull) throws RaplaException {
checkConnected();
// Test if user is already stored
if (user != null) {
resolve(user.getId(), User.class);
}
String userId = user != null ? user.getId() : null;
String preferenceId = PreferencesImpl.getPreferenceIdFromUser(userId);
PreferencesImpl pref = (PreferencesImpl) cache.tryResolve( preferenceId, Preferences.class);
if (pref == null && createIfNotNull )
{
PreferencesImpl preferencesImpl = emptyPreferencesProxy.get( preferenceId);
if ( preferencesImpl != null)
{
return preferencesImpl;
}
}
if (pref == null && createIfNotNull) {
PreferencesImpl newPref = newPreferences(userId);
newPref.setReadOnly( );
pref = newPref;
emptyPreferencesProxy.put(preferenceId , pref);
}
return pref;
}
private PreferencesImpl newPreferences(final String userId) throws EntityNotFoundException {
Date now = getCurrentTimestamp();
String id = PreferencesImpl.getPreferenceIdFromUser(userId);
PreferencesImpl newPref = new PreferencesImpl(now,now);
newPref.setResolver( this);
if ( userId != null)
{
User user = resolve( userId, User.class);
newPref.setOwner(user);
}
newPref.setId( id );
return newPref;
}
public Category getSuperCategory() {
return cache.getSuperCategory();
}
public synchronized void addStorageUpdateListener(StorageUpdateListener listener) {
storageUpdateListeners.add(listener);
}
public synchronized void removeStorageUpdateListener(StorageUpdateListener listener) {
storageUpdateListeners.remove(listener);
}
public synchronized StorageUpdateListener[] getStorageUpdateListeners() {
return storageUpdateListeners.toArray(new StorageUpdateListener[] {});
}
protected Lock writeLock() throws RaplaException {
return RaplaComponent.lock( lock.writeLock(), 60);
}
protected Lock readLock() throws RaplaException {
return RaplaComponent.lock( lock.readLock(), 10);
}
protected void unlock(Lock lock) {
RaplaComponent.unlock( lock );
}
protected I18nBundle getI18n() {
return i18n;
}
protected void fireStorageUpdated(final UpdateResult evt) {
StorageUpdateListener[] listeners = getStorageUpdateListeners();
for (int i = 0; i < listeners.length; i++) {
listeners[i].objectsUpdated(evt);
}
}
protected void fireUpdateError(final RaplaException ex) {
if (storageUpdateListeners.size() == 0)
return;
StorageUpdateListener[] listeners = getStorageUpdateListeners();
for (int i = 0; i < listeners.length; i++) {
listeners[i].updateError(ex);
}
}
protected void fireStorageDisconnected(String message) {
if (storageUpdateListeners.size() == 0)
return;
StorageUpdateListener[] listeners = getStorageUpdateListeners();
for (int i = 0; i < listeners.length; i++) {
listeners[i].storageDisconnected(message);
}
}
// End of StorageOperator interface
protected void checkConnected() throws RaplaException {
if (!isConnected())
{
throw new RaplaException(getI18n().format("error.connection_closed", ""));
}
}
@Override
public Map<String,Entity> getFromId(Collection<String> idSet, boolean throwEntityNotFound) throws RaplaException {
Lock readLock = readLock();
try
{
Map<String, Entity> result= new LinkedHashMap<String,Entity>();
for ( String id:idSet)
{
Entity persistant = (throwEntityNotFound ? cache.resolve(id) : cache.tryResolve(id));
if ( persistant != null)
{
result.put( id,persistant);
}
}
return result;
}
finally
{
unlock(readLock);
}
}
@Override
public Map<Entity,Entity> getPersistant(Collection<? extends Entity> list) throws RaplaException
{
Map<String,Entity> idMap = new LinkedHashMap<String,Entity>();
for ( Entity key: list)
{
String id = key.getId().toString();
idMap.put( id, key);
}
Map<Entity,Entity> result = new LinkedHashMap<Entity,Entity>();
Set<String> keySet = idMap.keySet();
Map<String,Entity> resolvedList = getFromId( keySet, false);
for (Entity entity:resolvedList.values())
{
String id = entity.getId().toString();
Entity key = idMap.get( id);
if ( key != null )
{
result.put( key, entity);
}
}
return result;
}
/**
* @throws RaplaException
*/
protected void setResolver(Collection<? extends Entity> entities) throws RaplaException {
for (Entity entity: entities) {
if (entity instanceof EntityReferencer)
{
((EntityReferencer)entity).setResolver(this);
}
}
// It is important to do the read only later because some resolve might involve write to referenced objects
for (Entity entity: entities) {
if (entity instanceof RefEntity)
{
((RefEntity)entity).setReadOnly();
}
}
}
protected void testResolve(Collection<? extends Entity> entities) throws EntityNotFoundException {
EntityStore store = new EntityStore( this, getSuperCategory());
store.addAll( entities);
for (Entity entity: entities) {
if (entity instanceof EntityReferencer)
{
((EntityReferencer)entity).setResolver(store);
}
}
for (Entity entity: entities) {
if (entity instanceof EntityReferencer)
{
testResolve(store, (EntityReferencer)entity);
}
}
}
private void testResolve(EntityResolver resolver, EntityReferencer referencer) throws EntityNotFoundException {
Iterable<ReferenceInfo> referencedIds =referencer.getReferenceInfo();
for ( ReferenceInfo id:referencedIds)
{
testResolve(resolver, referencer, id);
}
}
private void testResolve(EntityResolver resolver, EntityReferencer obj, ReferenceInfo reference) throws EntityNotFoundException {
Class<? extends Entity> class1 = reference.getType();
String id = reference.getId();
if (tryResolve(resolver,id, class1) == null)
{
String prefix = (class1!= null) ? class1.getName() : " unkown type";
throw new EntityNotFoundException(prefix + " with id " + id + " not found for " + obj);
}
}
protected String getName(Object object) {
if (object == null)
return null;
if (object instanceof Named)
return (((Named) object).getName(i18n.getLocale()));
return object.toString();
}
protected String getString(String key) {
return getI18n().getString(key);
}
public DynamicType getDynamicType(String key) {
Lock readLock = null;
try {
readLock = readLock();
} catch (RaplaException e) {
// this is not so dangerous
getLogger().warn("Returning type " + key + " without read lock ");
}
try
{
return cache.getDynamicType( key);
}
finally
{
unlock(readLock);
}
}
@Override
public Entity tryResolve(String id)
{
return tryResolve( id, null);
}
@Override
public Entity resolve(String id) throws EntityNotFoundException
{
return resolve( id, null);
}
@Override
public <T extends Entity> T tryResolve(String id,Class<T> entityClass) {
Lock readLock = null;
try {
readLock = readLock();
} catch (RaplaException e) {
getLogger().warn("Returning object for id " + id + " without read lock ");
}
try
{
return tryResolve(cache,id, entityClass);
}
finally
{
unlock(readLock);
}
}
@Override
public <T extends Entity> T resolve(String id,Class<T> entityClass) throws EntityNotFoundException {
Lock readLock;
try {
readLock = readLock();
} catch (RaplaException e) {
throw new EntityNotFoundException( e.getMessage() + " " +e.getCause());
}
try
{
return resolve(cache,id, entityClass);
}
finally
{
unlock(readLock);
}
}
protected <T extends Entity> T resolve(EntityResolver resolver,String id,Class<T> entityClass) throws EntityNotFoundException {
T entity = tryResolve(resolver,id, entityClass);
SimpleEntity.checkResolveResult(id, entityClass, entity);
return entity;
}
protected <T extends Entity> T tryResolve(EntityResolver resolver,String id,Class<T> entityClass) {
return resolver.tryResolve(id, entityClass);
}
/** Writes the UpdateEvent in the cache */
protected UpdateResult update(final UpdateEvent evt) throws RaplaException {
HashMap<Entity,Entity> oldEntities = new HashMap<Entity,Entity>();
// First make a copy of the old entities
Collection<Entity>storeObjects = new LinkedHashSet<Entity>(evt.getStoreObjects());
for (Entity entity : storeObjects)
{
Entity persistantEntity = findPersistant(entity);
if ( persistantEntity == null)
{
continue;
}
if (getLogger().isDebugEnabled())
{
getLogger().debug("Storing old: " + entity);
}
if ( persistantEntity instanceof Appointment || ((persistantEntity instanceof Category) && storeObjects.contains( ((Category) persistantEntity).getParent())))
{
throw new RaplaException( persistantEntity.getRaplaType() + " can only be stored via parent entity ");
// we ingore subentities, because these are added as bellow via addSubentites. The originals will be contain false parent references (to the new parents) when copy is called
}
else
{
Entity oldEntity = persistantEntity;
oldEntities.put(persistantEntity, oldEntity);
}
}
Collection<PreferencePatch> preferencePatches = evt.getPreferencePatches();
for ( PreferencePatch patch:preferencePatches)
{
String userId = patch.getUserId();
PreferencesImpl oldEntity = cache.getPreferencesForUserId( userId);
PreferencesImpl clone;
if ( oldEntity == null)
{
clone = newPreferences( userId);
}
else
{
clone = oldEntity.clone();
}
clone.applyPatch( patch);
oldEntities.put(clone, oldEntity);
storeObjects.add( clone);
}
List<Entity>updatedEntities = new ArrayList<Entity>();
// Then update the new entities
for (Entity entity : storeObjects) {
Entity persistant = findPersistant(entity);
// do nothing, because the persitantVersion is always read only
if (persistant == entity) {
continue;
}
if ( entity instanceof Category)
{
Category category = (Category)entity;
CategoryImpl parent = (CategoryImpl)category.getParent();
if ( parent != null)
{
parent.replace( category);
}
}
cache.put(entity);
updatedEntities.add(entity);
}
Collection<Entity> removeObjects = evt.getRemoveObjects();
Collection<Entity> toRemove = new HashSet<Entity>();
for (Entity entity : removeObjects) {
Entity persistantVersion = findPersistant(entity);
if (persistantVersion != null) {
cache.remove(persistantVersion);
((RefEntity)persistantVersion).setReadOnly();
}
toRemove.add( entity);
}
setResolver(updatedEntities);
TimeInterval invalidateInterval = evt.getInvalidateInterval();
String userId = evt.getUserId();
return createUpdateResult(oldEntities, updatedEntities, toRemove, invalidateInterval, userId);
}
protected Entity findPersistant(Entity entity) {
@SuppressWarnings("unchecked")
Class<? extends Entity> typeClass = entity.getRaplaType().getTypeClass();
Entity persistantEntity = cache.tryResolve(entity.getId(), typeClass);
return persistantEntity;
}
protected UpdateResult createUpdateResult(
Map<Entity,Entity> oldEntities,
Collection<Entity>updatedEntities,
Collection<Entity>toRemove,
TimeInterval invalidateInterval,
String userId)
throws EntityNotFoundException {
User user = null;
if (userId != null) {
user = resolve(cache,userId, User.class);
}
UpdateResult result = new UpdateResult(user);
if ( invalidateInterval != null)
{
result.setInvalidateInterval( invalidateInterval);
}
for (Entity toUpdate:updatedEntities)
{
Entity newEntity = toUpdate;
Entity oldEntity = oldEntities.get(toUpdate);
if (oldEntity != null) {
result.addOperation(new UpdateResult.Change( newEntity, oldEntity));
} else {
result.addOperation(new UpdateResult.Add( newEntity));
}
}
for (Entity entity:toRemove)
{
result.addOperation(new UpdateResult.Remove(entity));
}
return result;
}
}
| Java |
package org.rapla.storage;
import org.rapla.framework.RaplaException;
public interface CachableStorageOperatorCommand {
public void execute( LocalCache cache) throws RaplaException;
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.storage;
import org.rapla.framework.RaplaException;
/**
* This exception is thrown on an invalid login,
* or when a client tries to access data without
* the proper permissions.
*/
public class RaplaSecurityException extends RaplaException {
private static final long serialVersionUID = 1L;
public RaplaSecurityException(String text) {
super(text);
}
public RaplaSecurityException(Throwable throwable) {
super(throwable);
}
public RaplaSecurityException(String text,Throwable ex) {
super(text,ex);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.rapla.components.util.CommandScheduler;
import org.rapla.components.util.IOUtil;
import org.rapla.components.util.xml.RaplaNonValidatedInput;
import org.rapla.components.xmlbundle.CompoundI18n;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.components.xmlbundle.LocaleSelector;
import org.rapla.components.xmlbundle.impl.I18nBundleImpl;
import org.rapla.entities.domain.AppointmentFormater;
import org.rapla.entities.dynamictype.internal.AttributeImpl;
import org.rapla.facade.CalendarOptions;
import org.rapla.facade.RaplaComponent;
import org.rapla.facade.internal.CalendarOptionsImpl;
import org.rapla.framework.Configuration;
import org.rapla.framework.Provider;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaDefaultContext;
import org.rapla.framework.RaplaLocale;
import org.rapla.framework.ServiceListCreator;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.TypedComponentRole;
import org.rapla.framework.internal.ComponentInfo;
import org.rapla.framework.internal.ConfigTools;
import org.rapla.framework.internal.ContainerImpl;
import org.rapla.framework.internal.RaplaJDKLoggingAdapter;
import org.rapla.framework.internal.RaplaLocaleImpl;
import org.rapla.framework.internal.RaplaMetaConfigInfo;
import org.rapla.framework.logger.Logger;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.rest.gwtjsonrpc.common.ResultImpl;
import org.rapla.storage.dbrm.RaplaConnectException;
import org.rapla.storage.dbrm.RaplaHTTPConnector;
import org.rapla.storage.dbrm.RemoteConnectionInfo;
import org.rapla.storage.dbrm.RemoteMethodStub;
import org.rapla.storage.dbrm.RemoteServiceCaller;
import org.rapla.storage.dbrm.StatusUpdater;
import org.rapla.storage.dbrm.StatusUpdater.Status;
/**
The Rapla Main Container class for the basic container for Rapla specific services and the rapla plugin architecture.
The rapla container has only one instance at runtime. Configuration of the RaplaMainContainer is done in the rapla*.xconf
files. Typical configurations of the MainContainer are
<ol>
<li>Client: A ClientContainerService, one facade and a remote storage ( automaticaly pointing to the download server in webstart mode)</li>
<li>Server: A ServerContainerService (providing a facade) a messaging server for handling the connections with the clients, a storage (file or db) and an extra service for importing and exporting in the db</li>
<li>Standalone: A ClientContainerService (with preconfigured auto admin login) and a ServerContainerService that is directly connected to the client without http communication.</li>
<li>Embedded: Configuration example follows.</li>
</ol>
<p>
Configuration of the main container is usually done via the raplaserver.xconf
</p>
<p>
The Main Container provides the following Services to all RaplaComponents
<ul>
<li>I18nBundle</li>
<li>AppointmentFormater</li>
<li>RaplaLocale</li>
<li>LocaleSelector</li>
<li>RaplaMainContainer.PLUGIN_LIST (A list of all available plugins)</li>
</ul>
</p>
@see I18nBundle
@see RaplaLocale
@see AppointmentFormater
@see LocaleSelector
*/
final public class RaplaMainContainer extends ContainerImpl
{
public static final TypedComponentRole<Configuration> RAPLA_MAIN_CONFIGURATION = new TypedComponentRole<Configuration>("org.rapla.MainConfiguration");
public static final TypedComponentRole<String> DOWNLOAD_SERVER = new TypedComponentRole<String>("download-server");
public static final TypedComponentRole<URL> DOWNLOAD_URL = new TypedComponentRole<URL>("download-url");
public static final TypedComponentRole<String> ENV_RAPLADATASOURCE = new TypedComponentRole<String>("env.rapladatasource");
public static final TypedComponentRole<String> ENV_RAPLAFILE = new TypedComponentRole<String>("env.raplafile");
public static final TypedComponentRole<Object> ENV_RAPLADB= new TypedComponentRole<Object>("env.rapladb");
public static final TypedComponentRole<Object> ENV_RAPLAMAIL= new TypedComponentRole<Object>("env.raplamail");
public static final TypedComponentRole<Boolean> ENV_DEVELOPMENT = new TypedComponentRole<Boolean>("env.development");
public static final TypedComponentRole<Object> TIMESTAMP = new TypedComponentRole<Object>("timestamp");
public static final TypedComponentRole<String> CONTEXT_ROOT = new TypedComponentRole<String>("context-root");
public final static TypedComponentRole<Set<String>> PLUGIN_LIST = new TypedComponentRole<Set<String>>("plugin-list");
public final static TypedComponentRole<String> TITLE = new TypedComponentRole<String>("org.rapla.title");
public final static TypedComponentRole<String> TIMEZONE = new TypedComponentRole<String>("org.rapla.timezone");
Logger callLogger;
public RaplaMainContainer() throws Exception {
this(new RaplaStartupEnvironment());
}
public RaplaMainContainer(StartupEnvironment env) throws Exception {
this( env, new RaplaDefaultContext() );
}
public RaplaMainContainer( StartupEnvironment env, RaplaContext context) throws Exception
{
this( env,context,createRaplaLogger());
}
RemoteConnectionInfo globalConnectInfo;
CommandScheduler commandQueue;
public RaplaMainContainer( StartupEnvironment env, RaplaContext context,Logger logger) throws Exception{
super( context, env.getStartupConfiguration(),logger );
addContainerProvidedComponentInstance( StartupEnvironment.class, env);
addContainerProvidedComponentInstance( DOWNLOAD_SERVER, env.getDownloadURL().getHost());
addContainerProvidedComponentInstance( DOWNLOAD_URL, env.getDownloadURL());
commandQueue = createCommandQueue();
addContainerProvidedComponentInstance( CommandScheduler.class, commandQueue);
addContainerProvidedComponentInstance( RemoteServiceCaller.class, new RemoteServiceCaller() {
@Override
public <T> T getRemoteMethod(Class<T> a) throws RaplaContextException {
return RaplaMainContainer.this.getRemoteMethod(getContext(), a);
}
} );
if (env.getContextRootURL() != null)
{
File file = IOUtil.getFileFrom( env.getContextRootURL());
addContainerProvidedComponentInstance( CONTEXT_ROOT, file.getPath());
}
addContainerProvidedComponentInstance( TIMESTAMP, new Object() {
public String toString() {
DateFormat formatter = new SimpleDateFormat("yyyyMMdd-HHmmss");
String formatNow = formatter.format(new Date());
return formatNow;
}
});
initialize();
}
private static Logger createRaplaLogger()
{
Logger logger;
try {
RaplaMainContainer.class.getClassLoader().loadClass("org.slf4j.Logger");
@SuppressWarnings("unchecked")
Provider<Logger> logManager = (Provider<Logger>) RaplaMainContainer.class.getClassLoader().loadClass("org.rapla.framework.internal.Slf4jAdapter").newInstance();
logger = logManager.get();
logger.info("Logging via SLF4J API.");
} catch (Throwable e1) {
Provider<Logger> logManager = new RaplaJDKLoggingAdapter( );
logger = logManager.get();
logger.info("Logging via java.util.logging API. " + e1.toString());
}
return logger;
}
protected Map<String,ComponentInfo> getComponentInfos() {
return new RaplaMetaConfigInfo();
}
private void initialize() throws Exception {
Logger logger = getLogger();
int startupMode = getStartupEnvironment().getStartupMode();
logger.debug("----------- Rapla startup mode = " + startupMode);
RaplaLocaleImpl raplaLocale = new RaplaLocaleImpl(m_config.getChild("locale"), logger);
Configuration localeConfig = m_config.getChild("locale");
CalendarOptions calendarOptions = new CalendarOptionsImpl(localeConfig);
addContainerProvidedComponentInstance( CalendarOptions.class, calendarOptions );
addContainerProvidedComponentInstance( RAPLA_MAIN_CONFIGURATION, m_config );
addContainerProvidedComponent( RaplaNonValidatedInput.class, ConfigTools.RaplaReaderImpl.class);
// Startup mode= EMBEDDED = 0, CONSOLE = 1, WEBSTART = 2, APPLET = 3, SERVLET = 4
addContainerProvidedComponentInstance( RaplaLocale.class,raplaLocale);
addContainerProvidedComponentInstance( LocaleSelector.class,raplaLocale.getLocaleSelector());
m_config.getChildren("rapla-client");
String defaultBundleName = m_config.getChild("default-bundle").getValue( null);
// Override the intern Resource Bundle with user provided
Configuration parentConfig = I18nBundleImpl.createConfig( RaplaComponent.RAPLA_RESOURCES.getId() );
if ( defaultBundleName!=null) {
I18nBundleImpl i18n = new I18nBundleImpl( getContext(), I18nBundleImpl.createConfig( defaultBundleName ), logger);
String parentId = i18n.getParentId();
if ( parentId != null && parentId.equals(RaplaComponent.RAPLA_RESOURCES.getId()))
{
I18nBundleImpl parent = new I18nBundleImpl( getContext(), parentConfig, logger);
I18nBundle compound = new CompoundI18n( i18n, parent);
addContainerProvidedComponentInstance(RaplaComponent.RAPLA_RESOURCES, compound);
}
else
{
addContainerProvidedComponent(RaplaComponent.RAPLA_RESOURCES,I18nBundleImpl.class, parentConfig);
}
}
else
{
addContainerProvidedComponent(RaplaComponent.RAPLA_RESOURCES,I18nBundleImpl.class, parentConfig);
}
addContainerProvidedComponentInstance( AppointmentFormater.class, new AppointmentFormaterImpl( getContext()));
// Discover and register the plugins for Rapla
Set<String> pluginNames = new LinkedHashSet<String>();
boolean isDevelopment = getContext().has(RaplaMainContainer.ENV_DEVELOPMENT) && getContext().lookup( RaplaMainContainer.ENV_DEVELOPMENT);
Enumeration<URL> pluginEnum = ConfigTools.class.getClassLoader().getResources("META-INF/rapla-plugin.list");
if (!pluginEnum.hasMoreElements() || isDevelopment)
{
Collection<String> result = ServiceListCreator.findPluginClasses(logger);
pluginNames.addAll(result);
}
while ( pluginEnum.hasMoreElements() ) {
BufferedReader reader = new BufferedReader(new InputStreamReader((pluginEnum.nextElement()).openStream()));
while ( true ) {
String plugin = reader.readLine();
if ( plugin == null)
break;
pluginNames.add(plugin);
}
}
addContainerProvidedComponentInstance( PLUGIN_LIST, pluginNames);
logger.info("Config=" + getStartupEnvironment().getConfigURL());
I18nBundle i18n = getContext().lookup(RaplaComponent.RAPLA_RESOURCES);
String version = i18n.getString( "rapla.version" );
logger.info("Rapla.Version=" + version);
version = i18n.getString( "rapla.build" );
logger.info("Rapla.Build=" + version);
AttributeImpl.TRUE_TRANSLATION.setName(i18n.getLang(), i18n.getString("yes"));
AttributeImpl.FALSE_TRANSLATION.setName(i18n.getLang(), i18n.getString("no"));
try {
version = System.getProperty("java.version");
logger.info("Java.Version=" + version);
} catch (SecurityException ex) {
version = "-";
logger.warn("Permission to system property java.version is denied!");
}
callLogger =logger.getChildLogger("call");
}
public void dispose() {
getLogger().info("Shutting down rapla-container");
if ( commandQueue != null)
{
((DefaultScheduler)commandQueue).cancel();
}
super.dispose();
}
public <T> T getRemoteMethod(final RaplaContext context,final Class<T> a) throws RaplaContextException
{
if (context.has( RemoteMethodStub.class))
{
RemoteMethodStub server = context.lookup(RemoteMethodStub.class);
return server.getWebserviceLocalStub(a);
}
InvocationHandler proxy = new InvocationHandler()
{
RemoteConnectionInfo localConnectInfo;
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
if ( method.getName().equals("setConnectInfo") && method.getParameterTypes()[0].equals(RemoteConnectionInfo.class))
{
localConnectInfo = (RemoteConnectionInfo) args[0];
if ( globalConnectInfo == null)
{
globalConnectInfo =localConnectInfo;
}
return null;
}
RemoteConnectionInfo remoteConnectionInfo = localConnectInfo != null ? localConnectInfo : globalConnectInfo;
if ( remoteConnectionInfo == null)
{
throw new IllegalStateException("you need to call setConnectInfo first");
}
Class<?> returnType = method.getReturnType();
String methodName = method.getName();
final URL server;
try
{
server = new URL( remoteConnectionInfo.getServerURL());
}
catch (MalformedURLException e)
{
throw new RaplaContextException(e.getMessage());
}
StatusUpdater statusUpdater = remoteConnectionInfo.getStatusUpdater();
if ( statusUpdater != null)
{
statusUpdater.setStatus( Status.BUSY );
}
FutureResult result;
try
{
result = call(context,server, a, methodName, args, remoteConnectionInfo);
if (callLogger.isDebugEnabled())
{
callLogger.debug("Calling " + server + " " + a.getName() + "."+methodName);
}
}
finally
{
if ( statusUpdater != null)
{
statusUpdater.setStatus( Status.READY );
}
}
if ( !FutureResult.class.isAssignableFrom(returnType))
{
return result.get();
}
return result;
}
};
ClassLoader classLoader = a.getClassLoader();
@SuppressWarnings("unchecked")
Class<T>[] interfaces = new Class[] {a};
@SuppressWarnings("unchecked")
T proxyInstance = (T)Proxy.newProxyInstance(classLoader, interfaces, proxy);
return proxyInstance;
}
static private FutureResult call( RaplaContext context,URL server,Class<?> service, String methodName,Object[] args,RemoteConnectionInfo connectionInfo) {
RaplaHTTPConnector connector = new RaplaHTTPConnector();
try {
FutureResult result =connector.call(service, methodName, args, connectionInfo);
return result;
} catch (RaplaConnectException ex) {
return new ResultImpl(getConnectError(context,ex, server.toString()));
} catch (Exception ex) {
return new ResultImpl(ex);
}
}
static private RaplaConnectException getConnectError(RaplaContext context,RaplaConnectException ex2, String server) {
try
{
String message = context.lookup(RaplaComponent.RAPLA_RESOURCES).format("error.connect", server) + " " + ex2.getMessage();
return new RaplaConnectException(message);
}
catch (Exception ex)
{
return new RaplaConnectException("Connection error with server " + server + ": " + ex2.getMessage());
}
}
}
| Java |
/*
* Sun Microsystems grants you ("Licensee") a non-exclusive, royalty
* free, license to use, modify and redistribute this software in
* source and binary code form, provided that i) this copyright notice
* and license appear on all copies of the software; and ii) Licensee
* does not utilize the software in a manner which is disparaging to
* Sun Microsystems.
*
* The software media is distributed on an "As Is" basis, without
* warranty. Neither the authors, the software developers nor Sun
* Microsystems make any representation, or warranty, either express
* or implied, with respect to the software programs, their quality,
* accuracy, or fitness for a specific purpose. Therefore, neither the
* authors, the software developers nor Sun Microsystems shall have
* any liability to you or any other person or entity with respect to
* any liability, loss, or damage caused or alleged to have been
* caused directly or indirectly by programs contained on the
* media. This includes, but is not limited to, interruption of
* service, loss of data, loss of classroom time, loss of consulting
* or anticipatory *profits, or consequential damages from the use of
* these programs.
*/
package org.rapla.components.tablesorter;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
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.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
/**
* TableSorter is a decorator for TableModels; adding sorting
* functionality to a supplied TableModel. TableSorter does
* not store or copy the data in its TableModel; instead it maintains
* a map from the row indexes of the view to the row indexes of the
* model. As requests are made of the sorter (like getValueAt(row, col))
* they are passed to the underlying model after the row numbers
* have been translated via the internal mapping array. This way,
* the TableSorter appears to hold another copy of the table
* with the rows in a different order.
* <p/>
* TableSorter registers itself as a listener to the underlying model,
* just as the JTable itself would. Events recieved from the model
* are examined, sometimes manipulated (typically widened), and then
* passed on to the TableSorter's listeners (typically the JTable).
* If a change to the model has invalidated the order of TableSorter's
* rows, a note of this is made and the sorter will resort the
* rows the next time a value is requested.
* <p/>
* When the tableHeader property is set, either by using the
* setTableHeader() method or the two argument constructor, the
* table header may be used as a complete UI for TableSorter.
* The default renderer of the tableHeader is decorated with a renderer
* that indicates the sorting status of each column. In addition,
* a mouse listener is installed with the following behavior:
* <ul>
* <li>
* Mouse-click: Clears the sorting status of all other columns
* and advances the sorting status of that column through three
* values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to
* NOT_SORTED again).
* <li>
* SHIFT-mouse-click: Clears the sorting status of all other columns
* and cycles the sorting status of the column through the same
* three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
* <li>
* CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except
* that the changes to the column do not cancel the statuses of columns
* that are already sorting - giving a way to initiate a compound
* sort.
* </ul>
* <p/>
* This is a long overdue rewrite of a class of the same name that
* first appeared in the swing table demos in 1997.
*
* @author Philip Milne
* @author Brendon McLean
* @author Dan van Enckevort
* @author Parwinder Sekhon
* @version 2.0 02/27/04
*/
public class TableSorter extends AbstractTableModel {
private static final long serialVersionUID = 1L;
protected TableModel tableModel;
public static final int DESCENDING = -1;
public static final int NOT_SORTED = 0;
public static final int ASCENDING = 1;
private Map<Integer,Boolean> enabled= new HashMap<Integer,Boolean>();
private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
@SuppressWarnings("rawtypes")
public static final Comparator<Comparable> COMPARABLE_COMAPRATOR = new Comparator<Comparable>() {
@SuppressWarnings("unchecked")
public int compare(Comparable o1, Comparable o2) {
return o1.compareTo(o2);
}
};
private Row[] viewToModel;
private int[] modelToView;
private JTableHeader tableHeader;
private MouseListener mouseListener;
private TableModelListener tableModelListener;
private Map<Integer,Comparator<?>> columnComparators = new HashMap<Integer,Comparator<?>>();
private List<Directive> sortingColumns = new ArrayList<Directive>();
public TableSorter() {
this.mouseListener = new MouseHandler();
this.tableModelListener = new TableModelHandler();
}
public TableSorter(TableModel tableModel) {
this();
setTableModel(tableModel);
}
public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
this();
setTableHeader(tableHeader);
setTableModel(tableModel);
}
private void clearSortingState() {
viewToModel = null;
modelToView = null;
}
public TableModel getTableModel() {
return tableModel;
}
public void setTableModel(TableModel tableModel) {
if (this.tableModel != null) {
this.tableModel.removeTableModelListener(tableModelListener);
}
this.tableModel = tableModel;
if (this.tableModel != null) {
this.tableModel.addTableModelListener(tableModelListener);
}
clearSortingState();
fireTableStructureChanged();
}
public JTableHeader getTableHeader() {
return tableHeader;
}
public void setTableHeader(JTableHeader tableHeader) {
if (this.tableHeader != null) {
this.tableHeader.removeMouseListener(mouseListener);
TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
if (defaultRenderer instanceof SortableHeaderRenderer) {
this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
}
}
this.tableHeader = tableHeader;
if (this.tableHeader != null) {
this.tableHeader.addMouseListener(mouseListener);
this.tableHeader.setDefaultRenderer(
new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
}
}
public boolean isSorting() {
return sortingColumns.size() != 0;
}
private Directive getDirective(int column) {
for (int i = 0; i < sortingColumns.size(); i++) {
Directive directive = sortingColumns.get(i);
if (directive.column == column) {
return directive;
}
}
return EMPTY_DIRECTIVE;
}
public int getSortingStatus(int column) {
return getDirective(column).direction;
}
private void sortingStatusChanged() {
clearSortingState();
fireTableDataChanged();
if (tableHeader != null) {
tableHeader.repaint();
}
}
public void setSortingStatus(int column, int status) {
Directive directive = getDirective(column);
if (directive != EMPTY_DIRECTIVE) {
sortingColumns.remove(directive);
}
if (status != NOT_SORTED) {
sortingColumns.add(new Directive(column, status));
}
sortingStatusChanged();
}
protected Icon getHeaderRendererIcon(int column, int size) {
Directive directive = getDirective(column);
if (directive == EMPTY_DIRECTIVE) {
return null;
}
return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
}
private void cancelSorting() {
sortingColumns.clear();
sortingStatusChanged();
}
public void setColumnComparator(int column, Comparator<?> comparator) {
if (comparator == null) {
columnComparators.remove(column);
} else {
columnComparators.put(column, comparator);
}
setSortingStatus(column, ASCENDING);
}
@SuppressWarnings("rawtypes")
protected Comparator getComparator(int column) {
Comparator<?> comparator = columnComparators.get(column);
if (comparator != null) {
return comparator;
}
Class<?> columnType = tableModel.getColumnClass(column);
if ( columnType.isAssignableFrom( String.class))
{
return String.CASE_INSENSITIVE_ORDER;
}
if (Comparable.class.isAssignableFrom(columnType)) {
return COMPARABLE_COMAPRATOR;
}
return String.CASE_INSENSITIVE_ORDER;
}
private Row[] getViewToModel() {
if (viewToModel == null) {
int tableModelRowCount = tableModel.getRowCount();
viewToModel = new Row[tableModelRowCount];
for (int row = 0; row < tableModelRowCount; row++) {
viewToModel[row] = new Row(row);
}
if (isSorting()) {
Arrays.sort(viewToModel);
}
}
return viewToModel;
}
public int modelIndex(int viewIndex) {
return getViewToModel()[viewIndex].modelIndex;
}
private int[] getModelToView() {
if (modelToView == null) {
int n = getViewToModel().length;
modelToView = new int[n];
for (int i = 0; i < n; i++) {
modelToView[modelIndex(i)] = i;
}
}
return modelToView;
}
// TableModel interface methods
public int getRowCount() {
return (tableModel == null) ? 0 : tableModel.getRowCount();
}
public int getColumnCount() {
return (tableModel == null) ? 0 : tableModel.getColumnCount();
}
public String getColumnName(int column) {
return tableModel.getColumnName(column);
}
public Class<?> getColumnClass(int column) {
return tableModel.getColumnClass(column);
}
public boolean isCellEditable(int row, int column) {
return tableModel.isCellEditable(modelIndex(row), column);
}
public Object getValueAt(int row, int column) {
return tableModel.getValueAt(modelIndex(row), column);
}
public void setValueAt(Object aValue, int row, int column) {
tableModel.setValueAt(aValue, modelIndex(row), column);
}
// Helper classes
private class Row implements Comparable<Object> {
private int modelIndex;
public Row(int index) {
this.modelIndex = index;
}
@SuppressWarnings("unchecked")
public int compareTo(Object o) {
int row1 = modelIndex;
int row2 = ((Row) o).modelIndex;
for (Iterator<Directive> it = sortingColumns.iterator(); it.hasNext();) {
Directive directive = it.next();
int column = directive.column;
Object o1 = tableModel.getValueAt(row1, column);
Object o2 = tableModel.getValueAt(row2, column);
int comparison = 0;
// Define null less than everything, except null.
if (o1 == null && o2 == null) {
comparison = 0;
} else if (o1 == null) {
comparison = -1;
} else if (o2 == null) {
comparison = 1;
} else {
if ( isSortabe(column) )
{
comparison = getComparator(column).compare(o1, o2);
}
}
if (comparison != 0) {
return directive.direction == DESCENDING ? -comparison : comparison;
}
}
return 0;
}
}
private class TableModelHandler implements TableModelListener {
public void tableChanged(TableModelEvent e) {
// If we're not sorting by anything, just pass the event along.
if (!isSorting()) {
clearSortingState();
fireTableChanged(e);
return;
}
// If the table structure has changed, cancel the sorting; the
// sorting columns may have been either moved or deleted from
// the model.
if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
cancelSorting();
fireTableChanged(e);
return;
}
// We can map a cell event through to the view without widening
// when the following conditions apply:
//
// a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
// b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
// c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
// d) a reverse lookup will not trigger a sort (modelToView != null)
//
// Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
//
// The last check, for (modelToView != null) is to see if modelToView
// is already allocated. If we don't do this check; sorting can become
// a performance bottleneck for applications where cells
// change rapidly in different parts of the table. If cells
// change alternately in the sorting column and then outside of
// it this class can end up re-sorting on alternate cell updates -
// which can be a performance problem for large tables. The last
// clause avoids this problem.
int column = e.getColumn();
if (e.getFirstRow() == e.getLastRow()
&& column != TableModelEvent.ALL_COLUMNS
&& getSortingStatus(column) == NOT_SORTED
&& modelToView != null) {
int viewIndex = getModelToView()[e.getFirstRow()];
fireTableChanged(new TableModelEvent(TableSorter.this,
viewIndex, viewIndex,
column, e.getType()));
return;
}
// Something has happened to the data that may have invalidated the row order.
clearSortingState();
fireTableDataChanged();
return;
}
}
private class MouseHandler extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
JTableHeader h = (JTableHeader) e.getSource();
TableColumnModel columnModel = h.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
if ( viewColumn != -1)
{
int column = columnModel.getColumn(viewColumn).getModelIndex();
if (column != -1) {
if ( !isSortabe( column))
{
return;
}
int status = getSortingStatus(column);
if (!e.isControlDown()) {
cancelSorting();
}
// Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
// {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
status = status + (e.isShiftDown() ? -1 : 1);
status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
setSortingStatus(column, status);
}
}
}
}
private static class Arrow implements Icon {
private boolean descending;
private int size;
private int priority;
public Arrow(boolean descending, int size, int priority) {
this.descending = descending;
this.size = size;
this.priority = priority;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Color color = c == null ? Color.gray : c.getBackground();
// In a compound sort, make each succesive triangle 20%
// smaller than the previous one.
int dx = (int)(size/2*Math.pow(0.8, priority));
int dy = descending ? dx : -dx;
// Align icon (roughly) with font baseline.
y = y + 5*size/6 + (descending ? -dy : 0);
int shift = descending ? 1 : -1;
g.translate(x, y);
// Right diagonal.
g.setColor(color.darker());
g.drawLine(dx / 2, dy, 0, 0);
g.drawLine(dx / 2, dy + shift, 0, shift);
// Left diagonal.
g.setColor(color.brighter());
g.drawLine(dx / 2, dy, dx, 0);
g.drawLine(dx / 2, dy + shift, dx, shift);
// Horizontal line.
if (descending) {
g.setColor(color.darker().darker());
} else {
g.setColor(color.brighter().brighter());
}
g.drawLine(dx, 0, 0, 0);
g.setColor(color);
g.translate(-x, -y);
}
public int getIconWidth() {
return size;
}
public int getIconHeight() {
return size;
}
}
private class SortableHeaderRenderer implements TableCellRenderer {
private TableCellRenderer tableCellRenderer;
public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
this.tableCellRenderer = tableCellRenderer;
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
Component c = tableCellRenderer.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
if (c instanceof JLabel) {
JLabel l = (JLabel) c;
l.setHorizontalTextPosition(JLabel.LEFT);
int modelColumn = table.convertColumnIndexToModel(column);
l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
}
return c;
}
}
private static class Directive {
private int column;
private int direction;
public Directive(int column, int direction) {
this.column = column;
this.direction = direction;
}
}
public void setSortable(int column, boolean b) {
enabled.put( column,b);
}
public boolean isSortabe( int column)
{
final Boolean sortable = enabled.get(column);
if ( sortable == null)
{
return true;
}
return sortable;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.AbstractButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.ButtonUI;
public class NavButton extends AbstractButton implements MouseListener {
private static final long serialVersionUID = 1L;
Polygon m_poly;
char m_type;
boolean m_buttonDown = false;
Color m_disabledColor;
boolean m_enabled=true;
boolean m_border=true;
int m_delay = 0;
int leftPosition;
ButtonStateChecker m_checker = new ButtonStateChecker();
/** You can set the alignment of the arrow with one of these four characters:
'<', '^', '>', 'v'
*/
public NavButton(char type) {
this(type,18);
}
public NavButton(char type,int size) {
this(type,size,true);
}
public NavButton(char type,int size,boolean border) {
super();
m_border = border;
m_type = type;
setSize(size,size);
addMouseListener(this);
m_disabledColor = UIManager.getColor("Button.disabledText");
}
/** Here you can set if the button should fire repeated clicks. If
set to 0 the button will fire only once when pressed.
*/
public void setClickRepeatDelay(int millis) {
m_delay = millis;
}
public int getClickRepeatDelay() {
return m_delay;
}
public void setUI(ButtonUI ui) {
super.setUI(ui);
m_disabledColor = UIManager.getColor("Button.disabledText");
}
void setLeftPosition(int position) {
leftPosition = position;
}
/** Implementation-specific. Should be private.*/
public void mouseEntered(MouseEvent me) {
}
/** Implementation-specific. Should be private.*/
public void mouseExited(MouseEvent me) {
}
/** Implementation-specific. Should be private.*/
public void mousePressed(MouseEvent me) {
if (!isEnabled())
return;
m_buttonDown = true;
repaint();
m_checker.start();
}
/** Implementation-specific. Should be private.*/
public void mouseReleased(MouseEvent me) {
m_buttonDown = false;
repaint();
}
/** Implementation-specific. Should be private.*/
public void mouseClicked(MouseEvent me) {
m_buttonDown = false;
repaint();
}
/** Set the size of the nav-button. A nav button is square.
The maximum of width and height will be used as new size.
*/
public void setSize(int width,int height) {
int size = Math.max(width,height);
m_poly = new ArrowPolygon(m_type,size,m_border);
super.setSize(size,size);
Dimension dim = new Dimension(size,size);
setPreferredSize(dim);
setMaximumSize(dim);
setMinimumSize(dim);
}
public void setEnabled(boolean enabled) {
m_enabled = enabled;
repaint();
}
public boolean isEnabled() {
return m_enabled;
}
public void paint(Graphics g) {
g.translate( leftPosition, 0);
if (m_buttonDown) {
//g.setColor( UIManager.getColor("Button.pressed"));
g.setColor( UIManager.getColor("Button.focus"));
g.fillPolygon(m_poly);
g.drawPolygon(m_poly);
} else {
if (isEnabled()) {
g.setColor( UIManager.getColor("Button.font") );
g.fillPolygon(m_poly);
} else {
g.setColor(m_disabledColor);
}
g.drawPolygon(m_poly);
}
}
class ButtonStateChecker implements Runnable{
long startMillis;
long startDelay;
public void start() {
startDelay = m_delay * 8;
fireAndReset();
if (m_delay > 0)
SwingUtilities.invokeLater(this);
}
private void fireAndReset() {
fireActionPerformed(new ActionEvent(this
,ActionEvent.ACTION_PERFORMED
,""));
startMillis = System.currentTimeMillis();
}
public void run() {
if (!m_buttonDown)
return;
if ((Math.abs(System.currentTimeMillis() - startMillis) > startDelay)) {
if (startDelay > m_delay)
startDelay = startDelay/2;
fireAndReset();
}
try {
Thread.sleep(10);
} catch (Exception ex) {
return;
}
SwingUtilities.invokeLater(this);
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
import java.awt.Color;
/** Implement this interface if you want to highlight special days or
show tooltip for some days. Use {@link DateRendererAdapter} if you
want to work with Date objects.
*/
public interface DateRenderer {
/** Specifies a rendering info ( colors and tooltip text) for the passed day.
Return null if you don't want to use rendering info for this day. month ranges from 1-12*/
public RenderingInfo getRenderingInfo(int dayOfWeek,int day,int month, int year);
class RenderingInfo
{
Color backgroundColor;
Color foregroundColor;
String tooltipText;
public RenderingInfo(Color backgroundColor, Color foregroundColor, String tooltipText) {
this.backgroundColor = backgroundColor;
this.foregroundColor = foregroundColor;
this.tooltipText = tooltipText;
}
public Color getBackgroundColor() {
return backgroundColor;
}
public Color getForegroundColor() {
return foregroundColor;
}
public String getTooltipText() {
return tooltipText;
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
import java.awt.Color;
/** Implement this interface if you want to highlight special times or
show tooltip for some times.
*/
public interface TimeRenderer {
/** Specifies a special background color for the passed time.
Return null if you want to use the default color.*/
public Color getBackgroundColor(int hourOfDay,int minute);
/** Specifies a tooltip text for the passed time.
Return null if you don't want to use a tooltip for this time.*/
public String getToolTipText(int hourOfDay,int minute);
/** returns a formated text of the duration can return null if the duration should not be appended, e.g. if its < 0*/
public String getDurationString(int durationInMinutes);
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/** The model is a wrapper arround an Calendar object.
*/
final class TimeModel {
Calendar m_calendar;
Locale m_locale;
private Date durationStart;
ArrayList<DateChangeListener> m_listenerList = new ArrayList<DateChangeListener>();
public TimeModel(Locale locale,TimeZone timeZone) {
m_locale = locale;
m_calendar = Calendar.getInstance(timeZone, m_locale);
trim(m_calendar);
m_calendar.setLenient(true);
}
public void addDateChangeListener(DateChangeListener listener) {
m_listenerList.add(listener);
}
public void removeDateChangeListener(DateChangeListener listener) {
m_listenerList.remove(listener);
}
public Locale getLocale() {return m_locale; }
public Date getTime() {
return m_calendar.getTime();
}
public Date getDurationStart()
{
return durationStart;
}
public void setDurationStart(Date durationStart)
{
if ( durationStart == null)
{
this.durationStart = durationStart;
return;
}
Calendar clone = Calendar.getInstance(m_calendar.getTimeZone(), m_locale);
clone.setTime( durationStart);
trim(clone);
this.durationStart = clone.getTime();
}
// #TODO Property change listener for TimeZone
public void setTimeZone(TimeZone timeZone) {
m_calendar.setTimeZone(timeZone);
}
public TimeZone getTimeZone() {
return m_calendar.getTimeZone();
}
public void setTime(int hours,int minutes) {
m_calendar.set(Calendar.HOUR_OF_DAY,hours);
m_calendar.set(Calendar.MINUTE,minutes);
trim(m_calendar);
fireDateChanged();
}
public void setTime(Date date) {
m_calendar.setTime(date);
trim(m_calendar);
fireDateChanged();
}
public boolean sameTime(Date date) {
Calendar calendar = Calendar.getInstance(getTimeZone(), getLocale());
calendar.setTime(date);
trim(calendar);
return calendar.getTime().equals(getTime());
}
private void trim(Calendar calendar) {
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
calendar.setTimeInMillis(0);
calendar.set(Calendar.HOUR_OF_DAY, hours);
calendar.set(Calendar.MINUTE, minutes);
}
public DateChangeListener[] getDateChangeListeners() {
return m_listenerList.toArray(new DateChangeListener[]{});
}
protected void fireDateChanged() {
DateChangeListener[] listeners = getDateChangeListeners();
DateChangeEvent evt = new DateChangeEvent(this,getTime());
for (int i = 0;i<listeners.length; i++) {
listeners[i].dateChanged(evt);
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2003 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.EventListenerList;
/** The RaplaNumber is an adapter for NumberField.
* <strong>Warning!<strong> Currently only Longs are supported.
* @see NumberField
*/
public final class RaplaNumber extends JPanel{
private static final long serialVersionUID = 1L;
NumberField m_numberField = null;
public static Number ZERO = new Long(0);
public static Number ONE = new Long(1);
public static Number DEFAULT_STEP_SIZE = new Long(1);
EventListenerList m_listenerList;
Listener m_listener = new Listener();
Number m_emptyValue = ZERO;
JPanel m_buttonPanel = new JPanel();
RaplaArrowButton m_upButton = new RaplaArrowButton('+', 15);//'^',10,false);
RaplaArrowButton m_downButton = new RaplaArrowButton('-', 15);//new NavButton('v',10,false);
/** currently only Longs are supported */
public RaplaNumber() {
this( null, null, null, false);
}
public RaplaNumber(Number value,Number minimum,Number maximum,boolean isNullPermitted) {
m_numberField = new NumberField(minimum,maximum,DEFAULT_STEP_SIZE.intValue(),10);
m_numberField.setNumber(value);
m_numberField.setNullPermitted(isNullPermitted);
if (minimum != null && minimum.longValue()>0)
m_emptyValue = minimum;
else if (maximum != null && maximum.longValue()<0)
m_emptyValue = maximum;
m_buttonPanel.setLayout(new GridLayout(2,1));
m_buttonPanel.add(m_upButton);
m_upButton.setBorder( null);
m_buttonPanel.add(m_downButton);
m_downButton.setBorder(null);
m_buttonPanel.setMinimumSize(new Dimension(18,20));
m_buttonPanel.setPreferredSize(new Dimension(18,20));
m_buttonPanel.setBorder(BorderFactory.createEtchedBorder());
m_upButton.setClickRepeatDelay(50);
m_downButton.setClickRepeatDelay(50);
m_upButton.addActionListener(m_listener);
m_downButton.addActionListener(m_listener);
setLayout(new BorderLayout());
add(m_numberField,BorderLayout.CENTER);
add(m_buttonPanel,BorderLayout.EAST);
m_upButton.setFocusable( false);
m_downButton.setFocusable( false);
}
public void setFont(Font font) {
super.setFont(font);
// Method called during constructor?
if (m_numberField == null || font == null)
return;
m_numberField.setFont(font);
}
public void setColumns(int columns) {
m_numberField.setColumns(columns);
}
public NumberField getNumberField() {
return m_numberField;
}
public void setEnabled( boolean enabled ) {
super.setEnabled( enabled );
if ( m_numberField != null ) {
m_numberField.setEnabled( enabled );
}
if ( m_upButton != null ) {
m_upButton.setEnabled ( enabled );
m_downButton.setEnabled ( enabled );
}
}
/** currently only Longs are supported */
public void setNumber(Number newValue) {
m_numberField.setNumber(newValue);
}
public Number getNumber() {
return m_numberField.getNumber();
}
public void addChangeListener(ChangeListener changeListener) {
if (m_listenerList == null) {
m_listenerList = new EventListenerList();
m_numberField.addChangeListener(m_listener);
}
m_listenerList.add(ChangeListener.class,changeListener);
}
public void removeChangeListener(ChangeListener changeListener) {
if (m_listenerList == null) {
return;
}
m_listenerList.remove(ChangeListener.class,changeListener);
}
class Listener implements ChangeListener,ActionListener {
public void actionPerformed(ActionEvent evt) {
m_numberField.requestFocus();
if (evt.getSource() == m_upButton) {
m_numberField.increase();
}
if (evt.getSource() == m_downButton) {
m_numberField.decrease();
}
SwingUtilities.invokeLater( new Runnable() {
public void run() {
stateChanged(null);
m_numberField.selectAll();
}
}
);
}
public void stateChanged(ChangeEvent originalEvent) {
if (m_listenerList == null)
return;
ChangeEvent evt = new ChangeEvent(RaplaNumber.this);
Object[] listeners = m_listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ChangeListener.class) {
((ChangeListener)listeners[i+1]).stateChanged(evt);
}
}
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
import java.util.Date;
import java.util.EventObject;
public class DateChangeEvent extends EventObject {
private static final long serialVersionUID = 1L;
Date m_date;
public DateChangeEvent(Object source,Date date) {
super(source);
m_date = date;
}
public Date getDate() {
return m_date;
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import javax.swing.JComponent;
import javax.swing.UIManager;
import org.rapla.components.calendar.DateRenderer.RenderingInfo;
/** The graphical date-selection field
* @author Christopher Kohlhaas
*/
final class DaySelection extends JComponent implements DateChangeListener,MouseListener {
private static final long serialVersionUID = 1L;
// 7 rows and 7 columns
static final int ROWS = 7; //including the header row
static final int COLUMNS = 7;
// 6 * 7 Fields for the Month + 7 Fields for the Header
static final int FIELDS = (ROWS - 1) * COLUMNS;
static final int HBORDER = 0; // horizontal BORDER of the component
static final int VBORDER = 0; // vertical BORDER of the component
static final int VGAP = 2; // vertical gap between the cells
static final int HGAP = 2; // horizontal gap between the cells
static final Color DARKBLUE = new Color(0x00, 0x00, 0x88);
static final Color LIGHTGRAY = new Color(0xdf, 0xdf, 0xdf);
static final Color FOCUSCOLOR = UIManager.getColor("Button.focus");
static final Color DEFAULT_CELL_BACKGROUND = Color.white;
static final Color HEADER = Color.white;
static final Color HEADER_BACKGROUND = DARKBLUE;
static final Color SELECTION = Color.white;
static final Color SELECTION_BACKGROUND = DARKBLUE;
static final Color SELECTION_BORDER = Color.red;
static final Color SELECTABLE = Color.black;
static final Color UNSELECTABLE = LIGHTGRAY;
/** stores the weekdays order e.g so,mo,tu,.. or mo,tu.
* Requirement: The week has seven days
*/
private int[] weekday2slot = new int[8];
/** stores the weekdayNames mon - sun.
* Requirement: The week has seven days.
*/
private String[] weekdayNames = new String[7];
/** stores the days 1 - 31 days[1] = 1
* <br>maximum days per month 40
*/
private String[] days = new String[40];
private int selectedField = 10;
private int focusedField = 10;
private DateModel model;
private DateModel focusModel;
private int lastFocusedMonth; // performance improvement
private int lastFocusedYear; // performance improvement
private PaintEnvironment e;
private DateRenderer dateRenderer = null;
public DaySelection(DateModel model,DateModel focusModel) {
this.model = model;
this.focusModel = focusModel;
focusModel.addDateChangeListener(this);
addMouseListener(this);
createWeekdays(model.getLocale());
createDays(model.getLocale());
// setFont(DEFAULT_FONT);
}
/** Implementation-specific. Should be private.*/
public void mousePressed(MouseEvent me) {
me.consume();
selectField(me.getX(),me.getY());
}
/** Implementation-specific. Should be private.*/
public void mouseReleased(MouseEvent me) {
me.consume();
}
/** Implementation-specific. Should be private.*/
public void mouseClicked(MouseEvent me) {
me.consume();
}
/** Implementation-specific. Should be private.*/
public void mouseEntered(MouseEvent me) {
}
/** You must call javax.swing.ToolTipManager.sharedInstance().registerComponent(thisComponent)
to enable ToolTip text.
*/
public String getToolTipText(MouseEvent me) {
int day = calcDay(me.getX(),me.getY());
if (day >=0 && dateRenderer != null)
return dateRenderer.getRenderingInfo(focusModel.getWeekday(day), day, focusModel.getMonth(), focusModel.getYear()).getTooltipText();
else
return "";
}
/** Implementation-specific. Should be private.*/
public void mouseExited(MouseEvent me) {
}
public void setDateRenderer(DateRenderer dateRenderer) {
this.dateRenderer = dateRenderer;
}
// Recalculate the Components minimum and maximum sizes
private void calculateSizes() {
if (e == null)
e = new PaintEnvironment();
int maxWidth =0;
FontMetrics fm = getFontMetrics(getFont());
e.fontHeight = fm.getHeight();
e.cellHeight = fm.getHeight() + VGAP *2;
for (int i=0;i<weekdayNames.length;i++) {
int len = fm.stringWidth(weekdayNames[i]);
if (len>maxWidth)
maxWidth = len;
}
if (fm.stringWidth("33")> maxWidth)
maxWidth = fm.stringWidth("33");
e.fontWidth = maxWidth;
e.cellWidth = maxWidth + HGAP * 2 ;
int width = COLUMNS * e.cellWidth + HBORDER *2;
setPreferredSize(new Dimension( width,(ROWS) * e.cellHeight + 2*HBORDER));
setMinimumSize(new Dimension( width,(ROWS) * e.cellHeight + 2*VBORDER));
invalidate();
}
public void setFont(Font font) {
super.setFont(font);
if (font == null)
return;
else
// We need the font-size to calculate the component size
calculateSizes();
}
public Dimension getPreferredSize() {
if (getFont() != null && e==null)
// We need the font-size to calculate the component size
calculateSizes();
return super.getPreferredSize();
}
public void dateChanged(DateChangeEvent evt) {
if (e==null)
// We need the font-size to calculate the component size
if (getFont() != null )
calculateSizes();
else
return;
int lastSelectedField = selectedField;
if (model.getMonth() == focusModel.getMonth() &&
model.getYear() == focusModel.getYear())
// #BUGFIX consider index shift.
// weekdays 1..7 and days 1..31 but field 0..40
selectedField = weekday2slot[model.firstWeekday()]+ (model.getDay() - 1) ;
else
selectedField = -1;
int lastFocusedField = focusedField;
// #BUGFIX consider index shift.
// weekdays 1..7 and days 1..31 but field 0..40
int newFocusedField = weekday2slot[focusModel.firstWeekday()] + (focusModel.getDay() - 1) ;
if (lastSelectedField == selectedField
&& lastFocusedMonth == focusModel.getMonth()
&& lastFocusedYear == focusModel.getYear()
) {
// Only repaint the focusedField (Performance improvement)
focusedField = -1;
calculateRectangle(lastFocusedField);
repaint(e.r);
focusedField = newFocusedField;
calculateRectangle(focusedField);
repaint(e.r);
} else {
// repaint everything
focusedField = newFocusedField;
repaint();
}
lastFocusedMonth = focusModel.getMonth();
lastFocusedYear = focusModel.getYear();
}
/** calculate the day of month from the specified field. 1..31
*/
private int calcDay(int field) {
return (field + 1) - weekday2slot[focusModel.firstWeekday()] ;
}
/** calculate the day of month from the x and y coordinates.
@return -1 if coordinates don't point to a day in the selected month
*/
private int calcDay(int x,int y) {
int col = (x - HBORDER) / e.cellWidth;
int row = (y - VBORDER) / e.cellHeight;
int field = 0;
// System.out.println(row + ":" + col);
if ( row > 0 && col < COLUMNS && row < ROWS) {
field =(row-1) * COLUMNS + col;
}
if (belongsToMonth(field)) {
return calcDay(field);
} else {
return -1;
}
}
private void createDays(Locale locale) {
NumberFormat format = NumberFormat.getInstance(locale);
// Try to simluate a right align of the numbers with a space
for ( int i=0; i <10; i++)
days[i] = " " + format.format(i);
for ( int i=10; i < 40; i++)
days[i] = format.format(i);
}
/** This method is necessary to shorten the names down to 2 characters.
Some date-formats ignore the setting.
*/
private String small(String string) {
return string.substring(0,Math.min(string.length(),2));
}
private void createWeekdays(Locale locale ) {
Calendar calendar = Calendar.getInstance(locale);
SimpleDateFormat format = new SimpleDateFormat("EE",locale);
calendar.set(Calendar.DAY_OF_WEEK,calendar.getFirstDayOfWeek());
for (int i=0;i<7;i++) {
weekday2slot[calendar.get(Calendar.DAY_OF_WEEK)] = i;
weekdayNames[i] = small(format.format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_WEEK,1);
}
}
// calculates the rectangle for a given field
private void calculateRectangle(int field) {
int row = (field / COLUMNS) + 1;
int col = (field % COLUMNS);
calculateRectangle(row,col);
}
// calculates the rectangle for a given row and col
private void calculateRectangle(int row,int col) {
Rectangle r = e.r;
r.x = e.cellWidth * col + HBORDER;
r.y = e.cellHeight * row + VBORDER;
r.width = e.cellWidth;
r.height = e.cellHeight;
}
private void calculateTextPos(int field) {
int row = (field / COLUMNS) + 1;
int col = (field % COLUMNS);
calculateTextPos(row,col);
}
// calculates the text-anchor for a giver field
private void calculateTextPos(int row,int col) {
Point p = e.p;
p.x = e.cellWidth * col + HBORDER + (e.cellWidth - e.fontWidth)/2;
p.y = e.cellHeight * row + VBORDER + e.fontHeight - 1;
}
private boolean belongsToMonth(int field) {
return (calcDay(field) > 0 && calcDay(field) <= focusModel.daysMonth());
}
private void selectField(int x,int y) {
int day = calcDay(x,y);
if ( day >=0 ) {
model.setDate(day, focusModel.getMonth(), focusModel.getYear());
} // end of if ()
}
private Color getBackgroundColor(RenderingInfo renderingInfo) {
Color color = null;
if ( renderingInfo != null)
{
color = renderingInfo.getBackgroundColor();
}
if (color != null)
return color;
return DEFAULT_CELL_BACKGROUND;
}
protected RenderingInfo getRenderingInfo(int field) {
RenderingInfo renderingInfo = null;
int day = calcDay(field);
if (belongsToMonth(field) && dateRenderer != null) {
renderingInfo = dateRenderer.getRenderingInfo(focusModel.getWeekday(day), day, focusModel.getMonth(), focusModel.getYear());
}
return renderingInfo;
}
// return the Daytext, that should be displayed in the specified field
private String getText(int field) {
int index = 0;
if ( calcDay(field) < 1)
index = focusModel.daysLastMonth() + calcDay(field) ;
if (belongsToMonth(field))
index = calcDay(field);
if ( calcDay(field) > focusModel.daysMonth() )
index = calcDay(field) - focusModel.daysMonth();
return days[index];
}
static char[] test = {'1'};
private void drawField(int field,boolean highlight) {
if (field <0)
return;
Graphics g = e.g;
Rectangle r = e.r;
Point p = e.p;
calculateRectangle(field);
RenderingInfo renderingInfo = getRenderingInfo( field);
if ( field == selectedField ) {
g.setColor(SELECTION_BACKGROUND);
g.fillRect(r.x +2 ,r.y +2 ,r.width-4,r.height-4);
g.setColor(SELECTION_BORDER);
//g.drawRect(r.x,r.y,r.width-1,r.height-1);
g.drawRect(r.x+1,r.y+1,r.width-3,r.height-3);
if ( field == focusedField )
{
g.setColor(FOCUSCOLOR);
}
else
{
g.setColor(getBackgroundColor(renderingInfo));
}
g.drawRect(r.x,r.y,r.width-1,r.height-1);
g.setColor(SELECTION);
} else if ( field == focusedField ) {
g.setColor(getBackgroundColor(renderingInfo));
g.fillRect(r.x,r.y,r.width -1,r.height -1);
g.setColor(FOCUSCOLOR);
g.drawRect(r.x,r.y,r.width-1,r.height-1);
if ( highlight) {
g.setColor(SELECTABLE);
} else {
g.setColor(UNSELECTABLE);
} // end of else
} else {
g.setColor(getBackgroundColor(renderingInfo));
g.fillRect(r.x ,r.y ,r.width ,r.height);
if ( highlight) {
g.setColor(SELECTABLE);
} else {
g.setColor(UNSELECTABLE);
} // end of else
}
calculateTextPos(field);
if ( field!= selectedField)
{
if ( renderingInfo != null)
{
Color foregroundColor = renderingInfo.getForegroundColor();
if ( foregroundColor != null)
{
g.setColor( foregroundColor);
}
}
}
g.drawString(getText(field)
, p.x , p.y);
}
private void drawHeader() {
Graphics g = e.g;
Point p = e.p;
g.setColor(HEADER_BACKGROUND);
g.fillRect(HBORDER,VBORDER, getSize().width - 2 * HBORDER, e.cellHeight);
g.setColor(HEADER);
for ( int i=0; i < COLUMNS; i++) {
calculateTextPos(0,i);
g.drawString(weekdayNames[i], p.x,p.y);
}
}
private void paintComplete() {
drawHeader();
int field = 0;
int start = weekday2slot[focusModel.firstWeekday()];
int end= start + focusModel.daysMonth() -1 ;
for ( int i=0; i< start; i++) {
drawField(field ++,false);
}
for ( int i= start; i <= end ; i++) {
drawField(field ++,true);
}
for ( int i= end + 1; i< FIELDS ; i++) {
drawField(field ++,false);
}
}
private void updateEnvironment(Graphics g) {
e.cellWidth = (getSize().width - HBORDER * 2) / COLUMNS;
e.g = g;
}
public void paint(Graphics g) {
super.paint(g);
if (e==null)
if (getFont() != null )
// We need the font-size to calculate the component size
calculateSizes();
else
return;
updateEnvironment(g);
paintComplete();
drawField(selectedField,true);
drawField(focusedField,true);
}
}
// Environment stores the values that would normaly be stored on the stack.
// This is to speedup performance, e.g. new Point and new Rectangle are only called once.
class PaintEnvironment {
Graphics g;
int cellWidth;
int cellHeight;
int fontWidth;
int fontHeight;
Point p = new Point();
Rectangle r = new Rectangle();
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
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.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.MenuElement;
import javax.swing.MenuSelectionManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/** A ComboBox like time chooser.
* It is localizable and it uses swing-components.
* <p>The combobox editor is a {@link TimeField}. If the ComboBox-Button
* is pressed a TimeSelectionList will drop down.</p>
* @author Christopher Kohlhaas
*/
public final class RaplaTime extends RaplaComboBox {
private static final long serialVersionUID = 1L;
protected TimeField m_timeField;
protected TimeList m_timeList;
protected TimeModel m_timeModel;
protected Collection<DateChangeListener> m_listenerList = new ArrayList<DateChangeListener>();
private Date m_lastTime;
private int m_visibleRowCount = -1;
private int m_rowsPerHour = 4;
private TimeRenderer m_renderer;
private static Image clock;
boolean m_showClock;
/** Create a new TimeBox with the default locale. */
public RaplaTime() {
this(Locale.getDefault(),TimeZone.getDefault(),true, true);
}
/** Create a new TimeBox with the specified locale and timeZone. */
public RaplaTime(Locale locale,TimeZone timeZone) {
this(locale,timeZone,true, true);
}
/** Create a new TimeBox with the specified locale and timeZone. The
isDropDown flag specifies if times could be selected
via a drop-down-box.
*/
public RaplaTime(Locale locale,TimeZone timeZone,boolean isDropDown, boolean showClock) {
super(isDropDown,new TimeField(locale,timeZone));
m_showClock = showClock;
m_timeModel = new TimeModel(locale, timeZone);
m_timeField = (TimeField) m_editorComponent;
Listener listener = new Listener();
m_timeField.addChangeListener(listener);
m_timeModel.addDateChangeListener(listener);
m_lastTime = m_timeModel.getTime();
if ( showClock )
{
if ( clock == null )
{
URL url = RaplaTime.class.getResource("clock.png");
if ( url != null )
{
clock =Toolkit.getDefaultToolkit().createImage(url );
MediaTracker m = new MediaTracker(this);
m.addImage(clock, 0);
try { m.waitForID(0); } catch (InterruptedException ex) {}
}
}
getLabel().setIcon( new ImageIcon( createClockImage()));
getLabel().setBorder( BorderFactory.createEmptyBorder(0,0,0,1));
}
}
public TimeField getTimeField()
{
return m_timeField;
}
static Color HOUR_POINTER = new Color( 40,40,100);
static Color MINUTE_POINTER = new Color( 100,100,180);
protected Image createClockImage() {
BufferedImage image = new BufferedImage( 17, 17, BufferedImage.TYPE_INT_ARGB);
Calendar calendar = Calendar.getInstance(getTimeZone(),m_timeModel.getLocale());
calendar.setTime( m_timeModel.getTime());
int hourOfDay = calendar.get( Calendar.HOUR_OF_DAY) % 12;
int minute = calendar.get( Calendar.MINUTE);
Graphics g = image.getGraphics();
double hourPos = (hourOfDay * 60 + minute - 180) / (60.0 * 12) * 2 * Math.PI ;
double minutePos = (minute -15) / 60.0 * 2 * Math.PI;
int xhour = (int) (Math.cos( hourPos) * 4.5);
int yhour = (int) (Math.sin( hourPos ) * 4.5 );
int xminute = (int) (Math.cos( minutePos ) * 6.5 );
int yminute = (int) (Math.sin( minutePos) * 6.5);
g.drawImage( clock,0,0,17,17, null);
g.setColor( HOUR_POINTER);
int centerx = 8;
int centery = 8;
g.drawLine( centerx, centery, centerx + xhour,centery + yhour);
g.setColor( MINUTE_POINTER);
g.drawLine( centerx, centery, centerx + xminute,centery +yminute);
return image;
}
/** The granularity of the selection rows:
* <ul>
* <li>1: 1 rows per hour = 1 Hour</li>
* <li>2: 2 rows per hour = 1/2 Hour</li>
* <li>2: 3 rows per hour = 20 Minutes</li>
* <li>4: 4 rows per hour = 15 Minutes</li>
* <li>6: 6 rows per hour = 10 Minutes</li>
* <li>12: 12 rows per hour = 5 Minutes</li>
* </ul>
*/
public void setRowsPerHour(int rowsPerHour) {
m_rowsPerHour = rowsPerHour;
if (m_timeList != null) {
throw new IllegalStateException("Property can only be set during initialization.");
}
}
/** @see #setRowsPerHour */
public int getRowsPerHour() {
return m_rowsPerHour;
}
class Listener implements ChangeListener,DateChangeListener {
// Implementation of ChangeListener
public void stateChanged(ChangeEvent evt) {
validateEditor();
}
public void dateChanged(DateChangeEvent evt) {
closePopup();
if (needSync())
m_timeField.setTime(evt.getDate());
if (m_lastTime == null || !m_lastTime.equals(evt.getDate()))
fireTimeChanged(evt.getDate());
m_lastTime = evt.getDate();
if ( clock != null && m_showClock)
{
getLabel().setIcon( new ImageIcon( createClockImage()));
}
}
}
/** test if we need to synchronize the dateModel and the m_timeField*/
private boolean needSync() {
return (m_timeField.getTime() != null && !m_timeModel.sameTime(m_timeField.getTime()));
}
protected void validateEditor() {
if (needSync())
m_timeModel.setTime(m_timeField.getTime());
}
/** the number of visble rows in the drop-down menu.*/
public void setVisibleRowCount(int count) {
m_visibleRowCount = count;
if (m_timeList != null)
m_timeList.getList().setVisibleRowCount(count);
}
public void setFont(Font font) {
super.setFont(font);
// Method called during constructor?
if (m_timeList == null || font == null)
return;
m_timeList.setFont(font);
}
public TimeZone getTimeZone() {
return m_timeField.getTimeZone();
}
/** Set the time relative to the given timezone.
* The date,month and year values will be ignored.
*/
public void setTime(Date time) {
m_timeModel.setTime(time);
}
public Date getDurationStart()
{
return m_timeModel.getDurationStart();
}
public void setDurationStart(Date durationStart)
{
m_timeModel.setDurationStart(durationStart);
if ( m_timeList != null)
{
m_timeList.setModel(m_timeModel,m_timeField.getOutputFormat());
}
}
/** Set the time relative to the given timezone.
*/
public void setTime(int hour, int minute) {
m_timeModel.setTime(hour,minute);
}
/** Parse this date with a calendar-object set to the correct
time-zone to get the hour,minute and second. The
date,month and year values should be ignored.
*/
public Date getTime() {
return m_timeModel.getTime();
}
protected void showPopup() {
validateEditor();
super.showPopup();
m_timeList.selectTime(m_timeField.getTime());
}
/** registers new DateChangedListener for this component.
* An DateChangedEvent will be fired to every registered DateChangedListener
* when the a different time is selected.
* @see DateChangeListener
* @see DateChangeEvent
*/
public void addDateChangeListener(DateChangeListener listener) {
m_listenerList.add(listener);
}
/** removes a listener from this component.*/
public void removeDateChangeListener(DateChangeListener listener) {
m_listenerList.remove(listener);
}
public DateChangeListener[] getDateChangeListeners() {
return m_listenerList.toArray(new DateChangeListener[]{});
}
protected void fireTimeChanged(Date date) {
DateChangeListener[] listeners = getDateChangeListeners();
if (listeners.length == 0)
return;
DateChangeEvent evt = new DateChangeEvent(this,date);
for (int i = 0; i<listeners.length; i++) {
listeners[i].dateChanged(evt);
}
}
/** The popup-component will be created lazily.*/
public JComponent getPopupComponent() {
if (m_timeList == null) {
m_timeList = new TimeList( m_rowsPerHour);
m_timeList.setFont( getFont() );
if (m_visibleRowCount>=0)
m_timeList.getList().setVisibleRowCount(m_visibleRowCount);
}
m_timeList.setTimeRenderer( m_renderer );
m_timeList.setModel(m_timeModel,m_timeField.getOutputFormat());
return m_timeList;
}
public void setTimeRenderer(TimeRenderer renderer) {
m_renderer = renderer;
}
}
class TimeList extends JPanel implements MenuElement,MouseListener,MouseMotionListener {
private static final long serialVersionUID = 1L;
JScrollPane scrollPane = new JScrollPane();
NavButton upButton = new NavButton('^',10);
NavButton downButton = new NavButton('v',10);
JList m_list;
DateFormat m_format;
TimeModel m_timeModel;
int m_rowsPerHour = 4;
int m_minutesPerRow = 60 / m_rowsPerHour;
TimeRenderer m_renderer;
private double getRowHeight() {
return m_list.getVisibleRect().getHeight()/m_list.getVisibleRowCount();
}
public TimeList(int rowsPerHour) {
super();
this.setLayout( new BorderLayout());
JPanel upPane = new JPanel();
upPane.setLayout( new BorderLayout());
upPane.add( upButton, BorderLayout.CENTER );
JPanel downPane = new JPanel();
downPane.setLayout( new BorderLayout());
downPane.add( downButton, BorderLayout.CENTER );
upButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e )
{
int direction = (int)- getRowHeight() * (m_list.getVisibleRowCount() -1);
JScrollBar bar = scrollPane.getVerticalScrollBar();
int value = Math.min( Math.max( 0, bar.getValue() + direction ), bar.getMaximum());
scrollPane.getVerticalScrollBar().setValue( value );
}
});
downButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e )
{
int direction = (int) getRowHeight() * (m_list.getVisibleRowCount() -1) ;
JScrollBar bar = scrollPane.getVerticalScrollBar();
int value = Math.min( Math.max( 0, bar.getValue() + direction ), bar.getMaximum());
scrollPane.getVerticalScrollBar().setValue( value );
}
});
/*
upPane.addMouseListener( new Mover( -1));
upButton.addMouseListener( new Mover( -1));
downPane.addMouseListener( new Mover( 1));
downButton.addMouseListener( new Mover( 1));
*/
//upPane.setPreferredSize( new Dimension(0,0));
//downPane.setPreferredSize( new Dimension(0,0));
this.add(upPane, BorderLayout.NORTH);
this.add( scrollPane, BorderLayout.CENTER);
this.add( downPane, BorderLayout.SOUTH);
scrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
scrollPane.getVerticalScrollBar().setEnabled( false );
scrollPane.getVerticalScrollBar().setSize( new Dimension(0,0));
scrollPane.getVerticalScrollBar().setPreferredSize( new Dimension(0,0));
scrollPane.getVerticalScrollBar().setMaximumSize( new Dimension(0,0));
scrollPane.getVerticalScrollBar().setMinimumSize( new Dimension(0,0));
m_rowsPerHour = rowsPerHour;
m_minutesPerRow = 60 / m_rowsPerHour;
//this.setLayout(new BorderLayout());
m_list = new JList();
scrollPane.setViewportView( m_list);
m_list.setBackground(this.getBackground());
//JScrollPane scrollPane = new JScrollPane(m_list, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
m_list.setVisibleRowCount(8);
m_list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
m_list.addMouseListener(this);
m_list.addMouseMotionListener(this);
DefaultListCellRenderer cellRenderer = new DefaultListCellRenderer() {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus )
{
int hour = getHourForIndex( index );
int minute = getMinuteForIndex( index );
String string = (String) value;
Component component = super.getListCellRendererComponent( list, string, index, isSelected,cellHasFocus );
if ( m_renderer!= null && !isSelected && !cellHasFocus ) {
Color color = m_renderer.getBackgroundColor( hour, minute );
if ( color != null ) {
component.setBackground( color );
}
}
return component;
}
};
setRenderer(cellRenderer);
}
@SuppressWarnings("unchecked")
private void setRenderer(DefaultListCellRenderer cellRenderer) {
m_list.setCellRenderer( cellRenderer);
}
@SuppressWarnings("unchecked")
public void setModel(TimeModel model,DateFormat format) {
m_timeModel = model;
m_format = (DateFormat) format.clone();
Calendar calendar = Calendar.getInstance(m_format.getTimeZone(),model.getLocale());
DefaultListModel listModel = new DefaultListModel();
for (int i=0;i<24 * m_rowsPerHour;i++) {
int hour = i/m_rowsPerHour;
int minute = (i%m_rowsPerHour) * m_minutesPerRow;
calendar.setTimeInMillis(0);
calendar.set(Calendar.HOUR_OF_DAY,hour );
calendar.set(Calendar.MINUTE,minute);
Date durationStart = m_timeModel.getDurationStart();
String duration = "";
if ( m_renderer != null && durationStart != null)
{
Date time = calendar.getTime();
long millis = time.getTime() - durationStart.getTime();
int durationInMinutes = (int) (millis / (1000 * 60));
duration = m_renderer.getDurationString(durationInMinutes);
}
String timeWithoutDuration = m_format.format(calendar.getTime());
String time = timeWithoutDuration;
if ( duration != null)
{
time += " " + duration;
}
listModel.addElement(" " + time + " ");
}
m_list.setModel(listModel);
int pos = (int)getPreferredSize().getWidth()/2 - 5;
upButton.setLeftPosition( pos);
downButton.setLeftPosition( pos );
}
public void setTimeRenderer(TimeRenderer renderer) {
m_renderer = renderer;
}
public JList getList() {
return m_list;
}
public void setFont(Font font) {
super.setFont(font);
if (m_list == null || font == null)
return;
m_list.setFont(font);
int pos = (int)getPreferredSize().getWidth()/2 - 5;
upButton.setLeftPosition( pos);
downButton.setLeftPosition( pos );
}
/** Implementation-specific. Should be private.*/
public void mousePressed(MouseEvent e) {
ok();
}
/** Implementation-specific. Should be private.*/
public void mouseClicked(MouseEvent e) {
}
/** Implementation-specific. Should be private.*/
public void mouseReleased(MouseEvent e) {
}
/** Implementation-specific. Should be private.*/
public void mouseEntered(MouseEvent me) {
}
/** Implementation-specific. Should be private.*/
public void mouseExited(MouseEvent me) {
}
private int lastIndex = -1;
private int lastY= -1;
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
if (e.getY() == lastY)
return;
lastY = e.getY();
Point p = new Point(e.getX(),e.getY());
int index = m_list.locationToIndex(p);
if (index == lastIndex)
return;
lastIndex = index;
m_list.setSelectedIndex(index);
}
public void selectTime(Date time) {
Calendar calendar = Calendar.getInstance(m_timeModel.getTimeZone(),m_timeModel.getLocale());
calendar.setTime(time);
int index = (calendar.get(Calendar.HOUR_OF_DAY)) * m_rowsPerHour
+ (calendar.get(Calendar.MINUTE) / m_minutesPerRow);
select(index);
}
private void select(int index) {
m_list.setSelectedIndex(index);
m_list.ensureIndexIsVisible(Math.max(index -3,0));
m_list.ensureIndexIsVisible(Math.min(index + 3,m_list.getModel().getSize() -1));
}
// Start of MenuElement implementation
public Component getComponent() {
return this;
}
public MenuElement[] getSubElements() {
return new MenuElement[0];
}
public void menuSelectionChanged(boolean isIncluded) {
}
public void processKeyEvent(KeyEvent event, MenuElement[] path, MenuSelectionManager manager) {
int index;
if (event.getID() == KeyEvent.KEY_PRESSED) {
switch (event.getKeyCode()) {
case (KeyEvent.VK_KP_UP):
case (KeyEvent.VK_UP):
index = m_list.getSelectedIndex();
if (index > 0)
select(index - 1);
break;
case (KeyEvent.VK_KP_DOWN):
case (KeyEvent.VK_DOWN):
index = m_list.getSelectedIndex();
if (index <m_list.getModel().getSize()-1)
select(index + 1);
break;
case (KeyEvent.VK_SPACE):
case (KeyEvent.VK_ENTER):
ok();
break;
case (KeyEvent.VK_ESCAPE):
manager.clearSelectedPath();
break;
}
// System.out.println(event.getKeyCode());
event.consume();
}
}
private int getHourForIndex( int index ) {
return index / m_rowsPerHour;
}
private int getMinuteForIndex( int index ) {
return (index % m_rowsPerHour) * m_minutesPerRow;
}
private void ok() {
int index = m_list.getSelectedIndex();
int hour = getHourForIndex( index );
int minute = getMinuteForIndex( index );
Calendar calendar = Calendar.getInstance(m_timeModel.getTimeZone(),m_timeModel.getLocale());
if (hour >= 0) {
calendar.set(Calendar.HOUR_OF_DAY,hour );
calendar.set(Calendar.MINUTE,minute);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND,0);
m_timeModel.setTime(calendar.getTime());
}
}
public void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager) {
}
// End of MenuElement implementation
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
/* The components that implement DateChangeListener
* get notified by the DateModel if the date has been changed
*/
public interface DateChangeListener extends java.util.EventListener {
public void dateChanged(DateChangeEvent evt);
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
public class RaplaArrowButton extends JButton {
private static final long serialVersionUID = 1L;
ButtonStateChecker m_checker = new ButtonStateChecker();
int m_delay = 0;
boolean m_buttonDown = false;
ArrowPolygon poly;
char c;
public RaplaArrowButton(char c) {
this(c,18);
}
public RaplaArrowButton(char c,int size) {
super();
this.c = c;
setMargin(new Insets(0,0,0,0));
setSize(size,size);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
if (!isEnabled())
return;
m_buttonDown = true;
// repaint();
m_checker.start();
}
/** Implementation-specific. Should be private.*/
public void mouseReleased(MouseEvent me) {
m_buttonDown = false;
// repaint();
}
/** Implementation-specific. Should be private.*/
public void mouseClicked(MouseEvent me) {
m_buttonDown = false;
//repaint();
}
});
}
/** Here you can set if the button should fire repeated clicks. If
set to 0 the button will fire only once when pressed.
*/
public void setClickRepeatDelay(int millis) {
m_delay = millis;
}
public int getClickRepeatDelay() {
return m_delay;
}
public boolean isOpen()
{
return c == '^';
}
public void setChar( char c)
{
this.c = c;
final Dimension size = getSize();
final int width2 = (int)size.getWidth();
final int height2 = (int)size.getHeight();
setSize( width2,height2);
}
/** Set the size of the drop-down button.
The minimum of width and height will be used as new size of the arrow.
*/
public void setSize(int width,int height) {
int size = Math.min(width,height);
int imageSize = size - 8;
if (imageSize > 0) {
poly = new ArrowPolygon(c,imageSize);
BufferedImage image = new BufferedImage(imageSize,imageSize,BufferedImage.TYPE_INT_ARGB);
Graphics g = image.createGraphics();
g.setColor(new Color(0, 0, 0, 0));
g.fillRect( 0, 0, imageSize, imageSize );
g.setColor( Color.darkGray );
g.fillPolygon( poly );
g.setColor( Color.black );
g.drawPolygon( poly );
setIcon(new ImageIcon(image));
} else {
setIcon(null);
}
super.setSize(width ,height);
Dimension dim = new Dimension(width ,height);
setPreferredSize(dim);
setMaximumSize(dim);
setMinimumSize(dim);
}
class ButtonStateChecker implements Runnable{
long startMillis;
long startDelay;
public void start() {
startDelay = m_delay * 10;
startMillis = System.currentTimeMillis();
if (m_delay > 0)
SwingUtilities.invokeLater(this);
}
private void fireAndReset() {
fireActionPerformed(new ActionEvent(this
,ActionEvent.ACTION_PERFORMED
,""));
startMillis = System.currentTimeMillis();
}
public void run() {
if (!m_buttonDown)
return;
if ((Math.abs(System.currentTimeMillis() - startMillis) > startDelay)) {
if (startDelay > m_delay)
startDelay = startDelay/2;
fireAndReset();
}
try {
Thread.sleep(10);
} catch (Exception ex) {
return;
}
SwingUtilities.invokeLater(this);
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/** Maps the DateRenderer methods to the appropriate date method.
@see DateRenderer
*/
public class DateRendererAdapter implements DateRenderer {
Calendar m_calendar;
DateRenderer m_renderer = null;
/** use this constructor if you want to implement a custom getBackgroundColor(Date)
or getToolTipText(Date) method.
*/
public DateRendererAdapter(TimeZone timeZone,Locale locale) {
m_calendar = Calendar.getInstance(timeZone,locale);
}
/** use this constructor if you want to make an existing {@link DateRenderer}
listen to the methods getBackgroundColor(Date) and getToolTipText(Date).
*/
public DateRendererAdapter(DateRenderer renderer,TimeZone timeZone,Locale locale) {
m_calendar = Calendar.getInstance(timeZone,locale);
m_renderer = renderer;
}
/** override this method for a custom renderiungInfo
@return null.*/
public RenderingInfo getRenderingInfo(Date date) {
if (m_renderer == null)
return null;
m_calendar.setTime(date);
return m_renderer.getRenderingInfo(
m_calendar.get(Calendar.DAY_OF_WEEK)
,m_calendar.get(Calendar.DATE)
,m_calendar.get(Calendar.MONTH) + 1
,m_calendar.get(Calendar.YEAR)
);
}
/* calls {@link #getBackgroundColor(Date)} */
public RenderingInfo getRenderingInfo(int dayOfWeek,int day,int month, int year) {
m_calendar.set(Calendar.DATE,day);
m_calendar.set(Calendar.MONTH,month -1 );
m_calendar.set(Calendar.YEAR,year);
m_calendar.set(Calendar.HOUR_OF_DAY,0);
m_calendar.set(Calendar.MINUTE,0);
m_calendar.set(Calendar.SECOND,0);
m_calendar.set(Calendar.MILLISECOND,0);
return getRenderingInfo(m_calendar.getTime());
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
/**
* The model of the obligatory MVC approach is a wrapper arround an
* Calendar object.
*/
final class DateModel {
private Calendar m_calendar;
private int m_daysMonth;
private int m_daysLastMonth;
private int m_firstWeekday;
private Locale m_locale;
private DateFormat m_yearFormat;
private DateFormat m_currentDayFormat;
ArrayList<DateChangeListener> listenerList = new ArrayList<DateChangeListener>();
public DateModel(Locale locale,TimeZone timeZone) {
m_locale = locale;
m_calendar = Calendar.getInstance(timeZone,m_locale);
trim(m_calendar);
m_yearFormat = new SimpleDateFormat("yyyy", m_locale);
m_yearFormat.setTimeZone(timeZone);
m_currentDayFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, m_locale);
m_currentDayFormat.setTimeZone(timeZone);
m_calendar.setLenient(true);
recalculate();
}
public boolean sameDate(Date date) {
Calendar calendar2 = Calendar.getInstance(m_locale);
TimeZone timeZone = getTimeZone();
calendar2.setTimeZone(timeZone);
calendar2.setTime(date);
trim(calendar2);
Date trimedDate = getDate();
Date date2 = calendar2.getTime();
return date2.equals(trimedDate);
}
public void addDateChangeListener(DateChangeListener listener) {
listenerList.add(listener);
}
public void removeDateChangeListener(DateChangeListener listener) {
listenerList.remove(listener);
}
public Locale getLocale() {return m_locale; }
public int getDay() { return m_calendar.get(Calendar.DATE); }
public int getMonth() { return m_calendar.get(Calendar.MONTH) + 1; }
public int getYear() { return m_calendar.get(Calendar.YEAR); }
/** return the number of days of the selected month */
public int daysMonth() { return m_daysMonth; }
/** return the number of days of the month before the selected month. */
public int daysLastMonth() { return m_daysLastMonth; }
/** return the first weekday of the selected month (1 - 7). */
public int firstWeekday() { return m_firstWeekday; }
/** calculates the weekday from the passed day. */
public int getWeekday(int day) {
// calculate the weekday, consider the index shift
return (((firstWeekday() - 1) + (day - 1)) % 7 ) + 1;
}
public Date getDate() {
return m_calendar.getTime();
}
// #TODO Property change listener for TimeZone
public void setTimeZone(TimeZone timeZone) {
m_calendar.setTimeZone(timeZone);
m_yearFormat.setTimeZone(timeZone);
m_currentDayFormat.setTimeZone(timeZone);
recalculate();
}
public TimeZone getTimeZone() {
return m_calendar.getTimeZone();
}
public String getDateString() {
return m_currentDayFormat.format(getDate());
}
public String getCurrentDateString() {
return m_currentDayFormat.format(new Date());
}
public void addMonth(int count) {
m_calendar.add(Calendar.MONTH,count);
recalculate();
}
public void addYear(int count) {
m_calendar.add(Calendar.YEAR,count);
recalculate();
}
public void addDay(int count) {
m_calendar.add(Calendar.DATE,count);
recalculate();
}
public void setDay(int day) {
m_calendar.set(Calendar.DATE,day);
recalculate();
}
public void setMonth(int month) {
m_calendar.set(Calendar.MONTH,month);
recalculate();
}
public String getYearString() {
DateFormat format;
if (m_calendar.get(Calendar.ERA)!=GregorianCalendar.AD)
format = new SimpleDateFormat("yyyy GG", getLocale());
else
format = m_yearFormat;
return format.format(getDate());
}
public void setYear(int year) {
m_calendar.set(Calendar.YEAR,year);
recalculate();
}
public void setDate(int day,int month,int year) {
m_calendar.set(Calendar.DATE,day);
m_calendar.set(Calendar.MONTH,month -1);
m_calendar.set(Calendar.YEAR,year);
trim(m_calendar);
recalculate();
}
public void setDate(Date date) {
m_calendar.setTime(date);
trim(m_calendar);
recalculate();
}
private void trim(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND,0);
}
// 18.02.2004 CK: Workaround for bug in JDK 1.5.0 .Replace add with roll
private void recalculate() {
Calendar calendar = Calendar.getInstance(getTimeZone(), getLocale());
Date date = getDate();
calendar.setTime(date);
// calculate the number of days of the selected month
calendar.add(Calendar.MONTH,1);
calendar.set(Calendar.DATE,1);
calendar.add(Calendar.DAY_OF_YEAR,-1);
calendar.getTime();
m_daysMonth = calendar.get(Calendar.DAY_OF_MONTH);
// calculate the number of days of the month before the selected month
calendar.set(Calendar.DATE,1);
m_firstWeekday = calendar.get(Calendar.DAY_OF_WEEK);
calendar.add(Calendar.DAY_OF_YEAR,-1);
m_daysLastMonth = calendar.get(Calendar.DAY_OF_MONTH);
// System.out.println("Calendar Recalculate: " + getDay() + "." + getMonth() + "." + getYear());
fireDateChanged();
}
public DateChangeListener[] getDateChangeListeners() {
return listenerList.toArray(new DateChangeListener[]{});
}
protected void fireDateChanged() {
DateChangeListener[] listeners = getDateChangeListeners();
Date date = getDate();
DateChangeEvent evt = new DateChangeEvent(this,date);
for (int i = 0;i<listeners.length; i++) {
listeners[i].dateChanged(evt);
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
import java.awt.Font;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import javax.swing.JComponent;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/** This is another ComboBox-like calendar component.
* It is localizable and it uses swing-components.
* <p>The combobox editor is a {@link DateField}. If the ComboBox-Button
* is pressed, a CalendarMenu will drop down.</p>
* @see CalendarMenu
* @see DateField
* @author Christopher Kohlhaas
*/
public final class RaplaCalendar extends RaplaComboBox {
private static final long serialVersionUID = 1L;
protected DateField m_dateField;
protected CalendarMenu m_calendarMenu;
Collection<DateChangeListener> m_listenerList = new ArrayList<DateChangeListener>();
protected DateModel m_model;
private Date m_lastDate;
DateRenderer m_dateRenderer;
/** Create a new Calendar with the default locale. The calendarmenu
will be accessible via a drop-down-box */
public RaplaCalendar() {
this(Locale.getDefault(),TimeZone.getDefault(),true);
}
public DateField getDateField()
{
return m_dateField;
}
/** Create a new Calendar with the specified locale and timezone. The calendarmenu
will be accessible via a drop-down-box */
public RaplaCalendar(Locale locale,TimeZone timeZone) {
this(locale,timeZone,true);
}
/** Create a new Calendar with the specified locale and timezone. The
isDropDown flag specifies if the calendarmenu should be
accessible via a drop-down-box. Alternatively you can get the
calendarmenu with getPopupComponent().
*/
public RaplaCalendar(Locale locale,TimeZone timeZone,boolean isDropDown) {
super(isDropDown,new DateField(locale,timeZone));
m_model = new DateModel(locale,timeZone);
m_dateField = (DateField) m_editorComponent;
Listener listener = new Listener();
m_dateField.addChangeListener(listener);
m_model.addDateChangeListener(listener);
m_lastDate = m_model.getDate();
setDateRenderer(new WeekendHighlightRenderer());
}
class Listener implements ChangeListener,DateChangeListener {
// Implementation of ChangeListener
public void stateChanged(ChangeEvent evt) {
validateEditor();
}
// Implementation of DateChangeListener
public void dateChanged(DateChangeEvent evt) {
closePopup();
if (needSync())
m_dateField.setDate(evt.getDate());
if (m_lastDate == null || !m_lastDate.equals(evt.getDate()))
fireDateChange(evt.getDate());
m_lastDate = evt.getDate();
}
}
public TimeZone getTimeZone() {
return m_model.getTimeZone();
}
/* Use this to get the CalendarMenu Component. The calendar menu will be created lazily.*/
public JComponent getPopupComponent() {
if (m_calendarMenu == null) {
m_calendarMenu = new CalendarMenu(m_model);
m_calendarMenu.setFont( getFont() );
// #TODO Property change listener for TimeZone
m_calendarMenu.getDaySelection().setDateRenderer(m_dateRenderer);
javax.swing.ToolTipManager.sharedInstance().registerComponent(m_calendarMenu.getDaySelection());
}
return m_calendarMenu;
}
public void setFont(Font font) {
super.setFont(font);
// Method called during super-constructor?
if (m_calendarMenu == null || font == null)
return;
m_calendarMenu.setFont(font);
}
/** Selects the date relative to the given timezone.
* The hour,minute,second and millisecond values will be ignored.
*/
public void setDate(Date date)
{
if ( date != null)
{
m_model.setDate(date);
}
else
{
boolean changed = m_dateField.getDate() != null;
m_dateField.setDate( null);
m_lastDate =null;
if ( changed )
{
fireDateChange(null);
}
}
}
/** Parse the returned date with a calendar-object set to the
* correct time-zone to get the date,month and year. The
* hour,minute,second and millisecond values should be ignored.
* @return the selected date
* @see #getYear
* @see #getMonth
* @see #getDay
*/
public Date getDate() {
if ( m_dateField.isNullValue())
{
return null;
}
return m_model.getDate();
}
/** selects the specified day, month and year.
@see #setDate(Date date)*/
public void select(int day,int month,int year) {
m_model.setDate(day,month,year);
}
/** sets the DateRenderer for the calendar */
public void setDateRenderer(DateRenderer dateRenderer) {
m_dateRenderer = dateRenderer;
if (m_calendarMenu != null) {
m_calendarMenu.getDaySelection().setDateRenderer(m_dateRenderer);
}
m_dateField.setDateRenderer(m_dateRenderer);
}
/** you can choose, if weekdays should be displayed in the right corner of the DateField.
Default is true. This method simply calls setWeekdaysVisble on the DateField Component.
If a DateRender is installed the weekday will be rendered with the DateRenderer.
This includes a tooltip that shows up on the DateRenderer.
@see DateField
*/
public void setWeekdaysVisibleInDateField(boolean bVisible) {
m_dateField.setWeekdaysVisible(bVisible);
}
/** @return the selected year (relative to the given TimeZone)
@see #getDate
@see #getMonth
@see #getDay
*/
public int getYear() {return m_model.getYear(); }
/** @return the selected month (relative to the given TimeZone)
@see #getDate
@see #getYear
@see #getDay
*/
public int getMonth() {return m_model.getMonth(); }
/** @return the selected day (relative to the given TimeZone)
@see #getDate
@see #getYear
@see #getMonth
*/
public int getDay() {return m_model.getDay(); }
/** registers new DateChangeListener for this component.
* A DateChangeEvent will be fired to every registered DateChangeListener
* when the a different date is selected.
* @see DateChangeListener
* @see DateChangeEvent
*/
public void addDateChangeListener( DateChangeListener listener ) {
m_listenerList.add(listener);
}
/** removes a listener from this component.*/
public void removeDateChangeListener( DateChangeListener listener ) {
m_listenerList.remove(listener);
}
public DateChangeListener[] getDateChangeListeners() {
return m_listenerList.toArray(new DateChangeListener[]{});
}
/** A DateChangeEvent will be fired to every registered DateChangeListener
* when the a different date is selected.
*/
protected void fireDateChange( Date date ) {
if (m_listenerList.size() == 0)
return;
DateChangeListener[] listeners = getDateChangeListeners();
DateChangeEvent evt = new DateChangeEvent(this,date);
for (int i = 0;i<listeners.length;i++) {
listeners[i].dateChanged(evt);
}
}
protected void showPopup() {
validateEditor();
super.showPopup();
}
/** test if we need to synchronize the dateModel and the dateField*/
private boolean needSync() {
return (isNullValuePossible() && m_dateField.getDate() == null ) || (m_dateField.getDate() != null && !m_model.sameDate(m_dateField.getDate())) ;
}
protected void validateEditor() {
if (needSync() )
if (m_dateField.isNullValue())
{
if ( m_lastDate != null)
{
m_lastDate = null;
fireDateChange(null);
}
}
else
{
m_model.setDate(m_dateField.getDate());
}
}
public boolean isNullValuePossible()
{
return m_dateField.isNullValuePossible();
}
public void setNullValuePossible(boolean nullValuePossible)
{
m_dateField.setNullValuePossible(nullValuePossible);
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
import java.awt.ComponentOrientation;
/**
* The NumberField only accepts integer values.
* <strong>Warning!<strong> Currently only Longs are supported.
*/
public class NumberField extends AbstractBlockField {
private static final long serialVersionUID = 1L;
static char[] m_separators = new char[0];
Number m_number;
Number m_minimum;
Number m_maximum;
/**
* @return Returns the m_blockStepSize.
*/
public int getBlockStepSize() {
return m_blockStepSize;
}
/**
* @param stepSize The m_blockStepSize to set.
*/
public void setBlockStepSize(int stepSize) {
m_blockStepSize = stepSize;
}
/**
* @return Returns the m_stepSize.
*/
public int getStepSize() {
return m_stepSize;
}
/**
* @param size The m_stepSize to set.
*/
public void setStepSize(int size) {
m_stepSize = size;
}
int m_stepSize;
int m_blockStepSize;
int m_maxLength;
boolean m_isNullPermitted = true;
public NumberField() {
setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT);
updateColumns();
}
public NumberField(Number minimum,Number maximum,int stepSize,int blockStepSize) {
this();
setStepSize(stepSize);
setBlockStepSize(blockStepSize);
setMinimum( minimum );
setMaximum( maximum );
}
public void setMinimum(Number minimum){
m_minimum = minimum;
updateColumns();
}
public void setMaximum(Number maximum){
m_maximum = maximum;
updateColumns();
}
public Number getMinimum() {
return m_minimum;
}
public Number getMaximum() {
return m_maximum;
}
private void updateColumns() {
if (m_maximum!= null && m_minimum != null) {
if ((Math.abs(m_maximum.longValue()))
> (Math.abs(m_minimum.longValue())) * 10)
m_maxLength = m_maximum.toString().length();
else
m_maxLength = m_minimum.toString().length();
setColumns(m_maxLength);
} else {
m_maxLength = 100;
setColumns(4);
}
}
public boolean isNullPermitted() {
return m_isNullPermitted;
}
public void setNullPermitted(boolean isNullPermitted) {
m_isNullPermitted = isNullPermitted;
if (m_number == null && !isNullPermitted)
m_number = new Double(defaultValue());
}
private long defaultValue() {
if (m_minimum != null && m_minimum.longValue()>0)
return m_minimum.longValue();
else if (m_maximum != null && m_maximum.longValue()<0)
return m_maximum.longValue();
return 0;
}
public void setNumber(Number number) {
updateNumber( number );
m_oldText = getText();
fireValueChanged();
}
private void updateNumber(Number number) {
m_number = number;
String text;
if (number != null) {
text = String.valueOf(number.longValue());
} else {
text = "";
}
String previous = getText();
if ( previous != null && text.equals( previous))
{
return;
}
setText( text );
}
public void increase() {
changeSelectedBlock(new int[1],0,"",1);
}
public void decrease() {
changeSelectedBlock(new int[1],0,"",-1);
}
public Number getNumber() {
return m_number;
}
public boolean allowsNegative() {
return (m_minimum == null || m_minimum.longValue()<0);
}
protected char[] getSeparators() {
return m_separators;
}
protected boolean isSeparator(char c) {
return false;
}
protected void changeSelectedBlock(int[] blocks,int block,String selected,int count) {
long longValue = ((m_number != null) ? m_number.longValue() : defaultValue());
if (count == 1)
longValue = longValue + m_stepSize;
if (count == -1)
longValue = longValue - m_stepSize;
if (count == 10)
longValue = longValue + m_blockStepSize;
if (count == -10)
longValue = longValue - m_blockStepSize;
if (m_minimum != null && longValue<m_minimum.longValue())
longValue = m_minimum.longValue();
if (m_maximum != null && longValue>m_maximum.longValue())
longValue = m_maximum.longValue();
updateNumber(new Long(longValue));
calcBlocks(blocks);
markBlock(blocks,block);
}
public boolean blocksValid() {
try {
String text = getText();
if (text.length() ==0) {
if (isNullPermitted())
m_number = null;
return true;
}
long newLong = Long.parseLong(text);
if ((m_minimum == null || newLong>=m_minimum.longValue())
&& (m_maximum == null || newLong<=m_maximum.longValue())) {
m_number = new Long(newLong);
return true;
}
} catch (NumberFormatException e) {
if (isNullPermitted())
m_number = null;
}
return false;
}
protected int blockCount() {
return 1;
}
protected int maxBlockLength(int block) {
return m_maxLength;
}
protected boolean isValidChar(char c) {
return (Character.isDigit(c) || (allowsNegative() && c=='-'));
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendar;
import java.awt.Color;
import java.util.Calendar;
/** Renders the weekdays (or any other day of week, if selected) in a special color. */
public class WeekendHighlightRenderer implements DateRenderer {
Color m_weekendBackgroundColor = new Color(0xe2, 0xf3, 0xff);
boolean[] m_highlightedDays = new boolean[10];
public WeekendHighlightRenderer() {
setHighlight(Calendar.SATURDAY,true);
setHighlight(Calendar.SUNDAY,true);
}
/** Default color is #e2f3ff */
public void setWeekendBackgroundColor(Color color) {
m_weekendBackgroundColor = color;
}
/**
enable/disable the highlighting for the selected day.
Default highlighted days are saturday and sunday.
*/
public void setHighlight(int day,boolean highlight) {
m_highlightedDays[day] = highlight;
}
public boolean isHighlighted(int day) {
return m_highlightedDays[day];
}
public RenderingInfo getRenderingInfo(int dayOfWeek, int day, int month, int year) {
Color backgroundColor = isHighlighted(dayOfWeek) ? m_weekendBackgroundColor : null;
Color foregroundColor = null;
String tooltipText = null;
RenderingInfo info = new RenderingInfo(backgroundColor, foregroundColor, tooltipText);
return info;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.