code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package org.rapla.framework;
@SuppressWarnings("unused")
public class TypedComponentRole<T> {
String id;
public TypedComponentRole(String id) {
this.id = id.intern();
}
public String getId()
{
return id;
}
public String toString()
{
return id;
}
public boolean equals(Object obj)
{
if (obj == null)
{
return false;
}
if ( !(obj instanceof TypedComponentRole))
{
return false;
}
return id.equals(obj.toString());
}
@Override
public int hashCode() {
return id.hashCode();
}
}
| Java |
package org.rapla.framework;
import java.net.URL;
import org.rapla.framework.logger.Logger;
public interface StartupEnvironment
{
int CONSOLE = 1;
int WEBSTART = 2;
int APPLET = 3;
Configuration getStartupConfiguration() throws RaplaException;
URL getDownloadURL() throws RaplaException;
URL getConfigURL() throws RaplaException;
/** either EMBEDDED, CONSOLE, WEBSTART, APPLET,SERVLET or CLIENT */
int getStartupMode();
URL getContextRootURL() throws RaplaException;
Logger getBootstrapLogger();
} | Java |
package org.rapla.framework;
public interface RaplaContext
{
/** Returns a reference to the requested object (e.g. a component instance).
* throws a RaplaContextException if the object can't be returned. This could have
* different reasons: For example it is not found in the context, or there has been
* a problem during the component creation.
*/
<T> T lookup(Class<T> componentRole) throws RaplaContextException;
boolean has(Class<?> clazz);
<T> T lookup(TypedComponentRole<T> componentRole) throws RaplaContextException;
//<T> T lookup(TypedComponentRole<T> componentRole, String hint) throws RaplaContextException;
boolean has(TypedComponentRole<?> componentRole);
}
| Java |
package org.rapla.framework;
public interface Disposable {
public void dispose();
}
| Java |
package org.rapla.framework;
import java.util.HashMap;
public class RaplaDefaultContext implements RaplaContext
{
private final HashMap<String,Object> contextObjects = new HashMap<String,Object>();
protected final RaplaContext parent;
public RaplaDefaultContext()
{
this( null );
}
public RaplaDefaultContext( final RaplaContext parent )
{
this.parent = parent;
}
/**
* @throws RaplaContextException
*/
protected Object lookup( final String key ) throws RaplaContextException
{
return contextObjects.get( key );
}
protected boolean has( final String key )
{
return contextObjects.get( key ) != null;
}
public <T> void put(Class<T> componentRole, T instance) {
contextObjects.put(componentRole.getName(), instance );
}
public <T> void put(TypedComponentRole<T> componentRole, T instance) {
contextObjects.put(componentRole.getId(), instance );
}
public boolean has(Class<?> componentRole) {
if (has(componentRole.getName()))
{
return true;
}
return parent != null && parent.has( componentRole);
}
public boolean has(TypedComponentRole<?> componentRole) {
if (has( componentRole.getId()))
{
return true;
}
return parent != null && parent.has( componentRole);
}
@SuppressWarnings("unchecked")
public <T> T lookup(Class<T> componentRole) throws RaplaContextException {
final String key = componentRole.getName();
T lookup = (T) lookup(key);
if ( lookup == null)
{
if ( parent != null)
{
return parent.lookup( componentRole);
}
else
{
throw new RaplaContextException( key );
}
}
return lookup;
}
@SuppressWarnings("unchecked")
public <T> T lookup(TypedComponentRole<T> componentRole) throws RaplaContextException {
final String key = componentRole.getId();
T lookup = (T) lookup(key);
if ( lookup == null)
{
if ( parent != null)
{
return parent.lookup( componentRole);
}
else
{
throw new RaplaContextException( key );
}
}
return lookup;
}
// @SuppressWarnings("unchecked")
// public <T> T lookup(TypedComponentRole<T> componentRole, String hint) throws RaplaContextException {
// String key = componentRole.getId()+ "/" + hint;
// T lookup = (T) lookup(key);
// if ( lookup == null)
// {
// if ( parent != null)
// {
// return parent.lookup( componentRole, hint);
// }
// else
// {
// throw new RaplaContextException( key );
// }
// }
// 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.framework;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Stack;
import org.rapla.framework.logger.Logger;
/** Helper Class for automated creation of the rapla-plugin.list in the
* META-INF directory. Can be used in the build environment.
*/
public class ServiceListCreator {
public static void main (String[] args) {
try {
String sourceDir = args[0];
String destDir = (args.length>1) ? args[1] : sourceDir;
processDir(sourceDir,destDir);
} catch (IOException e) {
throw new RuntimeException( e.getMessage());
} catch (ClassNotFoundException e) {
throw new RuntimeException( e.getMessage());
}
}
public static void processDir(String srcDir,String destFile)
throws ClassNotFoundException, IOException
{
File topDir = new File(srcDir);
List<String> list = findPluginClasses(topDir, null);
Writer writer = new BufferedWriter(new FileWriter( destFile ));
try
{
for ( String className:list)
{
System.out.println("Found PluginDescriptor for " + className);
writer.write( className );
writer.write( "\n" );
}
} finally {
writer.close();
}
}
public static List<String> findPluginClasses(File topDir,Logger logger)
throws ClassNotFoundException {
List<String> list = new ArrayList<String>();
Stack<File> stack = new Stack<File>();
stack.push(topDir);
while (!stack.empty()) {
File file = stack.pop();
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i=0;i<files.length;i++)
stack.push(files[i]);
} else {
String name = file.getName();
if (file.getAbsolutePath().contains("rapla") && (name.endsWith("Plugin.class") || name.endsWith("PluginServer.class"))) {
String absolut = file.getAbsolutePath();
String relativePath = absolut.substring(topDir.getAbsolutePath().length());
String pathName = relativePath.substring(1,relativePath.length()-".class".length());
String className = pathName.replace(File.separatorChar,'.');
try
{
Class<?> pluginClass = ServiceListCreator.class.getClassLoader().loadClass(className );
if (!pluginClass.isInterface() ) {
if ( PluginDescriptor.class.isAssignableFrom(pluginClass)) {
list.add( className);
} else {
if ( logger != null)
{
logger.warn("No PluginDescriptor found for Class " + className );
}
}
}
}
catch (NoClassDefFoundError ex)
{
System.out.println(ex.getMessage());
}
}
}
}
return list;
}
/** lookup for plugin classes in classpath*/
public static Collection<String> findPluginClasses(Logger logger)
throws ClassNotFoundException {
Collection<String> result = new LinkedHashSet<String>();
URL mainDir = ServiceListCreator.class.getResource("/");
if ( mainDir != null)
{
String classpath = System.getProperty("java.class.path");
final String[] split;
if (classpath != null)
{
split = classpath.split(""+File.pathSeparatorChar);
}
else
{
split = new String[] { mainDir.toExternalForm()};
}
for ( String path: split)
{
File pluginPath = new File(path);
List<String> foundInClasspathEntry = findPluginClasses(pluginPath, logger);
result.addAll(foundInClasspathEntry);
}
}
return result;
}
/** lookup for plugin classes in classpath*/
public static Collection<File> findPluginWebappfolders(Logger logger)
throws ClassNotFoundException {
Collection<File> result = new LinkedHashSet<File>();
URL mainDir = ServiceListCreator.class.getResource("/");
if ( mainDir != null)
{
String classpath = System.getProperty("java.class.path");
final String[] split;
if (classpath != null)
{
split = classpath.split(""+File.pathSeparatorChar);
}
else
{
split = new String[] { mainDir.toExternalForm()};
}
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name != null && name.equals("war");
}
};
for ( String path: split)
{
File pluginPath = new File(path);
List<String> foundInClasspathEntry = findPluginClasses(pluginPath, logger);
if ( foundInClasspathEntry.size() > 0)
{
File parent = pluginPath.getParentFile().getAbsoluteFile();
int depth= 0;
while ( parent != null && parent.isDirectory())
{
File[] listFiles = parent.listFiles( filter);
if (listFiles != null && listFiles.length == 1)
{
result.add( listFiles[0]);
}
depth ++;
if ( depth > 5)
{
break;
}
parent = parent.getParentFile();
}
}
}
}
return result;
}
}
| Java |
package org.rapla.framework;
public class ConfigurationException extends Exception {
private static final long serialVersionUID = 1L;
public ConfigurationException(String string, Throwable exception) {
super( string, exception);
}
public ConfigurationException(String string) {
super( string );
}
}
| Java |
package org.rapla.framework;
public class RaplaSynchronizationException extends RaplaException {
private static final long serialVersionUID = 1L;
public RaplaSynchronizationException(String text) {
super(text);
}
public RaplaSynchronizationException(Throwable ex) {
super( ex.getMessage(), 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.framework;
import java.util.Collection;
public interface Container extends Disposable
{
StartupEnvironment getStartupEnvironment();
RaplaContext getContext();
/** lookup an named component from the raplaserver.xconf */
<T> T lookup(Class<T> componentRole, String hint) throws RaplaContextException;
<T,I extends T> void addContainerProvidedComponent(Class<T> roleInterface,Class<I> implementingClass);
<T,I extends T> void addContainerProvidedComponent(Class<T> roleInterface,Class<I> implementingClass, Configuration config);
<T,I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass);
<T,I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass, Configuration config);
/** lookup all services for this role*/
<T> Collection<T> lookupServicesFor(TypedComponentRole<T> extensionPoint) throws RaplaContextException;
/** lookup all services for this role*/
<T> Collection<T> lookupServicesFor(Class<T> role) throws RaplaContextException;
}
| Java |
package org.rapla.framework;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class DefaultConfiguration implements Configuration {
Map<String,String> attributes = new LinkedHashMap<String, String>();
List<DefaultConfiguration> children = new ArrayList<DefaultConfiguration>();
String value;
String name;
public DefaultConfiguration()
{
}
public DefaultConfiguration(String localName) {
this.name = localName;
}
public DefaultConfiguration(String localName, String value) {
this.name = localName;
if ( value != null)
{
this.value = value;
}
}
public DefaultConfiguration(Configuration config)
{
this.name = config.getName();
for (Configuration conf: config.getChildren())
{
children.add( new DefaultConfiguration( conf));
}
this.value = ((DefaultConfiguration)config).value;
attributes.putAll(((DefaultConfiguration)config).attributes);
}
public void addChild(Configuration configuration) {
children.add( (DefaultConfiguration) configuration);
}
public void setAttribute(String name, boolean value) {
attributes.put( name, value ? "true" : "false");
}
public void setAttribute(String name, String value) {
attributes.put( name, value);
}
public void setValue(String value) {
this.value = value;
}
public void setValue(int intValue) {
this.value = Integer.toString( intValue);
}
public void setValue(boolean selected) {
this.value = Boolean.toString( selected);
}
public DefaultConfiguration getMutableChild(String name, boolean create) {
for (DefaultConfiguration child:children)
{
if ( child.getName().equals( name))
{
return child;
}
}
if ( create )
{
DefaultConfiguration newConfig = new DefaultConfiguration( name);
children.add( newConfig);
return newConfig;
}
else
{
return null;
}
}
public void removeChild(Configuration child) {
children.remove( child);
}
public String getName()
{
return name;
}
public Configuration getChild(String name)
{
for (DefaultConfiguration child:children)
{
if ( child.getName().equals( name))
{
return child;
}
}
return new DefaultConfiguration( name);
}
public Configuration[] getChildren(String name) {
List<Configuration> result = new ArrayList<Configuration>();
for (DefaultConfiguration child:children)
{
if ( child.getName().equals( name))
{
result.add( child);
}
}
return result.toArray( new Configuration[] {});
}
public Configuration[] getChildren()
{
return children.toArray( new Configuration[] {});
}
public String getValue() throws ConfigurationException {
if ( value == null)
{
throw new ConfigurationException("Value not set in configuration " + name);
}
return value;
}
public String getValue(String defaultValue) {
if ( value == null)
{
return defaultValue;
}
return value;
}
public boolean getValueAsBoolean(boolean defaultValue) {
if ( value == null)
{
return defaultValue;
}
if ( value.equalsIgnoreCase("yes"))
{
return true;
}
if ( value.equalsIgnoreCase("no"))
{
return false;
}
return Boolean.parseBoolean( value);
}
public long getValueAsLong(int defaultValue) {
if ( value == null)
{
return defaultValue;
}
return Long.parseLong( value);
}
public int getValueAsInteger(int defaultValue) {
if ( value == null)
{
return defaultValue;
}
return Integer.parseInt( value);
}
public String getAttribute(String name) throws ConfigurationException {
String value = attributes.get(name);
if ( value == null)
{
throw new ConfigurationException("Attribute " + name + " not found ");
}
return value;
}
public String getAttribute(String name, String defaultValue) {
String value = attributes.get(name);
if ( value == null)
{
return defaultValue;
}
return value;
}
public boolean getAttributeAsBoolean(String string, boolean defaultValue) {
String value = getAttribute(string, defaultValue ? "true": "false");
return Boolean.parseBoolean( value);
}
public String[] getAttributeNames() {
String[] attributeNames = attributes.keySet().toArray( new String[] {});
return attributeNames;
}
public Configuration find( String localName) {
Configuration[] childList= getChildren();
for ( int i=0;i<childList.length;i++) {
if (childList[i].getName().equals( localName)) {
return childList[i];
}
}
return null;
}
public Configuration find( String attributeName, String attributeValue) {
Configuration[] childList= getChildren();
for ( int i=0;i<childList.length;i++) {
String attribute = childList[i].getAttribute( attributeName,null);
if (attributeValue.equals( attribute)) {
return childList[i];
}
}
return null;
}
public DefaultConfiguration replace( Configuration newChild) throws ConfigurationException {
Configuration find = find( newChild.getName());
if ( find == null)
{
throw new ConfigurationException(" could not find " + newChild.getName());
}
return replace( find, newChild );
}
public DefaultConfiguration replace( Configuration oldChild, Configuration newChild) {
String localName = getName();
DefaultConfiguration newConfig = newConfiguration(localName);
boolean present = false;
Configuration[] childList= getChildren();
for ( int i=0;i<childList.length;i++) {
if (childList[i] != oldChild) {
newConfig.addChild( childList[i]);
} else {
present = true;
newConfig.addChild( newChild );
}
}
if (!present) {
newConfig.addChild( newChild );
}
return newConfig;
}
protected DefaultConfiguration newConfiguration(String localName) {
return new DefaultConfiguration( localName);
}
public DefaultConfiguration add( Configuration newChild) {
String localName = getName();
DefaultConfiguration newConfig = newConfiguration(localName);
boolean present = false;
Configuration[] childList= getChildren();
for ( int i=0;i<childList.length;i++) {
if (childList[i] == newChild) {
present = true;
}
}
if (!present) {
newConfig.addChild( newChild );
}
return newConfig;
}
/**
* @param configuration
* @throws ConfigurationException
*/
public DefaultConfiguration remove(Configuration configuration) {
String localName = getName();
DefaultConfiguration newConfig = newConfiguration(localName);
Configuration[] childList= getChildren();
for ( int i=0;i<childList.length;i++) {
if (childList[i] != configuration) {
newConfig.addChild( childList[i]);
}
}
return newConfig;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((attributes == null) ? 0 : attributes.hashCode());
result = prime * result + ((children == null) ? 0 : children.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DefaultConfiguration other = (DefaultConfiguration) obj;
if (attributes == null) {
if (other.attributes != null)
return false;
} else if (!attributes.equals(other.attributes))
return false;
if (children == null) {
if (other.children != null)
return false;
} else if (!children.equals(other.children))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append( name);
if (attributes.size() > 0)
{
buf.append( "[");
boolean first= true;
for ( Map.Entry<String, String> entry: attributes.entrySet())
{
if (!first)
{
buf.append( ", ");
}
else
{
first = false;
}
buf.append(entry.getKey());
buf.append( "='");
buf.append(entry.getValue());
buf.append( "'");
}
buf.append( "]");
}
buf.append( "{");
boolean first= true;
for ( Configuration child:children)
{
if (first)
{
buf.append("\n");
first =false;
}
buf.append( child.toString());
buf.append("\n");
}
if ( value != null)
{
buf.append( value);
}
buf.append( "}");
return buf.toString();
}
}
| Java |
package org.rapla.client;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.framework.TypedComponentRole;
import org.rapla.gui.AppointmentStatusFactory;
import org.rapla.gui.ObjectMenuFactory;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.PluginOptionPanel;
import org.rapla.gui.PublishExtensionFactory;
import org.rapla.gui.ReservationCheck;
import org.rapla.gui.SwingViewFactory;
import org.rapla.gui.toolkit.IdentifiableMenuEntry;
/** Constant Pool of basic extension points of the Rapla client.
* You can add your extension in the provideService Method of your PluginDescriptor
* <pre>
* container.addContainerProvidedComponent( REPLACE_WITH_EXTENSION_POINT_NAME, REPLACE_WITH_CLASS_IMPLEMENTING_EXTENSION, config);
* </pre>
* @see org.rapla.framework.PluginDescriptor
*/
public interface RaplaClientExtensionPoints
{
/** add your own views to Rapla, by providing a org.rapla.gui.ViewFactory
* @see SwingViewFactory
* */
Class<SwingViewFactory> CALENDAR_VIEW_EXTENSION = SwingViewFactory.class;
/** A client extension is 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.
*/
Class<ClientExtension> CLIENT_EXTENSION = ClientExtension.class;
/** You can add a specific configuration panel for your plugin.
* Note if you add a pluginOptionPanel you need to provide the PluginClass as hint.
* Example
* <code>
* container.addContainerProvidedComponent( RaplaExtensionPoints.PLUGIN_OPTION_PANEL_EXTENSION, AutoExportPluginOption.class, getClass().getName());
* </code>
* @see org.rapla.entities.configuration.Preferences
* @see OptionPanel
* */
TypedComponentRole<PluginOptionPanel> PLUGIN_OPTION_PANEL_EXTENSION = new TypedComponentRole<PluginOptionPanel>("org.rapla.plugin.Option");
/** You can add additional option panels for editing the user preference.
* @see org.rapla.entities.configuration.Preferences
* @see OptionPanel
* */
TypedComponentRole<OptionPanel> USER_OPTION_PANEL_EXTENSION = new TypedComponentRole<OptionPanel>("org.rapla.UserOptions");
/** You can add additional option panels for the editing the system preferences
* @see org.rapla.entities.configuration.Preferences
* @see OptionPanel
* */
TypedComponentRole<OptionPanel> SYSTEM_OPTION_PANEL_EXTENSION = new TypedComponentRole<OptionPanel>("org.rapla.SystemOptions");
/** add your own wizard menus to create events. Use the CalendarSelectionModel service to get access to the current calendar
* @see CalendarSelectionModel
**/
TypedComponentRole<IdentifiableMenuEntry> RESERVATION_WIZARD_EXTENSION = new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ReservationWizardExtension");
/** you can add an interactive check when the user stores a reservation
*@see ReservationCheck
**/
Class<ReservationCheck> RESERVATION_SAVE_CHECK = ReservationCheck.class;
/** add your own menu entries in the context menu of an object. To do this provide
an ObjectMenuFactory under this entry.
@see ObjectMenuFactory
*/
Class<ObjectMenuFactory> OBJECT_MENU_EXTENSION = ObjectMenuFactory.class;
/** add a footer for summary of appointments in edit window
* provide an AppointmentStatusFactory to add your own footer to the appointment edit
@see AppointmentStatusFactory
* */
Class<AppointmentStatusFactory> APPOINTMENT_STATUS = AppointmentStatusFactory.class;
/** add your own submenus to the admin menu.
*/
TypedComponentRole<IdentifiableMenuEntry> ADMIN_MENU_EXTENSION_POINT = new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.AdminMenuInsert");
/** add your own import-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> IMPORT_MENU_EXTENSION_POINT =new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ImportMenuInsert");
/** add your own export-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> EXPORT_MENU_EXTENSION_POINT =new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ExportMenuInsert");
/** add your own view-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> VIEW_MENU_EXTENSION_POINT =new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ViewMenuInsert");
/** add your own edit-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> EDIT_MENU_EXTENSION_POINT = new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.EditMenuInsert");
/** add your own help-menu submenus
*/
TypedComponentRole<IdentifiableMenuEntry> HELP_MENU_EXTENSION_POINT = new TypedComponentRole<IdentifiableMenuEntry>("org.rapla.gui.ExtraMenuInsert");
/** add your own publish options for the calendars*/
Class<PublishExtensionFactory> PUBLISH_EXTENSION_OPTION = PublishExtensionFactory.class;
}
| 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 |
/*--------------------------------------------------------------------------*
| 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 |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to 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;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.internal.ConfigTools;
final public class MainWebstart
{
public static void main(String[] args) {
MainWebclient main = new MainWebclient();
try {
main.init( ConfigTools.webstartConfigToURL( MainWebclient.CLIENT_CONFIG_SERVLET_URL),StartupEnvironment.WEBSTART);
main.startRapla("client");
} catch (Throwable ex) {
main.getLogger().error("Couldn't start Rapla",ex);
main.raplaContainer.dispose();
System.out.flush();
try
{
Thread.sleep( 2000 );
}
catch ( InterruptedException e )
{
}
System.exit(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.client;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.rapla.framework.StartupEnvironment;
/** The applet-encapsulation of the Main.class reads the configuration
* from the document-base of the applet and displays
* an applet with a start button.
* @author Christopher Kohlhaas
* @see MainWebstart
*/
final public class MainApplet extends JApplet
{
private static final long serialVersionUID = 1L;
JPanel dlg = new JPanel();
JButton button;
JLabel label;
boolean startable = false;
public MainApplet()
{
JPanel panel1 = new JPanel();
panel1.setBackground( new Color( 255, 255, 204 ) );
GridLayout gridLayout1 = new GridLayout();
gridLayout1.setColumns( 1 );
gridLayout1.setRows( 3 );
gridLayout1.setHgap( 10 );
gridLayout1.setVgap( 10 );
panel1.setLayout( gridLayout1 );
label = new JLabel( "Rapla-Applet loading" );
panel1.add( label );
button = new JButton( "StartRapla" );
button.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
startThread();
}
} );
panel1.add( button );
dlg.setBackground( new Color( 255, 255, 204 ) );
dlg.setBorder( BorderFactory.createMatteBorder( 1, 1, 2, 2, Color.black ) );
dlg.add( panel1 );
}
public void start()
{
getRootPane().putClientProperty( "defeatSystemEventQueueCheck", Boolean.TRUE );
try
{
setContentPane( dlg );
button.setEnabled( startable );
startable = true;
button.setEnabled( startable );
}
catch ( Exception ex )
{
ex.printStackTrace();
}
}
private void updateStartable()
{
javax.swing.SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
button.setEnabled( startable );
}
} );
}
private void startThread()
{
( new Thread()
{
public void run()
{
try
{
startable = false;
updateStartable();
MainWebclient main = new MainWebclient();
URL configURL = new URL( getDocumentBase(), MainWebclient.CLIENT_CONFIG_SERVLET_URL );
main.init( configURL, StartupEnvironment.APPLET );
main.env.setDownloadURL( getDocumentBase() );
System.out.println( "Docbase " + getDocumentBase() );
main.startRapla("client");
}
catch ( Exception ex )
{
ex.printStackTrace();
}
finally
{
startable = true;
updateStartable();
}
}
} ).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.client;
import org.rapla.ConnectInfo;
public interface RaplaClientListener
{
public void clientStarted();
public void clientClosed(ConnectInfo reconnect);
public void clientAborted();
}
| 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 |
/*--------------------------------------------------------------------------*
| 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;
import java.net.URL;
import org.rapla.ConnectInfo;
import org.rapla.RaplaMainContainer;
import org.rapla.RaplaStartupEnvironment;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.logger.ConsoleLogger;
import org.rapla.framework.logger.Logger;
public class MainWebclient
{
/** The default config filename for client-mode raplaclient.xconf*/
public final static String CLIENT_CONFIG_SERVLET_URL = "rapla/raplaclient.xconf";
private Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_WARN).getChildLogger("init");
RaplaStartupEnvironment env = new RaplaStartupEnvironment();
Container raplaContainer;
void init(URL configURL,int mode) throws Exception {
env.setStartupMode( mode );
env.setConfigURL( configURL );
env.setBootstrapLogger( getLogger() );
}
void startRapla(final String id) throws Exception {
ConnectInfo connectInfo = null;
startRapla(id, connectInfo);
}
protected void startRapla(final String id, ConnectInfo connectInfo) throws Exception, RaplaContextException {
raplaContainer = new RaplaMainContainer( env);
ClientServiceContainer clientContainer = raplaContainer.lookup(ClientServiceContainer.class, id );
ClientService client = clientContainer.getContext().lookup( ClientService.class);
client.addRaplaClientListener(new RaplaClientListenerAdapter() {
public void clientClosed(ConnectInfo reconnect) {
if ( reconnect != null) {
raplaContainer.dispose();
try {
startRapla(id, reconnect);
} catch (Exception ex) {
getLogger().error("Error restarting client",ex);
exit();
}
} else {
exit();
}
}
public void clientAborted()
{
exit();
}
});
clientContainer.start(connectInfo);
}
public static void main(String[] args) {
MainWebclient main = new MainWebclient();
try {
main.init( new URL("http://localhost:8051/rapla/raplaclient.xconf"),StartupEnvironment.CONSOLE);
main.startRapla("client");
} catch (Throwable ex) {
main.getLogger().error("Couldn't start Rapla",ex);
main.raplaContainer.dispose();
System.out.flush();
try
{
Thread.sleep( 2000 );
}
catch ( InterruptedException e )
{
}
System.exit(1);
}
}
private void exit() {
if ( raplaContainer != null)
{
raplaContainer.dispose();
}
if (env.getStartupMode() != StartupEnvironment.APPLET)
{
System.exit(0);
}
}
Logger getLogger() {
return logger;
}
}
| 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.client;
import org.rapla.ConnectInfo;
public class RaplaClientListenerAdapter implements RaplaClientListener
{
public void clientStarted() {
}
public void clientClosed(ConnectInfo reconnect) {
}
public void clientAborted()
{
}
}
| 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.client;
import java.util.Map;
import org.rapla.entities.User;
import org.rapla.facade.ClientFacade;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.gui.toolkit.RaplaFrame;
import org.rapla.gui.toolkit.RaplaWidget;
/** This service starts and manages the rapla-gui-client.
*/
public interface ClientService
{
public static TypedComponentRole<Map<Object,Object>> SESSION_MAP = new TypedComponentRole<Map<Object,Object>>("org.rapla.SessionMap");
public static TypedComponentRole<RaplaFrame> MAIN_COMPONENT = new TypedComponentRole<RaplaFrame>("org.rapla.MainComponent");
public static TypedComponentRole<RaplaWidget> WELCOME_FIELD = new TypedComponentRole<RaplaWidget>("org.rapla.gui.WelcomeField");
void addRaplaClientListener(RaplaClientListener listener);
void removeRaplaClientListener(RaplaClientListener listener);
ClientFacade getFacade() throws RaplaContextException;
/** setup a component with the services logger,context and servicemanager */
boolean isRunning();
/** the admin can switch to another user!
* @throws RaplaContextException
* @throws RaplaException */
void switchTo(User user) throws RaplaException;
/** returns true if the admin has switched to anoter user!*/
boolean canSwitchBack();
/** restarts the complete Client and displays a new login*/
void restart();
/** returns true if an logout option is available. This is true when the user used an login dialog.*/
boolean isLogoutAvailable();
RaplaContext getContext();
void logout();
}
| Java |
package org.rapla.examples;
import java.net.MalformedURLException;
import java.net.URL;
import org.rapla.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.logger.Logger;
/** Startup environment that creates an Facade Object to communicate with an rapla server instance.
*/
public class SimpleConnectorStartupEnvironment implements StartupEnvironment
{
DefaultConfiguration config;
URL server;
Logger logger;
public SimpleConnectorStartupEnvironment(final String host, final Logger logger) throws MalformedURLException
{
this( host, 8051, "/",false, logger);
}
public SimpleConnectorStartupEnvironment(final String host, final int hostPort, String contextPath,boolean isSecure, final Logger logger) throws MalformedURLException {
this.logger = logger;
config = new DefaultConfiguration("rapla-config");
final DefaultConfiguration facadeConfig = new DefaultConfiguration("facade");
facadeConfig.setAttribute("id","facade");
final DefaultConfiguration remoteConfig = new DefaultConfiguration("remote-storage");
remoteConfig.setAttribute("id","remote");
DefaultConfiguration serverHost =new DefaultConfiguration("server");
serverHost.setValue( "${download-url}" );
remoteConfig.addChild( serverHost );
config.addChild( facadeConfig );
config.addChild( remoteConfig );
String protocoll = "http";
if ( isSecure )
{
protocoll = "https";
}
if ( !contextPath.startsWith("/"))
{
contextPath = "/" + contextPath ;
}
if ( !contextPath.endsWith("/"))
{
contextPath = contextPath + "/";
}
server = new URL(protocoll,host, hostPort, contextPath);
}
public Configuration getStartupConfiguration() throws RaplaException
{
return config;
}
public int getStartupMode()
{
return CONSOLE;
}
public URL getContextRootURL() throws RaplaException
{
return null;
}
public Logger getBootstrapLogger()
{
return logger;
}
public URL getDownloadURL() throws RaplaException
{
return server;
}
public URL getConfigURL() throws RaplaException {
return null;
}
}
| Java |
package org.rapla.examples;
import java.util.Locale;
import org.rapla.RaplaMainContainer;
import org.rapla.entities.domain.Allocatable;
import org.rapla.facade.ClientFacade;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.logger.ConsoleLogger;
/** Simple demonstration for connecting your app and importing some users. See sources*/
public class RaplaConnectorTest
{
public static void main(String[] args) {
final ConsoleLogger logger = new ConsoleLogger( ConsoleLogger.LEVEL_INFO);
try
{
// Connects to http://localhost:8051/
// and calls rapla/rpc/methodNames for interacting
StartupEnvironment env = new SimpleConnectorStartupEnvironment( "localhost", 8051,"/", false, logger);
RaplaMainContainer container = new RaplaMainContainer( env);
RaplaContext context = container.getContext();
// get an interface to the facade and login
ClientFacade facade = context.lookup(ClientFacade.class);
if ( !facade.login( "admin", "".toCharArray()) ) {
throw new RaplaException("Can't login");
}
// query resouce
Allocatable firstResource = facade.getAllocatables() [0] ;
logger.info( firstResource.getName( Locale.getDefault()));
// cleanup the Container
container.dispose();
}
catch ( Exception e )
{
logger.error("Could not start test ", 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.examples;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import org.rapla.RaplaMainContainer;
import org.rapla.components.util.Tools;
import org.rapla.entities.Category;
import org.rapla.entities.User;
import org.rapla.facade.ClientFacade;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.framework.logger.ConsoleLogger;
/**Demonstration for connecting your app and importing some users */
public class RaplaImportUsers {
public static void main(String[] args) {
if ( args.length< 1 ) {
System.out.println("Usage: filename");
System.out.println("Example: users.csv ");
return;
}
final ConsoleLogger logger = new ConsoleLogger( ConsoleLogger.LEVEL_INFO);
try
{
StartupEnvironment env = new SimpleConnectorStartupEnvironment( "localhost", 8051, "/",false, logger);
RaplaMainContainer container = new RaplaMainContainer( env);
importFile( container.getContext(), args[0] );
// cleanup the Container
container.dispose();
}
catch ( Exception e )
{
logger.error("Could not start test ", e );
}
}
private static void importFile(RaplaContext context,String filename) throws Exception {
System.out.println(" Please enter the admin password ");
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String adminPass = stdin.readLine();
// get an interface to the facade and login
ClientFacade facade = context.lookup(ClientFacade.class);
if ( !facade.login("admin", adminPass.toCharArray() ) ) {
throw new RaplaException("Can't login");
}
FileReader reader = new FileReader( filename );
importUsers( facade, reader);
reader.close();
facade.logout();
}
public static void importUsers(ClientFacade facade, Reader reader) throws RaplaException, IOException {
String[][] entries = Tools.csvRead( reader, 5 );
Category rootCategory = facade.getUserGroupsCategory();
for ( int i=0;i<entries.length; i++ ) {
String[] lineEntries = entries[i];
String name = lineEntries[0];
String email = lineEntries[1];
String username = lineEntries[2];
String groupKey = lineEntries[3];
String password = lineEntries[4];
User user = facade.newUser();
user.setUsername( username );
user.setName ( name );
user.setEmail( email );
Category group = findCategory( rootCategory, groupKey );
if (group != null) {
user.addGroup( group );
}
facade.store(user);
facade.changePassword( user, new char[] {} ,password.toCharArray());
System.out.println("Imported user " + user + " with password '" + password + "'");
}
}
static private Category findCategory( Category rootCategory, String groupPath) {
Category group = rootCategory;
String[] groupKeys = Tools.split( groupPath, '/');
for ( int i=0;i<groupKeys.length; i++) {
group = group.getCategory( groupKeys[i] );
}
return group;
}
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.common;
/**
* Marker interface for JSON based RPC. Should be replaced with a marker annotation when generator supports annotations
* <p>
* Application service interfaces should extend this interface:
*
* <pre>
* public interface FooService extends RemoteJsonService ...
* </pre>
* <p>
* and declare each method as returning void and accepting {@link org.rapla.rest.gwtjsonrpc.common.AsyncCallback}
* as the final parameter, with a concrete type specified as the result type:
*
* <pre>
* public interface FooService extends RemoteJsonService {
* public void fooItUp(AsyncCallback<ResultType> callback);
* }
* </pre>
* <p>
* Instances of the interface can be obtained in the client and configured to
* reference a particular JSON server:
*
* <pre>
* FooService mysvc = GWT.create(FooService.class);
* ((ServiceDefTarget) mysvc).setServiceEntryPoint(GWT.getModuleBaseURL()
* + "FooService");
*</pre>
* <p>
* Calling conventions match the JSON-RPC 1.1 working draft from 7 August 2006
* (<a href="http://json-rpc.org/wd/JSON-RPC-1-1-WD-20060807.html">draft</a>).
* Only positional parameters are supported.
* <p>
* JSON service callbacks may also be declared; see
* {@link com.google.gwtjsonrpc.client.CallbackHandle}.
*/
public interface RemoteJsonService {
}
| Java |
// Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.common;
/** Invoked with the result (or error) of an RPC. */
public interface AsyncCallback<T> {
/**
* Called when an asynchronous call fails to complete normally.
* {@link com.google.gwt.user.client.rpc.InvocationException}s,
* or checked exceptions thrown by the service method are examples of the type
* of failures that can be passed to this method.
*
* @param caught failure encountered while executing a remote procedure call
*/
void onFailure(Throwable caught);
/**
* Called when an asynchronous call completes successfully.
*
* @param result the return value of the remote produced call
*/
void onSuccess(T result);
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.common;
/** Shared constants between client and server implementations. */
public class JsonConstants {
/** Proper Content-Type header value for JSON encoded data. */
public static final String JSON_TYPE = "application/json";
/** Character encoding preferred for JSON text. */
public static final String JSON_ENC = "UTF-8";
/** Request Content-Type header for JSON data. */
public static final String JSON_REQ_CT = JSON_TYPE + "; charset=utf-8";
/** Json-rpc 2.0: Proper Content-Type header value for JSON encoded data. */
public static final String JSONRPC20_TYPE = "application/json-rpc";
/** Json-rpc 2.0: Request Content-Type header for JSON data. */
public static final String JSONRPC20_REQ_CT = JSON_TYPE + "; charset=utf-8";
/** Json-rpc 2.0: Content types that we SHOULD accept as being valid */
public static final String JSONRPC20_ACCEPT_CTS =
JSON_TYPE + ",application/json,application/jsonrequest";
/** Error message when xsrfKey in request is missing or invalid. */
public static final String ERROR_INVALID_XSRF = "Invalid xsrfKey in request";
}
| Java |
package org.rapla.rest.gwtjsonrpc.common;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.entities.configuration.internal.RaplaMapImpl;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.InstanceCreator;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.ConstructorConstructor;
import com.google.gson.internal.Excluder;
import com.google.gson.internal.bind.MapTypeAdapterFactory;
import com.google.gson.internal.bind.ReflectiveTypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
public class JSONParserWrapper {
/** Create a default GsonBuilder with some extra types defined. */
public static GsonBuilder defaultGsonBuilder() {
final GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(java.util.Set.class,
new InstanceCreator<java.util.Set<Object>>() {
@Override
public Set<Object> createInstance(final Type arg0) {
return new LinkedHashSet<Object>();
}
});
Map<Type, InstanceCreator<?>> instanceCreators = new LinkedHashMap<Type,InstanceCreator<?>>();
instanceCreators.put(Map.class, new InstanceCreator<Map>() {
public Map createInstance(Type type) {
return new LinkedHashMap();
}
});
ConstructorConstructor constructorConstructor = new ConstructorConstructor(instanceCreators);
FieldNamingStrategy fieldNamingPolicy = FieldNamingPolicy.IDENTITY;
Excluder excluder = Excluder.DEFAULT;
final ReflectiveTypeAdapterFactory reflectiveTypeAdapterFactory = new ReflectiveTypeAdapterFactory(constructorConstructor, fieldNamingPolicy, excluder);
gb.registerTypeAdapterFactory(new MapTypeAdapterFactory(constructorConstructor, false));
gb.registerTypeAdapterFactory(new MyAdaptorFactory(reflectiveTypeAdapterFactory));
gb.registerTypeAdapter(java.util.Date.class, new GmtDateTypeAdapter());
GsonBuilder configured = gb.disableHtmlEscaping().setPrettyPrinting();
return configured;
}
public static class GmtDateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
private GmtDateTypeAdapter() {
}
@Override
public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
String timestamp = SerializableDateTimeFormat.INSTANCE.formatTimestamp(date);
return new JsonPrimitive(timestamp);
}
@Override
public synchronized Date deserialize(JsonElement jsonElement, Type type,JsonDeserializationContext jsonDeserializationContext) {
String asString = jsonElement.getAsString();
try {
Date timestamp = SerializableDateTimeFormat.INSTANCE.parseTimestamp(asString);
return timestamp;
} catch (Exception e) {
throw new JsonSyntaxException(asString, e);
}
}
}
public static class MyAdaptorFactory implements TypeAdapterFactory
{
ReflectiveTypeAdapterFactory reflectiveTypeAdapterFactory;
public MyAdaptorFactory(ReflectiveTypeAdapterFactory reflectiveTypeAdapterFactory) {
this.reflectiveTypeAdapterFactory = reflectiveTypeAdapterFactory;
}
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
Class<? super T> raw = type.getRawType();
if (!RaplaMapImpl.class.isAssignableFrom(raw)) {
return null; // it's a primitive!
}
return reflectiveTypeAdapterFactory.create(gson, type);
}
}
}
| Java |
package org.rapla.rest.gwtjsonrpc.common;
public interface FutureResult<T> {
public T get() throws Exception;
public T get(long wait) throws Exception;
public void get(AsyncCallback<T> callback);
}
| Java |
package org.rapla.rest.gwtjsonrpc.common;
@java.lang.annotation.Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(value={java.lang.annotation.ElementType.METHOD})
public @interface ResultType {
Class value();
Class container() default Object.class;
}
| Java |
// Copyright 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Specify the json rpc protocol version and transport mechanism to be used for
* a service.
* <p>
* Default is version 1.1 over HTTP POST.
* <p>
* <b>Note: if you use the generated (servlet), only version 1.1 over HTTP POST
* is supported</b>.
*/
@Target(ElementType.TYPE)
public @interface RpcImpl {
/**
* JSON-RPC protocol versions.
*/
public enum Version {
/**
* Version 1.1.
*
* @see <a
* href="http://groups.google.com/group/json-rpc/web/json-rpc-1-1-wd">Spec</a>
*/
V1_1,
/**
* Version 2.0.
*
* @see <a
* href="http://groups.google.com/group/json-rpc/web/json-rpc-1-2-proposal">Spec</a>
*/
V2_0
}
/**
* Supported transport mechanisms.
*/
public enum Transport {
HTTP_POST, HTTP_GET
}
/**
* Specify the JSON-RPC version. Default is version 1.1.
*/
Version version() default Version.V1_1;
/**
* Specify the transport protocol used to make the RPC call. Default is HTTP
* POST.
*/
Transport transport() default Transport.HTTP_POST;
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.common;
/** Mock object for AsyncCallbacks which do not need to return data. */
public class VoidResult {
public static final VoidResult INSTANCE = new VoidResult();
protected VoidResult() {
}
}
| Java |
package org.rapla.rest.gwtjsonrpc.common;
public class ResultImpl<T> implements FutureResult<T>
{
Exception ex;
T result;
public static VoidResultImpl VOID = new VoidResultImpl();
public static class VoidResultImpl extends ResultImpl<org.rapla.rest.gwtjsonrpc.common.VoidResult>
{
VoidResultImpl() {
}
public VoidResultImpl(Exception ex)
{
super( ex);
}
}
protected ResultImpl()
{
}
public ResultImpl(T result) {
this.result = result;
}
public ResultImpl(Exception ex)
{
this.ex = ex;
}
@Override
public T get() throws Exception {
if ( ex != null)
{
throw ex;
}
return result;
}
@Override
public T get(long wait) throws Exception {
if ( ex != null)
{
throw ex;
}
return result;
}
@Override
public void get(AsyncCallback<T> callback) {
if ( ex != null)
{
callback.onFailure( ex);
}
else
{
callback.onSuccess(result);
}
}
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.server;
/** Indicates the requested method is not known. */
@SuppressWarnings("serial")
public class XsrfException extends Exception {
public XsrfException(final String message) {
super(message);
}
public XsrfException(final String message, final Throwable why) {
super(message, why);
}
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.server;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** Utility to handle writing JSON-RPC responses, possibly compressed. */
public class RPCServletUtils {
public static boolean acceptsGzipEncoding(HttpServletRequest request) {
String accepts = request.getHeader("Accept-Encoding");
return accepts != null && accepts.indexOf("gzip") != -1;
}
public static void writeResponse(ServletContext ctx, HttpServletResponse res,
String responseContent, boolean encodeWithGzip) throws IOException {
byte[] data = responseContent.getBytes("UTF-8");
if (encodeWithGzip) {
ByteArrayOutputStream buf = new ByteArrayOutputStream(data.length);
GZIPOutputStream gz = new GZIPOutputStream(buf);
try {
gz.write(data);
gz.finish();
gz.flush();
res.setHeader("Content-Encoding", "gzip");
data = buf.toByteArray();
} catch (IOException e) {
ctx.log("Unable to compress response", e);
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
} finally {
gz.close();
}
}
res.setContentLength(data.length);
res.setContentType("application/json; charset=utf-8");
res.setStatus(HttpServletResponse.SC_OK);
res.setHeader("Content-Disposition", "attachment");
res.getOutputStream().write(data);
}
private RPCServletUtils() {
}
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.server;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import javax.jws.WebParam;
/**
* Pairing of a specific implementation and method.
*/
public class MethodHandle {
//private final RemoteJsonService imp;
private final Method method;
private final Type[] parameterTypes;
private String[] parameterNames;
/**
* Create a new handle for a specific service implementation and method.
*
* @param imp instance of the service all calls will be made on.
* @param method Java method to invoke on <code>imp</code>. The last parameter
* of the method must accept an {@link org.rapla.rest.gwtjsonrpc.common.AsyncCallback}
* and the method must return void.
*/
MethodHandle( final Method method) {
//this.imp = imp;
this.method = method;
final Type[] args = method.getGenericParameterTypes();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
parameterNames = new String[args.length ];
for (int i=0;i<args.length;i++)
{
Annotation[] annot= parameterAnnotations[i];
String paramterName = null;
for ( Annotation a:annot)
{
Class<? extends Annotation> annotationType = a.annotationType();
if ( annotationType.equals( WebParam.class))
{
paramterName = ((WebParam)a).name();
}
}
if ( paramterName != null)
{
parameterNames[i] = paramterName;
}
}
parameterTypes = new Type[args.length ];
System.arraycopy(args, 0, parameterTypes, 0, parameterTypes.length);
}
/**
* @return unique name of the method within the service.
*/
public String getName() {
return method.getName();
}
/** @return an annotation attached to the method's description. */
public <T extends Annotation> T getAnnotation(final Class<T> t) {
return method.getAnnotation(t);
}
/**
* @return true if this method requires positional arguments.
*/
public Type[] getParamTypes() {
return parameterTypes;
}
public String[] getParamNames()
{
return parameterNames;
}
/**
* Invoke this method with the specified arguments, updating the callback.
*
* @param arguments arguments to the method. May be the empty array if no
* parameters are declared beyond the AsyncCallback, but must not be
* null.
* @param imp the implementing object
* @param callback the callback the implementation will invoke onSuccess or
* onFailure on as it performs its work. Only the last onSuccess or
* onFailure invocation matters.
*/
public void invoke(final Object imp,final Object[] arguments,final ActiveCall callback) {
try {
Object result = method.invoke(imp, arguments);
callback.onSuccess(result);
} catch (InvocationTargetException e) {
final Throwable c = e.getCause();
if (c != null) {
callback.onInternalFailure(c);
} else {
callback.onInternalFailure(e);
}
} catch (IllegalAccessException e) {
callback.onInternalFailure(e);
} catch (RuntimeException e) {
callback.onInternalFailure(e);
} catch (Error e) {
callback.onInternalFailure(e);
}
}
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.server;
/** Indicates the requested method is not known. */
@SuppressWarnings("serial")
class NoSuchRemoteMethodException extends RuntimeException {
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.server;
import java.lang.reflect.Type;
import com.google.gson.InstanceCreator;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
final class CallDeserializer implements
JsonDeserializer<ActiveCall>, InstanceCreator<ActiveCall> {
private final ActiveCall req;
private final JsonServlet server;
CallDeserializer(final ActiveCall call, final JsonServlet jsonServlet) {
req = call;
server = jsonServlet;
}
@Override
public ActiveCall createInstance(final Type type) {
return req;
}
@Override
public ActiveCall deserialize(final JsonElement json, final Type typeOfT,
final JsonDeserializationContext context) throws JsonParseException,
NoSuchRemoteMethodException {
if (!json.isJsonObject()) {
throw new JsonParseException("Expected object");
}
final JsonObject in = json.getAsJsonObject();
req.id = in.get("id");
final JsonElement jsonrpc = in.get("jsonrpc");
final JsonElement version = in.get("version");
if (isString(jsonrpc) && version == null) {
final String v = jsonrpc.getAsString();
if ("2.0".equals(v)) {
req.versionName = "jsonrpc";
req.versionValue = jsonrpc;
} else {
throw new JsonParseException("Expected jsonrpc=2.0");
}
} else if (isString(version) && jsonrpc == null) {
final String v = version.getAsString();
if ("1.1".equals(v)) {
req.versionName = "version";
req.versionValue = version;
} else {
throw new JsonParseException("Expected version=1.1");
}
} else {
throw new JsonParseException("Expected version=1.1 or jsonrpc=2.0");
}
final JsonElement method = in.get("method");
if (!isString(method)) {
throw new JsonParseException("Expected method name as string");
}
req.method = server.lookupMethod(method.getAsString());
if (req.method == null) {
throw new NoSuchRemoteMethodException();
}
final Type[] paramTypes = req.method.getParamTypes();
final JsonElement params = in.get("params");
if (params != null) {
if (!params.isJsonArray()) {
throw new JsonParseException("Expected params array");
}
final JsonArray paramsArray = params.getAsJsonArray();
if (paramsArray.size() != paramTypes.length) {
throw new JsonParseException("Expected " + paramTypes.length
+ " parameter values in params array");
}
final Object[] r = new Object[paramTypes.length];
for (int i = 0; i < r.length; i++) {
final JsonElement v = paramsArray.get(i);
if (v != null) {
r[i] = context.deserialize(v, paramTypes[i]);
}
}
req.params = r;
} else {
if (paramTypes.length != 0) {
throw new JsonParseException("Expected params array");
}
req.params = JsonServlet.NO_PARAMS;
}
return req;
}
private static boolean isString(final JsonElement e) {
return e != null && e.isJsonPrimitive()
&& e.getAsJsonPrimitive().isString();
}
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.server;
/** A validated token from {@link SignedToken#checkToken(String, String)} */
public class ValidToken {
private final boolean refresh;
private final String data;
public ValidToken(final boolean ref, final String d) {
refresh = ref;
data = d;
}
/** The text protected by the token's encryption key. */
public String getData() {
return data;
}
/** True if the token's life span is almost half-over and should be renewed. */
public boolean needsRefresh() {
return refresh;
}
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.server;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.jws.WebService;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.rapla.components.util.ParseDateException;
import org.rapla.components.util.SerializableDateTimeFormat;
import org.rapla.entities.DependencyException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.logger.Logger;
import org.rapla.rest.gwtjsonrpc.common.FutureResult;
import org.rapla.rest.gwtjsonrpc.common.JSONParserWrapper;
import org.rapla.rest.gwtjsonrpc.common.JsonConstants;
import org.rapla.rest.jsonpatch.mergepatch.server.JsonMergePatch;
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;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
/**
* Forward JSON based RPC requests onto services.
* <b>JSON-RPC 1.1</b><br>
* Calling conventions match the JSON-RPC 1.1 working draft from 7 August 2006
* (<a href="http://json-rpc.org/wd/JSON-RPC-1-1-WD-20060807.html">draft</a>).
* Only positional parameters are supported.
* <p>
* <b>JSON-RPC 2.0</b><br>
* Calling conventions match the JSON-RPC 2.0 specification.
* <p>
* When supported by the browser/client, the "gzip" encoding is used to compress
* the resulting JSON, reducing transfer time for the response data.
*/
public class JsonServlet {
public final static String JSON_METHOD = "method";
static final Object[] NO_PARAMS = {};
Class class1;
private Map<String, MethodHandle> myMethods;
Logger logger;
public JsonServlet(final Logger logger, final Class class1) throws RaplaException {
this.class1 = class1;
this.logger = logger;
myMethods = methods(class1);
if (myMethods.isEmpty()) {
throw new RaplaException("No public service methods declared in " + class1 + " Did you forget the javax.jws.WebService annotation?");
}
}
public Class getInterfaceClass() {
return class1;
}
/** Create a GsonBuilder to parse a request or return a response. */
protected GsonBuilder createGsonBuilder() {
return JSONParserWrapper.defaultGsonBuilder();
}
/**
* Lookup a method implemented by this servlet.
*
* @param methodName
* name of the method.
* @return the method handle; null if the method is not declared.
*/
protected MethodHandle lookupMethod(final String methodName) {
return myMethods.get(methodName);
}
/** @return maximum size of a JSON request, in bytes */
protected int maxRequestSize() {
// Our default limit of 100 MB should be sufficient for nearly any
// application. It takes a long time to format this on the client
// or to upload it.
//
return 100 * 1024 * 1024;
}
public void service(final HttpServletRequest req, final HttpServletResponse resp, ServletContext servletContext, final Object service) throws IOException {
ActiveCall call = new ActiveCall(req, resp);
call.noCache();
// if (!acceptJSON(call)) {
// textError(call, SC_BAD_REQUEST, "Must Accept " +
// JsonConstants.JSON_TYPE);
// return;
// }
boolean isPatch = req.getMethod().equals("PATCH");
doService(service, call);
if ( isPatch && !call.hasFailed())
{
Object result = call.result;
call = new ActiveCall(req, resp);
try
{
final Gson gs = createGsonBuilder().create();
JsonElement unpatchedObject = gs.toJsonTree(result);
String patchBody = readBody(call);
JsonElement patchElement = new JsonParser().parse( patchBody);
final JsonMergePatch patch = JsonMergePatch.fromJson(patchElement);
final JsonElement patchedObject = patch.apply(unpatchedObject);
Object patchMethod = req.getAttribute("patchMethod");
if ( patchMethod == null )
{
throw new RaplaException("request attribute patchMethod or patchParameter is missing.");
}
req.setAttribute("method", patchMethod);
String patchedObjectToString =gs.toJson( patchedObject);
req.setAttribute("postBody", patchedObjectToString);
doService(service, call);
}
catch (Exception ex)
{
call.externalFailure = ex;
}
}
final String out = formatResult(call);
RPCServletUtils.writeResponse(servletContext, call.httpResponse, out, out.length() > 256 && RPCServletUtils.acceptsGzipEncoding(call.httpRequest));
}
public void serviceError(final HttpServletRequest req, final HttpServletResponse resp, ServletContext servletContext, final Throwable ex) throws IOException {
final ActiveCall call = new ActiveCall(req, resp);
call.versionName = "jsonrpc";
call.versionValue = new JsonPrimitive("2.0");
call.noCache();
call.onInternalFailure(ex);
final String out = formatResult(call);
RPCServletUtils.writeResponse(servletContext, call.httpResponse, out, out.length() > 256 && RPCServletUtils.acceptsGzipEncoding(call.httpRequest));
}
// private boolean acceptJSON(final CallType call) {
// final String accepts = call.httpRequest.getHeader("Accept");
// if (accepts == null) {
// // A really odd client, it didn't send us an accept header?
// //
// return false;
// }
//
// if (JsonConstants.JSON_TYPE.equals(accepts)) {
// // Common case, as our JSON client side code sets only this
// //
// return true;
// }
//
// // The browser may take JSON, but also other types. The popular
// // Opera browser will add other accept types to our AJAX requests
// // even though our AJAX handler wouldn't be able to actually use
// // the data. The common case for these is to start with our own
// // type, then others, so we special case it before we go through
// // the expense of splitting the Accepts header up.
// //
// if (accepts.startsWith(JsonConstants.JSON_TYPE + ",")) {
// return true;
// }
// final String[] parts = accepts.split("[ ,;][ ,;]*");
// for (final String p : parts) {
// if (JsonConstants.JSON_TYPE.equals(p)) {
// return true;
// }
// }
//
// // Assume the client is busted and won't take JSON back.
// //
// return false;
// }
private void doService(final Object service, final ActiveCall call) throws IOException {
try {
try {
String httpMethod = call.httpRequest.getMethod();
if ("GET".equals(httpMethod) || "PATCH".equals(httpMethod)) {
parseGetRequest(call);
} else if ("POST".equals(httpMethod)) {
parsePostRequest(call);
} else {
call.httpResponse.setStatus(SC_BAD_REQUEST);
call.onFailure(new Exception("Unsupported HTTP method"));
return;
}
} catch (JsonParseException err) {
if (err.getCause() instanceof NoSuchRemoteMethodException) {
// GSON seems to catch our own exception and wrap it...
//
throw (NoSuchRemoteMethodException) err.getCause();
}
call.httpResponse.setStatus(SC_BAD_REQUEST);
call.onFailure(new Exception("Error parsing request " + err.getMessage(), err));
return;
}
} catch (NoSuchRemoteMethodException err) {
call.httpResponse.setStatus(SC_NOT_FOUND);
call.onFailure(new Exception("No such service method"));
return;
}
if (!call.isComplete()) {
call.method.invoke(service, call.params, call);
}
}
private void parseGetRequest(final ActiveCall call) {
final HttpServletRequest req = call.httpRequest;
if ("2.0".equals(req.getParameter("jsonrpc"))) {
final JsonObject d = new JsonObject();
d.addProperty("jsonrpc", "2.0");
d.addProperty("method", req.getParameter("method"));
d.addProperty("id", req.getParameter("id"));
try {
String parameter = req.getParameter("params");
final byte[] params = parameter.getBytes("ISO-8859-1");
JsonElement parsed;
try {
parsed = new JsonParser().parse(parameter);
} catch (JsonParseException e) {
final String p = new String(Base64.decodeBase64(params), "UTF-8");
parsed = new JsonParser().parse(p);
}
d.add("params", parsed);
} catch (UnsupportedEncodingException e) {
throw new JsonParseException("Cannot parse params", e);
}
try {
final GsonBuilder gb = createGsonBuilder();
gb.registerTypeAdapter(ActiveCall.class, new CallDeserializer(call, this));
gb.create().fromJson(d, ActiveCall.class);
} catch (JsonParseException err) {
call.method = null;
call.params = null;
throw err;
}
} else { /* JSON-RPC 1.1 or GET REST API */
String body = (String)req.getAttribute("postBody");
mapRequestToCall(call, req, body);
}
}
public void mapRequestToCall(final ActiveCall call, final HttpServletRequest req, String body) {
final Gson gs = createGsonBuilder().create();
String methodName = (String) req.getAttribute(JSON_METHOD);
if (methodName != null) {
call.versionName = "jsonrpc";
call.versionValue = new JsonPrimitive("2.0");
} else {
methodName = req.getParameter("method");
call.versionName = "version";
call.versionValue = new JsonPrimitive("1.1");
}
call.method = lookupMethod(methodName);
if (call.method == null) {
throw new NoSuchRemoteMethodException();
}
final Type[] paramTypes = call.method.getParamTypes();
String[] paramNames = call.method.getParamNames();
final Object[] r = new Object[paramTypes.length];
for (int i = 0; i < r.length; i++) {
Type type = paramTypes[i];
String name = paramNames[i];
if (name == null && !call.versionName.equals("jsonrpc")) {
name = "param" + i;
}
{
// First search in the request attributes
Object attribute = req.getAttribute(name);
Object paramValue;
if ( attribute != null)
{
paramValue =attribute;
Class attributeClass = attribute.getClass();
// we try to convert string and jsonelements to the parameter type (if the parameter type is not string or jsonelement)
if ( attributeClass.equals(String.class) && !type.equals(String.class) )
{
JsonParser parser = new JsonParser();
JsonElement parsed = parser.parse((String)attribute);
paramValue = gs.fromJson(parsed, type);
}
else if (JsonElement.class.isAssignableFrom(attributeClass) && !type.equals(JsonElement.class))
{
JsonElement parsed = (JsonElement) attribute;
paramValue = gs.fromJson(parsed, type);
}
else
{
paramValue =attribute;
}
}
// then in request parameters
else
{
String v = null;
v = req.getParameter(name);
// if not found in request use body
if ( v == null && body != null && !body.isEmpty())
{
v = body;
}
if (v == null) {
paramValue = null;
} else if (type == String.class) {
paramValue = v;
} else if (type == Date.class) {
// special case for handling date parameters with the
// ':' char i it
try {
paramValue = SerializableDateTimeFormat.INSTANCE.parseTimestamp(v);
} catch (ParseDateException e) {
throw new JsonSyntaxException(v, e);
}
} else if (type instanceof Class<?> && ((Class<?>) type).isPrimitive()) {
// Primitive type, use the JSON representation of that
// type.
//
paramValue = gs.fromJson(v, type);
} else {
// Assume it is like a java.sql.Timestamp or something
// and treat
// the value as JSON string.
//
JsonParser parser = new JsonParser();
JsonElement parsed = parser.parse(v);
paramValue = gs.fromJson(parsed, type);
}
}
r[i] = paramValue;
}
}
call.params = r;
}
private static boolean isBodyJson(final ActiveCall call) {
String type = call.httpRequest.getContentType();
if (type == null) {
return false;
}
int semi = type.indexOf(';');
if (semi >= 0) {
type = type.substring(0, semi).trim();
}
return JsonConstants.JSON_TYPE.equals(type);
}
private static boolean isBodyUTF8(final ActiveCall call) {
String enc = call.httpRequest.getCharacterEncoding();
if (enc == null) {
enc = "";
}
return enc.toLowerCase().contains(JsonConstants.JSON_ENC.toLowerCase());
}
private String readBody(final ActiveCall call) throws IOException {
if (!isBodyJson(call)) {
throw new JsonParseException("Invalid Request Content-Type");
}
if (!isBodyUTF8(call)) {
throw new JsonParseException("Invalid Request Character-Encoding");
}
final int len = call.httpRequest.getContentLength();
if (len < 0) {
throw new JsonParseException("Invalid Request Content-Length");
}
if (len == 0) {
throw new JsonParseException("Invalid Request POST Body Required");
}
if (len > maxRequestSize()) {
throw new JsonParseException("Invalid Request POST Body Too Large");
}
final InputStream in = call.httpRequest.getInputStream();
if (in == null) {
throw new JsonParseException("Invalid Request POST Body Required");
}
try {
final byte[] body = new byte[len];
int off = 0;
while (off < len) {
final int n = in.read(body, off, len - off);
if (n <= 0) {
throw new JsonParseException("Invalid Request Incomplete Body");
}
off += n;
}
final CharsetDecoder d = Charset.forName(JsonConstants.JSON_ENC).newDecoder();
d.onMalformedInput(CodingErrorAction.REPORT);
d.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
return d.decode(ByteBuffer.wrap(body)).toString();
} catch (CharacterCodingException e) {
throw new JsonParseException("Invalid Request Not UTF-8", e);
}
} finally {
in.close();
}
}
private void parsePostRequest(final ActiveCall call) throws UnsupportedEncodingException, IOException {
try {
HttpServletRequest request = call.httpRequest;
String attribute = (String)request.getAttribute(JSON_METHOD);
String postBody = readBody(call);
final GsonBuilder gb = createGsonBuilder();
if ( attribute != null)
{
mapRequestToCall(call, request, postBody);
}
else
{
gb.registerTypeAdapter(ActiveCall.class, new CallDeserializer(call, this));
Gson mapper = gb.create();
mapper.fromJson(postBody, ActiveCall.class);
}
} catch (JsonParseException err) {
call.method = null;
call.params = null;
throw err;
}
}
private String formatResult(final ActiveCall call) throws UnsupportedEncodingException, IOException {
final GsonBuilder gb = createGsonBuilder();
gb.registerTypeAdapter(call.getClass(), new JsonSerializer<ActiveCall>() {
@Override
public JsonElement serialize(final ActiveCall src, final Type typeOfSrc, final JsonSerializationContext context) {
if (call.externalFailure != null) {
final String msg;
if (call.method != null) {
msg = "Error in " + call.method.getName();
} else {
msg = "Error";
}
logger.error(msg, call.externalFailure);
}
Throwable failure = src.externalFailure != null ? src.externalFailure : src.internalFailure;
Object result = src.result;
if (result instanceof FutureResult) {
try {
result = ((FutureResult) result).get();
} catch (Exception e) {
failure = e;
}
}
final JsonObject r = new JsonObject();
if (src.versionName == null || src.versionValue == null)
{
r.add("jsonrpc", new JsonPrimitive("2.0"));
}
else
{
r.add(src.versionName, src.versionValue);
}
if (src.id != null) {
r.add("id", src.id);
}
if (failure != null) {
final int code = to2_0ErrorCode(src);
final JsonObject error = getError(src.versionName, code, failure, gb);
r.add("error", error);
} else {
r.add("result", context.serialize(result));
}
return r;
}
});
Gson create = gb.create();
final StringWriter o = new StringWriter();
create.toJson(call, o);
o.close();
String string = o.toString();
return string;
}
private int to2_0ErrorCode(final ActiveCall src) {
final Throwable e = src.externalFailure;
final Throwable i = src.internalFailure;
if (e instanceof NoSuchRemoteMethodException || i instanceof NoSuchRemoteMethodException) {
return -32601 /* Method not found. */;
}
if (e instanceof IllegalArgumentException || i instanceof IllegalArgumentException) {
return -32602 /* Invalid paramters. */;
}
if (e instanceof JsonParseException || i instanceof JsonParseException) {
return -32700 /* Parse error. */;
}
return -32603 /* Internal error. */;
}
// private static void textError(final ActiveCall call, final int status,
// final String message) throws IOException {
// final HttpServletResponse r = call.httpResponse;
// r.setStatus(status);
// r.setContentType("text/plain; charset=" + ENC);
//
// final Writer w = new OutputStreamWriter(r.getOutputStream(), ENC);
// try {
// w.write(message);
// } finally {
// w.close();
// }
// }
public static JsonObject getError(String version, int code, Throwable failure, GsonBuilder gb) {
final JsonObject error = new JsonObject();
String message = failure.getMessage();
if (message == null) {
message = failure.toString();
}
Gson gson = gb.create();
if ("jsonrpc".equals(version)) {
error.addProperty("code", code);
error.addProperty("message", message);
JsonObject errorData = new JsonObject();
errorData.addProperty("exception", failure.getClass().getName());
// FIXME Replace with generic solution for exception param
// serialization
if (failure instanceof DependencyException) {
JsonArray params = new JsonArray();
for (String dep : ((DependencyException) failure).getDependencies()) {
params.add(new JsonPrimitive(dep));
}
errorData.add("params", params);
}
JsonArray stackTrace = new JsonArray();
for (StackTraceElement el : failure.getStackTrace()) {
JsonElement jsonRep = gson.toJsonTree(el);
stackTrace.add( jsonRep);
}
errorData.add("stacktrace", stackTrace);
error.add("data", errorData);
} else {
error.addProperty("name", "JSONRPCError");
error.addProperty("code", 999);
error.addProperty("message", message);
}
return error;
}
private static Map<String, MethodHandle> methods(Class class1) {
final Class d = findInterface(class1);
if (d == null) {
return Collections.<String, MethodHandle> emptyMap();
}
final Map<String, MethodHandle> r = new HashMap<String, MethodHandle>();
for (final Method m : d.getMethods()) {
if (!Modifier.isPublic(m.getModifiers())) {
continue;
}
final MethodHandle h = new MethodHandle(m);
r.put(h.getName(), h);
}
return Collections.unmodifiableMap(r);
}
private static Class findInterface(Class<?> c) {
while (c != null) {
if ( c.getAnnotation(WebService.class) != null) {
return c;
}
for (final Class<?> i : c.getInterfaces()) {
final Class r = findInterface(i);
if (r != null) {
return r;
}
}
c = c.getSuperclass();
}
return null;
}
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.server;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Date;
import javax.crypto.Mac;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
* Utility function to compute and verify XSRF tokens.
* <p>
* {@link JsonServlet} uses this class to verify tokens appearing in the custom
* <code>xsrfKey</code> JSON request property. The tokens protect against
* cross-site request forgery by depending upon the browser's security model.
* The classic browser security model prohibits a script from site A from
* reading any data received from site B. By sending unforgeable tokens from the
* server and asking the client to return them to us, the client script must
* have had read access to the token at some point and is therefore also from
* our server.
*/
public class SignedToken {
private static final int INT_SZ = 4;
private static final String MAC_ALG = "HmacSHA1";
/**
* Generate a random key for use with the XSRF library.
*
* @return a new private key, base 64 encoded.
*/
public static String generateRandomKey() {
final byte[] r = new byte[26];
new SecureRandom().nextBytes(r);
return encodeBase64(r);
}
private final int maxAge;
private final SecretKeySpec key;
private final SecureRandom rng;
private final int tokenLength;
/**
* Create a new utility, using a randomly generated key.
*
* @param age the number of seconds a token may remain valid.
* @throws XsrfException the JVM doesn't support the necessary algorithms.
*/
public SignedToken(final int age) throws XsrfException {
this(age, generateRandomKey());
}
/**
* Create a new utility, using the specific key.
*
* @param age the number of seconds a token may remain valid.
* @param keyBase64 base 64 encoded representation of the key.
* @throws XsrfException the JVM doesn't support the necessary algorithms.
*/
public SignedToken(final int age, final String keyBase64)
throws XsrfException {
maxAge = age > 5 ? age / 5 : age;
key = new SecretKeySpec(decodeBase64(keyBase64), MAC_ALG);
rng = new SecureRandom();
tokenLength = 2 * INT_SZ + newMac().getMacLength();
}
/** @return maximum age of a signed token, in seconds. */
public int getMaxAge() {
return maxAge > 0 ? maxAge * 5 : maxAge;
}
// /**
// * Get the text of a signed token which is stored in a cookie.
// *
// * @param cookieName the name of the cookie to get the text from.
// * @return the signed text; null if the cookie is not set or the cookie's
// * token was forged.
// */
// public String getCookieText(final String cookieName) {
// final String val = ServletCookieAccess.get(cookieName);
// boolean ok;
// try {
// ok = checkToken(val, null) != null;
// } catch (XsrfException e) {
// ok = false;
// }
// return ok ? ServletCookieAccess.getTokenText(cookieName) : null;
// }
/**
* Generate a new signed token.
*
* @param text the text string to sign. Typically this should be some
* user-specific string, to prevent replay attacks. The text must be
* safe to appear in whatever context the token itself will appear, as
* the text is included on the end of the token.
* @return the signed token. The text passed in <code>text</code> will appear
* after the first ',' in the returned token string.
* @throws XsrfException the JVM doesn't support the necessary algorithms.
*/
public String newToken(final String text, Date now) throws XsrfException {
final int q = rng.nextInt();
final byte[] buf = new byte[tokenLength];
encodeInt(buf, 0, q);
encodeInt(buf, INT_SZ, now(now) ^ q);
computeToken(buf, text);
return encodeBase64(buf) + '$' + text;
}
/**
* Validate a returned token.
*
* @param tokenString a token string previously created by this class.
* @param text text that must have been used during {@link #newToken(String)}
* in order for the token to be valid. If null the text will be taken
* from the token string itself.
* @return true if the token is valid; false if the token is null, the empty
* string, has expired, does not match the text supplied, or is a
* forged token.
* @throws XsrfException the JVM doesn't support the necessary algorithms to
* generate a token. XSRF services are simply not available.
*/
public ValidToken checkToken(final String tokenString, final String text,Date now)
throws XsrfException {
if (tokenString == null || tokenString.length() == 0) {
return null;
}
final int s = tokenString.indexOf('$');
if (s <= 0) {
return null;
}
final String recvText = tokenString.substring(s + 1);
final byte[] in;
try {
String substring = tokenString.substring(0, s);
in = decodeBase64(substring);
} catch (RuntimeException e) {
return null;
}
if (in.length != tokenLength) {
return null;
}
final int q = decodeInt(in, 0);
final int c = decodeInt(in, INT_SZ) ^ q;
final int n = now( now);
if (maxAge > 0 && Math.abs(c - n) > maxAge) {
return null;
}
final byte[] gen = new byte[tokenLength];
System.arraycopy(in, 0, gen, 0, 2 * INT_SZ);
computeToken(gen, text != null ? text : recvText);
if (!Arrays.equals(gen, in)) {
return null;
}
return new ValidToken(maxAge > 0 && c + (maxAge >> 1) <= n, recvText);
}
private void computeToken(final byte[] buf, final String text)
throws XsrfException {
final Mac m = newMac();
m.update(buf, 0, 2 * INT_SZ);
m.update(toBytes(text));
try {
m.doFinal(buf, 2 * INT_SZ);
} catch (ShortBufferException e) {
throw new XsrfException("Unexpected token overflow", e);
}
}
private Mac newMac() throws XsrfException {
try {
final Mac m = Mac.getInstance(MAC_ALG);
m.init(key);
return m;
} catch (NoSuchAlgorithmException e) {
throw new XsrfException(MAC_ALG + " not supported", e);
} catch (InvalidKeyException e) {
throw new XsrfException("Invalid private key", e);
}
}
private static int now(Date now) {
return (int) (now.getTime() / 5000L);
}
private static byte[] decodeBase64(final String s) {
return Base64.decodeBase64(toBytes(s));
}
private static String encodeBase64(final byte[] buf) {
return toString(Base64.encodeBase64(buf));
}
private static void encodeInt(final byte[] buf, final int o, int v) {
buf[o + 3] = (byte) v;
v >>>= 8;
buf[o + 2] = (byte) v;
v >>>= 8;
buf[o + 1] = (byte) v;
v >>>= 8;
buf[o] = (byte) v;
}
private static int decodeInt(final byte[] buf, final int o) {
int r = buf[o] << 8;
r |= buf[o + 1] & 0xff;
r <<= 8;
r |= buf[o + 2] & 0xff;
return (r << 8) | (buf[o + 3] & 0xff);
}
private static byte[] toBytes(final String s) {
final byte[] r = new byte[s.length()];
for (int k = r.length - 1; k >= 0; k--) {
r[k] = (byte) s.charAt(k);
}
return r;
}
private static String toString(final byte[] b) {
final StringBuilder r = new StringBuilder(b.length);
for (int i = 0; i < b.length; i++) {
r.append((char) b[i]);
}
return r.toString();
}
}
| Java |
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.rapla.rest.gwtjsonrpc.server;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.rest.gwtjsonrpc.common.AsyncCallback;
import com.google.gson.JsonElement;
/** An active RPC call. */
public class ActiveCall implements AsyncCallback<Object> {
protected final HttpServletRequest httpRequest;
protected final HttpServletResponse httpResponse;
JsonElement id;
String versionName;
JsonElement versionValue;
MethodHandle method;
Object[] params;
Object result;
Throwable externalFailure;
Throwable internalFailure;
/**
* Create a new call.
*
* @param req the request.
* @param resp the response.
*/
public ActiveCall(final HttpServletRequest req, final HttpServletResponse resp) {
httpRequest = req;
httpResponse = resp;
}
/**
* @return true if this call has something to send to the client; false if the
* call still needs to be computed further in order to come up with a
* success return value or a failure
*/
public final boolean isComplete() {
return result != null || externalFailure != null || internalFailure != null;
}
@Override
public final void onSuccess(final Object result) {
this.result = result;
this.externalFailure = null;
this.internalFailure = null;
}
@Override
public void onFailure(final Throwable error) {
this.result = null;
this.externalFailure = error;
this.internalFailure = null;
}
public final void onInternalFailure(final Throwable error) {
this.result = null;
this.externalFailure = null;
this.internalFailure = error;
}
/** Mark the response to be uncached by proxies and browsers. */
public void noCache() {
httpResponse.setHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT");
httpResponse.setHeader("Pragma", "no-cache");
httpResponse.setHeader("Cache-Control", "no-cache, must-revalidate");
}
public boolean hasFailed() {
return externalFailure != null || internalFailure != null;
}
}
| Java |
package org.rapla.rest;
public @interface GwtIncompatible {
}
| Java |
package org.rapla.rest.client;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
public class HTTPJsonConnector {
public HTTPJsonConnector() {
super();
}
private String readResultToString(InputStream input) throws IOException {
InputStreamReader in = new InputStreamReader( input,"UTF-8");
char[] buf = new char[4096];
StringBuffer buffer = new StringBuffer();
while ( true )
{
int len = in.read(buf);
if ( len == -1)
{
break;
}
buffer.append( buf, 0,len );
}
String result = buffer.toString();
in.close();
return result;
}
public JsonObject sendPost(URL methodURL, JsonElement jsonObject, String authenticationToken) throws IOException,JsonParseException {
return sendCall("POST", methodURL, jsonObject, authenticationToken);
}
public JsonObject sendGet(URL methodURL, String authenticationToken) throws IOException,JsonParseException {
return sendCall("GET", methodURL, null, authenticationToken);
}
public JsonObject sendPut(URL methodURL, JsonElement jsonObject, String authenticationToken) throws IOException,JsonParseException {
return sendCall("PUT", methodURL, jsonObject, authenticationToken);
}
public JsonObject sendPatch(URL methodURL, JsonElement jsonObject, String authenticationToken) throws IOException,JsonParseException {
return sendCall("PATCH", methodURL, jsonObject, authenticationToken);
}
public JsonObject sendDelete(URL methodURL, String authenticationToken) throws IOException,JsonParseException {
return sendCall("DELETE", methodURL, null, authenticationToken);
}
protected JsonObject sendCall(String requestMethod, URL methodURL, JsonElement jsonObject, String authenticationToken) throws IOException,JsonParseException {
HttpURLConnection conn = (HttpURLConnection)methodURL.openConnection();
if ( !requestMethod.equals("POST") && !requestMethod.equals("GET"))
{
conn.setRequestMethod("POST");
// we tunnel all non POST or GET requests to avoid proxy filtering (e.g. URLConnection does not allow PATCH)
conn.setRequestProperty("X-HTTP-Method-Override",requestMethod);
}
else
{
conn.setRequestMethod(requestMethod);
}
conn.setUseCaches( false );
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.setRequestProperty("Content-Type", "application/json" + ";charset=utf-8");
conn.setRequestProperty("Accept", "application/json");
if ( authenticationToken != null)
{
conn.setRequestProperty("Authorization", "Bearer " + authenticationToken);
}
conn.setReadTimeout(20000); //set timeout to 20 seconds
conn.setConnectTimeout(15000); //set connect timeout to 15 seconds
conn.setDoOutput(true);
conn.connect();
if ( requestMethod.equals("PUT") ||requestMethod.equals("POST") ||requestMethod.equals("PATCH"))
{
OutputStream outputStream = null;
Writer wr = null;
try
{
outputStream= conn.getOutputStream();
wr = new OutputStreamWriter(outputStream,"UTF-8");
Gson gson = new GsonBuilder().create();
String body = gson.toJson( jsonObject);
wr.write( body);
wr.flush();
}
finally
{
if ( wr != null)
{
wr.close();
}
if ( outputStream != null)
{
outputStream.close();
}
}
}
else
{
}
JsonObject resultMessage = readResult(conn);
return resultMessage;
}
public JsonObject readResult(HttpURLConnection conn) throws IOException,JsonParseException {
String resultString;
InputStream inputStream = null;
try
{
String encoding = conn.getContentEncoding();
if (encoding != null && encoding.equalsIgnoreCase("gzip"))
{
inputStream = new GZIPInputStream(conn.getInputStream());
}
else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
inputStream = new InflaterInputStream(conn.getInputStream(), new Inflater(true));
}
else {
inputStream = conn.getInputStream();
}
resultString = readResultToString( inputStream);
}
finally
{
if ( inputStream != null)
{
inputStream.close();
}
}
JsonParser jsonParser = new JsonParser();
JsonElement parsed = jsonParser.parse(resultString);
if ( !(parsed instanceof JsonObject))
{
throw new JsonParseException("Invalid json result. JsonObject expected.");
}
JsonObject resultMessage = (JsonObject) parsed;
return resultMessage;
}
} | Java |
package org.rapla.rest.jsonpatch.mergepatch.server;
import com.google.gson.JsonElement;
final class ArrayMergePatch extends JsonMergePatch
{
// Always an array
private final JsonElement content;
ArrayMergePatch(final JsonElement content)
{
super(content);
this.content = clearNulls(content);
}
@Override
public JsonElement apply(final JsonElement input) throws JsonPatchException
{
return content;
}
} | Java |
package org.rapla.rest.jsonpatch.mergepatch.server;
public class JsonPatchException extends Exception {
private static final long serialVersionUID = 1L;
public JsonPatchException(String string) {
super(string);
}
}
| Java |
package org.rapla.rest.jsonpatch.mergepatch.server;
import java.util.Iterator;
import java.util.Map;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public abstract class JsonMergePatch
{
protected final JsonElement origPatch;
/**
* Protected constructor
*
* <p>Only necessary for serialization purposes. The patching process
* itself never requires the full node to operate.</p>
*
* @param node the original patch node
*/
protected JsonMergePatch(final JsonElement node)
{
origPatch = node;
}
public abstract JsonElement apply(final JsonElement input) throws JsonPatchException;
public static JsonMergePatch fromJson(final JsonElement input)
throws JsonPatchException
{
if ( input.isJsonPrimitive())
{
throw new JsonPatchException("Only json containers are supported");
}
return input.isJsonArray() ? new ArrayMergePatch(input)
: new ObjectMergePatch(input);
}
/**
* Clear "null values" from a JSON value
*
* <p>Non container values are unchanged. For arrays, null elements are
* removed. From objects, members whose values are null are removed.</p>
*
* <p>This method is recursive, therefore arrays within objects, or objects
* within arrays, or arrays within arrays etc are also affected.</p>
*
* @param node the original JSON value
* @return a JSON value without null values (see description)
*/
protected static JsonElement clearNulls(final JsonElement node)
{
if (node.isJsonPrimitive())
return node;
return node.isJsonArray() ? clearNullsFromArray((JsonArray)node) : clearNullsFromObject((JsonObject)node);
}
private static JsonElement clearNullsFromArray(final JsonArray node)
{
final JsonArray ret = new JsonArray();
/*
* Cycle through array elements. If the element is a null node itself,
* skip it. Otherwise, add a "cleaned up" element to the result.
*/
for (final JsonElement element: node)
if (!element.isJsonNull())
ret.add(clearNulls(element));
return ret;
}
private static JsonElement clearNullsFromObject(final JsonObject node)
{
final JsonObject ret = new JsonObject();
final Iterator<Map.Entry<String, JsonElement>> iterator
= node.entrySet().iterator();
Map.Entry<String, JsonElement> entry;
JsonElement value;
/*
* When faces with an object, cycle through this object's entries.
*
* If the value of the entry is a JSON null, don't include it in the
* result. If not, include a "cleaned up" value for this key instead of
* the original element.
*/
while (iterator.hasNext()) {
entry = iterator.next();
value = entry.getValue();
if (value != null) {
String key = entry.getKey();
JsonElement clearNulls = clearNulls(value);
ret.add(key, clearNulls);
}
}
return ret;
}
public String toString()
{
return origPatch.toString();
}
} | Java |
/*
* Copyright (c) 2014, Francis Galiegue (fgaliegue@gmail.com)
*
* This software is dual-licensed under:
*
* - the Lesser General Public License (LGPL) version 3.0 or, at your option, any
* later version;
* - the Apache Software License (ASL) version 2.0.
*
* The text of both licenses is available under the src/resources/ directory of
* this project (under the names LGPL-3.0.txt and ASL-2.0.txt respectively).
*
* Direct link to the sources:
*
* - LGPL 3.0: https://www.gnu.org/licenses/lgpl-3.0.txt
* - ASL 2.0: http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.rapla.rest.jsonpatch.mergepatch.server;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/**
* Merge patch for a JSON Object
*
* <p>This only takes care of the top level, and delegates to other {@link
* JsonMergePatch} instances for deeper levels.</p>
*/
final class ObjectMergePatch
extends JsonMergePatch
{
private final Map<String, JsonElement> fields;
private final Set<String> removals;
ObjectMergePatch(final JsonElement content)
{
super(content);
fields = asMap(content);
removals = new HashSet<String>();
for (final Map.Entry<String, JsonElement> entry: fields.entrySet())
if (entry.getValue() == null)
removals.add(entry.getKey());
fields.keySet().removeAll(removals);
}
@Override
public JsonElement apply(final JsonElement input) throws JsonPatchException
{
if (!input.isJsonObject())
return mapToNode(fields);
final Map<String, JsonElement> map = asMap(input);
// Remove all entries which must be removed
map.keySet().removeAll(removals);
// Now cycle through what is left
String memberName;
JsonElement patchNode;
for (final Map.Entry<String, JsonElement> entry: map.entrySet()) {
memberName = entry.getKey();
patchNode = fields.get(memberName);
// Leave untouched if no mention in the patch
if (patchNode == null)
continue;
// If the patch node is a primitive type, replace in the result.
// Reminder: there cannot be a JSON null anymore
if (patchNode.isJsonPrimitive()) {
entry.setValue(patchNode); // no need for .deepCopy()
continue;
}
final JsonMergePatch patch = JsonMergePatch.fromJson(patchNode);
entry.setValue(patch.apply(entry.getValue()));
}
// Finally, if there are members in the patch not present in the input,
// fill in members
for (final String key: difference(fields.keySet(), map.keySet()))
map.put(key, clearNulls(fields.get(key)));
return mapToNode(map);
}
private Set<String> difference(Set<String> keySet, Set<String> keySet2) {
LinkedHashSet<String> result = new LinkedHashSet<String>();
for ( String key:keySet)
{
if ( !keySet2.contains(key))
{
result.add( key);
}
}
return result;
}
private Map<String, JsonElement> asMap(JsonElement input) {
Map<String,JsonElement> result = new LinkedHashMap<String,JsonElement>();
for ( Entry<String, JsonElement> entry :input.getAsJsonObject().entrySet())
{
JsonElement value = entry.getValue();
String key = entry.getKey();
result.put( key,value);
}
return result;
}
private static JsonElement mapToNode(final Map<String, JsonElement> map)
{
final JsonObject ret = new JsonObject();
for ( String key: map.keySet())
{
JsonElement value = map.get( key);
ret.add(key, value);
}
return ret;
}
}
| Java |
package org.rapla.rest.server;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.jws.WebParam;
import javax.jws.WebService;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.internal.AppointmentImpl;
import org.rapla.entities.domain.internal.ReservationImpl;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.servletpages.RaplaPageGenerator;
import org.rapla.storage.RaplaSecurityException;
@WebService
public class RaplaEventsRestPage extends AbstractRestPage implements RaplaPageGenerator
{
public RaplaEventsRestPage(RaplaContext context) throws RaplaException
{
super(context);
}
private Collection<String> CLASSIFICATION_TYPES = Arrays.asList(new String[] {DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION});
public List<ReservationImpl> list(@WebParam(name="user") User user, @WebParam(name="start")Date start, @WebParam(name="end")Date end, @WebParam(name="resources") List<String> resources, @WebParam(name="eventTypes") List<String> eventTypes,@WebParam(name="attributeFilter") Map<String,String> simpleFilter ) throws RaplaException
{
Collection<Allocatable> allocatables = new ArrayList<Allocatable>();
for (String id :resources)
{
Allocatable allocatable = operator.resolve(id, Allocatable.class);
allocatables.add( allocatable);
}
ClassificationFilter[] filters = getClassificationFilter(simpleFilter, CLASSIFICATION_TYPES, eventTypes);
Map<String, String> annotationQuery = null;
boolean canReadReservationsFromOthers = getQuery().canReadReservationsFromOthers(user);
User owner = null;
Collection<Reservation> reservations = operator.getReservations(owner, allocatables, start, end, filters, annotationQuery);
List<ReservationImpl> result = new ArrayList<ReservationImpl>();
for ( Reservation r:reservations)
{
if ( RaplaComponent.canRead(r, user, canReadReservationsFromOthers))
{
result.add((ReservationImpl) r);
}
}
return result;
}
public ReservationImpl get(@WebParam(name="user") User user, @WebParam(name="id")String id) throws RaplaException
{
ReservationImpl event = (ReservationImpl) operator.resolve(id, Reservation.class);
boolean canReadReservationsFromOthers = getQuery().canReadReservationsFromOthers(user);
if (!RaplaComponent.canRead(event, user, canReadReservationsFromOthers))
{
throw new RaplaSecurityException("User " + user + " can't read event " + event);
}
return event;
}
public ReservationImpl update(@WebParam(name="user") User user, ReservationImpl event) throws RaplaException
{
if (!RaplaComponent.canModify(event, user))
{
throw new RaplaSecurityException("User " + user + " can't modify event " + event);
}
event.setResolver( operator);
getModification().store( event);
ReservationImpl result =(ReservationImpl) getModification().getPersistant( event);
return result;
}
public ReservationImpl create(@WebParam(name="user") User user, ReservationImpl event) throws RaplaException
{
if (!getQuery().canCreateReservations(user))
{
throw new RaplaSecurityException("User " + user + " can't modify event " + event);
}
if (event.getId() != null)
{
throw new RaplaException("Id has to be null for new events");
}
String eventId = operator.createIdentifier(Reservation.TYPE, 1)[0];
event.setId( eventId);
event.setResolver( operator);
event.setCreateDate( operator.getCurrentTimestamp());
Appointment[] appointments = event.getAppointments();
String[] appointmentIds = operator.createIdentifier(Appointment.TYPE, 1);
for ( int i=0;i<appointments.length;i++)
{
AppointmentImpl app = (AppointmentImpl)appointments[i];
String id = appointmentIds[i];
app.setId(id);
}
event.setOwner( user );
getModification().store( event);
ReservationImpl result =(ReservationImpl) getModification().getPersistant( event);
return result;
}
}
| Java |
package org.rapla.rest.server;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.servletpages.RaplaPageGenerator;
import org.rapla.storage.dbrm.RemoteServer;
public class RaplaAuthRestPage extends RaplaAPIPage implements RaplaPageGenerator
{
public RaplaAuthRestPage(RaplaContext context) throws RaplaContextException {
super(context);
}
@Override
protected String getServiceAndMethodName(HttpServletRequest request)
{
return RemoteServer.class.getName() +"/auth";
}
@Override
public void generatePage(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
super.generatePage(servletContext, request, response);
}
}
| Java |
package org.rapla.rest.server;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.entities.User;
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.facade.ClientFacade;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.rest.gwtjsonrpc.server.JsonServlet;
import org.rapla.server.ServerServiceContainer;
import org.rapla.servletpages.RaplaPageGenerator;
import org.rapla.storage.RaplaSecurityException;
import org.rapla.storage.StorageOperator;
public class AbstractRestPage extends RaplaComponent implements RaplaPageGenerator {
protected StorageOperator operator;
protected JsonServlet servlet;
protected final ServerServiceContainer serverContainer;
String getMethod = null;
String updatetMethod = null;
String listMethod = null;
String createMethod = null;
public AbstractRestPage(RaplaContext context) throws RaplaException
{
super(context);
operator = context.lookup( ClientFacade.class).getOperator();
serverContainer = context.lookup(ServerServiceContainer.class);
Class class1 = getServiceObject().getClass();
Collection<String> publicMethodNames = getPublicMethods(class1);
servlet = new JsonServlet(getLogger(), class1);
if ( publicMethodNames.contains("get"))
{
getMethod = "get";
}
if ( publicMethodNames.contains("update"))
{
updatetMethod = "update";
}
if ( publicMethodNames.contains("create"))
{
createMethod = "create";
}
if ( publicMethodNames.contains("list"))
{
listMethod = "list";
}
}
@Override
public void generatePage(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
User user;
Object serviceObj = getServiceObject();
try {
user = serverContainer.getUser(request);
if ( user == null)
{
throw new RaplaSecurityException("User not authentified. Pass access token");
}
request.setAttribute("user", user);
String pathInfo = request.getPathInfo();
int appendix = pathInfo.indexOf("/",1);
String method = request.getMethod();
if ( appendix > 0)
{
if ( method.equals("GET") && getMethod != null )
{
String id = pathInfo.substring(appendix+1);
request.setAttribute("id", id);
request.setAttribute("method", getMethod);
}
else if ( method.equals("PATCH") && getMethod != null && updatetMethod != null)
{
String id = pathInfo.substring(appendix+1);
request.setAttribute("id", id);
request.setAttribute("method", getMethod);
request.setAttribute("patchMethod", updatetMethod);
}
else if ( method.equals("PUT") && updatetMethod != null)
{
String id = pathInfo.substring(appendix+1);
request.setAttribute("id", id);
request.setAttribute("method", updatetMethod);
}
else
{
throw new RaplaException(method + " Method not supported in this context");
}
}
else
{
if ( method.equals("GET") && listMethod != null)
{
request.setAttribute("method", listMethod);
}
else if ( method.equals("POST") && createMethod != null)
{
request.setAttribute("method", createMethod);
}
else
{
throw new RaplaException(method + " Method not supported in this context");
}
}
} catch (RaplaException ex) {
servlet.serviceError(request, response, servletContext, ex);
return;
}
servlet.service(request, response, servletContext, serviceObj);
// super.generatePage(servletContext, request, response);
}
protected Collection<String> getPublicMethods(Class class1) {
HashSet<String> result = new HashSet<String>();
for (Method m:class1.getMethods())
{
if ( Modifier.isPublic(m.getModifiers() ))
{
result.add( m.getName());
}
}
return result;
}
public ClassificationFilter[] getClassificationFilter(Map<String, String> simpleFilter, Collection<String> selectedClassificationTypes, Collection<String> typeNames) throws RaplaException {
ClassificationFilter[] filters = null;
if ( simpleFilter != null || typeNames == null)
{
DynamicType[] types = getQuery().getDynamicTypes(null);
List<ClassificationFilter> filterList = new ArrayList<ClassificationFilter>();
for ( DynamicType type:types)
{
String classificationType = type.getAnnotation(DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
if ( classificationType == null || !selectedClassificationTypes.contains(classificationType))
{
continue;
}
ClassificationFilter classificationFilter = type.newClassificationFilter();
if ( typeNames != null)
{
if ( !typeNames.contains( type.getKey()))
{
continue;
}
}
if ( simpleFilter != null)
{
for (String key:simpleFilter.keySet())
{
Attribute att = type.getAttribute(key);
if ( att != null)
{
String value = simpleFilter.get(key);
// convert from string to attribute type
Object object = att.convertValue(value);
if ( object != null)
{
classificationFilter.addEqualsRule(att.getKey(), object);
}
filterList.add(classificationFilter);
}
}
}
else
{
filterList.add(classificationFilter);
}
}
filters = filterList.toArray( new ClassificationFilter[] {});
}
return filters;
}
private Object getServiceObject() {
return this;
}
} | Java |
package org.rapla.rest.server;
import java.util.ArrayList;
import java.util.List;
import javax.jws.WebParam;
import javax.jws.WebService;
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.servletpages.RaplaPageGenerator;
@WebService
public class RaplaDynamicTypesRestPage extends AbstractRestPage implements RaplaPageGenerator
{
public RaplaDynamicTypesRestPage(RaplaContext context) throws RaplaException {
super(context);
}
public List<DynamicTypeImpl> list(@WebParam(name="classificationType") String classificationType ) throws RaplaException
{
DynamicType[] types = getQuery().getDynamicTypes(classificationType);
List<DynamicTypeImpl> result = new ArrayList<DynamicTypeImpl>();
for ( DynamicType r:types)
{
result.add((DynamicTypeImpl) r);
}
return result;
}
}
| Java |
package org.rapla.rest.server;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.jws.WebParam;
import javax.jws.WebService;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.internal.AllocatableImpl;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.servletpages.RaplaPageGenerator;
import org.rapla.storage.RaplaSecurityException;
@WebService
public class RaplaResourcesRestPage extends AbstractRestPage implements RaplaPageGenerator
{
private Collection<String> CLASSIFICATION_TYPES = Arrays.asList(new String[] {DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE,DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON});
public RaplaResourcesRestPage(RaplaContext context) throws RaplaException
{
super(context);
}
public List<AllocatableImpl> list(@WebParam(name="user") User user,@WebParam(name="resourceTypes") List<String> resourceTypes, @WebParam(name="attributeFilter") Map<String,String> simpleFilter ) throws RaplaException
{
ClassificationFilter[] filters = getClassificationFilter(simpleFilter, CLASSIFICATION_TYPES, resourceTypes);
Collection<Allocatable> resources = operator.getAllocatables(filters);
List<AllocatableImpl> result = new ArrayList<AllocatableImpl>();
for ( Allocatable r:resources)
{
if ( RaplaComponent.canRead(r, user))
{
result.add((AllocatableImpl) r);
}
}
return result;
}
public AllocatableImpl get(@WebParam(name="user") User user, @WebParam(name="id")String id) throws RaplaException
{
AllocatableImpl resource = (AllocatableImpl) operator.resolve(id, Allocatable.class);
if (!RaplaComponent.canRead(resource, user))
{
throw new RaplaSecurityException("User " + user + " can't read " + resource);
}
return resource;
}
public AllocatableImpl update(@WebParam(name="user") User user, AllocatableImpl resource) throws RaplaException
{
if (!RaplaComponent.canModify(resource, user))
{
throw new RaplaSecurityException("User " + user + " can't modify " + resource);
}
resource.setResolver( operator);
getModification().store( resource );
AllocatableImpl result =(AllocatableImpl) getModification().getPersistant( resource);
return result;
}
public AllocatableImpl create(@WebParam(name="user") User user, AllocatableImpl resource) throws RaplaException
{
if (!getQuery().canCreateReservations(user))
{
throw new RaplaSecurityException("User " + user + " can't modify " + resource);
}
if (resource.getId() != null)
{
throw new RaplaException("Id has to be null for new events");
}
String eventId = operator.createIdentifier(Allocatable.TYPE, 1)[0];
resource.setId( eventId);
resource.setResolver( operator);
resource.setCreateDate( operator.getCurrentTimestamp());
resource.setOwner( user );
getModification().store( resource);
AllocatableImpl result =(AllocatableImpl) getModification().getPersistant( resource);
return result;
}
}
| Java |
package org.rapla.rest.server;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.rest.gwtjsonrpc.common.JSONParserWrapper;
import org.rapla.rest.gwtjsonrpc.server.JsonServlet;
import org.rapla.rest.gwtjsonrpc.server.RPCServletUtils;
import org.rapla.server.ServerServiceContainer;
import org.rapla.servletpages.RaplaPageGenerator;
import org.rapla.storage.RaplaSecurityException;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
public class RaplaAPIPage extends RaplaComponent implements RaplaPageGenerator
{
final ServerServiceContainer serverContainer;
public RaplaAPIPage(RaplaContext context) throws RaplaContextException {
super(context);
serverContainer = context.lookup(ServerServiceContainer.class);
}
Map<String,JsonServlet> servletMap = new HashMap<String, JsonServlet>();
private JsonServlet getJsonServlet(HttpServletRequest request,String serviceAndMethodName) throws RaplaException {
if ( serviceAndMethodName == null || serviceAndMethodName.length() == 0) {
throw new RaplaException("Servicename missing in url");
}
int indexRole = serviceAndMethodName.indexOf( "/" );
String interfaceName;
if ( indexRole > 0 )
{
interfaceName= serviceAndMethodName.substring( 0, indexRole );
if ( serviceAndMethodName.length() >= interfaceName.length())
{
String methodName = serviceAndMethodName.substring( indexRole + 1 );
request.setAttribute(JsonServlet.JSON_METHOD, methodName);
}
}
else
{
interfaceName = serviceAndMethodName;
}
JsonServlet servlet = servletMap.get( interfaceName);
if ( servlet == null)
{
try
{
if (!serverContainer.hasWebservice(interfaceName))
{
throw new RaplaException("Webservice " + interfaceName + " not configured or initialized.");
}
Class<?> interfaceClass = Class.forName(interfaceName, true,RaplaAPIPage.class.getClassLoader());
// Test if service is found
servlet = new JsonServlet(getLogger(), interfaceClass);
}
catch (Exception ex)
{
throw new RaplaException( ex.getMessage(), ex);
}
servletMap.put( interfaceName, servlet);
}
return servlet;
}
public void generatePage(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException
{
String id = request.getParameter("id");
String serviceAndMethodName = getServiceAndMethodName(request);
try
{
JsonServlet servlet;
try
{
servlet = getJsonServlet( request, serviceAndMethodName );
}
catch (RaplaException ex)
{
getLogger().error(ex.getMessage(), ex);
String out = serializeException(id, ex);
RPCServletUtils.writeResponse(servletContext, response, out, false);
return;
}
Class<?> role = servlet.getInterfaceClass();
Object impl;
try
{
impl = serverContainer.createWebservice(role, request);
}
catch (RaplaSecurityException ex)
{
servlet.serviceError(request, response, servletContext, ex);
return;
}
servlet.service(request, response, servletContext, impl);
}
catch ( RaplaSecurityException ex)
{
getLogger().error(ex.getMessage());
}
catch ( RaplaException ex)
{
getLogger().error(ex.getMessage(), ex);
}
}
protected String getServiceAndMethodName(HttpServletRequest request) {
String requestURI =request.getPathInfo();
String path = "/json/";
int rpcIndex=requestURI.indexOf(path) ;
String serviceAndMethodName = requestURI.substring(rpcIndex + path.length()).trim();
return serviceAndMethodName;
}
protected String serializeException(String id, Exception ex)
{
final JsonObject r = new JsonObject();
String versionName = "jsonrpc";
int code = -32603;
r.add(versionName, new JsonPrimitive("2.0"));
if (id != null) {
r.add("id", new JsonPrimitive(id));
}
GsonBuilder gb = JSONParserWrapper.defaultGsonBuilder();
final JsonObject error = JsonServlet.getError(versionName, code, ex, gb);
r.add("error", error);
GsonBuilder builder = JSONParserWrapper.defaultGsonBuilder();
String out = builder.create().toJson( r);
return out;
}
}
| Java |
/*
* AbstractTreeTableModel.java
*
* Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
*
* 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.treetable;
import javax.swing.event.EventListenerList;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreePath;
/**
* @version 1.2 10/27/98
* An abstract implementation of the TreeTableModel interface, handling the list
* of listeners.
* @author Philip Milne
*/
public abstract class AbstractTreeTableModel implements TreeTableModel {
protected Object root;
protected EventListenerList listenerList = new EventListenerList();
public AbstractTreeTableModel(Object root) {
this.root = root;
}
//
// Default implementations for methods in the TreeModel interface.
//
public Object getRoot() {
return root;
}
public boolean isLeaf(Object node) {
return getChildCount(node) == 0;
}
public void valueForPathChanged(TreePath path, Object newValue) {}
// This is not called in the JTree's default mode: use a naive implementation.
public int getIndexOfChild(Object parent, Object child) {
for (int i = 0; i < getChildCount(parent); i++) {
if (getChild(parent, i).equals(child)) {
return i;
}
}
return -1;
}
public void addTreeModelListener(TreeModelListener l) {
listenerList.add(TreeModelListener.class, l);
}
public void removeTreeModelListener(TreeModelListener l) {
listenerList.remove(TreeModelListener.class, l);
}
/*
* Notify all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
* @see EventListenerList
*/
protected void fireTreeNodesChanged(Object source, Object[] path,
int[] childIndices,
Object[] children) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeModelEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeModelListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeModelEvent(source, path,
childIndices, children);
((TreeModelListener)listeners[i+1]).treeNodesChanged(e);
}
}
}
/*
* Notify all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
* @see EventListenerList
*/
protected void fireTreeNodesInserted(Object source, Object[] path,
int[] childIndices,
Object[] children) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeModelEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeModelListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeModelEvent(source, path,
childIndices, children);
((TreeModelListener)listeners[i+1]).treeNodesInserted(e);
}
}
}
/*
* Notify all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
* @see EventListenerList
*/
protected void fireTreeNodesRemoved(Object source, Object[] path,
int[] childIndices,
Object[] children) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeModelEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeModelListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeModelEvent(source, path,
childIndices, children);
((TreeModelListener)listeners[i+1]).treeNodesRemoved(e);
}
}
}
/*
* Notify all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
* @see EventListenerList
*/
protected void fireTreeStructureChanged(Object source, Object[] path,
int[] childIndices,
Object[] children) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeModelEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeModelListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeModelEvent(source, path,
childIndices, children);
((TreeModelListener)listeners[i+1]).treeStructureChanged(e);
}
}
}
//
// Default impelmentations for methods in the TreeTableModel interface.
//
public Class<?> getColumnClass(int column) { return Object.class; }
/** By default, make the column with the Tree in it the only editable one.
* Making this column editable causes the JTable to forward mouse
* and keyboard events in the Tree column to the underlying JTree.
*/
public boolean isCellEditable(Object node, int column) {
return getColumnClass(column) == TreeTableModel.class;
}
public void setValueAt(Object aValue, Object node, int column) {}
// Left to be implemented in the subclass:
/*
* public Object getChild(Object parent, int index)
* public int getChildCount(Object parent)
* public int getColumnCount()
* public String getColumnName(Object node, int column)
* public Object getValueAt(Object node, int column)
*/
}
| 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.treetable;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeSelectionModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
/**
* Original version Philip Milne and Scott Violet
* Modified by Christopher Kohlhaas to support editing and keyboard handling.
*/
public class JTreeTable extends JTable {
private static final long serialVersionUID = 1L;
private RendererTree tree = new RendererTree();
private TreeTableEditor treeCellEditor;
private TableToolTipRenderer toolTipRenderer = null;
private int focusedRow = -1;
private String cachedSearchKey = "";
public JTreeTable(TreeTableModel model) {
super();
setTreeTableModel( model );
// Force the JTable and JTree to share their row selection models.
ListToTreeSelectionModelWrapper selectionWrapper = new
ListToTreeSelectionModelWrapper();
setSelectionModel(selectionWrapper.getListSelectionModel());
setShowGrid( false);
// No intercell spacing
setIntercellSpacing(new Dimension(1, 0));
setShowVerticalLines(true);
tree.setEditable(false);
tree.setSelectionModel(selectionWrapper);
tree.setShowsRootHandles(true);
tree.setRootVisible(false);
setDefaultRenderer( TreeTableModel.class, tree );
setTreeCellEditor(null);
// And update the height of the trees row to match that of
// the table.
if (tree.getRowHeight() < 1) {
// Metal looks better like this.
setRowHeight(22);
}
}
public void setToolTipRenderer(TableToolTipRenderer renderer) {
toolTipRenderer = renderer;
}
public TableToolTipRenderer getToolTipRenderer() {
return toolTipRenderer;
}
public String getToolTipText(MouseEvent evt) {
if (toolTipRenderer == null)
return super.getToolTipText(evt);
Point p = new Point(evt.getX(),evt.getY());
int column = columnAtPoint(p);
int row = rowAtPoint(p);
if (row >=0 && column>=0)
return toolTipRenderer.getToolTipText(this,row,column);
else
return super.getToolTipText(evt);
}
/**
* Overridden to message super and forward the method to the tree.
* Since the tree is not actually in the component hierarchy it will
* never receive this unless we forward it in this manner.
*/
public void updateUI() {
super.updateUI();
if(tree != null) {
tree.updateUI();
}
// Use the tree's default foreground and background colors in the
// table.
LookAndFeel.installColorsAndFont(this, "Tree.background",
"Tree.foreground", "Tree.font");
}
/** Set a custom TreeCellEditor. The default one is a TextField.*/
public void setTreeCellEditor(TreeTableEditor editor) {
treeCellEditor = editor;
setDefaultEditor( TreeTableModel.class, new DelegationgTreeCellEditor(treeCellEditor) );
}
/** Returns the tree that is being shared between the model.
If you set a different TreeCellRenderer for this tree it should
inherit from DefaultTreeCellRenderer. Otherwise the selection-color
and focus color will not be set correctly.
*/
public JTree getTree() {
return tree;
}
/**
* search for given search term in child nodes of selected nodes
* @param search what to search for
* @param parentNode where to search fo
* @return first childnode where its tostring representation in tree starts with search term, null if no one found
*/
private TreeNode getNextTreeNodeMatching(String search, TreeNode parentNode) {
TreeNode result = null;
Enumeration<?> children = parentNode.children();
while (children.hasMoreElements()) {
TreeNode treeNode = (TreeNode) children.nextElement();
String compareS = treeNode.toString().toLowerCase();
if (compareS.startsWith(search)) {
result = treeNode;
break;
}
}
return result;
}
/**
* create treepath from treenode
* @param treeNode Treenode
* @return treepath object
*/
public static TreePath getPath(TreeNode treeNode) {
List<Object> nodes = new ArrayList<Object>();
if (treeNode != null) {
nodes.add(treeNode);
treeNode = treeNode.getParent();
while (treeNode != null) {
nodes.add(0, treeNode);
treeNode = treeNode.getParent();
}
}
return nodes.isEmpty() ? null : new TreePath(nodes.toArray());
}
/** overridden to support keyboard expand/collapse for the tree.*/
protected boolean processKeyBinding(KeyStroke ks,
KeyEvent e,
int condition,
boolean pressed)
{
if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
{
if (tree != null && !isEditing() && getSelectedColumn() == getTreeColumnNumber()) {
if (e.getID() == KeyEvent.KEY_PRESSED)
{
if ( (e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyChar() =='+')) {
int row = getSelectedRow();
if (row >= 0) {
if (tree.isExpanded(row)) {
tree.collapseRow(row);
} else {
tree.expandPath(tree.getPathForRow(row));
}
}
return true;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
int row = getSelectedRow();
if (row >= 0) {
TreePath pathForRow = tree.getPathForRow(row);
// if selected node is expanded than collapse it
// else selected parents node
if (tree.isExpanded(pathForRow)) {
// only if root is visible we should collapse first level
final boolean canCollapse = pathForRow.getPathCount() > (tree.isRootVisible() ? 0 : 1);
if (canCollapse)
tree.collapsePath(pathForRow);
} else {
// only if root is visible we should collapse first level or select parent node
final boolean canCollapse = pathForRow.getPathCount() > (tree.isRootVisible() ? 1 : 2);
if (canCollapse) {
pathForRow = pathForRow.getParentPath();
final int parentRow = tree.getRowForPath(pathForRow );
tree.setSelectionInterval(parentRow, parentRow);
}
}
if (pathForRow != null) {
Rectangle rect = getCellRect(tree.getRowForPath(pathForRow), 0, false);
scrollRectToVisible(rect );
}
}
return true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
int row = getSelectedRow();
if (row >= 0) {
final TreePath path = tree.getPathForRow(row);
if (tree.isCollapsed(path)) {
tree.expandPath(path);
}
}
return true;
}
// live search in current parent node
if ((Character.isLetterOrDigit(e.getKeyChar()))) {
char keyChar = e.getKeyChar();
// we are searching in the current parent node
// first we assume that we have selected a parent node
// so we should have children
TreePath selectedPath = tree.getSelectionModel().getLeadSelectionPath();
TreeNode selectedNode = (TreeNode) selectedPath.getLastPathComponent();
// if we don't have children we might have selected a leaf so choose its parent
if (selectedNode.getChildCount() == 0) {
// set new selectedNode
selectedPath = selectedPath.getParentPath();
selectedNode = (TreeNode) selectedPath.getLastPathComponent();
}
// search term
String search = ("" + keyChar).toLowerCase();
// try to find node with matching searchterm plus the search before
TreeNode nextTreeNodeMatching = getNextTreeNodeMatching(cachedSearchKey + search, selectedNode);
// if we did not find anything, try to find search term only: restart!
if (nextTreeNodeMatching == null) {
nextTreeNodeMatching = getNextTreeNodeMatching(search, selectedNode);
cachedSearchKey = "";
}
// if we found a node, select it, make it visible and return true
if (nextTreeNodeMatching != null) {
TreePath foundPath = getPath(nextTreeNodeMatching);
// select our found path
this.tree.getSelectionModel().setSelectionPath(foundPath);
//make it visible
this.tree.expandPath(foundPath);
this.tree.makeVisible(foundPath);
// Scroll to the found row
int row = tree.getRowForPath( foundPath);
int col = 0;
Rectangle rect = getCellRect(row, col, false);
scrollRectToVisible(rect );
// store found treepath
cachedSearchKey = cachedSearchKey + search;
return true;
}
}
cachedSearchKey = "";
/* Uncomment this if you don't want to start tree-cell-editing
on a non navigation key stroke.
if (e.getKeyCode() != e.VK_TAB && e.getKeyCode() != e.VK_F2
&& e.getKeyCode() != e.VK_DOWN && e.getKeyCode() != e.VK_UP
&& e.getKeyCode() != e.VK_LEFT && e.getKeyCode() != e.VK_RIGHT
&& e.getKeyCode() != e.VK_PAGE_UP && e.getKeyCode() != e.VK_PAGE_DOWN
)
return true;
*/
}
}
}
// reset cachedkey to null if we did not find anything
return super.processKeyBinding(ks,e,condition,pressed);
}
public void setTreeTableModel(TreeTableModel model) {
tree.setModel(model);
super.setModel(new TreeTableModelAdapter(model));
}
/**
* Workaround for BasicTableUI anomaly. Make sure the UI never tries to
* resize the editor. The UI currently uses different techniques to
* paint the renderers and editors; overriding setBounds() below
* is not the right thing to do for an editor. Returning -1 for the
* editing row in this case, ensures the editor is never painted.
*/
public int getEditingRow() {
int column = getEditingColumn();
if( getColumnClass(column) == TreeTableModel.class )
return -1;
return editingRow;
}
/**
* Returns the actual row that is editing as <code>getEditingRow</code>
* will always return -1.
*/
private int realEditingRow() {
return editingRow;
}
/** Overridden to pass the new rowHeight to the tree. */
public void setRowHeight(int rowHeight) {
super.setRowHeight(rowHeight);
if (tree != null && tree.getRowHeight() != rowHeight)
tree.setRowHeight( rowHeight );
}
private int getTreeColumnNumber() {
for (int counter = getColumnCount() - 1; counter >= 0;counter--)
if (getColumnClass(counter) == TreeTableModel.class)
return counter;
return -1;
}
/** <code>isCellEditable</code> returns true for the Tree-Column, even if it is not editable.
<code>isCellRealEditable</code> returns true only if the underlying TreeTableModel-Cell is
editable.
*/
private boolean isCellRealEditable(int row,int column) {
TreePath treePath = tree.getPathForRow(row);
if (treePath == null)
return false;
return (((TreeTableModel)tree.getModel()).isCellEditable(treePath.getLastPathComponent()
,column));
}
class RendererTree extends JTree implements TableCellRenderer {
private static final long serialVersionUID = 1L;
protected int rowToPaint;
Color borderColor = Color.gray;
/** Border to draw around the tree, if this is non-null, it will
* be painted. */
protected Border highlightBorder;
public RendererTree() {
super();
}
public void setRowHeight(int rowHeight) {
if (rowHeight > 0) {
super.setRowHeight(rowHeight);
if (
JTreeTable.this.getRowHeight() != rowHeight) {
JTreeTable.this.setRowHeight(getRowHeight());
}
}
}
// Move and resize the tree to the table position
public void setBounds( int x, int y, int w, int h ) {
super.setBounds( x, 0, w, JTreeTable.this.getHeight() );
}
public void paintEditorBackground(Graphics g,int row) {
tree.rowToPaint = row;
g.translate( 0, -row * getRowHeight());
Rectangle rect = g.getClipBounds();
if (rect.width >0 && rect.height >0)
super.paintComponent(g);
g.translate( 0, row * getRowHeight());
}
// start painting at the rowToPaint
public void paint( Graphics g ) {
int row = rowToPaint;
g.translate( 0, -rowToPaint * getRowHeight() );
super.paint(g);
int x = 0;
TreePath path = getPathForRow(row);
Object value = path.getLastPathComponent();
boolean isSelected = tree.isRowSelected(row);
x = tree.getRowBounds(row).x;
if (treeCellEditor != null) {
x += treeCellEditor.getGap(tree,value,isSelected,row);
} else {
TreeCellRenderer tcr = getCellRenderer();
if (tcr instanceof DefaultTreeCellRenderer) {
DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer)tcr);
// super.paint must have been called before
x += dtcr.getIconTextGap() + dtcr.getIcon().getIconWidth();
}
}
// Draw the Table border if we have focus.
if (highlightBorder != null) {
highlightBorder.paintBorder(this, g, x, rowToPaint *
getRowHeight(), getWidth() -x,
getRowHeight() );
} // Paint the selection rectangle
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row, int column) {
Color background;
Color foreground;
if (hasFocus)
focusedRow = row;
if(isSelected) {
background = table.getSelectionBackground();
foreground = table.getSelectionForeground();
}
else {
background = table.getBackground();
foreground = table.getForeground();
}
highlightBorder = null;
if (realEditingRow() == row && getEditingColumn() == column) {
background = UIManager.getColor("Table.focusCellBackground");
foreground = UIManager.getColor("Table.focusCellForeground");
} else if (hasFocus) {
highlightBorder = UIManager.getBorder
("Table.focusCellHighlightBorder");
if (isCellRealEditable(row,convertColumnIndexToModel(column))) {
background = UIManager.getColor
("Table.focusCellBackground");
foreground = UIManager.getColor
("Table.focusCellForeground");
}
}
this.rowToPaint = row;
setBackground(background);
TreeCellRenderer tcr = getCellRenderer();
if (tcr instanceof DefaultTreeCellRenderer) {
DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer)tcr);
if (isSelected) {
dtcr.setTextSelectionColor(foreground);
dtcr.setBackgroundSelectionColor(background);
}
else {
dtcr.setTextNonSelectionColor(foreground);
dtcr.setBackgroundNonSelectionColor(background);
}
}
return this;
}
}
class DelegationgTreeCellEditor implements TableCellEditor
{
TreeTableEditor delegate;
JComponent lastComp = null;
int textOffset = 0;
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent evt)
{
if (lastComp == null)
return;
if (delegate == null)
return;
if (evt.getY() < 0 || evt.getY()>lastComp.getHeight())
delegate.stopCellEditing();
// User clicked left from the text
if (textOffset > 0 && evt.getX()< textOffset )
delegate.stopCellEditing();
}
};
public DelegationgTreeCellEditor(TreeTableEditor delegate) {
this.delegate = delegate;
}
public void addCellEditorListener(CellEditorListener listener) {
delegate.addCellEditorListener(listener);
}
public void removeCellEditorListener(CellEditorListener listener) {
delegate.removeCellEditorListener(listener);
}
public void cancelCellEditing() {
delegate.cancelCellEditing();
}
public Object getCellEditorValue() {
return delegate.getCellEditorValue();
}
public boolean stopCellEditing() {
return delegate.stopCellEditing();
}
public boolean shouldSelectCell(EventObject anEvent) {
return true;
}
private int getTextOffset(Object value,boolean isSelected,int row) {
int gap = delegate.getGap(tree,value,isSelected,row);
TreePath path = tree.getPathForRow(row);
return tree.getUI().getPathBounds(tree,path).x + gap;
}
public boolean inHitRegion(int x,int y) {
int row = tree.getRowForLocation(x,y);
TreePath path = tree.getPathForRow(row);
if (path == null)
return false;
int gap = (delegate != null) ?
delegate.getGap(tree,null,false,row)
:16;
return (x - gap >= tree.getUI().getPathBounds(tree,path).x || x<0);
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected,
int row,
int column)
{
JTreeTable.this.tree.rowToPaint = row;
JComponent comp = delegate.getEditorComponent(tree,value,isSelected,row);
if (lastComp != comp) {
if (comp != null)
{
comp.removeMouseListener(mouseListener);
comp.addMouseListener(mouseListener);
}
}
lastComp = comp;
textOffset = getTextOffset(value,isSelected,row);
Border outerBorder = new TreeBorder(0, textOffset , 0, 0,row);
Border editBorder = UIManager.getBorder("Tree.editorBorder");
Border border = new CompoundBorder(outerBorder
,editBorder
);
if ( comp != null)
{
comp.setBorder(border);
}
return comp;
}
public boolean isCellEditable( EventObject evt ) {
int col = getTreeColumnNumber();
if( evt instanceof MouseEvent ) {
MouseEvent me = (MouseEvent)evt;
if (col >= 0) {
int xPosRelativeToCell = me.getX() - getCellRect(0, col, true).x;
if (me.getClickCount() > 1
&& inHitRegion(xPosRelativeToCell,me.getY())
&& isCellRealEditable(tree.getRowForLocation(me.getX(),me.getY())
,convertColumnIndexToModel(col)))
return true;
MouseEvent newME = new MouseEvent(tree, me.getID(),
me.getWhen(), me.getModifiers(),
xPosRelativeToCell,
me.getY(), me.getClickCount(),
me.isPopupTrigger());
if (! inHitRegion(xPosRelativeToCell,me.getY()) || me.getClickCount() > 1)
tree.dispatchEvent(newME);
}
return false;
}
if (delegate != null && isCellRealEditable(focusedRow,convertColumnIndexToModel(col)))
return delegate.isCellEditable(evt);
else
return false;
}
}
class TreeBorder implements Border {
int row;
Insets insets;
public TreeBorder(int top,int left,int bottom,int right,int row) {
this.row = row;
insets = new Insets(top,left,bottom,right);
}
public Insets getBorderInsets(Component c) {
return insets;
}
public void paintBorder(Component c,Graphics g,int x,int y,int width,int height) {
Shape originalClip = g.getClip();
g.clipRect(0,0,insets.left -1 ,tree.getHeight());
tree.paintEditorBackground(g,row);
g.setClip(originalClip);
}
public boolean isBorderOpaque() {
return false;
}
}
/**
* ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel
* to listen for changes in the ListSelectionModel it maintains. Once
* a change in the ListSelectionModel happens, the paths are updated
* in the DefaultTreeSelectionModel.
*/
class ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel implements ListSelectionListener{
private static final long serialVersionUID = 1L;
/** Set to true when we are updating the ListSelectionModel. */
protected boolean updatingListSelectionModel;
public ListToTreeSelectionModelWrapper() {
super();
getListSelectionModel().addListSelectionListener
(createListSelectionListener());
}
/**
* Returns the list selection model. ListToTreeSelectionModelWrapper
* listens for changes to this model and updates the selected paths
* accordingly.
*/
ListSelectionModel getListSelectionModel() {
return listSelectionModel;
}
/**
* This is overridden to set <code>updatingListSelectionModel</code>
* and message super. This is the only place DefaultTreeSelectionModel
* alters the ListSelectionModel.
*/
public void resetRowSelection() {
if(!updatingListSelectionModel) {
updatingListSelectionModel = true;
try {
super.resetRowSelection();
}
finally {
updatingListSelectionModel = false;
}
}
// Notice how we don't message super if
// updatingListSelectionModel is true. If
// updatingListSelectionModel is true, it implies the
// ListSelectionModel has already been updated and the
// paths are the only thing that needs to be updated.
}
/**
* Creates and returns an instance of ListSelectionHandler.
*/
protected ListSelectionListener createListSelectionListener() {
return this;
}
/**
* If <code>updatingListSelectionModel</code> is false, this will
* reset the selected paths from the selected rows in the list
* selection model.
*/
protected void updateSelectedPathsFromSelectedRows() {
if(!updatingListSelectionModel) {
updatingListSelectionModel = true;
try {
// This is way expensive, ListSelectionModel needs an
// enumerator for iterating.
int min = listSelectionModel.getMinSelectionIndex();
int max = listSelectionModel.getMaxSelectionIndex();
clearSelection();
if(min != -1 && max != -1) {
for(int counter = min; counter <= max; counter++) {
if(listSelectionModel.isSelectedIndex(counter)) {
TreePath selPath = tree.getPathForRow
(counter);
if(selPath != null) {
addSelectionPath(selPath);
}
}
}
}
} finally {
updatingListSelectionModel = false;
}
}
}
/** Implemention of ListSelectionListener Interface:
* Class responsible for calling updateSelectedPathsFromSelectedRows
* when the selection of the list changse.
*/
public void valueChanged(ListSelectionEvent e) {
updateSelectedPathsFromSelectedRows();
}
}
class TreeTableModelAdapter extends AbstractTableModel implements TreeExpansionListener,TreeModelListener
{
private static final long serialVersionUID = 1L;
TreeTableModel treeTableModel;
public TreeTableModelAdapter(TreeTableModel treeTableModel) {
this.treeTableModel = treeTableModel;
tree.addTreeExpansionListener(this);
// Install a TreeModelListener that can update the table when
// tree changes. We use delayedFireTableDataChanged as we can
// not be guaranteed the tree will have finished processing
// the event before us.
treeTableModel.addTreeModelListener(this);
}
// Implementation of TreeExpansionListener
public void treeExpanded(TreeExpansionEvent event) {
int row = tree.getRowForPath(event.getPath());
if (row + 1 < tree.getRowCount())
fireTableRowsInserted(row + 1,row + 1);
}
public void treeCollapsed(TreeExpansionEvent event) {
int row = tree.getRowForPath(event.getPath());
if (row < getRowCount())
fireTableRowsDeleted(row + 1,row + 1);
}
// Implementation of TreeModelLstener
public void treeNodesChanged(TreeModelEvent e) {
int firstRow = 0;
int lastRow = tree.getRowCount() -1;
delayedFireTableRowsUpdated(firstRow,lastRow);
}
public void treeNodesInserted(TreeModelEvent e) {
delayedFireTableDataChanged();
}
public void treeNodesRemoved(TreeModelEvent e) {
delayedFireTableDataChanged();
}
public void treeStructureChanged(TreeModelEvent e) {
delayedFireTableDataChanged();
}
// Wrappers, implementing TableModel interface.
public int getColumnCount() {
return treeTableModel.getColumnCount();
}
public String getColumnName(int column) {
return treeTableModel.getColumnName(column);
}
public Class<?> getColumnClass(int column) {
return treeTableModel.getColumnClass(column);
}
public int getRowCount() {
return tree.getRowCount();
}
private Object nodeForRow(int row) {
TreePath treePath = tree.getPathForRow(row);
if (treePath == null)
return null;
return treePath.getLastPathComponent();
}
public Object getValueAt(int row, int column) {
Object node = nodeForRow(row);
if (node == null)
return null;
return treeTableModel.getValueAt(node, column);
}
public boolean isCellEditable(int row, int column) {
if (getColumnClass(column) == TreeTableModel.class) {
return true;
} else {
Object node = nodeForRow(row);
if (node == null)
return false;
return treeTableModel.isCellEditable(node, column);
}
}
public void setValueAt(Object value, int row, int column) {
Object node = nodeForRow(row);
if (node == null)
return;
treeTableModel.setValueAt(value, node, column);
}
/**
* Invokes fireTableDataChanged after all the pending events have been
* processed. SwingUtilities.invokeLater is used to handle this.
*/
protected void delayedFireTableRowsUpdated(int firstRow,int lastRow) {
SwingUtilities.invokeLater(new UpdateRunnable(firstRow,lastRow));
}
class UpdateRunnable implements Runnable {
int lastRow;
int firstRow;
UpdateRunnable(int firstRow,int lastRow) {
this.firstRow = firstRow;
this.lastRow = lastRow;
}
public void run() {
fireTableRowsUpdated(firstRow,lastRow);
}
}
/**
* Invokes fireTableDataChanged after all the pending events have been
* processed. SwingUtilities.invokeLater is used to handle this.
*/
protected void delayedFireTableDataChanged() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
fireTableDataChanged();
}
});
}
}
/*
public void paintComponent(Graphics g) {
super.paintComponent( g );
Rectangle r = g.getClipBounds();
g.setColor( Color.white);
g.fillRect(0,0, r.width, r.height );
}
*/
}
| 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.treetable;
import javax.swing.CellEditor;
import javax.swing.JComponent;
import javax.swing.JTree;
public interface TreeTableEditor extends CellEditor {
JComponent getEditorComponent(JTree tree,Object value,boolean isSelected,int row);
int getGap(JTree tree, Object value, boolean isSelected, int row);
}
| 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.treetable;
import javax.swing.JTable;
public interface TableToolTipRenderer {
public String getToolTipText(JTable table, int row, int column);
}
| 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.treetable;
import javax.swing.tree.TreeModel;
/**
* TreeTableModel is the model used by a JTreeTable. It extends TreeModel
* to add methods for getting inforamtion about the set of columns each
* node in the TreeTableModel may have. Each column, like a column in
* a TableModel, has a name and a type associated with it. Each node in
* the TreeTableModel can return a value for each of the columns and
* set that value if isCellEditable() returns true.
*
* @author Philip Milne
* @author Scott Violet
*/
public interface TreeTableModel extends TreeModel
{
/**
* Returns the number ofs available columns.
*/
public int getColumnCount();
/**
* Returns the name for column number <code>column</code>.
*/
public String getColumnName(int column);
/**
* Returns the type for column number <code>column</code>.
* Should return TreeTableModel.class for the tree-column.
*/
public Class<?> getColumnClass(int column);
/**
* Returns the value to be displayed for node <code>node</code>,
* at column number <code>column</code>.
*/
public Object getValueAt(Object node, int column);
/**
* Indicates whether the the value for node <code>node</code>,
* at column number <code>column</code> is editable.
*/
public boolean isCellEditable(Object node, int column);
/**
* Sets the value for node <code>node</code>,
* at column number <code>column</code>.
*/
public void setValueAt(Object aValue, Object node, int column);
}
| 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.xmlbundle;
import java.util.Locale;
import java.util.MissingResourceException;
import javax.swing.ImageIcon;
/** Allows the combination of two resource-bundles.
First the inner bundle will be searched.
If the requested resource was not found the
outer bundle will be searched.
*/
public class CompoundI18n implements I18nBundle {
I18nBundle inner;
I18nBundle outer;
public CompoundI18n(I18nBundle inner,I18nBundle outer) {
this.inner = inner;
this.outer = outer;
}
public String format(String key,Object obj1) {
Object[] array1 = new Object[1];
array1[0] = obj1;
return format(key,array1);
}
public String format(String key,Object obj1,Object obj2) {
Object[] array2 = new Object[2];
array2[0] = obj1;
array2[1] = obj2;
return format(key,array2);
}
@Override
public String format(String key,Object[] obj) {
try {
return inner.format(key, obj);
} catch (MissingResourceException ex) {
return outer.format( key, obj);
}
}
public ImageIcon getIcon(String key) {
try {
return inner.getIcon(key);
} catch (MissingResourceException ex) {
return outer.getIcon(key);
}
}
public String getString(String key) {
try {
return inner.getString(key);
} catch (MissingResourceException ex) {
return outer.getString(key);
}
}
public String getLang() {
return inner.getLang();
}
public Locale getLocale() {
return inner.getLocale();
}
public String getString(String key, Locale locale) {
try {
return inner.getString(key,locale);
} catch (MissingResourceException ex) {
return outer.getString(key, locale);
}
}
}
| 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.xmlbundle;
import java.util.EventListener;
public interface LocaleChangeListener extends EventListener{
void localeChanged(LocaleChangeEvent evt);
}
| Java |
package org.rapla.components.xmlbundle.impl;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.Vector;
public class PropertyResourceBundleWrapper extends ResourceBundle {
private Map<String,Object> lookup;
String name;
static Charset charset = Charset.forName("UTF-8");
@SuppressWarnings({ "unchecked", "rawtypes" })
public PropertyResourceBundleWrapper(InputStream stream,String name) throws IOException {
Properties properties = new Properties();
properties.load(new InputStreamReader(stream, charset));
lookup = new LinkedHashMap(properties);
this.name = name;
}
public String getName()
{
return name;
}
// We make the setParent method public, so that we can use it in I18nImpl
public void setParent(ResourceBundle parent) {
super.setParent(parent);
}
// Implements java.util.ResourceBundle.handleGetObject; inherits javadoc specification.
public Object handleGetObject(String key) {
if (key == null) {
throw new NullPointerException();
}
return lookup.get(key);
}
/**
* Returns an <code>Enumeration</code> of the keys contained in
* this <code>ResourceBundle</code> and its parent bundles.
*
* @return an <code>Enumeration</code> of the keys contained in
* this <code>ResourceBundle</code> and its parent bundles.
* @see #keySet()
*/
public Enumeration<String> getKeys() {
ResourceBundle parent = this.parent;
Set<String> set = new LinkedHashSet<String>(lookup.keySet());
if ( parent != null)
{
set.addAll( parent.keySet());
}
Vector<String> vector = new Vector<String>(set);
Enumeration<String> enum1 = vector.elements();
return enum1;
}
/**
* Returns a <code>Set</code> of the keys contained
* <em>only</em> in this <code>ResourceBundle</code>.
*
* @return a <code>Set</code> of the keys contained only in this
* <code>ResourceBundle</code>
* @since 1.6
* @see #keySet()
*/
protected Set<String> handleKeySet() {
return lookup.keySet();
}
// ==================privates====================
}
| 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.xmlbundle.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.TreeMap;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import org.rapla.components.util.IOUtil;
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.framework.Configuration;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.Disposable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.logger.Logger;
/** The default implementation of the xmlbundle component allows reading from
a compiled ResourceBundle as well as directly from the source-xml-file.
<p>
Sample Configuration 1: (Resources are loaded from the compiled ResourceBundles)
<pre>
<resource-bundle id="org.rapla.RaplaResources"/>
</pre>
</p>
<p>
Sample Configuration 2: (Resources will be loaded directly from the resource-file)
<pre>
<resource-bundle id="org.rapla.plugin.periodwizard.WizardResources">
<file>/home/christopher/Rapla/src/org/rapla/periodwizard/WizardResources.xml</file>
</resource-bundle>
</pre>
</p>
<p>
This class looks for a LocaleSelector on the context and registers itself as
a LocaleChangeListener and switches to the new Locale on a LocaleChangeEvent.
</p>
@see TranslationParser
@see LocaleSelector
*/
public class I18nBundleImpl implements I18nBundle, LocaleChangeListener, Disposable
{
String className;
Locale locale;
Logger logger = null;
LocaleSelectorImpl m_localeSelector;
final String dictionaryFile;
final RaplaDictionary dict;
LinkedHashMap<Locale,LanguagePack> packMap = new LinkedHashMap<Locale,LanguagePack>();
String parentId = null;
class LanguagePack
{
Locale locale;
Map<String,Icon> iconCache = Collections.synchronizedMap( new TreeMap<String,Icon>() );
ResourceBundle resourceBundle;
public String getString( String key ) throws MissingResourceException
{
String lang = locale.getLanguage();
if ( dictionaryFile != null )
{
String lookup = dict.lookup(key, lang);
if ( lookup == null)
{
throw new MissingResourceException("Entry not found for "+ key, dictionaryFile, key);
}
return lookup;
}
DictionaryEntry entry = dict.getEntry(key);
String string;
if ( entry != null)
{
string = entry.get( lang );
if ( string == null )
{
string = resourceBundle.getString( key );
entry.add(lang, key);
}
}
else
{
string = resourceBundle.getString( key );
entry = new DictionaryEntry( key);
entry.add(lang, string);
try {
dict.addEntry( entry);
} catch (UniqueKeyException e) {
// we can ignore it here
}
}
return string;
}
public ImageIcon getIcon( String key ) throws MissingResourceException
{
String iconfile;
try
{
iconfile = getString( key );
}
catch ( MissingResourceException ex )
{
getLogger().debug( ex.getMessage() ); //BJO
throw ex;
}
try
{
ImageIcon icon = (ImageIcon) iconCache.get( iconfile );
if ( icon == null )
{
icon = new ImageIcon( loadResource( iconfile ), key );
iconCache.put( iconfile, icon );
} // end of if ()
return icon;
}
catch ( Exception ex )
{
String message = "Icon " + iconfile + " can't be created: " + ex.getMessage();
getLogger().error( message );
throw new MissingResourceException( message, className, key );
}
}
private final byte[] loadResource( String fileName ) throws IOException
{
return IOUtil.readBytes( getResourceFromFile( fileName ) );
}
private URL getResourceFromFile( String fileName ) throws IOException
{
URL resource = null;
String base;
if ( dictionaryFile == null )
{
if ( resourceBundle == null)
{
throw new IOException("Resource Bundle for locale " + locale + " is missing while looking up " + fileName);
}
if ( resourceBundle instanceof PropertyResourceBundleWrapper)
{
base = ((PropertyResourceBundleWrapper) resourceBundle).getName();
}
else
{
base = resourceBundle.getClass().getName();
}
base = base.substring(0,base.lastIndexOf("."));
base = base.replaceAll("\\.", "/");
String file = "/" + base + "/" + fileName;
resource = I18nBundleImpl.class.getResource( file );
}
else
{
if ( getLogger().isDebugEnabled() )
getLogger().debug( "Looking for resourcefile " + fileName + " in classpath ");
URL resourceBundleURL = getClass().getClassLoader().getResource(dictionaryFile);
if (resourceBundleURL != null)
{
resource = new URL( resourceBundleURL, fileName);
base = resource.getPath();
}
else
{
base = ( new File( dictionaryFile ) ).getParent();
if ( base != null)
{
if ( getLogger().isDebugEnabled() )
getLogger().debug( "Looking for resourcefile " + fileName + " in directory " + base );
File resourceFile = new File( base, fileName );
if ( resourceFile.exists() )
resource = resourceFile.toURI().toURL();
}
}
}
if ( resource == null )
throw new IOException( "File '"
+ fileName
+ "' not found. "
+ " in bundle "
+ className
+ " It must be in the same location as '"
+ base
+ "'" );
return resource;
}
}
/**
* @throws RaplaException when the resource-file is missing or can't be accessed
or can't be parsed
*/
public I18nBundleImpl( RaplaContext context, Configuration config, Logger logger ) throws RaplaException
{
enableLogging( logger );
Locale locale;
m_localeSelector = (LocaleSelectorImpl) context.lookup( LocaleSelector.class ) ;
if ( m_localeSelector != null )
{
m_localeSelector.addLocaleChangeListenerFirst( this );
locale = m_localeSelector.getLocale();
}
else
{
locale = Locale.getDefault();
}
String filePath = config.getChild( "file" ).getValue( null );
try
{
InputStream resource;
if ( filePath == null )
{
className = config.getChild( "classname" ).getValue( null );
if ( className == null )
{
className = config.getAttribute( "id" );
}
else
{
className = className.trim();
}
String resourceFile = "" + className.replaceAll("\\.", "/") + ".xml";
resource = getClass().getClassLoader().getResourceAsStream(resourceFile);
dictionaryFile = resource != null ? resourceFile : null;
}
else
{
File file = new File( filePath);
getLogger().info( "getting lanaguageResources from " + file.getCanonicalPath() );
resource = new FileInputStream( file );
dictionaryFile = filePath;
}
if ( resource != null)
{
dict = new TranslationParser().parse( resource );
resource.close();
}
else
{
dict = new RaplaDictionary(locale.getLanguage());
}
}
catch ( Exception ex )
{
throw new RaplaException( ex );
}
setLocale( locale );
try
{
parentId = getPack(locale).getString( TranslationParser.PARENT_BUNDLE_IDENTIFIER );
}
catch ( MissingResourceException ex )
{
}
}
public String getParentId()
{
return parentId;
}
public static Configuration createConfig( String resourceFile )
{
DefaultConfiguration config = new DefaultConfiguration( "component");
config.setAttribute( "id", resourceFile.toString() );
return config;
}
public void dispose()
{
if ( m_localeSelector != null )
m_localeSelector.removeLocaleChangeListener( this );
}
public void localeChanged( LocaleChangeEvent evt )
{
try
{
setLocale( evt.getLocale() );
}
catch ( Exception ex )
{
getLogger().error( "Can't set new locale " + evt.getLocale(), ex );
}
}
public void enableLogging( Logger logger )
{
this.logger = logger;
}
protected Logger getLogger()
{
return logger;
}
public String format( String key, Object obj1 )
{
Object[] array1 = new Object[1];
array1[0] = obj1;
return format( key, array1 );
}
public String format( String key, Object obj1, Object obj2 )
{
Object[] array2 = new Object[2];
array2[0] = obj1;
array2[1] = obj2;
return format( key, array2 );
}
public String format( String key, Object... obj )
{
MessageFormat msg = new MessageFormat( getString( key ) );
return msg.format( obj );
}
public ImageIcon getIcon( String key ) throws MissingResourceException
{
ImageIcon icon = getPack(getLocale()).getIcon( key);
return icon;
}
public Locale getLocale()
{
if ( locale == null )
throw new IllegalStateException( "Call setLocale first!" );
return locale;
}
public String getLang()
{
if ( locale == null )
throw new IllegalStateException( "Call setLocale first!" );
return locale.getLanguage();
}
public String getString( String key ) throws MissingResourceException
{
if ( locale == null )
throw new IllegalStateException( "Call setLocale first!" );
return getString(key, locale);
}
public String getString( String key, Locale locale) throws MissingResourceException
{
LanguagePack pack = getPack(locale);
return pack.getString(key);
}
// /* replaces XHTML with HTML because swing can't display proper XHTML*/
// String filterXHTML( String text )
// {
// if ( text.indexOf( "<br/>" ) >= 0 )
// {
// return applyXHTMLFilter( text );
// }
// else
// {
// return text;
// } // end of else
// }
// public static String replaceAll( String text, String token, String with )
// {
// StringBuffer buf = new StringBuffer();
// int i = 0;
// int lastpos = 0;
// while ( ( i = text.indexOf( token, lastpos ) ) >= 0 )
// {
// if ( i > 0 )
// buf.append( text.substring( lastpos, i ) );
// buf.append( with );
// i = ( lastpos = i + token.length() );
// } // end of if ()
// buf.append( text.substring( lastpos, text.length() ) );
// return buf.toString();
// }
//
// private String applyXHTMLFilter( String text )
// {
// return replaceAll( text, "<br/>", "<br></br>" );
// }
public void setLocale( Locale locale )
{
this.locale = locale;
getLogger().debug( "Locale changed to " + locale );
try
{
getPack(locale);
}
catch (MissingResourceException ex)
{
getLogger().error(ex.getMessage(), ex);
}
}
private LanguagePack getPack(Locale locale) throws MissingResourceException {
LanguagePack pack = packMap.get(locale);
if (pack != null)
{
return pack;
}
synchronized ( packMap )
{
// again, now with synchronization
pack = packMap.get(locale);
if (pack != null)
{
return pack;
}
pack = new LanguagePack();
pack.locale = locale;
if ( dictionaryFile == null )
{
pack.resourceBundle = new ResourceBundleLoader().loadResourceBundle( className, locale );
}
packMap.put( locale, pack);
return pack;
}
}
}
class ResourceBundleLoader
{
/** this method imitates the orginal
* <code>ResourceBundle.getBundle(String className,Locale
* locale)</code> which causes problems when the locale is changed
* to the base locale (english). For a full description see
* ResourceBundle.getBundle(String className) in the java-api.*/
public ResourceBundle loadResourceBundle( String className, Locale locale ) throws MissingResourceException
{
String tries[] = new String[7];
StringBuffer buf = new StringBuffer();
tries[6] = className;
buf.append( className );
if ( locale.getLanguage().length() > 0 )
{
buf.append( '_' );
buf.append( locale.getLanguage() );
tries[2] = buf.toString();
}
if ( locale.getCountry().length() > 0 )
{
buf.append( '_' );
buf.append( locale.getCountry() );
tries[1] = buf.toString();
}
if ( locale.getVariant().length() > 0 )
{
buf.append( '_' );
buf.append( locale.getVariant() );
tries[0] = buf.toString();
}
buf.delete( className.length(), buf.length() - 1 );
Locale defaultLocale = Locale.getDefault();
if ( defaultLocale.getLanguage().length() > 0 )
{
buf.append( defaultLocale.getLanguage() );
tries[5] = buf.toString();
}
if ( defaultLocale.getCountry().length() > 0 )
{
buf.append( '_' );
buf.append( defaultLocale.getCountry() );
tries[4] = buf.toString();
}
if ( defaultLocale.getVariant().length() > 0 )
{
buf.append( '_' );
buf.append( defaultLocale.getVariant() );
tries[3] = buf.toString();
}
ResourceBundle bundle = null;
for ( int i = 0; i < tries.length; i++ )
{
if ( tries[i] == null )
continue;
bundle = loadBundle( tries[i] );
if ( bundle != null )
{
loadParent( tries, i, bundle );
return bundle;
}
}
throw new MissingResourceException( "'" + className + "' not found. The resource-file is missing.", className,
"" );
}
private ResourceBundle loadBundle( String name )
{
InputStream io = null;
try
{
String pathName = getPropertyFileNameFromClassName( name );
io = this.getClass().getResourceAsStream( pathName );
if ( io != null )
{
return new PropertyResourceBundleWrapper(io , name);
}
ResourceBundle bundle = (ResourceBundle) this.getClass().getClassLoader().loadClass( name ).newInstance();
return bundle;
}
catch ( Exception ex )
{
return null;
}
catch ( ClassFormatError ex )
{
return null;
}
finally
{
if ( io != null)
{
try {
io.close();
} catch (IOException e) {
return null;
}
}
}
}
private void loadParent( String[] tries, int i, ResourceBundle bundle )
{
ResourceBundle parent = null;
if ( i == 0 || i == 3 )
{
parent = loadBundle( tries[i++] );
if ( parent != null )
setParent( bundle, parent );
bundle = parent;
}
if ( i == 1 || i == 4 )
{
parent = loadBundle( tries[i++] );
if ( parent != null )
setParent( bundle, parent );
bundle = parent;
}
if ( i == 2 || i == 5 )
{
parent = loadBundle( tries[6] );
if ( parent != null )
setParent( bundle, parent );
}
}
private void setParent( ResourceBundle bundle, ResourceBundle parent )
{
try
{
Method method = bundle.getClass().getMethod( "setParent", new Class[]
{ ResourceBundle.class } );
method.invoke( bundle, new Object[]
{ parent } );
}
catch ( Exception ex )
{
}
}
private String getPropertyFileNameFromClassName( String classname )
{
StringBuffer result = new StringBuffer( classname );
for ( int i = 0; i < result.length(); i++ )
{
if ( result.charAt( i ) == '.' )
result.setCharAt( i, '/' );
}
result.insert( 0, '/' );
result.append( ".properties" );
return result.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.components.xmlbundle.impl;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
class DictionaryEntry {
String key;
Map<String,String> translations = Collections.synchronizedMap(new TreeMap<String,String>());
public DictionaryEntry(String key) {
this.key = key;
}
public void add(String lang,String value) {
translations.put(lang,value);
}
public String getKey() {
return key;
}
public String get(String lang) {
return translations.get(lang);
}
public String get(String lang,String defaultLang) {
String content = translations.get(lang);
if ( content == null) {
content = translations.get(defaultLang);
} // end of if ()
if ( content == null) {
Iterator<String> it = translations.values().iterator();
content = it.next();
}
return content;
}
public String[] availableLanguages() {
String[] result = new String[translations.keySet().size()];
Iterator<String> it = translations.keySet().iterator();
int i = 0;
while ( it.hasNext()) {
result[i++] = it.next();
}
return result;
}
}
| 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.xmlbundle.impl;
/** thrown by the RaplaDictionary when a duplicated entry is found */
class UniqueKeyException extends Exception {
private static final long serialVersionUID = 1L;
public UniqueKeyException(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.components.xmlbundle.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;
class RaplaDictionary {
Map<String,DictionaryEntry> entries = new TreeMap<String,DictionaryEntry>();
Collection<String> availableLang = new ArrayList<String>();
String defaultLang;
public RaplaDictionary(String defaultLang) {
this.defaultLang = defaultLang;
}
public void addEntry(DictionaryEntry entry) throws UniqueKeyException {
if ( entries.get(entry.getKey()) != null) {
throw new UniqueKeyException("Key '" + entry.getKey() + "' already in map.");
} // end of if ()
String[] lang = entry.availableLanguages();
for ( int i = 0; i<lang.length;i++)
if (!availableLang.contains(lang[i]))
availableLang.add(lang[i]);
entries.put(entry.getKey(),entry);
}
public Collection<DictionaryEntry> getEntries() {
return entries.values();
}
public String getDefaultLang() {
return defaultLang;
}
public String[] getAvailableLanguages() {
return availableLang.toArray(new String[0]);
}
public String lookup(String key,String lang) {
DictionaryEntry entry = getEntry(key);
if ( entry != null) {
return entry.get(lang,defaultLang);
} else {
return null;
} // end of else
}
public DictionaryEntry getEntry(String key) {
return entries.get(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.components.xmlbundle.impl;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import java.util.Vector;
import org.rapla.framework.ConfigurationException;
import org.rapla.framework.logger.ConsoleLogger;
import org.rapla.framework.logger.Logger;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
class ResourceFileGenerator {
public static final String encoding = "UTF-8";
static Logger log = new ConsoleLogger( ConsoleLogger.LEVEL_INFO );
boolean writeProperties = true;
public void transform(RaplaDictionary dict
,String packageName
,String classPrefix
,File destDir
)
throws IOException
{
String[] languages = dict.getAvailableLanguages();
for (String lang:languages) {
String className = classPrefix;
if (!lang.equals(dict.getDefaultLang()))
{
className += "_" + lang;
}
String ending = writeProperties ? ".properties" : ".java";
File file = new File(destDir, className + ending);
PrintWriter w = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),encoding)));
if ( writeProperties)
{
Properties properties = new Properties();
Iterator<DictionaryEntry> it = dict.getEntries().iterator();
while ( it.hasNext()) {
DictionaryEntry entry = it.next();
String key = entry.getKey();
String value = entry.get(lang);
if ( value != null)
{
properties.put(key, value);
}
}
@SuppressWarnings("serial")
Properties temp = new Properties()
{
@SuppressWarnings({ "rawtypes", "unchecked" })
public synchronized Enumeration keys() {
Enumeration<Object> keysEnum = super.keys();
Vector keyList = new Vector<Object>();
while(keysEnum.hasMoreElements()){
keyList.add(keysEnum.nextElement());
}
Collections.sort(keyList);
return keyList.elements();
}
};
temp.putAll( properties);
String comment = packageName + "." + className + "_" + lang;
temp.store(w, comment);
}
else
{
generateJavaHeader(w,packageName);
generateJavaContent(w,dict, className, lang);
}
w.flush();
w.close();
}
}
// public void transformSingleLanguage(RaplaDictionary dict
// ,String packageName
// ,String classPrefix
// ,String lang
// ) {
// String className = classPrefix + "_" + lang;
// w = new PrintWriter(System.out);
// generateHeader(packageName);
// generateContent(dict,className, lang);
// w.flush();
// }
public static String toPackageName(String pathName) {
StringBuffer buf = new StringBuffer();
char[] c =pathName.toCharArray();
for (int i=0;i<c.length;i++) {
if (c[i] == File.separatorChar ) {
if (i>0 && i<c.length-1)
buf.append('.');
} else {
buf.append(c[i]);
}
}
return buf.toString();
}
private void generateJavaHeader(PrintWriter w, String packageName) {
w.println("/*******************************************");
w.println(" * Autogenerated file. Please do not edit. *");
w.println(" * Edit the *Resources.xml file. *");
w.println(" *******************************************/");
w.println();
w.println("package " + packageName + ";");
}
private void generateJavaContent(PrintWriter w, RaplaDictionary dict
,String className
,String lang
)
{
w.println("import java.util.ListResourceBundle;");
w.println("import java.util.ResourceBundle;");
w.println();
w.println("public class " + className + " extends ListResourceBundle {");
w.println(" public Object[][] getContents() { return contents; }");
// We make the setParent method public, so that we can use it in I18nImpl
w.println(" public void setParent(ResourceBundle parent) { super.setParent(parent); }");
w.println(" static final Object[][] contents = { {\"\",\"\"} ");
Iterator<DictionaryEntry> it = dict.getEntries().iterator();
while ( it.hasNext()) {
DictionaryEntry entry = it.next();
String value = entry.get(lang);
if (value != null) {
String content = convertToJava(value);
w.println(" , { \"" + entry.getKey() + "\",\"" + content + "\"}");
}
}
w.println(" };");
w.println("}");
}
static public String byteToHex(byte b) {
// Returns hex String representation of byte b
char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
return new String(array);
}
static public String charToHex(char c) {
// Returns hex String representation of char c
byte hi = (byte) (c >>> 8);
byte lo = (byte) (c & 0xff);
return byteToHex(hi) + byteToHex(lo);
}
private String convertToJava(String text) {
StringBuffer result = new StringBuffer();
for ( int i = 0;i< text.length();i++) {
char c = text.charAt(i);
switch ( c) {
case '\n': // LineBreaks
result.append("\" \n + \"");
break;
case '\\': // \
result.append("\\\\");
break;
case '\"': // "
result.append("\\\"");
break;
default:
if ( c > 127) {
result.append("\\u" + charToHex(c));
} else {
result.append(c);
} // end of else
break;
} // end of switch ()
} // end of for ()
return result.toString();
}
public static final String USAGE = new String( "Usage : \n"
+ "PATH_TO_SOURCES [DESTINATION_PATH]\n"
+ "Example usage under windows:\n"
+ "java -classpath build\\classes "
+ "org.rapla.components.xmlbundle.ResourceFileGenerator "
+ "src \n" );
public static void processDir( String srcDir, String destDir ) throws IOException, SAXException,
ConfigurationException
{
TranslationParser parser = new TranslationParser();
ResourceFileGenerator generator = new ResourceFileGenerator();
Set<String> languages = new HashSet<String>();
Stack<File> stack = new Stack<File>();
File topDir = new File( srcDir );
stack.push( topDir );
while ( !stack.empty() )
{
File file = stack.pop();
if ( file.isDirectory() )
{
// System.out.println("Checking Dir: " + file.getName());
File[] files = file.listFiles();
for ( int i = 0; i < files.length; i++ )
stack.push( files[i] );
}
else
{
// System.out.println("Checking File: " + file.getName());
if ( file.getName().endsWith( "Resources.xml" ) )
{
String absolut = file.getAbsolutePath();
System.out.println( "Transforming source:" + file );
String relativePath = absolut.substring( topDir.getAbsolutePath().length() );
String prefix = file.getName().substring( 0, file.getName().length() - "Resources.xml".length() );
String pathName = relativePath.substring( 0, relativePath.indexOf( file.getName() ) );
RaplaDictionary dict = parser.parse( file.toURI().toURL().toExternalForm() );
File dir = new File( destDir, pathName );
System.out.println( "destination:" + dir );
dir.mkdirs();
String packageName = ResourceFileGenerator.toPackageName( pathName );
generator.transform( dict, packageName, prefix + "Resources", dir );
String[] langs = dict.getAvailableLanguages();
for ( int i = 0; i < langs.length; i++ )
languages.add( langs[i] );
}
}
}
}
public static void main( String[] args )
{
try
{
if ( args.length < 1 )
{
System.out.println( USAGE );
return;
} // end of if ()
String sourceDir = args[0];
String destDir = ( args.length > 1 ) ? args[1] : sourceDir;
processDir( sourceDir, destDir );
}
catch ( SAXParseException ex )
{
log.error( "Line:" + ex.getLineNumber() + " Column:" + ex.getColumnNumber() + " " + ex.getMessage(), ex );
System.exit( 1 );
}
catch ( Throwable e )
{
log.error( e.getMessage(), e );
System.exit( 1 );
}
} // end of main ()
}
| 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.xmlbundle.impl;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.rapla.components.util.Assert;
import org.rapla.components.util.IOUtil;
import org.rapla.components.util.xml.XMLReaderAdapter;
import org.rapla.framework.ConfigurationException;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
/** This class reads *Resources.xml files and generates
the appropriate ResourceBundle java-files.
<pre>
Usage :
org.rapla.components.xmlbundle.TranslationParser PATH_TO_SOURCES [DESTINATION_PATH]
Note: a xml-parser must be on your classpath.
Example usage under windows:
java -classpath lib\saxon.jar;lib\fortress.jar;build\classes org.rapla.components.xmlbundle.TranslationParser src
</pre>
*/
public class TranslationParser extends DefaultHandler
{
RaplaDictionary dict;
DictionaryEntry currentEntry = null;
String currentLang = null;
String defaultLang = null;
String currentIconSrc = null;
int level = 0;
// used to store the nested content in the translation element
StringBuffer charBuffer;
XMLReader xmlReader;
/** The translation parser will add an extra identifer {$i18nbundle_parent$} to
the translation table if a parentbundle is specified.
*/
public final static String PARENT_BUNDLE_IDENTIFIER = "{$i18nbundle_parent$}";
DefaultHandler handler = new DefaultHandler()
{
public InputSource resolveEntity( String publicId, String systemId ) throws SAXException
{
if ( systemId.endsWith( "resources.dtd" ) )
{
try
{
URL resource = getClass().getResource( "/org/rapla/components/xmlbundle/resources.dtd" );
Assert.notNull( resource, "resources.dtd not found on classpath" );
return new InputSource( IOUtil.getInputStream( resource ) );
}
catch ( IOException ex )
{
throw new SAXException( ex );
}
}
else
{
// use the default behaviour
try
{
return super.resolveEntity( publicId, systemId );
}
catch ( SAXException ex )
{
throw ex;
}
catch ( Exception ex )
{
throw new SAXException( ex );
}
}
}
public void startElement( String uri, String name, String qName, Attributes atts ) throws SAXException
{
// if ( log.isDebugEnabled() )
// log.debug( indent() + "Start element: " + qName + "(" + name + ")" );
level:
{
if ( name.equals( "resources" ) )
{
String defaultLang = atts.getValue( "", "default" );
String parentDict = atts.getValue( "", "parent" );
dict = new RaplaDictionary( defaultLang );
if ( parentDict != null && parentDict.trim().length() > 0 )
{
DictionaryEntry entry = new DictionaryEntry( PARENT_BUNDLE_IDENTIFIER );
entry.add( "en", parentDict.trim() );
try
{
dict.addEntry( entry );
}
catch ( UniqueKeyException ex )
{
//first entry must be unique
}
}
break level;
}
if ( name.equals( "entry" ) )
{
String key = atts.getValue( "", "key" );
currentEntry = new DictionaryEntry( key );
break level;
}
if ( name.equals( "text" ) )
{
currentLang = atts.getValue( "", "lang" );
if ( currentLang == null )
currentLang = dict.getDefaultLang();
charBuffer = new StringBuffer();
break level;
}
if ( name.equals( "icon" ) )
{
currentLang = atts.getValue( "", "lang" );
if ( currentLang == null )
currentLang = dict.getDefaultLang();
currentIconSrc = atts.getValue( "", "src" );
charBuffer = new StringBuffer();
break level;
}
// copy startag
if ( charBuffer != null )
{
copyStartTag( name, atts );
}
}
level++;
}
public void endElement( String uri, String name, String qName ) throws SAXException
{
level--;
// if ( log.isDebugEnabled() )
// log.debug( indent() + "End element: " + qName + "(" + name + ")" );
level:
{
if ( name.equals( "icon" ) )
{
if ( currentIconSrc != null )
currentEntry.add( currentLang, currentIconSrc );
break level;
}
if ( name.equals( "text" ) )
{
removeWhiteSpaces( charBuffer );
currentEntry.add( currentLang, charBuffer.toString() );
break level;
}
if ( name.equals( "entry" ) )
{
try
{
dict.addEntry( currentEntry );
}
catch ( UniqueKeyException e )
{
throw new SAXException( e.getMessage() );
} // end of try-catch
currentEntry = null;
break level;
}
// copy endtag
if ( charBuffer != null )
{
copyEndTag( name );
} // end of if ()
}
}
public void characters( char ch[], int start, int length )
{
// copy nested content
if ( charBuffer != null )
{
charBuffer.append( ch, start, length );
} // end of if ()
}
};
TranslationParser() throws ConfigurationException
{
super();
try
{
xmlReader = XMLReaderAdapter.createXMLReader( false );
xmlReader.setContentHandler( handler );
xmlReader.setErrorHandler( handler );
xmlReader.setDTDHandler( handler );
xmlReader.setEntityResolver( handler );
}
catch ( SAXException ex )
{
if ( ex.getException() != null )
{
throw new ConfigurationException( "", ex.getException() );
}
else
{
throw new ConfigurationException( "", ex );
} // end of else
}
}
RaplaDictionary parse( InputStream in ) throws IOException, SAXException
{
dict = null;
xmlReader.parse( new InputSource( in ) );
checkDict();
return dict;
}
RaplaDictionary parse( String systemID ) throws IOException, SAXException
{
dict = null;
xmlReader.parse( systemID );
checkDict();
return dict;
}
private void checkDict() throws IOException
{
if ( dict == null )
{
throw new IOException( "Dictionary file empty " );
}
}
private void copyStartTag( String name, Attributes atts )
{
charBuffer.append( '<' );
charBuffer.append( name );
for ( int i = 0; i < atts.getLength(); i++ )
{
charBuffer.append( ' ' );
charBuffer.append( atts.getLocalName( i ) );
charBuffer.append( '=' );
charBuffer.append( '\"' );
charBuffer.append( atts.getValue( i ) );
charBuffer.append( '\"' );
}
charBuffer.append( '>' );
}
private void copyEndTag( String name )
{
if ( ( charBuffer != null )
&& ( charBuffer.length() > 0 )
&& ( charBuffer.charAt( charBuffer.length() - 1 ) == '>' ) )
{
// <some-tag></some-tag> --> <some-tag/>
charBuffer.insert( charBuffer.length() - 1, "/" );
}
else
{
// </some-tag>
charBuffer.append( "</" + name + ">" );
} // end of else
}
private void removeWhiteSpaces( StringBuffer buf )
{
for ( int i = 1; i < buf.length(); i++ )
{
if ( ( buf.charAt( i ) == ' ' ) && ( buf.charAt( i - 1 ) == ' ' ) )
buf.deleteCharAt( --i );
} // end of for ()
}
/** @deprecated moved to {@link ResourceFileGenerator}*/
@Deprecated
public static void main( String[] args )
{
ResourceFileGenerator.main(args);
}
}
| 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.xmlbundle.impl;
import java.util.Locale;
import java.util.Vector;
import org.rapla.components.xmlbundle.LocaleChangeEvent;
import org.rapla.components.xmlbundle.LocaleChangeListener;
import org.rapla.components.xmlbundle.LocaleSelector;
/** If you want to change the locales during runtime put a LocaleSelector
in the base-context. Instances of {@link I18nBundleImpl} will then register them-self
as {@link LocaleChangeListener LocaleChangeListeners}. Change the locale
with {@link #setLocale} and all bundles will try to load the appropriate resources.
*/
public class LocaleSelectorImpl implements LocaleSelector {
Locale locale;
Vector<LocaleChangeListener> localeChangeListeners = new Vector<LocaleChangeListener>();
public LocaleSelectorImpl() {
locale = Locale.getDefault();
}
public void addLocaleChangeListener(LocaleChangeListener listener) {
localeChangeListeners.add(listener);
}
public void removeLocaleChangeListener(LocaleChangeListener listener) {
localeChangeListeners.remove(listener);
}
public void setLocale(Locale locale) {
this.locale = locale;
fireLocaleChanged();
}
public Locale getLocale() {
return this.locale;
}
public LocaleChangeListener[] getLocaleChangeListeners() {
return localeChangeListeners.toArray(new LocaleChangeListener[]{});
}
public void setLanguage(String language) {
setLocale(new Locale(language,locale.getCountry()));
}
public void setCountry(String country) {
setLocale(new Locale(locale.getLanguage(),country));
}
public String getLanguage() {
return locale.getLanguage();
}
protected void fireLocaleChanged() {
if (localeChangeListeners.size() == 0)
return;
LocaleChangeListener[] listeners = getLocaleChangeListeners();
LocaleChangeEvent evt = new LocaleChangeEvent(this,getLocale());
for (int i=0;i<listeners.length;i++)
listeners[i].localeChanged(evt);
}
/** This Listeners is for the bundles only, it will ensure the bundles are always
notified first.
*/
void addLocaleChangeListenerFirst(LocaleChangeListener listener) {
localeChangeListeners.add(0,listener);
}
}
| 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.xmlbundle;
import java.util.Locale;
/** If you want to change the locales during runtime put a LocaleSelector
in the base-context. Instances of I18nBundle will then register them-self
as {@link LocaleChangeListener LocaleChangeListeners}. Change the locale
with {@link #setLocale} and all bundles will try to load the appropriate resources.
*/
public interface LocaleSelector {
void addLocaleChangeListener(LocaleChangeListener listener);
void removeLocaleChangeListener(LocaleChangeListener listener);
void setLocale(Locale locale);
Locale getLocale();
void setLanguage(String language);
void setCountry(String country);
String getLanguage();
}
| 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.xmlbundle;
import java.util.Locale;
import java.util.MissingResourceException;
import javax.swing.ImageIcon;
/**The interface provides access to a resourcebundle that
can be defined in XML or as an java-object.
Example Usage:
<pre>
I18nBundle i18n = serviceManager.lookup(I18nBundle.class);
i18n.getString("yes"); // will get the translation for yes.
</pre>
*/
public interface I18nBundle {
/** same as </code>format(key,new Object[] {obj1});</code>
@see #format(String,Object[])
*/
String format(String key,Object obj1) throws MissingResourceException;
/** same as </code>format(key,new Object[] {obj1, obj2});</code>
@see #format(String,Object[])
*/
String format(String key,Object obj1,Object obj2) throws MissingResourceException;
/** same as
<code>
(new MessageFormat(getString(key))).format(obj);
</code>
@see java.text.MessageFormat
*/
String format(String key,Object... obj) throws MissingResourceException;
/** returns the specified icon from the image-resource-file.
@throws MissingResourceException if not found or can't be loaded.
*/
ImageIcon getIcon(String key) throws MissingResourceException;
/** returns the specified string from the selected resource-file.
* Same as getString(key,getLocale())
* @throws MissingResourceException if not found or can't be loaded.
*/
String getString(String key) throws MissingResourceException;
/** returns the specified string from the selected resource-file for the specified locale
@throws MissingResourceException if not found or can't be loaded.
*/
String getString( String key, Locale locale);
/** @return the selected language. */
String getLang();
/** @return the selected Locale. */
Locale getLocale();
}
| 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.xmlbundle;
import java.util.EventObject;
import java.util.Locale;
public class LocaleChangeEvent extends EventObject{
private static final long serialVersionUID = 1L;
Locale locale;
public LocaleChangeEvent(Object source,Locale locale) {
super(source);
this.locale = locale;
}
public Locale getLocale() {
return locale;
}
}
| 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;
/** 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.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;
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) 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.FlowLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.TimeZone;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.MenuElement;
import javax.swing.MenuSelectionManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
/** The graphical date-selection field with month and year incerement/decrement buttons.
* @author Christopher Kohlhaas
*/
public class CalendarMenu extends JPanel implements MenuElement {
private static final long serialVersionUID = 1L;
static Color BACKGROUND_COLOR = Color.white;
static Border FOCUSBORDER = new LineBorder(DaySelection.FOCUSCOLOR,1);
static Border EMPTYBORDER = new EmptyBorder(1,1,1,1);
BorderLayout borderLayout1 = new BorderLayout();
JPanel topSelection = new JPanel();
Border border1 = BorderFactory.createEtchedBorder();
BorderLayout borderLayout2 = new BorderLayout();
JPanel monthSelection = new JPanel();
NavButton jPrevMonth = new NavButton('<');
JLabel labelMonth = new JLabel();
NavButton jNextMonth = new NavButton('>');
JPanel yearSelection = new JPanel();
NavButton jPrevYear = new NavButton('<');
JLabel labelYear = new JLabel();
NavButton jNextYear = new NavButton('>');
protected DaySelection daySelection;
JLabel labelCurrentDay = new JLabel();
JButton focusButton = new JButton() {
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
Dimension size = getSize();
g.setColor(getBackground());
g.fillRect(0,0,size.width,size.height);
}
};
DateModel m_model;
DateModel m_focusModel;
String[] m_monthNames;
boolean m_focusable = true;
public CalendarMenu(DateModel newModel) {
m_model = newModel;
m_monthNames = createMonthNames();
m_focusModel = new DateModel(newModel.getLocale(),newModel.getTimeZone());
daySelection = new DaySelection(newModel,m_focusModel);
initGUI();
Listener listener = new Listener();
jPrevMonth.addActionListener(listener);
jPrevMonth.setBorder( null );
jNextMonth.addActionListener(listener);
jNextMonth.setBorder( null );
jPrevYear.addActionListener(listener);
jPrevYear.setBorder( null );
jNextYear.addActionListener(listener);
jNextYear.setBorder( null );
jPrevMonth.setFocusable( false );
jNextMonth.setFocusable( false );
jPrevYear.setFocusable( false );
jNextYear.setFocusable( false );
this.addMouseListener(listener);
jPrevMonth.addMouseListener(listener);
jNextMonth.addMouseListener(listener);
jPrevYear.addMouseListener(listener);
jNextYear.addMouseListener(listener);
labelCurrentDay.addMouseListener(listener);
daySelection.addMouseListener(listener);
labelCurrentDay.addMouseListener(listener);
m_model.addDateChangeListener(listener);
m_focusModel.addDateChangeListener(listener);
focusButton.addKeyListener(listener);
focusButton.addFocusListener(listener);
calculateSizes();
m_focusModel.setDate(m_model.getDate());
}
class Listener implements ActionListener,MouseListener,FocusListener,DateChangeListener,KeyListener {
public void actionPerformed(ActionEvent evt) {
if ( evt.getSource() == jNextMonth) {
m_focusModel.addMonth(1);
} // end of if ()
if ( evt.getSource() == jPrevMonth) {
m_focusModel.addMonth(-1);
} // end of if ()
if ( evt.getSource() == jNextYear) {
m_focusModel.addYear(1);
} // end of if ()
if ( evt.getSource() == jPrevYear) {
m_focusModel.addYear(-1);
} // end of if ()
}
// Implementation of DateChangeListener
public void dateChanged(DateChangeEvent evt) {
if (evt.getSource() == m_model) {
m_focusModel.setDate(evt.getDate());
} else {
updateFields();
}
}
// Implementation of MouseListener
public void mousePressed(MouseEvent me) {
if (me.getSource() == labelCurrentDay) {
// Set the current day as sellected day
m_model.setDate(new Date());
} else {
if (m_focusable && !focusButton.hasFocus())
focusButton.requestFocus();
}
}
public void mouseClicked(MouseEvent me) {
}
public void mouseReleased(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
// Implementation of KeyListener
public void keyPressed(KeyEvent e) {
processCalendarKey(e);
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
// Implementation of FocusListener
public void focusGained(FocusEvent e) {
if (e.getSource() == focusButton)
setBorder(FOCUSBORDER);
else
transferFocus();
}
public void focusLost(FocusEvent e) {
if (e.getSource() == focusButton)
setBorder(EMPTYBORDER);
}
}
private void updateFields() {
labelCurrentDay.setText(m_focusModel.getCurrentDateString());
labelMonth.setText(m_monthNames[m_focusModel.getMonth() -1]);
labelYear.setText(m_focusModel.getYearString());
}
public DateModel getModel() {
return m_model;
}
public boolean hasFocus() {
return focusButton.hasFocus();
}
public boolean isFocusable() {
return m_focusable;
}
public void setFocusable(boolean m_focusable) {
this.m_focusable = m_focusable;
}
// #TODO Property change listener for TimeZone
public void setTimeZone(TimeZone timeZone) {
m_focusModel.setTimeZone(timeZone);
}
public void setFont(Font font) {
super.setFont(font);
// Method called during constructor?
if (labelMonth == null || font == null)
return;
labelMonth.setFont(font);
labelYear.setFont(font);
daySelection.setFont(font);
labelCurrentDay.setFont(font);
calculateSizes();
invalidate();
}
public void requestFocus() {
if (m_focusable)
focusButton.requestFocus();
}
public DaySelection getDaySelection() {
return daySelection;
}
private void calculateSizes() {
// calculate max size of month names
int maxWidth =0;
FontMetrics fm = getFontMetrics(labelMonth.getFont());
for (int i=0;i< m_monthNames.length;i++) {
int len = fm.stringWidth(m_monthNames[i]);
if (len>maxWidth)
maxWidth = len;
}
labelMonth.setPreferredSize(new Dimension(maxWidth,fm.getHeight()));
int h = fm.getHeight();
jPrevMonth.setSize(h,h);
jNextMonth.setSize(h,h);
jPrevYear.setSize(h,h);
jNextYear.setSize(h,h);
// Workaraund for focus-bug in JDK 1.3.1
Border dummyBorder = new EmptyBorder(fm.getHeight(),0,0,0);
focusButton.setBorder(dummyBorder);
}
private void initGUI() {
setBorder(EMPTYBORDER);
topSelection.setLayout(borderLayout2);
topSelection.setBorder(border1);
daySelection.setBackground(BACKGROUND_COLOR);
FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT,0,0);
monthSelection.setLayout(flowLayout);
monthSelection.add(focusButton);
monthSelection.add(jPrevMonth);
monthSelection.add(labelMonth);
monthSelection.add(jNextMonth);
yearSelection.setLayout(flowLayout);
yearSelection.add(jPrevYear);
yearSelection.add(labelYear);
yearSelection.add(jNextYear);
topSelection.add(monthSelection,BorderLayout.WEST);
topSelection.add(yearSelection,BorderLayout.EAST);
setLayout(borderLayout1);
add(topSelection,BorderLayout.NORTH);
add(daySelection,BorderLayout.CENTER);
add(labelCurrentDay,BorderLayout.SOUTH);
}
private String[] createMonthNames( ) {
Calendar calendar = Calendar.getInstance(m_model.getLocale());
calendar.setLenient(true);
Collection<String> monthNames = new ArrayList<String>();
SimpleDateFormat format = new SimpleDateFormat("MMM",m_model.getLocale());
int firstMonth = 0;
int month = 0;
while (true) {
calendar.set(Calendar.DATE,1);
calendar.set(Calendar.MONTH,month);
if (month == 0)
firstMonth = calendar.get(Calendar.MONTH);
else
if (calendar.get(Calendar.MONTH) == firstMonth)
break;
monthNames.add(format.format(calendar.getTime()));
month ++;
}
return monthNames.toArray(new String[0]);
}
private void processCalendarKey(KeyEvent e) {
switch (e.getKeyCode()) {
case (KeyEvent.VK_KP_UP):
case (KeyEvent.VK_UP):
m_focusModel.addDay(-7);
break;
case (KeyEvent.VK_KP_DOWN):
case (KeyEvent.VK_DOWN):
m_focusModel.addDay(7);
break;
case (KeyEvent.VK_KP_LEFT):
case (KeyEvent.VK_LEFT):
m_focusModel.addDay(-1);
break;
case (KeyEvent.VK_KP_RIGHT):
case (KeyEvent.VK_RIGHT):
m_focusModel.addDay(1);
break;
case (KeyEvent.VK_PAGE_DOWN):
m_focusModel.addMonth(1);
break;
case (KeyEvent.VK_PAGE_UP):
m_focusModel.addMonth(-1);
break;
case (KeyEvent.VK_ENTER):
m_model.setDate(m_focusModel.getDate());
break;
case (KeyEvent.VK_SPACE):
m_model.setDate(m_focusModel.getDate());
break;
}
}
// 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) {
if (event.getID() == KeyEvent.KEY_PRESSED)
processCalendarKey(event);
switch (event.getKeyCode()) {
case (KeyEvent.VK_ENTER):
case (KeyEvent.VK_ESCAPE):
manager.clearSelectedPath();
}
event.consume();
}
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;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/** The TimeField only accepts characters that are part of DateFormat.getTimeInstance(DateFormat.SHORT,locale).
* The input blocks are [hour,minute,am_pm] or [hour_of_day,minute]
* depending on the selected locale. You can use the keyboard to
* navigate between the blocks or to increment/decrement the blocks.
* @see AbstractBlockField
*/
final public class TimeField extends AbstractBlockField {
private static final long serialVersionUID = 1L;
private DateFormat m_outputFormat;
private DateFormat m_parsingFormat;
private Calendar m_calendar;
private int m_rank[] = null;
private char[] m_separators;
private boolean m_useAM_PM = false;
private boolean americanAM_PM_character = false;
public TimeField() {
this(Locale.getDefault());
}
public TimeField(Locale locale) {
this(locale, TimeZone.getDefault());
}
public TimeField(Locale locale,TimeZone timeZone) {
super();
m_calendar = Calendar.getInstance(timeZone, locale);
super.setLocale(locale);
setFormat();
setTime(new Date());
}
public void setLocale(Locale locale) {
super.setLocale(locale);
if (locale != null && getTimeZone() != null)
setFormat();
}
private void setFormat() {
m_parsingFormat = DateFormat.getTimeInstance(DateFormat.SHORT, getLocale());
m_parsingFormat.setTimeZone(getTimeZone());
Date oldDate = m_calendar.getTime();
m_calendar.set(Calendar.HOUR_OF_DAY,0);
m_calendar.set(Calendar.MINUTE,0);
String formatStr = m_parsingFormat.format(m_calendar.getTime());
FieldPosition minutePos = new FieldPosition(DateFormat.MINUTE_FIELD);
m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),minutePos);
FieldPosition hourPos = new FieldPosition(DateFormat.HOUR0_FIELD);
StringBuffer hourBuf = new StringBuffer();
m_parsingFormat.format(m_calendar.getTime(), hourBuf,hourPos);
FieldPosition hourPos1 = new FieldPosition(DateFormat.HOUR1_FIELD);
StringBuffer hourBuf1 = new StringBuffer();
m_parsingFormat.format(m_calendar.getTime(), hourBuf1,hourPos1);
FieldPosition amPmPos = new FieldPosition(DateFormat.AM_PM_FIELD);
m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),amPmPos);
String zeroDigit = m_parsingFormat.getNumberFormat().format(0);
int zeroPos = hourBuf.toString().indexOf(zeroDigit,hourPos.getBeginIndex());
// 0:30 or 12:30
boolean zeroBased = (zeroPos == 0);
String testFormat = m_parsingFormat.format( m_calendar.getTime() ).toLowerCase();
int mp = minutePos.getBeginIndex();
int ap = amPmPos.getBeginIndex();
int hp = Math.max( hourPos.getBeginIndex(), hourPos1.getBeginIndex() );
int pos[] = null;
// Use am/pm
if (amPmPos.getEndIndex()>0) {
m_useAM_PM = true;
americanAM_PM_character = m_useAM_PM && (testFormat.indexOf( "am" )>=0 || testFormat.indexOf( "pm" )>=0);
// System.out.println(formatStr + " hour:"+hp+" minute:"+mp+" ampm:"+ap);
if (hp<0 || mp<0 || ap<0 || formatStr == null) {
throw new IllegalArgumentException("Can't parse the time-format for this locale: " + formatStr);
}
// quick and diry sorting
if (mp<hp && hp<ap) {
pos = new int[] {mp,hp,ap};
m_rank = new int[] {Calendar.MINUTE, Calendar.HOUR, Calendar.AM_PM};
} else if (mp<ap && ap<hp) {
pos = new int[] {mp,ap,hp};
m_rank = new int[] {Calendar.MINUTE, Calendar.AM_PM, Calendar.HOUR};
} else if (hp<mp && mp<ap) {
pos = new int[] {hp,mp,ap};
m_rank = new int[] {Calendar.HOUR, Calendar.MINUTE, Calendar.AM_PM};
} else if (hp<ap && ap<mp) {
pos = new int[] {hp,ap,mp};
m_rank = new int[] {Calendar.HOUR, Calendar.AM_PM, Calendar.MINUTE};
} else if (ap<mp && mp<hp) {
pos = new int[] {ap,mp,hp};
m_rank = new int[] {Calendar.AM_PM, Calendar.MINUTE, Calendar.HOUR};
} else if (ap<hp && hp<mp) {
pos = new int[] {ap,hp,mp};
m_rank = new int[] {Calendar.AM_PM, Calendar.HOUR, Calendar.MINUTE};
}
else
{
throw new IllegalStateException("Ordering am=" +ap + " h=" +hp + " m="+mp +" not supported");
}
char firstSeparator = formatStr.charAt(pos[1]-1);
char secondSeparator = formatStr.charAt(pos[2]-1);
if (Character.isDigit(firstSeparator)
|| Character.isDigit(secondSeparator))
throw new IllegalArgumentException("Can't parse the time-format for this locale: " + formatStr);
m_separators = new char[] {firstSeparator,secondSeparator};
StringBuffer buf = new StringBuffer();
for (int i=0;i<m_rank.length;i++) {
if (m_rank[i] == Calendar.HOUR) {
if (zeroBased)
buf.append("KK");
else
buf.append("hh");
} else if (m_rank[i] == Calendar.MINUTE) {
buf.append("mm");
} else if (m_rank[i] == Calendar.AM_PM) {
buf.append("a");
}
if (i==0 && americanAM_PM_character) {
buf.append(firstSeparator);
} else if (i==1) {
buf.append(secondSeparator);
}
}
m_outputFormat= new SimpleDateFormat(buf.toString(), getLocale());
m_outputFormat.setTimeZone(getTimeZone());
setColumns(7);
// Don't use am/pm
} else {
m_useAM_PM = false;
// System.out.println(formatStr + " hour:"+hp+" minute:" + mp);
if (hp<0 || mp<0) {
throw new IllegalArgumentException("Can't parse the time-format for this locale");
}
// quick and diry sorting
if (mp<hp) {
pos = new int[] {mp,hp};
m_rank = new int[] {Calendar.MINUTE, Calendar.HOUR_OF_DAY};
} else {
pos = new int[] {hp,mp};
m_rank = new int[] {Calendar.HOUR_OF_DAY, Calendar.MINUTE};
}
char firstSeparator = formatStr.charAt(pos[1]-1);
if (Character.isDigit(firstSeparator))
throw new IllegalArgumentException("Can't parse the time-format for this locale");
m_separators = new char[] {firstSeparator};
StringBuffer buf = new StringBuffer();
for (int i=0;i<m_rank.length;i++) {
if (m_rank[i] == Calendar.HOUR_OF_DAY) {
if (zeroBased)
buf.append("HH");
else
buf.append("kk");
} else if (m_rank[i] == Calendar.MINUTE) {
buf.append("mm");
} else if (m_rank[i] == Calendar.AM_PM) {
buf.append("a");
}
if (i==0) {
buf.append(firstSeparator);
}
}
m_outputFormat= new SimpleDateFormat(buf.toString(), getLocale());
m_outputFormat.setTimeZone(getTimeZone());
setColumns(5);
}
m_calendar.setTime(oldDate);
}
public TimeZone getTimeZone() {
if (m_calendar != null)
return m_calendar.getTimeZone();
return
null;
}
/** returns the parsingFormat of the selected locale.
This is same as the default time-format of the selected locale.*/
public DateFormat getParsingFormat() {
return m_parsingFormat;
}
/** returns the output format of the date-field.
The outputFormat always uses the full block size:
01:02 instead of 1:02 */
public DateFormat getOutputFormat() {
return m_outputFormat;
}
private void update(TimeZone timeZone, Locale locale) {
Date date = getTime();
m_calendar = Calendar.getInstance(timeZone, locale);
setFormat();
setText(m_outputFormat.format(date));
}
public void setTimeZone(TimeZone timeZone) {
update(timeZone, getLocale());
}
public Date getTime() {
return m_calendar.getTime();
}
public void setTime(Date value) {
m_calendar.setTime(value);
setText(m_outputFormat.format(value));
}
protected char[] getSeparators() {
return m_separators;
}
protected boolean isSeparator(char c) {
for (int i=0;i<m_separators.length;i++)
if (m_separators[i] == c)
return true;
return false;
}
protected void changeSelectedBlock(int[] blocks,int block,String selected,int count) {
int type = m_rank[block];
if (m_rank.length<block)
return;
if (type == Calendar.AM_PM) {
m_calendar.roll(Calendar.HOUR_OF_DAY,12);
} else if (type == Calendar.MINUTE) {
m_calendar.add(type,count);
} else {
if (Math.abs(count) == 10)
m_calendar.add(type,count/Math.abs(count) * 12);
else
m_calendar.add(type,count/Math.abs(count));
}
setTime(m_calendar.getTime());
calcBlocks(blocks);
markBlock(blocks,block);
}
public boolean blocksValid() {
try {
m_calendar.setTime(m_parsingFormat.parse(getText()));
return true;
} catch (ParseException e) {
return false;
}
}
static int[] BLOCKLENGTH1 = new int[] {2,2,2};
static int[] BLOCKLENGTH2 = new int[] {2,2};
protected int blockCount() {
return m_useAM_PM ? BLOCKLENGTH1.length : BLOCKLENGTH2.length;
}
protected int maxBlockLength(int block) {
return m_useAM_PM ? BLOCKLENGTH1[block] : BLOCKLENGTH2[block];
}
protected boolean isValidChar(char c) {
return (Character.isDigit(c)
|| isSeparator(c)
|| ((m_useAM_PM) &&
((americanAM_PM_character && (c == 'a' || c=='A' || c=='p' || c=='P' || c=='m' || c=='M'))
|| (!americanAM_PM_character && Character.isLetter( 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.Polygon;
/*
The following classes are only responsible to paint the Arrows for the NavButton.
*/
class ArrowPolygon extends Polygon {
private static final long serialVersionUID = 1L;
public ArrowPolygon(char type,int width) {
this(type,width,true);
}
public ArrowPolygon(char type,int width,boolean border) {
int polyWidth = ((width - 7) / 8);
polyWidth = (polyWidth + 1) * 8;
int dif = border ? (width - polyWidth) /2 : 0;
int half = polyWidth / 2 + dif;
int insets = (polyWidth == 8) ? 0 : polyWidth / 4;
int start = insets + dif;
int full = polyWidth - insets + dif;
int size = (polyWidth == 8) ? polyWidth / 4 : polyWidth / 8;
if ( type == '>') {
addPoint(half - size,start);
addPoint(half + size,half);
addPoint(half - size,full);
} // end of if ()
if ( type == '<') {
addPoint(half + size,start);
addPoint(half - size,half);
addPoint(half + size,full);
} // end of if ()
if ( type == '^') {
addPoint(start,half + size);
addPoint(half,half - size);
addPoint(full,half + size);
} // end of if ()
if ( type == 'v') {
addPoint(start,half - size);
addPoint(half,half + size);
addPoint(full,half - size);
} // end of if ()
if ( type == '-') {
addPoint(start + 1,half - 1);
addPoint(full - 3,half - 1);
} // end of if ()
if ( type == '+') {
addPoint(start + 1,half - 1);
addPoint(full - 3,half - 1);
addPoint(half -1,half - 1);
addPoint(half- 1, half - (size + 1));
addPoint(half -1,half + ( size -1));
addPoint(half -1,half - 1);
} // end of if ()
}
}
| 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.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.MouseEvent;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.rapla.components.calendar.DateRenderer.RenderingInfo;
/** The DateField only accepts characters that are part of
* DateFormat.getDateInstance(DateFormat.SHORT,locale). The
* inputblocks are [date,month,year]. The order of the input-blocks is
* determined by the locale. You can use the keyboard to navigate
* between the blocks or to increment/decrement the blocks.
* @see AbstractBlockField
*/
final public class DateField extends AbstractBlockField {
private static final long serialVersionUID = 1L;
private DateFormat m_outputFormat;
private DateFormat m_parsingFormat;
private Calendar m_calendar;
private int m_rank[] = null;
private char[] m_separators;
private SimpleDateFormat m_weekdayFormat;
private boolean m_weekdaysVisible = true;
private DateRenderer m_dateRenderer;
/** stores the y-coordinate of the weekdays display field*/
private int m_weekdaysX;
private boolean nullValuePossible;
private boolean nullValue;
RenderingInfo renderingInfo;
public boolean isNullValue() {
return nullValue;
}
public void setNullValue(boolean nullValue) {
this.nullValue = nullValue;
}
public boolean isNullValuePossible()
{
return nullValuePossible;
}
public void setNullValuePossible(boolean nullValuePossible)
{
this.nullValuePossible = nullValuePossible;
}
public DateField() {
this(Locale.getDefault(),TimeZone.getDefault());
}
public DateField(Locale locale,TimeZone timeZone) {
super();
m_calendar = Calendar.getInstance(timeZone, locale);
super.setLocale(locale);
setFormat();
setDate(new Date());
}
/** you can choose, if weekdays should be displayed in the right corner of the DateField.
Default is true.
*/
public void setWeekdaysVisible(boolean m_weekdaysVisible) {
this.m_weekdaysVisible = m_weekdaysVisible;
}
/** sets the DateRenderer for the calendar */
public void setDateRenderer(DateRenderer dateRenderer) {
m_dateRenderer = dateRenderer;
}
private void setFormat() {
m_parsingFormat = DateFormat.getDateInstance(DateFormat.SHORT, getLocale());
m_weekdayFormat = new SimpleDateFormat("EE", getLocale());
TimeZone timeZone = getTimeZone();
m_parsingFormat.setTimeZone(timeZone);
m_weekdayFormat.setTimeZone(timeZone);
String formatStr = m_parsingFormat.format(m_calendar.getTime());
FieldPosition datePos = new FieldPosition(DateFormat.DATE_FIELD);
FieldPosition monthPos = new FieldPosition(DateFormat.MONTH_FIELD);
FieldPosition yearPos = new FieldPosition(DateFormat.YEAR_FIELD);
m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),datePos);
m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),monthPos);
m_parsingFormat.format(m_calendar.getTime(), new StringBuffer(),yearPos);
int mp = monthPos.getBeginIndex();
int dp = datePos.getBeginIndex();
int yp = yearPos.getBeginIndex();
int pos[] = null;
// System.out.println(formatStr + " day:"+dp+" month:"+mp+" year:"+yp);
if (mp<0 || dp<0 || yp<0) {
throw new IllegalArgumentException("Can't parse the date-format for this locale");
}
// quick and diry sorting
if (dp<mp && mp<yp) {
pos = new int[] {dp,mp,yp};
m_rank = new int[] {Calendar.DATE, Calendar.MONTH, Calendar.YEAR};
} else if (dp<yp && yp<mp) {
pos = new int[] {dp,yp,mp};
m_rank = new int[] {Calendar.DATE, Calendar.YEAR, Calendar.MONTH};
} else if (mp<dp && dp<yp) {
pos = new int[] {mp,dp,yp};
m_rank = new int[] {Calendar.MONTH, Calendar.DATE, Calendar.YEAR};
} else if (mp<yp && yp<dp) {
pos = new int[] {mp,yp,dp};
m_rank = new int[] {Calendar.MONTH, Calendar.YEAR, Calendar.DATE};
} else if (yp<dp && dp<mp) {
pos = new int[] {yp,dp,mp};
m_rank = new int[] {Calendar.YEAR, Calendar.DATE, Calendar.MONTH};
} else if (yp<mp && mp<dp) {
pos = new int[] {yp,mp,dp};
m_rank = new int[] {Calendar.YEAR, Calendar.MONTH, Calendar.DATE};
} else {
throw new IllegalStateException("Ordering y=" +yp + " d=" +dp + " m="+mp +" not supported");
}
char firstSeparator = formatStr.charAt(pos[1]-1);
char secondSeparator = formatStr.charAt(pos[2]-1);
// System.out.println("first-sep:"+firstSeparator+" sec-sep:"+secondSeparator);
if (Character.isDigit(firstSeparator)
|| Character.isDigit(secondSeparator))
throw new IllegalArgumentException("Can't parse the date-format for this locale");
m_separators = new char[] {firstSeparator,secondSeparator};
StringBuffer buf = new StringBuffer();
for (int i=0;i<m_rank.length;i++) {
if (m_rank[i] == Calendar.YEAR) {
buf.append("yyyy");
} else if (m_rank[i] == Calendar.MONTH) {
buf.append("MM");
} else if (m_rank[i] == Calendar.DATE) {
buf.append("dd");
}
if (i==0) {
buf.append(firstSeparator);
} else if (i==1) {
buf.append(secondSeparator);
}
}
setColumns(buf.length() -1 + (m_weekdaysVisible ? 1:0 ));
m_outputFormat= new SimpleDateFormat(buf.toString(),getLocale());
m_outputFormat.setTimeZone(timeZone);
}
public TimeZone getTimeZone() {
if (m_calendar != null)
return m_calendar.getTimeZone();
return
null;
}
public Date getDate()
{
if ( nullValue && nullValuePossible)
{
return null;
}
Date date = m_calendar.getTime();
return date;
}
public void setDate(Date value)
{
if ( value == null)
{
if ( !nullValuePossible)
{
return;
}
}
nullValue = value == null;
if ( !nullValue)
{
m_calendar.setTime(value);
if (m_dateRenderer != null) {
renderingInfo = m_dateRenderer.getRenderingInfo(
m_calendar.get(Calendar.DAY_OF_WEEK)
,m_calendar.get(Calendar.DATE)
,m_calendar.get(Calendar.MONTH) + 1
,m_calendar.get(Calendar.YEAR)
);
String text = renderingInfo.getTooltipText();
setToolTipText(text);
}
String formatedDate = m_outputFormat.format(value);
setText(formatedDate);
}
else
{
setText("");
}
}
protected char[] getSeparators() {
return m_separators;
}
protected boolean isSeparator(char c) {
for (int i=0;i<m_separators.length;i++)
if (m_separators[i] == c)
return true;
return false;
}
/** returns the parsingFormat of the selected locale.
This is same as the default date-format of the selected locale.*/
public DateFormat getParsingFormat() {
return m_parsingFormat;
}
/** returns the output format of the date-field.
The OutputFormat always uses the full block size:
01.01.2000 instead of 1.1.2000 */
public DateFormat getOutputFormat() {
return m_outputFormat;
}
protected void changeSelectedBlock(int[] blocks,int block,String selected,int count) {
int type = m_rank[block];
if (m_rank.length<block)
return;
if (type == Calendar.MONTH)
if (Math.abs(count) == 10)
m_calendar.add(type,count/Math.abs(count) * 3);
else
m_calendar.add(type,count/Math.abs(count));
else if (type == Calendar.DATE)
if (Math.abs(count) == 10)
m_calendar.add(type,count/Math.abs(count) * 7);
else
m_calendar.add(type,count/Math.abs(count));
else
m_calendar.add(type,count);
setDate(m_calendar.getTime());
calcBlocks(blocks);
markBlock(blocks,block);
}
public String getToolTipText(MouseEvent event) {
if (m_weekdaysVisible && event.getX() >= m_weekdaysX)
return super.getToolTipText(event);
return null;
}
public boolean blocksValid() {
String dateTxt = null;
try {
dateTxt = getText();
if ( isNullValuePossible() && dateTxt.length() == 0)
{
nullValue = true;
return true;
}
m_calendar.setTime(m_parsingFormat.parse(dateTxt));
nullValue = false;
return true;
} catch (ParseException e) {
return false;
}
}
static int[] BLOCKLENGTH = new int[] {2,2,5};
protected int blockCount() {
return BLOCKLENGTH.length;
}
protected void mark(int dot,int mark) {
super.mark(dot,mark);
if (!m_weekdaysVisible)
repaint();
}
protected int maxBlockLength(int block) {
return BLOCKLENGTH[block];
}
protected boolean isValidChar(char c) {
return (Character.isDigit(c) || isSeparator(c) );
}
/** 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));
}
public void paint(Graphics g) {
super.paint(g);
if (!m_weekdaysVisible)
return;
Insets insets = getInsets();
final String format = nullValue ? "" :m_weekdayFormat.format(m_calendar.getTime());
String s = small(format);
FontMetrics fm = g.getFontMetrics();
int width = fm.stringWidth(s);
int x = getWidth()-width-insets.right-3;
m_weekdaysX = x;
int y = insets.top + (getHeight() - (insets.bottom + insets.top))/2 + fm.getAscent()/3;
g.setColor(Color.gray);
if (renderingInfo != null) {
Color color = renderingInfo.getBackgroundColor();
if (color != null) {
g.setColor(color);
g.fillRect(x-1, insets.top, width + 3 , getHeight() - insets.bottom - insets.top - 1);
}
color = renderingInfo.getForegroundColor();
if (color != null) {
g.setColor(color);
}
else
{
g.setColor(Color.GRAY);
}
}
g.drawString(s,x,y);
}
}
| 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.Component;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.util.ArrayList;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
/** The base class for TextFields that supports entering values in
blocks. Most notifiably the DateField and the TimeField. <br> You
can use the left/right arrow keys to switch the blocks. Use of the
top/down arrow keys will increase/decrease the values in the
selected block (page_up/page_down for major changes). You can
specify maximum length for each block. If a block reaches this
maximum value the focus will switch to the next block.
@see DateField
@see TimeField
*/
public abstract class AbstractBlockField extends JTextField {
private static final long serialVersionUID = 1L;
int m_markedBlock = 0;
char m_lastChar = 0;
boolean m_keyPressed = false;
protected String m_oldText;
ArrayList<ChangeListener> m_listenerList = new ArrayList<ChangeListener>();
public AbstractBlockField() {
Listener listener = new Listener();
addMouseListener(listener);
addActionListener(listener);
addFocusListener(listener);
addKeyListener(listener);
addMouseWheelListener( listener );
setInputVerifier(new InputVerifier() {
public boolean verify(JComponent comp) {
boolean valid = blocksValid();
if ( valid )
{
fireValueChanged();
}
return valid;
}
});
}
class Listener implements MouseListener,KeyListener,FocusListener,ActionListener, MouseWheelListener {
public void mouseReleased(MouseEvent evt) {
}
public void mousePressed(MouseEvent evt) {
if ( !isMouseOverComponent())
{
blocksValid();
fireValueChanged();
}
if ( evt.getButton() != MouseEvent.BUTTON1)
{
return;
}
// We have to mark the block on mouse pressed and mouse clicked.
// Windows needs mouse clicked while Linux needs mouse pressed.
markCurrentBlock();
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
blocksValid();
fireValueChanged();
}
public void mouseClicked(MouseEvent evt) {
if ( evt.getButton() != MouseEvent.BUTTON1)
{
return;
}
// We have to mark the block on mouse pressed and mouse clicked.
markCurrentBlock();
if (evt.getClickCount()>1) {
selectAll();
return;
}
if (blocksValid()) {
fireValueChanged();
}
}
// Implementation of ActionListener
public void actionPerformed(ActionEvent e) {
blocksValid();
fireValueChanged();
}
public void focusGained(FocusEvent evt) {
if (blocksValid()) {
//setBlock(0);
}
}
public void focusLost(FocusEvent evt) {
//select(-1,-1);
blocksValid();
fireValueChanged();
}
public void keyPressed(KeyEvent evt) {
m_keyPressed = true;
m_lastChar=evt.getKeyChar();
if (!blocksValid())
return;
if (isSeparator(evt.getKeyChar())) {
evt.consume();
return;
}
switch (evt.getKeyCode()) {
case KeyEvent.VK_LEFT:
case KeyEvent.VK_KP_LEFT:
if (blockCount() >1) {
setBlock(-1);
evt.consume();
}
return;
case KeyEvent.VK_KP_RIGHT:
case KeyEvent.VK_RIGHT:
if (blockCount() >1) {
setBlock(1);
evt.consume();
}
return;
case KeyEvent.VK_HOME:
setBlock(-1000);
evt.consume();
return;
case KeyEvent.VK_END:
setBlock(1000);
evt.consume();
return;
case KeyEvent.VK_KP_UP:
case KeyEvent.VK_UP:
changeSelectedBlock(1);
evt.consume();
return;
case KeyEvent.VK_KP_DOWN:
case KeyEvent.VK_DOWN:
changeSelectedBlock(-1);
evt.consume();
return;
case KeyEvent.VK_PAGE_UP:
changeSelectedBlock(10);
evt.consume();
return;
case KeyEvent.VK_PAGE_DOWN:
changeSelectedBlock(-10);
evt.consume();
return;
}
}
public void keyReleased(KeyEvent evt) {
m_lastChar=evt.getKeyChar();
// Only change the block if the keyReleased
// event follows a keyPressed.
// If you type very quickly you could
// get two strunged keyReleased events
if (m_keyPressed == true)
m_keyPressed = false;
else
return;
if (!blocksValid())
return;
if (isSeparator(m_lastChar) ) {
if ( isSeparator( getText().charAt(getCaretPosition())))
nextBlock();
evt.consume();
} else if (isValidChar(m_lastChar)) {
advance();
evt.consume();
if (blocksValid() && !isMouseOverComponent())
{
// fireValueChanged();
}
}
}
private boolean isMouseOverComponent()
{
Component comp = AbstractBlockField.this;
Point compLoc = comp.getLocationOnScreen();
Point mouseLoc = MouseInfo.getPointerInfo().getLocation();
boolean result = (mouseLoc.x >= compLoc.x && mouseLoc.x <= compLoc.x + comp.getWidth()
&& mouseLoc.y >= compLoc.y && mouseLoc.y <= compLoc.y + comp.getHeight());
return result;
}
public void keyTyped(KeyEvent evt) {
}
public void mouseWheelMoved(MouseWheelEvent e) {
if (!hasFocus())
{
return;
}
if (!blocksValid() || e == null)
return;
int count = e.getWheelRotation();
changeSelectedBlock(-1 * count/(Math.abs(count)));
}
}
private void markCurrentBlock() {
if (!blocksValid()) {
return;
}
int blockstart[] = new int[blockCount()];
int block = calcBlocks(blockstart);
markBlock(blockstart,block);
}
public void addChangeListener(ChangeListener listener) {
m_listenerList.add(listener);
}
/** removes a listener from this component.*/
public void removeChangeListener(ChangeListener listener) {
m_listenerList.remove(listener);
}
public ChangeListener[] getChangeListeners() {
return m_listenerList.toArray(new ChangeListener[]{});
}
/** A ChangeEvent will be fired to every registered ActionListener
* when the value has changed.
*/
protected void fireValueChanged() {
if (m_listenerList.size() == 0)
return;
// Only fire, when text has changed.
if (m_oldText != null && m_oldText.equals(getText()))
return;
m_oldText = getText();
ChangeEvent evt = new ChangeEvent(this);
ChangeListener[] listeners = getChangeListeners();
for (int i = 0; i<listeners.length; i ++) {
listeners[i].stateChanged(evt);
}
}
// switch to next block
private void nextBlock() {
int[] blockstart = new int[blockCount()];
int block = calcBlocks(blockstart);
markBlock(blockstart,Math.min(block + 1,blockCount() -1));
}
// switch to next block if blockend is reached and
private void advance() {
if (blockCount()<2)
return;
int blockstart[] = new int[blockCount()];
int block = calcBlocks(blockstart);
if (block >= blockCount() -1)
return;
int selectedLen = (block ==0) ? blockstart[1] : (blockstart[block + 1] - blockstart[block] - 1);
if (selectedLen == maxBlockLength(block)) {
markBlock(blockstart,Math.min(block + 1,blockCount() -1));
}
}
/** changes the value of the selected Block. Adds the count value. */
private void changeSelectedBlock(int count) {
int blockstart[] = new int[blockCount()];
int block = calcBlocks(blockstart);
int start = (block == 0) ? 0 : blockstart[block] + 1;
int end = (block == blockCount() -1) ? getText().length() : blockstart[block+1];
String selected = getText().substring(start,end);
markBlock(blockstart,block);
changeSelectedBlock(blockstart,block,selected,count);
}
private void setBlock(int count) {
if (blockCount()<1)
return;
int blockstart[] = new int[blockCount()];
int block = calcBlocks(blockstart);
if (count !=0)
markBlock(blockstart,Math.min(Math.max(0,block + count),blockCount()-1));
else
markBlock(blockstart,m_markedBlock);
}
/** Select the specified block. */
final protected void markBlock(int[] blockstart,int block) {
m_markedBlock = block;
if (m_markedBlock == 0)
mark(blockstart[0], (blockCount()>1) ? blockstart[1] : getText().length());
else if (m_markedBlock==blockCount()-1)
mark(blockstart[m_markedBlock] + 1,getText().length());
else
mark(blockstart[m_markedBlock] + 1,blockstart[m_markedBlock+1]);
}
private boolean isPrevSeparator(int i,char[] source,String currentText,int offs) {
return (i>0 && isSeparator(source[i-1])
|| (offs > 0 && isSeparator(currentText.charAt(offs-1))));
}
private boolean isNextSeparator(String currentText,int offs) {
return (offs < currentText.length()-1 && isSeparator(currentText.charAt(offs)));
}
class DateDocument extends PlainDocument {
private static final long serialVersionUID = 1L;
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
String currentText = getText(0, getLength());
char[] source = str.toCharArray();
char[] result = new char[source.length];
int j = 0;
boolean bShouldBeep = false;
for (int i = 0; i < source.length; i++) {
boolean bValid = true;
if (!isValidChar(source[i])) {
bValid = false;
} else {
//if (offs < currentText.length()-1)
//System.out.println("offset-char: " + currentText.charAt(offs));
//
if (isSeparator(source[i]))
if (isNextSeparator(currentText,offs)
|| isPrevSeparator(i,source,currentText,offs)
|| (i==0 && offs==0)
|| (i==source.length && offs==currentText.length())
)
{
// beep();
continue;
}
}
if (bValid)
result[j++] = source[i];
else
bShouldBeep = true;
}
if (bShouldBeep)
beep();
super.insertString(offs, new String(result, 0, j), a);
}
public void remove(int offs, int len)
throws BadLocationException {
if (m_lastChar == 0
|| (!isSeparator(m_lastChar)
&& (isValidChar(m_lastChar)
|| !Character.isLetter(m_lastChar))
)
)
super.remove(offs, len);
}
}
final protected Document createDefaultModel() {
return new DateDocument();
}
/** Calculate the blocks. The new blockstarts will be stored in
the int array.
@return the block that contains the caret.
*/
protected int calcBlocks(int[] blockstart) {
String text = getText();
int dot = getCaretPosition();
int block = 0;
blockstart[0] = 0;
char[] separators = getSeparators();
for (int i=1;i<blockstart.length;i++) {
int min = text.length();
for (int j=0;j<separators.length;j++) {
int pos = text.indexOf(separators[j], blockstart[i-1] + 1);
if (pos>=0 && pos < min)
min = pos;
}
blockstart[i] = min;
if (dot>blockstart[i])
block = i;
}
return block;
}
/** Select the text from dot to mark. */
protected void mark(int dot,int mark) {
setCaretPosition(mark);
moveCaretPosition(dot);
}
/** this method will be called when an non-valid character is entered. */
protected void beep() {
Toolkit.getDefaultToolkit().beep();
}
/** returns true if the text can be split into blocks. */
abstract public boolean blocksValid();
/** The number of blocks for this Component. */
abstract protected int blockCount();
/** This method will be called, when the user has pressed the up/down
* arrows on a selected block.
* @param count Posible values are 1,-1,10,-10.
*/
abstract protected void changeSelectedBlock(int[] blocks,int block,String selected,int count);
/** returns the maximum length of the specified block. */
abstract protected int maxBlockLength(int block);
/** returns true if the character should be accepted by the component. */
abstract protected boolean isValidChar(char c);
/** returns true if the character is a block-separator. All block-separators must
be valid characters.
@see #isValidChar
*/
abstract protected boolean isSeparator(char c);
/** @return all seperators.*/
abstract protected char[] getSeparators();
}
| 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 |
/*--------------------------------------------------------------------------*
| 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;
/* 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.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;
/** 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.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.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) 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) 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.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.CardLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
/** This is an alternative ComboBox implementation. The main differences are:
<ul>
<li>No pluggable look and feel</li>
<li>drop-down button and editor in a separate component (each can get focus)</li>
<li>the popup-component can be an arbitrary JComponent.</li>
</ul>
*/
public abstract class RaplaComboBox extends JPanel {
private static final long serialVersionUID = 1L;
private JPopupMenu m_popup;
private boolean m_popupVisible = false;
private boolean m_isDropDown = true;
protected RaplaArrowButton m_popupButton;
protected JLabel jLabel;
protected JComponent m_editorComponent;
// If you click on the popupButton while the PopupWindow is shown,
// the Window will be closed, because you clicked outside the Popup
// (not because you clicked that special button).
// The flag popupVisible is unset.
// After that the same click will trigger the actionPerfomed method
// on our button. And the window would popup again.
// Solution: We track down that one mouseclick that closes the popup
// with the following flags:
private boolean m_closing = false;
private boolean m_pressed = false;
private Listener m_listener = new Listener();
public RaplaComboBox(JComponent editorComponent) {
this(true,editorComponent);
}
RaplaComboBox(boolean isDropDown,JComponent editorComponent) {
m_editorComponent = editorComponent;
m_isDropDown = isDropDown;
jLabel = new JLabel();
setLayout(new BorderLayout());
add(jLabel,BorderLayout.WEST);
add(m_editorComponent,BorderLayout.CENTER);
if (m_isDropDown) {
installPopupButton();
add(m_popupButton,BorderLayout.EAST);
m_popupButton.addActionListener(m_listener);
m_popupButton.addMouseListener(m_listener);
m_popupVisible = false;
}
}
public JLabel getLabel() {
return jLabel;
}
class Listener implements ActionListener,MouseListener,PopupMenuListener {
// Implementation of ActionListener
public void actionPerformed(ActionEvent e) {
// Ignore action, when Popup is closing
log("Action Performed");
if (m_pressed && m_closing) {
m_closing = false;
return;
}
if ( !m_popupVisible && !m_closing) {
log("Open");
showPopup();
} else {
m_popupVisible = false;
closePopup();
} // end of else
}
private void log(@SuppressWarnings("unused") String string) {
// System.out.println(System.currentTimeMillis() / 1000 + "m_visible:" + m_popupVisible + " closing: " + m_closing + " [" + string + "]");
}
// Implementation of MouseListener
public void mousePressed(MouseEvent evt) {
m_pressed = true;
m_closing = false;
log("Pressed");
}
public void mouseClicked(MouseEvent evt) {
m_closing = false;
}
public void mouseReleased(MouseEvent evt) {
m_pressed = false;
m_closing = false;
log("Released");
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
// Implementation of PopupListener
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
m_popupVisible = true;
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
m_popupVisible = false;
m_closing = true;
m_popupButton.requestFocus();
m_popupButton.setChar('v');
log("Invisible");
final boolean oldState = m_popupButton.isEnabled();
m_popupButton.setEnabled( false);
final Timer timer = new Timer(true);
TimerTask task = new TimerTask()
{
public void run()
{
m_popupButton.setEnabled( oldState);
}
};
timer.schedule(task, 100);
}
public void popupMenuCanceled(PopupMenuEvent e) {
m_popupVisible = false;
m_closing = true;
m_popupButton.requestFocus();
log("Cancel");
}
}
private void installPopupButton() {
// Maybe we could use the combobox drop-down button here.
m_popupButton = new RaplaArrowButton('v');
}
public void setFont(Font font) {
super.setFont(font);
// Method called during constructor?
if (font == null)
return;
if (m_editorComponent != null)
m_editorComponent.setFont(font);
if (m_popupButton != null && m_isDropDown) {
int size = (int) getPreferredSize().getHeight();
m_popupButton.setSize(size,size);
}
}
public void setEnabled( boolean enabled ) {
super.setEnabled( enabled );
if ( m_editorComponent != null ) {
m_editorComponent.setEnabled( enabled );
}
if ( m_popupButton != null ) {
m_popupButton.setEnabled ( enabled );
}
}
protected void showPopup() {
if (m_popup == null)
createPopup();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension menuSize = m_popup.getPreferredSize();
Dimension buttonSize = m_popupButton.getSize();
Point location = m_popupButton.getLocationOnScreen();
int diffx= buttonSize.width - menuSize.width;
if (location.x + diffx<0)
diffx = - location.x;
int diffy= buttonSize.height;
if (location.y + diffy + menuSize.height > screenSize.height)
diffy = screenSize.height - menuSize.height - location.y;
m_popup.show(m_popupButton,diffx,diffy);
m_popup.requestFocus();
m_popupButton.setChar('^');
}
protected void closePopup() {
if (m_popup != null && m_popup.isVisible()) {
// #Workaround for JMenuPopup-Bug in JDK 1.4
// intended behaviour: m_popup.setVisible(false);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Show JMenuItem and fire a mouse-click
cardLayout.last(m_popup);
menuItem.menuSelectionChanged(true);
menuItem.dispatchEvent(new MouseEvent(m_popup
,MouseEvent.MOUSE_RELEASED
,System.currentTimeMillis()
,0
,0
,0
,1
,false));
// show original popup again
cardLayout.first(m_popup);
m_popupButton.requestFocus();
}
});
}
m_popupVisible = false;
}
private JMenuItem menuItem;
private CardLayout cardLayout;
class MyPopup extends JPopupMenu {
private static final long serialVersionUID = 1L;
MyPopup() {
super();
}
public void menuSelectionChanged(boolean isIncluded) {
closePopup();
}
}
private void createPopup() {
m_popup = new JPopupMenu();
/* try {
PopupMenu.class.getMethod("isPopupTrigger",new Object[]{});
} catch (Exception ex) {
m_popup.setLightWeightPopupEnabled(true);
}*/
m_popup.setBorder(null);
cardLayout = new CardLayout();
m_popup.setLayout(cardLayout);
m_popup.setInvoker(this);
m_popup.add(getPopupComponent(),"0");
menuItem = new JMenuItem("");
m_popup.add(menuItem,"1");
m_popup.setBorderPainted(true);
m_popup.addPopupMenuListener(m_listener);
}
/** the component that should apear in the popup menu */
protected abstract JComponent getPopupComponent();
}
| 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.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) 2006 Gereon Fassbender |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.iolayer;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import javax.swing.RepaintManager;
/** Use this to print an awt-Component on one page.
*/
public class ComponentPrinter implements Printable
{
private Component component;
protected Dimension scaleToFit;
public ComponentPrinter(Component c, Dimension scaleToFit)
{
component= c;
this.scaleToFit = scaleToFit;
}
protected boolean setPage( int pageNumber)
{
// default is one page
return pageNumber == 0;
}
public int print(Graphics g, PageFormat format, int pagenumber) throws PrinterException
{
if (!setPage( pagenumber)) { return Printable.NO_SUCH_PAGE; }
Graphics2D g2 = (Graphics2D) g;
if ( scaleToFit != null) {
scaleToFit(g2, format, scaleToFit);
}
RepaintManager rm = RepaintManager.currentManager(component);
boolean db= rm.isDoubleBufferingEnabled();
try {
rm.setDoubleBufferingEnabled(false);
component.printAll(g2);
} finally {
rm.setDoubleBufferingEnabled(db);
}
return Printable.PAGE_EXISTS;
}
private static void scaleToFit(Graphics2D g, PageFormat format, Dimension dim)
{
scaleToFit(g, format, dim.getWidth(),dim.getHeight());
}
public static void scaleToFit(Graphics2D g, PageFormat format, double width, double height)
{
g.translate(format.getImageableX(), format.getImageableY());
double sx = format.getImageableWidth() / width;
double sy = format.getImageableHeight() / height;
if (sx < sy) { sy = sx; } else { sx = sy; }
g.scale(sx, sy);
}
}
| Java |
package org.rapla.components.iolayer;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import com.itextpdf.text.Document;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
public class ITextPrinter {
static public void createPdf( Printable printable, java.io.OutputStream fileOutputStream, PageFormat format) {
float width = (float)format.getWidth();
float height = (float)format.getHeight();
Rectangle pageSize = new Rectangle(width, height);
Document document = new Document(pageSize);
try {
PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();
for (int page = 0;page<5000;page++)
{
Graphics2D g2;
PdfTemplate tp = cb.createTemplate(width, height);
g2 = tp.createGraphics(width, height);
int status = printable.print(g2, format, page);
g2.dispose();
if ( status == Printable.NO_SUCH_PAGE)
{
break;
}
if ( status != Printable.PAGE_EXISTS)
{
break;
}
cb.addTemplate(tp, 0, 0);
document.newPage();
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
document.close();
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.iolayer;
import java.awt.Component;
import java.awt.Frame;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import org.rapla.framework.logger.Logger;
final public class WebstartIO extends DefaultIO {
Method lookup;
Method getDefaultPage;
Method showPageFormatDialog;
Method print;
Method saveFileDialog;
Method openFileDialog;
Method getName;
Method getInputStream;
Method setContents;
Method getContents;
Method showDocument;
Class<?> unavailableServiceException;
String basicService = "javax.jnlp.BasicService";
String printService = "javax.jnlp.PrintService";
String fileSaveService = "javax.jnlp.FileSaveService";
String fileOpenService = "javax.jnlp.FileOpenService";
String clipboardService = "javax.jnlp.ClipboardService";
public WebstartIO(Logger logger) throws UnsupportedOperationException {
super( logger);
try {
Class<?> serviceManagerC = Class.forName("javax.jnlp.ServiceManager");
Class<?> printServiceC = Class.forName(printService);
Class<?> fileSaveServiceC = Class.forName(fileSaveService);
Class<?> fileOpenServiceC = Class.forName(fileOpenService);
Class<?> clipboardServiceC = Class.forName(clipboardService);
Class<?> basicServiceC = Class.forName(basicService);
Class<?> fileContents = Class.forName("javax.jnlp.FileContents");
unavailableServiceException = Class.forName("javax.jnlp.UnavailableServiceException");
getName = fileContents.getMethod("getName", new Class[] {} );
getInputStream = fileContents.getMethod("getInputStream", new Class[] {} );
lookup = serviceManagerC.getMethod("lookup", new Class[] {String.class});
getDefaultPage = printServiceC.getMethod("getDefaultPage",new Class[] {});
showPageFormatDialog = printServiceC.getMethod("showPageFormatDialog",new Class[] {PageFormat.class});
print = printServiceC.getMethod("print",new Class[] {Printable.class});
saveFileDialog = fileSaveServiceC.getMethod("saveFileDialog",new Class[] {String.class,String[].class,InputStream.class,String.class});
openFileDialog = fileOpenServiceC.getMethod("openFileDialog",new Class[] {String.class,String[].class});
setContents = clipboardServiceC.getMethod("setContents", new Class[] {Transferable.class});
getContents = clipboardServiceC.getMethod("getContents", new Class[] {});
showDocument = basicServiceC.getMethod("showDocument", new Class[] {URL.class});
} catch (ClassNotFoundException ex) {
getLogger().error(ex.getMessage());
throw new UnsupportedOperationException("Java Webstart not available due to " + ex.getMessage());
} catch (Exception ex) {
getLogger().error(ex.getMessage());
throw new UnsupportedOperationException(ex.getMessage());
}
}
private Object invoke(String serviceName, Method method, Object[] args) throws Exception {
Object service;
try {
service = lookup.invoke( null, new Object[] { serviceName });
return method.invoke( service, args);
} catch (InvocationTargetException e) {
throw (Exception) e.getTargetException();
} catch (Exception e) {
if ( unavailableServiceException.isInstance( e ) ) {
throw new UnsupportedOperationException("The java-webstart service " + serviceName + " is not available!");
}
throw new UnsupportedOperationException(e.getMessage());
}
}
public PageFormat defaultPage() throws UnsupportedOperationException {
if ( isJDK1_5orHigher() )
return super.defaultPage();
PageFormat format = null;
try {
format = (PageFormat) invoke ( printService, getDefaultPage, new Object[] {} ) ;
} catch (Exception ex) {
getLogger().error("Can't get print service using default PageFormat." + ex.getMessage());
}
if (format == null)
format = new PageFormat();
logPaperSize (format.getPaper());
return format;
}
public void setContents(Transferable transferable, ClipboardOwner owner) {
try {
invoke( clipboardService, setContents, new Object[] {transferable});
} catch (Exception ex) {
throw new UnsupportedOperationException(ex.getMessage());
}
}
public Transferable getContents( ClipboardOwner owner) {
try {
return (Transferable)invoke( clipboardService, getContents, new Object[] {});
} catch (Exception ex) {
throw new UnsupportedOperationException(ex.getMessage());
}
}
public PageFormat showFormatDialog(PageFormat format) throws UnsupportedOperationException {
if ( isJDK1_5orHigher() )
return super.showFormatDialog( format );
logPaperSize (format.getPaper());
try {
// format = getPrintService().showPageFormatDialog(format);
format = (PageFormat) invoke( printService, showPageFormatDialog, new Object[] {format});
} catch (Exception ex) {
throw new UnsupportedOperationException(ex.getMessage());
}
return format;
}
/** in the new JDK we don't need the webstart print service */
private boolean isJDK1_5orHigher() {
try {
String version = System.getProperty("java.version");
boolean oldVersion = version.startsWith("1.4") || version.startsWith("1.3");
//System.out.println( version + " new=" + !oldVersion);
return !oldVersion;
//return false;
} catch (SecurityException ex) {
return false;
}
}
/**
Prints an printable object. The format parameter is ignored, if askFormat is not set.
Call showFormatDialog to set the PageFormat.
@param askFormat If true a dialog will show up to allow the user to edit printformat.
*/
public boolean print(Printable printable, PageFormat format, boolean askFormat) throws PrinterException,UnsupportedOperationException {
if ( isJDK1_5orHigher() ) {
return super.print( printable , format, askFormat );
}
logPaperSize (format.getPaper());
if ( askFormat ) {
format= showFormatDialog(format);
}
try {
Boolean result = (Boolean) invoke( printService , print, new Object[] { printable });
return result.booleanValue();
} catch (PrinterException ex) {
throw ex;
} catch (Exception ex) {
throw new UnsupportedOperationException(ex.getMessage());
}
}
public String saveAsFileShowDialog(String dir,Printable printable,PageFormat format,boolean askFormat,Component owner, boolean pdf) throws IOException,UnsupportedOperationException {
if (askFormat) { format= showFormatDialog(format); }
ByteArrayOutputStream out = new ByteArrayOutputStream();
callExport(printable,format,out, pdf);
if (dir == null)
dir = "";
if ( pdf){
return saveFile( null, dir, new String[] {"pdf"},"RaplaOutput.pdf", out.toByteArray());
}
else
{
return saveFile( null, dir, new String[] {"ps"},"RaplaOutput.ps", out.toByteArray());
}
}
public String saveFile(Frame frame,String dir, String[] fileExtensions, String filename, byte[] content) throws IOException {
try {
InputStream in = new ByteArrayInputStream( content);
Object result = invoke( fileSaveService, saveFileDialog, new Object[] {
dir
,fileExtensions
,in
,filename
});
if (result != null)
return (String) getName.invoke( result, new Object[] {});
else
return null;
} catch (IOException ex) {
throw ex;
} catch (Exception ex) {
throw new UnsupportedOperationException("Can't invoke save Method " + ex.getMessage() );
}
}
public FileContent openFile(Frame frame,String dir, String[] fileExtensions) throws IOException {
try {
Object result = invoke( fileOpenService, openFileDialog, new Object[] {
dir
,fileExtensions
});
if (result != null)
{
String name = (String) getName.invoke( result, new Object[] {});
InputStream in = (InputStream) getInputStream.invoke( result, new Object[] {});
FileContent content = new FileContent();
content.setName( name );
content.setInputStream( in );
return content;
}
return null;
} catch (IOException ex) {
throw ex;
} catch (Exception ex) {
throw new UnsupportedOperationException("Can't invoke open Method " + ex.getMessage() );
}
}
public boolean openUrl(URL url) throws IOException {
try {
// Lookup the javax.jnlp.BasicService object
invoke(basicService,showDocument, new Object[] {url});
// Invoke the showDocument method
return true;
} catch(Exception ex) {
return false;
}
}
}
| Java |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.iolayer;
import java.awt.Component;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.PrintException;
import javax.print.SimpleDoc;
import javax.print.StreamPrintService;
import javax.print.StreamPrintServiceFactory;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.Size2DSyntax;
import javax.print.attribute.standard.MediaName;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.standard.OrientationRequested;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import org.rapla.framework.logger.Logger;
public class DefaultIO implements IOInterface{
static DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
/**
* Name of all Rapla printjobs (used in dialogs, printerqueue, etc).
*/
public final static String RAPLA_JOB= "Rapla Printjob";
public PrinterJob job;
Logger logger;
public DefaultIO(Logger logger) {
this.logger = logger;
}
public Logger getLogger() {
return logger;
}
private PrinterJob getJob() {
if (job == null)
job = PrinterJob.getPrinterJob();
return job;
}
public PageFormat defaultPage() throws UnsupportedOperationException {
try {
PageFormat format = getJob().defaultPage();
return format;
} catch (SecurityException ex) {
return new PageFormat();
}
}
public PageFormat showFormatDialog(PageFormat format) throws UnsupportedOperationException {
logPaperSize (format.getPaper());
format = getJob().pageDialog(format);
logPaperSize (format.getPaper());
return format;
}
public void setContents(Transferable transferable, ClipboardOwner owner) {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents( transferable, owner );
}
public Transferable getContents( ClipboardOwner owner) {
return Toolkit.getDefaultToolkit().getSystemClipboard().getContents( owner);
}
public boolean supportsPostscriptExport() {
if (!supportsPrintService())
return false;
return getPSExportServiceFactory() != null;
}
private boolean supportsPrintService() {
try {
getClass().getClassLoader().loadClass("javax.print.StreamPrintServiceFactory");
return true;
} catch (ClassNotFoundException ex) {
getLogger().warn("No support for javax.print.StreamPrintServiceFactory");
return false;
}
}
protected void callExport(Printable printable, PageFormat format,OutputStream out, boolean pdf) throws UnsupportedOperationException,IOException {
if ( pdf)
{
ITextPrinter.createPdf(printable, out, format);
}
save(printable,format,out);
}
private static StreamPrintServiceFactory getPSExportServiceFactory() {
StreamPrintServiceFactory []factories =
StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor,"application/postscript");
if (factories.length == 0) {
return null;
}
/*
for (int i=0;i<factories.length;i++) {
System.out.println("Stream Factory " + factories[i]);
System.out.println(" Output " + factories[i].getOutputFormat());
DocFlavor[] docFlavors = factories[i].getSupportedDocFlavors();
for (int j=0;j<docFlavors.length;j++) {
System.out.println(" Flavor " + docFlavors[j].getMimeType());
}
}*/
return factories[0];
}
public void save(Printable print,PageFormat format,OutputStream out) throws IOException {
StreamPrintService sps = null;
try {
StreamPrintServiceFactory spsf = getPSExportServiceFactory();
if (spsf == null)
{
throw new UnsupportedOperationException("No suitable factories for postscript-export.");
}
sps = spsf.getPrintService(out);
Doc doc = new SimpleDoc(print, flavor, null);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
if (format.getOrientation() == PageFormat.LANDSCAPE)
{
aset.add(OrientationRequested.LANDSCAPE);
}
if (format.getOrientation() == PageFormat.PORTRAIT)
{
aset.add(OrientationRequested.PORTRAIT);
}
if (format.getOrientation() == PageFormat.REVERSE_LANDSCAPE)
{
aset.add(OrientationRequested.REVERSE_LANDSCAPE);
}
aset.add(MediaName.ISO_A4_WHITE);
Paper paper = format.getPaper();
if (sps.getSupportedAttributeValues(MediaPrintableArea.class,null,null) != null)
{
MediaPrintableArea printableArea = new MediaPrintableArea
(
(float)(paper.getImageableX()/72)
,(float)(paper.getImageableY()/72)
,(float)(paper.getImageableWidth()/72)
,(float)(paper.getImageableHeight()/72)
,Size2DSyntax.INCH
);
aset.add(printableArea);
// System.out.println("new Area: " + printableArea);
}
sps.createPrintJob().print(doc,aset);
} catch (PrintException ex) {
throw new IOException(ex.getMessage());
} finally {
if (sps != null)
sps.dispose();
}
}
public String saveAsFileShowDialog(String dir,Printable printable,PageFormat format,boolean askFormat,Component owner, boolean pdf) throws UnsupportedOperationException,IOException {
if (askFormat) { format= showFormatDialog(format); }
JFileChooser chooser = new JFileChooser();
chooser.setAcceptAllFileFilterUsed(false);
chooser.setApproveButtonText("Save");
if (dir != null)
chooser.setCurrentDirectory(new File(dir));
// Note: source for ExampleFileFilter can be found in FileChooserDemo,
// under the demo/jfc directory in the Java 2 SDK, Standard Edition.
chooser.setFileFilter( pdf ? new PDFFileFilter() :new PSFileFilter());
int returnVal = chooser.showOpenDialog(owner);
if(returnVal != JFileChooser.APPROVE_OPTION)
return null;
File selectedFile = chooser.getSelectedFile();
String suffix = pdf ? ".pdf" : ".ps";
String name = selectedFile.getName();
if (!name.endsWith(suffix))
{
String parent = selectedFile.getParent();
selectedFile = new File( parent, name + suffix);
}
OutputStream out = new FileOutputStream(selectedFile);
callExport(printable,format,out, pdf);
out.close();
return selectedFile.getPath();
}
private class PSFileFilter extends FileFilter {
public boolean accept(File file) {
return (file.isDirectory() || file.getName().toLowerCase().endsWith(".ps"));
}
public String getDescription() {
return "Postscript";
}
}
private class PDFFileFilter extends FileFilter {
public boolean accept(File file) {
return (file.isDirectory() || file.getName().toLowerCase().endsWith(".pdf"));
}
public String getDescription() {
return "PDF";
}
}
public void saveAsFile(Printable printable,PageFormat format,OutputStream out, boolean pdf) throws UnsupportedOperationException,IOException {
callExport(printable,format,out, pdf);
}
/**
Prints an awt or swing component.
@param askFormat If true a dialog will show up to allow the user to edit printformat.
*/
public boolean print(Printable printable, PageFormat format, boolean askFormat) throws PrinterException {
getJob().setPrintable(printable, format);
getJob().setJobName(RAPLA_JOB);
if (askFormat) {
if (getJob().printDialog()) {
logPaperSize (format.getPaper());
getJob().print();
return true;
}
} else {
getJob().print();
return true;
}
getJob().cancel();
return false;
}
void logPaperSize(Paper paper) {
if (getLogger().isDebugEnabled())
getLogger().debug(
(paper.getImageableX()/72) * INCH_TO_MM
+", " +(paper.getImageableY()/72) * INCH_TO_MM
+", " +(paper.getImageableWidth() /72) * INCH_TO_MM
+", " +(paper.getImageableHeight() /72) * INCH_TO_MM
);
}
public String saveFile(Frame frame,String dir,final String[] fileExtensions, String filename, byte[] content) throws IOException {
final FileDialog fd = new FileDialog(frame, "Save File", FileDialog.SAVE);
if ( dir == null)
{
try
{
dir = getDirectory();
}
catch (Exception ex)
{
}
}
if ( dir != null)
{
fd.setDirectory(dir);
}
fd.setFile(filename);
if ( fileExtensions.length > 0)
{
fd.setFilenameFilter( new FilenameFilter() {
public boolean accept(File dir, String name) {
final String[] split = name.split(".");
if ( split.length > 1)
{
String extension = split[split.length -1].toLowerCase();
for ( String ext: fileExtensions)
{
if ( ext.toLowerCase().equals(extension ))
{
return true;
}
}
}
return false;
}
});
}
fd.setLocation(50, 50);
fd.setVisible( true);
final String savedFileName = fd.getFile();
if (savedFileName == null) {
return null;
}
String path = createFullPath(fd);
final File savedFile = new File( path);
writeFile(savedFile, content);
return path;
}
public FileContent openFile(Frame frame,String dir, String[] fileExtensions) throws IOException {
final FileDialog fd = new FileDialog(frame, "Open File", FileDialog.LOAD);
if ( dir == null)
{
dir = getDirectory();
}
fd.setDirectory(dir);
fd.setLocation(50, 50);
fd.setVisible( true);
final String openFileName = fd.getFile();
if (openFileName == null) {
return null;
}
String path = createFullPath(fd);
final FileInputStream openFile = new FileInputStream( path);
FileContent content = new FileContent();
content.setName( openFileName);
content.setInputStream( openFile );
return content;
}
private String getDirectory() {
final String userHome = System.getProperty("user.home");
if (userHome == null) {
final File execDir = new File("");
return execDir.getAbsolutePath();
}
return userHome;
}
private String createFullPath(final FileDialog fd) {
return fd.getDirectory()
+ System.getProperty("file.separator").charAt(0) + fd.getFile();
}
private void writeFile(final File savedFile, byte[] content) throws IOException {
final FileOutputStream out;
out = new FileOutputStream(savedFile);
out.write( content);
out.flush();
out.close();
}
public boolean openUrl(URL url) throws IOException {
try
{
java.awt.Desktop.getDesktop().browse(url.toURI());
return true;
}
catch (Throwable ex)
{
getLogger().error(ex.getMessage(), ex);
return false;
}
}
}
| Java |
package org.rapla.components.iolayer;
import java.io.InputStream;
public class FileContent {
String name;
InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.