MainApplicationWindow.java
上传用户:damzkj
上传日期:2022-01-07
资源大小:24k
文件大小:11k
- package jxtamessenger;
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.util.ArrayList;
- import java.util.Enumeration;
- import java.util.concurrent.ConcurrentHashMap;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.logging.Logger;
- import jxtamessenger.bean.OnlineMessage;
- import jxtamessenger.service.JxtaMulticastSocketService;
- import jxtamessenger.service.JxtaServerSocketService;
- import jxtamessenger.service.Service;
- import jxtamessenger.util.ThreadPoolUtil;
- import jxtamessenger.xml.XmlCreator;
- import net.jxta.peergroup.PeerGroup;
- import net.jxta.platform.NetworkManager;
- import net.jxta.socket.JxtaMulticastSocket;
- import org.eclipse.jface.action.Action;
- import org.eclipse.jface.action.IMenuListener;
- import org.eclipse.jface.action.IMenuManager;
- import org.eclipse.jface.action.MenuManager;
- import org.eclipse.jface.dialogs.MessageDialog;
- import org.eclipse.jface.viewers.DoubleClickEvent;
- import org.eclipse.jface.viewers.IDoubleClickListener;
- import org.eclipse.jface.viewers.ISelection;
- import org.eclipse.jface.viewers.IStructuredContentProvider;
- import org.eclipse.jface.viewers.IStructuredSelection;
- import org.eclipse.jface.viewers.ITableLabelProvider;
- import org.eclipse.jface.viewers.LabelProvider;
- import org.eclipse.jface.viewers.TableViewer;
- import org.eclipse.jface.viewers.Viewer;
- import org.eclipse.jface.window.ApplicationWindow;
- import org.eclipse.jface.window.Window;
- import org.eclipse.swt.SWT;
- import org.eclipse.swt.graphics.Image;
- import org.eclipse.swt.graphics.Point;
- import org.eclipse.swt.layout.FillLayout;
- import org.eclipse.swt.widgets.Composite;
- import org.eclipse.swt.widgets.Control;
- import org.eclipse.swt.widgets.Display;
- import org.eclipse.swt.widgets.Event;
- import org.eclipse.swt.widgets.Listener;
- import org.eclipse.swt.widgets.Menu;
- import org.eclipse.swt.widgets.MenuItem;
- import org.eclipse.swt.widgets.MessageBox;
- import org.eclipse.swt.widgets.Shell;
- import org.eclipse.swt.widgets.Tray;
- import org.eclipse.swt.widgets.TrayItem;
- import com.swtdesigner.SWTResourceManager;
- public class MainApplicationWindow extends ApplicationWindow {
- private static final Logger LOG = Logger.getLogger(MainApplicationWindow.class.getName());
- private TableViewer viewer;
-
- private NetworkManager manager = null;
- private PeerGroup pg = null;
-
- /** 保存当前用户激活的窗口对象 */
- @SuppressWarnings("unchecked")
- public static ConcurrentHashMap chatwin = new ConcurrentHashMap();
-
- /**
- * The content provider class is responsible for providing objects to the
- * view. It can wrap existing objects in adapters or simply return objects
- * as-is. These objects may be sensitive to the current input of the view,
- * or ignore it and always show the same content (like Task List, for
- * example).
- */
- class ViewContentProvider implements IStructuredContentProvider {
- public void inputChanged(Viewer v, Object oldInput, Object newInput) {
- }
- public void dispose() {
- }
- public Object[] getElements(Object parent) {
- return new String[] {};
- }
- }
- class ViewLabelProvider extends LabelProvider implements
- ITableLabelProvider {
- public String getColumnText(Object obj, int index) {
- return ((OnlineMessage)obj).getUserName();
- }
- public Image getColumnImage(Object obj, int index) {
- return getImage(obj);
- }
- public Image getImage(Object obj) {
- return SWTResourceManager.getImage(this.getClass(), "online.ico");
- }
- }
- /**
- * Create the application window
- */
- public MainApplicationWindow() {
- super(null);
- try {
- // TODO: Currently use EDGE mode configuration
- manager = new NetworkManager(NetworkManager.ConfigMode.EDGE, "JxtaMessenger");
- manager.startNetwork();
-
- // Here directly use NetPeerGroup for simplicity
- pg = manager.getNetPeerGroup();
- } catch (Exception e) {
- LOG.severe("JxtaMessenger initialize failed.");
- e.printStackTrace();
- System.exit(-1);
- }
- }
- /**
- * Create contents of the application window
- * @param parent
- */
- protected Control createContents(Composite parent) {
- Composite container = new Composite(parent, SWT.NONE);
- FillLayout layout = new FillLayout();
- layout.marginWidth = 3;
- layout.marginHeight = 3;
- container.setLayout(layout);
- viewer = new TableViewer(container, SWT.SINGLE | SWT.V_SCROLL);
- viewer.setContentProvider(new ViewContentProvider());
- viewer.setLabelProvider(new ViewLabelProvider());
- viewer.setInput(new ArrayList<OnlineMessage>());
- final Action fileAction = new Action() {
- @SuppressWarnings("unchecked")
- public void run() {
- ISelection selection = viewer.getSelection();
- OnlineMessage msg = (OnlineMessage)((IStructuredSelection)selection).getFirstElement();
- showMessage("Comming soon!");
- }
- };
- fileAction.setText("文件传输...");
-
- final Action chatAction = new Action() {
- @SuppressWarnings("unchecked")
- public void run() {
- ISelection selection = viewer.getSelection();
- OnlineMessage msg = (OnlineMessage)((IStructuredSelection)selection).getFirstElement();
- if(chatwin.containsKey(msg.getHostName())) {
- // The chat window has already existed
- ChatWindow chatWindow = (ChatWindow)chatwin.get(msg.getHostName());
- chatWindow.getShell().forceActive();
- } else {
- LOG.info("Chat window is opened.");
- Window chatWindow = new ChatWindow(viewer.getControl().getShell(), pg, msg);
- chatwin.put(msg.getHostName(), chatWindow);
- chatWindow.open();
- }
- }
- };
- chatAction.setText("交谈...");
-
- viewer.addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- chatAction.run();
- }
- });
- final MenuManager mgr = new MenuManager("#PopupMenu");
- mgr.setRemoveAllWhenShown(true);
- mgr.addMenuListener(new IMenuListener() {
- public void menuAboutToShow(IMenuManager manager) {
- IStructuredSelection selection = (IStructuredSelection)viewer.getSelection();
- if (!selection.isEmpty()) {
- mgr.add(chatAction);
- mgr.add(fileAction);
- }
- }
- });
- viewer.getControl().setMenu(mgr.createContextMenu(viewer.getControl()));
-
- // Now UI has initialized, Start service
- startService();
-
- // Multicast online message
- mcastOnlineMessage(pg);
- return container;
- }
- /**
- * Launch the application
- * @param args
- */
- public static void main(String args[]) {
- try {
- MainApplicationWindow window = new MainApplicationWindow();
- window.setBlockOnOpen(true);
- window.open();
- Display.getCurrent().dispose();
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- // TODO: Must call this so the program can terminated gracefully, why?
- // Some jxta none-daemon threads can not terminate, why?
- System.exit(0);
- }
- /**
- * Configure the shell
- * @param newShell
- */
- protected void configureShell(final Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("JxtaMessenger");
- newShell.setImage(SWTResourceManager.getImage(this.getClass(), "blue.ico"));
- /* TODO: System tray
- final Tray tray = newShell.getDisplay().getSystemTray();
- if (tray == null) {
- LOG.severe("The system tray is not available");
- System.exit(-1);
- } else {
- final TrayItem item = new TrayItem(tray, SWT.NONE);
- item.setToolTipText("JxtaMessenger");
- item.addListener(SWT.DefaultSelection, new Listener() {
- public void handleEvent(Event event) {
- if(!newShell.isVisible()) {
- newShell.setVisible(true);
- }
- if(newShell.getMinimized()) {
- newShell.setMinimized(false);
- }
- newShell.forceActive();
- }
- });
- final Menu menu = new Menu(newShell, SWT.POP_UP);
-
- // About
- MenuItem mi = new MenuItem(menu, SWT.PUSH);
- mi.setText("About...");
- mi.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event event) {
- int style = SWT.APPLICATION_MODAL | SWT.YES;
- MessageBox messageBox = new MessageBox (newShell, style);
- messageBox.setText ("关于本软件...");
- messageBox.setMessage ("email:cuizhenfu@gmail.comnmsn:cuizhf3000@hotmail.com");
- messageBox.open ();
- }
- });
-
- // separator
- mi = new MenuItem(menu, SWT.SEPARATOR);
-
- // Exit
- mi = new MenuItem(menu, SWT.PUSH);
- mi.setText("Exit");
- mi.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event event) {
- // 关闭应用程序
- close();
- }
- });
- menu.setDefaultItem(mi);
-
- item.addListener(SWT.MenuDetect, new Listener() {
- public void handleEvent(Event event) {
- menu.setVisible(true);
- }
- });
- item.setImage(SWTResourceManager.getImage(this.getClass(), "online.ico"));
- }*/
- }
- /**
- * Return the initial size of the window
- */
- protected Point getInitialSize() {
- return new Point(275, 400);
- }
- @SuppressWarnings("unchecked")
- public boolean close() {
- LOG.info("MainApplicationWindow close");
- if(!chatwin.isEmpty()) {
- Enumeration enumeration = chatwin.elements();
- if(enumeration.hasMoreElements()) {
- ChatWindow chatWindow = (ChatWindow)enumeration.nextElement();
- chatWindow.close();
- }
- }
- mcastOfflineMessage(pg);
- stopService();
- manager.stopNetwork();
- SWTResourceManager.dispose();
- return super.close();
- }
-
- // service array
- private Service[] service;
- private ExecutorService serviceExecutor;
- private void startService() {
- service = new Service[] {
- new JxtaMulticastSocketService(pg, viewer),
- new JxtaServerSocketService(pg, viewer)
- };
-
- serviceExecutor = Executors.newFixedThreadPool(service.length);
-
- for(int i=0; i<service.length; i++)
- serviceExecutor.execute(service[i]);
- }
-
- private void stopService() {
- for(int i=0; i<service.length; i++)
- service[i].shutdownAndAwaitTermination();
-
- ThreadPoolUtil.shutdownAndAwaitTermination(serviceExecutor);
- }
-
- /**
- * Multicast online message
- */
- private void mcastOnlineMessage(PeerGroup pg) {
- try {
- JxtaMulticastSocket mcastSocket = new JxtaMulticastSocket(pg, JxtaMulticastSocketService.getSocketAdvertisement(pg));
- String msg = XmlCreator.createOnlineMessage();
-
- DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.length());
- mcastSocket.send(packet);
- mcastSocket.close();
- } catch (IOException e) {
- LOG.warning("multicast peer node message failed");
- e.printStackTrace();
- }
- }
-
- /**
- * Multicast offline message
- */
- private void mcastOfflineMessage(PeerGroup pg) {
- try {
- JxtaMulticastSocket mcastSocket = new JxtaMulticastSocket(pg, JxtaMulticastSocketService.getSocketAdvertisement(pg));
- String msg = XmlCreator.createOfflineMessage();
-
- DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.length());
- mcastSocket.send(packet);
- mcastSocket.close();
- } catch (IOException e) {
- LOG.warning("multicast peer node message failed");
- e.printStackTrace();
- }
- }
- /* @Override
- protected void handleShellCloseEvent() {
- // super.handleShellCloseEvent();
- // TODO: Hide the main window, but child window hided too?
- this.getShell().setVisible(false);
- }*/
-
- private void showMessage(String message) {
- MessageDialog.openInformation(
- viewer.getControl().getShell(),
- "JxtaMessenger",
- message);
- }
- }