2
0
Fork 0

wip made remote ejb working over http

This commit is contained in:
Willem Cazander 2012-11-21 20:45:08 +01:00
parent d4e537a2bf
commit 2a0d992642
393 changed files with 8916 additions and 3872 deletions

View file

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>vasc-demo-tech-client-swing</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,58 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>vasc-demo-tech</artifactId>
<groupId>net.forwardfire.vasc.demo</groupId>
<version>0.4.1-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<artifactId>vasc-demo-tech-client-swing</artifactId>
<dependencies>
<dependency>
<groupId>net.forwardfire.vasc</groupId>
<artifactId>vasc-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>net.forwardfire.vasc</groupId>
<artifactId>vasc-backend-metamodel</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>net.forwardfire.vasc</groupId>
<artifactId>vasc-frontend-swing</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>net.forwardfire.vasc</groupId>
<artifactId>vasc-core-ejb3-client</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>net.forwardfire.vasc.demo</groupId>
<artifactId>vasc-demo-tech-web</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>net.forwardfire.vasc.demo</groupId>
<artifactId>vasc-demo-tech-ejb3</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>openejb-client</artifactId>
<version>4.5.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.jdesktop.bsaf</groupId>
<artifactId>bsaf</artifactId>
<version>${bsaf.version}</version>
<exclusions>
<exclusion>
<artifactId>jnlp</artifactId>
<groupId>javax.jnlp</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>

View file

@ -0,0 +1,556 @@
/*
* Copyright 2007-2012 forwardfire.net All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.forwardfire.vasc.demo.client.swing;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.swing.BorderFactory;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTree;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import net.forwardfire.vasc.annotations.VascModelReference;
import net.forwardfire.vasc.backend.VascBackend;
import net.forwardfire.vasc.backend.VascBackendController;
import net.forwardfire.vasc.backend.VascBackendControllerLocal;
import net.forwardfire.vasc.backend.VascBackendState;
import net.forwardfire.vasc.backend.proxy.VascBackendProxyEventExecutor;
import net.forwardfire.vasc.core.VascController;
import net.forwardfire.vasc.core.VascControllerLocal;
import net.forwardfire.vasc.core.VascControllerProvider;
import net.forwardfire.vasc.core.VascEntry;
import net.forwardfire.vasc.core.VascEntryControllerLocal;
import net.forwardfire.vasc.core.VascEntryField;
import net.forwardfire.vasc.core.VascEntryFieldLocal;
import net.forwardfire.vasc.core.VascEntryLocal;
import net.forwardfire.vasc.core.VascException;
import net.forwardfire.vasc.core.entry.VascEntryFieldValue;
import net.forwardfire.vasc.core.entry.VascEntryRecordCreator;
import net.forwardfire.vasc.demo.tech.ejb3.menu.VascMenuController;
import net.forwardfire.vasc.demo.tech.ejb3.menu.model.VascMenu;
import net.forwardfire.vasc.demo.tech.ejb3.menu.model.VascMenuGroup;
import net.forwardfire.vasc.ejb3.VascServiceManager;
import net.forwardfire.vasc.frontend.swing.SwingPanelIntegration;
import net.forwardfire.vasc.frontend.swing.SwingPanelTabbed;
import net.forwardfire.vasc.impl.DefaultVascController;
import net.forwardfire.vasc.impl.DefaultVascFactory;
import net.forwardfire.vasc.impl.entry.SetParameterBackendListener;
/**
* JMainPanel is the main panel/window of this demo.
*
* @author Willem Cazander
* @version 1.0 May 12, 2012
*/
public class JMainPanel extends JPanel {
private static final long serialVersionUID = 5834715323973411147L;
//private VascControllerService vascManager = null;
private VascController vc = null;
private VascMenuController vmc = null;
private VascServiceManager vsm = null;
private SwingPanelIntegration spi = null;
private JTabbedPane tabPane = null;
private JTree vascTree = null;
private JSplitPane bottomSplitPane = null;
private JSplitPane treeSplitPane = null;
public JMainPanel(VascServiceManager vsm,VascMenuController vmc) {
//this.vascManager=VascTechDemoStartup.getInstance().getVascControllerService();
this.vsm = vsm;
this.vmc = vmc;
setLayout(new BorderLayout());
add(createBottomSplit(), BorderLayout.CENTER);
vc = createVascController(vsm);
//vascManager.addVascServiceListener(this);
rebuildTree();
}
class RemoteVascBackend implements VascBackend {
private String backendId = null;
private VascServiceManager vascManager = null;
public RemoteVascBackend(String backendId,VascServiceManager vascManager) {
this.backendId=backendId;
this.vascManager=vascManager;
}
public void startBackend() {
}
public void stopBackend() {
}
public void delete(Object object) throws VascException {
Object[] args = new Object[1];
args[0]=object;
vascManager.invokeBackendMethod(backendId, "delete", args);
}
public long doRecordMoveDownById(VascBackendState state,Object primaryId) throws VascException {
Object[] args = new Object[2];
args[0]=state;
args[1]=primaryId;
Object result = vascManager.invokeBackendMethod(backendId, "doRecordMoveDownById", args);
return (Long)result;
}
public long doRecordMoveUpById(VascBackendState state, Object primaryId) throws VascException {
Object[] args = new Object[2];
args[0]=state;
args[1]=primaryId;
Object result = vascManager.invokeBackendMethod(backendId, "doRecordMoveUpById", args);
return (Long)result;
}
@SuppressWarnings("unchecked")
public List<Object> execute(VascBackendState state) throws VascException {
Object[] args = new Object[1];
args[0]=state;
Object result = vascManager.invokeBackendMethod(backendId, "execute", args);
return (List<Object>)result;
}
public long fetchTotalExecuteSize(VascBackendState state) {
Object[] args = new Object[1];
args[0]=state;
Object result = vascManager.invokeBackendMethod(backendId, "fetchTotalExecuteSize", args);
return (Long)result;
}
public String getId() {
return backendId;
}
public boolean isPageable() {
Object[] args = new Object[0];
Object result = vascManager.invokeBackendMethod(backendId, "isPageable", args);
return (Boolean)result;
}
public boolean isRecordMoveable() {
Object[] args = new Object[0];
Object result = vascManager.invokeBackendMethod(backendId, "isRecordMoveable", args);
return (Boolean)result;
}
public boolean isSearchable() {
Object[] args = new Object[0];
Object result = vascManager.invokeBackendMethod(backendId, "isSearchable", args);
return (Boolean)result;
}
public boolean isSortable() {
Object[] args = new Object[0];
Object result = vascManager.invokeBackendMethod(backendId, "isSortable", args);
return (Boolean)result;
}
public Object merge(Object object) throws VascException {
Object[] args = new Object[1];
args[0]=object;
Object result = vascManager.invokeBackendMethod(backendId, "merge", args);
return result;
}
public void persist(Object object) throws VascException {
Object[] args = new Object[1];
args[0]=object;
vascManager.invokeBackendMethod(backendId, "delete", args);
}
public VascEntryFieldValue provideVascEntryFieldValue(VascEntryField field) {
try {
field = ((VascEntryFieldLocal)field).clone(); // RM...
ByteArrayOutputStream dataArray = new ByteArrayOutputStream(256); // it grows when needed
ObjectOutputStream objOutstream = new ObjectOutputStream(dataArray);
objOutstream.writeObject(field);
objOutstream.close();
int objectSize = dataArray.size();
System.out.println("Writing obj to field: "+objectSize);
} catch (Exception e) {
throw new RuntimeException(e);
}
Object[] args = new Object[1];
args[0]=field;
Object result = vascManager.invokeBackendMethod(backendId, "provideVascEntryFieldValue", args);
return (VascEntryFieldValue)result;
}
public VascEntryRecordCreator provideVascEntryRecordCreator(VascEntry vascEntry) {
VascEntryLocal clone = null;
try {
clone = ((VascEntryLocal)vascEntry).clone();
clone.setVascFrontendController(null);
clone.setVascEntryFieldEventChannel(null);
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ByteArrayOutputStream dataArray = new ByteArrayOutputStream(256); // it grows when needed
ObjectOutputStream objOutstream = new ObjectOutputStream(dataArray);
objOutstream.writeObject(clone);
objOutstream.close();
//int objectSize = dataArray.size();
//System.out.println("Writing obj to entry: "+objectSize);
} catch (IOException e) {
throw new RuntimeException(e);
}
Object[] args = new Object[1];
args[0]=clone;
Object result = vascManager.invokeBackendMethod(backendId, "provideVascEntryRecordCreator", args);
return (VascEntryRecordCreator)result;
}
public void setId(String id) {
// we cant change id
}
public Map<String, Object> executePageSummary() {
return null;
}
public Map<String, Object> executeTotalSummary() {
return null;
}
public boolean isPageSummary() {
Object[] args = new Object[0];
Object result = vascManager.invokeBackendMethod(backendId, "isPageSummary", args);
return (Boolean)result;
}
public boolean isTotalSummary() {
Object[] args = new Object[0];
Object result = vascManager.invokeBackendMethod(backendId, "isTotalSummary", args);
return (Boolean)result;
}
public boolean isReadOnly() {
return false;
}
}
/**
* @return the vascController
*/
public VascController createVascController(VascServiceManager vsm) {
try {
// VascUserInfo vui = getVascUserInfo();
// get local jvm plugging controller
VascController c = DefaultVascFactory.getDefaultVascController();
/*
DefaultVascEntryController con = new DefaultVascEntryController() {
public VascEntry getVascEntryById(String id) {
VascEntry ve = super.getVascEntryById(id);
// add global listener to make sure we have all LAZY properties of a bean before we goto edit mode.
ve.addVascEntryEventListener(VascEventType.DATA_SELECT, new RefreshObjectForLazyPropertiesListener());
return ve;
}
};
((DefaultVascController)c).setVascEntryController(con);
*/
VascServiceManager vascManager = vsm;
List<String> entryIds = vascManager.getVascEntryIds();
VascEntryControllerLocal localEntryController = (VascEntryControllerLocal)c.getVascEntryController();
VascBackendControllerLocal localBackendController = (VascBackendControllerLocal)c.getVascBackendController();
for (String id:entryIds) {
VascEntryLocal ve = (VascEntryLocal)vascManager.getVascEntry(id);
String backendId = ve.getBackendId();
VascBackend vb = new RemoteVascBackend(backendId,vascManager);
/*
for (String key:ve.getEntryParameterKeys()) {
Object value = ve.getEntryParameter(key);
if (value instanceof String==false) {
continue;
}
String paraValue = (String)value;
if (paraValue.startsWith("userPara")==false) {
continue;
}
String[] ps = paraValue.split(":");
String type = ps[1];
String paraTypeValue = ps[2];
SetParameterBackendListener listener = new SetParameterBackendListener(vui.userId,vui.username);
listener.setName(key);
listener.setType(type);
listener.setValue(paraTypeValue);
VascBackendProxyEventExecutor localUserProxy = new VascBackendProxyEventExecutor();
localUserProxy.addVascEntryBackendEventListener(listener);
vb = localUserProxy;
}
*/
localBackendController.addVascBackend(vb);
localEntryController.addVascEntry(ve);
c.getVascEntryConfigController().configVascEntry(c, ve);
}
return c;
} catch (Exception e) {
throw new RuntimeException("Could not create remote based vasc controller; "+e.getMessage(),e);
}
}
private JSplitPane createBottomSplit() {
JSplitPane sp0 = createTreeSplit();
JPanel sp1 = new JPanel();//JConsolePanel();
bottomSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,sp0,sp1);
bottomSplitPane.setOneTouchExpandable(true);
bottomSplitPane.setResizeWeight(0.2);
bottomSplitPane.setDividerLocation(700);
sp0.setMinimumSize(new Dimension(400, 400));
sp1.setMinimumSize(new Dimension(400, 150));
return bottomSplitPane;
}
private JSplitPane createTreeSplit() {
JScrollPane sp0 = createTreePane();
JScrollPane sp1 = createContentPane();
treeSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,sp0,sp1);
treeSplitPane.setOneTouchExpandable(true);
treeSplitPane.setResizeWeight(0.7);
treeSplitPane.setDividerLocation(200);
sp0.setMinimumSize(new Dimension(200, 400));
sp1.setMinimumSize(new Dimension(400, 400));
return treeSplitPane;
}
class VascTreeModel extends DefaultTreeModel {
public VascTreeModel(TreeNode root) {
super(root);
}
private static final long serialVersionUID = -7436681803506994277L;
@Override
public void addTreeModelListener(TreeModelListener l) {
super.addTreeModelListener(l);
}
}
public void openVascEntry(String vascId) throws VascException {
VascEntryLocal ee = (VascEntryLocal)vsm.getVascEntry(vascId);
vc.getVascEntryConfigController().configVascFrontendController(vc, ee);
spi.createNewVascView(ee);
}
private JScrollPane createTreePane() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode(new VascTreeNode(VascTreeNodeType.ROOT,"Menu"));
vascTree = new JTree(new VascTreeModel(root));
vascTree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if (e.getClickCount() == 2 && vascTree.getSelectionModel().isSelectionEmpty()==false) {
try {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)vascTree.getSelectionModel().getSelectionPath().getLastPathComponent();
if (node.getUserObject() instanceof String) {
return;
}
VascTreeNode vascNode = (VascTreeNode)node.getUserObject();
if (vascNode != null && vsm!=null) {
if (vascNode.type == VascTreeNodeType.ENTRY) {
openVascEntry(vascNode.id);
}
}
} catch (Exception ee) {
ee.printStackTrace();
}
}
}
});
JPanel treePanel = new JPanel();
treePanel.setLayout(new GridLayout(1,0));
JScrollPane p = createJScrollPane(treePanel);
p.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
p.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
treePanel.add(vascTree);
rebuildTree();
return p;
}
private JScrollPane createContentPane() {
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(1,0));
JScrollPane p = createJScrollPane(contentPane);
tabPane = new JTabbedPane();
spi = new SwingPanelTabbed(tabPane);
contentPane.add(tabPane);
return p;
}
private JScrollPane createJScrollPane(JPanel innerPanel) {
JScrollPane scrollPane = new JScrollPane(innerPanel);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.getVerticalScrollBar().setUnitIncrement(10);
scrollPane.getHorizontalScrollBar().setUnitIncrement(10);
//innerPanel.setParentScrollPane(scrollPane);
return scrollPane;
}
class VascTreeNode implements Serializable {
private static final long serialVersionUID = -1177727401194030822L;
public VascTreeNode() {}
public VascTreeNode(VascTreeNodeType type,String id) { this.type=type;this.id=id; }
public VascTreeNode(VascTreeNodeType type,String id,String entryId) { this.type=type;this.id=id;this.entryId=entryId; }
VascTreeNodeType type;
String id;
String entryId;
@Override
public String toString() {
return id;
}
}
enum VascTreeNodeType {
ROOT,
GROUP,
ENTRY
}
public void rebuildTree() {
if (vsm==null) {
return;
}
DefaultMutableTreeNode root = (DefaultMutableTreeNode)vascTree.getModel().getRoot();
root.removeAllChildren();
List<VascMenuGroup> groups = vmc.getFilteredMenuGroup();
for (VascMenuGroup group:groups) {
DefaultMutableTreeNode groupNode = new DefaultMutableTreeNode(new VascTreeNode(VascTreeNodeType.GROUP,group.getTitle()));
for (VascMenu vm:group.getMenus()) {
DefaultMutableTreeNode entryNode = new DefaultMutableTreeNode(new VascTreeNode(VascTreeNodeType.ENTRY,vm.getVascEntryId()));
groupNode.add(entryNode);
}
root.add(groupNode);
}
SwingUtilities.updateComponentTreeUI(vascTree);
/*
// todo move
Map<String,String> keys = new HashMap<String,String>(300);
VascBundleCheckEntryKeys checker = new VascBundleCheckEntryKeys(ResourceBundle.getBundle("net.forwardfire.vasc.lib.i18n.bundle.RootApplicationBundle"));
for (String veId:vascManager.getVascController().getVascEntryController().getVascEntryIds()) {
VascEntry ve = vascManager.getVascController().getVascEntryController().getVascEntryById(veId);
keys.putAll(checker.generateMissingKeys(ve));
}
if (keys.isEmpty()==false) {
Properties p = new Properties();
File dataDir = new File("data");
if (dataDir.exists()==false) {
dataDir.mkdirs();
}
File resourceFile = new File("data/vasc-bundle.properties");
if (resourceFile.exists()) {
readPropertiesFile(p,resourceFile);
}
for (String key:keys.keySet()) {
if (key==null) {
continue;
}
if (keys.get(key)==null) {
continue;
}
p.put(key, keys.get(key));
}
writePropertiesFile(p,resourceFile);
ResourceBundle.clearCache();
}
*/
}
public JTabbedPane getTabPane() {
return tabPane;
}
public void changeEvent() {
rebuildTree();
}
}

View file

@ -0,0 +1,213 @@
/*
* Copyright 2007-2012 forwardfire.net All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.forwardfire.vasc.demo.client.swing;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTabbedPane;
import net.forwardfire.vasc.backend.VascBackendControllerLocal;
import net.forwardfire.vasc.core.VascEntryControllerLocal;
import net.forwardfire.vasc.core.VascException;
import net.forwardfire.vasc.demo.tech.ejb3.menu.VascMenuController;
import net.forwardfire.vasc.demo.tech.ejb3.menu.model.VascMenu;
import net.forwardfire.vasc.demo.tech.ejb3.menu.model.VascMenuGroup;
/**
* JMainPanelMenuBar Adds all menu bar items.
*
* @author Willem Cazander
* @version 1.0 May 12, 2012
*/
public class JMainPanelMenuBar extends JMenuBar implements ActionListener {
private static final long serialVersionUID = -2828428804621352725L;
private VascMenuController vmc = null;
private JMainPanel mainPanel = null;
private List<JMenu> vascMenus = null;
private JMenu clientFileMenu = null;
private JMenu clientTabMenu = null;
public JMainPanelMenuBar(VascMenuController vmc,JMainPanel mainPanel) {
this.vmc=vmc;
this.mainPanel=mainPanel;
clientFileMenu = new JMenu("File");
add(clientFileMenu);
JMenuItem logoutItem = new JMenuItem("Logout");
logoutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
/*
final JFileChooser fc = new JFileChooser();
//fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showOpenDialog((JMenuItem)e.getSource());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//VascTechDemoStartup.getInstance().getVascControllerService().openFile(file);
}
*/
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
clientFileMenu.add(logoutItem);
clientFileMenu.addSeparator();
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
VascDemoSwingClient.getInstance().exit();
}
});
clientFileMenu.add(exitItem);
List<VascMenuGroup> groups = vmc.getFilteredMenuGroup();
for (VascMenuGroup group:groups) {
JMenu menu = new JMenu(group.getTitle());
for (VascMenu vm:group.getMenus()) {
JMenuItem item = new JMenuItem(vm.getTitle());
item.putClientProperty("vascEntryId", vm.getVascEntryId());
item.addActionListener(this);
menu.add(item);
}
add(menu);
}
clientTabMenu = new JMenu("Tabs");
add(clientTabMenu);
JMenuItem item = new JMenuItem("Close tab");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTabbedPane tabPane = getTabPane();
if (tabPane.getSelectedIndex()>=0) {
tabPane.removeTabAt(tabPane.getSelectedIndex()); // todo release vasc frontend
}
}
});
clientTabMenu.add(item);
JMenuItem itemAll = new JMenuItem("Close All tabs");
itemAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTabbedPane tabPane = getTabPane();
for (int i=tabPane.getTabCount();i>0;i--) {
tabPane.removeTabAt(i-1); // todo release vasc frontend
}
}
});
clientTabMenu.add(itemAll);
}
public JTabbedPane getTabPane() {
return mainPanel.getTabPane();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JMenuItem) {
JMenuItem item = (JMenuItem)e.getSource();
String vascId = (String)item.getClientProperty("vascEntryId");
try {
mainPanel.openVascEntry(vascId);
} catch (VascException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
/*
private void createMenuItems() {
JMenuItem openXmlItem = new JMenuItem("Import Xml");
openXmlItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
final JFileChooser fc = new JFileChooser();
//fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showOpenDialog((JMenuItem)e.getSource());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//VascTechDemoStartup.getInstance().getVascControllerService().openFile(file);
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
fileMenu.add(openXmlItem);
//JMenuItem closeXmlItem = new JMenuItem("Close");
//fileMenu.add(closeXmlItem);
fileMenu.addSeparator();
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//JApplication.getInstance().exit();
}
});
fileMenu.add(exitItem);
JMenuItem connectVascItem = new JMenuItem("Add Vasc");
connectVascItem.setEnabled(false);
connectVascItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
vascMenu.add(connectVascItem);
JMenuItem connectLdapItem = new JMenuItem("Add Ldap");
connectLdapItem.setEnabled(false);
vascMenu.add(connectLdapItem);
vascMenu.addSeparator();
vascMenu.addSeparator();
JMenuItem removeEntryItem = new JMenuItem("Remove entry");
removeEntryItem.setEnabled(false);
removeEntryItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
vascMenu.add(removeEntryItem);
tabMenu.add(itemAll);
}
*/
}

View file

@ -0,0 +1,361 @@
package net.forwardfire.vasc.demo.client.swing;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingException;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.swing.JOptionPane;
import net.forwardfire.vasc.demo.tech.ejb3.menu.VascMenuController;
import net.forwardfire.vasc.demo.tech.ejb3.user.LoginUserController;
import net.forwardfire.vasc.ejb3.VascServiceManager;
import org.jdesktop.application.Application;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.SingleFrameApplication;
public class VascDemoSwingClient extends SingleFrameApplication {
private static VascDemoSwingClient instance = null;
static protected Context context = null;
static protected LoginContext loginContext = null;
private Logger logger = null;
static public void main(String[] args) {
/*
instance = new VascDemoSwingClient();
instance.initialize(args);
instance.startup();
*/
Application.launch(VascDemoSwingClient.class, new String[] {});
}
@Override
protected void startup() {
logger = Logger.getLogger(VascDemoSwingClient.class.getName());
createContext();
try {
setJaasConfig();
} catch (IOException e) {
e.printStackTrace();
}
doLogin();
JdniTreePrinter printer = new JdniTreePrinter(false);
StringBuffer buf = new StringBuffer();
printer.printJNDITree(context, "", buf);
System.out.println(buf);
VascServiceManager vc = null;
LoginUserController luc = null;
VascMenuController vmc = null;
try {
vc = (VascServiceManager)context.lookup("vascServiceManagerRemote");
System.out.println("ob: "+vc);
luc = (LoginUserController)context.lookup("loginUserControllerRemote");
System.out.println("fll: "+luc.doClientLogin());
vmc = (VascMenuController)context.lookup("vascMenuControllerRemote");
} catch (Exception e) {
e.printStackTrace();
}
JMainPanel mainPanel = new JMainPanel(vc,vmc);
SingleFrameApplication a = (VascDemoSwingClient)getInstance(); // BIG NOTE because of 'launch' for auto conf swing.
FrameView mainView = a.getMainView();
mainView.setComponent(mainPanel);
mainView.setMenuBar(new JMainPanelMenuBar(vmc,mainPanel));
mainView.getFrame().setSize(600, 800);
mainView.getFrame().setVisible(true);
}
/**
* Created an context to the showplanner server.
*/
private void createContext() {
Properties props = new Properties();
String connectUrl = "http://localhost:8899/demo/ejb"; //System.getProperty("javaws.connecturl");
logger.info("Connecting to: "+connectUrl);
props.put(Context.PROVIDER_URL, connectUrl );
props.put("openejb.authentication.realmName", "vasc-auth-server");
props.put(Context.SECURITY_PRINCIPAL,"admin");
props.put(Context.SECURITY_CREDENTIALS,"admin123");
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.RemoteInitialContextFactory");
try {
context = new InitialContext(props);
} catch (Exception e) {
e.printStackTrace();
//logger.log(Level.WARNING,e.getMessage(),e);
//ExceptionDialog err = new ExceptionDialog(e,true);
//err.showOpenDialog(null,i18n(VascDemoSwingClient.class,"dialogTitle"),i18n(VascDemoSwingClient.class,"dialogContext"));
}
}
/**
* Sets our jaas config path
*/
private void setJaasConfig() throws IOException {
// tomee
String path = System.getProperty("java.security.auth.login.config");
if (path == null) {
URL url = VascDemoSwingClient.class.getClassLoader().getResource("META-INF/client.login.conf");
File tempFile = File.createTempFile("cached-", ".jar");
tempFile.deleteOnExit();
copyFile(url.openConnection().getInputStream(),tempFile);
String urlString = "file:"+tempFile.getAbsolutePath();
//logger.info("Setting jaas config property to url: "+urlString);
System.setProperty("java.security.auth.login.config", urlString);
logger.info("Setting jaas config property to url: "+urlString);
/*
if (resource != null) {
path = URLDecoder.decode(resource.getFile());
System.setProperty("java.security.auth.login.config", path);
} else {
logger.warning("Could not find client.login.conf");
}*/
}
/* jboss
URL url = Thread.currentThread().getContextClassLoader().getResource("META-INF/jaas.config");
String urlString = url.toExternalForm();
// jdk1.6 update10 has different classloader, so just copy for the moment..... ..
if (urlString.startsWith("jar:")) {
File tempFile = File.createTempFile("cached-", ".jar");
tempFile.deleteOnExit();
copyFile(url.openConnection().getInputStream(),tempFile);
urlString = "file:"+tempFile.getAbsolutePath();
}
//logger.info("Setting jaas config property to url: "+urlString);
System.setProperty("java.security.auth.login.config", urlString);
*/
}
private void copyFile(InputStream in, File out) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(1024*4);
byte[] bufferArray = buffer.array();
FileChannel outputChannel = new FileOutputStream(out).getChannel();
while (true) {
buffer.clear();
int lim = in.read(bufferArray);
if (lim < 0) {
break; // could not read anymore
}
buffer.flip();
buffer.limit(lim);
while (buffer.hasRemaining()) {
outputChannel.write(buffer);
}
}
outputChannel.close();
}
/**
* Do an login on the server
*/
private void doLogin() {
VascDemoUserLoginDialog loginHandler = new VascDemoUserLoginDialog();
try {
loginContext = new LoginContext("vasc-auth-client", loginHandler);
loginContext.login();
} catch(Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, i18n(this,"dialogNoLoginContext"),i18n(this,"dialogTitle"), JOptionPane.WARNING_MESSAGE);
System.exit(1);
}
try {
// Subject subject = loginContext.getSubject();
if(doLoginTest()) {
return;
}
loginContext.login();
if(doLoginTest()) {
return;
}
loginContext.login();
if(doLoginTest()) {
return;
}
JOptionPane.showMessageDialog(null, i18n(this,"dialogUserLoginFailure"),i18n(this,"dialogTitle"), JOptionPane.WARNING_MESSAGE);
System.exit(1);
} catch (CommunicationException e) {
List<String> messages = new ArrayList<String>(3);
messages.add("Could not connect to Vasc Tech Client Swing server, please try again.");
messages.add("If the problem persists please contact your systems administrator.");
String connectionError = "Could not obtain connection to any of these urls: ";
Integer connectionErrorLen = connectionError.length();
String emsg = e.getMessage();
if (emsg!=null && emsg.startsWith(connectionError)) {
Integer urlEndIdx = emsg.substring(connectionErrorLen).indexOf(':');
if (urlEndIdx>=0) {
messages.add("Server unreachable at: "+emsg.substring(connectionErrorLen, connectionErrorLen+urlEndIdx));
}
}
JOptionPane.showMessageDialog(null, messages.toArray(), "Vasc Tech Client Swing", JOptionPane.WARNING_MESSAGE);
System.exit(1);
} catch (Exception e) {
//logger.log(Level.WARNING,e.getMessage(),e);
JOptionPane.showMessageDialog(null, "Failure on login test.", "Vasc Tech Client Swing", JOptionPane.WARNING_MESSAGE);
System.exit(1);
}
}
/**
* Check if we have 'login' role on server.
* @return
* @throws Exception
*/
private boolean doLoginTest() throws Exception {
try {
LoginUserController loginManager = (LoginUserController)context.lookup("loginUserControllerRemote");
loginManager.doClientLogin();
return true;
} catch (javax.naming.NameNotFoundException e) {
JOptionPane.showMessageDialog(null, "Server is not deployed.\nPlease wait a couple of minuts and try again.");
return false;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Server error: "+e.getMessage());
e.printStackTrace();
return false;
}
}
/**
* Some simple hardcoded i18n function here
*
* @param key
* @param params
* @return
*/
static protected String i18n(Object obj,String key,Object...params) {
if(obj==null) { throw new NullPointerException("Can't get key of null obj"); }
if (key==null) { throw new NullPointerException("key may not be null"); }
if(obj instanceof Class) {
key=((Class<?>)obj).getName()+"."+key;
} else {
key=obj.getClass().getName()+"."+key;
}
return key;
/*
try {
String text = ResourceBundle.getBundle("resources.i18n.root").getString(key);
if (params != null) {
MessageFormat mf = new MessageFormat(text);
text = mf.format(params, new StringBuffer(), null).toString();
}
return text;
} catch(MissingResourceException e){
return "MISSING: '"+key+"'";
}
*/
}
class JdniTreePrinter {
boolean printXml = true;
public JdniTreePrinter(boolean printXml) {
this.printXml=printXml;
}
public void printJNDITree(javax.naming.Context context,String ct,StringBuffer buf) {
if (printXml) {
buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
buf.append("<NamingRoot name=\""+ct+"\">\n");
}
printTree(context,ct,buf);
if (printXml) {
buf.append("</NamingRoot>\n");
}
}
public void printTree(javax.naming.Context context,String ct,StringBuffer buf) {
try {
printNE(context,context.list(ct), ct,buf);
} catch (NamingException e) {
//ignore leaf node exception
}
}
private void printNE(javax.naming.Context context,javax.naming.NamingEnumeration<?> ne, String parentctx,StringBuffer buf) throws NamingException {
if (ne==null) {
return;
}
while (ne.hasMoreElements()) {
NameClassPair next = (NameClassPair) ne.nextElement();
if (printXml) {
printIndent(buf);
buf.append("<NamingRoot name=\""+next.getName()+"\" className=\""+next.getClassName()+"\">\n");
increaseIndent();
printTree(context,(parentctx.length() == 0) ? next.getName() : parentctx + "/" + next.getName(),buf);
decreaseIndent();
printIndent(buf);
buf.append("</NamingRoot>\n");
} else {
printEntry(next,buf);
increaseIndent();
printTree(context,(parentctx.length() == 0) ? next.getName() : parentctx + "/" + next.getName(),buf);
decreaseIndent();
}
}
}
private void printEntry(javax.naming.NameClassPair next,StringBuffer buf) {
printIndent(buf);
buf.append("-->");
buf.append(next);
buf.append("\n");
}
private int indentLevel = 0;
private void increaseIndent() {
indentLevel += 4;
}
private void decreaseIndent() {
indentLevel -= 4;
}
private void printIndent(StringBuffer buf) {
for (int i = 0; i < indentLevel; i++) {
buf.append(" ");
}
}
}
}

View file

@ -0,0 +1,408 @@
/*
* @(#)DialogCallbackHandler.java 1.9 03/12/19
*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package net.forwardfire.vasc.demo.client.swing;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.ConfirmationCallback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
/**
* Zwaar gehacke jaas login dialog
* added features:
* - name remebering
* - focus on name field
* - alway on top
* - logo stuff
* - message field
*
* <p>
* Uses a Swing dialog window to query the user for answers to authentication
* questions. This can be used by a JAAS application to instantiate a
* CallbackHandler
*
* @see javax.security.auth.callback
*/
public class VascDemoUserLoginDialog implements CallbackHandler {
/* The parent window, or null if using the default parent */
private Component parentComponent;
private static final int JPasswordFieldLen = 8;
private int loginTry = 0;
private String userName = null;
/**
* Creates a callback dialog with the default parent window.
*/
public VascDemoUserLoginDialog() {
}
/**
* Creates a callback dialog and specify the parent window.
*
* @param parentComponent
* the parent window -- specify <code>null</code> for the
* default parent
*/
public VascDemoUserLoginDialog(Component parentComponent) {
this.parentComponent = parentComponent;
}
/**
* An interface for recording actions to carry out if the user clicks OK for
* the dialog.
*/
private static interface Action {
void perform();
}
/**
* Handles the specified set of callbacks.
*
* @param callbacks
* the callbacks to handle
* @throws UnsupportedCallbackException
* if the callback is not an instance of NameCallback or
* PasswordCallback
*/
public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
this.loginTry++;
/* Collect messages to display in the dialog */
final JPanel loginDesign = new JPanel();
loginDesign.setLayout(new BoxLayout(loginDesign, BoxLayout.PAGE_AXIS));
//final Image logoImage = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/resources/images/logos/logo.png"));
final JPanel logoPanel = new JPanel() {
private static final long serialVersionUID = 10l;
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
// for antialiasing geometric shapes
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
// for antialiasing text
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// to go for quality over speed
g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
// Paint the default look of the panel.
super.paintComponent(g2d);
int offsetX = 0; // for windows systems
boolean isWindows = System.getProperty("os.name").toLowerCase().indexOf("windows") != -1;
if (isWindows) {
offsetX += 25;
}
g2d.setColor(Color.BLACK);
g2d.fillRect(0,0,getWidth(),getHeight());
g2d.setColor(new Color(238,212,1));
//int w = (getWidth()/2)-(logoImage.getWidth(null)/2);
//int h = (getHeight()/2)-(logoImage.getHeight(null)/2);
//g2d.drawImage(logoImage, w, h, this);
}
};
logoPanel.setPreferredSize(new Dimension(200, 170));
logoPanel.setBorder(BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
loginDesign.add(logoPanel);
loginDesign.add(Box.createVerticalStrut(5));
JPanel namePanel = new JPanel();
JLabel nameLabel = new JLabel("Vasc Demo Client");
nameLabel.setFont(new Font("Lucida Sans", Font.BOLD, 24));
namePanel.add(nameLabel);
loginDesign.add(namePanel);
loginDesign.add(Box.createVerticalStrut(5));
final GridLayout messagesLayout = new GridLayout(2,2);
final JPanel messages = new JPanel();
messages.setLayout(messagesLayout);
/* Collection actions to perform if the user clicks OK */
final List<Action> okActions = new ArrayList<Action>(2);
ConfirmationInfo confirmation = new ConfirmationInfo();
// hackje for focus
final JTextField name = new JTextField();
confirmation.initialValue=name;
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof TextOutputCallback) {
TextOutputCallback tc = (TextOutputCallback) callbacks[i];
switch (tc.getMessageType()) {
case TextOutputCallback.INFORMATION:
confirmation.messageType = JOptionPane.INFORMATION_MESSAGE;
break;
case TextOutputCallback.WARNING:
confirmation.messageType = JOptionPane.WARNING_MESSAGE;
break;
case TextOutputCallback.ERROR:
confirmation.messageType = JOptionPane.ERROR_MESSAGE;
break;
default:
throw new UnsupportedCallbackException(callbacks[i], "Unrecognized message type");
}
messages.add(new JLabel(tc.getMessage()));
} else if (callbacks[i] instanceof NameCallback) {
final NameCallback nc = (NameCallback) callbacks[i];
JLabel prompt = new JLabel(nc.getPrompt());
String defaultName = nc.getDefaultName();
// if (check some property)
defaultName = "";
if (defaultName != null) {
name.setText(defaultName);
}
// default to last user name
if (userName !=null ) {
name.setText(userName);
}
messages.add(prompt);
messages.add(name);
/* Store the name back into the callback if OK */
okActions.add(new Action() {
public void perform() {
nc.setName(name.getText());
}
});
} else if (callbacks[i] instanceof PasswordCallback) {
final PasswordCallback pc = (PasswordCallback) callbacks[i];
JLabel prompt = new JLabel(pc.getPrompt());
final JPasswordField password = new JPasswordField(JPasswordFieldLen);
if (!pc.isEchoOn()) {
password.setEchoChar('*');
}
messages.add(prompt);
messages.add(password);
okActions.add(new Action() {
public void perform() {
pc.setPassword(password.getPassword());
}
});
} else if (callbacks[i] instanceof ConfirmationCallback) {
ConfirmationCallback cc = (ConfirmationCallback) callbacks[i];
confirmation.setCallback(cc);
if (cc.getPrompt() != null) {
messages.add(new JLabel(cc.getPrompt()));
}
} else {
throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
}
}
if (this.loginTry>1) {
JPanel messagesPanel = new JPanel();
messagesPanel.setBorder(BorderFactory.createEtchedBorder());
JLabel iup = new JLabel("Invalid Username and Password:");
iup.setForeground(Color.RED);
messagesPanel.add(iup);
loginDesign.add(messagesPanel);
loginDesign.add(Box.createVerticalStrut(5));
}
JPanel messagesPanel = new JPanel();
messagesPanel.setBorder(BorderFactory.createEtchedBorder());
messagesPanel.add(messages);
loginDesign.add(messagesPanel);
/* Display the dialog */
/// JOptionPane(Object message, int messageType, int optionType, Icon icon, Object[] options, Object initialValue)
JOptionPane jop = new JOptionPane(loginDesign, JOptionPane.PLAIN_MESSAGE,confirmation.optionType,null,
confirmation.options,confirmation.initialValue);
JDialog dialog = jop.createDialog(parentComponent,"Vasc Demo Login");
// We alway request focus after the windows gets focus
dialog.addWindowFocusListener(new WindowFocusListener() {
/**
* @see java.awt.event.WindowFocusListener#windowGainedFocus(java.awt.event.WindowEvent)
*/
public void windowGainedFocus(WindowEvent arg0) {
//System.out.println("request focus window focus");
name.requestFocus();
}
/**
* @see java.awt.event.WindowFocusListener#windowLostFocus(java.awt.event.WindowEvent)
*/
public void windowLostFocus(WindowEvent arg0) {
}
});
// HACK, EVEN the listener above doesn't work 100% so just request focus request
// until we have focus, then cancel task, see println output
final Timer lTimer = new Timer();
lTimer.schedule(new TimerTask() {
public void run() {
if(name.hasFocus()==false) {
//System.out.println("request focus timer task");
name.requestFocus();
} else {
cancel();
}
}
}, 10, 5);
// wait 10ms
// execute every 5ms
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
Integer result = (Integer)jop.getValue();
dialog.dispose();
if (result==null) {
// is null when escaping by window closing
result = JOptionPane.CANCEL_OPTION;
}
// copy user name for next try
userName = name.getText();
/* Perform the OK actions */
if (result == JOptionPane.OK_OPTION || result == JOptionPane.YES_OPTION) {
Iterator<Action> iterator = okActions.iterator();
while (iterator.hasNext()) {
iterator.next().perform();
}
} else if (result == JOptionPane.CANCEL_OPTION || result == JOptionPane.NO_OPTION) {
System.exit(1);
}
confirmation.handleResult(result);
}
/**
* Provides assistance with translating between JAAS and Swing confirmation
* dialogs.
*/
private static class ConfirmationInfo {
private int[] translations;
int optionType = JOptionPane.OK_CANCEL_OPTION;
Object[] options = null;
Object initialValue = null;
int messageType = JOptionPane.QUESTION_MESSAGE;
private ConfirmationCallback callback;
/* Set the confirmation callback handler */
void setCallback(ConfirmationCallback callback) throws UnsupportedCallbackException {
this.callback = callback;
int confirmationOptionType = callback.getOptionType();
switch (confirmationOptionType) {
case ConfirmationCallback.YES_NO_OPTION:
optionType = JOptionPane.YES_NO_OPTION;
translations = new int[] {
JOptionPane.YES_OPTION, ConfirmationCallback.YES, JOptionPane.NO_OPTION, ConfirmationCallback.NO, JOptionPane.CLOSED_OPTION, ConfirmationCallback.NO
};
break;
case ConfirmationCallback.YES_NO_CANCEL_OPTION:
optionType = JOptionPane.YES_NO_CANCEL_OPTION;
translations = new int[] {
JOptionPane.YES_OPTION, ConfirmationCallback.YES, JOptionPane.NO_OPTION, ConfirmationCallback.NO, JOptionPane.CANCEL_OPTION,
ConfirmationCallback.CANCEL, JOptionPane.CLOSED_OPTION, ConfirmationCallback.CANCEL
};
break;
case ConfirmationCallback.OK_CANCEL_OPTION:
optionType = JOptionPane.OK_CANCEL_OPTION;
translations = new int[] {
JOptionPane.OK_OPTION, ConfirmationCallback.OK, JOptionPane.CANCEL_OPTION, ConfirmationCallback.CANCEL, JOptionPane.CLOSED_OPTION,
ConfirmationCallback.CANCEL
};
break;
case ConfirmationCallback.UNSPECIFIED_OPTION:
options = callback.getOptions();
/*
* There's no way to know if the default option means to
* cancel the login, but there isn't a better way to guess
* this.
*/
translations = new int[] {
JOptionPane.CLOSED_OPTION, callback.getDefaultOption()
};
break;
default:
throw new UnsupportedCallbackException(callback, "Unrecognized option type: " + confirmationOptionType);
}
int confirmationMessageType = callback.getMessageType();
switch (confirmationMessageType) {
case ConfirmationCallback.WARNING:
messageType = JOptionPane.WARNING_MESSAGE;
break;
case ConfirmationCallback.ERROR:
messageType = JOptionPane.ERROR_MESSAGE;
break;
case ConfirmationCallback.INFORMATION:
messageType = JOptionPane.INFORMATION_MESSAGE;
break;
default:
throw new UnsupportedCallbackException(callback, "Unrecognized message type: " + confirmationMessageType);
}
}
/* Process the result returned by the Swing dialog */
void handleResult(int result) {
if (callback == null) {
return;
}
for (int i = 0; i < translations.length; i += 2) {
if (translations[i] == result) {
result = translations[i + 1];
break;
}
}
callback.setSelectedIndex(result);
}
}
}

View file

@ -0,0 +1,6 @@
vasc-auth-client {
org.apache.openejb.client.ClientLoginModule required
debug=true
openejb.server.uri="http://localhost:8899/demo/ejb";
};