1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-07-25 09:55:29 +02:00

initial population

This commit is contained in:
David Dykstal 2006-04-10 20:02:23 +00:00
parent f05ff6fa0e
commit f73d913396
196 changed files with 27841 additions and 0 deletions

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View file

@ -0,0 +1 @@
bin

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.eclipse.dstore.core</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,22 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: %plugin.name
Bundle-SymbolicName: org.eclipse.dstore.core
Bundle-Version: 1.0.0
Bundle-Activator: org.eclipse.dstore.core.Activator
Bundle-Localization: plugin
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
org.eclipse.dstore.extra,
org.eclipse.ui.views
Eclipse-LazyStart: true
Export-Package: org.eclipse.dstore.core,
org.eclipse.dstore.core.client,
org.eclipse.dstore.core.java,
org.eclipse.dstore.core.miners.miner,
org.eclipse.dstore.core.model,
org.eclipse.dstore.core.server,
org.eclipse.dstore.core.util,
org.eclipse.dstore.core.util.ssl
Bundle-Vendor: Eclipse.org
Bundle-ClassPath: dstore_core.jar

View file

@ -0,0 +1,22 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
<title>About</title>
<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1">
</head>
<body lang="EN-US">
<h2>About This Content</h2>
<p>February 24, 2005</p>
<h3>License</h3>
<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the
Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>.
For purposes of the EPL, &quot;Program&quot; will mean the Content.</p>
<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may
apply to your use of any object code in the Content. Check the Redistributor's license that was provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
indicated below, the terms and conditions of the EPL still apply to any source code in the Content.</p>
</body>
</html>

View file

@ -0,0 +1,10 @@
bin.includes = plugin.properties,\
about.html,\
META-INF/, \
serverscripts/
source.dstore_core.jar = src/
output.dstore_core.jar = bin/
src.includes = about.html,\
plugin.properties,\
META-INF/,\
serverscripts/

View file

@ -0,0 +1,12 @@
###############################################################################
# Copyright (c) 2000, 2006 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
plugin.name = RSE Dstore Core

View file

@ -0,0 +1,57 @@
#!/usr/bin/perl -w
use Shell;
if (!defined($ARGV[0]) || !defined($ARGV[1]) || !defined($ARGV[2]) || !defined($ARGV[3]) || !defined($ARGV[4]))
{
print("command usage:\n");
print("auth.pl USER, PATH, PORT, TIMEOUT, TICKET\n");
}
else
{
$userIN = $ARGV[0];
$pathIN = $ARGV[1];
$portIN = $ARGV[2];
$timeoutIN = $ARGV[3];
$ticketIN = $ARGV[4];
$pwdIN = <STDIN>;
chomp($pwdIN);
@passwdStruct = getpwnam($userIN);
if (@passwdStruct == 0)
{
print("invalid user name\n");
0;
}
else
{
$passwd=$passwdStruct[1];
$encryptedPWD = crypt($pwdIN, $passwd);
$classpath=$ENV{CLASSPATH};
$suOptions="-lp";
if ($passwd eq $encryptedPWD)
{
print("success\n");
$os = uname();
chomp($os);
if (lc($os) eq "aix")
{
$suOptions="-";
}
system("su $suOptions $userIN -c 'java -cp $classpath -DA_PLUGIN_PATH=$pathIN org.eclipse.dstore.core.server.Server $portIN $timeoutIN $ticketIN -Xshareclasses:name=RSE,verbose'");
1;
}
else
{
print("incorrect password\n");
0;
}
}
}

View file

@ -0,0 +1,45 @@
#!/usr/bin/perl -w
$port = "4035";
$helpFlag = "-h";
if (defined($ARGV[0]))
{
$port = $ARGV[0];
}
$isHelp = $helpFlag cmp $port;
if ($isHelp == 0)
{
print("command usage:\n");
print("daemon.linux [<port> | <low port>-<high port>]\n");
0;
}
else
{
$trace = $ENV{DSTORE_TRACING_ON};
$user=`whoami`; chomp($user);
$match = $user cmp "root";
if ($match != 0)
{
print("To run the server daemon, you must be root\n");
0;
}
else
{
$dir= $ENV{PWD};
$plugins_dir=$dir;
$ENV{A_PLUGIN_PATH}="$plugins_dir/";
$oldClasspath = $ENV{CLASSPATH};
$ENV{"CLASSPATH"}="$plugins_dir:$plugins_dir/dstore_extra_server.jar:$plugins_dir/dstore_core.jar:$plugins_dir/dstore_miners.jar:$plugins_dir/universalminers.jar:$plugins_dir/clientserver.jar:$oldClasspath";
system("java -DA_PLUGIN_PATH=\$A_PLUGIN_PATH -DDSTORE_TRACING_ON=$trace org.eclipse.dstore.core.server.ServerLauncher $port");
$ENV{CLASSPATH}=$oldClasspath;
}
}

View file

@ -0,0 +1,2 @@
java -DA_PLUGIN_PATH=%A_PLUGIN_PATH% org.eclipse.dstore.core.server.ServerLauncher

View file

@ -0,0 +1 @@
java -DA_PLUGIN_PATH=%A_PLUGIN_PATH% org.eclipse.dstore.core.server.Server 4033 120000

View file

@ -0,0 +1,41 @@
################################################################################
# Copyright (c) 2006 IBM Corporation. All rights reserved.
# This program and the accompanying materials are made available under the terms
# of the Eclipse Public License v1.0 which accompanies this distribution, and is
# available at http://www.eclipse.org/legal/epl-v10.html
#
# Initial Contributors:
# The following IBM employees contributed to the Remote System Explorer
# component that contains this file: David McKnight, Kushal Munir,
# Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
# Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
#
# Contributors:
# {Name} (company) - description of contribution.
################################################################################
#
# SSL Security Properties for RSE server and daemon
#
# Specify this property as true to enable SSL
enable_ssl=false
###################################
# Daemon Properties
###################################
# The keystore file and password need to be specified for daemon
# to use.
#
#daemon_keystore_file=
#daemon_keystore_password=
###################################
# Server Properties
###################################
# The keystore file and password need to be specified for the
# server to use. If none is specified, the server falls back
# to use the same keystore and password as the daemon
#
#server_keystore_file=
#server_keystore_password=

View file

@ -0,0 +1,70 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The main plugin class to be used in the desktop.
*/
public class Activator extends AbstractUIPlugin {
//The shared instance.
private static Activator plugin;
/**
* The constructor.
*/
public Activator() {
plugin = this;
}
/**
* This method is called upon plug-in activation
*/
public void start(BundleContext context) throws Exception {
super.start(context);
}
/**
* This method is called when the plug-in is stopped
*/
public void stop(BundleContext context) throws Exception {
super.stop(context);
plugin = null;
}
/**
* Returns the shared instance.
*/
public static Activator getDefault() {
return plugin;
}
/**
* Returns an image descriptor for the image file at the given
* plug-in relative path.
*
* @param path the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return AbstractUIPlugin.imageDescriptorFromPlugin("org.eclipse.dstore.core", path);
}
}

View file

@ -0,0 +1,57 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.client;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.eclipse.dstore.core.model.DataStoreAttributes;
/**
* ClientAttributes is a container of communication related
* information.
*/
public class ClientAttributes extends DataStoreAttributes
{
/**
* Constructor
*/
public ClientAttributes()
{
super();
try
{
String pluginPath = System.getProperty("A_PLUGIN_PATH");
if ((pluginPath != null) && (pluginPath.length() > 0))
{
setAttribute(A_PLUGIN_PATH, pluginPath + File.separator);
}
setAttribute(A_LOCAL_NAME, InetAddress.getLocalHost().getHostName());
setAttribute(A_LOCAL_PATH, "/tmp/");
setAttribute(A_HOST_NAME, "local");
setAttribute(A_HOST_PATH, "/");
}
catch (UnknownHostException e)
{
}
}
}

View file

@ -0,0 +1,371 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.client;
import org.eclipse.dstore.core.java.IRemoteClassInstance;
import org.eclipse.dstore.core.model.CommandHandler;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
import org.eclipse.dstore.core.model.DataStoreResources;
import org.eclipse.dstore.core.util.Sender;
/**
* The ClientCommandHandler is reponsible for maintaining
* a queue of commands and periodically sending commands
* from the queue to the server side.
*/
public class ClientCommandHandler extends CommandHandler
{
private Sender _sender;
protected DataElement _requestClassDocumentElement;
protected DataElement _keepAliveDocumentElement;
protected DataElement _confirmKeepAliveDocumentElement;
protected DataElement _pendingKeepAliveRequest;
protected DataElement _pendingKeepAliveConfirmation;
private static String[] _docAttributes = {
DataStoreResources.DOCUMENT_TYPE,
"client.doc.root.id",
"client.document",
"doc",
"",
"",
DataStoreResources.FALSE,
"2"};
private static String[] _fileAttributes = {
DataStoreResources.FILE_TYPE,
"client.file.root.id",
"client.file",
"doc",
"",
"",
DataStoreResources.FALSE,
"2"};
private static String[] _classAttributes = {
DataStoreResources.CLASS_TYPE,
"client.class.root.id",
"client.class",
"doc",
"",
"",
DataStoreResources.FALSE,
"2"};
private static String[] _serializeAttributes = {
DataStoreResources.SERIALIZED_TYPE,
"client.serialized.root.id",
"client.serialized",
"doc",
"",
"",
DataStoreResources.FALSE,
"2"};
private static String[] _requestClassAttributes = {
DataStoreResources.REQUEST_CLASS_TYPE,
"client.requestclass.root.id",
"client.requestclass",
"doc",
"",
"",
DataStoreResources.FALSE,
"2"};
private static String[] _keepAliveAttributes = {
DataStoreResources.KEEPALIVE_TYPE,
"client.keepalive.root.id",
"server.keepalive",
"doc",
"",
"",
DataStoreResources.FALSE,
"2"};
private static String[] _confirmKeepAliveAttributes = {
DataStoreResources.KEEPALIVECONFIRM_TYPE,
"client.keepalive.confirm.root.id",
"server.confirmkeepalive",
"doc",
"",
"",
DataStoreResources.FALSE,
"2"};
protected DataElement _fileDocumentElement;
protected DataElement _docDocumentElement;
protected DataElement _classDocumentElement;
protected DataElement _serializedDocumentElement;
/**
* Constructor
* @param sender the Sender
*/
public ClientCommandHandler(Sender sender)
{
super();
_sender = sender;
}
public void setDataStore(DataStore dataStore)
{
super.setDataStore(dataStore);
_fileDocumentElement = dataStore.createTransientObject(_fileAttributes);
_docDocumentElement = dataStore.createObject(null, _docAttributes);
_classDocumentElement = dataStore.createTransientObject(_classAttributes);
_serializedDocumentElement = dataStore.createTransientObject(_serializeAttributes);
_requestClassDocumentElement = dataStore.createTransientObject(_requestClassAttributes);
_keepAliveDocumentElement = dataStore.createTransientObject(_keepAliveAttributes);
_confirmKeepAliveDocumentElement = dataStore.createTransientObject(_confirmKeepAliveAttributes);
}
/**
* Transmits the bytes of a file from the client to the server
* @param bytes the bytes of a file to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes as binary or unicode
* @param bytesStreamHandlerId indicates wwhich byte stream handler should receive the bytes
*/
public synchronized void sendFile(String fileName, byte[] bytes, int size, boolean binary, String byteStreamHandlerId)
{
// send pending commands before file
if (_commands.size() > 0)
sendCommands();
//DataElement document = _dataStore.createObject(null, DataStoreResources.FILE_TYPE, byteStreamHandlerId, fileName, fileName);
DataElement document = _fileDocumentElement;
document.setAttribute(DE.A_NAME, byteStreamHandlerId);
document.setAttribute(DE.A_VALUE, byteStreamHandlerId);
document.setAttribute(DE.A_SOURCE, fileName);
document.setPendingTransfer(true);
document.setParent(null);
_sender.sendFile(document, bytes, size, binary);
}
/**
* Transmits the bytes of a file from the client to the server
* @param bytes the bytes of a file to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes as binary or unicode
*/
public synchronized void sendFile(String fileName, byte[] bytes, int size, boolean binary)
{
sendFile(fileName, bytes, size, binary, "default");
}
/**
* Appends bytes of a file from the client to the server
* @param bytes the bytes of a file to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes as binary or unicode
* @param byteStreamHandlerId indicates which byte stream handler should receive the bytes
*/
public synchronized void sendAppendFile(String fileName, byte[] bytes, int size, boolean binary, String byteStreamHandlerId)
{
// send pending commands before file
if (_commands.size() > 0)
sendCommands();
//DataElement document = _dataStore.createObject(null, DataStoreResources.FILE_TYPE, byteStreamHandlerId, fileName, fileName);
DataElement document = _fileDocumentElement;
document.setAttribute(DE.A_NAME, byteStreamHandlerId);
document.setAttribute(DE.A_VALUE, byteStreamHandlerId);
document.setAttribute(DE.A_SOURCE, fileName);
document.setPendingTransfer(true);
document.setParent(null);
_sender.sendAppendFile(document, bytes, size, binary);
}
/**
* Appends bytes of a file from the client to the server
* @param bytes the bytes of a file to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes as binary or unicode
*/
public synchronized void sendAppendFile(String fileName, byte[] bytes, int size, boolean binary)
{
sendAppendFile(fileName, bytes, size, binary, "default");
}
/**
* Called periodically to send the current queue of commands to the server
*/
public synchronized void sendCommands()
{
//DataElement commandRoot = _dataStore.createObject(null, DataStoreResources.DOCUMENT_TYPE, "client.doc"/*"client.doc." + _requests++*/);
DataElement commandRoot = _docDocumentElement;
commandRoot.removeNestedData();
commandRoot.setPendingTransfer(true);
commandRoot.setParent(null);
while (_commands.size() > 0)
{
DataElement command = null;
//synchronized (_commands)
{
command = (DataElement)_commands.remove(0);
}
commandRoot.addNestedData(command, false);
}
_sender.sendDocument(commandRoot, 3);
if (_pendingKeepAliveConfirmation != null)
{
_sender.sendKeepAliveConfirmation(_pendingKeepAliveConfirmation);
_pendingKeepAliveConfirmation = null;
}
if (_pendingKeepAliveRequest != null)
{
_sender.sendKeepAliveRequest(_pendingKeepAliveRequest);
_pendingKeepAliveRequest = null;
}
// finished sending commands, now send all classes that are waiting
// in the queue
while (_classesToSend != null && _classesToSend.size() > 0)
{
DataElement document = null;
synchronized (_classesToSend)
{
document = (DataElement)_classesToSend.remove(0);
}
_sender.sendClass(document);
}
}
public void handle()
{
if (!_commands.isEmpty() || _pendingKeepAliveConfirmation != null || _pendingKeepAliveRequest != null || !_classesToSend.isEmpty())
{
sendCommands();
}
}
/**
* Implemented to provide the means by which classes are sent
* across the comm channel.
* @param className the name of the class to send
* @param classbyteStreamHandlerId the name of the byte stream handler to use to receive the class
*/
public synchronized void sendClass(String className, String classbyteStreamHandlerId)
{
// send pending commands before sending class
if (_commands.size() > 0)
sendCommands();
DataElement document = _classDocumentElement;
document.setAttribute(DE.A_NAME, className);
document.setAttribute(DE.A_SOURCE, classbyteStreamHandlerId);
//document.setAttribute(DE.A_SOURCE, className);
document.setPendingTransfer(true);
document.setParent(null);
addClassToSend(document);
}
/**
* Implemented to provide the means by which classes are requested and sent
* across the comm channel.
* @param className the name of the class to send
*/
public synchronized void sendClass(String className)
{
sendClass(className, "default");
}
/**
* Adds a class to the queue of classes (represented by DataElements) to
* be sent to the server.
* @param classElement the DataElement representing the class to be sent
*/
public void addClassToSend(DataElement classElement)
{
synchronized (_classesToSend)
{
if (!_classesToSend.contains(classElement))
{
_classesToSend.add(classElement);
}
}
notifyInput();
}
public synchronized void sendClassInstance(IRemoteClassInstance runnable, String deserializebyteStreamHandlerId)
{
// send pending commands before sending class
if (_commands.size() > 0)
sendCommands();
DataElement document = _serializedDocumentElement;
document.setAttribute(DE.A_NAME, runnable.toString());
document.setAttribute(DE.A_SOURCE, deserializebyteStreamHandlerId);
document.setPendingTransfer(true);
document.setParent(null);
_sender.sendRemoteClassRunnable(document, runnable);
}
/**
* Implemented to provide the means by which classes are requested
* across the comm channel.
* @param className the name of the class to request
*/
public void requestClass(String className)
{
DataElement document = _requestClassDocumentElement;
document.setPendingTransfer(true);
document.setAttribute(DE.A_NAME, className);
document.setAttribute(DE.A_VALUE, className);
document.setParent(null);
_sender.requestClass(document);
}
public void sendKeepAliveConfirmation()
{
DataElement document = _confirmKeepAliveDocumentElement;
document.setPendingTransfer(true);
document.setAttribute(DE.A_NAME, "confirm");
document.setAttribute(DE.A_VALUE, "confirm");
document.setParent(null);
_pendingKeepAliveConfirmation = document;
}
public void sendKeepAliveRequest()
{
DataElement document = _keepAliveDocumentElement;
document.setPendingTransfer(true);
document.setAttribute(DE.A_NAME, "request");
document.setAttribute(DE.A_VALUE, "request");
document.setParent(null);
_pendingKeepAliveRequest = document;
}
}

View file

@ -0,0 +1,848 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import org.eclipse.dstore.core.model.CommandHandler;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
import org.eclipse.dstore.core.model.DataStoreAttributes;
import org.eclipse.dstore.core.model.ISSLProperties;
import org.eclipse.dstore.core.server.ServerCommandHandler;
import org.eclipse.dstore.core.server.ServerLauncher;
import org.eclipse.dstore.core.util.ExternalLoader;
import org.eclipse.dstore.core.util.Sender;
import org.eclipse.dstore.core.util.ssl.DStoreSSLContext;
import org.eclipse.dstore.core.util.ssl.DataStoreTrustManager;
import org.eclipse.dstore.extra.internal.extra.DomainNotifier;
/**
* ClientConnection provides the standard means of creating a new connection to
* a DataStore.
*
* <li>
* If a connection is local, then a DataStore is instantiated
* in the same process to be used by the client to communicate with miners (tools).
* </li>
*
* <li>
* If a connection is not local, then a virtual DataStore is instantiated in the
* current process to communicate with the remote DataStore. If the client wishes
* to instantiate a remote DataStore through a daemon, then ClientConnection first connects
* to the daemon requesting a DataStore at a given port, and then connects to the
* newly launched DataStore. Otherwise, a DataStore is expected to be running on
* the remote machine under the same port that the client tries to connect to.
* </li>
*
*
*/
public class ClientConnection
{
private ClientAttributes _clientAttributes;
private Socket _theSocket;
private boolean _isConnected = false;
private boolean _isRemote = false;
private DataStore _dataStore;
private DomainNotifier _domainNotifier;
private Sender _sender;
private ClientReceiver _receiver;
private ClientUpdateHandler _updateHandler;
private CommandHandler _commandHandler;
private int _clientVersion;
private int _clientMinor;
private String _name;
private String _host;
private String _port;
private String _hostDirectory;
private DataStoreTrustManager _trustManager;
private ArrayList _loaders;
private static final int HANDSHAKE_INCORRECT = 0;
private static final int HANDSHAKE_SERVER_OLDER = 1;
private static final int HANDSHAKE_CORRECT = 2;
private static final int HANDSHAKE_UNEXPECTED = 3;
private static final int HANDSHAKE_SERVER_NEWER = 4;
private static final int HANDSHAKE_SERVER_RECENT_OLDER = 5;
private static final int HANDSHAKE_SERVER_RECENT_NEWER = 6;
private static final int VERSION_INDEX_PROTOCOL = 0;
private static final int VERSION_INDEX_VERSION = 1;
private static final int VERSION_INDEX_MINOR = 2;
public static String INCOMPATIBLE_SERVER_UPDATE = "Incompatible DataStore.";
public static String INCOMPATIBLE_CLIENT_UPDATE = "Incompatible DataStore.";
public static String SERVER_OLDER = "Older DataStore Server.";
public static String CLIENT_OLDER = "Older DataStore Client.";
public static String INCOMPATIBLE_PROTOCOL = "Incompatible Protocol.";
/**
* Creates a new ClientConnection instance
*
* @param name an identifier for this connection
*/
public ClientConnection(String name)
{
_domainNotifier = new DomainNotifier();
_name = name;
init();
}
/**
* Creates a new ClientConnection instance
*
* @param name an identifier for this connection
* @param initialSize the number of elements to preallocate in the DataStore
*/
public ClientConnection(String name, int initialSize)
{
_domainNotifier = new DomainNotifier();
_name = name;
init(initialSize);
}
/**
* Creates a new ClientConnection instance
*
* @param name an identifier for this connection
* @param notifier the notifier used to keep the user interface in synch with the DataStore
*/
public ClientConnection(String name, DomainNotifier notifier)
{
_domainNotifier = notifier;
_name = name;
init();
}
/**
* Creates a new ClientConnection instance
*
* @param name an identifier for this connection
* @param notifier the notifier used to keep the user interface in synch with the DataStore
* @param initialSize the number of elements to preallocate in the DataStore
*/
public ClientConnection(String name, DomainNotifier notifier, int initialSize)
{
_domainNotifier = notifier;
_name = name;
init(initialSize);
}
public int getClientVersion()
{
return _clientVersion;
}
public int getClientMinor()
{
return _clientMinor;
}
public int getServerVersion()
{
return _dataStore.getServerVersion();
}
public int getServerMinor()
{
return _dataStore.getServerMinor();
}
public void setSSLProperties(ISSLProperties properties)
{
_dataStore.setSSLProperties(properties);
}
/**
* Specifies the loaders used to instantiate the miners
*
* @param loaders the loaders
*/
public void setLoaders(ArrayList loaders)
{
_loaders = loaders;
}
/**
* Adds a loader to be used to instantiate the miners
*
* @param loader the loader
*/
public void addLoader(ExternalLoader loader)
{
if (_loaders == null)
{
_loaders = new ArrayList();
}
_loaders.add(loader);
}
/**
* Specifies the hostname or IP of the host to connect to
*
* @param host the hostname or IP of the machine to connect to
*/
public void setHost(String host)
{
_host = host;
_clientAttributes.setAttribute(DataStoreAttributes.A_HOST_NAME, _host);
}
/**
* Specifies the number of the socket port to connect to
*
* @param port the number of the socket port to connect to
*/
public void setPort(String port)
{
if (port == null || port.length() == 0)
{
port = "0";
}
_port = port;
_clientAttributes.setAttribute(DataStoreAttributes.A_HOST_PORT, _port);
}
/**
* Specifies the default working directory on the remote machine
*
* @param directory the remote working directory
*/
public void setHostDirectory(String directory)
{
_hostDirectory = directory;
_clientAttributes.setAttribute(DataStoreAttributes.A_HOST_PATH, _hostDirectory);
}
/**
* Returns the hostname/IP of the host to connect to
*
* @return the hostname/IP
*/
public String getHost()
{
return _host;
}
/**
* Returns the number of the socket port to connect to
*
* @return the number of the socket port to connect to
*/
public String getPort()
{
return _port;
}
/**
* Returns the default working directory on the host machine
*
* @return the working directory on the host
*/
public String getHostDirectory()
{
return _hostDirectory;
}
/**
* Indicates whether the client is connected to the DataStore
*
* @return whether the client is connected
*/
public boolean isConnected()
{
if (_isConnected)
{
return _dataStore.isConnected();
}
return _isConnected;
}
/**
* Disconnects from the DataStore and cleans up DataStore meta-information
*/
public void disconnect()
{
if (_isConnected)
{
_dataStore.setConnected(false);
if (_isRemote)
{
_commandHandler.command(
_dataStore.find(_dataStore.getRoot(), DE.A_NAME, "Exit"),
_dataStore.getHostRoot(),
false);
_receiver.finish();
}
_commandHandler.finish();
try
{
Thread.sleep(200);
}
catch (InterruptedException e)
{
System.out.println(e);
}
_updateHandler.finish();
_dataStore.finish();
_isConnected = false;
}
}
/**
* Creates and connects to a local DataStore to work with in the current process.
*
* @return the status of the DataStore connection
*/
public ConnectionStatus localConnect()
{
_updateHandler = new ClientUpdateHandler();
_updateHandler.start();
if (_loaders == null)
{
_loaders = new ArrayList();
_loaders.add(new ExternalLoader(getClass().getClassLoader(), "*"));
}
_commandHandler = new ServerCommandHandler(_loaders);
_commandHandler.start();
_dataStore.setCommandHandler(_commandHandler);
_dataStore.setUpdateHandler(_updateHandler);
_dataStore.setConnected(true);
_dataStore.setLoaders(_loaders);
_dataStore.getDomainNotifier().enable(true);
_commandHandler.setDataStore(_dataStore);
_updateHandler.setDataStore(_dataStore);
((ServerCommandHandler) _commandHandler).loadMiners();
_clientAttributes.setAttribute(
DataStoreAttributes.A_LOCAL_NAME,
_clientAttributes.getAttribute(DataStoreAttributes.A_HOST_NAME));
_clientAttributes.setAttribute(
DataStoreAttributes.A_LOCAL_PATH,
_clientAttributes.getAttribute(DataStoreAttributes.A_HOST_PATH));
_isConnected = true;
DataElement ticket = _dataStore.getTicket();
ticket.setAttribute(DE.A_NAME, "null");
ConnectionStatus result = new ConnectionStatus(_isConnected);
result.setTicket(ticket.getName());
return result;
}
/**
* Connects to a remote DataStore by first communicating with a remote daemon and then
* connecting to the DataStore.
*
* @param launchServer an indication of whether to launch a DataStore on the daemon on not
* @param user the user ID of the current user on the remote machine
* @param password the password of the current user on the remote machine
* @return the status of the connection
*/
public ConnectionStatus connect(boolean launchServer, String user, String password)
{
ConnectionStatus launchStatus = null;
if (launchServer)
{
launchStatus = launchServer(user, password);
if (!launchStatus.isConnected())
{
return launchStatus;
}
}
else
{
launchStatus = new ConnectionStatus(true);
launchStatus.setTicket("null");
}
return connect(launchStatus.getTicket());
}
public DataStoreTrustManager getTrustManager()
{
if (_trustManager == null)
{
_trustManager = new DataStoreTrustManager();
}
return _trustManager;
}
/**
* Connects to a remote DataStore.
* A socket is created and the virtual DataStore is initialized with an update handler, command handler,
* socket sender and socket receiver.
*
* @param ticket the ticket required to be granted access to the remote DataStore
* @return the status of the connection
*/
public ConnectionStatus connect(String ticket)
{
return connect(ticket, -1);
}
public ConnectionStatus connect(String ticket, int timeout)
{
boolean doTimeOut = (timeout > 0);
ConnectionStatus result = null;
try
{
int port = 0;
if (_port != null && _port.length() > 0)
{
port = Integer.parseInt(_port);
}
if (_dataStore.usingSSL())
{
String location = _dataStore.getKeyStoreLocation();
String pw = _dataStore.getKeyStorePassword();
DataStoreTrustManager mgr = getTrustManager();
SSLContext context = DStoreSSLContext.getClientSSLContext(location, pw, mgr);
SSLSocketFactory factory = context.getSocketFactory();
_theSocket = factory.createSocket(_host, port);
if (doTimeOut && (_theSocket != null))
_theSocket.setSoTimeout(timeout);
try
{
((SSLSocket) _theSocket).startHandshake();
SSLSession session = ((SSLSocket) _theSocket).getSession();
}
catch (SSLHandshakeException e)
{
result = new ConnectionStatus(false, e, true, mgr.getUntrustedCerts());
return result;
}
catch (Exception e)
{
e.printStackTrace();
_theSocket.close();
result = new ConnectionStatus(false, e);
return result;
}
}
else
{
_theSocket = new Socket(_host, port);
if (doTimeOut && (_theSocket != null))
_theSocket.setSoTimeout(timeout);
}
String msg = null;
int handshakeResult = doHandShake();
switch (handshakeResult)
{
case HANDSHAKE_CORRECT:
result = doConnect(ticket);
break;
case HANDSHAKE_SERVER_RECENT_NEWER:
result = doConnect(ticket);
result.setMessage(CLIENT_OLDER);
break;
case HANDSHAKE_SERVER_RECENT_OLDER:
result = doConnect(ticket);
result.setMessage(SERVER_OLDER);
break;
case HANDSHAKE_SERVER_NEWER:
{
msg = INCOMPATIBLE_CLIENT_UPDATE;
msg += "\nThe server running on "
+ _host
+ " under port "
+ _port
+ " is a newer DataStore server.";
break;
}
case HANDSHAKE_SERVER_OLDER:
{
msg = INCOMPATIBLE_SERVER_UPDATE;
msg += "\nThe server running on "
+ _host
+ " under port "
+ _port
+ " is an older DataStore server.";
break;
}
case HANDSHAKE_INCORRECT:
{
msg = INCOMPATIBLE_PROTOCOL;
msg += "\nThe server running on "
+ _host
+ " under port "
+ _port
+ " is not a valid DataStore server.";
break;
}
case HANDSHAKE_UNEXPECTED:
{
msg = "Unexpected exception";
break;
}
default:
break;
}
if (result == null && msg != null)
{
result = new ConnectionStatus(false, msg);
}
}
catch (java.net.ConnectException e)
{
String msg = "Connection Refused.";
msg += "\nMake sure that the DataStore server is running on " + _host + " under port " + _port + ".";
result = new ConnectionStatus(false, msg);
}
catch (UnknownHostException uhe)
{
_isConnected = false;
result = new ConnectionStatus(_isConnected, uhe);
}
catch (IOException ioe)
{
_isConnected = false;
result = new ConnectionStatus(_isConnected, ioe);
}
return result;
}
protected ConnectionStatus doConnect(String ticket)
{
_sender = new Sender(_theSocket, _dataStore);
_updateHandler = new ClientUpdateHandler();
_updateHandler.start();
_commandHandler = new ClientCommandHandler(_sender);
_commandHandler.start();
_dataStore.setCommandHandler(_commandHandler);
_dataStore.setUpdateHandler(_updateHandler);
_dataStore.setConnected(true);
_dataStore.getDomainNotifier().enable(true);
_commandHandler.setDataStore(_dataStore);
_updateHandler.setDataStore(_dataStore);
_receiver = new ClientReceiver(_theSocket, _dataStore);
_receiver.start();
_isConnected = true;
_isRemote = true;
ConnectionStatus result = new ConnectionStatus(_isConnected);
result.setTicket(ticket);
return result;
}
/**
* Connects to a remote daemon and tells the daemon to launch
* a DataStore server.
*
* @param user the user ID of the current user on the remote machine
* @param password the password of the current user on the remote machine
* @return the status of the connection
*/
public ConnectionStatus launchServer(String user, String password)
{
// default daemon port is 4035
return launchServer(user, password, ServerLauncher.DEFAULT_DAEMON_PORT);
}
/**
* Connects to a remote daemon and tells the daemon to launch
* a DataStore server.
*
* @param user the user ID of the current user on the remote machine
* @param password the password of the current user on the remote machine
* @param daemonPort the port of the daemon
* @return the status of the connection
*/
public ConnectionStatus launchServer(String user, String password, int daemonPort)
{
ConnectionStatus result = null;
try
{
Socket launchSocket = null;
if (_dataStore.usingSSL())
{
try
{
String location = _dataStore.getKeyStoreLocation();
String pw = _dataStore.getKeyStorePassword();
DataStoreTrustManager mgr = getTrustManager();
SSLContext context = DStoreSSLContext.getClientSSLContext(location, pw, mgr);
try
{
SocketFactory factory = context.getSocketFactory();
SSLSocket lSocket = (SSLSocket) factory.createSocket(_host, daemonPort);
launchSocket = lSocket;
lSocket.startHandshake();
SSLSession session = lSocket.getSession();
if (session == null)
{
System.out.println("handshake failed");
lSocket.close();
}
}
catch (SSLHandshakeException e)
{
result = new ConnectionStatus(false, e, true, mgr.getUntrustedCerts());
return result;
}
catch (Exception e)
{
if (launchSocket != null)
{
launchSocket.close();
}
e.printStackTrace();
result = new ConnectionStatus(false, e);
return result;
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
launchSocket = new Socket(_host, daemonPort);
}
PrintWriter writer = null;
BufferedReader reader = null;
// create output stream for server launcher
try
{
writer = new PrintWriter(new OutputStreamWriter(launchSocket.getOutputStream(), DE.ENCODING_UTF_8));
writer.println(user);
writer.println(password);
writer.println(_port);
writer.flush();
reader = new BufferedReader(new InputStreamReader(launchSocket.getInputStream(), DE.ENCODING_UTF_8));
String status = reader.readLine();
if (status != null && !status.equals("connected"))
{
result = new ConnectionStatus(false, status);
}
else
{
result = new ConnectionStatus(true);
_port = reader.readLine();
String ticket = reader.readLine();
result.setTicket(ticket);
}
}
catch (java.io.IOException e)
{
e.printStackTrace();
result = new ConnectionStatus(false, e);
}
if (reader != null)
reader.close();
if (writer != null)
writer.close();
launchSocket.close();
}
catch (java.net.ConnectException e)
{
String msg = "Connection Refused.";
msg += "\nMake sure that the DataStore daemon is running on " + _host + ".";
result = new ConnectionStatus(false, msg);
}
catch (UnknownHostException uhe)
{
result = new ConnectionStatus(false, uhe);
}
catch (IOException ioe)
{
System.out.println(ioe);
ioe.printStackTrace();
result = new ConnectionStatus(false, ioe);
}
return result;
}
/**
* Returns the DataStore that the client is connected to.
* @return the DataStore
*/
public DataStore getDataStore()
{
return _dataStore;
}
private void init()
{
init(10000);
}
private void init(int initialSize)
{
_clientAttributes = new ClientAttributes();
_clientAttributes.setAttribute(DataStoreAttributes.A_ROOT_NAME, _name);
_dataStore = new DataStore(_clientAttributes, initialSize);
_dataStore.setDomainNotifier(_domainNotifier);
_dataStore.createRoot();
_host = _clientAttributes.getAttribute(DataStoreAttributes.A_HOST_NAME);
_hostDirectory = _clientAttributes.getAttribute(DataStoreAttributes.A_HOST_PATH);
_port = _clientAttributes.getAttribute(DataStoreAttributes.A_HOST_PORT);
String[] clientVersionStr = DataStoreAttributes.DATASTORE_VERSION.split("\\.");
_clientVersion = Integer.parseInt(clientVersionStr[VERSION_INDEX_VERSION]);
_clientMinor = Integer.parseInt(clientVersionStr[VERSION_INDEX_MINOR]);
}
private int doHandShake()
{
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(_theSocket.getInputStream(), DE.ENCODING_UTF_8));
String handshake = reader.readLine();
_theSocket.setSoTimeout(0);
String[] clientVersionStr = DataStoreAttributes.DATASTORE_VERSION.split("\\.");
String[] serverVersionStr = handshake.split("\\.");
_dataStore.setServerVersion(Integer.parseInt(serverVersionStr[VERSION_INDEX_VERSION]));
_dataStore.setServerMinor(Integer.parseInt(serverVersionStr[VERSION_INDEX_MINOR]));
if (handshake.equals(DataStoreAttributes.DATASTORE_VERSION))
{
return HANDSHAKE_CORRECT;
}
else
{
if (handshake.startsWith("<DataElement"))
{
return HANDSHAKE_SERVER_OLDER;
}
else if (serverVersionStr[VERSION_INDEX_PROTOCOL].equals(clientVersionStr[VERSION_INDEX_PROTOCOL]))
{
if (_dataStore.getServerVersion()== _clientVersion)
{
// major versions match so should be compatible
return HANDSHAKE_CORRECT;
}
else
{
if (_dataStore.getServerVersion()> _clientVersion)
{
// newer server
if (_dataStore.getServerVersion() - 1 == _clientVersion)
{
return HANDSHAKE_SERVER_RECENT_NEWER;
}
else
{
return HANDSHAKE_SERVER_NEWER;
}
}
else
{
// newer client
if (_dataStore.getServerVersion() + 1 == _clientVersion)
{
return HANDSHAKE_SERVER_RECENT_OLDER;
}
else
{
return HANDSHAKE_SERVER_OLDER;
}
}
}
}
else
{
System.out.println("handshake=" + handshake);
return HANDSHAKE_INCORRECT;
}
}
}
catch (Exception e)
{
return HANDSHAKE_UNEXPECTED;
}
}
}

View file

@ -0,0 +1,77 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.client;
import java.net.Socket;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
import org.eclipse.dstore.core.util.Receiver;
/*
* The ClientReciever is responsible for recieving data from
* the server side.
*/
public class ClientReceiver extends Receiver
{
/**
* Constructor
*/
public ClientReceiver(Socket socket, DataStore dataStore)
{
super(socket, dataStore);
}
/**
* Called when new data is received from the server side.
* @param documentObject the root object of incoming data
*/
public void handleDocument(DataElement documentObject)
{
if (documentObject.getName().equals("exit"))
{
_canExit = true;
}
else
{
synchronized (documentObject)
{
for (int i = 0; i < documentObject.getNestedSize(); i++)
{
DataElement rootOutput = documentObject.get(i);
_dataStore.refresh(rootOutput);
}
documentObject.removeNestedData();
//_dataStore.deleteObject(documentObject.getParent(), documentObject);
}
}
}
/**
* Called when an error occurs
* @param e the exception that occurred
*/
public void handleError(Throwable e)
{
DataElement status = _dataStore.getStatus();
status.setAttribute(DE.A_NAME, e.getMessage());
_dataStore.refresh(status);
_dataStore.setConnected(false);
}
}

View file

@ -0,0 +1,77 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.client;
import org.eclipse.dstore.core.model.ISSLProperties;
public class ClientSSLProperties implements ISSLProperties
{
private boolean _enableSSL = false;
private String _daemonKeyStorePath;
private String _daemonKeyStorePassword;
private String _serverKeyStorePath;
private String _serverKeyStorePassword;
public ClientSSLProperties(boolean enableSSL,
String daemonKeystore, String daemonPassword,
String serverKeystore, String serverPassword)
{
_enableSSL = enableSSL;
_daemonKeyStorePath = daemonKeystore;
_daemonKeyStorePassword = daemonPassword;
_serverKeyStorePath = serverKeystore;
_serverKeyStorePassword = serverPassword;
}
public ClientSSLProperties(boolean enableSSL, String keystore, String password)
{
_enableSSL = enableSSL;
_daemonKeyStorePath = keystore;
_daemonKeyStorePassword = password;
_serverKeyStorePath = keystore;
_serverKeyStorePassword = password;
}
public boolean usingSSL()
{
return _enableSSL;
}
public String getDaemonKeyStorePassword()
{
return _daemonKeyStorePassword;
}
public String getDaemonKeyStorePath()
{
return _daemonKeyStorePath;
}
public String getServerKeyStorePassword()
{
return _serverKeyStorePassword;
}
public String getServerKeyStorePath()
{
return _serverKeyStorePath;
}
}

View file

@ -0,0 +1,190 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.client;
import java.io.File;
import org.eclipse.dstore.core.java.IRemoteClassInstance;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.UpdateHandler;
import org.eclipse.dstore.extra.internal.extra.DomainEvent;
import org.eclipse.dstore.extra.internal.extra.IDomainNotifier;
/**
* The ClientUpdateHandler is contains a queue of data update requests
* and periodically sends out domain notifications to domain listeners
*/
public class ClientUpdateHandler extends UpdateHandler
{
/**
* Constructor
*/
public ClientUpdateHandler()
{
super();
_waitIncrement = 200;
}
/**
* Not applicable - this is only applicable on the server side
*/
public void updateFile(String path, byte[] bytes, int size, boolean binary)
{
}
/**
* Not applicable - this is only applicable on the server side
*/
public void updateAppendFile(String path, byte[] bytes, int size, boolean binary)
{
}
/**
* Not applicable - this is only applicable on the server side
*/
public void updateFile(String path, byte[] bytes, int size, boolean binary, String byteStreamHandlerId)
{
}
/**
* Not applicable - this is only applicable on the server side
*/
public void updateAppendFile(String path, byte[] bytes, int size, boolean binary, String byteStreamHandlerId)
{
}
/**
* Notifies domain listeners that a file has been updated
* @param file the updated file
* @param object the element associated with the updated file
*/
public void updateFile(File file, DataElement object)
{
IDomainNotifier notifier = _dataStore.getDomainNotifier();
notifier.fireDomainChanged(new DomainEvent(DomainEvent.FILE_CHANGE, object, DE.P_NESTED));
}
/**
* Periodically called to notify domain listeners of updated data from the
* server
*/
public void sendUpdates()
{
if (_dataStore != null && !isFinished())
{
IDomainNotifier notifier = _dataStore.getDomainNotifier();
while (_dataObjects.size() > 0)
{
DataElement object = null;
synchronized (_dataObjects)
{
if (_dataObjects.size() > 0)
{
object = (DataElement) _dataObjects.get(0);
_dataObjects.remove(object);
}
}
if ((object != null))
{
if (!object.isUpdated() && !object.isDescriptor())
{
//DataElement parent = object.getParent();
//System.out.println("notifying "+parent);
notify(object);
}
clean(object);
}
}
}
}
private void notify(DataElement object)
{
if (object.isExpanded())
{
object.setUpdated(true);
}
object.setExpanded(true);
IDomainNotifier notifier = _dataStore.getDomainNotifier();
if (object.getNestedSize() == 0)
{
notifier.fireDomainChanged(new DomainEvent(DomainEvent.NON_STRUCTURE_CHANGE, object, DE.P_NESTED));
}
else
{
notifier.fireDomainChanged(new DomainEvent(DomainEvent.INSERT, object, DE.P_NESTED));
}
}
/**
* Implemented to provide the means by which classes are requested
* across the comm channel. (Only applies to ServerUpdateHandler, so is a dummy method here)
* @param className the name of the class to request
*/
public void requestClass(String className)
{
}
/**
* Impleted to provide the means by which a class on the host is updated on the client
* @param runnable
* @param deserializebyteStreamHandlerId
*/
public synchronized void updateClassInstance(IRemoteClassInstance runnable, String deserializebyteStreamHandlerId)
{
notifyInput();
}
/**
* Does not apply in this case. Use ClientCommandHandler.sendClass().
*/
public void sendClass(String className, String classByteStreamHandlerId)
{
}
/**
* Does not apply in this case. Use ClientCommandHandler.sendClass().
*/
public void sendClass(String className)
{
}
/**
* Does not apply in this case. Use ClientCommandHandler.sendKeepAliveRequest().
*/
public void sendKeepAliveRequest()
{
}
/**
* Does not apply in this case. Use ClientCommandHandler.sendKeepAliveConfirmation().
*/
public void sendKeepAliveConfirmation()
{
}
}

View file

@ -0,0 +1,150 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.client;
import java.util.List;
/**
* ConnectionStatus represents the state of a connection. This class is
* used for feedback, when a client attempts to connect to a server.
*/
public class ConnectionStatus
{
private boolean _connected;
private Throwable _exception;
private String _message;
private String _ticket;
private boolean _SSLProblem = false;
private List _untrustedCertificates;
/**
* Constructor
* @param connected indicates whether a connection has been made
*/
public ConnectionStatus(boolean connected)
{
_connected = connected;
}
/**
* Constructor
* @param connected indicates whether a connection has been made
* @param e the exception that occurred when attempting to connect
*/
public ConnectionStatus(boolean connected, Throwable e)
{
_connected = connected;
_exception = e;
_message = e.toString();
}
/**
* Constructor
* @param connected indicates whether a connection has been made
* @param msg a connection error message
*/
public ConnectionStatus(boolean connected, String msg)
{
_connected = connected;
_message = msg;
}
public ConnectionStatus(boolean connected, Throwable e, boolean sslProblem, List untrustedCerts)
{
_connected = connected;
_exception = e;
_message = e.toString();
_SSLProblem = sslProblem;
_untrustedCertificates = untrustedCerts;
}
/**
* Sets whether the connection is successful or not
* @param flag indication of whether the connection is successful
*/
public void setConnected(boolean flag)
{
_connected = flag;
}
/**
* Sets the connection error message
* @param message the error message
*/
public void setMessage(String message)
{
_message = message;
}
/**
* Sets the ticket to use when connecting to a server. Typically,
* a ticket gets sent back from a server daemon so that the client
* can be granted access to the launched server DataStore
* @param ticket the ticket
*/
public void setTicket(String ticket)
{
_ticket = ticket;
}
/**
* Indicates whether the connection was successful or not
* @return whether the connection was successful or not
*/
public boolean isConnected()
{
return _connected;
}
/**
* Returns the error message for a connection attempt
* @return the error message
*/
public String getMessage()
{
return _message;
}
/**
* Returns the ticket required for connecting to a server
* @return the ticket
*/
public String getTicket()
{
return _ticket;
}
/*
* Returns the exception if there is one
* @return the exception
*/
public Throwable getException()
{
return _exception;
}
public boolean isSLLProblem()
{
return _SSLProblem;
}
public List getUntrustedCertificates()
{
return _untrustedCertificates;
}
}

View file

@ -0,0 +1,211 @@
/********************************************************************************
* Copyright (c) 2005, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.java;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
/**
* <p>
* The ClassByteStreamHandler class is used to abstract classfile read and write operations
* across the network. By default this is used for sending and receiving class files
* on the client and the server. The class can be extended if the default byte stream
* implementations are not sufficient for a particular platform or use.
* </p>
* <p>
* If ClassByteStreamHandler is extended, you need to tell the DataStore to use the
* extended implementation. To do that, call <code>DataStore.setClassByteStreamHandler(ClassByteStreamHandler)</code>.
* </p>
*
*/
public class ClassByteStreamHandler implements IClassByteStreamHandler
{
protected DataStore _dataStore;
protected DataElement _log;
protected static final String FILEMSG_REMOTE_SAVE_FAILED = "RSEF5006";
/**
* Contructor
* @param dataStore the DataStore instance
* @param the log in which to log status and messages
*/
public ClassByteStreamHandler(DataStore dataStore, DataElement log)
{
_dataStore = dataStore;
_log = log;
}
public String getIdentifier()
{
return getClass().getName();
}
/**
* Receive a class and load it. This method is called by the
* DataStore when the communication layer receives a class file transfer
* This method kicks off a new thread so that the receiver thread can be free
* to receive other data.
*
* @param className the name of the class to receive
* @param buffer the bytes that comprise the class
* @param size the number of bytes in the class
*/
public void receiveBytes(String className, byte[] buffer, int size)
{
ReceiveClassThread rct = new ReceiveClassThread(className, buffer, size);
rct.start();
}
/**
* Receive a class instance and load it. This method is called by the
* DataStore when the communication layer receives a class file transfer
* This method kicks off a new thread so that the receiver thread can be free
* to receive other data.
*
* @param buffer the bytes that comprise the class instance
* @param size the number of bytes in the class instance
*/
public void receiveInstanceBytes(byte[] buffer, int size)
{
ReceiveClassInstanceThread rct = new ReceiveClassInstanceThread(buffer, size);
rct.start();
}
protected DataElement findStatusFor(String remotePath)
{
if (_log != null)
{
for (int i = 0; i < _log.getNestedSize(); i++)
{
DataElement child = _log.get(i);
if (child.getName().equals(remotePath))
{
return child;
}
}
}
return null;
}
/**
* A new thread that can be spawned to receive the class
*
*/
protected class ReceiveClassThread extends Thread
{
private String _className;
private byte[] _buffer;
private int _size;
public ReceiveClassThread(String className, byte[] buffer, int size)
{
_className = className;
_buffer = buffer;
_size = size;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run()
{
RemoteClassLoader remoteLoader = new RemoteClassLoader(_dataStore);
remoteLoader.receiveClass(_className, _buffer, _size);
}
}
/**
* A new thread that can be spawned to receive the class
*
*/
protected class ReceiveClassInstanceThread extends Thread
{
private byte[] _buffer;
private int _size;
public ReceiveClassInstanceThread(byte[] buffer, int size)
{
_buffer = buffer;
_size = size;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run()
{
try
{
PipedInputStream ins = new PipedInputStream();
PipedOutputStream outStream = new PipedOutputStream(ins);
outStream.write(_buffer, 0, _size);
outStream.flush();
outStream.close();
IRemoteClassInstance instance = loadInstance(ins);
runInstance(instance);
}
catch (Exception e)
{
e.printStackTrace();
}
}
protected IRemoteClassInstance loadInstance(InputStream ins)
{
ObjectInputStream inStream = null;
try
{
inStream = new RemoteObjectInputStream(ins, _dataStore.getRemoteClassLoader());
return (IRemoteClassInstance)inStream.readObject();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void runInstance(IRemoteClassInstance instance)
{
if (_dataStore.isVirtual())
{
// on client notify
instance.updatedOnClient();
}
else
{
// on server run and update client
instance.arrivedOnServer();
_dataStore.updateRemoteClassInstance(instance, getIdentifier());
}
}
}
}

View file

@ -0,0 +1,78 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.java;
import java.util.HashMap;
import org.eclipse.dstore.core.model.DataStoreResources;
public class ClassByteStreamHandlerRegistry
{
private HashMap _map;
private IClassByteStreamHandler _default;
public ClassByteStreamHandlerRegistry()
{
_map = new HashMap();
}
/**
* Registers the default class byte stream handler
* @param handler the default byte stream handler
*/
public void setDefaultClassByteStreamHandler(IClassByteStreamHandler handler)
{
_default = handler;
_map.put(DataStoreResources.DEFAULT_CLASSBYTESTREAMHANDLER, handler);
registerClassByteStreamHandler(handler);
}
/**
* Registers a class byte stream handler.
* @param handler the handler to register
*/
public void registerClassByteStreamHandler(IClassByteStreamHandler handler)
{
_map.put(handler.getIdentifier(), handler);
}
/**
* Returns the class byte stream handler with the specified id.
* If "default" is specified or no such id has been registered,
* the default byte stream handler is returned.
* @param id the id of the byte stream handler
* @return the byte stream handler
*/
public IClassByteStreamHandler getClassByteStreamHandler(String id)
{
IClassByteStreamHandler handler = (IClassByteStreamHandler)_map.get(id);
if (handler == null)
{
handler = _default;
}
return handler;
}
/**
* Returns the default class byte stream handler
* @return the default
*/
public IClassByteStreamHandler getDefault()
{
return _default;
}
}

View file

@ -0,0 +1,29 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.java;
import java.io.IOException;
import java.io.OutputStream;
public class ClassInstanceOutputStream extends OutputStream {
public void write(int b) throws IOException {
// TODO Auto-generated method stub
}
}

View file

@ -0,0 +1,141 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.java;
/**
* Represents a remote class request in the RemoteClassLoader. Contains
* methods for getting the status of the request, as well as getting the
* actual class after it has been loaded.
* @author mjberger
*
*/
public class ClassRequest
{
private boolean _requested;
private boolean _loaded;
private boolean _synchronous;
private String _className;
private Class _class = null;
/**
* Constructs a new ClassRequest
* @param className The name of the class requested
* @param Thread optional thread that requested the class
* @param synchronous whether or not the request is synchronous
*/
public ClassRequest(String className, boolean synchronous)
{
_synchronous = synchronous;
_className = className;
_requested = false;
_loaded = false;
}
/**
* Causes the current thread to wait until this class request has been
* fulfilled.
*/
public synchronized void waitForResponse()
{
try
{
if (!_loaded) wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
/**
* Causes all threads waiting for this class request to be filled
* to wake up.
*/
public synchronized void notifyResponse()
{
notifyAll();
}
/**
* Returns the class loaded, or null if it has not been loaded yet.
*/
public Class getLoadedClass()
{
return _class;
}
/**
* Returns whether or not the class has been loaded yet.
*/
public boolean isLoaded()
{
return _loaded;
}
/**
* Returns the name of the class requested/loaded.
*/
public String getClassName()
{
return _className;
}
/**
* Returns whether or not the class has been requested yet.
*/
public boolean isRequested()
{
return _requested;
}
/**
* Returns whether or not the class request is synchronous.
*/
public boolean isSynchronous()
{
return _synchronous;
}
/**
* Call this method when the request for the class has been sent.
*/
public void setRequested(boolean requested)
{
_requested = requested;
}
/**
* Call this method when the class has been received and loaded.
*/
public void setLoaded(boolean loaded)
{
_loaded = loaded;
}
/**
* Sets the class represented by this object after it has been loaded.
* (Sets loaded to be true and requested to be false). Notifies all threads
* waiting on this class request that the class has been loaded.
*/
public synchronized void setLoadedClass(Class loadedClass)
{
_class = loadedClass;
setRequested(false);
setLoaded(true);
notifyAll();
}
}

View file

@ -0,0 +1,54 @@
/********************************************************************************
* Copyright (c) 2003, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.java;
/**
* <p>
* The IClassByteStreamHandler interface is used to abstract file read and write operations
* across the network.
*
*/
public interface IClassByteStreamHandler
{
/**
* Returns the unique ID for this bytestream handler
* @return the unique id
*/
public String getIdentifier();
/**
* Receive a class and load it. This method is called by the
* DataStore when the communication layer receives a class file transfer
* This method kicks off a new thread so that the receiver thread can be free
* to receive other data.
*
* @param className the name of the class to receive
* @param buffer the bytes that comprise the class
* @param size the number of bytes in the class
*/
public void receiveBytes(String className, byte[] buffer, int size);
/**
* Save a class instance in the specified location. Invokes the operation in a new thread. This method is called by the
* DataStore when the communication layer receives a class file transfer
*
* @param buffer the bytes to insert in the class instance
* @param size the number of bytes to insert
*/
public void receiveInstanceBytes(byte[] buffer, int size);
}

View file

@ -0,0 +1,25 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.java;
import java.io.Serializable;
public interface IRemoteClassInstance extends Serializable
{
public void arrivedOnServer();
public void updatedOnClient();
}

View file

@ -0,0 +1,54 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.java;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.util.List;
public class LocalObjectInputStream extends ObjectInputStream {
private List _localLoaders;
public LocalObjectInputStream(InputStream in, List localLoaders) throws IOException
{
super(in);
_localLoaders = localLoaders;
}
protected Class resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException
{
ClassNotFoundException ex = null;
String name = desc.getName();
for (int i = 0; i < _localLoaders.size(); i++)
{
ClassLoader cl = (ClassLoader)_localLoaders.get(i);
try
{
return cl.loadClass(name);
}
catch (ClassNotFoundException e)
{
ex = e;
}
}
throw ex;
}
}

View file

@ -0,0 +1,486 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.java;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import org.eclipse.dstore.core.model.DataStore;
/**
* This class loads a class from a remote peer.
* This classloader is used just as any other classloader is used. However,
* when instantiating the RemoteClassLoader, a DataStore is associated with
* it. The RemoteClassLoader goes through the following steps when trying to load
* a class:
* 1) Attempts to load the class from memory. Any class that had been loaded
* already this session would reside here.
* 2) Attempts to find the class using its parent classloader.
* 3) If caching preference is turned on:
* a) Attempts to find the class from the disk cache.
* 4) Requests the class, through the DataStore, from the remote peer. Waits for
* response.
* 5) If class cannot be found, throws ClassNotFoundException
* 6) If class is found, loads the class.
* 7) If caching preference is turned on:
* a) Caches new class in the disk cache for use in the next session.
* Notes:
* i) If there are one or more classes on which the target class depends,
* the RemoteClassLoader will attempt to load those classes too (possibly remotely),
* before loading the target class.
* ii) Since most implementations of Java use lazy classloading, the JVM may not
* attempt to load all required classes for the target class during class definition
* or instantiation. However, if the RemoteClassLoader was used to load the target
* class, then at any time, any additional classes required by the target class will
* be loaded using the RemoteClassLoader. Clients should be aware that this could trigger
* class requests and class transfers during the operation of objects of the target class,
* not just during definition and instantiation of it.
* iii) On the remote peer side, if you wish a class to be a candidate for transfer using the
* RemoteClassLoader on the opposite side of the connection, you MUST register the classloader
* for that class with the DataStore corresponding to the DataStore with which the RemoteClassLoader
* was instantiated. For example, in a client-server connection there is a "client" DataStore and a
* corresponding "server" DataStore. Suppose the server wishes to use the RemoteClassLoader to load
* class A from the client. Suppose A is loaded on the client using ClassLoaderForA. On the client
* side, ClassLoaderForA must be registered with the "client" DataStore so that when the
* class request for A comes in from the server, the client DataStore know how to load class A.
*
* Caching:
* To set your preference for caching, on either the client or server DataStore, use the following command:
* _dataStore.setPreference(RemoteClassLoader.CACHING_PREFERENCE, "true");
* The cache of classes is kept in a jar in the following directory:
* $HOME/.eclipse/RSE/rmt_classloader_cache.jar
* To clear the cache, you must delete the jar.
*
* Threading Issues:
* It's safest to use the RemoteClassLoader on a separate thread, and preferably not
* from the CommandHandler or UpdateHandler threads. The RemoteClassLoader uses those
* threads to request and send the class. However, DataStore commands can be structured such that
* safe use of the RemoteClassLoader on these threads is possible. See below for an
* example.
*
* Using the RemoteClassLoader in your subsystem miner:
* Suppose you want the client to be able to kick off a class request in your host subsystem
* miner. In order to accomplish this, you would take the following steps:
* 1) Add a command to your miner in the extendSchema() method.
* 2) Add logic in the handleCommand() method to route command to another method when handleCommand
* receives your new command.
* 3) In your command handling method, get the name of the class to load from the subject
* DataElement.
* 4) Load the class using the RemoteClassLoader.
* 5) Make sure the class you are attempting to load exists on the client and that class's
* ClassLoader is registered with the DataStore!
*
* @author mjberger
*
*/
public class RemoteClassLoader extends ClassLoader
{
public static String CACHING_PREFERENCE = "Class.Caching";
private DataStore _dataStore;
private boolean _useCaching = false;
private CacheClassLoader _urlClassLoader;
private class CacheClassLoader extends URLClassLoader
{
public CacheClassLoader(URL[] urls, ClassLoader parent)
{
super(urls, parent);
}
public Class findCachedClass(String className) throws ClassNotFoundException
{
return super.findClass(className);
}
}
/**
* Constructor
* @param dataStore A reference to the datastore to be used by this
* RemoteClassLoader.
*/
public RemoteClassLoader(DataStore dataStore)
{
super(dataStore.getClass().getClassLoader());
//_urlClassLoader = new URLClassLoader(new URL[0]);
_dataStore = dataStore;
useCaching();
}
public boolean useCaching()
{
boolean useCaching = false;
String pref = _dataStore.getPreference(CACHING_PREFERENCE);
if (pref != null && pref.equals("true"))
{
useCaching = true;
}
if (useCaching != _useCaching)
{
if (useCaching && _dataStore.getRemoteClassLoaderCache() != null)
{
try
{
URL cache = _dataStore.getRemoteClassLoaderCache().toURL();
URL[] urls = new URL[] { cache };
_urlClassLoader = new CacheClassLoader(urls, this);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
}
}
_useCaching = useCaching;
return _useCaching;
}
/**
* Finds the specified class. If the class cannot be found locally,
* a synchronous request for the class is sent to the client, and the calling thread
* waits for a response. If the client can find the class, it sends it back to
* the server. The server receives the class in a new thread, defines it, and
* then notifies this thread. The class is then returned by this method. If the class
* cannot be found, the client notifies the server, and this method throws a
* ClassNotFoundException.
* @param className the fully qualified classname to find
* @return the loaded class
* @throws ClassNotFoundException if the class cannot be found on either the client or the server.
*
*/
protected Class findClass(String className) throws ClassNotFoundException
{
System.out.println("finding "+className);
// first try using the datastore's local classloaders
ArrayList localLoaders = _dataStore.getLocalClassLoaders();
if (localLoaders != null)
{
Class theClass = null;
for (int i = 0; i < localLoaders.size(); i++)
{
try
{
theClass = ((ClassLoader)localLoaders.get(i)).loadClass(className);
if (theClass != null) return theClass;
}
catch (Exception e)
{
}
}
}
// next delegate the search to the superclass's find method.
try
{
Class theClass = super.findClass(className);
if (theClass != null)
{
System.out.println("Using super's: " + className);
return theClass;
}
}
catch (Exception e)
{
}
// DKM
// only do lookup if the classname looks valid
// don't want to be requesting rsecomm from client
if (className.indexOf('.') == -1)
{
throw new ClassNotFoundException(className);
}
// if it cannot be found:
// search the class request repository to see if the class has been requested
// already
ClassRequest request;
request = (ClassRequest) _dataStore.getClassRequestRepository().get(className);
if (request == null)
{
// the class has not been requested before
// try to look in the disk cache first
if (useCaching())
{
try
{
Class theClass = _urlClassLoader.findCachedClass(className);
System.out.println("Using cached: " + className);
return theClass;
}
catch (Throwable e)
{
// its not in the disk cache, so request it synchronously
return requestClass(className);
}
}
else
{
return requestClass(className);
}
}
else if (!request.isLoaded())
{
// the class has been requested before, but it has not yet been received
// System.out.println(className + " already requested but not loaded. Waiting for request to load.");
request.waitForResponse(); // just wait until the class is received
// after the class is received, get it from the repository and return it
// or if the class failed to be received, throw an exception
if (request.isLoaded()) return request.getLoadedClass();
else throw new ClassNotFoundException(className);
}
else if (request.isLoaded())
{
// the class has been requested before, and has already been received and loaded,
// so just return it.
return request.getLoadedClass();
}
// if we ever get to this point, the class has not been found,
// throw the exception
else throw new ClassNotFoundException(className);
}
/**
* Receives a class sent by a remote agent and loads it.
* Notifies all threads waiting for this class to load that the
* class has been loaded.
* @param className the name of the class to receive
* @param bytes the bytes in the class
* @param the size of the class
*/
public synchronized void receiveClass(String className, byte[] bytes, int size)
{
// System.out.println("receiving "+className);
// check the class request repository to see if the class is there
ClassRequest request = (ClassRequest) _dataStore.getClassRequestRepository().get(className);
if (request != null)
{
if (request.isLoaded()) return; // do not attempt to reload the class
}
if (size == 0)
{
// this is the signal that the class could not be found on the client
// System.out.println("Empty class/class not found: "+className);
// System.out.println("notifying requester");
request.notifyResponse(); // wake up the threads waiting for the class
return;
}
Class receivedClass = null;
try
{
// System.out.println("defining "+className+"...");
// try to define the class. If any dependent classes cannot be
// found the JRE implementation will call findClass to look for them.
// Thus we could end up with a stack of requests all waiting until the
// classes with no dependent classes load.
receivedClass = defineClass(className, bytes, 0, size);
// System.out.println("...finished defining "+className);
}
catch (NoClassDefFoundError e)
{
// the JRE implementation could not find a dependent class.
// (even after requesting it from the client). We must fail,
// but wake up the threads waiting for this class.
e.printStackTrace();
request.notifyResponse();
return;
}
catch (LinkageError e)
{
// this happens when the system tries to redefine a class.
// dont try to redefine the class, just reload it.
e.printStackTrace();
try
{
receivedClass = loadClass(className);
}
catch (NoClassDefFoundError err)
{
// we shouldn't really get here unless it has tried
// already to find the class on the client but couldnt,
// so we might as well just fail here and notify threads waiting
// for this class to load.
err.printStackTrace();
request.notifyResponse();
return;
}
catch (ClassNotFoundException ee)
{
// we definitely shouldnt get here
request.notifyResponse();
return;
}
// if after trying to define or trying to load the class
// we still dont have it, notify the threads and fail.
if (receivedClass == null)
{
request.notifyResponse();
return;
}
}
if (request == null)
{
// not used right now, this is the case where a class was sent by
// the client without us requesting it.
request = new ClassRequest(className, false);
request.setLoadedClass(receivedClass);
_dataStore.getClassRequestRepository().put(className, request);
return;
}
else
{
// SUCCESS! The class has been received, and defined, so just
// load it into the class request object. This action will
// also notify threads waiting for the class
// System.out.println("notifying requesters");
request.setLoadedClass(receivedClass);
if (useCaching())
{
_dataStore.cacheClass(className, bytes, size);
}
}
}
/**
* Kicks off a separate thread in which to request the class,
* rather than doing it synchronously.
* @param className The fully qualified name of the class to request.
*/
protected void requestClassInThread(String className)
{
// System.out.println("requesting (in thread)"+className);
LoadClassThread thread = new LoadClassThread(className);
thread.start();
}
/**
* Requests a class (synchronously) from the client
* @param className The fully qualified name of the class to request.
* @return the requested class
* @throws ClassNotFoundException if the class was not found on the client
*/
public Class requestClass(String className) throws ClassNotFoundException
{
// first check to see if the class has been requested before
// System.out.println("requesting "+className);
ClassRequest request;
request = (ClassRequest) _dataStore.getClassRequestRepository().get(className);
if (request == null)
{
// the class has not been requested yet, create a new ClassRequest
// object to represent it
request = new ClassRequest(className, true);
_dataStore.getClassRequestRepository().put(className, request);
request.setRequested(true);
// put in the request for the class
_dataStore.requestClass(className);
// wait for a response
// System.out.println("thread to wait: "+Thread.currentThread().getName());
if (!request.isLoaded()) request.waitForResponse();
// System.out.println("thread finished waiting: "+Thread.currentThread().getName());
if (request.isLoaded()) return request.getLoadedClass();
else throw new ClassNotFoundException(className);
}
else if (!request.isLoaded())
{
// class has already been requested, wait for it to load
// System.out.println("requested elsewhere, thread to wait: "+Thread.currentThread().getName());
if (!request.isLoaded()) request.waitForResponse();
// System.out.println("requested elsewhere, thread finished waiting: "+Thread.currentThread().getName());
if (request.isLoaded()) return request.getLoadedClass();
else throw new ClassNotFoundException(className);
}
else if (request.isLoaded())
{
// class has already been requested and loaded, just return it
return request.getLoadedClass();
}
// we shouldnt really get to this point, but if we do, it means the class
// was not found.
throw new ClassNotFoundException(className);
}
/**
* Causes a new thread to start in which the specified class is loaded
* into the repository. This method usually returns before the class has been
* loaded.
* @param className The fully qualified name of the class to load
*/
public synchronized void loadClassInThread(String className)
{
// check if the class has been requested before
ClassRequest request;
request = (ClassRequest) _dataStore.getClassRequestRepository().get(className);
if (request == null)
{
// class has not been requested, request it in a thread
request = new ClassRequest(className, false);
_dataStore.getClassRequestRepository().put(className, request);
request.setRequested(true);
requestClassInThread(className);
return;
}
else if (!request.isLoaded())
{
// class has been requested already, but not loaded. Just return.
return;
}
else if (request.isLoaded())
{
// class has been requested already and already loaded. Just return.
return;
}
}
/**
* A new thread for loading classes in.
* @author mjberger
*
*/
protected class LoadClassThread extends Thread
{
private String _className;
public LoadClassThread(String className)
{
_className = className;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run()
{
_dataStore.requestClass(_className);
}
}
}

View file

@ -0,0 +1,39 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.java;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
public class RemoteObjectInputStream extends ObjectInputStream {
private RemoteClassLoader _loader;
public RemoteObjectInputStream(InputStream in, RemoteClassLoader loader) throws IOException
{
super(in);
_loader = loader;
}
protected Class resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException
{
String name = desc.getName();
return _loader.loadClass(name);
}
}

View file

@ -0,0 +1,670 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.miners.miner;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
import org.eclipse.dstore.core.model.DataStoreResources;
import org.eclipse.dstore.core.model.DataStoreSchema;
import org.eclipse.dstore.core.model.Handler;
import org.eclipse.dstore.core.model.ISchemaExtender;
import org.eclipse.dstore.core.util.ExternalLoader;
/**
* Miner is the abstact base class of all DataStore extensions).
* The DataStore framework knows how to load and route commands to miners
* because it interfaces miners through the restricted set of interfaces declared here.
* To add a new miner, developers must extend this class and implement the abstract methods declared here.
*/
public abstract class Miner extends Handler
implements ISchemaExtender
{
public DataStore _dataStore;
public DataElement _minerElement;
public DataElement _minerData;
public DataElement _minerTransient;
private boolean _initialized;
private boolean _connected;
private ExternalLoader _loader;
protected String _name = null;
protected String _value = null;
protected ArrayList _dependencies;
protected List _commandQueue;
protected ResourceBundle _resourceBundle = null;
/**
* Creates a new Miner
*/
protected Miner()
{
_initialized = false;
_connected = false;
_commandQueue = new ArrayList();
}
/**
* Returns the qualified names of all miners that
* this miner depends on. A miner depends on another
* miner if it's schema extends or uses another's schema.
* By default it returns an empty list.
* @return a list of miner dependencies, each represented as a qualified name
*/
public final ArrayList getMinerDependencies()
{
if (_dependencies == null)
{
_dependencies = getDependencies();
}
return _dependencies;
}
protected ArrayList getDependencies()
{
return new ArrayList();
}
/**
* Indicates whether the miner has been initialized yet
* @return whether the miner has been initialized
*/
public final boolean isInitialized()
{
return _initialized;
}
/**
* Indicates whether the miner has been connected to
* the DataStore yet.
* @return whether the miner has been connected to the DataStore
*/
public final boolean isConnected()
{
return _connected;
}
/**
* Shuts down the miner and cleans up it's meta-information.
* Override this function to do your own cleanup.
*/
public void finish()
{
DataElement root = _dataStore.getMinerRoot();
_minerData.removeNestedData();
_minerElement.removeNestedData();
_dataStore.update(_minerElement);
if (root.getNestedData() != null)
{
root.getNestedData().remove(_minerElement);
}
root.setExpanded(false);
root.setUpdated(false);
_dataStore.update(root);
}
/**
* Interface to retrieve an NL enabled resource bundle.
* Override this function to get access to a real resource bundle.
*/
public ResourceBundle getResourceBundle()
{
return null;
}
/**
* Default method that gets called on a Miner when it is loaded.
* Override this function to perform some initialization at miner loading time.
*/
protected void load()
{
}
/**
* Default method that gets called on a Miner when it is loaded.
* Override this function to perform some initialization at miner loading time.
* If loading the miner can result in some failure, set that status to incomplete
*
* @param status the status of the initialize miner command
*/
protected void load(DataElement status)
{
load();
}
/**
* This gets called after a miner is initialized.
* If you need to update element information at that time, override this method.
*/
protected void updateMinerInfo()
{
}
/**
* Returns the qualified name of this miner
*
* @return the qualified name of this miner
*/
public final String getMinerName()
{
if (_name == null)
_name = getClass().getName();
return _name;
}
/**
* Returns the name of this miner
*
* @return the name of this miner
*/
public final String getValue()
{
if (_value == null)
{
String name = getMinerName();
int indexOfValue = name.lastIndexOf(".");
_value = name.substring(indexOfValue + 1, name.length());
}
return _value;
}
public final void handle()
{
while (!_commandQueue.isEmpty())
{
DataElement cmd = (DataElement)_commandQueue.remove(0);
command(cmd);
}
}
public final void requestCommand(DataElement command)
{
_commandQueue.add(command);
notifyInput();
}
public final void initMiner(DataElement status)
{
try
{
// System.out.println("initMiner:"+getMinerName());
if (!_initialized)
{
load(status);
_initialized = true;
}
updateMinerInfo();
DataElement minerRoot = _dataStore.getMinerRoot();
_dataStore.refresh(minerRoot);
if (status.getAttribute(DE.A_VALUE).equals(DataStoreResources.model_incomplete))
{
_dataStore.refresh(status);
}
else
{
status.setAttribute(DE.A_VALUE, DataStoreResources.model_done);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Issues a specified command on this miner from the DataStore framework.
* The base class handles "C_INIT_MINERS" but other commands are delegated to
* the concrete miner implementations through handleCommand()
*
* @param command the command that has been sent to this miner
* @return the status of the command
*/
protected final DataElement command(DataElement command)
{
String name = getCommandName(command);
DataElement status = getCommandStatus(command);
long startTime = System.currentTimeMillis();
if (status == null)
{
_dataStore.trace("bad command: ");
_dataStore.trace("\tcmd=" + command);
_dataStore.trace("\tparent=" + command.getParent());
return null;
}
if (status.getAttribute(DE.A_NAME).equals("start"))
{
status.setAttribute(DE.A_NAME, DataStoreResources.model_working);
}
if (name.equals(DataStoreSchema.C_INIT_MINERS))
{
initMiner(status);
}
else
{
try
{
status = handleCommand(command);
}
catch (Exception e)
{
//e.printStackTrace();
_dataStore.trace(e);
status.setAttribute(DE.A_VALUE, "Failed with Exception:"+getStack(e));
status.setAttribute(DE.A_NAME, DataStoreResources.model_done);
//status.setAttribute(DE.A_SOURCE, getStack(e));
_dataStore.refresh(status);
String exc = null;
if (e.getMessage() != null)
exc = e.getMessage();
else
exc = "Exception";
DataElement exception = _dataStore.createObject(status, DataStoreResources.model_error, exc);
}
catch (Error er)
{
er.printStackTrace();
_dataStore.trace(er);
_dataStore.finish();
System.exit(-1);
}
}
_dataStore.refresh(status);
return status;
}
private String getStack(Throwable e)
{
StringBuffer buf = new StringBuffer();
StackTraceElement[] stack = e.getStackTrace();
for (int i = 0; i < stack.length; i++)
{
buf.append(stack[i].getClassName() + ":" + stack[i].getMethodName() + ":" + stack[i].getLineNumber());
buf.append(",");
}
return buf.toString();
}
/**
* Sets the DataStore and performs some fundamental initialization for this miner.
* The framework calls this method on a miner before any commands are issued.
* The extendSchema() is called on the miner.
*
* @param dataStore the DataStore that owns this miner
*/
public final void setDataStore(DataStore dataStore)
{
_dataStore = dataStore;
DataElement root = _dataStore.getMinerRoot();
String name = getMinerName();
String value = getValue();
_resourceBundle = getResourceBundle();
// yantzi: Reuse existing miner root if found
_minerElement = _dataStore.find(root, DE.A_NAME, name, 1);
if (_minerElement == null || _minerElement.isDeleted())
{
// Create new child for this miner
_minerElement = _dataStore.createObject(root, DataStoreResources.model_miner, name, name);
_minerElement.setAttribute(DE.A_VALUE, value);
_minerElement.setAttribute(DE.A_SOURCE, getVersion());
_minerData = _dataStore.createObject(_minerElement, DataStoreResources.model_data, DataStoreResources.model_Data, name);
_minerTransient = _dataStore.createObject(_minerElement, DataStoreResources.model_transient, DataStoreResources.model_Transient_Objects, name);
}
else
{
// Reuse existing miner node
_minerData = _dataStore.find(_minerElement, DE.A_NAME, DataStoreResources.model_Data, 1);
if (_minerData == null || _minerData.isDeleted())
{
_minerData = _dataStore.createObject(_minerElement, DataStoreResources.model_data, DataStoreResources.model_Data, name);
}
_minerTransient = _dataStore.find(_minerElement, DE.A_NAME, DataStoreResources.model_Transient_Objects, 1);
if (_minerTransient == null || _minerData.isDeleted())
{
_minerTransient = _dataStore.createObject(_minerElement, DataStoreResources.model_transient, DataStoreResources.model_Transient_Objects, name);
}
}
_dataStore.refresh(root, true);
_dataStore.refresh(_minerElement);
_connected = true;
}
/**
* Creates an abstract command descriptor. This is a helper method that miner may call
* when it creates or updates the schema for it's tool domain
*
* @param descriptor the parent descriptor for the new descriptor
* @param name the name of the command
* @param value the identifier for this command
* @return the new command descriptor
*/
public final DataElement createAbstractCommandDescriptor(DataElement descriptor, String name, String value)
{
return _dataStore.createAbstractCommandDescriptor(descriptor, name, getMinerName(), value);
}
/**
* Creates a command descriptor. This is a helper method that miner may call
* when it creates or updates the schema for it's tool domain
*
* @param descriptor the parent descriptor for the new descriptor
* @param name the name of the command
* @param value the identifier for this command
* @return the new command descriptor
*/
public final DataElement createCommandDescriptor(DataElement descriptor, String name, String value)
{
return createCommandDescriptor(descriptor, name, value, true);
}
/**
* Creates a command descriptor. This is a helper method that miner may call
* when it creates or updates the schema for it's tool domain
*
* @param descriptor the parent descriptor for the new descriptor
* @param name the name of the command
* @param value the identifier for this command
* @param visible an indication whether this command descriptor should be visible to an end-user
* @return the new command descriptor
*/
public final DataElement createCommandDescriptor(DataElement descriptor, String name, String value, boolean visible)
{
DataElement cmdD = _dataStore.createCommandDescriptor(descriptor, name, getMinerName(), value);
if (!visible)
{
cmdD.setDepth(0);
}
return cmdD;
}
/**
* Creates an abstract object descriptor. This is a helper method that miner may call
* when it creates or updates the schema for it's tool domain
*
* @param descriptor the parent descriptor for the new descriptor
* @param name the name of the object type
* @return the new object descriptor
*/
public final DataElement createAbstractObjectDescriptor(DataElement descriptor, String name)
{
return _dataStore.createAbstractObjectDescriptor(descriptor, name);
}
/**
* Creates an abstract object descriptor. This is a helper method that miner may call
* when it creates or updates the schema for it's tool domain
*
* @param descriptor the parent descriptor for the new descriptor
* @param name the name of the object type
* @param source the plugin location of the miner that owns this object type
* @return the new object descriptor
*/
public final DataElement createAbstractObjectDescriptor(DataElement descriptor, String name, String source)
{
return _dataStore.createAbstractObjectDescriptor(descriptor, name, source);
}
/**
* Creates a object descriptor. This is a helper method that miner may call
* when it creates or updates the schema for it's tool domain
*
* @param descriptor the parent descriptor for the new descriptor
* @param name the name of the object type
* @return the new object descriptor
*/
public final DataElement createObjectDescriptor(DataElement descriptor, String name)
{
return _dataStore.createObjectDescriptor(descriptor, name);
}
/**
* Creates a object descriptor. This is a helper method that miner may call
* when it creates or updates the schema for it's tool domain
*
* @param descriptor the parent descriptor for the new descriptor
* @param name the name of the object type
* @param source the plugin location of the miner that owns this object type
* @return the new object descriptor
*/
public final DataElement createObjectDescriptor(DataElement descriptor, String name, String source)
{
return _dataStore.createObjectDescriptor(descriptor, name, source);
}
/**
* Creates a new type of relationship descriptor. This is a helper method that miner may call
* when it creates or updates the schema for it's tool domain
*
* @param descriptor the parent descriptor for the new descriptor
* @param name the name of the relationship type
* @return the new relationship descriptor
*/
public final DataElement createRelationDescriptor(DataElement descriptor, String name)
{
return _dataStore.createRelationDescriptor(descriptor, name);
}
/**
* Creates an abstract relationship between two descriptors. An abstract relationship between two descriptors
* indicates that the first descriptor abstracts the second, while the second inherits the
* properties of the first. This is a helper method that miner may call
* when it creates or updates the schema for it's tool domain.
*
* @param from the abstacting descriptor
* @param to the descriptor that is abstracted
* @return the new relationship descriptor
*/
public final DataElement createAbstractRelationship(DataElement from, DataElement to)
{
return _dataStore.createReference(from, to, "abstracts", "abstracted by");
}
/**
* Creates a contents relationship between any two elements.
*
* @param from the containing element
* @param to the element that is contained
* @return the new relationship
*/
public final DataElement createReference(DataElement from, DataElement to)
{
return _dataStore.createReference(from, to);
}
/**
* Returns the element that represents this miner.
*
* @return the miner element
*/
public final DataElement getMinerElement()
{
return _minerElement;
}
/**
* Returns the element that contains this miners meta-information.
*
* @return the miner data element
*/
public final DataElement getMinerData()
{
return _minerData;
}
/**
* Returns the transient object container for this element.
*
* @return the transient element
*/
public final DataElement getMinerTransient()
{
return _minerTransient;
}
/**
* Identifies a give object descriptor type to be transient in this miner.
*
* @param objectDescriptor the object descriptor type that is transient
*/
public final void makeTransient(DataElement objectDescriptor)
{
_dataStore.createReference(_minerTransient, objectDescriptor);
}
/**
* Returns the name of a command.
* This is a helper method to be used inside handleCommand().
*
* @param command a tree of elements representing a command
* @return the name of the command
*/
public final String getCommandName(DataElement command)
{
return (String) command.getAttribute(DE.A_NAME);
}
/**
* Returns the status of a command.
* This is a helper method to be used inside handleCommand().
*
* @param command a tree of elements representing a command
* @return the status element for the command
*/
public final DataElement getCommandStatus(DataElement command)
{
//DKM - status is always last
return command.get(command.getNestedSize() - 1);
//_dataStore.find(command, DE.A_TYPE, DataStoreResources.model_status"), 1);
}
/**
* Returns the number of arguments for this command.
* This is a helper method to be used inside handleCommand().
*
* @param command a tree of elements representing a command
* @return the number of arguments for this command
*/
public final int getNumberOfCommandArguments(DataElement command)
{
return command.getNestedSize();
}
/**
* Returns the argument of a command specified at a given index.
* This is a helper method to be used inside handleCommand().
*
* @param command a tree of elements representing a command
* @param arg the index into the commands children
* @return the argument of the command
*/
public final DataElement getCommandArgument(DataElement command, int arg)
{
if (command.getNestedSize() > 0)
{
DataElement argument = command.get(arg);
if (argument != null)
{
return argument.dereference();
}
}
return null;
}
/**
* Returns the descriptor root for the DataStore schema
*
* @return the descriptor root
*/
public final DataElement getSchemaRoot()
{
return _dataStore.getDescriptorRoot();
}
public void setExternalLoader(ExternalLoader loader)
{
_loader = loader;
}
public ExternalLoader getExternalLoader()
{
return _loader;
}
public synchronized void waitForInput()
{
if (_commandQueue.size() == 0)
{
super.waitForInput();
}
}
/**
* Handle commands that are routed to this miner.
* This interface must be implemented by each miner in order to
* perform tool actions driven from user interface interaction.
*
* @param theCommand an instance of a command containing a tree of arguments
*/
public abstract DataElement handleCommand(DataElement theCommand);
/**
* Returns the version of this miner
* The expected format for this is "<version>.<major>.<minor>"
*/
public abstract String getVersion();
}

View file

@ -0,0 +1,122 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.miners.miner;
/**
* MinerThread is a utility class used for doing threaded operations in a miner.
*/
public abstract class MinerThread extends Thread
{
private volatile Thread minerThread;
protected boolean _isCancelled;
/**
* Constructor
*/
public MinerThread()
{
super();
_isCancelled = false;
}
/**
* stops the thread
*/
public synchronized void stopThread()
{
if (minerThread != null)
{
_isCancelled = true;
try
{
minerThread = null;
}
catch (Exception e)
{
System.out.println(e);
}
}
notify();
}
/**
* runs the thread
*/
public void run()
{
Thread thisThread = Thread.currentThread();
minerThread = thisThread;
//thisThread.setPriority(thisThread.getPriority()+1);
//This function lets derived classes do some initialization
initializeThread();
while (minerThread != null && minerThread == thisThread && minerThread.isAlive() && !_isCancelled)
{
try
{
sleep(100);
// yield();
}
catch (InterruptedException e)
{
System.out.println(e);
}
//This function is where the Threads do real work, and return false when finished
if (!doThreadedWork())
{
try
{
minerThread = null;
}
catch (Exception e)
{
System.out.println(e);
}
}
}
//This function lets derived classes cleanup or whatever
cleanupThread();
}
/**
* Implement this method to provide initialization of this thread.
*/
public abstract void initializeThread();
/**
* Implement this method to provide the work implementation of this thread.
* This method gets called periodically by the miner thread so te work done
* here must be atomic. Each time this is called a incremental unit of
* work should be done. Once all the work is done, <b>true</b> should be
* returned.
*
* @return <b>true</b> if all the work is done.
*/
public abstract boolean doThreadedWork();
/**
* Implement this method to provide any cleanup that is required after
* all the work is done.
*/
public abstract void cleanupThread();
}

View file

@ -0,0 +1,282 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* <p>
* The ByteStreamHandler class is used to abstract file read and write operations
* across the network. By default this is used for sending and receiving files
* on the client and the server. The class can be extended if the default byte stream
* implementations are not sufficient for a particular platform or use.
* </p>
* <p>
* If ByteStreamHandler is extended, you need to tell the DataStore to use the
* extended implementation. To do that, call <code>DataStore.setByteStreamHandler(ByteStreamHandler)</code>.
* </p>
*
*/
public class ByteStreamHandler implements IByteStreamHandler
{
protected DataStore _dataStore;
protected DataElement _log;
protected static final String FILEMSG_REMOTE_SAVE_FAILED = "RSEF5006";
/**
* Contructor
* @param dataStore the DataStore instance
*/
public ByteStreamHandler(DataStore dataStore, DataElement log)
{
_dataStore = dataStore;
_log = log;
}
public String getId()
{
return getClass().getName();
}
/**
* Save a file in the specified location. This method is called by the
* DataStore when the communication layer receives a file transfer
*
* @param remotePath the path where to save the file
* @param buffer the bytes to insert in the file
* @param size the number of bytes to insert
* @param binary indicates whether to save the bytes as binary or text
*/
public void receiveBytes(String remotePath, byte[] buffer, int size, boolean binary)
{
remotePath = new String(remotePath.replace('\\', '/'));
DataElement status = findStatusFor(remotePath);
String fileName = _dataStore.mapToLocalPath(remotePath);
if (fileName != null)
{
try
{
// need to create directories as well
File file = new File(fileName);
if (!file.exists())
{
File parent = new File(file.getParent());
parent.mkdirs();
}
else
{
}
File newFile = new File(fileName);
FileOutputStream fileStream = new FileOutputStream(newFile);
if (binary)
{
fileStream.write(buffer, 0, size);
}
else
{
IByteConverter byteConverter = _dataStore.getByteConverter();
byteConverter.setContext(file);
byte[] convertedBytes = byteConverter.convertClientBytesToHostBytes(buffer, 0, size);
fileStream.write(convertedBytes, 0, convertedBytes.length);
/*
String bufferString = new String(buffer, 0, size, DE.ENCODING_UTF_8);
// hack for zOS
String theOS = System.getProperty("os.name");
if (theOS.toLowerCase().startsWith("z"))
{
bufferString = bufferString.replace('\r', ' ');
}
OutputStreamWriter writer = new OutputStreamWriter(fileStream);
writer.write(bufferString, 0, size);
writer.flush();
*/
}
fileStream.close();
if (status == null)
return;
status.setAttribute(DE.A_SOURCE, "success");
_dataStore.refresh(status.getParent());
}
catch (IOException e)
{
System.out.println(e);
if (status == null)
return;
status.setAttribute(DE.A_VALUE, FILEMSG_REMOTE_SAVE_FAILED);
status.setAttribute(DE.A_SOURCE, "failed");
_dataStore.refresh(status.getParent());
}
catch (Exception e)
{
System.out.println(e);
if (status == null)
return;
status.setAttribute(DE.A_VALUE, FILEMSG_REMOTE_SAVE_FAILED);
status.setAttribute(DE.A_SOURCE, "failed");
_dataStore.refresh(status.getParent());
}
}
}
/**
* Append a bytes to a file at a specified location. This method is called by the
* DataStore when the communication layer receives a file transfer append.
*
* @param remotePath the path where to save the file
* @param buffer the bytes to append in the file
* @param size the number of bytes to append in the file
* @param binary indicates whether to save the bytes as binary or text
*/
public void receiveAppendedBytes(String remotePath, byte[] buffer, int size, boolean binary)
{
remotePath = new String(remotePath.replace('\\', '/'));
DataElement status = findStatusFor(remotePath);
String fileName = _dataStore.mapToLocalPath(remotePath);
if (fileName != null)
{
try
{
// need to create directories as well
File file = new File(fileName);
if (!file.exists())
{
File parent = new File(file.getParent());
parent.mkdirs();
File newFile = new File(fileName);
FileOutputStream fileStream = new FileOutputStream(newFile);
if (binary)
{
fileStream.write(buffer, 0, size);
}
else
{
IByteConverter byteConverter = _dataStore.getByteConverter();
byteConverter.setContext(file);
byte[] convertedBytes = byteConverter.convertClientBytesToHostBytes(buffer, 0, size);
fileStream.write(convertedBytes, 0, convertedBytes.length);
}
fileStream.close();
}
else
{
FileOutputStream outStream = new FileOutputStream(fileName, true);
if (binary)
{
outStream.write(buffer, 0, size);
}
else
{
IByteConverter byteConverter = _dataStore.getByteConverter();
byteConverter.setContext(file);
byte[] convertedBytes = byteConverter.convertClientBytesToHostBytes(buffer, 0, size);
outStream.write(convertedBytes, 0, convertedBytes.length);
}
outStream.close();
}
if (status == null)
return;
status.setAttribute(DE.A_SOURCE, "success");
_dataStore.refresh(status.getParent());
}
catch (IOException e)
{
System.out.println(e);
if (status == null)
return;
status.setAttribute(DE.A_VALUE, FILEMSG_REMOTE_SAVE_FAILED);
status.setAttribute(DE.A_SOURCE, "failed");
_dataStore.refresh(status.getParent());
}
}
}
/**
* Called by <code>sendBytes</code> to either save the bytes to a local file or transmit
* them to a remote file.
* @param path the path of the file
* @param bytes the bytes of the file
* @param size the size of the file
* @param binary indicates whether the bytes are to be sent as binary or text
*/
protected void internalSendBytes(String path, byte[] bytes, int size, boolean binary)
{
if (_dataStore.isVirtual())
{
_dataStore.replaceFile(path, bytes, size, binary);
}
else
{
_dataStore.updateFile(path, bytes, size, binary);
}
}
/**
* Called by <code>sendBytes</code> to either append the bytes to a local file or transmit
* them and append them to a remote file.
* @param path the path of the file
* @param bytes the bytes of the file
* @param size the size of the file
* @param binary indicates whether the bytes are to be sent as binary or text
*/
protected void internalSendAppendBytes(String path, byte[] bytes, int size, boolean binary)
{
if (_dataStore.isVirtual())
{
_dataStore.replaceAppendFile(path, bytes, size, binary);
}
else
{
_dataStore.updateAppendFile(path, bytes, size, binary);
}
}
protected DataElement findStatusFor(String remotePath)
{
if (_log != null)
{
for (int i = 0; i < _log.getNestedSize(); i++)
{
DataElement child = _log.get(i);
if (child.getName().equals(remotePath))
{
return child;
}
}
}
return null;
}
}

View file

@ -0,0 +1,82 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
import java.util.HashMap;
/**
* Stores the set of registered byte stream handlers using the handler id
* as the key. Whenever a bytestream operation is required (i.e. for a save of bytes)
* The appropriate byte stream handler is retrieved via the specified id.
* If no such handler exists, then the default byte stream handler is returned.
*
*/
public class ByteStreamHandlerRegistry
{
private HashMap _map;
private IByteStreamHandler _default;
public ByteStreamHandlerRegistry()
{
_map = new HashMap();
}
/**
* Registers the default byte stream handler
* @param handler the default byte stream handler
*/
public void setDefaultByteStreamHandler(IByteStreamHandler handler)
{
_default = handler;
_map.put(DataStoreResources.DEFAULT_BYTESTREAMHANDLER, handler);
registerByteStreamHandler(handler);
}
/**
* Registers a byte stream handler.
* @param handler the handler to register
*/
public void registerByteStreamHandler(IByteStreamHandler handler)
{
_map.put(handler.getId(), handler);
}
/**
* Returns the byte stream handler with the specified id.
* If "default" is specified or no such id has been registered,
* the default byte stream handler is returned.
* @param id the id of the byte stream handler
* @return the byte stream handler
*/
public IByteStreamHandler getByteStreamHandler(String id)
{
IByteStreamHandler handler = (IByteStreamHandler)_map.get(id);
if (handler == null)
{
handler = _default;
}
return handler;
}
/**
* Returns the default byte stream handler
* @return the default
*/
public IByteStreamHandler getDefault()
{
return _default;
}
}

View file

@ -0,0 +1,298 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
import java.util.ArrayList;
import org.eclipse.dstore.core.java.IRemoteClassInstance;
import org.eclipse.dstore.core.util.CommandGenerator;
/**
* <p>
* Abtract class for handling commands. A <code>CommandHandler</code> is a <code>Handler</code> that
* contains a queue of commands to be sent to miners. Each DataStore instance uses a single
* command handler that periodically sends it's queue either to a server or directly
* to miners.
* </p>
* <p>
* The CommandHandler is the means by which the DataStore sends information or files from
* the client to the remote tools.
* </p>
*/
public abstract class CommandHandler extends Handler
{
protected ArrayList _commands;
protected ArrayList _classesToSend;
private CommandGenerator _commandGenerator;
/**
* Constructor
*/
public CommandHandler()
{
super();
_commands = new ArrayList();
_classesToSend = new ArrayList();
_commandGenerator = new CommandGenerator();
}
/**
* Sets the associated DataStore
*/
public void setDataStore(DataStore dataStore)
{
super.setDataStore(dataStore);
_commandGenerator.setDataStore(dataStore);
}
/**
* Returns the associated DataStore
* @return the associated DataStore
*/
public DataStore getDataStore()
{
return _dataStore;
}
/**
* Adds a command object to the queue
* @param command the command to add to the queue
* @param immediate indicates whether the command should be inserted first in the queue
* or whether it should be appended.
*/
public void addCommand(DataElement command, boolean immediate)
{
synchronized (_commands)
{
if (!_commands.contains(command))
{
if (immediate)
{
_commands.add(0, command);
}
else
{
_commands.add(command);
}
}
notifyInput();
}
}
/**
* Periodically called to send commands from the queue.
*/
public void handle()
{
if (!_commands.isEmpty() || !_classesToSend.isEmpty())
{
sendCommands();
}
}
/**
* Create and add a new command object to the command queue.
*
* @param commandDescriptor the descriptor for the new command
* @param arguments the arguments for the command
* @param object the subject of the command
* @param refArg indicates whether the subject should be represented in the command as a
* reference to the subject or the actual subject, itself
* @param immediate indicates whether the command should be first in the queue or appended to it
* @return the status object of the command
*/
public DataElement command(DataElement commandDescriptor, ArrayList arguments, DataElement object, boolean refArg, boolean immediate)
{
DataElement command = _commandGenerator.generateCommand(commandDescriptor, arguments, object, refArg);
return command(command, immediate);
}
/**
* Create and add a new command object to the command queue.
*
* @param commandDescriptor the descriptor for the new command
* @param arg the arg for the command
* @param object the subject of the command
* @param refArg indicates whether the subject should be represented in the command as a
* reference to the subject or the actual subject, itself
* @param immediate indicates whether the command should be first in the queue or appended to it
* @return the status object of the command
*/
public DataElement command(DataElement commandDescriptor, DataElement arg, DataElement object, boolean refArg, boolean immediate)
{
DataElement command = _commandGenerator.generateCommand(commandDescriptor, arg, object, refArg);
return command(command, immediate);
}
/**
* Create and add a new command object to the command queue.
*
* @param commandDescriptor the descriptor for the new command
* @param object the subject of the command
* @param refArg indicates whether the subject should be represented in the command as a
* reference to the subject or the actual subject, itself
* @return the status object of the command
*/
public DataElement command(DataElement commandDescriptor, DataElement object, boolean refArg)
{
DataElement command = _commandGenerator.generateCommand(commandDescriptor, object, refArg);
return command(command);
}
/**
* Add a command object to the command queue
* @param cmd the command object to add to the queue
* @return the status object of the command
*/
public DataElement command(DataElement cmd)
{
return command(cmd, false);
}
/**
* Add a command object to the command queue
* @param cmd the command object to add to the queue
* @param immediate indicates whether the command is to be inserted first in the queue or appended
* @return the status object of the command
*/
public DataElement command(DataElement cmd, boolean immediate)
{
DataElement status = null;
if ((cmd != null) && _dataStore != null)
{
status = cmd.get(cmd.getNestedSize() -1);
if (status != null && !status.getName().equals(DataStoreResources.model_done))
{
addCommand(cmd, immediate);
}
}
return status;
}
/**
* Removes and affectively cancels all commands from the current queue of commands
*/
public synchronized void cancelAllCommands()
{
DataElement log = _dataStore.getLogRoot();
for (int i = 0; i < _commands.size(); i++)
{
log.removeNestedData((DataElement) _commands.get(i));
}
_commands.clear();
}
public CommandGenerator getCommandGenerator()
{
return _commandGenerator;
}
/**
* Implemented to provide the means by which commands in the queue are sent
*/
public abstract void sendCommands();
/**
* Implemented to provide the means by which file bytes are sent
* @param fileName the name of the file to send
* @param bytes to bytes of the file to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes as binary or text
*/
public abstract void sendFile(String fileName, byte[] bytes, int size, boolean binary);
/**
* Implemented to provide the means by which file bytes are sent
* @param fileName the name of the file to send
* @param bytes to bytes of the file to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes as binary or text
* @param byteStreamHandlerId indicates which byte stream handler to receive the bytes with
*/
public abstract void sendFile(String fileName, byte[] bytes, int size, boolean binary, String byteStreamHandlerId);
/**
* Implemented to provide the means by which file bytes are sent and appended
* @param fileName the name of the file to send
* @param bytes to bytes of the file to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes as binary or text
*/
public abstract void sendAppendFile(String fileName, byte[] bytes, int size, boolean binary);
/**
* Implemented to provide the means by which file bytes are sent and appended
* @param fileName the name of the file to send
* @param bytes to bytes of the file to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes as binary or text
* @param byteStreamHandlerId indicates which byte stream handler to receive the bytes with
*/
public abstract void sendAppendFile(String fileName, byte[] bytes, int size, boolean binary, String byteStreamHandlerId);
/**
* Implemented to provide the means by which classes are sent
* across the comm channel.
* @param className the name of the class to send
*/
public abstract void sendClass(String className);
/**
* Implemented to provide the means by which classes are sent
* across the comm channel.
* @param className the name of the class to send
* @param classByteStreamHandlerId indicates which class byte stream handler to receive the class with
*/
public abstract void sendClass(String className, String classByteStreamHandlerId);
/**
* Runs the specified class on the remote system
*/
public abstract void sendClassInstance(IRemoteClassInstance runnable, String classByteStreamHandlerId);
/**
* Causes the current thread to wait until this class request has been
* fulfilled.
*/
public synchronized void waitForInput()
{
if (_commands.size() == 0 && _classesToSend.size() == 0)
{
super.waitForInput();
}
}
/**
* Implemented to provide the means by which classes are requested
* across the comm channel.
* @param className the name of the class to request
*/
public abstract void requestClass(String className);
public abstract void sendKeepAliveConfirmation();
public abstract void sendKeepAliveRequest();
}

View file

@ -0,0 +1,225 @@
/********************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and International Business Machines Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
/**
* DE is a container of <code>DataElement</code> constants. These constants
* are used to identify <code>DataElement</code> attributes.
*
* <li>
* Attributes beginning with "P_" indicate <I>property</I> attribute identifiers.
* </li>
* <li>
* Attributes beginning with "T_" indicate <code>DataElement</code> <I>type</I> attributes.
* </li>
* <li>
* Attributes beginning with "A_" indicate <code>DataElement</code> indexs into <I>attributes</I>.
* </li>
*
*/
public class DE
{
/*
* The nested data (children) property identifier of a <code>DataElement</code>.
*/
public static final String P_CHILDREN = "children";
/*
* The image property identifier of a <code>DataElement</code>. This is the same
* as the value property identifier
*/
public static final String P_LABEL = "label";
/*
* The notifier property identifier of a <code>DataElement</code>.
*/
public static final String P_NOTIFIER = "notifier";
/*
* The <code>DataStore</code> property identifier of a <code>DataElement</code>.
*/
public static final String P_DATASTORE = "dataStore";
/*
* The source name property identifier of a <code>DataElement</code>. This is the
* name of a source location if one exists.
*/
public static final String P_SOURCE_NAME = "source";
/*
* The source file property identifier of a <code>DataElement</code>.
*/
public static final String P_SOURCE = "sourcefile";
/*
* The source location property identifier of a <code>DataElement</code>.
*/
public static final String P_SOURCE_LOCATION = "sourcelocation";
public static final String P_SOURCE_LOCATION_COLUMN = "sourcelocationcolumn";
/*
* The nested data (children) property identifier of a <code>DataElement</code>. Same as <code>P_CHILDREN</code>.
*/
public static final String P_NESTED = "nested";
/*
* The buffer property identifier of a <code>DataElement</code>.
*/
public static final String P_BUFFER = "buffer";
/*
* The type property identifier of a <code>DataElement</code>.
*/
public static final String P_TYPE = "type";
/*
* The id property identifier of a <code>DataElement</code>.
*/
public static final String P_ID = "id";
/*
* The name property identifier of a <code>DataElement</code>.
*/
public static final String P_NAME = "name";
/*
* The value property identifier of a <code>DataElement</code>.
*/
public static final String P_VALUE = "value";
/*
* The <I>is reference?</I> property identifier of a <code>DataElement</code>.
*/
public static final String P_ISREF = "isRef";
/*
* The visibility property identifier of a <code>DataElement</code>.
*/
public static final String P_DEPTH = "depth";
/*
* The attributes property identifier of a <code>DataElement</code>.
*/
public static final String P_ATTRIBUTES = "attribute";
/*
* The file property identifier of a <code>DataElement</code>.
*/
public static final String P_FILE = "file";
/*
* The file property identifier of a <code>DataElement</code>.
*/
public static final String P_DESCRIPTOR = "descriptor";
/*
* Reference type.
*/
public static final String T_REFERENCE = "reference";
/*
* Command type.
*/
public static final String T_COMMAND = "command";
/*
* UI Command Descriptor type.
*/
public static final String T_UI_COMMAND_DESCRIPTOR = "ui_commanddescriptor";
/*
* Object Descriptor type.
*/
public static final String T_OBJECT_DESCRIPTOR = "objectdescriptor";
/*
* Command Descriptor type.
*/
public static final String T_COMMAND_DESCRIPTOR = "commanddescriptor";
/*
* Relation Descriptor type.
*/
public static final String T_RELATION_DESCRIPTOR = "relationdescriptor";
/*
* Abstract Object Descriptor type.
*/
public static final String T_ABSTRACT_OBJECT_DESCRIPTOR = "abstractobjectdescriptor";
/*
* Abstract Command Descriptor type.
*/
public static final String T_ABSTRACT_COMMAND_DESCRIPTOR = "abstractcommanddescriptor";
/*
* Abstract Relation Descriptor type.
*/
public static final String T_ABSTRACT_RELATION_DESCRIPTOR = "abstractrelationdescriptor";
/*
* Type attribute index.
*/
public static final int A_TYPE = 0;
/*
* ID attribute index.
*/
public static final int A_ID = 1;
/*
* Name attribute index.
*/
public static final int A_NAME = 2;
/*
* Value attribute index.
*/
public static final int A_VALUE = 3;
/*
* Source attribute index.
*/
public static final int A_SOURCE = 4;
/*
* Source location attribute index.
* @deprecated
*/
public static final int A_SOURCE_LOCATION = 5;
/*
* IsRef attribute index.
*/
public static final int A_ISREF = 6;
/*
* Visibility attribute index.
*/
public static final int A_DEPTH = 7;
/*
* Size attribute index.
*/
public static final int A_SIZE = 8;
public static final String ENCODING_UTF_8 = "UTF-8";
}

View file

@ -0,0 +1,95 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
/**
* This class is used to store attributes that are required
* for configurating a remote connection.
*/
public class DataStoreAttributes
{
public static final String DATASTORE_VERSION = "DataStore.8.0.0";
public static final int A_PLUGIN_PATH = 0;
public static final int A_ROOT_NAME = 1;
public static final int A_ROOT_PATH = 2;
public static final int A_HOST_NAME = 3;
public static final int A_HOST_PATH = 4;
public static final int A_HOST_PORT = 5;
public static final int A_LOCAL_NAME = 6;
public static final int A_LOCAL_PATH = 7;
public static final int A_LOG_NAME = 8;
public static final int A_LOG_PATH = 9;
public static final int A_SIZE = 10;
private String _attributes[];
/**
* Constructor
*/
public DataStoreAttributes()
{
_attributes = new String[A_SIZE];
// root
_attributes[A_ROOT_NAME] = new String("Local");
_attributes[A_ROOT_PATH] = new String("");
// log
_attributes[A_LOG_NAME] = new String("log");
_attributes[A_LOG_PATH] = new String("log.xml");
// host
_attributes[A_HOST_NAME] = new String("");
_attributes[A_HOST_PATH] = new String("");
_attributes[A_HOST_PORT] = new String("4033");
// local
_attributes[A_LOCAL_NAME] = new String("");
_attributes[A_LOCAL_PATH] = new String("");
}
/**
* Gets an attribute at a specified index
* @param attributeIndex the index of an attribute
* @return the attribute
*/
public String getAttribute(int attributeIndex)
{
return _attributes[attributeIndex];
}
/**
* Set an attribute at a specified index
* @param attributeIndex the index of an attribute
*/
public void setAttribute(int attributeIndex, String attribute)
{
_attributes[attributeIndex] = new String(attribute);
if (attributeIndex == A_PLUGIN_PATH)
{
if (_attributes[A_ROOT_PATH].length() == 0)
{
_attributes[A_ROOT_PATH] = attribute;
}
}
}
}

View file

@ -0,0 +1,112 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
public class DataStoreResources
{
public static String model_Log_Root="Log Root";
public static String model_Tool_Root="Tool Root";
public static String model_Set="Set";
public static String model_Modify="Modify";
public static String model_timeout="timeout";
public static String model_data="data";
public static String model_transient="transient";
public static String model_all="all";
public static String model_host="host";
public static String model_root="root";
public static String model_descriptors="descriptors";
public static String model_descriptor_for="descriptor for";
public static String model_project="Project";
public static String model_log="log";
public static String model_deleted="deleted";
public static String model_status="status";
public static String model_start="start";
public static String model_failed="failed";
public static String model_done="done";
public static String model_working="working";
public static String model_progress="progress";
public static String model_error="error";
public static String model_warning="warning";
public static String model_informational="informational";
public static String model_markers="markers";
public static String model_invocation="invocation";
public static String model_pattern="pattern";
public static String model_input="input";
public static String model_output="output";
public static String model_details="details";
public static String model_contents="contents";
public static String model_contents_arguments="Contents and Arguments";
public static String model_parent="parent";
public static String model_arguments="arguments";
public static String model_Commands="Commands";
public static String model_device="device";
public static String model_directory="directory";
public static String model_folder="folder";
public static String model_file="file";
public static String model_Filesystem_Objects="Filesystem Objects";
public static String model_Container_Object="Container Object";
public static String model_Directories="Directories";
public static String model_Details="Details";
public static String model_miners="miners";
public static String model_miner="miner";
public static String model_state="state";
public static String model_ticket="ticket";
public static String model_valid="valid";
public static String model_invalid="invalid";
public static String model_abstracted_by="abstracted by";
public static String model_abstracts="abstracts";
public static String model_incomplete="incomplete";
public static String model_Miner_Details="Miner Details";
public static String model_Hosts="Hosts";
public static String model_Tools="Tools";
public static String model_Schema="Schema";
public static String model_Logged_Commands="Logged Commands";
public static String model_Cancel="Cancel";
public static String model_Get_Schema="Get Schema";
public static String model_Show_Ticket="Show Ticket";
public static String model_Init_Miners="Init Miners";
public static String model_Set_Host="Set Host";
public static String model_Exit="Exit";
public static String model_Connect_to="Connect to";
public static String model_Disconnect_from="Disconnect from";
public static String model_Delete_Connection="Delete Connection";
public static String model_time="time";
public static String model_property="property";
public static String model_start_time="start time";
public static String model_command_time="command time";
public static String model_Transient_Objects="Transient Objects";
public static String model_Data="Data";
public static String model_No_input="No input";
public static String model_Open="Open";
public static String model_Close="Close";
public static String model_Refresh="Refresh";
public static String model_Query="Query";
public static String model_Cancellable="Cancellable";
public static String SERIALIZED_TYPE="SERIALIZED";
public static String CLASS_TYPE="CLASS";
public static String REQUEST_CLASS_TYPE="REQUEST_CLASS";
public static String DEFAULT_CLASSBYTESTREAMHANDLER="default";
public static String FILE_TYPE="FILE";
public static String DOCUMENT_TYPE="DOCUMENT";
public static String DEFAULT_BYTESTREAMHANDLER="default";
public static String TRUE="true";
public static String FALSE="false";
public static String DELETED="deleted";
public static String KEEPALIVE_TYPE="KEEPALIVE";
public static String KEEPALIVECONFIRM_TYPE="CONFIRMKEEPALIVE";
}

View file

@ -0,0 +1,102 @@
################################################################################
# Copyright (c) 2000, 2006 IBM Corporation. All rights reserved.
# This program and the accompanying materials are made available under the terms
# of the Eclipse Public License v1.0 which accompanies this distribution, and is
# available at http://www.eclipse.org/legal/epl-v10.html
#
# Initial Contributors:
# The following IBM employees contributed to the Remote System Explorer
# component that contains this file: David McKnight, Kushal Munir,
# Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
# Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
#
# Contributors:
# {Name} (company) - description of contribution.
################################################################################
# NLS_MESSAGEFORMAT_NONE
# This file contains the DataStore resources. English.
# model types
model.Log_Root=Log Root
model.Tool_Root=Tool Root
model.Set=Set
model.Modify=Modify
model.timeout=timeout
model.data=data
model.transient=transient
model.all=all
model.host=host
model.root=root
model.descriptors=descriptors
model.descriptor_for=descriptor for
model.project=Project
model.log=log
model.deleted=deleted
model.status=status
model.start=start
model.failed=failed
model.done=done
model.working=working
model.progress=progress
model.error=error
model.warning=warning
model.informational=informational
model.markers=markers
model.invocation=invocation
model.pattern=pattern
model.input=input
model.output=output
model.details=details
model.contents=contents
model.contents&arguments=Contents and Arguments
model.parent=parent
model.arguments=arguments
model.Commands=Commands
model.device=device
model.directory=directory
model.folder=folder
model.file=file
model.Filesystem_Objects=Filesystem Objects
model.Container_Object=Container Object
model.Directories=Directories
model.Details=Details
model.miners=miners
model.miner=miner
model.state=state
model.ticket=ticket
model.valid=valid
model.invalid=invalid
model.abstracted_by=abstracted by
model.abstracts=abstracts
model.incomplete=incomplete
model.Miner_Details=Miner Details
model.Hosts=Hosts
model.Details=Details
model.Tools=Tools
model.Schema=Schema
model.Logged_Commands=Logged Commands
model.Cancel=Cancel
model.Get_Schema=Get Schema
model.Show_Ticket=Show Ticket
model.Init_Miners=Init Miners
model.Set_Host=Set Host
model.Exit=Exit
model.Connect_to=Connect to
model.Disconnect_from=Disconnect from
model.Delete_Connection=Delete Connection
model.time=time
model.property=property
model.start_time=start time
model.command_time=command time
model.start=start
model.transient=transient
model.Transient_Objects=Transient Objects
model.Data=Data
model.No_input=No input
model.Open=Open
model.Close=Close
model.Refresh=Refresh
model.Query=Query
model.Cancellable=Cancellable

View file

@ -0,0 +1,342 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
/**
* This class is used for defining the base DataStore schema. All
* miner schemas are derived from the schema defined here. This class
* provides getters for quickly getting at commonly used schema descriptors.
*/
public class DataStoreSchema
{
private DataStore _dataStore;
private DataElement _abstractedBy;
private DataElement _abstracts;
private DataElement _contents;
private DataElement _container;
private DataElement _attributes;
private DataElement _objectDescriptor;
private DataElement _commandDescriptor;
private DataElement _relationDescriptor;
private DataElement _abstractObjectDescriptor;
private DataElement _abstractCommandDescriptor;
private DataElement _abstractRelationDescriptor;
public static final String C_VALIDATE_TICKET = "C_VALIDATE_TICKET";
public static final String C_SET = "C_SET";
public static final String C_MODIFY = "C_MODIFY";
public static final String C_SET_HOST = "C_SET_HOST";
public static final String C_SCHEMA = "C_SCHEMA";
public static final String C_SET_PREFERENCE = "C_SET_PREFERENCE";
public static final String C_ADD_MINERS = "C_ADD_MINERS";
public static final String C_ACTIVATE_MINER = "C_ACTIVATE_MINER";
public static final String C_INIT_MINERS = "C_INIT_MINERS";
public static final String C_OPEN = "C_OPEN";
public static final String C_CANCEL = "C_CANCEL";
public static final String C_SEND_INPUT = "C_SEND_INPUT";
public static final String C_QUERY = "C_QUERY";
public static final String C_REFRESH = "C_REFRESH";
public static final String C_EXIT = "C_EXIT";
public static final String C_CLOSE = "C_CLOSE";
public static final String C_NOTIFICATION = "C_NOTIFICATION";
public static final String C_QUERY_INSTALL = "C_QUERY_INSTALL";
public static final String C_QUERY_CLIENT_IP = "C_QUERY_CLIENT_IP";
public static final String C_QUERY_JVM = "C_QUERY_JVM";
/**
* Constructor
* @param dataStore the associated DataStore
*/
public DataStoreSchema(DataStore dataStore)
{
_dataStore = dataStore;
}
/**
* Returns the <i>abstracted by</i> relationship descriptor
* @return the descriptor
*/
public DataElement getAbstractedByRelation()
{
return _abstractedBy;
}
/**
* Returns the <i>abstracts</i> relationship descriptor
* @return the descriptor
*/
public DataElement getAbstractsRelation()
{
return _abstracts;
}
/**
* Returns the <i>contents</i> relationship descriptor
* @return the descriptor
*/
public DataElement getContentsRelation()
{
return _contents;
}
/**
* Returns the <i>attributes</i> relationship descriptor
* @return the descriptor
*/
public DataElement getAttributesRelation()
{
return _attributes;
}
/**
* Returns the <i>container</i> base object descriptor
* @return the descriptor
*/
public DataElement getContainerType()
{
return _container;
}
/**
* Returns the base object descriptor
* @return the descriptor
*/
public DataElement getObjectDescriptor()
{
return _objectDescriptor;
}
/**
* Returns the base command descriptor
* @return the descriptor
*/
public DataElement getCommandDescriptor()
{
return _commandDescriptor;
}
/**
* Returns the base relation descriptor
* @return the descriptor
*/
public DataElement getRelationDescriptor()
{
return _relationDescriptor;
}
/**
* Returns the base object descriptor
* @return the descriptor
*/
public DataElement getAbstractObjectDescriptor()
{
return _abstractObjectDescriptor;
}
/**
* Returns the base command descriptor
* @return the descriptor
*/
public DataElement getAbstractCommandDescriptor()
{
return _abstractCommandDescriptor;
}
/**
* Returns the base relation descriptor
* @return the descriptor
*/
public DataElement getAbstractRelationDescriptor()
{
return _abstractRelationDescriptor;
}
/**
* This method is called when the DataStore is initialized. It sets
* up the base DataStore schema.
* @param schemaRoot the root object of the DataStore schema
*/
public void extendSchema(DataElement schemaRoot)
{
// miner-specific descriptors are defined in the miners when they extend the schema
// these first elements are the most fundamental
DataElement uiCmdD = _dataStore.createObject(schemaRoot, DE.T_UI_COMMAND_DESCRIPTOR, DE.T_UI_COMMAND_DESCRIPTOR);
_commandDescriptor = _dataStore.createCommandDescriptor(schemaRoot, DE.T_COMMAND_DESCRIPTOR);
_objectDescriptor = _dataStore.createObjectDescriptor(schemaRoot, DE.T_OBJECT_DESCRIPTOR);
_relationDescriptor = _dataStore.createRelationDescriptor(schemaRoot, DE.T_RELATION_DESCRIPTOR);
_abstractObjectDescriptor = _dataStore.createAbstractObjectDescriptor(schemaRoot, DE.T_ABSTRACT_OBJECT_DESCRIPTOR);
_abstractCommandDescriptor = _dataStore.createAbstractCommandDescriptor(schemaRoot, DE.T_ABSTRACT_COMMAND_DESCRIPTOR);
_abstractRelationDescriptor = _dataStore.createAbstractRelationDescriptor(schemaRoot, DE.T_ABSTRACT_RELATION_DESCRIPTOR);
// cancellable command base descriptor
DataElement cancellable = _dataStore.createAbstractObjectDescriptor(schemaRoot, DataStoreResources.model_Cancellable);
DataElement rootD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_root);
DataElement hostD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_host);
DataElement logD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_log);
DataElement statusD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_status);
DataElement deletedD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_deleted);
// misc
DataElement allD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_all);
DataElement invokeD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_invocation);
DataElement patternD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_pattern);
DataElement inputD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_input);
DataElement outputD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_output);
// types of relationships
_contents = _dataStore.createRelationDescriptor(schemaRoot, DataStoreResources.model_contents);
_contents.setDepth(100);
DataElement descriptorForD = _dataStore.createRelationDescriptor(schemaRoot, DataStoreResources.model_descriptor_for);
descriptorForD.setDepth(1);
DataElement parentD = _dataStore.createRelationDescriptor(schemaRoot, DataStoreResources.model_parent);
parentD.setDepth(1);
_attributes = _dataStore.createRelationDescriptor(schemaRoot, "attributes");
_attributes.setDepth(0);
DataElement argsD = _dataStore.createRelationDescriptor(schemaRoot, DataStoreResources.model_arguments);
_abstracts = _dataStore.createRelationDescriptor(schemaRoot, DataStoreResources.model_abstracts);
_abstractedBy = _dataStore.createRelationDescriptor(schemaRoot, DataStoreResources.model_abstracted_by);
DataElement caRelations = _dataStore.createAbstractRelationDescriptor(schemaRoot, DataStoreResources.model_contents_arguments);
_dataStore.createReference(caRelations, _contents, _contents);
_dataStore.createReference(caRelations, argsD, _contents);
_dataStore.createReference(_objectDescriptor, _contents, _contents);
_dataStore.createReference(_objectDescriptor, parentD, _contents);
_dataStore.createReference(_objectDescriptor, _abstracts, _contents);
_dataStore.createReference(_objectDescriptor, _abstractedBy, _contents);
_dataStore.createReference(_abstractObjectDescriptor, _contents, _contents);
_dataStore.createReference(_abstractObjectDescriptor, parentD, _contents);
_dataStore.createReference(_abstractObjectDescriptor, _abstracts, _contents);
_dataStore.createReference(_abstractObjectDescriptor, _abstractedBy, _contents);
_dataStore.createReference(statusD, _contents, _contents);
_dataStore.createReference(_commandDescriptor, allD, _contents);
_dataStore.createReference(_commandDescriptor, caRelations, _contents);
_dataStore.createReference(_commandDescriptor, argsD, _contents);
_dataStore.createReference(_commandDescriptor, _contents, _contents);
DataElement logDetails = _dataStore.createAbstractObjectDescriptor(logD, DataStoreResources.model_Commands);
_dataStore.createReference(logDetails, _commandDescriptor, _contents);
_dataStore.createReference(logDetails, allD, _contents);
_dataStore.createReference(logD, caRelations, _contents);
_dataStore.createReference(logD, _contents, _contents);
//Base Container Object
_container = _dataStore.createAbstractObjectDescriptor(schemaRoot, DataStoreResources.model_Container_Object);
_dataStore.createCommandDescriptor(_container, DataStoreResources.model_Query, "*", C_QUERY, false);
_dataStore.createReference(_container, _contents, _contents);
// file objects
DataElement fileD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_file);
DataElement dirD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_directory);
DataElement fsObject = _dataStore.createAbstractObjectDescriptor(schemaRoot, DataStoreResources.model_Filesystem_Objects);
_dataStore.createReference(_container, fsObject, _abstracts, _abstractedBy);
_dataStore.createReference(fileD, fsObject, _abstracts, _abstractedBy);
_dataStore.createReference(fsObject, dirD, _abstracts, _abstractedBy);
_dataStore.createReference(fsObject, fileD, _contents);
_dataStore.createReference(fsObject, dirD, _contents);
_dataStore.createReference(fsObject, fsObject, _contents);
_dataStore.createReference(dirD, fileD, _contents);
_dataStore.createReference(dirD, dirD, _contents);
// miner descriptors
DataElement minersD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_miners);
DataElement minerD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_miner);
DataElement dataD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_data);
DataElement transientD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_transient);
DataElement stateD = _dataStore.createObjectDescriptor(schemaRoot, DataStoreResources.model_state);
// containers
_dataStore.createReference(_container, rootD, _abstracts, _abstractedBy);
_dataStore.createReference(_container, hostD, _abstracts, _abstractedBy);
_dataStore.createReference(_container, logD, _abstracts, _abstractedBy);
_dataStore.createReference(_container, minersD, _abstracts, _abstractedBy);
_dataStore.createReference(_container, minerD, _abstracts, _abstractedBy);
_dataStore.createReference(_container, dataD, _abstracts, _abstractedBy);
// basic commands
_dataStore.createCommandDescriptor(cancellable, DataStoreResources.model_Cancel, "*", C_CANCEL);
_dataStore.createCommandDescriptor(rootD, DataStoreResources.model_Set, "-", C_SET, false);
_dataStore.createCommandDescriptor(rootD, DataStoreResources.model_Set_Host, "-", C_SET_HOST, false);
_dataStore.createCommandDescriptor(rootD, DataStoreResources.model_Init_Miners, "*", C_INIT_MINERS, false);
_dataStore.createCommandDescriptor(rootD, "Add Miners", "-", C_ADD_MINERS, false);
_dataStore.createCommandDescriptor(rootD, "Activate Miner", "-", C_ACTIVATE_MINER, false);
_dataStore.createCommandDescriptor(rootD, "Set Preference", "-", C_SET_PREFERENCE, false);
_dataStore.createCommandDescriptor(rootD, DataStoreResources.model_Show_Ticket, "-", C_VALIDATE_TICKET, false);
_dataStore.createCommandDescriptor(rootD, DataStoreResources.model_Get_Schema, "*", C_SCHEMA, false);
_dataStore.createCommandDescriptor(rootD, DataStoreResources.model_Exit, "*", C_EXIT, false);
_dataStore.createCommandDescriptor(rootD, "Query Install", "*", C_QUERY_INSTALL, false);
_dataStore.createCommandDescriptor(rootD, "Query Client IP", "*", C_QUERY_CLIENT_IP, false);
_dataStore.createCommandDescriptor(rootD, "Query JVM", "*", C_QUERY_JVM, false);
_dataStore.createCommandDescriptor(rootD, "Notification", "*", C_NOTIFICATION, false);
_dataStore.createCommandDescriptor(rootD, "Send Input", "*", C_SEND_INPUT, false);
// both ends have this base schema, so mark each descriptor as updated
for (int i = 0; i < schemaRoot.getNestedSize(); i++)
{
DataElement descriptor = schemaRoot.get(i);
descriptor.setUpdated(true);
for (int j = 0; j < descriptor.getNestedSize(); j++)
{
DataElement subDescriptor = descriptor.get(j);
subDescriptor.setUpdated(true);
}
schemaRoot.setUpdated(true);
}
}
}

View file

@ -0,0 +1,91 @@
/********************************************************************************
* Copyright (c) 2004, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
import java.io.File;
import java.io.UnsupportedEncodingException;
/**
* @author dmcknigh
*
* To change the template for this generated type comment go to
* Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
*/
public class DefaultByteConverter implements IByteConverter
{
private String _clientEncoding = DE.ENCODING_UTF_8;
private String _hostEncoding = System.getProperty("file.encoding");
public void setContext(File file)
{
}
public void setHostEncoding(String hostEncoding)
{
_hostEncoding = hostEncoding;
}
public void setClientEncoding(String clientEncoding)
{
_clientEncoding = clientEncoding;
}
public byte[] convertHostBytesToClientBytes(byte[] buffer, int offset, int length)
{
byte[] convertedBytes =null;
try
{
convertedBytes = (new String(buffer, offset, length, _hostEncoding)).getBytes(_clientEncoding);
}
catch (UnsupportedEncodingException e)
{
try
{
convertedBytes = (new String(buffer, offset, length)).getBytes(_clientEncoding);
}
catch (UnsupportedEncodingException e2)
{
return buffer;
}
}
return convertedBytes;
}
public byte[] convertClientBytesToHostBytes(byte[] buffer, int offset, int length)
{
byte[] convertedBytes = null;
try
{
convertedBytes = (new String(buffer, offset, length, _clientEncoding)).getBytes(_hostEncoding);
}
catch (UnsupportedEncodingException e)
{
try
{
convertedBytes = (new String(buffer, offset, length)).getBytes(_hostEncoding);
}
catch (UnsupportedEncodingException e2)
{
return buffer;
}
}
return convertedBytes;
}
}

View file

@ -0,0 +1,161 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
/**
* The Handler class is the base class for the threaded mechanisms in
* the DataStore. This is a thread that periodically does some activity.
* The frequency of handling can be configured.
*/
public abstract class Handler extends Thread
{
protected int _waitIncrement;
protected DataStore _dataStore;
private boolean _keepRunning;
/**
* Constructor
*/
public Handler()
{
_keepRunning = true;
_waitIncrement = 100;
}
/**
* Sets the time interval to wait between handling
* @param value the wait interval
*/
public void setWaitTime(int value)
{
_waitIncrement = value;
}
/**
* Returns the time interval to wait between handling
* @return the wait interval
*/
public int getWaitTime()
{
return _waitIncrement;
}
/**
* Sets the associated DataStore
* @param dataStore
*/
public void setDataStore(DataStore dataStore)
{
_dataStore = dataStore;
}
/**
* Indicates whether the handler is finished or not
* @return whether the handler is finished or not
*/
public boolean isFinished()
{
return !_keepRunning;
}
/**
* Finish handling
*/
public void finish()
{
if (_keepRunning)
{
_waitIncrement = 0;
_keepRunning = false;
/* causes hang
try
{
interrupt();
join();
}
catch (InterruptedException e)
{
System.out.println(e);
}
*/
handle();
}
}
/**
* Implemented to provide the periodic activity to be done in a handler.
* This method is called between wait intervals by the handler thread.
*/
public abstract void handle();
/**
* Runs the handler loop in a thread.
*/
public void run()
{
while (_keepRunning)
{
/*
try
{
Thread.sleep(_waitIncrement);
Thread.yield();
}
catch (InterruptedException e)
{
e.printStackTrace();
finish();
return;
}
*/
waitForInput();
handle();
}
}
/**
* Causes the current thread to wait until this class request has been
* fulfilled.
*/
public synchronized void waitForInput()
{
try
{
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
finish();
return;
}
}
/**
* Causes all threads waiting for this class request to be filled
* to wake up.
*/
public synchronized void notifyInput()
{
notifyAll();
}
}

View file

@ -0,0 +1,29 @@
/********************************************************************************
* Copyright (c) 2004, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
import java.io.File;
/**
* Interface for converting between host bytes and client bytes
*/
public interface IByteConverter
{
public void setContext(File file);
public byte[] convertHostBytesToClientBytes(byte[] buffer, int offset, int length);
public byte[] convertClientBytesToHostBytes(byte[] buffer, int offset, int length);
}

View file

@ -0,0 +1,59 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
/**
* <p>
* The ByteStreamHandler interface is used to abstract file read and write operations
* across the network.
*
*/
public interface IByteStreamHandler
{
/**
* Returns the unique ID for this bytestream handler
* @return the unique id
*/
public String getId();
/**
* Save a file in the specified location. This method is called by the
* DataStore when the communication layer receives a file transfer
*
* @param remotePath the path where to save the file
* @param buffer the bytes to insert in the file
* @param size the number of bytes to insert
* @param binary indicates whether to save the bytes as binary or text
*/
public void receiveBytes(String remotePath, byte[] buffer, int size, boolean binary);
/**
* Append a bytes to a file at a specified location. This method is called by the
* DataStore when the communication layer receives a file transfer append.
*
* @param remotePath the path where to save the file
* @param buffer the bytes to append in the file
* @param size the number of bytes to append in the file
* @param binary indicates whether to save the bytes as binary or text
*/
public void receiveAppendedBytes(String remotePath, byte[] buffer, int size, boolean binary);
}

View file

@ -0,0 +1,22 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
public interface IDataStoreProvider
{
public DataStore getDataStore();
}

View file

@ -0,0 +1,27 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
public interface ISSLProperties
{
public boolean usingSSL();
public String getDaemonKeyStorePassword();
public String getDaemonKeyStorePath();
public String getServerKeyStorePassword();
public String getServerKeyStorePath();
}

View file

@ -0,0 +1,49 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
import org.eclipse.dstore.core.util.ExternalLoader;
/**
* ISchemaExtender describes the interfaces that tool extensions
* need to implement to add or extend other schemas in the DataStore.
*/
public interface ISchemaExtender
{
/**
* Add this tool's schema to the global DataStore schema.
* This interface must be implemented by each miner in order to
* populate the DataStore schema with information about this tool's
* object model and information about how to communicate with the
* tool from objects available to the user interface.
*
* @param schemaRoot the descriptor root
*/
public abstract void extendSchema(DataElement schemaRoot);
/**
* Implement this to returns the external class loader for this extender
* implementation. In order for a tool extension to be loaded by the DataStore, it's
* class loader needs to be supplied.
*
* @return the external loader
*/
public abstract ExternalLoader getExternalLoader();
}

View file

@ -0,0 +1,25 @@
/********************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and International Business Machines Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
public interface ISchemaProvider
{
public ISchemaRegistry getSchemaRegistry();
public ISchemaExtender getSchemaExtender();
}

View file

@ -0,0 +1,50 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
import org.eclipse.dstore.core.util.ExternalLoader;
/**
* ISchemaRegistry describes the interface that needs to be
* implemented for external tools to contribute their
* schemas to the DataStore.
*/
public interface ISchemaRegistry
{
/**
* This method gets called when a new schema extender needs to be
* registered.
*
* @param extender the new schema extender
*/
public void registerSchemaExtender(ISchemaExtender extender);
/**
* This method is responsible for calling <code>extendSchema</code> on
* each of the registered schema extenders.
* @param dataStore the DataStore for which the schema will be extended
*/
public void extendSchema(DataStore dataStore);
/**
* Returns an <code>ExternalLoader</code> for the specified qualified class name
* @param qualfiedClassName the qualified class name of an external tool
* @return the external loader that can load to specified class
*/
public ExternalLoader getLoaderFor(String qualifiedClassName);
}

View file

@ -0,0 +1,91 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
import java.util.ArrayList;
import org.eclipse.dstore.core.util.ExternalLoader;
/**
* SchemaRegistry implements the interface for external tools to contribute their
* schemas to the DataStore.
*/
public class SchemaRegistry implements ISchemaRegistry
{
private ArrayList _initializedDataStores = new ArrayList();
private ArrayList _extenders = new ArrayList();
/**
* Registers a schema extender with the associated DataStores
* @param extender the schema extender to register
*/
public void registerSchemaExtender(ISchemaExtender extender)
{
if (!_extenders.contains(extender))
{
_extenders.add(extender);
for (int i = 0; i < _initializedDataStores.size(); i++)
{
DataStore dataStore = (DataStore) _initializedDataStores.get(i);
DataElement schemaRoot = dataStore.getDescriptorRoot();
extender.extendSchema(schemaRoot);
}
}
}
/**
* Calls extendSchema() on each of the registered schema extenders to
* extend the schema of the specified DataStore
*
* @param dataStore the DataStore whos schema will be updated
*/
public void extendSchema(DataStore dataStore)
{
if (!_initializedDataStores.contains(dataStore))
{
DataElement schemaRoot = dataStore.getDescriptorRoot();
for (int i = 0; i < _extenders.size(); i++)
{
ISchemaExtender extender = (ISchemaExtender) _extenders.get(i);
extender.extendSchema(schemaRoot);
}
_initializedDataStores.add(dataStore);
}
}
/**
* Gets the <code>ExternalLoader</code> for the specified qualified classname
*
* @param source the qualified classname
* @return the external loader for the specified classname
*/
public ExternalLoader getLoaderFor(String source)
{
for (int i = 0; i < _extenders.size(); i++)
{
ISchemaExtender extender = (ISchemaExtender) _extenders.get(i);
ExternalLoader loader = extender.getExternalLoader();
if (loader.canLoad(source))
{
return loader;
}
}
return null;
}
}

View file

@ -0,0 +1,262 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.model;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.dstore.core.java.IRemoteClassInstance;
/**
* <p>
* Abtract class for handling updates. A <code>UpdateHandler</code> is a <code>Handler</code> that
* contains a queue of data responses to be sent to the client. Each DataStore instance uses a single
* update handler that periodically sends it's data queue either to a client or directly
* to a domain listener on the client.
* </p>
* <p>
* The UpdateHandler is the means by which the DataStore sends information or files from the remote tools to the client.
* </p>
*/
public abstract class UpdateHandler extends Handler
{
protected ArrayList _dataObjects;
protected ArrayList _classesToSend;
/**
* Constructor
*/
public UpdateHandler()
{
_dataObjects = new ArrayList();
_classesToSend = new ArrayList();
}
/**
* Periodically called on the handler thread to sends data updates.
*/
public void handle()
{
if (!_dataObjects.isEmpty() || !_classesToSend.isEmpty())
{
sendUpdates();
}
}
protected void clean(DataElement object)
{
if (_dataObjects.size() == 0)
{
clean(object, 2);
}
}
protected synchronized void clean(DataElement object, int depth)
{
if ((depth > 0) && (object != null) && object.getNestedSize() > 0)
{
List deletedList = _dataStore.findDeleted(object);
for (int i = 0; i < deletedList.size(); i++)
{
DataElement child = (DataElement) deletedList.get(i);
if (child != null && child.isDeleted())
{
DataElement parent = child.getParent();
child.clear();
if (parent != null)
{
parent.removeNestedData(child);
}
_dataStore.addToRecycled(child);
}
}
deletedList.clear();
}
}
/**
* Adds a set of data objects to the update queue
* @param objects a set of objects to get updated
*/
public void update(ArrayList objects)
{
for (int i = 0; i < objects.size(); i++)
{
update((DataElement) objects.get(i));
}
}
/**
* Adds an object to the update queue
* @param object an object to get updated
*/
public void update(DataElement object)
{
update(object, false);
}
/**
* Adds an object to the update queue
* @param object an object to get updated
* @param immediate true indicates that this object should be first in the queue
*/
public void update(DataElement object, boolean immediate)
{
synchronized (_dataObjects)
{
if (immediate)
{
_dataObjects.add(0, object);
handle();
}
else
{
if (!_dataObjects.contains(object))
{
_dataObjects.add(object);
}
else
{
if (_dataStore != null && object != null)
{
if (object.getType().equals(DataStoreResources.model_status))
{
if (object.getName().equals(DataStoreResources.model_done))
{
//DKM
// move to the back of the queue
// this is done so that if status that was already queued changed to done in between
// requests, and had not yet been transferred over comm layer, the completed status
// object does not come back to client (as "done") before the results of a query
_dataObjects.remove(object);
_dataObjects.add(object);
}
}
}
}
}
notifyInput();
}
}
/**
* Causes the current thread to wait until this class request has been
* fulfilled.
*/
public synchronized void waitForInput()
{
if (_dataObjects.size() == 0 && _classesToSend.size() == 0)
{
super.waitForInput();
}
}
/**
* Implemented to provide the means by which updates on the queue are sent.
*/
public abstract void sendUpdates();
/**
* Implemented to provide the means by which files are sent
* @param path the path of the file to send
* @param bytes the bytes to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes as binary or text
*/
public abstract void updateFile(String path, byte[] bytes, int size, boolean binary);
/**
* Implemented to provide the means by which files are sent and appended
* @param path the path of the file to send
* @param bytes the bytes to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes as binary or text
*/
public abstract void updateAppendFile(String path, byte[] bytes, int size, boolean binary);
/**
* Implemented to provide the means by which files are sent
* @param path the path of the file to send
* @param bytes the bytes to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes as binary or text
* @param byteStreamHandlerId indicates the byte stream handler to receive the bytes
*/
public abstract void updateFile(String path, byte[] bytes, int size, boolean binary, String byteStreamHandlerId);
/**
* Implemented to provide the means by which files are sent and appended
* @param path the path of the file to send
* @param bytes the bytes to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes as binary or text
* @param byteStreamHandlerId indicates the byte stream handler to receive the bytes
*/
public abstract void updateAppendFile(String path, byte[] bytes, int size, boolean binary, String byteStreamHandlerId);
/**
* Implemented to provide the means by which classes are requested
* across the comm channel.
* @param className the name of the class to request
*/
public abstract void requestClass(String className);
/**
* Implemented to provide the means by which keepalive requests are sent
* across the comm channel.
*/
public abstract void sendKeepAliveRequest();
/**
* Impleted to provide the means by which a class on the host is updated on the client
* @param runnable
* @param deserializebyteStreamHandlerId
*/
public abstract void updateClassInstance(IRemoteClassInstance runnable, String deserializebyteStreamHandlerId);
/**
* Implemented to provide the means by which classes are sent
* across the comm channel.
* @param className the name of the class to send
*/
public abstract void sendClass(String className);
/**
* Implemented to provide the means by which classes are sent
* across the comm channel.
* @param className the name of the class to send
* @param classByteStreamHandlerId indicates which class byte stream handler to receive the class with
*/
public abstract void sendClass(String className, String classByteStreamHandlerId);
/**
* Implemented to provide the means by which keepalive confirmations are sent
* across the comm channel.
*/
public abstract void sendKeepAliveConfirmation();
}

View file

@ -0,0 +1,433 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.server;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
import org.eclipse.dstore.core.model.DataStoreAttributes;
import org.eclipse.dstore.core.model.ISSLProperties;
import org.eclipse.dstore.core.util.ExternalLoader;
import org.eclipse.dstore.core.util.Sender;
import org.eclipse.dstore.core.util.ssl.DStoreSSLContext;
/**
* ConnectionEstablisher is responsible for managing the server DataStore and
* facilitating the communication between client and server DataStores.
*
*/
public class ConnectionEstablisher
{
private ServerSocket _serverSocket;
private static boolean _continue;
private ArrayList _receivers;
private ServerCommandHandler _commandHandler;
private ServerUpdateHandler _updateHandler;
private ServerAttributes _serverAttributes = new ServerAttributes();
private DataStore _dataStore;
private int _maxConnections;
private int _timeout;
/**
* Creates the default ConnectionEstablisher. Communication occurs
* on a default port, there is no timeout and no ticket is required
* for a client to work with the DataStore.
*
*/
public ConnectionEstablisher()
{
String port = _serverAttributes.getAttribute(DataStoreAttributes.A_HOST_PORT);
setup(port, null, null);
}
/**
* Creates a ConnectionEstablisher. Communication occurs
* on the specified port, there is no timeout and no ticket is required
* for a client to work with the DataStore.
*
* @param port the number of the socket port
*/
public ConnectionEstablisher(String port)
{
setup(port, null, null);
}
/**
* Creates a ConnectionEstablisher. Communication occurs
* on the specified port, a timeout value indicates the idle wait
* time before shutting down, and no ticket is required
* for a client to work with the DataStore.
*
* @param port the number of the socket port
* @param timeout the idle duration to wait before shutting down
*/
public ConnectionEstablisher(String port, String timeout)
{
setup(port, timeout, null);
}
/**
* Creates a ConnectionEstablisher. Communication occurs
* on the specified port, a timeout value indicates the idle wait
* time before shutting down, and ticket specified the required
* ticket for a client to present in order to work with the DataStore.
*
* @param port the number of the socket port
* @param timeout the idle duration to wait before shutting down
* @param ticket validation id required by the client to access the DataStore
*/
public ConnectionEstablisher(String port, String timeout, String ticket)
{
setup(port, timeout, ticket);
}
/**
* Starts the run loop for the ConnectionEstablisher.
*/
public void start()
{
run();
}
/**
* Returns the DataStore.
*
* @return the DataStore
*/
public DataStore getDataStore()
{
return _dataStore;
}
/**
* Tells the connection establisher to clean up and shutdown
*/
public void finished(ServerReceiver receiver)
{
_updateHandler.removeSenderWith(receiver.socket());
_receivers.remove(receiver);
//if (_receivers.size() == 0)
{
_continue = false;
_commandHandler.finish();
_updateHandler.finish();
_dataStore.finish();
System.out.println(ServerReturnCodes.RC_FINISHED);
System.exit(0);
}
}
private void waitForConnections()
{
while (_continue == true)
{
try
{
Socket newSocket = _serverSocket.accept();
if (_dataStore.usingSSL())
{
// wait for connection
SSLSocket sslSocket = (SSLSocket)newSocket;
sslSocket.setUseClientMode(false);
sslSocket.setNeedClientAuth(false);
SSLSession session = sslSocket.getSession();
if (session == null)
{
System.out.println("handshake failed");
sslSocket.close();
return;
}
}
doHandShake(newSocket);
newSocket.setKeepAlive(true);
ServerReceiver receiver = new ServerReceiver(newSocket, this);
Sender sender = new Sender(newSocket, _dataStore);
// add this connection to list of elements
_receivers.add(receiver);
_updateHandler.addSender(sender);
receiver.start();
if (_receivers.size() == 1)
{
_updateHandler.start();
_commandHandler.start();
}
if (_receivers.size() == _maxConnections)
{
_continue = false;
_serverSocket.close();
}
}
catch (IOException ioe)
{
System.err.println(ServerReturnCodes.RC_CONNECTION_ERROR);
System.err.println("Server: error initializing socket: " + ioe);
_continue = false;
}
}
}
private ServerSocket createSocket(String portStr) throws UnknownHostException
{
ServerSocket serverSocket = null;
SSLContext sslContext = null;
// port
int port = 0;
if (_dataStore.usingSSL())
{
String keyStoreFileName = _dataStore.getKeyStoreLocation();
String keyStorePassword = _dataStore.getKeyStorePassword();
try
{
sslContext = DStoreSSLContext.getServerSSLContext(keyStoreFileName, keyStorePassword);
}
catch (Exception e)
{
}
}
// determine if portStr is a port range or just a port
String[] range = portStr.split("-");
if (range.length == 2)
{
int lPort = 0;
int hPort = 0;
try
{
lPort = Integer.parseInt(range[0]);
hPort = Integer.parseInt(range[1]);
}
catch (Exception e)
{
}
for (int i = lPort; i < hPort; i++)
{
// create server socket from port
try
{
if (_dataStore.usingSSL())
{
try
{
serverSocket = sslContext.getServerSocketFactory().createServerSocket(i);
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
serverSocket = new ServerSocket(i);
}
}
catch (Exception e)
{
_dataStore.trace(e);
}
if (serverSocket != null && serverSocket.getLocalPort() > 0)
{
return serverSocket;
}
}
}
else
{
port = Integer.parseInt(portStr);
// create server socket from port
if (_dataStore.usingSSL())
{
try
{
serverSocket = sslContext.getServerSocketFactory().createServerSocket(port);
}
catch (Exception e)
{
_dataStore.trace(e);
}
}
else
{
try
{
serverSocket = new ServerSocket(port);
}
catch (Exception e)
{
_dataStore.trace(e);
}
}
}
return serverSocket;
}
/**
* Create the DataStore and initializes it's handlers and communications.
*
* @param portStr the number of the socket port
* @param timeoutStr the idle duration to wait before shutting down
* @param ticketStr validation id required by the client to access the DataStore
*/
private void setup(String portStr, String timeoutStr, String ticketStr)
{
_maxConnections = 1;
ArrayList loaders = new ArrayList();
loaders.add(new ExternalLoader(getClass().getClassLoader(), "*"));
_commandHandler = new ServerCommandHandler(loaders);
_updateHandler = new ServerUpdateHandler();
String pluginPath = System.getProperty("A_PLUGIN_PATH");
ISSLProperties sslProperties = new ServerSSLProperties();
_dataStore = new DataStore(_serverAttributes, _commandHandler, _updateHandler, null);
_dataStore.setSSLProperties(sslProperties);
DataElement ticket = _dataStore.getTicket();
ticket.setAttribute(DE.A_NAME, ticketStr);
_updateHandler.setDataStore(_dataStore);
_commandHandler.setDataStore(_dataStore);
_receivers = new ArrayList();
_continue = true;
try
{
_serverSocket = createSocket(portStr);
if (_serverSocket == null)
{
System.err.println(ServerReturnCodes.RC_BIND_ERROR);
_continue = false;
}
else
{
// timeout
if (timeoutStr != null)
{
_timeout = Integer.parseInt(timeoutStr);
}
else
{
_timeout = 120000;
}
if (_timeout > 0)
{
_serverSocket.setSoTimeout(_timeout);
}
System.err.println(ServerReturnCodes.RC_SUCCESS);
System.err.println(_serverSocket.getLocalPort());
try
{
System.err.println("Server running on: " + InetAddress.getLocalHost().getHostName());
}
catch (UnknownHostException e)
{
// keep running
}
}
}
catch (UnknownHostException e)
{
System.err.println(ServerReturnCodes.RC_UNKNOWN_HOST_ERROR);
_continue = false;
}
catch (BindException e)
{
System.err.println(ServerReturnCodes.RC_BIND_ERROR);
_continue = false;
}
catch (IOException e)
{
System.err.println(ServerReturnCodes.RC_GENERAL_IO_ERROR);
_continue = false;
}
catch (SecurityException e)
{
System.err.println(ServerReturnCodes.RC_SECURITY_ERROR);
_continue = false;
}
}
private void run()
{
waitForConnections();
}
private void doHandShake(Socket socket)
{
try
{
BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), DE.ENCODING_UTF_8));
PrintWriter writer = new PrintWriter(bwriter);
writer.println(DataStoreAttributes.DATASTORE_VERSION);
writer.flush();
}
catch (IOException e)
{
System.out.println(e);
}
}
}

View file

@ -0,0 +1,419 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.server;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.eclipse.dstore.core.java.RemoteClassLoader;
import org.eclipse.dstore.core.miners.miner.Miner;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
import org.eclipse.dstore.core.model.DataStoreAttributes;
import org.eclipse.dstore.core.model.ISchemaExtender;
import org.eclipse.dstore.core.model.ISchemaRegistry;
import org.eclipse.dstore.core.util.ExternalLoader;
/**
* MinerLoader is an implementation of <code>ISchemaRegistry</code> used for
* loading and initializing miners.
*/
public class MinerLoader implements ISchemaRegistry
{
private DataStore _dataStore;
private ArrayList _miners;
private ArrayList _minerList;
private ArrayList _minerFileList;
private ArrayList _connectedList;
private ArrayList _loaders;
private RemoteClassLoader _remoteLoader;
private ExternalLoader _externalRemoteLoader;
/**
* Constructor
*
* @param dataStore the associated DataStore
* @param loaders the list of <code>ExternalLoader</code>s used be the miner loader
*/
public MinerLoader(DataStore dataStore, ArrayList loaders)
{
_dataStore = dataStore;
_loaders = loaders;
_miners = new ArrayList();
_minerList = new ArrayList();
_minerFileList = new ArrayList();
_connectedList = new ArrayList();
}
/**
* Loads all miners that are specified in the default <i>minerFile.dat</i> as
* well as any others indicated by <code>DataStore.getMinersLocation</code> that
* have not yet been loaded.
*/
public void loadMiners()
{
// load the miners
String pluginDir = _dataStore.getAttribute(DataStoreAttributes.A_PLUGIN_PATH);
// default location
String defaultMinerFile = pluginDir + File.separator + "minerFile.dat";
File defaultMF = new File(defaultMinerFile);
if (defaultMF.exists())
{
try
{
loadMiners(defaultMinerFile, DE.ENCODING_UTF_8);
}
catch (Exception e)
{
_dataStore.trace("failed to load minerFile.data with UTF-8. Trying with native encoding");
try
{
loadMiners(defaultMinerFile, null);
}
catch (Exception ex)
{
_dataStore.trace(ex);
}
}
_minerFileList.add(defaultMinerFile);
}
ArrayList minerLocations = _dataStore.getMinersLocation();
for (int i = 0; i < minerLocations.size(); i++)
{
String minersDir = (String) minerLocations.get(i);
String minerFile = null;
if (minersDir.endsWith(".dat"))
{
minerFile = pluginDir + File.separator + minersDir;
}
else
{
minerFile = pluginDir + File.separator + minersDir + File.separator + "minerFile.dat";
}
//_dataStore.trace("load miners for " + minerFile);
if (!_minerFileList.contains(minerFile))
{
try
{
loadMiners(minerFile, DE.ENCODING_UTF_8);
}
catch (Exception e)
{
_dataStore.trace("failed to load minerFile.data with UTF-8. Trying with native encoding");
try
{
loadMiners(minerFile, null);
}
catch (Exception ex)
{
_dataStore.trace(ex);
}
}
_minerFileList.add(minerFile);
}
}
}
/**
* Loads that miners specified in a particular miner configuration file (i.e. <i>minerFile.dat</i>)
* @param minerFile a file specifying a list of miners
* @return a list of the loaded miners
*/
public ArrayList loadMiners(String minerFile, String encoding) throws Exception
{
// load the miners
ArrayList unconnectedMiners = new ArrayList();
File file = new File(minerFile);
FileInputStream inFile = new FileInputStream(file);
BufferedReader in = null;
if (encoding == null)
{
in = new BufferedReader(new InputStreamReader(inFile));
}
else
{
in = new BufferedReader(new InputStreamReader(inFile, encoding));
}
String name = null;
while ((name = in.readLine()) != null)
{
// check name
name = name.trim();
if (!name.startsWith("#") && (name.length() > 5))
{
Miner miner = loadMiner(name);
if (miner != null)
{
unconnectedMiners.add(miner);
}
}
}
connectMiners(unconnectedMiners);
return _miners;
}
public Miner loadMiner(String name)
{
Miner miner = null;
if (!_minerList.contains(name))
{
// only load new miners
try
{
ExternalLoader loader = getLoaderFor(name);
if (loader != null)
{
// try to load and instantiate the miner
// the RemoteClassLoader will kick off a synchronous
// request to the client for any classes that cannot be found
// on the host.
Class theClass = loader.loadClass(name);
miner = (Miner) theClass.newInstance();
if (miner != null)
{
miner.setExternalLoader(loader);
_minerList.add(name);
}
}
}
catch (NoClassDefFoundError e)
{
e.printStackTrace();
handleNoClassFound(e.getMessage().replace('/','.'));
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
handleNoClassFound(name);
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
}
return miner;
}
private void handleNoClassFound(String name)
{
_remoteLoader.loadClassInThread(name);
}
private void connectMiners(ArrayList unconnectedMiners)
{
// init list
for (int i = 0; i < _miners.size(); i++)
{
_connectedList.add(((Miner) _miners.get(i)).getMinerName());
}
while (unconnectedMiners.size() > 0)
{
Miner miner = (Miner) unconnectedMiners.get(0);
unconnectedMiners.remove(miner);
if (connectMiner(miner))
{
_dataStore.trace("connected " + miner.getMinerName());
}
else
{
unconnectedMiners.add(miner);
}
}
}
public boolean connectMiner(Miner miner)
{
boolean canConnect = true;
ArrayList dependencies = miner.getMinerDependencies();
for (int i = 0; i < dependencies.size(); i++)
{
String dependency = (String) dependencies.get(i);
if (!_connectedList.contains(dependency))
{
canConnect = false;
}
}
if (canConnect)
{
// set the datastore for the miner
miner.setDataStore(_dataStore);
miner.extendSchema(_dataStore.getDescriptorRoot());
_dataStore.refresh(_dataStore.getDescriptorRoot());
_miners.add(miner);
_connectedList.add(miner.getMinerName());
miner.start();
}
return canConnect;
}
/**
* Currently not used for the miner loader
*/
public void registerSchemaExtender(ISchemaExtender extender)
{
}
/**
* Calls <code>extendSchema</code> on each of the loaded miners
*
* @param dataStore the DataStore containing the base schema to extend
*/
public void extendSchema(DataStore dataStore)
{
DataElement schemaRoot = dataStore.getDescriptorRoot();
for (int i = 0; i < _miners.size(); i++)
{
Miner miner = (Miner) _miners.get(i);
miner.extendSchema(schemaRoot);
}
}
public ExternalLoader getExternalRemoteLoader()
{
if (_externalRemoteLoader == null)
{
_externalRemoteLoader = new ExternalLoader(getRemoteLoader(), "*");
}
return _externalRemoteLoader;
}
public RemoteClassLoader getRemoteLoader()
{
return _dataStore.getRemoteClassLoader();
}
/**
* Returns the <code>ExternalLoader</code> for a particular
* class.
*
* @param source a qualified classname
* @return the loader for the specified class
*/
public ExternalLoader getLoaderFor(String source)
{
ExternalLoader remoteLoader = getExternalRemoteLoader();
// for now we always return the RemoteClassLoader
//if (remoteLoader.canLoad(source))
if(true)
{
//System.out.println("using RemoteClassLoader");
return remoteLoader;
}
for (int i = 0; i < _loaders.size(); i++)
{
ExternalLoader loader = (ExternalLoader) _loaders.get(i);
if (loader.canLoad(source))
{
// System.out.println("using local loader");
return loader;
}
else
{
}
}
return null;
}
/**
* Returns the loaded miners
*
* @return the loaded miners
*/
public ArrayList getMiners()
{
return _miners;
}
/**
* Returns the miner indicated with the specified name
*
* @param name the qualified classname of the miner
* @return the miner
*/
public Miner getMiner(String name)
{
for (int i = 0; i < _miners.size(); i++)
{
Miner miner = (Miner) _miners.get(i);
if (miner.getClass().getName().equals(name))
{
return miner;
}
}
return null;
}
/**
* Terminates the specified miner
*
* @param name the qualified classname of the miner to terminate
*/
public void finishMiner(String name)
{
Miner miner = getMiner(name);
miner.finish();
_miners.remove(miner);
}
/**
* Terminate all the miners
*/
public void finishMiners()
{
for (int i = 0; i < _miners.size(); i++)
{
Miner miner = (Miner) _miners.get(i);
miner.finish();
}
}
}

View file

@ -0,0 +1,158 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.server;
import java.util.StringTokenizer;
/**
* Server is the standard way of instantiating and controlling a remote DataStore.
* The server runs a ConnectionEstablisher which manages client connections to
* the DataStore.
*
*/
public class Server
{
private ConnectionEstablisher _establisher;
/**
* The startup interface to run the Server.
*
* @param args a list of arguments for running the server. These consist of
* the socket port to wait on, the timeout value, and the the ticket
*/
public static void main(String[] args)
{
String jversion = System.getProperty("java.version");
StringTokenizer tokenizer = new StringTokenizer(jversion, ".");
try
{
String[] vers = new String[3];
vers[0] = tokenizer.nextToken();
vers[1] = tokenizer.nextToken();
int version = Integer.parseInt(vers[0]);
int major = Integer.parseInt(vers[1]);
if (version >= 1 && major >= 4)
{
// version is good
}
else
{
// version is bad
System.err.println(ServerReturnCodes.RC_JRE_VERSION_ERROR);
System.exit(-1);
}
}
catch (Exception e)
{
// version is bad
System.err.println(ServerReturnCodes.RC_JRE_VERSION_ERROR);
System.exit(-1);
}
try
{
Server theServer = null;
switch (args.length)
{
case 0 :
theServer = new Server();
break;
case 1 :
theServer = new Server(args[0]);
break;
case 2 :
theServer = new Server(args[0], args[1]);
break;
case 3 :
theServer = new Server(args[0], args[1], args[2]);
break;
default :
break;
}
if (theServer != null)
{
theServer.run();
}
}
catch (SecurityException e)
{
System.err.println(ServerReturnCodes.RC_SECURITY_ERROR);
throw e; // Optional
}
}
/**
* Creates a new Server with default DataStore and connection attributes.
*
*/
public Server()
{
_establisher = new ConnectionEstablisher();
}
/**
* Creates a new Server that waits on the specified socket port.
*
* @param port the number of the socket port to wait on
*/
public Server(String port)
{
_establisher = new ConnectionEstablisher(port);
}
/**
* Creates a new Server that waits on the specified socket port for
* the specified time interval before shutting down.
*
* @param port the number of the socket port to wait on
* @param timeout the idle time to wait before shutting down
*/
public Server(String port, String timeout)
{
_establisher = new ConnectionEstablisher(port, timeout);
}
/**
* Creates a new Server that waits on the specified socket port for
* the specified time interval before shutting down.
*
* @param port the number of the socket port to wait on
* @param timeout the idle time to wait before shutting down
* @param ticket the ticket that the client needs to interact with the DataStore
*/
public Server(String port, String timeout, String ticket)
{
_establisher = new ConnectionEstablisher(port, timeout, ticket);
}
/**
* Runs the server by starting the ConnectionEstablisher
*/
public void run()
{
_establisher.start();
}
}

View file

@ -0,0 +1,72 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.server;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.eclipse.dstore.core.model.DataStoreAttributes;
/**
* This class is used to store attributes that are required
* for configurating a remote connection.
*/
public class ServerAttributes extends DataStoreAttributes
{
/**
* Constructor
*/
public ServerAttributes()
{
super();
try
{
String pluginPath = System.getProperty("A_PLUGIN_PATH");
if (pluginPath != null) pluginPath = pluginPath.trim();
if ((pluginPath != null) && (pluginPath.length() > 0))
{
File f = new File(pluginPath);
try
{
pluginPath = f.getCanonicalPath();
}
catch (Exception e)
{
pluginPath = f.getAbsolutePath();
}
setAttribute(A_PLUGIN_PATH, pluginPath + File.separator);
}
else
{
setAttribute(A_PLUGIN_PATH, "/home/");
}
setAttribute(A_LOCAL_NAME, InetAddress.getLocalHost().getHostName());
setAttribute(A_HOST_NAME, "server_host");
setAttribute(A_HOST_PATH, "/home/");
}
catch (UnknownHostException e)
{
}
}
}

View file

@ -0,0 +1,492 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.server;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.dstore.core.java.IRemoteClassInstance;
import org.eclipse.dstore.core.miners.miner.Miner;
import org.eclipse.dstore.core.model.CommandHandler;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
import org.eclipse.dstore.core.model.DataStoreAttributes;
import org.eclipse.dstore.core.model.DataStoreResources;
import org.eclipse.dstore.core.model.DataStoreSchema;
/**
* The ServerCommandHandler is reponsible for maintaining
* a queue of commands and periodically routing commands
* from the queue to the appropriate miners.
*/
public class ServerCommandHandler extends CommandHandler
{
private ArrayList _loaders;
private MinerLoader _minerLoader;
/**
* Constructor
*
* @param loaders a list of <code>ExternalLoader</code>s used for loading miners
*/
public ServerCommandHandler(ArrayList loaders)
{
super();
_loaders = loaders;
}
/**
* Sets the associated DataStore
*
* @param dataStore the associated DataStore
*/
public void setDataStore(DataStore dataStore)
{
super.setDataStore(dataStore);
}
/**
* Loads the miners
*/
public void loadMiners()
{
if (_dataStore != null)
{
if (_minerLoader == null)
{
_minerLoader = new MinerLoader(_dataStore, _loaders);
}
// load the miners
_minerLoader.loadMiners();
}
}
public Miner loadMiner(String minerId)
{
if (_dataStore != null)
{
if (_minerLoader == null)
{
_minerLoader = new MinerLoader(_dataStore, _loaders);
}
// load and connect the miner
Miner miner = _minerLoader.loadMiner(minerId);
if (miner != null)
{
_minerLoader.connectMiner(miner);
}
return miner;
}
return null;
}
/**
* Returns the list of loaded miners
*
* @return the list of miners
*/
public ArrayList getMiners()
{
return _minerLoader.getMiners();
}
/**
* Returns the specified miner
*
* @param name the qualified classname of the miner to return
* @return the miner
*/
public Miner getMiner(String name)
{
return _minerLoader.getMiner(name);
}
/**
* Terminates a specified miner
*
* @param name the qualified classname of the miner to terminate
*/
public void finishMiner(String name)
{
_minerLoader.finishMiner(name);
}
/**
* Called when the DataStore session is finished or when there is
* an unexpected error.
*/
public void finish()
{
if (_minerLoader != null)
_minerLoader.finishMiners();
super.finish();
}
private void clearDeleted(DataElement element, int depth)
{
if (depth > 0 && element != null)
{
for (int i = 0; i < element.getNestedSize(); i++)
{
DataElement child = element.get(i);
if (child != null)
{
if (child.isReference())
child = child.dereference();
if (child != null)
{
if (child.isDeleted())
{
element.removeNestedData(child);
}
else
{
clearDeleted(child, depth - 1);
}
}
}
}
}
}
/**
* Called periodically to route the current queue of commands to the appropriate miners
*/
public void sendCommands()
{
// send commands to the appropriate miners
while (_commands.size() > 0)
{
DataElement command = null;
synchronized (_commands)
{
command = (DataElement) _commands.get(0);
clearDeleted(command, 2);
_commands.remove(command);
}
//DKM-status is always last
DataElement status = command.get(command.getNestedSize() - 1);
//_dataStore.find(command, DE.A_TYPE,DataStoreResources.model_status"), 1);
String commandSource = command.getSource();
String commandName = command.getName();
_dataStore.trace("command: " + commandName);
//System.out.println(commandName);
if (commandName.equals(DataStoreSchema.C_VALIDATE_TICKET))
{
DataElement serverTicket = _dataStore.getTicket();
DataElement clientTicket = (DataElement) command.get(0);
String st = serverTicket.getName();
String ct = clientTicket.getName();
if (ct.equals(st))
{
serverTicket.setAttribute(DE.A_VALUE,DataStoreResources.model_valid);
clientTicket.setAttribute(DE.A_VALUE,DataStoreResources.model_valid);
DataElement host = _dataStore.getHostRoot();
_dataStore.getHashMap().remove(host.getId());
host.setAttribute(DE.A_ID, "host." + serverTicket.getName());
_dataStore.getHashMap().put(host.getId(), host);
_dataStore.update(host);
}
else
{
serverTicket.setAttribute(DE.A_VALUE,DataStoreResources.model_invalid);
clientTicket.setAttribute(DE.A_VALUE,DataStoreResources.model_invalid);
}
_dataStore.update(clientTicket);
status.setAttribute(DE.A_NAME,DataStoreResources.model_done);
}
else if (commandName.equals(DataStoreSchema.C_SET))
{
DataElement dataObject = (DataElement) command.get(0);
status.setAttribute(DE.A_NAME,DataStoreResources.model_done);
}
else if (commandName.equals(DataStoreSchema.C_MODIFY))
{
DataElement dataObject = (DataElement) command.get(0);
DataElement original = _dataStore.find(dataObject.getId());
original.setAttributes(dataObject.getAttributes());
status.setAttribute(DE.A_NAME,DataStoreResources.model_done);
}
else if (commandName.equals(DataStoreSchema.C_SET_HOST))
{
DataElement dataObject = (DataElement) command.get(0);
DataElement original = _dataStore.getHostRoot();
original.setAttributes(dataObject.getAttributes());
_dataStore.setAttribute(DataStoreAttributes.A_LOCAL_PATH, dataObject.getSource());
_dataStore.setAttribute(DataStoreAttributes.A_HOST_PATH, dataObject.getSource());
status.setAttribute(DE.A_NAME,DataStoreResources.model_done);
}
else if (commandName.equals(DataStoreSchema.C_ADD_MINERS))
{
DataElement location = (DataElement) command.get(1);
_dataStore.addMinersLocation(location);
status.setAttribute(DE.A_NAME,DataStoreResources.model_done);
}
else if (commandName.equals(DataStoreSchema.C_ACTIVATE_MINER))
{
DataElement minerId = (DataElement) command.get(0);
String minerName = minerId.getName();
Miner miner = loadMiner(minerName);
miner.initMiner(status);
//System.out.println("finished initing "+miner.getMinerName());
//status.setAttribute(DE.A_NAME,DataStoreResources.model_done);
}
else if (commandName.equals(DataStoreSchema.C_SET_PREFERENCE))
{
DataElement dataObject = (DataElement) command.get(0);
String property = dataObject.getName();
String value = dataObject.getValue();
_dataStore.setPreference(property, value);
}
else if (commandName.equals(DataStoreSchema.C_QUERY_INSTALL))
{
// determine where dstore is located
status.setAttribute(DE.A_SOURCE, _dataStore.getAttribute(DataStoreAttributes.A_PLUGIN_PATH));
status.setAttribute(DE.A_NAME,DataStoreResources.model_done);
}
else if (commandName.equals(DataStoreSchema.C_QUERY_CLIENT_IP))
{
// determine where dstore is connected to
status.setAttribute(DE.A_SOURCE, _dataStore.getRemoteIP());
status.setAttribute(DE.A_NAME,DataStoreResources.model_done);
}
else if (commandName.equals(DataStoreSchema.C_QUERY_JVM))
{
// get jvm stats
// check memory consuption
// if we're running low, try to free some
Runtime runtime = Runtime.getRuntime();
runtime.gc();
long freeMem = runtime.freeMemory();
long totalMem = runtime.totalMemory();
long maxMem = runtime.maxMemory();
StringBuffer statsBuffer = new StringBuffer();
statsBuffer.append(freeMem);
statsBuffer.append(',');
statsBuffer.append(totalMem);
statsBuffer.append(',');
statsBuffer.append(maxMem);
statsBuffer.append(',');
statsBuffer.append(_dataStore.getNumElements());
statsBuffer.append(',');
// last 7 dataelements created
List lastCreated = _dataStore.getLastCreatedElements();
for (int i = 0; i < lastCreated.size(); i++)
{
DataElement element = (DataElement)lastCreated.get(i);
statsBuffer.append(element.getName());
statsBuffer.append(":");
statsBuffer.append("id="+element.getId());
statsBuffer.append(";");
}
status.setAttribute(DE.A_SOURCE, statsBuffer.toString());
status.setAttribute(DE.A_NAME,DataStoreResources.model_done);
}
else if (commandName.equals(DataStoreSchema.C_SCHEMA))
{
loadMiners();
DataElement schemaRoot = _dataStore.getDescriptorRoot();
// update all descriptor objects
_dataStore.refresh(schemaRoot);
status.setAttribute(DE.A_NAME,DataStoreResources.model_done);
}
else if (_dataStore.validTicket())
{
if (status != null)
{
boolean failure = false;
ArrayList miners = _minerLoader.getMiners();
for (int j = 0;(j < miners.size()) && !failure; j++)
{
Miner miner = (Miner) miners.get(j);
if (commandSource.equals("*") || commandSource.equals(miner.getClass().getName()))
{
if (_dataStore.isAutoRefreshOn())
{
_dataStore.enableAutoRefresh(false);
}
/*
status = miner.command(command);
if ((status != null) && status.getAttribute(DE.A_NAME).equals(DataStoreResources.model_incomplete))
{
failure = true;
}
*/
miner.requestCommand(command);
}
}
if (commandName.equals(DataStoreSchema.C_INIT_MINERS))
{
// old way was to submit this command for all miners at once
// now we wait til activateMiner call is made per each miner
// for backward compatibility, we still call init miners
// so we need to make sure, in cases were miners are loaded dynamically,
// that we set this to done if there's no miners to init
status.setAttribute(DE.A_NAME, DataStoreResources.model_done);
}
}
}
_dataStore.refresh(status);
}
}
/**
* Set the contents of a file with the specified file
* @param fileName the name of the target file
* @param file the source file
*/
public void sendFile(String fileName, File file)
{
//_dataStore.saveFile(fileName, file);
}
/**
* Sets the contents of a file with bytes sent from the client
* @param fileName the name of the file to append to
* @param bytes the bytes of a file to insert
* @param size the number of bytes to insert
* @param binary indicates whether to insert the bytes as binary or unicode
*/
public void sendFile(String fileName, byte[] bytes, int size, boolean binary)
{
sendFile(fileName, bytes, size, binary, "default");
}
/**
* Sets the contents of a file with bytes sent from the client
* @param fileName the name of the file to append to
* @param bytes the bytes of a file to insert
* @param size the number of bytes to insert
* @param binary indicates whether to insert the bytes as binary or unicode
* @param byteStreamHandlerId indicates which byte stream handler should receive the bytes
*/
public void sendFile(String fileName, byte[] bytes, int size, boolean binary, String byteStreamHandlerId)
{
_dataStore.saveFile(fileName, bytes, size, binary, byteStreamHandlerId);
}
/**
* Appends bytes sent from the client to a file
* @param fileName the name of the file to append to
* @param bytes the bytes of a file to append
* @param size the number of bytes to append
* @param binary indicates whether to append the bytes as binary or unicode
*/
public void sendAppendFile(String fileName, byte[] bytes, int size, boolean binary)
{
sendAppendFile(fileName, bytes, size, binary, "default");
}
/**
* Appends bytes sent from the client to a file
* @param fileName the name of the file to append to
* @param bytes the bytes of a file to append
* @param size the number of bytes to append
* @param binary indicates whether to append the bytes as binary or unicode
* @param byteStreamHandlerId indicates which byte stream handler should receive the bytes
*/
public void sendAppendFile(String fileName, byte[] bytes, int size, boolean binary, String byteStreamHandlerId)
{
_dataStore.appendToFile(fileName, bytes, size, binary);
}
/**
* Implemented to provide the means by which classes are requested and sent
* across the comm channel.
* @param className the name of the class to request
*/
public synchronized void sendClass(String className)
{
sendClass(className, "default");
}
/**
* Implemented to provide the means by which classes are requested and sent
* across the comm channel.
* @param className the name of the class to request
*/
public synchronized void sendClass(String className, String classByteStreamHandlerId)
{
//_dataStore.sendClass(className, classByteStreamHandlerId);
}
public void sendClassInstance(IRemoteClassInstance runnable, String classByteStreamHandlerId)
{
notifyInput();
}
/**
* Does not apply to server. Use ServerUpdateHandler.requestClass().
*/
public void requestClass(String className)
{
}
/**
* Does not apply to server. Use ServerUpdateHandler.sendKeepAliveConfirmation().
*/
public void sendKeepAliveConfirmation()
{
}
/**
* Does not apply to server. Use ServerUpdateHandler.sendKeepAliveRequest().
*/
public void sendKeepAliveRequest()
{
}
}

View file

@ -0,0 +1,548 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.ISSLProperties;
import org.eclipse.dstore.core.util.ssl.DStoreSSLContext;
/**
* This class is the DataStore daemon. It is used for authenticating users,
* launching DataStore servers under particular user IDs, and providing a
* client with enough information to conntect to a launched server.
*/
public class ServerLauncher extends Thread
{
/**
* An instances of this class get loaded whenever a client requests access
* to a DataStore server. The ConnectionListener attempts to launch a server
* under the client user's ID, communicating back information to the client
* so that if may connect to the launched server. If the authentification and
* connection to the server are successful, ConnectionListener continues to
* monitor the server connection until it is terminated.
*/
public class ConnectionListener extends Thread implements HandshakeCompletedListener
{
private Socket _socket;
private PrintWriter _writer;
private BufferedReader _reader;
private Process _serverProcess;
private String _port;
private boolean _done;
private BufferedReader _outReader;
private BufferedReader _errReader;
/**
* Constructor
* @param socket a socket to the daemon
*/
public ConnectionListener(Socket socket)
{
_socket = socket;
try
{
_writer = new PrintWriter(new OutputStreamWriter(_socket.getOutputStream(), DE.ENCODING_UTF_8));
_reader = new BufferedReader(new InputStreamReader(_socket.getInputStream(), DE.ENCODING_UTF_8));
}
catch (java.io.IOException e)
{
System.out.println("ServerLauncher:" + e);
}
}
/**
* Called when shutdown
*/
public void finalize() throws Throwable
{
if (_serverProcess != null)
{
_serverProcess.destroy();
}
super.finalize();
}
/**
* Listens to the connection and prints any output while the connection
* is active
*/
public void run()
{
_done = true;
if (listen())
{
if (_serverProcess != null)
{
_done = false;
try
{
String line = null;
while ((_outReader != null) && ((line = _outReader.readLine()) != null))
{
if (line.equals(ServerReturnCodes.RC_FINISHED))
{
break;
}
else
{
System.out.println(line);
}
}
if (_outReader != null)
{
_outReader.close();
}
if (_errReader != null)
{
_errReader.close();
}
_serverProcess.waitFor();
}
catch (Exception e)
{
System.out.println("ServerLauncher:" + e);
}
}
System.out.println("finished on port " + _port);
_outReader = null;
_errReader = null;
_serverProcess = null;
_done = true;
}
else
{
_done = true;
}
}
/**
* Indicates whether the connection has terminated or not
* @return true if the connection has terminated
*/
public boolean isDone()
{
return _done;
}
/**
* Returns the DataStore server port used
* @return the server port
*/
public String getServerPort()
{
return _port;
}
/**
* Attempt to start a new DataStore server. The port and the ticket for a
* newly started DataStore are captured and sent back to the client so that it
* may connect to the server.
*
* @return whether the server started successfully
*/
public boolean listen()
{
boolean connected = false;
String user = null;
String password = null;
_port = null;
try
{
user = _reader.readLine();
password = _reader.readLine();
_port = _reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
_port = "0";
}
{
// start new server
try
{
String launchStatus = null;
String ticket = new String("" + System.currentTimeMillis());
String theOS = System.getProperty("os.name");
String timeout = "120000";
if (!theOS.toLowerCase().startsWith("win"))
{
// assuming unix compatable
//
// Get the property which
// contains the authorization
// script path
//
String authPath = System.getProperty("RSE.AUTH");
File authFile = null;
if (authPath != null && authPath.length() > 0)
{
authFile = new File(authPath);
}
if (authFile == null || !authFile.exists())
{
authPath = "perl " + _path + File.separator + "auth.pl";
}
String authString =
authPath
+ " "
+ user
+ " "
+ _path
+ " "
+ _port
+ " "
+ timeout
+ " "
+ ticket
;
String[] authArray = { "sh", "-c", authString };
// test password
_serverProcess = Runtime.getRuntime().exec(authArray);
_outReader = new BufferedReader(new InputStreamReader(_serverProcess.getInputStream()));
_errReader = new BufferedReader(new InputStreamReader(_serverProcess.getErrorStream()));
BufferedWriter inWriter = new BufferedWriter(new OutputStreamWriter(_serverProcess.getOutputStream()));
// write password
inWriter.write(password);
inWriter.newLine();
inWriter.flush();
launchStatus = _outReader.readLine();
}
else
{
// launch new server
String[] cmdArray =
{
"java",
"-DA_PLUGIN_PATH=" + _path,
"org.eclipse.dstore.core.server.Server",
_port,
timeout,
ticket};
_serverProcess = Runtime.getRuntime().exec(cmdArray);
_outReader = new BufferedReader(new InputStreamReader(_serverProcess.getInputStream()));
_errReader = new BufferedReader(new InputStreamReader(_serverProcess.getErrorStream()));
launchStatus = "success";
}
if ((launchStatus == null) || !launchStatus.equals("success"))
{
_writer.println("Authentification Failed");
}
else
{
String status = _errReader.readLine();
_port = _errReader.readLine();
if ((status != null) && status.equals(ServerReturnCodes.RC_SUCCESS))
{
_errReader.readLine();
_writer.println("connected");
_writer.println(_port);
_writer.println(ticket);
System.out.println("launched new server on " + _port);
connected = true;
}
else
{
if (status == null)
{
status = new String("unknown problem connecting to server");
}
_writer.println(status);
_serverProcess.destroy();
_serverProcess = null;
_outReader.close();
_outReader = null;
_errReader.close();
_errReader = null;
}
}
}
catch (IOException e)
{
_writer.println("server failure: " + e);
}
}
_writer.flush();
// close socket
try
{
_socket.close();
}
catch (IOException e)
{
System.out.println("ServerLauncher:" + e);
}
return connected;
}
public void handshakeCompleted(HandshakeCompletedEvent event)
{
System.out.println("handshake completed");
System.out.println(event);
}
}
private ServerSocket _serverSocket;
private String _path;
private ArrayList _connections;
private ISSLProperties _sslProperties;
public static int DEFAULT_DAEMON_PORT = 4035;
/**
* Constructor
*/
public ServerLauncher()
{
String pluginPath = System.getProperty("A_PLUGIN_PATH");
if (pluginPath == null)
{
System.out.println("A_PLUGIN_PATH is not defined");
System.exit(-1);
}
_path = pluginPath.trim();
_connections = new ArrayList();
init(DEFAULT_DAEMON_PORT);
}
/**
* Constructor
* @param portStr the port for the daemon socket to run on
*/
public ServerLauncher(String portStr)
{
String pluginPath = System.getProperty("A_PLUGIN_PATH");
if (pluginPath == null)
{
System.out.println("A_PLUGIN_PATH is not defined");
System.exit(-1);
}
_path = pluginPath.trim();
_connections = new ArrayList();
int port = Integer.parseInt(portStr);
init(port);
}
private String getKeyStoreLocation()
{
return _sslProperties.getDaemonKeyStorePath();
}
private String getKeyStorePassword()
{
return _sslProperties.getDaemonKeyStorePassword();
}
/**
* initializes the DataStore daemon
*
* @param port the daemon port
*/
public void init(int port)
{
// create server socket from port
_sslProperties = new ServerSSLProperties();
try
{
if (_sslProperties.usingSSL())
{
String keyStoreFileName = getKeyStoreLocation();
String keyStorePassword = getKeyStorePassword();
try
{
SSLContext sslContext = DStoreSSLContext.getServerSSLContext(keyStoreFileName, keyStorePassword);
_serverSocket = sslContext.getServerSocketFactory().createServerSocket(port);
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
_serverSocket = new ServerSocket(port);
}
System.out.println("Daemon running on: " + InetAddress.getLocalHost().getHostName() + ", port: " + port);
}
catch (UnknownHostException e)
{
System.err.println("Networking problem, can't resolve local host");
e.printStackTrace();
System.exit(-1);
}
catch (IOException e)
{
System.err.println("Failure to create ServerSocket");
e.printStackTrace();
System.exit(-1);
}
}
/**
* Return the connection listener for the specified port if there is one
* @param port the port
* @return the listener associated with the port
*/
protected ConnectionListener getListenerForPort(String port)
{
for (int i = 0; i < _connections.size(); i++)
{
ConnectionListener listener = (ConnectionListener) _connections.get(i);
if (listener.getServerPort().equals(port))
{
return listener;
}
}
return null;
}
/**
* Run the daemon
*/
public void run()
{
while (true)
{
try
{
boolean connectionOkay = true;
Socket newSocket = _serverSocket.accept();
if (_sslProperties.usingSSL())
{
SSLSocket sslSocket = (SSLSocket) newSocket;
sslSocket.addHandshakeCompletedListener(new HandshakeCompletedListener()
{
public void handshakeCompleted(HandshakeCompletedEvent event)
{
System.out.println("handshake completed");
}
});
SSLSession session = sslSocket.getSession();
if (session == null)
{
System.out.println("handshake failed");
sslSocket.close();
connectionOkay = false;
}
}
if (connectionOkay)
{
ConnectionListener listener = new ConnectionListener(newSocket);
listener.start();
_connections.add(listener);
}
}
catch (IOException ioe)
{
System.err.println("Server: error initializing socket: " + ioe);
System.exit(-1);
}
}
}
/**
* Entry point into the DataStore daemon
*
* @param args the port for the daemon to run on (default is 4035). Optionally, the second arg specifies whether to use SSL or not.
*/
public static void main(String args[])
{
if (args.length > 0)
{
ServerLauncher theServer = new ServerLauncher(args[0]);
theServer.start();
}
else
{
ServerLauncher theServer = new ServerLauncher();
theServer.start();
}
}
}

View file

@ -0,0 +1,91 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.server;
import java.net.Socket;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.util.Receiver;
/**
* The ServerReciever is responsible for recieving data from
* the client side.
*/
public class ServerReceiver extends Receiver
{
private ConnectionEstablisher _connection;
/**
* Constructor
*
* @param socket the socket to receive from
* @param connection the connection establisher
*/
public ServerReceiver(Socket socket, ConnectionEstablisher connection)
{
super(socket, connection.getDataStore());
_connection = connection;
}
/**
* Implementation for handling the receiving on documents on
* the server side.
*
* @param documentObject to tree root of received data.
*/
public void handleDocument(DataElement documentObject)
{
// parse request and determine what is wanted
for (int a = 0; a < documentObject.getNestedSize(); a++)
{
DataElement rootOutput = (DataElement) documentObject.get(a);
DataElement log = _dataStore.getLogRoot();
log.addNestedData(rootOutput, false);
if (rootOutput.getName().equals("C_EXIT"))
{
finish();
}
else
{
_dataStore.command(rootOutput);
}
}
}
public void finish()
{
super.finish();
_connection.finished(this);
}
/**
* @see Receiver#finish()
*/
public void handleError(Throwable e)
{
System.out.println("RECEIVER ERROR");
// e.printStackTrace();
System.out.println(e);
_connection.finished(this);
}
}

View file

@ -0,0 +1,39 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.server;
/**
* This class contains a list of server return codes that are used
* to negociate server communication with a client
*/
public class ServerReturnCodes
{
public static final String RC_SUCCESS = "Server Started Successfully";
public static final String RC_UNKNOWN_HOST_ERROR = "Unknown host error";
public static final String RC_BIND_ERROR = "Error binding socket";
public static final String RC_GENERAL_IO_ERROR = "General IO error creating socket";
public static final String RC_CONNECTION_ERROR = "Connection error";
public static final String RC_SECURITY_ERROR = "Security error creating socket";
public static final String RC_FINISHED = "Server Finished";
public static final String RC_JRE_VERSION_ERROR = "JRE 1.4 or higher required";
}

View file

@ -0,0 +1,125 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.server;
import java.util.ResourceBundle;
import org.eclipse.dstore.core.model.ISSLProperties;
public class ServerSSLProperties implements ISSLProperties
{
private boolean _enableSSL = false;
private String _daemonKeyStorePath;
private String _daemonKeyStorePassword;
private String _serverKeyStorePath;
private String _serverKeyStorePassword;
private static final String ENABLE_SSL = "enable_ssl";
private static final String DAEMON_KEYSTORE_FILE = "daemon_keystore_file";
private static final String DAEMON_KEYSTORE_PASSWORD = "daemon_keystore_password";
private static final String SERVER_KEYSTORE_FILE = "server_keystore_file";
private static final String SERVER_KEYSTORE_PASSWORD = "server_keystore_password";
public ServerSSLProperties()
{
try
{
ResourceBundle properties = ResourceBundle.getBundle("ssl");
_enableSSL = properties.getString(ENABLE_SSL).equals("true");
if (_enableSSL)
{
try
{
_daemonKeyStorePath = properties.getString(DAEMON_KEYSTORE_FILE);
_daemonKeyStorePassword = properties.getString(DAEMON_KEYSTORE_PASSWORD);
}
catch (Exception e)
{
}
try
{
_serverKeyStorePath = properties.getString(SERVER_KEYSTORE_FILE);
_serverKeyStorePassword = properties.getString(SERVER_KEYSTORE_PASSWORD);
}
catch (Exception e)
{
}
if (_daemonKeyStorePath == null && _serverKeyStorePath != null)
{
_daemonKeyStorePath = _serverKeyStorePath;
_daemonKeyStorePassword = _serverKeyStorePassword;
}
if (_serverKeyStorePath == null && _daemonKeyStorePath != null)
{
_serverKeyStorePath = _daemonKeyStorePath;
_serverKeyStorePassword = _daemonKeyStorePassword;
}
}
if (_enableSSL)
{
System.out.println("SSL Settings");
System.out.println("[daemon keystore:\t"+_daemonKeyStorePath+"]");
System.out.println("[daemon keystore pw:\t"+_daemonKeyStorePassword+"]");
System.out.println("[server keystore:\t"+_serverKeyStorePath+"]");
System.out.println("[server keystore pw:\t"+_serverKeyStorePassword+"]");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public boolean usingSSL()
{
return _enableSSL;
}
public String getDaemonKeyStorePath()
{
return _daemonKeyStorePath;
}
public String getServerKeyStorePath()
{
return _serverKeyStorePath;
}
public String getDaemonKeyStorePassword()
{
return _daemonKeyStorePassword;
}
public String getServerKeyStorePassword()
{
return _serverKeyStorePassword;
}
}

View file

@ -0,0 +1,453 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.server;
import java.net.Socket;
import java.util.ArrayList;
import org.eclipse.dstore.core.java.IRemoteClassInstance;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
import org.eclipse.dstore.core.model.DataStoreResources;
import org.eclipse.dstore.core.model.UpdateHandler;
import org.eclipse.dstore.core.util.CommandGenerator;
import org.eclipse.dstore.core.util.Sender;
/**
* The ServerUpdateHandler is contains a queue of data update requests
* and periodically transmits it's queue to the client
*/
public class ServerUpdateHandler extends UpdateHandler
{
private ArrayList _senders;
private CommandGenerator _commandGenerator;
protected DataElement _classDocumentElement;
protected DataElement _keepAliveDocumentElement;
protected DataElement _confirmKeepAliveDocumentElement;
protected DataElement _pendingKeepAliveRequest;
protected DataElement _pendingKeepAliveConfirmation;
private static String[] _keepAliveAttributes = {
DataStoreResources.KEEPALIVE_TYPE,
"server.keepalive.root.id",
"server.keepalive",
"doc",
"",
"",
DataStoreResources.FALSE,
"2"};
private static String[] _confirmKeepAliveAttributes = {
DataStoreResources.KEEPALIVECONFIRM_TYPE,
"server.keepalive.confirm.root.id",
"server.confirmkeepalive",
"doc",
"",
"",
DataStoreResources.FALSE,
"2"};
private static String[] _docAttributes = {
DataStoreResources.DOCUMENT_TYPE,
"server.doc.root.id",
"server.document",
"doc",
"",
"",
DataStoreResources.FALSE,
"2"};
private static String[] _fileAttributes = {
DataStoreResources.FILE_TYPE,
"server.file.root.id",
"server.file",
"doc",
"",
"",
DataStoreResources.FALSE,
"2"};
private static String[] _classAttributes = {
DataStoreResources.CLASS_TYPE,
"server.class.root.id",
"server.class",
"doc",
"",
"",
DataStoreResources.FALSE,
"2"};
private static String[] _requestClassAttributes = {
DataStoreResources.REQUEST_CLASS_TYPE,
"server.requestclass.root.id",
"server.requestclass",
"doc",
"",
"",
DataStoreResources.FALSE,
"2"};
private static String[] _serializeAttributes = {
DataStoreResources.SERIALIZED_TYPE,
"server.serialized.root.id",
"server.serialized",
"doc",
"",
"",
DataStoreResources.FALSE,
"2"};
protected DataElement _fileDocumentElement;
protected DataElement _docDocumentElement;
protected DataElement _requestClassDocumentElement;
protected DataElement _serializedDocumentElement;
/**
* Constructor
*/
public ServerUpdateHandler()
{
_senders = new ArrayList();
_commandGenerator = new CommandGenerator();
}
/**
* Sets the associated DataStore
*/
public void setDataStore(DataStore dataStore)
{
super.setDataStore(dataStore);
_commandGenerator.setDataStore(dataStore);
_fileDocumentElement = dataStore.createTransientObject(_fileAttributes);
_docDocumentElement = dataStore.createObject(null, _docAttributes);
_requestClassDocumentElement = dataStore.createTransientObject(_requestClassAttributes);
_serializedDocumentElement = dataStore.createTransientObject(_serializeAttributes);
_classDocumentElement = dataStore.createTransientObject(_classAttributes);
_keepAliveDocumentElement = dataStore.createTransientObject(_keepAliveAttributes);
_confirmKeepAliveDocumentElement = dataStore.createTransientObject(_confirmKeepAliveAttributes);
}
/**
* Add a sender to the list of senders. Normally there is only one
* client for the server, which requires one <code>Sender</code>. If
* there are more than one clients, then this is how senders are added.
*
* @param sender a sender connected to a socket
*/
public void addSender(Sender sender)
{
_senders.add(sender);
}
/**
* Remove a sender from the list of senders.
* @param sender the sender to remove
*/
public void removeSender(Sender sender)
{
_senders.remove(sender);
if (_senders.size() == 0)
{
finish();
}
}
/**
* Sends bytes to the specified file on the client.
*
* @param path the name of the file on the client
* @param bytes the bytes to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes and binary or text
*/
public synchronized void updateFile(String path, byte[] bytes, int size, boolean binary)
{
updateFile(path, bytes, size, binary, DataStoreResources.DEFAULT_BYTESTREAMHANDLER);
}
/**
* Sends bytes to the specified file on the client.
*
* @param path the name of the file on the client
* @param bytes the bytes to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes and binary or text
* @param byteStreamHandlerId indicates the byte stream handler to receive the bytes
*
*/
public synchronized void updateFile(String path, byte[] bytes, int size, boolean binary, String byteStreamHandlerId)
{
//DataElement document = _dataStore.createObject(null, DataStoreResources.FILE_TYPE, byteStreamHandlerId, path, path);
DataElement document = _fileDocumentElement;
document.setAttribute(DE.A_NAME, byteStreamHandlerId);
document.setAttribute(DE.A_VALUE, byteStreamHandlerId);
document.setAttribute(DE.A_SOURCE, path);
document.setPendingTransfer(true);
document.setParent(null);
for (int j = 0; j < _senders.size(); j++)
{
Sender sender = (Sender) _senders.get(j);
sender.sendFile(document, bytes, size, binary);
}
}
/**
* Appends bytes to the specified file on the client.
*
* @param path the name of the file on the client
* @param bytes the bytes to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes and binary or text
*/
public synchronized void updateAppendFile(String path, byte[] bytes, int size, boolean binary)
{
updateAppendFile(path, bytes, size, binary, DataStoreResources.DEFAULT_BYTESTREAMHANDLER);
}
/**
* Appends bytes to the specified file on the client.
*
* @param path the name of the file on the client
* @param bytes the bytes to send
* @param size the number of bytes to send
* @param binary indicates whether to send the bytes and binary or text
* @param byteStreamHandlerId indicates the byte stream handler to receive the bytes
*/
public synchronized void updateAppendFile(String path, byte[] bytes, int size, boolean binary, String byteStreamHandlerId)
{
//DataElement document = _dataStore.createObject(null, DataStoreResources.FILE_TYPE, byteStreamHandlerId, path, path);
DataElement document = _fileDocumentElement;
document.setAttribute(DE.A_NAME, byteStreamHandlerId);
document.setAttribute(DE.A_VALUE, byteStreamHandlerId);
document.setAttribute(DE.A_SOURCE, path);
document.setPendingTransfer(true);
document.setParent(null);
for (int j = 0; j < _senders.size(); j++)
{
Sender sender = (Sender) _senders.get(j);
sender.sendAppendFile(document, bytes, size, binary);
}
}
/**
* Periodically called on the handler thread to sends data updates.
*/
public void handle()
{
if (!_dataObjects.isEmpty() || _pendingKeepAliveConfirmation != null || _pendingKeepAliveRequest != null || !_classesToSend.isEmpty())
{
sendUpdates();
}
}
/**
* Periodically called to send data in the queue from the server to the client
*/
public void sendUpdates()
{
synchronized (_dataObjects)
{
//DataElement document = _dataStore.createObject(null, DataStoreResources.DOCUMENT_TYPE, "server.doc");
DataElement document = _docDocumentElement;
document.removeNestedData();
document.setPendingTransfer(true);
document.setUpdated(true);
document.setParent(null);
DataElement response = _commandGenerator.generateResponse(document, _dataObjects);
for (int j = 0; j < _senders.size(); j++)
{
Sender sender = (Sender) _senders.get(j);
sender.sendDocument(document, 5);
if (_pendingKeepAliveConfirmation != null)
{
sender.sendKeepAliveConfirmation(_pendingKeepAliveConfirmation);
_pendingKeepAliveConfirmation = null;
}
if (_pendingKeepAliveRequest != null)
{
sender.sendKeepAliveRequest(_pendingKeepAliveRequest);
_pendingKeepAliveRequest = null;
}
}
for (int i = 0; i < _dataObjects.size(); i++)
{
DataElement obj = (DataElement) _dataObjects.get(i);
clean(obj);
}
_dataObjects.clear();
//_dataStore.getLogRoot().removeNestedData();
//_dataStore.getTempRoot().removeNestedData();
}
// finished sending updates, now send all classes that are waiting
// in the queue
while (_classesToSend.size() > 0)
{
DataElement document = null;
synchronized (_classesToSend)
{
document = (DataElement)_classesToSend.remove(0);
for (int i = 0; i < _senders.size(); i++)
{
Sender sender = (Sender) _senders.get(i);
sender.sendClass(document);
}
}
}
}
/**
* Removes the sender that is associated with the specified socket. This causes
* A disconnect for the client that is associated with this socket.
*
* @param socket the socket on which a sender communicates
*/
public void removeSenderWith(Socket socket)
{
for (int i = 0; i < _senders.size(); i++)
{
Sender sender = (Sender) _senders.get(i);
if (sender.socket() == socket)
{
// sender sends last ack before death
DataElement document = _dataStore.createObject(null, DataStoreResources.DOCUMENT_TYPE, "exit", "exit");
sender.sendDocument(document, 2);
removeSender(sender);
}
}
}
/**
* Implemented to provide the means by which classes are sent
* across the comm channel.
* @param className the name of the class to request
*/
public synchronized void requestClass(String className)
{
DataElement document = _requestClassDocumentElement;
document.setPendingTransfer(true);
document.setAttribute(DE.A_NAME, className);
document.setAttribute(DE.A_VALUE, className);
document.setParent(null);
//DataElement document = _dataStore.createObject(null, DataStoreResources.REQUEST_CLASS_TYPE, className);
for (int j = 0; j < _senders.size(); j++)
{
Sender sender = (Sender) _senders.get(j);
sender.requestClass(document);
}
}
public synchronized void updateClassInstance(IRemoteClassInstance runnable, String deserializebyteStreamHandlerId)
{
DataElement document = _serializedDocumentElement;
document.setAttribute(DE.A_NAME, runnable.toString());
document.setAttribute(DE.A_SOURCE, deserializebyteStreamHandlerId);
document.setPendingTransfer(true);
document.setParent(null);
for (int j = 0; j < _senders.size(); j++)
{
Sender sender = (Sender) _senders.get(j);
sender.sendRemoteClassRunnable(document, runnable);
}
notifyInput();
}
/**
* Implemented to provide the means by which classes are sent
* across the comm channel.
* @param className the name of the class to send
* @param classbyteStreamHandlerId the name of the byte stream handler to use to receive the class
*/
public synchronized void sendClass(String className, String classByteStreamHandlerId)
{
// send pending updates before sending class
if (_dataObjects.size() > 0)
sendUpdates();
DataElement document = _classDocumentElement;
document.setAttribute(DE.A_NAME, className);
document.setAttribute(DE.A_SOURCE, classByteStreamHandlerId);
document.setPendingTransfer(true);
document.setParent(null);
addClassToSend(document);
}
/**
* Adds a class to the queue of classes (represented by DataElements) to
* be sent to the client.
* @param classElement the DataElement representing the class to be sent
*/
public void addClassToSend(DataElement classElement)
{
synchronized (_classesToSend)
{
if (!_classesToSend.contains(classElement))
{
_classesToSend.add(classElement);
}
}
}
/**
* Implemented to provide the means by which classes are requested and sent
* across the comm channel.
* @param className the name of the class to send
*/
public synchronized void sendClass(String className)
{
sendClass(className, "default");
}
public void sendKeepAliveRequest()
{
DataElement document = _keepAliveDocumentElement;
document.setPendingTransfer(true);
document.setAttribute(DE.A_NAME, "request");
document.setAttribute(DE.A_VALUE, "request");
document.setParent(null);
_pendingKeepAliveRequest = document;
}
public void sendKeepAliveConfirmation()
{
DataElement document = _confirmKeepAliveDocumentElement;
document.setPendingTransfer(true);
document.setAttribute(DE.A_NAME, "confirm");
document.setAttribute(DE.A_VALUE, "confirm");
document.setParent(null);
_pendingKeepAliveConfirmation = document;
}
}

View file

@ -0,0 +1,320 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.util;
import java.util.ArrayList;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
import org.eclipse.dstore.core.model.DataStoreResources;
/**
* This class is used to generate command object instances from command descriptors and arguments to commands.
* Command instances are instances of command descriptors. Each command instance contains a set of data arguments
* and a status object, that represents the current state of a command. After a command instance is created,
* it is referenced in the command log for the DataStore.
*/
public class CommandGenerator
{
private DataStore _dataStore = null;
private DataElement _log = null;
static private int _id = 0;
/**
* Constructor
*/
public CommandGenerator()
{
}
/**
* Sets the associated DataStore
* @param dataStore the associated DataStore
*/
public void setDataStore(DataStore dataStore)
{
_dataStore = dataStore;
_log = _dataStore.getLogRoot();
}
/**
* This method logs the current command object in the DataStore command log. For each
* logged command, a status object is created and returned.
* @param commandObject the commandObject to log
* @return the status object of the command
*/
public DataElement logCommand(DataElement commandObject)
{
try
{
// prevent duplicate queries
String name = commandObject.getAttribute(DE.A_NAME);
// create time and status objects
DataElement status = null;
if (status == null)
{
StringBuffer id = new StringBuffer(commandObject.getId());
id.append(DataStoreResources.model_status);
status =
_dataStore.createObject(
commandObject,
DataStoreResources.model_status,
DataStoreResources.model_start,
"",
id.toString());
}
_log.addNestedData(commandObject, false);
}
catch (Exception e)
{
_dataStore.trace(e);
}
return commandObject;
}
/**
* Creates a new command instance object from a command descriptor
* @param commandDescriptor the descriptor of the command to create
* @return the new command instance
*/
public DataElement createCommand(DataElement commandDescriptor)
{
if (commandDescriptor != null)
{
if (commandDescriptor.getType().equals(DE.T_COMMAND_DESCRIPTOR))
{
DataElement commandInstance = _dataStore.createObject(null, commandDescriptor.getName(), commandDescriptor.getValue(), commandDescriptor.getSource());
commandInstance.setDescriptor(commandDescriptor);
return commandInstance;
}
else
{
System.out.println("not cd -> " + commandDescriptor);
return null;
}
}
else
{
return null;
}
}
private void clearDeleted(DataElement element)
{
for (int i = 0; i < element.getNestedSize(); i++)
{
DataElement child = element.get(i).dereference();
if (child.isDeleted())
{
element.removeNestedData(child);
}
}
}
/**
* Creates a new command from a command descriptor and it's arguments.
*
* @param commandDescriptor the command type of the new command
* @param arguments the arguments for the command, besides the subject
* @param dataObject the subject of the command
* @param refArg indicates whether the subject should be represented as a reference or directly
* @return the status object of the command
*/
public DataElement generateCommand(DataElement commandDescriptor, ArrayList arguments, DataElement dataObject, boolean refArg)
{
DataElement commandObject = createCommand(commandDescriptor);
if (commandObject != null)
{
clearDeleted(dataObject);
DataElement tempRoot = _dataStore.getTempRoot();
commandObject.setAttribute(DE.A_VALUE, commandDescriptor.getName());
if (dataObject.isUpdated())
{
_dataStore.createReference(commandObject, dataObject,DataStoreResources.model_contents);
}
else
{
dataObject.setPendingTransfer(true);
commandObject.addNestedData(dataObject, false);
}
if (arguments != null)
{
for (int i = 0; i < arguments.size(); i++)
{
DataElement arg = (DataElement) arguments.get(i);
if (arg != null)
{
if (!arg.isUpdated())
{
commandObject.addNestedData(arg, false);
}
else
{
_dataStore.createReference(commandObject, arg, "argument");
}
}
}
}
return logCommand(commandObject);
}
else
{
return null;
}
}
/**
* Creates a new command from a command descriptor and it's arguments.
*
* @param commandDescriptor the command type of the new command
* @param arg the arguement for the command, besides the subject
* @param dataObject the subject of the command
* @param refArg indicates whether the subject should be represented as a reference or directly
* @return the status object of the command
*/
public DataElement generateCommand(DataElement commandDescriptor, DataElement arg, DataElement dataObject, boolean refArg)
{
_id++;
DataElement commandObject = createCommand(commandDescriptor);
if (commandObject != null)
{
DataElement tempRoot = _dataStore.getTempRoot();
commandObject.setAttribute(DE.A_VALUE, commandDescriptor.getName());
clearDeleted(dataObject);
if (refArg || dataObject.isUpdated())
{
_dataStore.createReference(commandObject, dataObject,DataStoreResources.model_contents);
}
else
{
dataObject.setPendingTransfer(true);
commandObject.addNestedData(dataObject, false);
}
if (!arg.isUpdated())
{
commandObject.addNestedData(arg, false);
}
else
{
_dataStore.createReference(commandObject, arg, "argument");
}
return logCommand(commandObject);
}
else
{
return null;
}
}
/**
* Creates a new command from a command descriptor and it's arguments.
*
* @param commandDescriptor the command type of the new command
* @param dataObject the subject of the command
* @param refArg indicates whether the subject should be represented as a reference or directly
* @return the status object of the command
*/
public DataElement generateCommand(DataElement commandDescriptor, DataElement dataObject, boolean refArg)
{
_id++;
DataElement commandObject = createCommand(commandDescriptor);
if (commandObject != null)
{
commandObject.setAttribute(DE.A_VALUE, commandDescriptor.getName());
clearDeleted(dataObject);
if (refArg || dataObject.isUpdated())
{
_dataStore.createReference(commandObject, dataObject,DataStoreResources.model_arguments);
}
else
{
dataObject.setPendingTransfer(true);
commandObject.addNestedData(dataObject, false);
}
return logCommand(commandObject);
}
else
{
return null;
}
}
/**
* Creates a response tree for transmitting a set of data from a server to a client.
*
* @param document the root of the response
* @param objects the data contained in the response
* @return the response tree root
*/
public DataElement generateResponse(DataElement document, ArrayList objects)
{
document.addNestedData(objects, false);
return document;
}
/**
* Creates a response tree for transmitting a set of data from a server to a client.
*
* @param responseType the type of data to respond with
* @param dataObject the child object in the response tree
* @return the response tree root
*/
public DataElement generateResponse(String responseType, DataElement dataObject)
{
if (dataObject != null)
{
DataElement commandObject = _dataStore.createObject(null, "RESPONSE", responseType);
commandObject.addNestedData(dataObject, true);
return commandObject;
}
else
{
return null;
}
}
/**
* Creates a simple response object of the specified type
*
* @param responseType the type of data to respond with
* @return the response object
*/
public DataElement generateResponse(String responseType)
{
DataElement commandObject = _dataStore.createObject(null, "RESPONSE", responseType);
return commandObject;
}
}

View file

@ -0,0 +1,106 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.util;
import java.util.ArrayList;
import org.eclipse.dstore.core.java.RemoteClassLoader;
/**
* ExternalLoader is a <code>ClassLoader</code> wrapper used for loading external
* tools that are not in the same classpath as the DataStore. Each ExternalLoader
* contains a <i>load scope</i>, a list of classpaths that it's class loader is able
* to load.
*/
public class ExternalLoader
{
private ClassLoader _classLoader;
private ArrayList _loadScope;
/**
* Constructor
*
* @param classLoader the classloader
* @param loadScope the scope in which the classloader can load classes
*/
public ExternalLoader(ClassLoader classLoader, String loadScope)
{
_classLoader = classLoader;
_loadScope = new ArrayList();
_loadScope.add(loadScope);
}
/**
* Constructor
*
* @param classLoader the classloader
* @param loadScope the scope in which the classloader can load classes
*/
public ExternalLoader(ClassLoader classLoader, ArrayList loadScope)
{
_classLoader = classLoader;
_loadScope = loadScope;
}
/**
* Indicates whether this external loader can load a particular class
* @param source a qualified classname
* @return true if it can load the clas
*/
public boolean canLoad(String source)
{
if (_classLoader instanceof RemoteClassLoader)
{
return true;
}
boolean result = false;
if (_loadScope != null)
{
for (int i = 0; i < _loadScope.size(); i++)
{
String scope = (String) _loadScope.get(i);
result = StringCompare.compare(scope, source, true);
if (result)
{
return result;
}
}
}
return result;
}
/**
* Loads the specified class
* @param source a qualified classname
* @return the loaded class
* @throws ClassNotFoundException
*/
public Class loadClass(String source) throws ClassNotFoundException
{
try
{
return _classLoader.loadClass(source);
}
catch (NoClassDefFoundError e)
{
throw new ClassNotFoundException(source);
}
}
}

View file

@ -0,0 +1,27 @@
/********************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and International Business Machines Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.util;
import org.eclipse.dstore.core.model.DataElement;
public interface ISender
{
public void sendDocument(String document);
public void sendDocument(DataElement objectRoot, int depth);
}

View file

@ -0,0 +1,165 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.util;
import java.util.ArrayList;
/**
* This class is used to define a wildcard string pattern. Strings
* can be compared against a pattern to determine whether they match
* or not.
*/
public class Pattern
{
private String _pattern;
private ArrayList _subMatches;
private ArrayList _matchSchema;
/**
* Constructor
* @param pattern a wildcard string
* @param matchSchema
*/
public Pattern(String pattern, ArrayList matchSchema)
{
_pattern = pattern;
_matchSchema = matchSchema;
}
/**
* Returns a list of submatches
* @return a list of submatches
*/
public ArrayList getSubMatches()
{
return _subMatches;
}
/**
* Returns a submatch
* @param attribute an attribute to match
* @return a submatch
*/
public String getSubMatch(String attribute)
{
// find attribute index in match schema
int index = _matchSchema.indexOf(attribute);
if ((index >= 0) && (index < _subMatches.size()))
{
Object match = _subMatches.get(index);
return new String((String) match);
}
else
{
return new String("null");
}
}
/**
* Checks whther a compare string matches the pattern
* @param compareStr to string to compare
* @return true if there is a match
*/
public boolean matches(String compareStr)
{
String currentMatch = new String("");
_subMatches = new ArrayList();
int iText = 0;
int iPattern = 0;
int lastStar = 0;
int len = compareStr.length();
int patternLen = _pattern.length();
while (iPattern < patternLen)
{
char p = _pattern.charAt(iPattern++);
if (p == '*')
{
if (currentMatch.length() > 0)
{
_subMatches.add(new String(currentMatch));
}
currentMatch = new String("");
if (iPattern >= patternLen)
{
while (iText < len)
{
currentMatch += compareStr.charAt(iText++);
}
_subMatches.add(new String(currentMatch));
return true;
}
else
{
lastStar = iPattern;
}
}
else
{
if (iText >= len)
{
return false;
}
else
{
char t = compareStr.charAt(iText++);
if (p == t)
{
if ((lastStar > 0) && (iPattern >= patternLen) && (iText < len))
{
}
else
{
continue;
}
}
else
{
currentMatch += t;
if (lastStar == 0)
{
return false;
}
}
int matched = iPattern - lastStar - 1;
iPattern = lastStar;
iText -= matched;
}
}
}
if (iText >= len)
{
_subMatches.add(new String(currentMatch));
return true;
}
else
{
return false;
}
}
}

View file

@ -0,0 +1,165 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.util;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
/**
* This class is used for receiving data from a socket in the DataStore
* communication layer.
*/
public abstract class Receiver extends Thread
{
private Socket _socket;
protected DataStore _dataStore;
private XMLparser _xmlParser;
private BufferedInputStream _in;
protected boolean _canExit;
/**
* Constructor
* @param socket the socket to read from
* @param dataStore the associated DataStore
*/
public Receiver(Socket socket, DataStore dataStore)
{
_socket = socket;
_dataStore = dataStore;
_canExit = false;
_xmlParser = new XMLparser(dataStore);
try
{
_in = new BufferedInputStream(socket.getInputStream());
}
catch (UnknownHostException uhe)
{
//System.out.println("Receiver:" + uhe);
}
catch (IOException ioe)
{
//System.out.println("Receiver:" + ioe);
}
}
/**
* Called when a DataStore connection is terminated.
*/
public void finish()
{
_canExit = true;
}
/**
* Indicates that the receiver can stop receiving data from the socket.
* @return true if the receiver can stop
*/
public boolean canExit()
{
return _canExit;
}
/**
* Called when the receiver thread is running
*/
public void run()
{
try
{
while (!_canExit)
{
handleInput();
}
}
catch (Exception e)
{
_canExit = true;
e.printStackTrace();
handleError(e);
}
}
/**
* Periodically called to receive data from the socket
*/
public void handleInput()
{
try
{
// wait on the socket
DataElement rootObject = _xmlParser.parseDocument(_in, _socket);
if (rootObject != null)
{
String type = rootObject.getType();
if (!type.equals("FILE"))
{
handleDocument(rootObject);
}
}
else
{
// something really bad happened
_canExit = true;
if (_xmlParser.getPanicException() != null)
handleError(_xmlParser.getPanicException());
}
}
catch (IOException ioe)
{
_canExit = true;
handleError(ioe);
}
catch (Exception e)
{
handleError(e);
}
}
/**
* Returns the associated socket
* @return the socket
*/
public Socket socket()
{
return _socket;
}
/**
* Implemented to provide a means of handling received input
* @param documentObject the root object of the received data
*/
public abstract void handleDocument(DataElement documentObject);
/**
* Implemented to provide a means of handling errors in the communication layer
* @param e an exception that occurred
*/
public abstract void handleError(Throwable e);
}

View file

@ -0,0 +1,341 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.util;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.util.ArrayList;
import org.eclipse.dstore.core.java.IRemoteClassInstance;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
/**
* This class is used for sending data to a socket in the DataStore
* communication layer.
*/
public class Sender implements ISender
{
private Socket _socket;
private PrintStream _outFile;
private BufferedWriter _outData;
private XMLgenerator _xmlGenerator;
private DataStore _dataStore;
/**
* Constructor
* @param socket the associated socket
* @param dataStore the associated DataStore
*/
public Sender(Socket socket, DataStore dataStore)
{
_socket = socket;
_dataStore = dataStore;
_xmlGenerator = new XMLgenerator(_dataStore);
try
{
int bufferSize = _socket.getSendBufferSize();
_socket.setSendBufferSize(bufferSize);
_xmlGenerator.setBufferSize(bufferSize);
}
catch (SocketException e)
{
}
try
{
_outFile = new PrintStream(_socket.getOutputStream());
_outData = new BufferedWriter(new OutputStreamWriter(_socket.getOutputStream(), DE.ENCODING_UTF_8));
_xmlGenerator.setFileWriter(_outFile);
_xmlGenerator.setDataWriter(_outData);
_xmlGenerator.setGenerateBuffer(false);
InetSocketAddress address = (InetSocketAddress)socket.getRemoteSocketAddress();
if (address != null)
{
if (address.getAddress() != null)
{
String remoteIP = address.getAddress().getHostAddress();
_dataStore.setRemoteIP(remoteIP);
}
else
{
String remoteIP = address.getHostName();
_dataStore.setRemoteIP(remoteIP);
}
}
else
{
String remoteIP = socket.getInetAddress().getHostAddress();
_dataStore.setRemoteIP(remoteIP);
}
}
catch (java.io.IOException e)
{
e.printStackTrace();
}
}
/**
* Returns the associated socket
* @return the socket
*/
public Socket socket()
{
return _socket;
}
/**
* Sends a string through the socket
* @param document the string to send
*/
public void sendDocument(String document)
{
synchronized (_outData)
{
try
{
_outData.write(document, 0, document.length());
_outData.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* Sends the bytes of a file through the socket
* @param objectRoot the object representing the file to send
* @param bytes the bytes to send over the socket
* @param size the number of bytes to send over the socket
* @param binary indicates whether to send the bytes and binary or text
*/
public void sendFile(DataElement objectRoot, byte[] bytes, int size, boolean binary)
{
synchronized (_outData)
{
synchronized (_outFile)
{
_xmlGenerator.empty();
_xmlGenerator.generate(objectRoot, bytes, size, false, binary);
_xmlGenerator.flushData();
}
}
}
/**
* Sends a class through the socket
* @param classElement the object representing the class to send
*/
public void sendClass(DataElement classElement)
{
String className = classElement.getName();
ArrayList loaders = _dataStore.getLocalClassLoaders();
if (loaders == null)
{
// could not get the registered classLoaders. Fail.
generateEmptyClass(classElement);
return;
}
InputStream classInStream = null;
className = className.replace('.', '/');
className = className + ".class";
URL classLocation = null;
for (int i = 0; i < loaders.size(); i++)
{
ClassLoader loader = (ClassLoader) loaders.get(i);
classInStream = loader.getResourceAsStream(className);
classLocation = loader.getResource(className);
if (classInStream != null && classLocation != null) break;
}
if (classLocation == null || classInStream == null)
{
// could not load the class with any of the class loaders. Fail.
generateEmptyClass(classElement);
return;
}
// got a stream to read the classfile. Now read the class into a buffer.
BufferedInputStream bufInputStream = new BufferedInputStream(classInStream);
if (bufInputStream == null)
{
generateEmptyClass(classElement);
return; // throw new IOException("BufferedInputStream could not be instantiated on " + className);
}
try
{
int classSize = bufInputStream.available();
byte[] bytes = new byte[classSize];
int result = 0;
result = bufInputStream.read(bytes);
if (result != classSize)
{
generateEmptyClass(classElement);
return; // throw new IOException("Could not read class from BufferedInputStream: " + className);
}
synchronized (_outData)
{
synchronized (_outFile)
{
_xmlGenerator.empty();
_xmlGenerator.generate(classElement, bytes, classSize);
_xmlGenerator.flushData();
}
}
}
catch (IOException e)
{
generateEmptyClass(classElement);
return;
}
}
/**
* Generates an empty class and sends it across the pipe, as a signal that the
* class could not be found or loaded or read on the client.
* @param classElement
*/
private void generateEmptyClass(DataElement classElement)
{
_xmlGenerator.empty();
_xmlGenerator.generate(classElement, new byte[0], 0);
_xmlGenerator.flushData();
}
/**
* Sends the bytes of a file through the socket to be appended to a file on the other end
*
* @param objectRoot the object representing the file to send
* @param bytes the bytes to send over the socket
* @param size the number of bytes to send over the socket
* @param binary indicates whether to send the bytes and binary or text
*/
public void sendAppendFile(DataElement objectRoot, byte[] bytes, int size, boolean binary)
{
synchronized (_outData)
{
synchronized (_outFile)
{
_xmlGenerator.empty();
_xmlGenerator.generate(objectRoot, bytes, size, true, binary);
_xmlGenerator.flushData();
}
}
}
/**
* Sends a DataStore tree of data through the socket
*
* @param objectRoot the root of the tree to send
* @param depth the depth of the tree to send
*/
public void sendDocument(DataElement objectRoot, int depth)
{
synchronized (_outData)
{
synchronized (_outFile)
{
_xmlGenerator.empty();
_xmlGenerator.generate(objectRoot, depth);
_xmlGenerator.flushData();
}
}
// if (objectRoot.getParent() != null)
// objectRoot.getDataStore().deleteObject(objectRoot.getParent(), objectRoot);
}
/**
* Requests a class from the client
*/
public void requestClass(DataElement classRequest)
{
synchronized (_outData)
{
synchronized (_outFile)
{
_xmlGenerator.empty();
_xmlGenerator.generateClassRequest(classRequest);
_xmlGenerator.flushData();
}
}
}
public void sendRemoteClassRunnable(DataElement objectRoot, IRemoteClassInstance runnable)
{
synchronized (_outData)
{
synchronized (_outFile)
{
_xmlGenerator.empty();
_xmlGenerator.generateSerializedObject(objectRoot, runnable);
_xmlGenerator.flushData();
}
}
}
public void sendKeepAliveRequest(DataElement document)
{
synchronized (_outData)
{
synchronized (_outFile)
{
_xmlGenerator.empty();
_xmlGenerator.generate(document, 2);
_xmlGenerator.flushData();
}
}
}
public void sendKeepAliveConfirmation(DataElement document)
{
synchronized (_outData)
{
synchronized (_outFile)
{
_xmlGenerator.empty();
_xmlGenerator.generate(document, 2);
_xmlGenerator.flushData();
}
}
}
}

View file

@ -0,0 +1,71 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.util;
import java.util.ArrayList;
import org.eclipse.dstore.core.model.DataElement;
/**
* Utility class used for sorting a list of DataElements based on
* their depth attributes.
*/
public class Sorter
{
/**
* Sort a list of DataElements based on their depth attributes
* @param list a list of DataElements
* @return a sorted list of DataElements
*/
public static ArrayList sort(ArrayList list)
{
ArrayList sortedList = new ArrayList(list.size());
while (list.size() > 0)
{
DataElement first = findFirst(list);
sortedList.add(first);
}
return sortedList;
}
/**
* Find the DataElement with the highest depth in the list
* @param list a list of DataElements
* @return the DataElement with the highest depth
*/
private static DataElement findFirst(ArrayList list)
{
DataElement result = null;
for (int i = 0; i < list.size(); i++)
{
DataElement item = (DataElement) list.get(i);
if (item != null)
{
int depth = item.depth();
if ((result == null) || (depth > result.depth()))
{
result = item;
}
}
}
list.remove(result);
return result;
}
}

View file

@ -0,0 +1,125 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.util;
/**
* Utility class for comparing a wildcard string to another string
*/
public class StringCompare
{
/**
* Constructor
*/
public StringCompare()
{
}
/**
* Compare two strings
*
* @param pattern the pattern to match
* @param compareStr the string to compare against the pattern
* @param noCase indicates whether the strings should be compared based on case
* @return true if the compare string matches the pattern
*/
public static boolean compare(String pattern, String compareStr, boolean noCase)
{
if ((pattern == null) || (compareStr == null))
return false;
if (noCase)
{
pattern = pattern.toUpperCase();
compareStr = compareStr.toUpperCase();
}
String currentMatch = new String("");
int iText = 0;
int iPattern = 0;
int lastStar = 0;
int len = compareStr.length();
int patternLen = pattern.length();
while (iPattern < patternLen)
{
char p = pattern.charAt(iPattern++);
if (p == '*')
{
if (iPattern >= patternLen)
{
while (iText < len)
{
iText++;
}
return true;
}
else
{
lastStar = iPattern;
}
}
else
{
if (iText >= len)
{
return false;
}
else
{
char t = compareStr.charAt(iText++);
if (p == t)
{
if ((lastStar > 0) && (iPattern >= patternLen) && (iText < len))
{
}
else
{
continue;
}
}
else
{
if (lastStar == 0)
{
return false;
}
}
int matched = iPattern - lastStar - 1;
iPattern = lastStar;
iText -= matched;
}
}
}
if (iText >= len)
{
return true;
}
else
{
return false;
}
}
}

View file

@ -0,0 +1,691 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.util.Stack;
import org.eclipse.dstore.core.java.IRemoteClassInstance;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
import org.eclipse.dstore.core.model.DataStoreResources;
/**
* <p>
* This class is used to serialize data and send it either
* to a file or a socket.
* </p>
* <p>
* When a DataStore tree needs to be transmitted, it's DataElements are
* converted to XML before sending. Only those elements which have changed and
* are thus out of synch with the DataStore on the other end of the socket are
* actually transferred.
* </p>
* <p>
* When a byte stream or file needs to be transmitted, bytes are
* either send as is if binary transfer is requested or as unicode if
* binary transfer is not requested.
* </p>
*/
public class XMLgenerator
{
private int _state;
private StringBuffer _document;
private int _indent;
private Stack _tagStack;
private PrintStream _fileWriter;
private BufferedWriter _dataWriter;
private int _bufferSize;
private boolean _generateBuffer;
private boolean _ignoreDeleted;
private DataStore _dataStore;
public static final int EMPTY = 0;
public static final int OPEN = 1;
public static final int CLOSE = 2;
public static final int BODY = 3;
/**
* Constructor
* @param dataStore the associated DataStore
*/
public XMLgenerator(DataStore dataStore)
{
_dataStore = dataStore;
_state = EMPTY;
_bufferSize = 100000;
_document = new StringBuffer(_bufferSize);
_indent = 0;
_generateBuffer = true;
_ignoreDeleted = false;
_tagStack = new Stack();
}
/**
* Indicate whether DataElements marked as deleted should be sent.
* @param flag whether deleted elements should be sent
*/
public void setIgnoreDeleted(boolean flag)
{
_ignoreDeleted = flag;
}
/**
* Sets the file writer used for file transfer
* @param writer the file writer used for file transfer
*/
public void setFileWriter(PrintStream writer)
{
_fileWriter = writer;
}
/**
* Sets the data writer used for XML transfer
* @param writer the data writer used for XML transfer
*/
public void setDataWriter(BufferedWriter writer)
{
_dataWriter = writer;
}
/**
* Set the buffer size
* @param size of the buffer used for transmitting packets
*/
public void setBufferSize(int size)
{
_bufferSize = size;
}
/**
* Indicate whether the buffer attribute of each DataElement should be
* transferred
* @param flag whether the buffer should be transferred
*/
public void setGenerateBuffer(boolean flag)
{
_generateBuffer = flag;
}
private void append(char c)
{
_document.append(c);
}
private void append(String buffer)
{
_document.append(buffer);
}
private void append(StringBuffer buffer)
{
_document.append(buffer);
}
private void nextLine()
{
if (_dataWriter != null)
{
_document.append('\n');
int length = _document.length();
if (length > _bufferSize)
{
flushData();
}
}
}
/**
* Send all buffered data through the pipe.
*/
public void flushData()
{
if (_document.length() > 0 && _dataWriter != null)
{
try
{
_dataWriter.write(_document.toString(), 0, _document.length());
_dataWriter.write('\n');
_dataWriter.flush();
_document.setLength(0);
}
catch (Exception e)
{
_dataStore.trace(e);
_dataWriter = null;
}
}
}
private void indent()
{
for (int i = 0; i < _indent; i++)
{
append(' ');
}
}
private void startTag(String name)
{
if (_state == OPEN)
{
append('>');
_indent++;
}
if (_state == CLOSE)
{
_indent--;
}
if (_state == BODY)
{
nextLine();
}
indent();
if (_document == null)
{
append('<');
append(name);
}
else
{
append('<');
append(name);
}
_tagStack.push(name);
_state = OPEN;
}
private void endTag(String name)
{
String top = (String) _tagStack.pop();
if (_state == CLOSE)
{
}
else if (_state == OPEN)
{
if (top == name)
{
append("/>");
if (_tagStack.empty())
{
_state = CLOSE;
}
else
{
_state = BODY;
}
}
}
else if (_state == BODY)
{
if (top == name)
{
nextLine();
_indent--;
indent();
append("</");
append(name);
append('>');
if (_tagStack.empty())
{
_state = CLOSE;
}
}
}
}
private void addAttribute(String name, String value)
{
if (_state != OPEN)
{
}
StringBuffer niceValue = null;
if (value != null)
{
niceValue = prepareStringForXML(value);
append(' ');
append(name);
append("=\"");
append(niceValue);
append('"');
}
else
{
append(' ');
append(name);
append("=\"\"");
}
}
private void addFile(byte[] bytes, int size, boolean binary)
{
if (_state == OPEN)
{
append('>');
_indent++;
_state = BODY;
}
if (_state == BODY)
{
flushData();
// send everything across
if (binary)
{
_fileWriter.write(bytes, 0, size);
_fileWriter.flush();
}
else
{
try
{
_dataWriter.write(new String(bytes), 0, size);
_dataWriter.flush();
}
catch (IOException e)
{
_dataStore.trace(e);
}
}
}
else if (_state == EMPTY)
{
}
else if (_state == CLOSE)
{
}
}
private void addData(StringBuffer data)
{
if (_state == OPEN)
{
append('>');
_indent++;
_state = BODY;
}
if (_state == BODY)
{
if (_generateBuffer && data != null && (data.length() > 0))
{
StringBuffer text = prepareStringForXML(data);
if (text != null && text.length() > 0)
{
nextLine();
indent();
append("<Buffer>");
nextLine();
indent();
append(text.toString());
nextLine();
indent();
append("</Buffer>");
}
}
else
{
append("");
}
}
else if (_state == EMPTY)
{
}
else if (_state == CLOSE)
{
}
}
/**
* Returns the current serialized document
* @return the current document
*/
public StringBuffer document()
{
return _document;
}
/**
* Clears the current serlized document
*/
public void empty()
{
_indent = 0;
_document.delete(0, _document.length());
}
/**
* Converts special characters to appropriate representation in XML
* @param input buffer to convert
* @return the converted buffer
*/
public static StringBuffer prepareStringForXML(StringBuffer input)
{
StringBuffer output = new StringBuffer();
for (int idx = 0; idx < input.length(); idx++)
{
char currChar = input.charAt(idx);
switch (currChar)
{
case '&' :
output.append(XMLparser.STR_AMP);
break;
case '"' :
output.append(XMLparser.STR_QUOTE);
break;
case '\'' :
output.append(XMLparser.STR_APOS);
break;
case '<' :
output.append(XMLparser.STR_LT);
break;
case '>' :
output.append(XMLparser.STR_GT);
break;
case ';' :
output.append(XMLparser.STR_SEMI);
break;
default :
output.append(currChar);
break;
}
}
return output;
}
/**
* Converts special characters to appropriate representation in XML
* @param input buffer to convert
* @return the converted buffer
*/
public static StringBuffer prepareStringForXML(String input)
{
StringBuffer output = new StringBuffer();
for (int idx = 0; idx < input.length(); idx++)
{
char currChar = input.charAt(idx);
switch (currChar)
{
case '&' :
output.append(XMLparser.STR_AMP);
break;
case '"' :
output.append(XMLparser.STR_QUOTE);
break;
case '\'' :
output.append(XMLparser.STR_APOS);
break;
case '<' :
output.append(XMLparser.STR_LT);
break;
case '>' :
output.append(XMLparser.STR_GT);
break;
case ';' :
output.append(XMLparser.STR_SEMI);
break;
default :
output.append(currChar);
break;
}
}
return output;
}
/**
* Generate an tags for a file transfer and send bytes over the pipe.
*
* @param object the element representing the file transfer
* @param bytes the bytes to send
* @param size the number of bytes to send
* @param isAppend indicates whether bytes should be appended or not to a file on the other end of the pipe
* @param binary indicates whether the bytes should be sent as binary or text
*/
public synchronized void generate(DataElement object, byte[] bytes, int size, boolean isAppend, boolean binary)
{
String tagType = XMLparser.STR_FILE;
if (isAppend)
{
tagType += ".Append";
}
if (binary)
{
tagType += ".Binary";
}
if (object != null)
{
startTag(tagType);
addAttribute(DE.P_TYPE, object.getAttribute(DE.A_TYPE));
addAttribute(DE.P_ID, object.getAttribute(DE.A_ID));
addAttribute(DE.P_NAME, object.getAttribute(DE.A_NAME));
addAttribute(DE.P_VALUE, object.getAttribute(DE.A_VALUE));
addAttribute(DE.P_SOURCE, object.getAttribute(DE.A_SOURCE));
addAttribute(DE.P_SOURCE_LOCATION, object.getAttribute(DE.A_SOURCE_LOCATION));
if (object.isReference())
{
addAttribute(DE.P_ISREF, DataStoreResources.TRUE);
}
else
{
addAttribute(DE.P_ISREF, DataStoreResources.FALSE);
}
addAttribute(DE.P_DEPTH, "" + size);
addFile(bytes, size, binary);
endTag(tagType);
}
}
/**
* Generate tags for class transfer and send bytes over the pipe.
*
* @param object the element representing the class transfer
* @param bytes the bytes to send
* @param size the number of bytes to send
*/
public synchronized void generate(DataElement object, byte[] bytes, int size)
{
String tagType = XMLparser.STR_CLASS;
if (object != null)
{
startTag(tagType);
addAttribute(DE.P_TYPE, object.getAttribute(DE.A_TYPE));
addAttribute(DE.P_ID, object.getAttribute(DE.A_ID));
addAttribute(DE.P_NAME, object.getAttribute(DE.A_NAME));
addAttribute(DE.P_VALUE, object.getAttribute(DE.A_VALUE));
addAttribute(DE.P_SOURCE, object.getAttribute(DE.A_SOURCE));
addAttribute(DE.P_SOURCE_LOCATION, object.getAttribute(DE.A_SOURCE_LOCATION));
if (object.isReference())
{
addAttribute(DE.P_ISREF, "true");
}
else
{
addAttribute(DE.P_ISREF, "false");
}
addAttribute(DE.P_DEPTH, "" + size);
addFile(bytes, size, true);
endTag(tagType);
}
}
/**
* Serializes and sends a DataStore tree through the pipe
*
* @param object the root of the DataStore tree to send
* @param depth the depth of the tree to send
*/
public void generate(DataElement object, int depth)
{
if ((object != null) && (depth >= 0))
{
String tagType = XMLparser.STR_DATAELEMENT;
if (object.isUpdated() && !object.isPendingTransfer() && !_generateBuffer)
{
}
else
{
if (object.isDeleted() && _ignoreDeleted)
{
}
else
{
object.setPendingTransfer(false);
startTag(tagType);
addAttribute(DE.P_TYPE, object.getAttribute(DE.A_TYPE));
addAttribute(DE.P_ID, object.getAttribute(DE.A_ID));
addAttribute(DE.P_NAME, object.getAttribute(DE.A_NAME));
addAttribute(DE.P_VALUE, object.getAttribute(DE.A_VALUE));
addAttribute(DE.P_SOURCE, object.getAttribute(DE.A_SOURCE));
addAttribute(DE.P_SOURCE_LOCATION, object.getAttribute(DE.A_SOURCE_LOCATION));
if (object.isReference())
{
addAttribute(DE.P_ISREF, "true");
}
else
{
addAttribute(DE.P_ISREF, "false");
}
addAttribute(DE.P_DEPTH, "" + object.depth());
addData(object.getBuffer());
object.setUpdated(true);
if (!object.isReference() && depth >= 0)
{
for (int i = 0; i < object.getNestedSize(); i++)
{
generate(object.get(i), depth - 1);
}
}
// end generation
endTag(tagType);
}
}
}
}
public void generateClassRequest(DataElement object)
{
String tagType = XMLparser.STR_REQUEST_CLASS;
if (object != null)
{
startTag(tagType);
addAttribute(DE.P_TYPE, object.getAttribute(DE.A_TYPE));
addAttribute(DE.P_ID, object.getAttribute(DE.A_ID));
addAttribute(DE.P_NAME, object.getAttribute(DE.A_NAME));
addAttribute(DE.P_VALUE, object.getAttribute(DE.A_VALUE));
addAttribute(DE.P_SOURCE, object.getAttribute(DE.A_SOURCE));
addAttribute(DE.P_SOURCE_LOCATION, object.getAttribute(DE.A_SOURCE_LOCATION));
if (object.isReference())
{
addAttribute(DE.P_ISREF, "true");
}
else
{
addAttribute(DE.P_ISREF, "false");
}
_state = BODY;
endTag(tagType);
}
}
public void generateSerializedObject(DataElement object, IRemoteClassInstance runnable)
{
String tagType = XMLparser.STR_SERIALIZED;
if (object != null)
{
startTag(tagType);
addAttribute(DE.P_TYPE, object.getAttribute(DE.A_TYPE));
addAttribute(DE.P_ID, object.getAttribute(DE.A_ID));
addAttribute(DE.P_NAME, object.getAttribute(DE.A_NAME));
addAttribute(DE.P_VALUE, object.getAttribute(DE.A_VALUE));
addAttribute(DE.P_SOURCE, object.getAttribute(DE.A_SOURCE));
addAttribute(DE.P_SOURCE_LOCATION, object.getAttribute(DE.A_SOURCE_LOCATION));
if (object.isReference())
{
addAttribute(DE.P_ISREF, "true");
}
else
{
addAttribute(DE.P_ISREF, "false");
}
try
{
PipedInputStream pin = new PipedInputStream();
PipedOutputStream pout = new PipedOutputStream(pin);
ObjectOutputStream outStream = new ObjectOutputStream(pout);
outStream.writeObject(runnable);
int size = pin.available();
byte[] bytes = new byte[size];
int nRead = pin.read(bytes, 0, size);
addAttribute(DE.P_DEPTH, "" + nRead);
addFile(bytes, nRead, true);
outStream.close();
pin.close();
}
catch (Exception e)
{
e.printStackTrace();
}
endTag(tagType);
}
}
}

View file

@ -0,0 +1,984 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.util;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.Socket;
import java.net.SocketException;
import java.util.Stack;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStore;
import org.eclipse.dstore.core.model.DataStoreResources;
/**
* <p>
* This class is used to deserialize data received from a file or a socket.
* </p>
* <p>
* When tags indicate that data is being received, the byte stream is deserialized
* as a DataStore tree. When deserialized data maps to existing DataElements in
* the DataStore, those elements are updated directly. Any deserialized data
* that maps to within an existing DataElement, that does not already exist, gets
* created under the existing DataElement. When parsing DataElement XML, there is
* no intermediate DOM - rather the DOM is the DataStore itself.
* </p>
* <p>
* When tags indicate that a byte stream or file is being received, bytes are
* sent the the current DataStore <code>ByteStreamHandler</code> to be saved on disk.
* </p>
*/
public class XMLparser
{
public static final int IO_SOCKET_READ_TIMEOUT = 3600000;
public static final long KEEPALIVE_RESPONSE_TIMEOUT = 60000;
private DataStore _dataStore;
private DataElement _rootDataElement;
private Stack _tagStack;
private Stack _objStack;
private boolean _isFile;
private boolean _isClass;
private boolean _isRequestClass;
private boolean _isKeepAlive;
private boolean _isKeepAliveConfirm;
private boolean _isSerialized;
private String _tagType;
private byte[] _byteBuffer;
private byte[] _fileByteBuffer;
private int _maxBuffer;
private boolean _panic = false;
private Throwable _panicException = null;
private boolean _isKeepAliveCompatible = false;
private boolean _firstTime = true;
private KeepAliveRequestThread _kart = null;
private KeepAliveRequestThread _initialKart = null;
public static String STR_DATAELEMENT = "DataElement";
public static String STR_BUFFER_START = "<Buffer>";
public static String STR_BUFFER_END = "</Buffer>";
public static String STR_BUFFER = "Buffer";
public static String STR_STATUS = "status";
public static String STR_STATUS_DONE = "done";
public static String STR_STATUS_ALMOST_DONE = "almost done";
public static String STR_FILE = "File";
public static String STR_CLASS = "Class";
public static String STR_REQUEST_CLASS= "RequestClass";
public static String STR_SERIALIZED = "Serialized";
public static String STR_AMP = "&amp;";
public static String STR_QUOTE = "&quot;";
public static String STR_APOS = "&apos;";
public static String STR_LT = "&lt;";
public static String STR_GT = "&gt;";
public static String STR_SEMI = "&#59;";
/**
* Constructor
* @param dataStore the associated DataStore
*/
public XMLparser(DataStore dataStore)
{
_dataStore = dataStore;
_tagStack = new Stack();
_objStack = new Stack();
_maxBuffer = 100000;
_byteBuffer = new byte[_maxBuffer];
}
/**
* Read a file from the pipe
* @param reader the pipe reader
* @param size the number of bytes to read
* @param path the path of the file where the received bytes should be inserted
*/
public void readFile(BufferedInputStream reader, int size, String path, String byteStreamHandlerId)
{
Runtime rt = Runtime.getRuntime();
//long totalMem = rt.totalMemory();
long freeMem = rt.freeMemory();
if (size * 100 > freeMem)
{
rt.gc();
}
if (_fileByteBuffer == null || _fileByteBuffer.length < size)
{
try
{
_fileByteBuffer = new byte[size];
}
catch (OutOfMemoryError e)
{
System.exit(-1);
}
}
int written = 0;
// // hack to deal with platform inconsistencies
// // only needed on the server side
// if (!_dataStore.isVirtual())
// {
// try
// {
// synchronized (reader)
// {
// int first = reader.read();
//
// if (first != 10) {
// written = 1;
// buffer[0] = (byte) first;
// }
// else {
// System.out.println("First byte is 10!");
// }
// }
// }
// catch (IOException e)
// {
// _dataStore.trace(e);
// }
// }
while (written < size)
{
try
{
int read = reader.read(_fileByteBuffer, written, size - written);
written += read;
}
catch (SocketException se)
{
// DKM- socket exception means connection is gone
// need bail now!
_dataStore.trace(se);
handlePanic(se);
return;
}
catch (IOException e)
{
_dataStore.trace(e);
handlePanic(e);
}
catch (Error err)
{
System.out.println("error!");
handlePanic(err);
}
}
if (_tagType.startsWith("File.Append"))
{
boolean binary = _tagType.equals("File.Append.Binary");
_dataStore.appendToFile(path, _fileByteBuffer, size, binary, byteStreamHandlerId);
}
else
{
boolean binary = _tagType.equals("File.Binary");
_dataStore.saveFile(path, _fileByteBuffer, size, binary, byteStreamHandlerId);
}
}
public boolean readInstance(BufferedInputStream reader, int size, String classbyteStreamHandlerId)
{
byte[] buffer = new byte[size];
int written = 0;
while (written < size)
{
try
{
int read = reader.read(buffer, written, size - written);
written += read;
}
catch (SocketException se)
{
// DKM- socket exception means connection is gone
// need bail now!
_dataStore.trace(se);
handlePanic(se);
return false;
}
catch (IOException e)
{
_dataStore.trace(e);
handlePanic(e);
return false;
}
}
_dataStore.saveClassInstance(buffer, size, classbyteStreamHandlerId);
return true;
}
/**
* Read a class file from the pipe
* @param reader the pipe reader
* @param size the number of bytes to read
* @param className the name of the class defined by the byte array.
* @param classbyteStreamHandlerId the name of the classByteStreamHandler that will receive the bytes of the file.
* @return whether the operation is successful
*/
public boolean readClass(BufferedInputStream reader, int size, String className, String classbyteStreamHandlerId)
{
byte[] buffer = new byte[size];
int written = 0;
while (written < size)
{
try
{
int read = reader.read(buffer, written, size - written);
written += read;
}
catch (SocketException se)
{
// DKM- socket exception means connection is gone
// need bail now!
_dataStore.trace(se);
handlePanic(se);
return false;
}
catch (IOException e)
{
_dataStore.trace(e);
handlePanic(e);
return false;
}
}
_dataStore.saveClass(className, buffer, size, classbyteStreamHandlerId);
return true;
}
/**
* Reads a line from the pipe
*
* @param reader the pipe reader
* @return the line received
*/
public String readLine(BufferedInputStream reader, Socket socket)
{
boolean done = false;
int offset = 0;
try
{
boolean inquotes = false;
while (!done)
{
if (_firstTime)
{
_initialKart = new KeepAliveRequestThread(KEEPALIVE_RESPONSE_TIMEOUT, _dataStore);
_firstTime = false;
_initialKart.start();
continue;
}
else if (_initialKart != null && !_initialKart.isAlive())
{
if (!_initialKart.failed())
{
_isKeepAliveCompatible = true;
_initialKart = null;
}
else
{
_isKeepAliveCompatible = false;
_initialKart = null;
}
}
int in = -1;
if (_isKeepAliveCompatible)
{
socket.setSoTimeout(IO_SOCKET_READ_TIMEOUT);
try
{
in = reader.read();
}
catch (InterruptedIOException e)
{
if ((_kart != null) && _kart.failed())
{
done = true;
handlePanic(new Exception("KeepAlive request to client wasnt answered in time."));
continue;
}
else
{
_kart = new KeepAliveRequestThread(KEEPALIVE_RESPONSE_TIMEOUT, _dataStore);
_kart.start();
continue;
}
}
}
else
{
in = reader.read();
}
if (in == -1)
{
done = true;
Exception e = new Exception("The connection to the server has been lost.");
handlePanic(e);
}
else
{
if (in <= 0)
{
done = true;
}
else
{
if (_kart != null) _kart.interrupt();
}
byte aByte = (byte) in;
switch (aByte)
{
case '"':
inquotes = !inquotes;
break;
case '\n':
case '\r':
case '\0':
if (!inquotes)
done = true;
break;
default:
break;
}
if (offset >= _maxBuffer)
{
done = true;
}
_byteBuffer[offset] = aByte;
offset++;
}
}
}
catch (IOException e)
{
_dataStore.trace(e);
done = true;
handlePanic(e);
return null;
}
if (offset > 0)
{
String result = null;
try
{
result = new String(_byteBuffer, 0, offset, DE.ENCODING_UTF_8);
}
catch (IOException e)
{
_dataStore.trace(e);
}
return result;
}
else
{
return null;
}
}
/**
* Called if an exception occurs during reading of the pipe
* @param e the Exception
*/
private void handlePanic(Throwable e)
{
_panic = true;
_panicException = e;
}
/**
* Returns the communications exception if one occurred
* @return a exception
*/
public Throwable getPanicException()
{
return _panicException;
}
/**
* This method gets called to receive data from the pipe. It deserializes
* DataStore XML documents, creating the appropriate DataElements in appropriate
* places in the DataStore tree. If files are being transmitted it creates
* the appropriate files using the DataStore <code>ByteStreamHandler</code>.
*
* @param reader the pipe reader
* @return the root DataElement of the parsed document
* @throws IOException
*/
public DataElement parseDocument(BufferedInputStream reader, Socket socket) throws IOException
{
_tagStack.clear();
_objStack.clear();
_rootDataElement = null;
_isFile = false;
_isClass = false;
_isRequestClass = false;
_isKeepAlive = false;
_isKeepAliveConfirm = false;
_isSerialized = false;
_tagType = STR_DATAELEMENT;
DataElement parent = null;
String matchTag = null;
boolean done = false;
while (!done)
{
String xmlTag = readLine(reader, socket);
if (xmlTag != null)
{
String trimmedTag = xmlTag.trim();
if (!_tagStack.empty())
{
matchTag = (String) _tagStack.peek();
}
if (trimmedTag.equals(STR_BUFFER_START))
{
_tagType = STR_BUFFER;
_tagStack.push(STR_BUFFER_END);
}
else if (trimmedTag.equals(STR_BUFFER_END))
{
_tagType = STR_DATAELEMENT;
_tagStack.pop();
}
else if (_tagType.equals(STR_BUFFER))
{
String buffer = convertStringFromXML(xmlTag);
parent.appendToBuffer(buffer);
}
else if ((matchTag != null) && trimmedTag.equals(matchTag))
{
if (parent.getType().equals(STR_STATUS))
{
if (parent.getName().equals(STR_STATUS_ALMOST_DONE))
{
parent.setAttribute(DE.A_NAME, STR_STATUS_DONE);
if (parent.getValue().equals(STR_STATUS_ALMOST_DONE))
{
parent.setAttribute(DE.A_VALUE,STR_STATUS_DONE);
}
if (_dataStore.isWaiting(parent))
{
_dataStore.stopWaiting(parent);
parent.notifyUpdate();
}
}
}
_tagStack.pop();
if (_tagStack.empty())
{
done = true;
}
else if (_tagStack.size() == 1)
{
parent = _rootDataElement;
}
else
{
parent = (DataElement) _objStack.pop();
}
}
else
{
xmlTag = xmlTag.trim();
if (xmlTag.length() > 3)
{
try
{
if (parent != null)
{
if (_objStack.contains(parent))
{
}
else
{
_objStack.push(parent);
}
}
DataElement result = parseTag(xmlTag, parent);
if (_panic)
{
return null;
}
if (result != null)
{
result.setUpdated(true);
if (parent == null && _rootDataElement == null)
{
_rootDataElement = result;
_rootDataElement.setParent(null);
}
parent = result;
if (_isFile && (result != null))
{
int size = result.depth();
String path = result.getSource();
String byteStreamHandler = result.getName();
if (path.equals(byteStreamHandler))
{
// older client or server, fall back to default
byteStreamHandler = DataStoreResources.DEFAULT_BYTESTREAMHANDLER;
}
if (path != null)
{
readFile(reader, size, path, byteStreamHandler);
}
_isFile = false;
//_dataStore.deleteObject(parent, result);
}
else if (_isClass && (result != null))
{
int size = result.depth();
String classbyteStreamHandler = result.getSource();
if (result.getName() != null)
{
boolean success = readClass(reader, size, result.getName(), classbyteStreamHandler);
}
_isClass = false;
}
else if (_isRequestClass && (result != null))
{
result.getDataStore().sendClass(result.getName());
_isRequestClass = false;
}
else if (_isKeepAlive && (result != null))
{
result.getDataStore().sendKeepAliveConfirmation();
_isKeepAlive = false;
}
else if (_isKeepAliveConfirm && (result != null))
{
if (_initialKart != null) _initialKart.interrupt();
_isKeepAliveConfirm = false;
}
else if (_isSerialized && (result != null))
{
int size = result.depth();
String classbyteStreamHandler = result.getSource();
if (result.getName() != null)
{
boolean success = readInstance(reader, size, classbyteStreamHandler);
}
_isSerialized = false;
}
StringBuffer endTag = new StringBuffer("</");
endTag.append(_tagType);
endTag.append('>');
_tagStack.push(endTag.toString());
}
}
catch (Exception e)
{
e.printStackTrace();
_dataStore.trace(e);
return _rootDataElement;
}
}
}
}
if (_panic)
return null;
}
DataElement result = _rootDataElement;
_rootDataElement.setParent(null); // this root is transient
_rootDataElement = null;
return result;
}
/**
* Deserializes a single DataElement from the XML stream.
*
* @param fullTag the DataElement XML tag
* @param parent the DataElement that container for the deserialized DataElement
* @return the parsed DataElement
*/
protected synchronized DataElement parseTag(String fullTag, DataElement parent)
{
if (!fullTag.startsWith("<"))
return null;
try
{
fullTag = fullTag.substring(1, fullTag.length() - 1);
}
catch (Exception e)
{
return null;
}
// get type
int nextSpace = fullTag.indexOf(' ');
if (nextSpace > 0)
{
String[] attributes = new String[DE.A_SIZE];
// tag type
String tagType = fullTag.substring(0, nextSpace);
if (tagType.startsWith(STR_FILE))
{
_isFile = true;
_tagType = tagType;
}
else if (tagType.startsWith(STR_CLASS))
{
_isClass = true;
_tagType = tagType;
}
else if (tagType.startsWith(STR_REQUEST_CLASS))
{
_isRequestClass = true;
_tagType = tagType;
}
else if (tagType.startsWith(STR_SERIALIZED))
{
_isSerialized = true;
_tagType = tagType;
}
int index = 0;
int nextQuote = 0;
int nextnextQuote = nextSpace;
while ((index < DE.A_SIZE) && (nextQuote >= 0))
{
nextQuote = fullTag.indexOf('\"', nextnextQuote + 1);
nextnextQuote = fullTag.indexOf('\"', nextQuote + 1);
if ((nextQuote >= 0) && (nextnextQuote > nextQuote) && (fullTag.length() > nextnextQuote))
{
String attribute = fullTag.substring(nextQuote + 1, nextnextQuote);
attributes[index] = convertStringFromXML(attribute);
index++;
}
}
DataElement result = null;
if (attributes.length == DE.A_SIZE)
{
String type = attributes[DE.A_TYPE];
if (type.equals(DataStoreResources.KEEPALIVE_TYPE))
{
_isKeepAlive= true;
result = _dataStore.createTransientObject(attributes);
}
else if (type.equals(DataStoreResources.KEEPALIVECONFIRM_TYPE))
{
_isKeepAliveConfirm = true;
result = _dataStore.createTransientObject(attributes);
}
else if (type.equals(DataStoreResources.DOCUMENT_TYPE))
{
String id = attributes[DE.A_ID];
if (_dataStore.contains(id))
{
result = _dataStore.find(id);
result.removeNestedData();
}
else
{
result = _dataStore.createObject(null, attributes);
}
}
else if (_isFile || _isClass || _isSerialized || parent == null)
{
result = _dataStore.createTransientObject(attributes);
}
else
{
String isRefStr = attributes[DE.A_ISREF];
if ((isRefStr != null) && isRefStr.equals("true"))
{
// new reference
String origId = attributes[DE.A_NAME];
if (_dataStore.contains(origId))
{
DataElement to = _dataStore.find(origId);
if (parent != null)
{
result = _dataStore.createReference(parent, to, attributes[DE.A_TYPE], false);
}
else
{
_dataStore.trace("NULL2!");
}
}
else
{
// creating reference to unknown object
result = _dataStore.createObject(parent, attributes);
}
}
else
{
String id = attributes[DE.A_ID];
if (id == null)
{
handlePanic(new Exception(fullTag));
return null;
}
if (parent != null && _dataStore.contains(id))
{
result = _dataStore.find(id);
// treat status special test
String name = attributes[DE.A_NAME];
String value = attributes[DE.A_VALUE];
if (type.equals(STR_STATUS) && name.equals(STR_STATUS_DONE))
{
attributes[DE.A_NAME] = STR_STATUS_ALMOST_DONE;
if (value.equals(STR_STATUS_DONE))
{
attributes[DE.A_VALUE] = STR_STATUS_ALMOST_DONE;
}
result.setAttributes(attributes);
}
else
{
result.setAttributes(attributes);
}
if (parent == null)
{
return result;
}
else if (parent == _rootDataElement)
{
DataElement rParent = result.getParent();
parent = rParent;
_rootDataElement.addNestedData(result, false);
}
else
{
if (result.getParent() == null)
{
if (result != _dataStore.getRoot())
{
result.setParent(parent);
}
}
}
if (parent != null)
{
parent.addNestedData(result, true);
}
else
{
if (result != _dataStore.getRoot())
{
_dataStore.trace("parent of " + result.getName() + " is NULL!");
}
else
{
result.setParent(null);
}
}
if (result.isDeleted())
//_dataStore.deleteObject(result.getParent(), result);
result.delete();
}
else
{
// new object
result = _dataStore.createObject(parent, attributes);
}
}
}
}
if (result != null && result.isDeleted())
{
_dataStore.deleteObject(parent, result);
}
return result;
}
return null;
}
public static String replaceSpecial(String input)
{
int indexOfAmp = input.indexOf('&');
int indexOfSemi = input.indexOf(';');
if (indexOfAmp >= 0 && indexOfSemi > indexOfAmp)
{
String converted = input.replaceAll(STR_AMP, "&")
.replaceAll(STR_SEMI, ";")
.replaceAll(STR_QUOTE, "\"")
.replaceAll(STR_APOS, "\'")
.replaceAll(STR_LT, "<")
.replaceAll(STR_GT, ">");
return converted;
}
else
{
return input;
}
}
/**
* Converts XML special character representations to the appropriate characters
* @param input buffer to convert
* @return the converted buffer
*/
public static String convertStringFromXML(String input)
{
if (input.indexOf('&') > -1)
{
return replaceSpecial(input);
/*
StringBuffer result = new StringBuffer();
String[] tokens = splitString(input);
for (int i = 0; i < tokens.length; i++)
{
String token = tokens[i];
if (token.equals(STR_AMP_TRIMMED))
{
result.append('&');
}
else if (token.equals(STR_SEMI_TRIMMED))
{
result.append(';');
}
else if (token.equals(STR_QUOTE_TRIMMED))
{
result.append('"');
}
else if (token.equals(STR_APOS_TRIMMED))
{
result.append('\'');
}
else if (token.equals(STR_LT_TRIMMED))
{
result.append('<');
}
else if (token.equals(STR_GT_TRIMMED))
{
result.append('>');
}
else
result.append(token);
}
return result.toString();
*/
}
else
{
return input;
}
}
public class KeepAliveRequestThread extends Thread
{
private long _timeout;
private DataStore _dataStore;
private boolean _failed;
public KeepAliveRequestThread(long timeout, DataStore datastore)
{
_timeout = timeout;
_dataStore = datastore;
_failed = false;
}
public void run()
{
_dataStore.sendKeepAliveRequest();
try
{
sleep(_timeout);
}
catch (InterruptedException e)
{
return;
}
_failed = true;
}
public boolean failed()
{
return _failed;
}
}
}

View file

@ -0,0 +1,128 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.util.ssl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
public class DStoreKeyStore
{
public static DStoreKeyStore _instance = null;
public DStoreKeyStore()
{
_instance = this;
}
public static DStoreKeyStore getInstance()
{
if (_instance == null)
{
new DStoreKeyStore();
}
return _instance;
}
public static KeyStore getKeyStore(String filePath, String password)
throws KeyStoreException, NoSuchAlgorithmException,
CertificateException, IOException, NoSuchProviderException
{
KeyStore keyStore= null;
if (filePath != null)
{
File keyStoreFile = new File(filePath);
/* Do not stomp an existing file */
if(!keyStoreFile.exists())
{
keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, password.toCharArray());
persistKeyStore(keyStore, filePath, password);
}
else {
keyStore = loadKeyStore(filePath, password);
}
}
return keyStore;
}
public static KeyStore loadKeyStore(String pathname, String password)
throws KeyStoreException,
NoSuchAlgorithmException,
CertificateException,
IOException,
NoSuchProviderException {
KeyStore ks=null;
File file=new File(pathname);
/* Do not stomp an existing file */
if(file.exists()) {
ks=KeyStore.getInstance("JKS");
/* Initialize the keystore with no information */
FileInputStream is=new FileInputStream(file);
ks.load(is, password.toCharArray());
is.close();
}
return ks;
}
public static Certificate loadCertificate(String certFilename)
throws CertificateException,
FileNotFoundException {
CertificateFactory factory=CertificateFactory.getInstance("X.509");
return factory.generateCertificate(new FileInputStream(certFilename));
}
public static void addCertificateToKeyStore(KeyStore ks, Certificate cert, String alias)
throws KeyStoreException {
ks.setCertificateEntry(alias, cert);
}
public static void persistKeyStore(KeyStore ks, String pathname, String password)
throws KeyStoreException,
FileNotFoundException,
NoSuchAlgorithmException,
CertificateException,
IOException {
FileOutputStream os=new FileOutputStream(pathname);
ks.store(os, password.toCharArray());
os.close();
}
}

View file

@ -0,0 +1,74 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.util.ssl;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
public class DStoreSSLContext
{
public static SSLContext getServerSSLContext(String filePath, String password)
{
SSLContext serverContext = null;
try
{
KeyStore ks = DStoreKeyStore.getKeyStore(filePath, password);
String keymgrAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keymgrAlgorithm);
kmf.init(ks, password.toCharArray());
serverContext = SSLContext.getInstance("SSL");
serverContext.init(kmf.getKeyManagers(), null, null);
}
catch (Exception e)
{
e.printStackTrace();
}
return serverContext;
}
public static SSLContext getClientSSLContext(String filePath, String password, DataStoreTrustManager trustManager)
{
SSLContext clientContext = null;
try
{
trustManager.setKeystore(filePath, password);
clientContext = SSLContext.getInstance("SSL");
TrustManager[] mgrs = new TrustManager[1];
mgrs[0] = trustManager;
clientContext.init(null, mgrs, null);
}
catch (Exception e)
{
e.printStackTrace();
}
return clientContext;
}
}

View file

@ -0,0 +1,150 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.core.util.ssl;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.net.ssl.X509TrustManager;
public class DataStoreTrustManager implements X509TrustManager
{
private KeyStore _keystore;
private List _untrustedCerts;
private List _verifyExceptions;
//private X509Certificate _untrustedCert;
//private Exception _verifyException;
private List _trustedCerts;
public DataStoreTrustManager()
{
_trustedCerts = new ArrayList();
_untrustedCerts = new ArrayList();
_verifyExceptions = new ArrayList();
}
public void setKeystore(String filePath, String password)
{
try
{
KeyStore ks = DStoreKeyStore.getKeyStore(filePath, password);
_keystore = ks;
loadTrustedCertificates();
}
catch (Exception e)
{
}
}
private void loadTrustedCertificates()
{
_trustedCerts.clear();
try
{
Enumeration aliases = _keystore.aliases();
while (aliases.hasMoreElements())
{
String alias = (String) (aliases.nextElement());
/* The alias may be either a key or a certificate */
java.security.cert.Certificate cert = _keystore.getCertificate(alias);
_trustedCerts.add(cert);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public List getUntrustedCerts()
{
return _untrustedCerts;
}
public List getVerifyExceptions()
{
return _verifyExceptions;
}
private void checkTrusted(X509Certificate[] certs, String arg1) throws CertificateException
{
_untrustedCerts.clear();
_verifyExceptions.clear();
for (int i = 0; i < certs.length; i++)
{
X509Certificate cert = certs[i];
boolean foundMatch = false;
if (_trustedCerts.size() > 0)
{
for (int j = 0; j < _trustedCerts.size() && !foundMatch; j++)
{
X509Certificate tcert = (X509Certificate)_trustedCerts.get(j);
try
{
tcert.verify(cert.getPublicKey());
foundMatch = true;
}
catch (Exception e)
{
}
}
}
if (!foundMatch)
{
_untrustedCerts.add(cert);
}
}
if (_trustedCerts.size() == 0 || _untrustedCerts.size() > 0)
{
throw new CertificateException();
}
}
public void checkClientTrusted(X509Certificate[] certs, String arg1) throws CertificateException
{
checkTrusted(certs, arg1);
}
public void checkServerTrusted(X509Certificate[] certs, String arg1) throws CertificateException
{
checkTrusted(certs,arg1);
}
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
}

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View file

@ -0,0 +1 @@
bin

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.eclipse.dstore.extra</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,14 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: %plugin.name
Bundle-SymbolicName: org.eclipse.dstore.extra
Bundle-Version: 1.0.0
Bundle-Activator: org.eclipse.dstore.extra.Activator
Bundle-Localization: plugin
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
org.eclipse.ui.views
Eclipse-LazyStart: true
Export-Package: org.eclipse.dstore.extra.internal.extra
Bundle-Vendor: Eclipse.org
Bundle-ClassPath: dstore_extra.jar

View file

@ -0,0 +1,22 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
<title>About</title>
<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1">
</head>
<body lang="EN-US">
<h2>About This Content</h2>
<p>February 24, 2005</p>
<h3>License</h3>
<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the
Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>.
For purposes of the EPL, &quot;Program&quot; will mean the Content.</p>
<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may
apply to your use of any object code in the Content. Check the Redistributor's license that was provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
indicated below, the terms and conditions of the EPL still apply to any source code in the Content.</p>
</body>
</html>

View file

@ -0,0 +1,10 @@
bin.includes = about.html,\
META-INF/,\
plugin.properties,\
dstore_extra.jar
src.includes = META-INF/,\
about.html,\
plugin.properties
jars.compile.order = dstore_extra.jar
source.dstore_extra.jar = src/
output.dstore_extra.jar = bin/

View file

@ -0,0 +1,12 @@
###############################################################################
# Copyright (c) 2000, 2006 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
plugin.name = RSE Dstore Platform Support

View file

@ -0,0 +1,57 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
public class DataElementActionFilter
{
private static String _type = "type";
private static DataElementActionFilter _instance;
public static DataElementActionFilter getInstance()
{
if (_instance == null)
_instance = new DataElementActionFilter();
return _instance;
}
/**
* @see IActionFilter#testAttribute(Object, String, String)
*/
public boolean testAttribute(Object target, String name, String value)
{
if (name.equals(_type))
{
IDataElement le = (IDataElement)target;
if (le.getType().equals(value) || le.isOfType(value))
{
return true;
}
}
return false;
}
public static boolean matches(Class aClass)
{
return false;
}
}

View file

@ -0,0 +1,32 @@
/********************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and International Business Machines Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
public class DesktopElement
{
public static boolean matches(Class aClass)
{
return false;
}
public static Object getPlatformAdapter(Object obj, Class aClass)
{
return null;
}
}

View file

@ -0,0 +1,101 @@
/********************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and International Business Machines Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
import java.util.List;
public class DomainEvent
{
public static final int UNKNOWN= 0;
public static final int INSERT= 1;
public static final int REMOVE= 2;
public static final int STRUCTURE_CHANGE= 3;
public static final int NON_STRUCTURE_CHANGE= 4;
public static final int FILE_CHANGE=5;
public static final int FIRST_CUSTOM_CHANGE= 10;
public static final int LAST_CUSTOM_CHANGE= 255;
public static final int MASK= 0xFF;
public static final int REVEAL= 0x100;
public static final int SELECT= 0x200;
public static final int INSERT_REVEAL= INSERT | REVEAL;
public static final int INSERT_REVEAL_SELECT= INSERT_REVEAL | SELECT;
private IDataElement _parent;
private int _type;
public DomainEvent(int type, IDataElement parent, Object property)
{
_type = type;
_parent = parent;
}
public DomainEvent(int type, IDataElement parent, Object property, IDataElement child)
{
_type = type;
_parent = parent;
}
public DomainEvent(IDomainNotifier source, int type, IDataElement parent, Object property)
{
_type = type;
_parent = parent;
}
public boolean equals(Object event)
{
return (((DomainEvent)event).getParent() == getParent());
}
public String getId()
{
return _parent.getId();
}
public String getName()
{
return _parent.getName();
}
public int getType()
{
return _type;
}
public IDataElement getParent()
{
return _parent;
}
public List getChildren()
{
return _parent.getNestedData();
}
public int getChildrenCount()
{
return _parent.getNestedSize();
}
}

View file

@ -0,0 +1,53 @@
/********************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and International Business Machines Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
public class DomainNotifier implements IDomainNotifier
{
public DomainNotifier()
{
}
public void enable(boolean on)
{
}
public boolean isEnabled()
{
return false;
}
public void addDomainListener(IDomainListener listener)
{
}
public void fireDomainChanged(DomainEvent event)
{
}
public boolean hasDomainListener(IDomainListener listener)
{
return false;
}
public void removeDomainListener(IDomainListener listener)
{
}
}

View file

@ -0,0 +1,35 @@
/********************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and International Business Machines Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
import java.util.List;
public interface IDataElement extends IElement
{
String getName();
String getType();
String getId();
List getNestedData();
int getNestedSize();
Object getElementProperty(Object obj);
List getAssociated(String key);
boolean isOfType(String typeStr);
}

View file

@ -0,0 +1,23 @@
/********************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and International Business Machines Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
public interface IDesktopElement
{
}

View file

@ -0,0 +1,25 @@
/********************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and International Business Machines Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
public interface IDomainListener
{
public boolean listeningTo(DomainEvent e);
public void domainChanged(DomainEvent e);
}

View file

@ -0,0 +1,27 @@
/********************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and International Business Machines Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
public interface IDomainNotifier
{
public void addDomainListener(IDomainListener listener);
public void fireDomainChanged(DomainEvent event);
public boolean hasDomainListener(IDomainListener listener);
public void removeDomainListener(IDomainListener listener);
}

View file

@ -0,0 +1,24 @@
/********************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and International Business Machines Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
public interface IElement
{
public Object getElementProperty(Object key);
}

View file

@ -0,0 +1,23 @@
/********************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and International Business Machines Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
public interface IPropertySource
{
}

View file

@ -0,0 +1,31 @@
/********************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and International Business Machines Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
public class PropertySource
{
public PropertySource(IDataElement element)
{
}
public static boolean matches(Class key)
{
return false;
}
}

View file

@ -0,0 +1 @@
dstore_extra_server.jar

View file

@ -0,0 +1,70 @@
/********************************************************************************
* Copyright (c) 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The main plugin class to be used in the desktop.
*/
public class Activator extends AbstractUIPlugin {
//The shared instance.
private static Activator plugin;
/**
* The constructor.
*/
public Activator() {
plugin = this;
}
/**
* This method is called upon plug-in activation
*/
public void start(BundleContext context) throws Exception {
super.start(context);
}
/**
* This method is called when the plug-in is stopped
*/
public void stop(BundleContext context) throws Exception {
super.stop(context);
plugin = null;
}
/**
* Returns the shared instance.
*/
public static Activator getDefault() {
return plugin;
}
/**
* Returns an image descriptor for the image file at the given
* plug-in relative path.
*
* @param path the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return AbstractUIPlugin.imageDescriptorFromPlugin("org.eclipse.dstore.extra", path);
}
}

View file

@ -0,0 +1,87 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
public class DataElementActionFilter implements org.eclipse.ui.IActionFilter {
// constants to be used by Eclipse Filtering and Enablement Support.
private static String _type = "type";
private static String _name = "name";
private static DataElementActionFilter _instance;
public static DataElementActionFilter getInstance() {
if (_instance == null)
_instance = new DataElementActionFilter();
return _instance;
}
/**
* Supports Eclipse filtering and enablement.
* eg:<code>
* <extension point="org.eclipse.rse.ui.popupMenus">
* <objectContribution id="xyz.perspective.rse.actions.createprojectcontribution"
* subsytemfactoryid="xyz.files"
* typecategoryfilter="LIBRARIES">
* <action id="xyz.perspective.rse.actions.createproject"
* label="%create_xyz_project"
* tooltip="%create_xyz_project"
* helpContextId="xyz.perspective.rse01"
* enablesFor="1"
* class="xyz.rse.actions.RSECreateXyzProjectAction">
* <enablement>
* <not>
* <objectState name="name" value="SPECIAL*"/>
* </not>
* </enablement>
* </action>
* </objectContribution>
* </extension>
* </code>
*
* The above contribution uses the RSE pop-up extension point to contribute an action
* to any single RSE object but not anything beginning with SPECIAL.
* @see IActionFilter#testAttribute(Object, String, String)
*/
public boolean testAttribute(Object target, String name, String value) {
if (name.equals(_type) && target instanceof IDataElement) {
// support for "type" filter
IDataElement le = (IDataElement) target;
if (le.getType().equals(value) || le.isOfType(value))
return true;
} else if (name.equals(_name) && target instanceof IDataElement) {
// support for "name" filter.
IDataElement le = (IDataElement) target;
if (value.endsWith("*")) {
// we have a wild card test, and * is the last character in the value
if (le
.getName()
.startsWith(value.substring(0, value.length() - 1)))
return true;
} else if (le.getName().equals(value))
return true;
}
// type and name filter do not match, or we have a filter we do not support.
return false;
}
public static boolean matches(Class aClass) {
return (aClass == org.eclipse.ui.IActionFilter.class);
}
}

View file

@ -0,0 +1,82 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
import org.eclipse.jface.resource.*;
import java.util.*;
public class DesktopElement implements org.eclipse.ui.model.IWorkbenchAdapter
{
private IDataElement _element;
public DesktopElement (IDataElement e)
{
_element = e;
}
public IDataElement toElement(Object object)
{
IDataElement element = null;
if (object instanceof IDataElement)
{
element = (IDataElement)object;
}
else
{
element = _element;
}
return element;
}
public Object[] getChildren(Object o)
{
IDataElement element = toElement(o);
List objs = element.getAssociated("contents");
return objs.toArray();
}
public ImageDescriptor getImageDescriptor(Object object)
{
return null;
}
public String getLabel(Object o)
{
return (String)_element.getElementProperty("value");
}
public Object getParent(Object o)
{
return null;
}
public static boolean matches(Class aClass)
{
return (aClass == org.eclipse.ui.model.IWorkbenchAdapter.class);
}
public static Object getPlatformAdapter(Object obj, Class aClass)
{
return org.eclipse.core.runtime.Platform.getAdapterManager().getAdapter(obj, aClass);
}
}

View file

@ -0,0 +1,101 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
import java.util.*;
public class DomainEvent
{
public static final int UNKNOWN= 0;
public static final int INSERT= 1;
public static final int REMOVE= 2;
public static final int STRUCTURE_CHANGE= 3;
public static final int NON_STRUCTURE_CHANGE= 4;
public static final int FILE_CHANGE=5;
public static final int FIRST_CUSTOM_CHANGE= 10;
public static final int LAST_CUSTOM_CHANGE= 255;
public static final int MASK= 0xFF;
public static final int REVEAL= 0x100;
public static final int SELECT= 0x200;
public static final int INSERT_REVEAL= INSERT | REVEAL;
public static final int INSERT_REVEAL_SELECT= INSERT_REVEAL | SELECT;
private IDataElement _parent;
private int _type;
public DomainEvent(int type, IDataElement parent, Object property)
{
_type = type;
_parent = parent;
}
public DomainEvent(int type, IDataElement parent, Object property, IDataElement child)
{
_type = type;
_parent = parent;
}
public DomainEvent(IDomainNotifier source, int type, IDataElement parent, Object property)
{
_type = type;
_parent = parent;
}
public boolean equals(Object event)
{
return (((DomainEvent)event).getParent() == getParent());
}
public String getId()
{
return _parent.getId();
}
public String getName()
{
return _parent.getName();
}
public int getType()
{
return _type;
}
public IDataElement getParent()
{
return _parent;
}
public List getChildren()
{
return _parent.getNestedData();
}
public int getChildrenCount()
{
return _parent.getNestedSize();
}
}

View file

@ -0,0 +1,118 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
import java.util.*;
public class DomainNotifier implements IDomainNotifier
{
private ArrayList _listeners;
private boolean _enabled;
/*
public class FireMainThread extends Job
{
public boolean _isWorking;
private DomainEvent _event;
public FireMainThread(DomainEvent event)
{
super("DStore Events Fired");
_isWorking = false;
_event = event;
setPriority(Job.INTERACTIVE);
}
public IStatus run(IProgressMonitor monitor)
{
_isWorking = true;
if (_event.getType() != DomainEvent.FILE_CHANGE)
{
for (int i = 0; i < _listeners.size(); i++)
{
IDomainListener listener = (IDomainListener) _listeners.get(i);
if ((listener != null) && listener.listeningTo(_event))
{
listener.domainChanged(_event);
}
}
}
_isWorking = false;
return Status.OK_STATUS;
}
}
*/
public DomainNotifier()
{
_listeners = new ArrayList();
_enabled = false;
}
public void enable(boolean on)
{
_enabled = on;
}
public boolean isEnabled()
{
return _enabled;
}
public void addDomainListener(IDomainListener listener)
{
if (!_listeners.contains(listener))
{
_listeners.add(listener);
}
}
public void fireDomainChanged(DomainEvent event)
{
if (_enabled)
{
for (int i = 0; i < _listeners.size(); i++)
{
IDomainListener listener = (IDomainListener) _listeners.get(i);
if ((listener != null) && listener.listeningTo(event))
{
listener.domainChanged(event);
}
}
//FireMainThread fireJob = new FireMainThread(event);
//fireJob.schedule();
}
}
public boolean hasDomainListener(IDomainListener listener)
{
return _listeners.contains(listener);
}
public void removeDomainListener(IDomainListener listener)
{
_listeners.remove(listener);
}
}

View file

@ -0,0 +1,23 @@
/********************************************************************************
* Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* The following IBM employees contributed to the Remote System Explorer
* component that contains this file: David McKnight, Kushal Munir,
* Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson,
* Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
*
* Contributors:
* {Name} (company) - description of contribution.
********************************************************************************/
package org.eclipse.dstore.extra.internal.extra;
public interface IActionFilter extends org.eclipse.ui.IActionFilter
{
}

Some files were not shown because too many files have changed in this diff Show more