cdev-1.7.2n

This commit is contained in:
2022-12-13 12:44:04 +01:00
commit b3b88fc333
1357 changed files with 338883 additions and 0 deletions
+143
View File
@@ -0,0 +1,143 @@
ifneq ("$(VERBOSE)", "YES")
MAKE := $(MAKE) -s VERBOSE=NO
endif
BASEDIR = $(shell pwd)
BASEINCLUDES = $(BASEDIR)/include
BASEBIN = $(BASEDIR)/bin
BASELIB = $(BASEDIR)/lib
HEADERS = *.h *.i
SRCONLY_DIRS = $(BASEDIR)/cdevClient\
$(BASEDIR)/cdevContextMap\
$(BASEDIR)/cdevMonitorTable\
$(BASEDIR)/cdevPacket\
$(BASEDIR)/cdevServer\
$(BASEDIR)/cdevTagMap\
$(BASEDIR)/common\
LIB_DIRS = $(BASEDIR)/cdevReactor\
$(BASEDIR)/NameServer/src\
$(BASEDIR)/NameServer/cdev\
$(BASEDIR)/lib
UTIL_DIRS = $(BASEDIR)/NameServer/dumpServer
EXAMPLE_DIRS = $(BASEDIR)/NameServer/examples\
$(BASEDIR)/example
TEST_DIRS = $(BASEDIR)/tests\
$(BASEDIR)/cdevReactor/TimerTest\
$(BASEDIR)/cdevReactor/ServerTest
DOC_DIRS = $(BASEDIR)/doc\
HEADER_DIRS = $(BASEDIR)/cdevReactor\
$(BASEDIR)/cdevTagMap\
$(BASEDIR)/cdevContextMap\
$(BASEDIR)/cdevMonitorTable\
$(BASEDIR)/cdevPacket\
$(BASEDIR)/common\
$(BASEDIR)/cdevClient\
$(BASEDIR)/cdevServer\
$(BASEDIR)/NameServer/src\
$(BASEDIR)/NameServer/cdev
CLEAN_DIRS = $(SRCONLY_DIRS)\
$(LIB_DIRS)\
$(UTIL_DIRS)\
$(EXAMPLE_DIRS)\
$(TEST_DIRS)\
$(DOC_DIRS)
PURGE_DIRS = $(SRCONLY_DIRS)\
$(BASEDIR)/cdevReactor\
$(BASEDIR)/NameServer/src\
$(BASEDIR)/NameServer/cdev\
$(BASEDIR)/liteClient\
$(UTIL_DIRS)\
$(EXAMPLE_DIRS)\
$(TEST_DIRS)\
$(DOC_DIRS)
all: directories headers archive shared utils
directories:
@echo "=> Creating directories for binary files"
@mkdir -p $(BASEBIN)
@mkdir -p $(BASELIB)
@echo "<= Done...\n"
headers:
@echo "=> Linking header files to include directory"
@for dir in $(HEADER_DIRS); \
do \
cd $$dir; \
for file in $(HEADERS); \
do \
if test -f $$file; then cp $$dir/$$file $(BASEINCLUDES)/$$file; fi; \
done \
done
@cp $(BASEDIR)/include/makeinclude/Makefile.lib $(BASEDIR)/lib/Makefile
@echo "<= Done...\n"
archive:
@echo "=> Building archive version of libraries"
@for dir in $(LIB_DIRS); \
do \
$(MAKE) -C $$dir SHOBJ=NO; \
done
@echo "<= Done...\n"
shared:
@echo "=> Building shared version of libraries"
@for dir in $(LIB_DIRS); \
do \
$(MAKE) -C $$dir SHOBJ=YES; \
done
@echo "<= Done...\n"
utils:
@echo "=> Building utility programs"
@for dir in $(UTIL_DIRS); \
do \
$(MAKE) -C $$dir SHOBJ=YES; \
done
@echo "<= Done...\n"
examples:
@echo "=> Building example programs"
@for dir in $(EXAMPLE_DIRS); \
do \
$(MAKE) -C $$dir SHOBJ=YES; \
done
@echo "<= Done...\n"
apps:
@echo "=> Building test programs"
@for dir in $(TEST_DIRS); \
do \
$(MAKE) -C $$dir SHOBJ=YES; \
done
@echo "<= Done...\n"
clean:
@echo "=> Cleaning CDEV Generic Server Directories"
@for dir in $(CLEAN_DIRS); \
do \
$(MAKE) -C $$dir clean; \
done
@echo "<= Done...\n"
purge:
@echo "=> Purging CDEV Generic Server Directories"
@echo " => Removing links to header files"
@rm -rf $(BASEINCLUDES)/*.h $(BASEINCLUDES)/*.i
@echo " Done..."
@for dir in $(PURGE_DIRS); \
do \
$(MAKE) -C $$dir purge; \
done
@rm -rf $(BASEDIR)/lib
@rm -rf $(BASEDIR)/bin
@echo "<= Done...\n"
+135
View File
@@ -0,0 +1,135 @@
!IF "$(VERBOSE)" != "YES"
MAKE = $(MAKE) -s VERBOSE=NO
!ENDIF
BASEDIR = $(MAKEDIR)
BASEINCLUDES = $(BASEDIR)\include
BASEBIN = $(BASEDIR)\bin
BASELIB = $(BASEDIR)\lib
HEADERS = dir\*.h dir\*.i
SRCONLY_DIRS = $(BASEDIR)\cdevClient\
$(BASEDIR)\cdevContextMap\
$(BASEDIR)\cdevMonitorTable\
$(BASEDIR)\cdevPacket\
$(BASEDIR)\cdevServer\
$(BASEDIR)\cdevTagMap\
$(BASEDIR)\common\
LIB_DIRS = $(BASEDIR)\cdevReactor\
$(BASEDIR)\NameServer\src\
$(BASEDIR)\NameServer\cdev\
$(BASEDIR)\lib\
$(BASEDIR)\liteClient
UTIL_DIRS = $(BASEDIR)\NameServer\dumpServer
EXAMPLE_DIRS = $(BASEDIR)\NameServer\examples\
$(BASEDIR)\example
TEST_DIRS = $(BASEDIR)\tests\
$(BASEDIR)\cdevReactor\TimerTest\
$(BASEDIR)\cdevReactor\ServerTest
DOC_DIRS = $(BASEDIR)\doc\
HEADER_DIRS = $(BASEDIR)\cdevReactor\
$(BASEDIR)\cdevTagMap\
$(BASEDIR)\cdevContextMap\
$(BASEDIR)\cdevMonitorTable\
$(BASEDIR)\cdevPacket\
$(BASEDIR)\common\
$(BASEDIR)\cdevClient\
$(BASEDIR)\cdevServer\
$(BASEDIR)\NameServer\src\
$(BASEDIR)\NameServer\cdev
CLEAN_DIRS = $(SRCONLY_DIRS)\
$(LIB_DIRS)\
$(UTIL_DIRS)\
$(EXAMPLE_DIRS)\
$(TEST_DIRS)\
$(DOC_DIRS)
all: hail directories headers shared utils fairwell
everything: hail directories headers shared utils examples apps other fairwell
hail:
@echo ---------------------------------------------------------------
@echo Building CDEV Generic Server for Target : $(ARCH)
@echo ---------------------------------------------------------------
fairwell:
@echo ---------------------------------------------------------------
@echo CDEV Generic Server has been built for Target : $(ARCH)
@echo ---------------------------------------------------------------
directories:
@echo =^> Creating directories for binary files
-@if not exist $(BASEBIN) mkdir $(BASEBIN)
-@if not exist $(BASELIB) mkdir $(BASELIB)
-@copy $(BASEINCLUDES)\makeinclude\NMakefile.lib $(BASELIB)\NMakefile.mak
@echo ^<= Done...
headers:
@echo =^> Copying header files to include directory
-@for %d in ($(HEADER_DIRS)) do @for %f in ($(HEADERS:dir=%d)) do @copy %f $(BASEINCLUDES) > nul
@echo ^<= Done...
archives:
@echo =^> Building archive version of libraries
@for %d in ($(LIB_DIRS)) do @cd %d & $(MAKE) /NOLOGO SHOBJ=NO /f NMakefile.mak
@echo <^= Done...
shared:
@echo =^> Building shared version of libraries
@for %d in ($(LIB_DIRS)) do @cd %d & $(MAKE) /NOLOGO SHOBJ=YES /f NMakefile.mak
@echo ^<= Done...
utils:
@echo =^> Building utility programs
@for %d in ($(UTIL_DIRS)) do @cd %d & $(MAKE) /NOLOGO SHOBJ=YES /f NMakefile.mak
@echo ^<= Done...
examples:
@echo =^> Building example programs
@for %d in ($(EXAMPLE_DIRS)) do @cd %d & $(MAKE) /NOLOGO SHOBJ=YES /f NMakefile.mak
@echo ^<= Done...
apps:
@echo =^> Building test programs
@for %d in ($(TEST_DIRS)) do @cd %d & $(MAKE) /NOLOGO SHOBJ=YES /f NMakefile.mak
@echo ^<= Done...
other:
@echo =^> Building miscellaneous applications and libraries
@for %d in ($(SRCONLY_DIRS)) do @cd %d & $(MAKE) /NOLOGO SHOBJ=YES /f NMakefile.mak
@echo ^<= Done...
clean:
@echo =^> Cleaning CDEV Generic Server Directories
@for %d in ($(CLEAN_DIRS)) do @if exist %d\NMakefile.mak cd %d & $(MAKE) /NOLOGO /f NMakefile.mak clean
@echo ^<= Done...
purge:
@echo =^> Purging CDEV Generic Server Directories
@echo ^ ^ ^ =^> Removing header files
-@for %f in ($(BASEINCLUDES)\*.h $(BASEINCLUDES)\*.i) do @erase %f
@echo ^ ^ ^ ^ ^ ^ Done...
@for %d in ($(CLEAN_DIRS)) do @if exist %d\NMakefile.mak cd %d & $(MAKE) /NOLOGO /f NMakefile.mak purge
-@if exist $(BASEDIR)\lib rmdir /s /q $(BASEDIR)\lib
-@if exist $(BASEDIR)\bin rmdir /s /q $(BASEDIR)\bin
@echo ^<= Done...
!IF "$(SUBTARGETDIR)" == ""
subtarget :
-@echo SUBTARGETDIR variable must be defined to build subtargets
!ELSE
!IF "$(SUBTARGET)" == ""
SUBTARGET = all
!ENDIF
subtarget :
@cd $(SUBTARGETDIR)
@$(MAKE) /NOLOGO /f NMakefile.mak $(SUBTARGET)
!ENDIF
+21
View File
@@ -0,0 +1,21 @@
BASEDIR = $(shell pwd)
BUILDDIRS = $(BASEDIR)/src $(BASEDIR)/cdev $(BASEDIR)/dumpServer $(BASEDIR)/examples
CLEANDIRS = $(BASEDIR)/src $(BASEDIR)/cdev $(BASEDIR)/dumpServer $(BASEDIR)/examples
all:
@for dir in $(BUILDDIRS); \
do \
$(MAKE) -C $$dir; \
done
clean:
@for dir in $(CLEANDIRS); \
do \
$(MAKE) -C $$dir clean; \
done
purge:
@for dir in $(CLEANDIRS); \
do \
$(MAKE) -C $$dir purge; \
done
+83
View File
@@ -0,0 +1,83 @@
ARCH = OS
SHOBJ = YES
APPNAME = "Name Server Interface for CDEV"
include ../../include/makeinclude/Makefile.$(ARCH)
TEMPLINKS = rsvcSlist.cc \
rsvcHSlist.cc \
rsvcHash.cc \
rsvcDataStreamer.cc \
rsvcDataEntry.cc \
rsvcData.cc \
rsvcNetData.cc \
rsvcCbk.cc \
rsvcHashable.cc \
rsvcStreamable.cc \
rsvcCallback.cc \
rsvcClient.cc \
rsvcUdpClient.cc
OBJS = $(OBJDIR)/rsvcSlist.o \
$(OBJDIR)/rsvcHSlist.o \
$(OBJDIR)/rsvcHash.o \
$(OBJDIR)/rsvcDataStreamer.o \
$(OBJDIR)/rsvcDataEntry.o \
$(OBJDIR)/rsvcData.o \
$(OBJDIR)/rsvcNetData.o \
$(OBJDIR)/rsvcCbk.o \
$(OBJDIR)/rsvcHashable.o \
$(OBJDIR)/rsvcStreamable.o \
$(OBJDIR)/rsvcCallback.o \
$(OBJDIR)/rsvcClient.o \
$(OBJDIR)/rsvcUdpClient.o \
$(OBJDIR)/rnsService.o \
$(OBJDIR)/rnsRequestObject.o
ifeq ($(SHOBJ),YES)
TARGETS = $(CDEVSHOBJ)/$(CDEVVERSION)/rnsService.so $(BASEBIN)/cdev_test
else
TARGETS = $(BASELIB)/librnsService.a
endif
CXXINCLUDES = -I./
LIBS = -L$(CDEVLIB) -lcdevReactor $(CDEVLIBS) $(OSLIBS)
BINARIES = $(BASEBIN)/cdev_test $(BASELIB)/rnsService.so $(BASELIB)/librnsService.a $(TEMPLINKS)
targets: $(TEMPLINKS) $(TARGETS)
$(TEMPLINKS) :
@cp $^ $@
$(BASEBIN)/cdev_test: $(OBJDIR)/cdev_test.o
$(LINK.cc) $^ $(LIBS) -o $@
$(BASELIB)/librnsService.a: $(OBJS)
$(LINK.a) $@ $^
@$(RANLIB) $@ > /dev/null
@cp $@ $(CDEVLIB)
$(BASELIB)/rnsService.so: $(OBJS)
@mkdir -p $(CDEVSHOBJ)/$(CDEVVERSION)
$(LINK.so) -o $@ $^ $(NETLIBS)
@cp $@ $(CDEVSHOBJ)/$(CDEVVERSION)
$(CDEVSHOBJ)/$(CDEVVERSION)/rnsService.so : $(BASELIB)/rnsService.so
@mkdir -p $(@D)
@echo " => Copying $(@^) to $@"
@rm -f $@
@cp $^ $@
rsvcSlist.cc : ../src/rsvcSlist.cc
rsvcHSlist.cc : ../src/rsvcHSlist.cc
rsvcHash.cc : ../src/rsvcHash.cc
rsvcDataStreamer.cc : ../src/rsvcDataStreamer.cc
rsvcDataEntry.cc : ../src/rsvcDataEntry.cc
rsvcData.cc : ../src/rsvcData.cc
rsvcNetData.cc : ../src/rsvcNetData.cc
rsvcCbk.cc : ../src/rsvcCbk.cc
rsvcHashable.cc : ../src/rsvcHashable.cc
rsvcStreamable.cc : ../src/rsvcStreamable.cc
rsvcCallback.cc : ../src/rsvcCallback.cc
rsvcClient.cc : ../src/rsvcClient.cc
rsvcUdpClient.cc : ../src/rsvcUdpClient.cc
@@ -0,0 +1,118 @@
.SUFFIXES: .cc .obj
APPNAME = Name Server Interface for CDEV
ARCH = WINNT-4.0
BINARIES = $(TEMPLINKS) $(BASEBIN)\cdev_test
include ..\..\include\makeinclude\Makefile.WINNT-4.0
TEMPLINKS = rsvcSlist.cc\
rsvcHSlist.cc\
rsvcHash.cc\
rsvcDataStreamer.cc\
rsvcDataEntry.cc\
rsvcData.cc\
rsvcNetData.cc\
rsvcCbk.cc\
rsvcHashable.cc\
rsvcStreamable.cc\
rsvcCallback.cc\
rsvcClient.cc\
rsvcUdpClient.cc
OBJS = $(OBJDIR)\rsvcSlist.obj\
$(OBJDIR)\rsvcHSlist.obj\
$(OBJDIR)\rsvcHash.obj\
$(OBJDIR)\rsvcDataStreamer.obj\
$(OBJDIR)\rsvcDataEntry.obj\
$(OBJDIR)\rsvcData.obj\
$(OBJDIR)\rsvcNetData.obj\
$(OBJDIR)\rsvcCbk.obj\
$(OBJDIR)\rsvcHashable.obj\
$(OBJDIR)\rsvcStreamable.obj\
$(OBJDIR)\rsvcCallback.obj\
$(OBJDIR)\rsvcClient.obj\
$(OBJDIR)\rsvcUdpClient.obj\
$(OBJDIR)\rnsService.obj\
$(OBJDIR)\rnsRequestObject.obj
!IF "$(SHOBJ)" == "YES"
TARGETS = $(TEMPLINKS) $(CDEVSHOBJ)\$(CDEVVERSION)\rnsService.dll $(BASEBIN)\cdev_test.exe
!ELSE
TARGETS = $(TEMPLINKS) $(CDEVLIB)\rnsService.lib
!ENDIF
CXXINCLUDES = -I.\\
CXXEXTRA_DLL = /D "_RSVC_CORE_EXPORTS_=1"
targets : $(TARGETS)
@erase $(TEMPLINKS)
$(BASEBIN)\cdev_test.exe: $(OBJDIR)\cdev_test.obj
-@if exist $@ erase $@
@echo ^ ^ ^ ^ ^ ^ =^> Linking $(@F)
$(LINK) $(CDEVLIB)\cdev.lib\
$(LINK_EXE_FLAGS) /out:$@ $?
@echo ^ ^ ^ ^ ^ ^ ^ ^ ^ Done...
$(CDEVLIB)\rnsService.lib: $(OBJS)
@echo ^ ^ ^ =^> Linking $(@F)
-@if exist $@ erase $@
-@if not exist $(@D) mkdir $(@D)
@$(LIB32) $(CDEVLIB)\cdev.lib\
$(LINK_LIB_FLAGS) /out:$@ $(OBJS)
@echo ^ ^ ^ ^ ^ ^ Done...
$(CDEVLIB)\rnsService.dll: $(OBJS)
@echo ^ ^ ^ =^> Linking $(@F)
-@if exist $@ erase $@
-@if not exist $(@D) mkdir $(@D)
@$(LIB32) $(CDEVLIB)\cdev.lib\
$(LINK_DLL_FLAGS) /out:$@ /implib:$(@D)\$(@B).lib $(OBJS)
-@if not exist $(CDEVSHOBJ)\$(CDEVVERSION) mkdir $(CDEVSHOBJ)\$(CDEVVERSION)
@copy $@ $(CDEVSHOBJ)\$(CDEVVERSION)\$(@F) > nul
@echo ^ ^ ^ ^ ^ ^ Done...
$(CDEVSHOBJ)\$(CDEVVERSION)\rnsService.dll : $(CDEVLIB)\rnsService.dll
@echo ^ ^ ^ =^> Transfer $(@F) to CDEVSHOBJ directory
-@copy $(CDEVLIB)\rnsService.dll $@
rsvcSlist.cc : ..\src\rsvcSlist.cc
-@$(CREATE_LINK)
rsvcHSlist.cc : ..\src\rsvcHSlist.cc
-@$(CREATE_LINK)
rsvcHash.cc : ..\src\rsvcHash.cc
-@$(CREATE_LINK)
rsvcDataStreamer.cc : ..\src\rsvcDataStreamer.cc
-@$(CREATE_LINK)
rsvcDataEntry.cc : ..\src\rsvcDataEntry.cc
-@$(CREATE_LINK)
rsvcData.cc : ..\src\rsvcData.cc
-@$(CREATE_LINK)
rsvcNetData.cc : ..\src\rsvcNetData.cc
-@$(CREATE_LINK)
rsvcCbk.cc : ..\src\rsvcCbk.cc
-@$(CREATE_LINK)
rsvcHashable.cc : ..\src\rsvcHashable.cc
-@$(CREATE_LINK)
rsvcStreamable.cc : ..\src\rsvcStreamable.cc
-@$(CREATE_LINK)
rsvcCallback.cc : ..\src\rsvcCallback.cc
-@$(CREATE_LINK)
rsvcClient.cc : ..\src\rsvcClient.cc
-@$(CREATE_LINK)
rsvcUdpClient.cc : ..\src\rsvcUdpClient.cc
-@$(CREATE_LINK)
+132
View File
@@ -0,0 +1,132 @@
// simple test for name server cdev interface
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cdevSystem.h>
#include <cdevRequestObject.h>
#ifdef _WIN32
inline int strcasecmp ( const char * string1, const char * string2 )
{
return _stricmp(string1, string2);
}
#endif
static void entryCallback (int status, void *,
cdevRequestObject&, cdevData& data)
{
if (status == CDEV_SUCCESS || status == CDEV_INCOMPLETE) {
printf ("New server is here \n");
data.asciiDump ();
}
else if (status == CDEV_CBK_FINISHED) {
printf ("entry monitor finished\n");
}
else if (status == CDEV_DISCONNECTED)
printf ("Server is gone\n");
else
printf ("monitor callback failed\n");
}
static void monCallback (int status, void* /* arg */,
cdevRequestObject& /* obj */, cdevData& data)
{
if (status == CDEV_SUCCESS)
data.asciiDump ();
else if (status == CDEV_CBK_FINISHED) {
printf ("monitor finished\n");
data.asciiDump ();
}
else if (status == CDEV_DISCONNECTED)
printf ("server is dead\n");
else
printf ("monitor callback failed\n");
}
int main (int /* argc */, char** /* argv */)
{
cdevSystem& system = cdevSystem::defaultSystem ();
char temp[100];
char comd[100];
printf ("Enter cdev test command\n");
scanf ("%s", comd);
if (strcasecmp (comd, "get") == 0) {
cdevRequestObject* obj = cdevRequestObject::attachPtr ("serverNs", "get");
if (obj) {
cdevData result;
cdevData out;
printf ("enter namd and domain \n");
char name[100], domain[100];
scanf ("%s %s", name, domain);
out.insert ("name", name);
out.insert ("domain", domain);
if (obj->send (out, result) == CDEV_SUCCESS) {
result.asciiDump ();
}
else
printf ("get data failed\n");
}
}
else if (strcasecmp (comd, "monitorOn") == 0) {
cdevRequestObject* obj = cdevRequestObject::attachPtr ("serverNs",
"monitorOn");
if (obj) {
cdevData result;
cdevData out;
printf ("enter namd and domain \n");
char name[100], domain[100];
scanf ("%s %s", name, domain);
out.insert ("name", name);
out.insert ("domain", domain);
cdevCallback cbk (monCallback, 0);
if (obj->sendCallback (out, cbk) != CDEV_SUCCESS)
printf ("monitor data failed\n");
else {
while (1)
system.pend ();
}
// now remove monitor
cdevRequestObject* obj0 = cdevRequestObject::attachPtr ("serverNs",
"monitorOff");
if (obj0) {
if (obj0->sendCallback (out, cbk) != CDEV_SUCCESS)
printf ("monitor off data failed\n");
else
system.pend (20.0);
}
}
}
else if (strcasecmp (comd, "monitorEntry") == 0) {
cdevRequestObject* obj = cdevRequestObject::attachPtr ("serverNs",
"monitorEntry");
if (obj) {
cdevCallback cbk (entryCallback, 0);
if (obj->sendCallback (0, cbk) != CDEV_SUCCESS)
printf ("monitor entry failed\n");
else {
while (1)
system.pend ();
}
// now remove monitor
cdevRequestObject* obj0 = cdevRequestObject::attachPtr ("serverNs",
"monitorEntryOff");
if (obj0) {
if (obj0->sendCallback (0, cbk) != CDEV_SUCCESS)
printf ("monitor off data failed\n");
else
system.pend (20.0);
}
}
}
return 0;
}
+17
View File
@@ -0,0 +1,17 @@
service rns {
tags {PV}
}
class RNS {
messages {
get rns;
monitorOn rns;
monitorOff rns;
monitorEntry rns;
monitorEntryOff rns;
}
}
RNS :
serverNs
;
@@ -0,0 +1,54 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
// Name Server Monitor Object
//
// Author: Jie Chen
//
//
//
#ifndef _RNS_MONITOR_OBJ_H
#define _RNS_MONITOR_OBJ_H
#include <cdevMonitorObj.h>
class rnsRequestObject;
class rnsMonitorObj : public cdevMonitorObj
{
public:
// constructor and destructor
rnsMonitorObj (cdevTranObj& tranObj)
:cdevMonitorObj (tranObj), out_ (0), started_ (1)
{
#ifdef _TRACE_OBJECTS
printf (" Create rnsMonitorObj Class Object\n");
#endif
}
~rnsMonitorObj (void)
{
#ifdef _TRACE_OBJECTS
printf (" Delete rnsMonitorObj Class Object\n");
#endif
if (out_)
delete out_;
}
const char* className (void) const {return "rnsMonitorObj";}
// out bound cdevdata
cdevData* out_;
// whether this monitor callback is restarted or not
int started_;
};
#endif
@@ -0,0 +1,439 @@
#include <cdevSystem.h>
#include <cdevRequestObject.h>
#include <cdevData.h>
#include <cdevCallback.h>
class rnsQueryCollector
{
private:
cdevData * data;
int deleteFlag;
unsigned char * byteData;
short * shortData;
unsigned short * ushortData;
long * longData;
unsigned long * ulongData;
float * floatData;
double * doubleData;
cdev_TS_STAMP * tsData;
size_t byteCnt;
size_t shortCnt;
size_t ushortCnt;
size_t longCnt;
size_t ulongCnt;
size_t floatCnt;
size_t doubleCnt;
size_t tsCnt;
public:
rnsQueryCollector ( cdevData & userData, int deleteData = 0 )
: data(&userData), deleteFlag(deleteData),
byteData(NULL), shortData(NULL), ushortData(NULL),
longData(NULL), ulongData(NULL), floatData(NULL),
doubleData(NULL), tsData(NULL), byteCnt(0),
shortCnt(0), ushortCnt(0), longCnt(0), ulongCnt(0),
floatCnt(0), doubleCnt(0), tsCnt(0)
{
data->remove();
}
~rnsQueryCollector ( void )
{
if(deleteFlag) delete data;
if(byteData) delete byteData;
if(shortData) delete shortData;
if(ushortData) delete ushortData;
if(longData) delete longData;
if(ulongData) delete ulongData;
if(floatData) delete floatData;
if(doubleData) delete doubleData;
if(tsData) delete tsData;
}
cdevData * getData ( void ) { return data; }
void clearData ( void ) { data->remove(); }
inline int collect ( cdevData & userData );
private:
inline int collectAttribute ( cdevData & userData, int tag, int position );
inline void collectByteAttribute ( cdevData & userData, int tag, int position );
inline void collectShortAttribute ( cdevData & userData, int tag, int position );
inline void collectUShortAttribute ( cdevData & userData, int tag, int position );
inline void collectLongAttribute ( cdevData & userData, int tag, int position );
inline void collectULongAttribute ( cdevData & userData, int tag, int position );
inline void collectFloatAttribute ( cdevData & userData, int tag, int position );
inline void collectDoubleAttribute ( cdevData & userData, int tag, int position );
inline void collectStringAttribute ( cdevData & userData, int tag, int position );
inline void collectTimestampAttribute ( cdevData & userData, int tag, int position );
};
// *****************************************************************************
// * class rnsQueryCallback :
// * This class provides the methods to allow a rnsQueryCollector to be
// * incorporated into a cdevCallback. The localCallback function will
// * be called with results until the data has been completely collected,
// * and only then will the user callback be executed - providing full
// * data.
// *****************************************************************************
class rnsQueryCallback : public cdevCallback
{
private:
rnsQueryCollector collector;
cdevCallback callback;
public:
rnsQueryCallback ( cdevCallback & Callback )
: cdevCallback(), callback(Callback), collector(*(new cdevData), 1)
{
userarg_ = this;
function_ = rnsQueryCallback::localCallback;
}
virtual ~rnsQueryCallback ( void )
{
}
static void localCallback ( int status, void * arg, cdevRequestObject & req, cdevData & data)
{
rnsQueryCallback * qCallback;
if((qCallback = (rnsQueryCallback *)arg)!=NULL)
{
if(status==CDEV_SUCCESS ||
status==CDEV_INCOMPLETE)
{
qCallback->collector.collect(data);
}
if(status==CDEV_SUCCESS ||
status==CDEV_ERROR ||
status==CDEV_NOTFOUND ||
status==CDEV_MSG_ERR)
{
qCallback->callback.fireCallback(status, qCallback->callback.userarg(),
req, *qCallback->collector.getData(), 0);
}
}
}
};
// *****************************************************************************
// * rnsQueryCollector::collect :
// * This method is called when a cdevData object needs to be appended to
// * the cdevData object that is serving as a collection. This method will
// * transfer each of the data items in the userData object to the proper
// * position in the local data object.
// *****************************************************************************
int rnsQueryCollector::collect ( cdevData & userData )
{
int cnt = 0;
size_t size = 0;
cdevDataIterator iter(&userData);
cdevDataIterator dIter(data);
// *********************************************************************
// * Look through the existing data and determine the largest number
// * of items that exist in a single tagged item. This value will be
// * used to specify the position of the data that is being added to the
// * array.
// *********************************************************************
dIter.init();
while(dIter.tag()!=0)
{
size_t elems = 0;
data->getElems(dIter.tag(), &elems);
if(elems>size) size = elems;
++dIter;
}
// *********************************************************************
// * Walk through the list of tagged data items that are stored in the
// * inbound data object. Call the collectAttribute method for each
// * data item. This method will copy the contents of the inbound
// * data object to the correct position in the local data object.
// *********************************************************************
iter.init();
while(iter.tag()!=0)
{
cnt+=(collectAttribute(userData, iter.tag(), size)==0)?1:0;
++iter;
}
// *********************************************************************
// * Return the count of data items that were assimilated into the
// * local data object.
// *********************************************************************
return cnt;
}
// *****************************************************************************
// * rnsQueryCollector::collectAttribute :
// * This method will assimilate a single attribute from the specified
// * userData object into the local cdevData object at the specified
// * position.
// *****************************************************************************
int rnsQueryCollector::collectAttribute ( cdevData & userData, int tag, int position )
{
cdevSystem & sys = cdevSystem::defaultSystem();
int result = 0;
size_t dim = 0;
size_t userDim = 0;
cdevDataTypes type = data->getType(tag);
cdevDataTypes userType = userData.getType(tag);
if(userData.getDim(tag, &dim)==CDEV_NOTFOUND || dim > 0)
{
sys.reportError(CDEV_SEVERITY_ERROR, "Name Server", NULL,
"Cannot add array data to query reply");
result = -1;
}
else if(data->getDim(tag, &dim)!=CDEV_NOTFOUND && dim > 1)
{
sys.reportError(CDEV_SEVERITY_ERROR, "Name Server", NULL,
"Cannot assemble a query with multi-dimensional data");
result = -1;
}
else if (userType == CDEV_INVALID)
{
sys.reportError(CDEV_SEVERITY_ERROR, "Name Server", NULL,
"Inbound query data object has invalid data type");
result = -1;
}
else {
if(type!=CDEV_INVALID)
{
if(type<CDEV_TIMESTAMP && userType<CDEV_TIMESTAMP)
{
type = (type>userType)?type:userType;
}
else if(type==CDEV_TIMESTAMP) type = userType;
}
else type = userType;
switch(type)
{
case CDEV_BYTE:
collectByteAttribute(userData, tag, position);
break;
case CDEV_INT16:
collectShortAttribute(userData, tag, position);
break;
case CDEV_UINT16:
collectUShortAttribute(userData, tag, position);
break;
case CDEV_INT32:
collectLongAttribute(userData, tag, position);
break;
case CDEV_UINT32:
collectULongAttribute(userData, tag, position);
break;
case CDEV_FLOAT:
collectFloatAttribute(userData, tag, position);
break;
case CDEV_DOUBLE:
collectDoubleAttribute(userData, tag, position);
break;
case CDEV_STRING:
collectStringAttribute(userData, tag, position);
break;
case CDEV_TIMESTAMP:
collectTimestampAttribute(userData, tag, position);
break;
default:
result = -1;
break;
}
}
return result;
}
// *****************************************************************************
// * rnsQueryCollector::collectByteAttribute :
// * This method will transfer the byte attribute stored in the userData
// * object into the local cdevData object at the specified position.
// *****************************************************************************
void rnsQueryCollector::collectByteAttribute (cdevData & userData, int tag, int position )
{
if((position+1)>byteCnt)
{
if(byteData!=NULL) delete byteData;
byteCnt = ((position+1)>100)?(position+100):100;
byteData = new unsigned char [byteCnt];
}
memset(byteData, 0, byteCnt*sizeof(unsigned char));
data->get(tag, byteData);
userData.get(tag, &byteData[position]);
data->insert(tag, byteData, position+1);
}
// *****************************************************************************
// * rnsQueryCollector::collectShortAttribute :
// * This method will transfer the short attribute stored in the userData
// * object into the local cdevData object at the specified position.
// *****************************************************************************
void rnsQueryCollector::collectShortAttribute (cdevData & userData, int tag, int position )
{
if((position+1)>shortCnt)
{
if(shortData!=NULL) delete shortData;
shortCnt = ((position+1)>100)?(position+100):100;
shortData = new short [shortCnt];
}
memset(shortData, 0, shortCnt*sizeof(short));
data->get(tag, shortData);
userData.get(tag, &shortData[position]);
data->insert(tag, shortData, position+1);
}
// *****************************************************************************
// * rnsQueryCollector::collectUShortAttribute :
// * This method will transfer the unsigned short attribute stored in the
// * userData object into the local cdevData object at the specified
// * position.
// *****************************************************************************
void rnsQueryCollector::collectUShortAttribute (cdevData & userData, int tag, int position )
{
if((position+1)>ushortCnt)
{
if(ushortData!=NULL) delete ushortData;
ushortCnt = ((position+1)>100)?(position+100):100;
ushortData = new unsigned short [ushortCnt];
}
memset(ushortData, 0, ushortCnt*sizeof(unsigned short));
data->get(tag, ushortData);
userData.get(tag, &ushortData[position]);
data->insert(tag, ushortData, position+1);
}
// *****************************************************************************
// * rnsQueryCollector::collectLongAttribute :
// * This method will transfer the long attribute stored in the
// * userData object into the local cdevData object at the specified
// * position.
// *****************************************************************************
void rnsQueryCollector::collectLongAttribute (cdevData & userData, int tag, int position )
{
if((position+1)>longCnt)
{
if(longData!=NULL) delete longData;
longCnt = ((position+1)>100)?(position+100):100;
longData = new long [longCnt];
}
memset(longData, 0, longCnt*sizeof(long));
data->get(tag, longData);
userData.get(tag, &longData[position]);
data->insert(tag, longData, position+1);
}
// *****************************************************************************
// * rnsQueryCollector::collectULongAttribute :
// * This method will transfer the unsigned long attribute stored in the
// * userData object into the local cdevData object at the specified
// * position.
// *****************************************************************************
void rnsQueryCollector::collectULongAttribute (cdevData & userData, int tag, int position )
{
if((position+1)>ulongCnt)
{
if(ulongData!=NULL) delete ulongData;
ulongCnt = ((position+1)>100)?(position+100):100;
ulongData = new unsigned long [ulongCnt];
}
memset(ulongData, 0, ulongCnt*sizeof(unsigned long));
data->get(tag, ulongData);
userData.get(tag, &ulongData[position]);
data->insert(tag, ulongData, position+1);
}
// *****************************************************************************
// * rnsQueryCollector::collectFloatAttribute :
// * This method will transfer the float attribute stored in the
// * userData object into the local cdevData object at the specified
// * position.
// *****************************************************************************
void rnsQueryCollector::collectFloatAttribute (cdevData & userData, int tag, int position )
{
if((position+1)>floatCnt)
{
if(floatData!=NULL) delete floatData;
floatCnt = ((position+1)>100)?(position+100):100;
floatData = new float [floatCnt];
}
memset(floatData, 0, floatCnt*sizeof(float));
data->get(tag, floatData);
userData.get(tag, &floatData[position]);
data->insert(tag, floatData, position+1);
}
// *****************************************************************************
// * rnsQueryCollector::collectDoubleAttribute :
// * This method will transfer the double attribute stored in the
// * userData object into the local cdevData object at the specified
// * position.
// *****************************************************************************
void rnsQueryCollector::collectDoubleAttribute (cdevData & userData, int tag, int position )
{
if((position+1)>doubleCnt)
{
if(doubleData!=NULL) delete doubleData;
doubleCnt = ((position+1)>100)?(position+100):100;
doubleData = new double [doubleCnt];
}
memset(doubleData, 0, doubleCnt*sizeof(double));
data->get(tag, doubleData);
userData.get(tag, &doubleData[position]);
data->insert(tag, doubleData, position+1);
}
// *****************************************************************************
// * rnsQueryCollector::collectStringAttribute :
// * This method will transfer the string attribute stored in the
// * userData object into the local cdevData object at the specified
// * position.
// *****************************************************************************
void rnsQueryCollector::collectStringAttribute (cdevData & userData, int tag, int position )
{
int i;
char blank = 0;
char ** stringData = new char * [ position+1 ];
memset(stringData, 0, (position+1)*sizeof(char *));
data->get(tag, stringData);
userData.get(tag, &stringData[position]);
for(i=0; i<position+1; i++)
{
if(stringData[i] == NULL) stringData[i] = &blank;
}
data->insert(tag, stringData, position+1);
for(i=0; i<position+1; i++)
{
if(stringData[i]!=&blank) delete stringData[i];
}
delete stringData;
}
// *****************************************************************************
// * rnsQueryCollector::collectTimestampAttribute :
// * This method will transfer the time stamp attribute stored in the
// * userData object into the local cdevData object at the specified
// * position.
// *****************************************************************************
void rnsQueryCollector::collectTimestampAttribute (cdevData & userData, int tag, int position )
{
if((position+1)>tsCnt)
{
if(tsData!=NULL) delete tsData;
tsCnt = ((position+1)>100)?(position+100):100;
tsData = new cdev_TS_STAMP [tsCnt];
}
memset(tsData, 0, tsCnt);
data->get(tag, tsData);
userData.get(tag, &tsData[position]);
data->insert(tag, tsData, position+1);
}
@@ -0,0 +1,752 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
// Implementation of rnsRequesObject Class
//
// Author: Jie Chen
//
// Revision History:
// rnsRequestObject.cc,v
// Revision 1.7 1998/04/01 15:32:12 chen
// fix transaction done flag
//
// Revision 1.6 1998/03/19 18:31:43 chen
// add monitorEntry capability
//
// Revision 1.5 1998/02/09 13:35:47 chen
// duplicate cdev data in the monitor object
//
// Revision 1.4 1998/02/06 15:11:25 chen
// add connection management for name server
//
// Revision 1.3 1998/02/05 15:59:19 akers
// Ongoing development
//
// Revision 1.2 1998/01/30 18:31:37 akers
// Ongoing development
//
// Revision 1.1 1998/01/22 17:07:51 akers
// Addition of new NameServer
//
//
//
#include <cdevErrCode.h>
#include <cdevCommon.h>
#include <rnsMonitorObj.h>
#include <cdevClock.h>
#include "rnsService.h"
#include "rnsRequestObject.h"
#include "rnsQueryCollector.h"
#include <rsvcClient.h>
char* rnsRequestObject::stags_[] = {"name", "domain"};
int rnsRequestObject::numstags_ = 2;
#ifdef _WIN32
inline int strcasecmp ( const char * string1, const char * string2 )
{
return stricmp(string1, string2);
}
#endif
// *****************************************************************************
// * The localQuerySynchronizer class has been added to allow me to make
// * synchronous requests to query the NameServer.
// *****************************************************************************
class localQuerySynchronizer
{
public:
static int cbDone;
static long cbIdent;
static cdevData cbData;
static cdevCallback getCallbackObj ( void )
{
cbData.remove();
cbDone = 0;
cbIdent++;
cdevCallback cbObj(callback, (void *)cbIdent);
return cbObj;
}
static void callback ( int /*status*/, void * userarg, cdevRequestObject &/*reqObj*/, cdevData &data)
{
if(((long)userarg)==cbIdent)
{
cbDone = 1;
cbData = data;
}
}
};
int localQuerySynchronizer::cbDone = 0;
long localQuerySynchronizer::cbIdent = 0;
cdevData localQuerySynchronizer::cbData;
rnsRequestObject::rnsRequestObject (char* device, char* msg,
rnsService* svc,
cdevSystem& system)
:cdevRequestObject (device, msg, system), client_ (0)
{
#ifdef _TRACE_OBJECTS
printf (" Create rnsRequestObject Class Object\n");
#endif
client_ = &(svc->client_);
// convert msg to integer action
rnsRequestObject::findAction (msg, action_);
}
rnsRequestObject::~rnsRequestObject (void)
{
#ifdef _TRACE_OBJECTS
printf (" Delete rnsRequestObject Class Object\n");
#endif
}
int
rnsRequestObject::getState (void)
{
if (client_->connected ())
return CDEV_STATE_CONNECTED;
return CDEV_STATE_NOTCONNECTED;
}
int
rnsRequestObject::sendCallback (cdevData& out, cdevCallback& cbk)
{
return sendCallback (&out, cbk);
}
int
rnsRequestObject::sendCallback (cdevData* out, cdevCallback& userCallback)
{
if (deferExecution (out, &userCallback))
return CDEV_SUCCESS;
int status = CDEV_SUCCESS;
cdevTranObj* xobj = 0;
rnsMonitorObj* mobj = 0;
rnsService* nservice = (rnsService *)service_;
// copy userCallback into the following callback, which will free
// the user from worrying about cdevCallback object
// note: cdevCallback's new operator is an overloaded operator
cdevCallback* callback = 0;
if (client_->connected ()) {
switch (action_) {
case rnsRequestObject::GET:
{
if (out == 0)
return CDEV_INVALIDARG;
callback = new cdevCallback (userCallback);
xobj = new cdevTranObj (&system_, this, 0, callback);
rsvcData outdata;
if (rnsRequestObject::dataCdevToRsvc (*out, outdata) != CDEV_SUCCESS)
status = CDEV_INVALIDARG;
else {
if (client_->getValue (_RSVC_CDEV_SERVERS, outdata,
&(rnsRequestObject::getCallback),
(void *)xobj) != CDEV_SUCCESS)
status = CDEV_IOFAILED;
}
if (status != CDEV_SUCCESS)
delete xobj;
}
break;
case rnsRequestObject::QUERY:
{
if (out == 0)
return CDEV_INVALIDARG;
callback = (cdevCallback *)new rnsQueryCallback(userCallback);
xobj = new cdevTranObj (&system_, this, 0, callback);
mobj = new rnsMonitorObj (*xobj);
char qmsg[1024];
if (out->get ("queryMsg", qmsg, sizeof (qmsg)) != CDEV_SUCCESS)
status = CDEV_INVALIDARG;
else {
mobj->out_ = new cdevData (*out);
if (client_->query (_RSVC_CDEV_SERVERS, qmsg,
&(rnsRequestObject::queryCallback),
(void *)mobj) != CDEV_SUCCESS)
status = CDEV_IOFAILED;
else
nservice->addMonitorObject (mobj);
}
if (status != CDEV_SUCCESS) {
delete xobj;
delete mobj;
}
}
break;
case rnsRequestObject::MONITORON:
{
if (out == 0)
return CDEV_INVALIDARG;
if (nservice->hasCallback (userCallback))
return CDEV_INVALIDARG;
callback = new cdevCallback (userCallback);
xobj = new cdevTranObj (&system_, this, 0, callback);
mobj = new rnsMonitorObj (*xobj);
rsvcData outdata;
if (rnsRequestObject::dataCdevToRsvc (*out, outdata) != CDEV_SUCCESS)
status = CDEV_INVALIDARG;
else {
mobj->out_ = new cdevData (*out);
if (client_->monitorValue (_RSVC_CDEV_SERVERS, outdata,
&(rnsRequestObject::monitorCallback),
(void *)mobj) != CDEV_SUCCESS)
status = CDEV_IOFAILED;
else
nservice->addMonitorObject (mobj);
}
if (status != CDEV_SUCCESS) {
delete xobj;
delete mobj;
}
}
break;
case rnsRequestObject::MONITOROFF:
{
if (out == 0)
return CDEV_INVALIDARG;
rnsMonitorObj* mobj = 0;
rsvcData outdata;
if (rnsRequestObject::dataCdevToRsvc (*out, outdata) != CDEV_SUCCESS)
status = CDEV_INVALIDARG;
else {
if ((mobj = nservice->hasCallback (userCallback)) == 0) {
printf ("this callback function is not registered\n");
status = CDEV_INVALIDARG;
}
else
status = monitorOff (outdata, mobj);
}
}
break;
case rnsRequestObject::MONITORENTRY:
{
if (nservice->hasCallback (userCallback))
return CDEV_INVALIDARG;
callback = new cdevCallback (userCallback);
xobj = new cdevTranObj (&system_, this, 0, callback);
mobj = new rnsMonitorObj (*xobj);
rsvcData empty;
if (client_->monitorIncomingEntries (_RSVC_CDEV_SERVERS, empty,
&(rnsRequestObject::entryCallback),
(void *)mobj) != CDEV_SUCCESS)
status = CDEV_IOFAILED;
else
nservice->addMonitorObject (mobj);
if (status != CDEV_SUCCESS) {
delete xobj;
delete mobj;
}
}
break;
case rnsRequestObject::MONITORENTRYOFF:
{
rnsMonitorObj* mobj = 0;
if ((mobj = nservice->hasCallback (userCallback)) == 0) {
#ifdef _CDEV_DEBUG
printf ("this callback function is not registered\n");
#endif
status = CDEV_INVALIDARG;
}
else
status = monitorEntryOff (mobj);
}
break;
default:
status = CDEV_INVALIDARG;
break;
}
}
else
status = CDEV_NOTCONNECTED;
return status;
}
int
rnsRequestObject::sendMonitor (rnsMonitorObj* mobj)
{
rsvcData outdata;
int status = CDEV_SUCCESS;
if (rnsRequestObject::dataCdevToRsvc (*mobj->out_, outdata)!= CDEV_SUCCESS) {
mobj->started_ = 1;
status = CDEV_INVALIDARG;
}
else {
if ((status = client_->monitorValue (_RSVC_CDEV_SERVERS, outdata,
&(rnsRequestObject::monitorCallback),
(void *)mobj)) != CDEV_SUCCESS)
mobj->started_ = 1;
}
return status;
}
int
rnsRequestObject::sendEntryMonitor (rnsMonitorObj* mobj)
{
int status = CDEV_SUCCESS;
rsvcData empty;
if ((status = client_->monitorIncomingEntries (_RSVC_CDEV_SERVERS, empty,
&(rnsRequestObject::entryCallback),
(void *)mobj)) != CDEV_SUCCESS)
mobj->started_ = 1;
return status;
}
void
rnsRequestObject::getCallback (int status, void* arg, rsvcData* data)
{
cdevTranObj* xobj = (cdevTranObj *)arg;
// if a callback has been discarded, do not do anything
if (xobj->isTrash ()) {
delete xobj;
return;
}
cdevCallback* cbk = xobj->userCallback_;
cdevRequestObject* obj = xobj->reqObj_;
cdevData* rda = xobj->resultData_;
cdevData result;
if (rda) // send no block
rda->remove ();
else
rda = &result;
if (status == RSVC_SUCCESS)
rnsRequestObject::dataRsvcToCdev (*data, *rda);
if (cbk)
cbk->fireCallback (status, cbk->userarg (), *obj, result, 0);
delete xobj;
}
void
rnsRequestObject::queryCallback (int status, void* arg, rsvcData* data)
{
rnsMonitorObj* mobj = (rnsMonitorObj *)arg;
cdevCallback* cbk = mobj->userCallback_;
cdevRequestObject* obj = mobj->reqObj_;
cdevData result;
int cbk_finished = 1;
// first time this callback is called
if (mobj->tobj_) {
delete mobj->tobj_;
mobj->tobj_ = 0;
}
if (status == RSVC_ERROR || status == RSVC_NOTFOUND)
cbk->fireCallback (status, cbk->userarg (), *obj, result, 0);
else if (status == RSVC_INCOMPLETE) {
rnsRequestObject::dataRsvcToCdev (*data, result);
cbk->fireCallback (status, cbk->userarg (), *obj, result, 1);
cbk_finished = 0;
}
else if (status == RSVC_QUERYMSG_ERR)
cbk->fireCallback (CDEV_MSG_ERR, cbk->userarg (), *obj, result, 0);
else {
rnsRequestObject::dataRsvcToCdev (*data, result);
cbk->fireCallback (status, cbk->userarg (), *obj, result, 0);
}
if (cbk_finished) {
rnsRequestObject* nsreq = (rnsRequestObject *)obj;
nsreq->removeMonitorObject (mobj);
}
}
void
rnsRequestObject::monitorCallback (int status, void* arg, rsvcData* data)
{
rnsMonitorObj* mobj = (rnsMonitorObj *)arg;
cdevCallback* cbk = mobj->userCallback_;
cdevRequestObject* obj = mobj->reqObj_;
cdevData result;
int cbk_finished = 1;
// first time this callback is called
if (mobj->tobj_) {
delete mobj->tobj_;
mobj->tobj_ = 0;
}
if (status == RSVC_SUCCESS) {
rnsRequestObject::dataRsvcToCdev (*data, result);
cbk->fireCallback (status, cbk->userarg (), *obj, result, 1);
cbk_finished = 0;
if (!mobj->started_)
mobj->started_ = 1;
}
else if (status == RSVC_CBK_FINISHED) {
rnsRequestObject::dataRsvcToCdev (*data, result);
if (mobj->started_)
cbk->fireCallback (status, cbk->userarg (), *obj, result, 0);
}
else {
if (mobj->started_)
cbk->fireCallback (status, cbk->userarg (), *obj, result, 0);
}
if (cbk_finished && mobj->started_) {
rnsRequestObject* nsreq = (rnsRequestObject *)obj;
nsreq->removeMonitorObject (mobj);
}
}
void
rnsRequestObject::entryCallback (int status, void* arg, rsvcData* data)
{
rnsMonitorObj* mobj = (rnsMonitorObj *)arg;
cdevCallback* cbk = mobj->userCallback_;
cdevRequestObject* obj = mobj->reqObj_;
cdevData result;
int cbk_finished = 1;
// first time this callback is called
if (mobj->tobj_) {
delete mobj->tobj_;
mobj->tobj_ = 0;
}
if (status == RSVC_SUCCESS || status == RSVC_INCOMPLETE) {
rnsRequestObject::dataRsvcToCdev (*data, result);
cbk->fireCallback (RSVC_SUCCESS, cbk->userarg (), *obj, result, 1);
cbk_finished = 0;
if (!mobj->started_)
mobj->started_ = 1;
}
else if (status == RSVC_CBK_FINISHED) {
rnsRequestObject::dataRsvcToCdev (*data, result);
if (mobj->started_)
cbk->fireCallback (status, cbk->userarg (), *obj, result, 0);
}
else {
if (mobj->started_)
cbk->fireCallback (status, cbk->userarg (), *obj, result, 1);
}
if (cbk_finished && mobj->started_) {
rnsRequestObject* nsreq = (rnsRequestObject *)obj;
nsreq->removeMonitorObject (mobj);
}
}
int
rnsRequestObject::monitorOff (rsvcData& data, rnsMonitorObj* mobj)
{
int status;
status = client_->monitorOffValue (_RSVC_CDEV_SERVERS, data,
&(rnsRequestObject::monitorCallback),
(void *)mobj);
return status;
}
int
rnsRequestObject::monitorEntryOff (rnsMonitorObj* mobj)
{
int status;
rsvcData empty;
status = client_->monitorOffIncomingEntries (_RSVC_CDEV_SERVERS, empty,
&(rnsRequestObject::entryCallback),
(void *)mobj);
return status;
}
int
rnsRequestObject::sendNoBlock (cdevData& out, cdevData& result)
{
return sendNoBlock (&out, &result);
}
int
rnsRequestObject::sendNoBlock (cdevData* out, cdevData& result)
{
return sendNoBlock (out, &result);
}
int
rnsRequestObject::sendNoBlock (cdevData& out, cdevData* result)
{
return sendNoBlock (&out, result);
}
int
rnsRequestObject::sendNoBlock (cdevData* out, cdevData* result)
{
if (deferExecution (out, result))
return CDEV_SUCCESS;
int status = CDEV_SUCCESS;
cdevTranObj* xobj = 0;
rnsService* nservice = (rnsService *)service_;
if (client_->connected ()) {
switch (action_) {
case rnsRequestObject::GET:
{
if (out == 0 || result == 0)
return CDEV_INVALIDARG;
xobj = new cdevTranObj (&system_, this, result, 0);
rsvcData outdata;
if (rnsRequestObject::dataCdevToRsvc (*out, outdata) != CDEV_SUCCESS)
status = CDEV_INVALIDARG;
else {
if (client_->getValue (_RSVC_CDEV_SERVERS, outdata,
&(rnsRequestObject::getCallback),
(void *)xobj) != CDEV_SUCCESS)
status = CDEV_IOFAILED;
}
if (status != CDEV_SUCCESS)
delete xobj;
}
break;
default:
status = CDEV_INVALIDARG;
break;
}
}
else
status = CDEV_NOTCONNECTED;
return status;
}
int
rnsRequestObject::send (cdevData& out, cdevData& result)
{
return send (&out, &result);
}
int
rnsRequestObject::send (cdevData* out, cdevData& result)
{
return send (out, &result);
}
int
rnsRequestObject::send (cdevData& out, cdevData* result)
{
return send (&out, result);
}
int
rnsRequestObject::send (cdevData* out, cdevData* result)
{
int status = CDEV_SUCCESS;
rnsService* nservice = (rnsService *)service_;
if (client_->connected ()) {
switch (action_) {
case rnsRequestObject::GET:
if (out == 0 || result == 0)
status = CDEV_INVALIDARG;
else {
cdevGroup grp (2, system_);
grp.start ();
sendNoBlock (out, result);
grp.end ();
grp.pend (4.0);
if (!grp.allFinished ())
status = CDEV_TIMEOUT;
}
break;
case rnsRequestObject::QUERY:
if(out==0 || result==0)
status = CDEV_INVALIDARG;
else {
cdevCallback cb = localQuerySynchronizer::getCallbackObj();
if((status=sendCallback(out, cb))==CDEV_SUCCESS)
{
cdevTimeValue t(5.0);
cdevClock timer;
timer.schedule(NULL, t);
while(!localQuerySynchronizer::cbDone && !timer.expired()) nservice->poll();
if(!localQuerySynchronizer::cbDone) status = CDEV_TIMEOUT;
else *result = localQuerySynchronizer::cbData;
}
}
break;
default:
status = CDEV_INVALIDARG;
break;
}
}
else
status = CDEV_NOTCONNECTED;
return status;
}
int
rnsRequestObject::dataCdevToRsvc (cdevData& data, rsvcData& res)
{
char val[1024];
for (int i = 0; i < rnsRequestObject::numstags_; i++) {
if (data.get (rnsRequestObject::stags_[i], val, sizeof (val))
!= CDEV_SUCCESS)
return CDEV_ERROR;
res.insert (rnsRequestObject::stags_[i], val);
}
return CDEV_SUCCESS;
}
int
rnsRequestObject::dataRsvcToCdev (rsvcData& data, cdevData& res)
{
rsvcDataIterator ite (&data);
int type;
int tag;
size_t numelems;
size_t dim;
char* ctag;
for (ite.init (); !ite ; ++ite) {
ctag = (char *)ite.tag ();
type = data.getType (ctag);
data.getElems (ctag, &numelems);
data.getDim (ctag, &dim);
if (cdevData::tagC2I (ctag, &tag) != CDEV_SUCCESS || dim > 1)
continue;
switch (type) {
case RSVC_BYTE:
case RSVC_INT16:
case RSVC_UINT16:
case RSVC_INT32:
case RSVC_UINT32:
{
if (dim == 0) {
int val;
data.get (ctag, &val);
res.insert (tag, val);
}
else {
int* val = new int[numelems];
data.get (ctag, val);
res.insert (tag, val, numelems);
delete []val;
}
}
break;
case RSVC_FLOAT:
{
if (dim == 0) {
float val;
data.get (ctag, &val);
res.insert (tag, val);
}
else {
float* val = new float[numelems];
data.get (ctag, val);
res.insert (tag, val, numelems);
delete []val;
}
}
break;
case RSVC_DOUBLE:
{
if (dim == 0) {
double val;
data.get (ctag, &val);
res.insert (tag, val);
}
else {
double* val = new double[numelems];
data.get (ctag, val);
res.insert (tag, val, numelems);
delete []val;
}
}
break;
case RSVC_STRING:
{
if (dim == 0) {
char val[1024];
data.get (ctag, val, sizeof (val));
res.insert (tag, val);
}
else {
char** val = new char*[numelems];
data.get (ctag, val);
res.insert (tag, val, numelems);
}
}
break;
default:
break;
}
}
return CDEV_SUCCESS;
}
int
rnsRequestObject::removeMonitorObject (rnsMonitorObj* mobj)
{
rnsService *nservice = (rnsService *)service_;
nservice->removeMonitorObject (mobj);
delete mobj;
return CDEV_SUCCESS;
}
int
rnsRequestObject::findAction (char* msg, int& action)
{
if (strcasecmp (msg, "query") == 0)
action = rnsRequestObject::QUERY;
else if (strcasecmp (msg, "get") == 0)
action = rnsRequestObject::GET;
else if (strcasecmp (msg, "monitorOn") == 0)
action = rnsRequestObject::MONITORON;
else if (strcasecmp (msg, "monitorOff") == 0)
action = rnsRequestObject::MONITOROFF;
else if (strcasecmp (msg, "monitorEntry") == 0)
action = rnsRequestObject::MONITORENTRY;
else if (strcasecmp (msg, "monitorEntryOff") == 0)
action = rnsRequestObject::MONITORENTRYOFF;
else
action = rnsRequestObject::UNKNOWN;
return CDEV_SUCCESS;
}
@@ -0,0 +1,130 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
// CDEV Resource Name Service Request Object
//
// Author: Jie Chen
//
//
//
#ifndef _RNS_REQUEST_OBJECT_H
#define _RNS_REQUEST_OBJECT_H
#include <cdevSystem.h>
#include <cdevRequestObject.h>
class rsvcClient;
class rnsService;
class rnsMonitorObj;
class rnsRequestObject: public cdevRequestObject
{
public:
// constructor and destructor
rnsRequestObject (char* device,
char* msg,
rnsService* svc,
cdevSystem& system = cdevSystem::defaultSystem());
~rnsRequestObject (void);
int send (cdevData& out, cdevData& result);
int send (cdevData *out, cdevData& result);
int send (cdevData& out, cdevData* result);
int send (cdevData *out, cdevData* result);
// PURPOSE: Synchronous IO operations
// REQUIRE: When do query and get, result must be provided
// PROMISE: return CDEV_SUCCESS: success.
int sendNoBlock (cdevData& out, cdevData& result);
int sendNoBlock (cdevData* out, cdevData& result);
int sendNoBlock (cdevData& out, cdevData* result);
int sendNoBlock (cdevData* out, cdevData* result);
// PURPOSE: Asynchronous IO operations used in conjunction with
// cdevGroup or system
// REQUIRE:
// PROMISE: return CDEV_SUCCESS: requests have been sent out.
int sendCallback (cdevData& out, cdevCallback& callback);
int sendCallback (cdevData* out, cdevCallback& callback);
// PURPOSE: Asynchromous IO operations with a user supplied callback function
// REQUIRE:
// PROMISE: User callback function will be called with status information
// status = CDEV_DISCONNECTED: channel discconected
// status = CDEV_SUCCESS : everything is OK
// status = CDEV_ERROR : something fishy.
// status = CDEV_INCOMPLETE : data flow will coming (88)
// status = CDEV_CBK_FINISHED: query callback finished (89)
// status = CDEV_QUERYMSG_ERR: query message syntax erro (91)
int getState (void);
// PURPOSE: get connection state
// REQUIRE: none
// PROMISE: CDEV_CONNECTED or CDEV_NOTCONNECTED
const char *className (void) const {return "rnsRequestObject";}
protected:
// find out action from message
static int findAction (char* msg, int& action);
// action value
typedef enum {GET = 0x2000,QUERY,MONITORON,MONITOROFF,
MONITORENTRY, MONITORENTRYOFF, UNKNOWN} RNSENUMVERB;
// get value callback
static void getCallback (int status, void* arg, rsvcData* data);
// query value callback
static void queryCallback (int status, void* arg, rsvcData* data);
// monitor value callback
static void monitorCallback (int status, void* arg, rsvcData* data);
// monitor entry callback
static void entryCallback (int status, void* arg, rsvcData* data);
// data conversion from rsvc to cdev
static int dataRsvcToCdev (rsvcData& data, cdevData& result);
// data conversion from cdev to rsvc
static int dataCdevToRsvc (cdevData& data, rsvcData& result);
// remove a monitor object
int removeMonitorObject (rnsMonitorObj* mobj);
// monitor off a callback
int monitorOff (rsvcData& data, rnsMonitorObj* obj);
// monitor off entry callback
int monitorEntryOff (rnsMonitorObj* obj);
// resend a monitor callback
int sendMonitor (rnsMonitorObj* mobj);
// resend a monitor entry callback
int sendEntryMonitor (rnsMonitorObj* mobj);
private:
// two tags are needed for all serachs
static char* stags_[];
static int numstags_;
// action type
int action_;
// pointer of underlying client connection
rsvcClient* client_;
// friend class
friend class rnsService;
};
#endif
+383
View File
@@ -0,0 +1,383 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
// Implementation of nsService Class
//
// Author: Jie Chen
//
// Revision History:
// rnsService.cc,v
// Revision 1.8 1998/03/19 18:31:43 chen
// add monitorEntry capability
//
// Revision 1.7 1998/02/23 16:29:35 chen
// change back to use alarm to handle reconnecton to the name server
//
// Revision 1.6 1998/02/19 18:39:52 akers
// Bug Fixes
//
// Revision 1.5 1998/02/18 14:42:52 chen
// add registerFd to the service
//
// Revision 1.4 1998/02/10 18:06:44 chen
// use system timer instead of alarm
//
// Revision 1.3 1998/02/06 15:11:26 chen
// add connection management for name server
//
// Revision 1.2 1998/01/30 18:31:37 akers
// Ongoing development
//
// Revision 1.1 1998/01/22 17:07:52 akers
// Addition of new NameServer
//
//
//
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#ifndef _WIN32
#include <unistd.h>
#endif
#include "rnsService.h"
#include "rnsRequestObject.h"
#include <rnsMonitorObj.h>
#define _RNS_CLIENT_RECONN_TIMEOUT 5
char * rnsService::tags_[] = {
"table",
"key",
"keyExp",
"keyType",
"name",
"domain",
"host",
"owner",
"time",
"port",
"pid",
"ping",
"client",
"queryMsg"
};
int rnsService::numtags_ = 14;
static rnsService* _rnsNameService_ = 0;
#ifdef _WIN32
void CALLBACK _rnsAlarmHandler_ ( HWND hwnd, UINT umsg, UINT idEvent, DWORD dwTime )
{
if (_rnsNameService_->reconnect () == CDEV_SUCCESS)
{
if (_rnsNameService_->monitorsRestarted ())
{
KillTimer(NULL, idEvent);
}
}
}
#else
static struct sigaction _oldaction_;
static void _rnsAlarmHandler_ (int /* signo */)
{
int done = 0;
if (_rnsNameService_->reconnect () == CDEV_SUCCESS) {
if (_rnsNameService_->monitorsRestarted ()) {
sigaction (SIGALRM, &_oldaction_, 0);
done = 1;
}
}
if (!done)
alarm (_RNS_CLIENT_RECONN_TIMEOUT);
}
#endif
rnsService::rnsService (char* name, cdevSystem& system)
:cdevService (name, system), client_ (), fds_ (0), numFds_ (0),
monobjs_ ()
{
#ifdef _TRACE_OBJECTS
printf (" Create rnsService Class Object\n");
#endif
// register all tags
for (int i = 0; i < rnsService::numtags_; i++)
cdevData::addTag (rnsService::tags_[i]);
// remember this service
_rnsNameService_ = this;
}
rnsService::~rnsService (void)
{
#ifdef _TRACE_OBJECTS
printf (" Delete rnsService Class Object\n");
#endif
if (client_.connected ())
client_.disconnect ();
if (numFds_ > 0)
delete []fds_;
// delete all callbacks
cdevSlistIterator ite (monobjs_);
rnsMonitorObj* mobj = 0;
for (ite.init (); !ite; ++ite) {
mobj = (rnsMonitorObj *) ite ();
delete mobj;
}
}
int
rnsService::getFd (int* &fd, int& numFd)
{
fd = fds_;
numFd = numFds_;
return CDEV_SUCCESS;
}
int
rnsService::flush (void)
{
return CDEV_SUCCESS;
}
int
rnsService::poll (void)
{
return client_.pendIO (0.001);
}
int
rnsService::pend (int /* fd */)
{
return client_.pendIO ();
}
int
rnsService::pend (double seconds, int)
{
return client_.pendIO (seconds);
}
int
rnsService::getRequestObject (char* deviceName, char* msg,
cdevRequestObject* &req)
{
if (!client_.connected ()) {
char* nsHost = getenv ("CDEV_NAME_SERVER");
if (!nsHost) {
reportError (CDEV_SEVERITY_SEVERE, serviceName_, 0,
"Cannot find environment variable CDEV_NAME_SERVER !!!");
req = 0;
return CDEV_ERROR;
}
if (client_.connect (nsHost, RSVC_SERVER_PORT, 3.0) != RSVC_SUCCESS) {
reportError (CDEV_SEVERITY_SEVERE, serviceName_, 0,
"Cannot connect to name server at port %d on %s",
RSVC_SERVER_PORT, nsHost);
req = 0;
return CDEV_ERROR;
}
if (numFds_ > 0)
delete []fds_;
fds_ = new int[1];
numFds_ = 1;
fds_[0] = client_.getFd ();
// register fd to the system
registerFd (client_.getFd (), 1);
// register a disconnection callback
if (client_.disconnectCallback (&(rnsService::discCallback),
(void *)this) != RSVC_SUCCESS)
reportError (CDEV_SEVERITY_WARN, serviceName_, 0,
"Cannot register disconnect callback");
}
req = new rnsRequestObject (deviceName, msg, this, system_);
return CDEV_SUCCESS;
}
int
rnsService::reconnect (void)
{
char* nsHost = getenv ("CDEV_NAME_SERVER");
if (!client_.connected ()) {
if (client_.connect (nsHost, RSVC_SERVER_PORT, 3.0) == RSVC_SUCCESS) {
reportError (CDEV_SEVERITY_INFO, serviceName_, 0,
"Reconnected to name server at port %d on %s",
RSVC_SERVER_PORT, nsHost);
fds_ = new int[1];
numFds_ = 1;
fds_[0] = client_.getFd ();
// register this fd to the sysem
registerFd (client_.getFd(), 1);
// register a disconnection callback
if (client_.disconnectCallback (&(rnsService::discCallback),
(void *)this) != RSVC_SUCCESS)
reportError (CDEV_SEVERITY_WARN, serviceName_, 0,
"Cannot register disconnect callback");
return CDEV_SUCCESS;
}
else
return CDEV_TIMEOUT;
}
return CDEV_SUCCESS;
}
int
rnsService::getNameServer (cdevDevice* &ns)
{
ns = 0;
return CDEV_SUCCESS;
}
cdevService *
newRnsService (char* name, cdevSystem* system)
{
return new rnsService (name, *system);
}
int
rnsService::addMonitorObject (rnsMonitorObj* obj)
{
cdevSlistIterator ite (monobjs_);
rnsMonitorObj* mobj = 0;
for (ite.init (); !ite; ++ite) {
mobj = (rnsMonitorObj *) ite ();
if (*(mobj->userCallback_) == *(obj->userCallback_))
return CDEV_ERROR;
}
monobjs_.add ((void *)obj);
return CDEV_SUCCESS;
}
int
rnsService::removeMonitorObject (rnsMonitorObj* obj)
{
cdevSlistIterator ite (monobjs_);
rnsMonitorObj* mobj = 0;
int found = 0;
for (ite.init (); !ite; ++ite) {
mobj = (rnsMonitorObj *) ite ();
if (mobj == obj) {
found = 1;
break;
}
}
if (found) {
monobjs_.remove ((void *)obj);
return CDEV_SUCCESS;
}
return CDEV_ERROR;
}
rnsMonitorObj*
rnsService::hasCallback (cdevCallback& cbk)
{
cdevSlistIterator ite (monobjs_);
rnsMonitorObj* mobj = 0;
for (ite.init (); !ite; ++ite) {
mobj = (rnsMonitorObj *) ite ();
if (*(mobj->userCallback_) == cbk)
return mobj;
}
return 0;
}
int
rnsService::monitorsRestarted (void)
{
cdevSlistIterator ite (monobjs_);
rnsMonitorObj* mobj = 0;
rnsRequestObject* req = 0;
int notdone = 0;
for (ite.init (); !ite; ++ite) {
mobj = (rnsMonitorObj *)ite ();
if (!mobj->started_) {
notdone = 1;
req = (rnsRequestObject *)mobj->reqObj_;
if (req->action_ == rnsRequestObject::MONITORON)
req->sendMonitor (mobj);
else if (req->action_ == rnsRequestObject::MONITORENTRY)
req->sendEntryMonitor (mobj);
}
}
return !notdone;
}
void
rnsService::discCallback (int /* status */, void* arg, rsvcData* /* data */)
{
rnsService* nsvc = (rnsService *) arg;
if (nsvc->numFds_ > 0) {
// remove this fd from the system
for (int i = 0; i < nsvc->numFds_; i++)
nsvc->registerFd (nsvc->fds_[i], 0);
delete [](nsvc->fds_);
nsvc->numFds_ = 0;
}
cdevSlistIterator ite (nsvc->monobjs_);
rnsMonitorObj* mobj = 0;
cdevCallback* cbk = 0;
cdevRequestObject *req = 0;
cdevData empty;
for (ite.init (); !ite; ++ite) {
mobj = (rnsMonitorObj *) ite ();
cbk = mobj->userCallback_;
req = mobj->reqObj_;
cbk->fireCallback (CDEV_DISCONNECTED, cbk->userarg (),
*req, empty, 0);
mobj->started_ = 0;
}
#ifdef _WIN32
SetTimer (NULL, 0, 1000*_RNS_CLIENT_RECONN_TIMEOUT, _rnsAlarmHandler_);
#else
// register a alarm handler to try to connect to the name server
struct sigaction act;
act.sa_handler = _rnsAlarmHandler_;
sigemptyset (&act.sa_mask);
act.sa_flags = 0;
if (sigaction (SIGALRM, &act, &_oldaction_) < 0)
cdevSystem::defaultSystem().reportError(
CDEV_SEVERITY_ERROR, "RNS Service", NULL,
"Cannot register alarm signal handler");
else
alarm (_RNS_CLIENT_RECONN_TIMEOUT);
#endif
}
+128
View File
@@ -0,0 +1,128 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
// Implementation of cdev interface to resouce service client
//
// This is only a subset of whole APIs of rsvc client
//
// Author: Jie Chen
//
//
//
#ifndef _NS_SERVICE_H
#define _NS_SERVICE_H
#ifndef _CDEV_MANAGE_SERVERS
#define _CDEV_MANAGE_SERVERS
#endif
#include <stdio.h>
#include <string.h>
#include <cdevService.h>
#include <cdevRequestObject.h>
#include <cdevSlist.h>
#include <rsvcClient.h>
#include <rsvcSpec.h>
extern "C" RSVCAPI cdevService * newRnsService (char* name, cdevSystem* system);
class rnsMonitorObj;
class rnsRequestObject;
class rnsService: public cdevService
{
public:
// cornstructor
rnsService (char* name, cdevSystem& system = cdevSystem::defaultSystem ());
int getFd (int * &fd, int &numFd);
// PURPOSE: return channel access network file descriptors
// REQUIRE: callers provide pointer only and don't free memory
// PROMISE: numFd will be real number of file descriptors of the
// channel access client. return 0: always
int flush (void);
// PURPOSE: flush network requests
// REQUIRE: nothing
// PROMISE: return CDEV_SUCCESS: success
int poll (void);
// PURPOSE: polling method
// REQUIRE: nothing
// PROMISE: return CDEV_SUCCESS: success. Else error
int pend (int fd = -1);
// PURPOSE: handle network pending
// REQUIRE: nothing
// PROMISE: return CDEV_SUCCESS: success, else error
int pend (double seconds, int fd = -1);
// PURPOSE: handle network pending for 'seconds'
// REQUIRE: nothing
// PROMISE: return 0: success. return CDEV_TIMEOUT for timeout
int getRequestObject (char *deviceName, char *msg,
cdevRequestObject * &req);
// PURPOSE: return a rnsRequestObject (called from attachPtr function
// of cdevRequestObject class)
// REQUIRE: right pair of deviceName and msg.
// PROMISE: a rnsRequestObject
int getNameServer (cdevDevice* &rns);
// PURPOSE: retrieve ca name server in case of missing DDL
// REQUIRE: nothing
// PROMISE:
int monitorsRestarted (void);
// PURPOSE: check whether all monitors have been restarted or not
// REQUIRE: nothing
// PROMISE: 1: yes, 0: no
int reconnect (void);
// PURPOSE: reconnect to name server
// REQUIRE: nothing
// PROMISE: CDEV_SUCCESS on sucessful connection
const char* className (void) const {return "rnsService";}
protected:
// deny direct access to destructor
~rnsService (void);
// add a monitor object
int addMonitorObject (rnsMonitorObj* obj);
// remove a monitor object
int removeMonitorObject (rnsMonitorObj* obj);
// check whether this callback is in the list
rnsMonitorObj* hasCallback (cdevCallback& cbk);
// server disconnection callback
static void discCallback (int status, void* arg, rsvcData* data);
private:
rsvcClient client_;
int *fds_;
int numFds_;
// list of monitor object
cdevSlist monobjs_;
// all tags needed for this service
static char* tags_[];
// number of tags needed for this service
static int numtags_;
// friend class
friend class rnsRequestObject;
};
#endif
@@ -0,0 +1,94 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
// Implementation of rsvcCallback Class
//
// Author: Jie Chen
//
// Revision History:
// rsvcCallback.cc,v
// Revision 1.1 1998/01/22 17:08:00 akers
// Addition of new NameServer
//
//
//
#include "rsvcCallback.h"
rsvcCallback::rsvcCallback (void)
:cbk_ (0), arg_ (0)
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcCallback Class Object\n");
#endif
}
rsvcCallback::rsvcCallback (rsvcCbkFunc func, void* arg)
:cbk_ (func), arg_ (arg)
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcCallback Class Object\n");
#endif
}
rsvcCallback::rsvcCallback (const rsvcCallback& cbk)
:cbk_ (cbk.cbk_), arg_ (cbk.arg_)
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcCallback Class Object\n");
#endif
}
rsvcCallback &
rsvcCallback::operator = (const rsvcCallback& cbk)
{
if (this != &cbk) {
cbk_ = cbk.cbk_;
arg_ = cbk.arg_;
}
return *this;
}
rsvcCallback::~rsvcCallback (void)
{
#ifdef _TRACE_OBJECTS
printf ("Delete rsvcCallback Class Object\n");
#endif
}
int
rsvcCallback::operator == (const rsvcCallback& cbk)
{
return (cbk_ == cbk.cbk_ && arg_ == cbk.arg_);
}
int
rsvcCallback::operator != (const rsvcCallback& cbk)
{
return !(cbk_ == cbk.cbk_ && arg_ == cbk.arg_);
}
rsvcCbkFunc
rsvcCallback::cbkFunc (void) const
{
return cbk_;
}
void *
rsvcCallback::userarg (void) const
{
return arg_;
}
int
rsvcCallback::empty (void)
{
return !cbk_;
}
+377
View File
@@ -0,0 +1,377 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
// Implementation of rsvcCbk class
//
// Author: Jie Chen
//
// Revision History:
// rsvcCbk.cc,v
// Revision 1.1 1998/01/22 17:08:01 akers
// Addition of new NameServer
//
//
//
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#ifdef _WIN32
#include <WinSock2.h>
#else
#include <netinet/in.h>
#endif
#include <rsvcConfig.h>
#include "rsvcCbk.h"
rsvcCbk::rsvcCbk (void)
:rsvcStreamable (), rsvcHashable (),
opcode_ (RSVC_OP_UNKNOWN), cbkid_ (0), reqid_ (0),
clientid_ (0), socketid_ (0), status_ (RSVC_SUCCESS), private_ (0)
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcCbk Class Object\n");
#endif
// empty
}
rsvcCbk::rsvcCbk (int opcode, int cbkid, int reqid,
int clientid, int socketid, int status, void* ptr)
:rsvcStreamable (), rsvcHashable (),
opcode_ (opcode), cbkid_ (cbkid), reqid_ (reqid),
clientid_ (clientid), socketid_ (socketid),
status_ (status), private_ (ptr)
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcCbk Class Object\n");
#endif
// empty
}
rsvcCbk::rsvcCbk (const rsvcCbk& cbk)
:rsvcStreamable (), rsvcHashable (),
opcode_ (cbk.opcode_), cbkid_ (cbk.cbkid_), reqid_ (cbk.reqid_),
clientid_ (cbk.clientid_), socketid_ (cbk.socketid_),
status_ (cbk.status_), private_ (cbk.private_)
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcCbk Class Object\n");
#endif
// empty
}
rsvcCbk &
rsvcCbk::operator = (const rsvcCbk& cbk)
{
if (this != &cbk) {
opcode_ = cbk.opcode_;
cbkid_ = cbk.cbkid_;
reqid_ = cbk.reqid_;
clientid_ = cbk.clientid_;
socketid_ = cbk.socketid_;
status_ = cbk.status_;
private_ = cbk.private_;
}
return *this;
}
rsvcCbk::~rsvcCbk (void)
{
#ifdef _TRACE_OBJECTS
printf ("Delete rsvcCbk Class Object\n");
#endif
// empty
}
void
rsvcCbk::cleanup (void)
{
opcode_ = 0;
cbkid_ = 0;
reqid_ = 0;
clientid_ = 0;
socketid_ = 0;
status_ = 0;
private_ = 0;
}
void
rsvcCbk::socketid (int socketid)
{
socketid_ = socketid;
}
int
rsvcCbk::socketid (void) const
{
return socketid_;
}
void
rsvcCbk::cbkstatus (int st)
{
status_ = st;
}
int
rsvcCbk::cbkstatus (void) const
{
return status_;
}
int
rsvcCbk::opcode (void) const
{
return opcode_;
}
void
rsvcCbk::opcode (int op)
{
opcode_ = op;
}
int
rsvcCbk::reqid (void) const
{
return reqid_;
}
void
rsvcCbk::reqid (int req)
{
reqid_ = req;
}
int
rsvcCbk::cbkid (void) const
{
return cbkid_;
}
void
rsvcCbk::cbkid (int id)
{
cbkid_ = id;
}
int
rsvcCbk::clientid (void) const
{
return clientid_;
}
void
rsvcCbk::clientid (int cid)
{
clientid_ = cid;
}
void *
rsvcCbk::userptr (void) const
{
return private_;
}
void
rsvcCbk::userptr (void* ptr)
{
private_ = ptr;
}
size_t
rsvcCbk::streamSize (void)
{
return 6*sizeof (int);
}
int
rsvcCbk::streamOut (char** buf, size_t* len)
{
char* buffer = new char[6*sizeof (int)];
if (buffer == 0) {
fprintf (stderr, "Allocate buffer for rsvcCbk error, quit\n");
exit (1);
}
*len = 6*sizeof (int);
*buf = buffer;
int tmp;
int i = 0;
tmp = htonl (opcode_);
memcpy (&(buffer[i]), &tmp, sizeof (int));
i += sizeof (int);
tmp = htonl (cbkid_);
memcpy (&(buffer[i]), &tmp, sizeof (int));
i += sizeof (int);
tmp = htonl (reqid_);
memcpy (&(buffer[i]), &tmp, sizeof (int));
i += sizeof (int);
tmp = htonl (clientid_);
memcpy (&(buffer[i]), &tmp, sizeof (int));
i += sizeof (int);
tmp = htonl (socketid_);
memcpy (&(buffer[i]), &tmp, sizeof (int));
i += sizeof (int);
tmp = htonl (status_);
memcpy (&(buffer[i]), &tmp, sizeof (int));
i += sizeof (int);
return RSVC_SUCCESS;
}
int
rsvcCbk::streamOut (char* buffer, size_t len)
{
if (buffer == 0) {
fprintf (stderr, "Allocate buffer for rsvcCbk error, quit\n");
exit (1);
}
if (len < 6*sizeof (int)) {
fprintf (stderr, "Streaming out rsvcCbk has not enough buffer size\n");
return RSVC_OVERFLOW;
}
int tmp;
int i = 0;
tmp = htonl (opcode_);
memcpy (&(buffer[i]), &tmp, sizeof (int));
i += sizeof (int);
tmp = htonl (cbkid_);
memcpy (&(buffer[i]), &tmp, sizeof (int));
i += sizeof (int);
tmp = htonl (reqid_);
memcpy (&(buffer[i]), &tmp, sizeof (int));
i += sizeof (int);
tmp = htonl (clientid_);
memcpy (&(buffer[i]), &tmp, sizeof (int));
i += sizeof (int);
tmp = htonl (socketid_);
memcpy (&(buffer[i]), &tmp, sizeof (int));
i += sizeof (int);
tmp = htonl (status_);
memcpy (&(buffer[i]), &tmp, sizeof (int));
i += sizeof (int);
return RSVC_SUCCESS;
}
int
rsvcCbk::streamIn (char* buffer, size_t len)
{
if (buffer == 0) {
fprintf (stderr, "Stream in buffer == 0 error, quit\n");
exit (1);
}
if (len < 6*sizeof (int)) {
fprintf (stderr, "Streaming in rsvcCbk has not enough buffer size\n");
return RSVC_OVERFLOW;
}
int tmp;
int i = 0;
memcpy (&tmp, &(buffer[i]), sizeof (int));
i += sizeof (int);
opcode_ = ntohl (tmp);
memcpy (&tmp, &(buffer[i]), sizeof (int));
i += sizeof (int);
cbkid_ = ntohl (tmp);
memcpy (&tmp, &(buffer[i]), sizeof (int));
i += sizeof (int);
reqid_ = ntohl (tmp);
memcpy (&tmp, &(buffer[i]), sizeof (int));
i += sizeof (int);
clientid_ = ntohl (tmp);
memcpy (&tmp, &(buffer[i]), sizeof (int));
i += sizeof (int);
socketid_ = ntohl (tmp);
memcpy (&tmp, &(buffer[i]), sizeof (int));
i += sizeof (int);
status_ = ntohl (tmp);
return RSVC_SUCCESS;
}
int
rsvcCbk::sameCallback (rsvcCbk* cbk1, rsvcCbk* cbk2,
int checkreq)
{
if (checkreq) {
if (cbk1->reqid_ == cbk2->reqid_ &&
cbk1->clientid_ == cbk2->clientid_ &&
cbk1->socketid_ == cbk2->socketid_ &&
cbk1->cbkid_ == cbk2->cbkid_)
return 1;
else
return 0;
}
else {
if (cbk1->clientid_ == cbk2->clientid_ &&
cbk1->socketid_ == cbk2->socketid_ &&
cbk1->cbkid_ == cbk2->cbkid_)
return 1;
else
return 0;
}
}
int
rsvcCbk::match (rsvcCbk* cbk)
{
if (opcode_ == cbk->opcode_ &&
reqid_ == cbk->reqid_ &&
clientid_ == cbk->clientid_ &&
cbkid_ == cbk->cbkid_)
return 1;
return 0;
}
unsigned int
rsvcCbk::hash (void)
{
// return hash value of callback id
unsigned int h = 0;
unsigned char *k, *e;
k = (unsigned char *)&cbkid_;
e = k + sizeof (int);
for (h = 0; k < e; ++k) {
h *= 16777619;
h ^= *k;
}
return h;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,173 @@
//------------------------------------------------------------------------------
// Copyright (c) 1991,1992 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//------------------------------------------------------------------------------
//
// description: rcsDataEntry.cc
// This file contains the non-inlined functions associated with the
// rsvcDataEntry family of classes.
//
// Author: Walt Akers
//
// Revision History:
// rsvcDataEntry.cc,v
// Revision 1.1 1998/01/22 17:08:05 akers
// Addition of new NameServer
//
//
//
//------------------------------------------------------------------------------
#include "rsvcDataEntry.h"
// *****************************************************************************
// * rsvcDataEntryeStorage::operator ==:
// * This operator allows you to directly and rapidly compare two
// * rsvcDataEntryStorage objects...
// *****************************************************************************
int rsvcDataEntryStorage::operator == (rsvcDataEntryStorage & entry)
{
int result = 0;
int i = 0;
// *********************************************************************
// * First compare all of the pertinent scalar values...
// *********************************************************************
if(strcmp (tag_, entry.tag_) == 0 &&
dataType_ == entry.dataType_ &&
dim_ == entry.dim_ &&
elems_ == entry.elems_)
{
// *************************************************************
// * Next compare the contents of the data items...
// *************************************************************
if(dim_)
{
result = 0;
if(dataType_==RSVC_BYTE)
for(i=0; i<elems_ && !result; i++)
result=!(data_.cptr[i]==entry.data_.cptr[i]);
else if(dataType_==RSVC_INT16)
for(i=0; i<elems_ && !result; i++)
result=!(data_.sptr[i]==entry.data_.sptr[i]);
else if(dataType_==RSVC_UINT16)
for(i=0; i<elems_ && !result; i++)
result=!(data_.usptr[i]==entry.data_.usptr[i]);
else if(dataType_==RSVC_INT32)
for(i=0; i<elems_ && !result; i++)
result=!(data_.lptr[i]==entry.data_.lptr[i]);
else if(dataType_==RSVC_UINT32)
for(i=0; i<elems_ && !result; i++)
result=!(data_.ulptr[i]==entry.data_.ulptr[i]);
else if(dataType_==RSVC_FLOAT)
for(i=0; i<elems_ && !result; i++)
result=!(data_.fptr[i]==entry.data_.fptr[i]);
else if(dataType_==RSVC_DOUBLE)
for(i=0; i<elems_ && !result; i++)
result=!(data_.dptr[i]==entry.data_.dptr[i]);
else if(dataType_==RSVC_STRING)
for(i=0; i<elems_ && !result; i++)
result=strcmp(data_.strarr[i], entry.data_.strarr[i]);
else if(dataType_==RSVC_TIMESTAMP)
for(i=0; i<elems_ && !result; i++)
result=!((data_.tsptr[i].nsec==entry.data_.tsptr[i].nsec) &&
(data_.tsptr[i].secPastEpoch==entry.data_.tsptr[i].secPastEpoch));
}
else if(dataType_==RSVC_BYTE) result=!(data_.cval==entry.data_.cval);
else if(dataType_==RSVC_INT16) result=!(data_.sval==entry.data_.sval);
else if(dataType_==RSVC_UINT16) result=!(data_.usval==entry.data_.usval);
else if(dataType_==RSVC_INT32) result=!(data_.lval==entry.data_.lval);
else if(dataType_==RSVC_UINT32) result=!(data_.ulval==entry.data_.ulval);
else if(dataType_==RSVC_FLOAT) result=!(data_.fval==entry.data_.fval);
else if(dataType_==RSVC_DOUBLE) result=!(data_.dval==entry.data_.dval);
else if(dataType_==RSVC_STRING) result=strcmp(data_.str, entry.data_.str);
else if(dataType_==RSVC_TIMESTAMP) result=!((data_.ts.nsec==entry.data_.ts.nsec) &&
(data_.ts.secPastEpoch==entry.data_.ts.secPastEpoch));
else result = memcmp(&data_, &entry.data_, sizeof(data_));
}
else result = -1;
return !result;
}
rsvcDataEntry::rsvcDataEntry (const rsvcDataEntry& entry)
{
dataType_ = entry.dataType_;
dim_ = entry.dim_;
elems_ = entry.elems_;
bytes_ = entry.bytes_;
size_ = entry.size_;
strcpy (tag_, entry.tag_);
buffer_ = 0;
next_ = 0;
if (dim_ > 0) {
// allocate memory
allocate (entry.dim_, entry.elems_, entry.bytes_);
// copy memory
memcpy (buffer_, entry.buffer_, size_);
}
else
memcpy (&data_, &entry.data_, sizeof (data_));
}
rsvcDataEntry &
rsvcDataEntry::operator = (const rsvcDataEntry& entry)
{
if (this != &entry) {
clear ();
dataType_ = entry.dataType_;
dim_ = entry.dim_;
elems_ = entry.elems_;
bytes_ = entry.bytes_;
size_ = entry.size_;
strcpy (tag_, entry.tag_);
buffer_ = 0;
if (dim_ > 0 || (dim_ == 0 && dataType_ == RSVC_STRING)) {
// allocate memory
allocate (entry.dim_, entry.elems_, entry.bytes_);
// copy memory
memcpy (buffer_, entry.buffer_, size_);
}
else
memcpy (&data_, &entry.data_, sizeof (data_));
}
return *this;
}
// *****************************************************************************
// * Global initialization of the static freeList_ member of the
// * rsvcDataEntry class.
// *****************************************************************************
rsvcDataEntry * rsvcDataEntry::freeList_ = NULL;
// *****************************************************************************
// * new:
// * Allocation function for the object. It will get the next preallocated
// * rsvcDataEntry object from the freeList_, or, if none are available,
// * refill the freeList_ and then return a new rsvcDataEntry object.
// *****************************************************************************
void * rsvcDataEntry::operator new ( size_t )
{
rsvcDataEntry * result = NULL;
if(freeList_==NULL)
{
freeList_ = ::new rsvcDataEntry[ALLOCATION_COUNT];
for(int i=0; i<ALLOCATION_COUNT; i++) {
freeList_[i].next_ = (i<(ALLOCATION_COUNT-1))?&freeList_[i+1]:(rsvcDataEntry *)NULL;
}
}
if(freeList_!=NULL) {
result = freeList_;
freeList_ = result->next_;
}
return result;
}
@@ -0,0 +1,630 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
// rsvc data streamer class
//
// Author: Jie Chen
//
// Revision History:
// rsvcDataStreamer.cc,v
// Revision 1.1 1998/01/22 17:08:08 akers
// Addition of new NameServer
//
//
//
#include "rsvcErr.h"
#include "rsvcDataStreamer.h"
// ******************************************************************
// float and double conversion routines
// not portable yet especially for VAX machines
// ******************************************************************
static float htonf (float f)
{
float fret;
long *p = (long *)&f;
long nl = htonl (*p);
fret = *(float *)&nl;
return fret;
}
static float ntohf (float f)
{
float fret;
long *p = (long *)&f;
long nl = ntohl (*p);
fret = *(float *)&nl;
return fret;
}
static double htond (double d)
{
long *lp, *lq;
long *dp, *dq;
double ret;
// move high byte first
lp = lq = (long *)&d;
lp++;
dp = dq = (long *)&ret;
*dp = htonl (*lp);
lp--; dp++;
*dp = htonl (*lp);
ret = *(double *)dq;
return ret;
}
static double ntohd (double d)
{
long *lp, *lq;
long *dp, *dq;
double ret;
// low byte of incoming data should be high byte of host native data
lp = lq = (long *)&d;
dp = dq = (long *)&ret;
dp++;
*dp = ntohl (*lp);
lp++; dp--;
*dp = ntohl (*lp);
ret = *(double *)dq;
return ret;
}
static rsvc_TS_STAMP htonts (rsvc_TS_STAMP& ts)
{
rsvc_TS_STAMP rts;
rts.secPastEpoch = htonl (ts.secPastEpoch);
rts.nsec = htonl (ts.nsec);
return rts;
}
static rsvc_TS_STAMP ntohts (rsvc_TS_STAMP& ts)
{
rsvc_TS_STAMP rts;
rts.secPastEpoch = ntohl (ts.secPastEpoch);
rts.nsec = ntohl (ts.nsec);
return rts;
}
rsvcDataStreamer::rsvcDataStreamer (char* buffer, size_t buflen,
int dealloc)
:buffer_ (buffer), buflen_ (buflen), dealloc_ (dealloc), pos_ (0),
err_ (RSVC_SUCCESS)
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcDataStreamer Class Object\n");
#endif
}
rsvcDataStreamer::~rsvcDataStreamer (void)
{
#ifdef _TRACE_OBJECTS
printf ("Delete rsvcDataStreamer Class Object\n");
#endif
if (dealloc_)
if (buffer_) {
delete []buffer_;
buffer_ = 0;
}
}
char*
rsvcDataStreamer::buffer (void) const
{
return buffer_;
}
size_t
rsvcDataStreamer::bufferLength (void) const
{
return buflen_;
}
int
rsvcDataStreamer::streamStatus (void) const
{
return err_;
}
//===============================================================
// Implementation of rsvcDataStreamWriter
//===============================================================
rsvcDataStreamWriter::rsvcDataStreamWriter (char* buffer, size_t size,
int dealloc)
:rsvcDataStreamer (buffer, size, dealloc)
{
#ifdef _TRACE_OBJECTS
printf (" Create rsvcDataStreamWriter Class Object\n");
#endif
}
rsvcDataStreamWriter::~rsvcDataStreamWriter (void)
{
#ifdef _TRACE_OBJECTS
printf (" Delete rsvcDataStreamWriter Class Object\n");
#endif
}
int
rsvcDataStreamWriter::write (char c)
{
long tmp = (long)c;
return write (tmp);
}
int
rsvcDataStreamWriter::write (unsigned char c)
{
long tmp = (long)c;
return write (tmp);
}
int
rsvcDataStreamWriter::write (short c)
{
long tmp = (long)c;
return write (tmp);
}
int
rsvcDataStreamWriter::write (unsigned short c)
{
long tmp = (long)c;
return write (tmp);
}
int
rsvcDataStreamWriter::write (int c)
{
long tmp = (long)c;
return write (tmp);
}
int
rsvcDataStreamWriter::write (unsigned int c)
{
long tmp = (long)c;
return write (tmp);
}
int
rsvcDataStreamWriter::write (long c)
{
long tmp = htonl (c);
if (pos_ + rsvcStreamSize (c) > buflen_) {
#ifdef _RSVC_DEBUG
fprintf (stderr, "Fatal Error: write overflow buffer at %d with bufsize %d\n",
pos_, buflen_);
#endif
err_ = RSVC_ERROR;
return err_;
}
memcpy (&(buffer_[pos_]), &tmp, rsvcStreamSize (c));
pos_ += rsvcStreamSize (c);
return RSVC_SUCCESS;
}
int
rsvcDataStreamWriter::write (unsigned long c)
{
long tmp = (long)c;
return write (tmp);
}
int
rsvcDataStreamWriter::write (float c)
{
float ftmp = htonf (c);
if (pos_ + rsvcStreamSize (c) > buflen_) {
#ifdef _RSVC_DEBUG
fprintf (stderr, "Fatal Error: write float overflow buffer at %d with bufsize %d\n",
pos_, buflen_);
#endif
err_ = RSVC_ERROR;
return err_;
}
memcpy (&(buffer_[pos_]), &ftmp, rsvcStreamSize (c));
pos_ += rsvcStreamSize (c);
return RSVC_SUCCESS;
}
int
rsvcDataStreamWriter::write (double c)
{
double dtmp = htond (c);
if (pos_ + rsvcStreamSize (c) > buflen_) {
#ifdef _RSVC_DEBUG
fprintf (stderr, "Fatal Error: write double overflow buffer at %d with bufsize %d\n",
pos_, buflen_);
#endif
err_ = RSVC_ERROR;
return err_;
}
memcpy (&(buffer_[pos_]), &dtmp, rsvcStreamSize (c));
pos_ += rsvcStreamSize (c);
#ifdef _RSVC_DEBUG
printf ("Write cursor is %d\n", pos_);
#endif
return RSVC_SUCCESS;
}
int
rsvcDataStreamWriter::write (char* str)
{
size_t slen = strlen (str) + 1;
size_t rlen = _RSVC_RNDUP (slen);
size_t len = sizeof (long) + _RSVC_RNDUP (slen);
if (pos_ + len > buflen_) {
#ifdef _RSVC_DEBUG
fprintf (stderr, "Fatal Error: write string %s overflow buffer at %d with bufsize %d\n",
str, pos_, buflen_);
#endif
err_ = RSVC_ERROR;
return err_;
}
// write size of string first
write ((long)rlen);
memcpy (&(buffer_[pos_]), str, slen);
pos_ += slen;
if (rlen > slen)
memset (&(buffer_[pos_]), 0, rlen - slen);
pos_ += (rlen - slen);
return RSVC_SUCCESS;
}
int
rsvcDataStreamWriter::write (void* data, size_t len)
{
size_t rlen = _RSVC_RNDUP (len);
size_t wlen = sizeof (long) + rlen;
if (pos_ + wlen > buflen_) {
#ifdef _RSVC_DEBUG
fprintf (stderr, "Fatal Error: write void * overflow buffer at %d with bufsize %d\n",
pos_, buflen_);
#endif
err_ = RSVC_ERROR;
return err_;
}
// write out size of data first
write ((long)rlen);
memcpy (&(buffer_[pos_]), data, len);
pos_ += len;
if (rlen > len)
memset (&(buffer_[pos_]), 0, rlen - len);
pos_ += (rlen - len);
return RSVC_SUCCESS;
}
int
rsvcDataStreamWriter::write (rsvc_TS_STAMP& ts)
{
rsvc_TS_STAMP tts = htonts (ts);
if (pos_ + rsvcStreamSize (ts) > buflen_) {
#ifdef _RSVC_DEBUG
fprintf (stderr, "Fatal Error: write TS overflow buffer at %d with bufsize %d\n",
pos_, buflen_);
#endif
err_ = RSVC_ERROR;
return err_;
}
memcpy (&(buffer_[pos_]), &tts, rsvcStreamSize (ts));
pos_ += rsvcStreamSize (ts);
return RSVC_SUCCESS;
}
//===============================================================
// Implementation of rsvcDataStreamReader
//===============================================================
rsvcDataStreamReader::rsvcDataStreamReader (char* buffer, size_t buflen,
int dealloc)
:rsvcDataStreamer (buffer, buflen, dealloc)
{
#ifdef _TRACE_OBJECTS
printf (" Create rsvcDataStreamReader Class Object\n");
#endif
}
rsvcDataStreamReader::~rsvcDataStreamReader (void)
{
#ifdef _TRACE_OBJECTS
printf (" Delete rsvcDataStreamReader Class Object\n");
#endif
}
int
rsvcDataStreamReader::read (char& c)
{
long tmp;
int st;
if ((st = read (tmp)) == RSVC_SUCCESS)
c = (char)tmp;
else
c = 0;
return st;
}
int
rsvcDataStreamReader::read (unsigned char& c)
{
long tmp;
int st;
if ((st = read (tmp)) == RSVC_SUCCESS)
c = (unsigned char)tmp;
else
c = 0;
return st;
}
int
rsvcDataStreamReader::read (short & c)
{
long tmp;
int st;
if ((st = read (tmp)) == RSVC_SUCCESS)
c = (short)tmp;
else
c = 0;
return st;
}
int
rsvcDataStreamReader::read (unsigned short& c)
{
long tmp;
int st;
if ((st = read (tmp)) == RSVC_SUCCESS)
c = (unsigned short)tmp;
else
c = 0;
return st;
}
int
rsvcDataStreamReader::read (int& c)
{
long tmp;
int st;
if ((st = read (tmp)) == RSVC_SUCCESS)
c = (int)tmp;
else
c = 0;
return st;
}
int
rsvcDataStreamReader::read (unsigned int& c)
{
long tmp;
int st;
if ((st = read (tmp)) == RSVC_SUCCESS)
c = (unsigned int)tmp;
else
c = 0;
return st;
}
int
rsvcDataStreamReader::read (long& c)
{
long tmp;
if (pos_ + sizeof (c) > buflen_) {
#ifdef _RSVC_DEBUG
fprintf (stderr, "Fatal Error: read long overflow buffer at %d with bufsize %d\n",
pos_, buflen_);
#endif
err_ = RSVC_ERROR;
return err_;
}
memcpy (&tmp, &(buffer_[pos_]), sizeof (long));
pos_ += sizeof (long);
c = ntohl (tmp);
return RSVC_SUCCESS;
}
int
rsvcDataStreamReader::read (unsigned long& c)
{
long tmp;
int st;
if ((st = read (tmp)) == RSVC_SUCCESS)
c = (unsigned long)tmp;
else
c = 0;
return st;
}
int
rsvcDataStreamReader::read (float& c)
{
float ftmp;
if (pos_ + rsvcStreamSize (c) > buflen_) {
#ifdef _RSVC_DEBUG
fprintf (stderr, "Fatal Error: read float overflow buffer at %d with bufsize %d\n",
pos_, buflen_);
#endif
err_ = RSVC_ERROR;
return err_;
}
memcpy (&ftmp, &(buffer_[pos_]), rsvcStreamSize (c));
pos_ += rsvcStreamSize (c);
c = ntohf (ftmp);
return RSVC_SUCCESS;
}
int
rsvcDataStreamReader::read (double& c)
{
double dtmp;
if (pos_ + rsvcStreamSize (c) > buflen_) {
#ifdef _RSVC_DEBUG
fprintf (stderr, "Fatal Error: read double overflow buffer at %d with bufsize %d\n",
pos_, buflen_);
#endif
err_ = RSVC_ERROR;
return err_;
}
memcpy (&dtmp, &(buffer_[pos_]), rsvcStreamSize (c));
pos_ += rsvcStreamSize (c);
c = ntohd (dtmp);
return RSVC_SUCCESS;
}
int
rsvcDataStreamReader::read (rsvc_TS_STAMP & ts)
{
rsvc_TS_STAMP tts;
if (pos_ + rsvcStreamSize (ts) > buflen_) {
#ifdef _RSVC_DEBUG
fprintf (stderr, "Fatal Error: read TS overflow buffer at %d with bufsize %d\n",
pos_, buflen_);
#endif
err_ = RSVC_ERROR;
return err_;
}
memcpy (&tts, &(buffer_[pos_]), rsvcStreamSize (ts));
pos_ += rsvcStreamSize (ts);
ts = ntohts (tts);
return RSVC_SUCCESS;
}
int
rsvcDataStreamReader::read (char* & str)
{
long str_size = 0;
int st = RSVC_SUCCESS;
if (pos_ + sizeof (long) > buflen_) {
#ifdef _RSVC_DEBUG
fprintf (stderr, "Fatal Error: read string header overflow buffer at %d with bufsize %d\n",
pos_, buflen_);
#endif
st = err_ = RSVC_ERROR;
return err_;
}
if ((st = read (str_size)) == RSVC_SUCCESS) {
if (pos_ + str_size > buflen_) {
#ifdef _RSVC_DEBUG
fprintf (stderr, "Fatal Error: read string overflow buffer at %d with bufsize %d\n",
pos_, buflen_);
#endif
err_ = RSVC_ERROR;
return err_;
}
if (str_size > 0) {
str = new char[str_size];
memcpy (str, &(buffer_[pos_]), (unsigned int)str_size);
pos_ += (int)str_size;
}
else {
str = 0;
err_ = st = RSVC_ERROR;
}
}
else {
str = 0;
st = err_ = RSVC_ERROR;
}
return st;
}
int
rsvcDataStreamReader::read (void* data, size_t size)
{
long data_size = 0;
int st = RSVC_SUCCESS;
if (pos_ + sizeof (long) > buflen_) {
#ifdef _RSVC_DEBUG
fprintf (stderr, "Fatal Error: read void * header overflow buffer at %d with bufsize %d\n",
pos_, buflen_);
#endif
st = err_ = RSVC_ERROR;
return err_;
}
if ((st = read (data_size)) == RSVC_SUCCESS) {
if (pos_ + data_size > buflen_) {
#ifdef _RSVC_DEBUG
fprintf (stderr, "Fatal Error: read void * overflow buffer at %d with bufsize %d\n",
pos_, buflen_);
#endif
st = err_ = RSVC_ERROR;
return err_;
}
if (data_size > 0) {
memcpy (data, &(buffer_[pos_]), size);
pos_ += (int)data_size;
}
else
st = err_ = RSVC_ERROR;
}
return st;
}
+762
View File
@@ -0,0 +1,762 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
// Single Linked List for rsvcHashable* pointer
//
// Note: remove and clean operations on the list
// will only remove link nodes without removal of
// the content inside the nodes. It is callers'
// responsiblity to clean up those contents
//
// Author: Jie Chen
// CEBAF Data Acquisition Group
//
// Revision History:
// rsvcHSlist.cc,v
// Revision 1.1 1998/01/22 17:08:12 akers
// Addition of new NameServer
//
//
//
#include <rsvcHashable.h>
#include "rsvcHSlist.h"
//======================================================================
// class rsvcHSlist implementation
//======================================================================
rsvcHSlist::rsvcHSlist (void)
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
:ptrToFirstLink(0), count_ (0), lock_ ()
#else
:ptrToFirstLink(0), count_ (0)
#endif
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcHSlist Class Object\n");
#endif
// no further initialization
}
rsvcHSlist::rsvcHSlist (const rsvcHSlist & source)
:count_ (source.count_)
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcHSlist Class Object\n");
#endif
// duplicate elements from source list
if (source.isEmpty_i())
ptrToFirstLink = 0;
else{
rsvcHSlistLink * firstLink = source.ptrToFirstLink;
ptrToFirstLink = firstLink->duplicate();
}
}
rsvcHSlist::~rsvcHSlist (void)
{
// empty all elements from the list
#ifdef _TRACE_OBJECTS
printf ("Delete rsvcHSlist Class Object\n");
#endif
deleteAllValues();
}
void
rsvcHSlist::add (rsvcHashable* val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// add a new value to the front of a linked list
ptrToFirstLink = new rsvcHSlistLink(val, ptrToFirstLink);
count_ ++;
assert(ptrToFirstLink != 0);
}
void
rsvcHSlist::addToEnd (rsvcHashable* val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
count_ ++;
if (ptrToFirstLink == 0) {
ptrToFirstLink = new rsvcHSlistLink(val, ptrToFirstLink);
return;
}
// loop through until last element
rsvcHSlistLink *p = 0;
for (p = ptrToFirstLink; p->ptrToNextLink; p = p->ptrToNextLink)
;
rsvcHSlistLink* q = new rsvcHSlistLink (val, 0);
p->ptrToNextLink = q;
}
void
rsvcHSlist::add_i (rsvcHashable* val)
{
// add a new value to the front of a linked list
count_ ++;
ptrToFirstLink = new rsvcHSlistLink(val, ptrToFirstLink);
assert(ptrToFirstLink != 0);
}
int
rsvcHSlist::remove (rsvcHashable* val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// remove an element from the list
// loop to test each element
rsvcHSlistLink *q = ptrToFirstLink;
for (rsvcHSlistLink * p = ptrToFirstLink; p; p = p->ptrToNextLink){
if (val == p->value){
if (q == p){
// remove first element
ptrToFirstLink = p->ptrToNextLink;
delete p;
}
else{
q->ptrToNextLink = p->ptrToNextLink;
delete p;
}
count_ --;
return 1;
}
q = p;
}
// not found
return 0;
}
void
rsvcHSlist::deleteAllValues (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// clear all items from the list
rsvcHSlistLink * next;
for (rsvcHSlistLink * p = ptrToFirstLink; p != 0; p = next){
// delete the element pointed to by p
next = p->ptrToNextLink;
p->ptrToNextLink = 0;
delete p;
}
// set count to zero
count_ = 0;
// mark that the list contains no elements
ptrToFirstLink = 0;
}
void
rsvcHSlist::deleteAllValues_i (void)
{
// clear all items from the list
rsvcHSlistLink * next;
for (rsvcHSlistLink * p = ptrToFirstLink; p != 0; p = next){
// delete the element pointed to by p
next = p->ptrToNextLink;
p->ptrToNextLink = 0;
delete p;
}
// set count to zero
count_ = 0;
// mark that the list contains no elements
ptrToFirstLink = 0;
}
int
rsvcHSlist::count (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
return count_;
}
rsvcHSlist*
rsvcHSlist::duplicate (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
rsvcHSlist * newlist = new rsvcHSlist;
assert(newlist != 0);
// copy list
if (ptrToFirstLink)
newlist->ptrToFirstLink = ptrToFirstLink->duplicate();
// set new list count
newlist->count_ = count_;
// return the new list
return newlist;
}
rsvcHashable*
rsvcHSlist::firstElement (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// return first value in list
assert(ptrToFirstLink != 0);
return ptrToFirstLink->value;
}
rsvcHashable*
rsvcHSlist::firstElement_i (void)
{
// return first value in list
assert(ptrToFirstLink != 0);
return ptrToFirstLink->value;
}
rsvcHashable*
rsvcHSlist::lastElement (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
assert(ptrToFirstLink != 0);
// loop through until last element
rsvcHSlistLink *p = 0;
for (p = ptrToFirstLink; p->ptrToNextLink; p = p->ptrToNextLink)
;
return p->value;
}
rsvcHashable*
rsvcHSlist::lastElement_i (void)
{
assert(ptrToFirstLink != 0);
// loop through until last element
rsvcHSlistLink *p = 0;
for (p = ptrToFirstLink; p->ptrToNextLink; p = p->ptrToNextLink)
;
return p->value;
}
int
rsvcHSlist::includes(rsvcHashable* v)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// loop to test each element
for (rsvcHSlistLink * p = ptrToFirstLink; p; p = p->ptrToNextLink)
if (v == p->value)
return 1;
// not found
return 0;
}
int
rsvcHSlist::isEmpty (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// test to see if the list is empty
// list is empty if the pointer to the first link is null
return ptrToFirstLink == 0;
}
int
rsvcHSlist::isEmpty_i (void) const
{
// test to see if the list is empty
// list is empty if the pointer to the first link is null
return ptrToFirstLink == 0;
}
void
rsvcHSlist::removeFirst (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// make sure there is a first element
assert(ptrToFirstLink != 0);
// save pointer to the removed node
rsvcHSlistLink * p = ptrToFirstLink;
// reassign the ptrToFirstLink node
ptrToFirstLink = p->ptrToNextLink;
// decrease the count
count_ --;
// recover memory used by the first element
delete p;
}
void
rsvcHSlist::removeFirst_i (void)
{
// make sure there is a first element
assert(ptrToFirstLink != 0);
// save pointer to the removed node
rsvcHSlistLink * p = ptrToFirstLink;
// reassign the ptrToFirstLink node
ptrToFirstLink = p->ptrToNextLink;
// decrease the count
count_ --;
// recover memory used by the first element
delete p;
}
//======================================================================
// class slink implementation
// No need to add any mutex protection since all member
// functions are called with lock held
//======================================================================
rsvcHSlistLink*
rsvcHSlistLink::insert(rsvcHashable* val)
{
// insert a new link after current node
ptrToNextLink = new rsvcHSlistLink(val, ptrToNextLink);
// check that allocation was successful
assert(ptrToNextLink != 0);
return ptrToNextLink;
}
rsvcHSlistLink::rsvcHSlistLink (rsvcHashable* val, rsvcHSlistLink * nxt)
:value(val), ptrToNextLink(nxt)
{
// create and initialize a new link field
}
rsvcHSlistLink*
rsvcHSlistLink::duplicate (void)
{
rsvcHSlistLink * newlink;
// if there is a next field. copy remainder of list
if (ptrToNextLink != 0)
newlink = new rsvcHSlistLink(value, ptrToNextLink->duplicate());
else
newlink = new rsvcHSlistLink (value, 0);
// check that allocation was successful
assert(newlink != 0);
return newlink;
}
rsvcHSlistLink*
rsvcHSlistLink::next (void)
{
return ptrToNextLink;
}
rsvcHashable*
rsvcHSlistLink::data (void)
{
return value;
}
//======================================================================
// class listIterator implementation
//======================================================================
rsvcHSlistIterator::rsvcHSlistIterator(rsvcHSlist & aList)
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
:theList(aList), lock_ ()
#else
:theList(aList)
#endif
{
// create and initialize a new list
init_i();
}
int
rsvcHSlistIterator::init_i()
{
// set the iterator to the first element in the list
previousLink = 0;
currentLink = theList.ptrToFirstLink;
return currentLink != 0;
}
int
rsvcHSlistIterator::init()
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// set the iterator to the first element in the list
previousLink = 0;
currentLink = theList.ptrToFirstLink;
return currentLink != 0;
}
rsvcHashable*
rsvcHSlistIterator::operator () (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// return value of current element
// check to see if there is a current element
assert(currentLink != 0);
// return value associated with current element
return currentLink->value;
}
int rsvcHSlistIterator::operator ! (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// test for termination of the iterator
// if current link references a removed value,
// update current to point to next position
if (currentLink == 0)
if (previousLink != 0)
currentLink = previousLink->ptrToNextLink;
// now see if currentLink is valid
return currentLink != 0;
}
int rsvcHSlistIterator::forward_i (void)
{
// move current pointer to nect element
// special processing if current link is deleted
if (currentLink == 0){
if (previousLink == 0)
currentLink = theList.ptrToFirstLink;
else
currentLink = previousLink->ptrToNextLink;
}
else{
// advance pointer
previousLink = currentLink;
currentLink = currentLink->ptrToNextLink;
}
// return true if we have a valid current element
return currentLink != 0;
}
int rsvcHSlistIterator::operator ++()
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// move current pointer to nect element
// special processing if current link is deleted
if (currentLink == 0){
if (previousLink == 0)
currentLink = theList.ptrToFirstLink;
else
currentLink = previousLink->ptrToNextLink;
}
else{
// advance pointer
previousLink = currentLink;
currentLink = currentLink->ptrToNextLink;
}
// return true if we have a valid current element
return currentLink != 0;
}
void rsvcHSlistIterator::operator = (rsvcHashable* val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// modify value of current element
assert(currentLink != 0);
// modify value of the current link
currentLink->value = val;
}
void rsvcHSlistIterator::removeCurrent_i (void)
{
// remove the current element from a list
// make sure there is a current element
assert(currentLink != 0);
// case 1, removing first element
if (previousLink == 0)
theList.ptrToFirstLink = currentLink->ptrToNextLink;
// case 2, not removing the first element
else
previousLink->ptrToNextLink = currentLink->ptrToNextLink;
// delete current node
delete currentLink;
// and set current pointer to null
currentLink = 0;
// decrease list count element
theList.count_ --;
}
void rsvcHSlistIterator::removeCurrent (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// remove the current element from a list
// make sure there is a current element
assert(currentLink != 0);
// case 1, removing first element
if (previousLink == 0)
theList.ptrToFirstLink = currentLink->ptrToNextLink;
// case 2, not removing the first element
else
previousLink->ptrToNextLink = currentLink->ptrToNextLink;
// delete current node
delete currentLink;
// and set current pointer to null
currentLink = 0;
// decrease list count element
theList.count_ --;
}
void rsvcHSlistIterator::addBefore(rsvcHashable* val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// add a new element to list before current value
// case 1, not at start
if (previousLink)
previousLink = previousLink->insert(val);
// case 2, at start of list
else{
theList.rsvcHSlist::add(val);
previousLink = theList.ptrToFirstLink;
currentLink = previousLink->ptrToNextLink;
}
// increase the count
theList.count_ ++;
}
void rsvcHSlistIterator::addAfter(rsvcHashable* val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// a a new element to list after current value
// case 1, not at start
if (currentLink != 0)
currentLink->insert(val);
// case 2, at end of list
else if (previousLink != 0)
currentLink = previousLink->insert(val);
// case 3, start of list
else
theList.rsvcHSlist::add(val);
// increase the count
theList.count_ ++;
}
int rsvcHSlistIterator::searchSame(rsvcHashable* &val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// search the list to find out whether we have this element
// if we do, move cursor to this element return 1
// if we don't return 0
init_i();
if (currentLink == 0){
// empty link
return 0;
}
while (currentLink != 0){
// advance pointer
if (currentLink->value == val)
break;
previousLink = currentLink;
currentLink = currentLink->ptrToNextLink;
}
// return true if we have a valid current element
return currentLink != 0;
}
//========================================================================
// Implementation of rsvcHSlistCursor
// Implements of cursor without changing list
//========================================================================
rsvcHSlistCursor::rsvcHSlistCursor(const rsvcHSlist & aList)
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
:theList(aList), lock_ ()
#else
:theList(aList)
#endif
{
// create and initialize a new list
init_i();
}
int
rsvcHSlistCursor::init_i()
{
// set the iterator to the first element in the list
previousLink = 0;
currentLink = theList.ptrToFirstLink;
return currentLink != 0;
}
int
rsvcHSlistCursor::init()
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// set the iterator to the first element in the list
previousLink = 0;
currentLink = theList.ptrToFirstLink;
return currentLink != 0;
}
rsvcHashable*
rsvcHSlistCursor::operator () (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// return value of current element
// check to see if there is a current element
assert(currentLink != 0);
// return value associated with current element
return currentLink->value;
}
int rsvcHSlistCursor::operator ! (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// test for termination of the iterator
// if current link references a removed value,
// update current to point to next position
if (currentLink == 0)
if (previousLink != 0)
currentLink = previousLink->ptrToNextLink;
// now see if currentLink is valid
return currentLink != 0;
}
int rsvcHSlistCursor::operator ++ (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// move current pointer to nect element
// special processing if current link is deleted
if (currentLink == 0){
if (previousLink == 0)
currentLink = theList.ptrToFirstLink;
else
currentLink = previousLink->ptrToNextLink;
}
else{
// advance pointer
previousLink = currentLink;
currentLink = currentLink->ptrToNextLink;
}
// return true if we have a valid current element
return currentLink != 0;
}
int rsvcHSlistCursor::searchSame (rsvcHashable* &val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// search the list to find out whether we have this element
// if we do, move cursor to this element return 1
// if we don't return 0
init_i();
if (currentLink == 0){
// empty link
return 0;
}
while (currentLink != 0){
// advance pointer
if (currentLink->value == val)
break;
previousLink = currentLink;
currentLink = currentLink->ptrToNextLink;
}
// return true if we have a valid current element
return currentLink != 0;
}
void rsvcHSlistCursor::operator = (rsvcHashable* )
{
// empty
}
+351
View File
@@ -0,0 +1,351 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// CEBAF Data Acquisition Group, 12000 Jefferson Ave., Newport News, VA 23606
// Email: coda@cebaf.gov Tel: (804) 249-7101 Fax: (804) 249-7363
//-----------------------------------------------------------------------------
//
// Description:
// rsvcHash: rsvc hash table keyed by a variable length string
// Open Hash with buckets implemented by single linked lists
//
// Note: void *s are stored inside the table. This class
// will not manage these pointers. Callers have to
// manage these pointers
//
// Note: this is unsafe C++ practice. Use at your own risk
//
// Reason: It is so difficult to use a template class inside
// a shared library. (Cfront based C++ compiler cannot
// instantiate a template class during compilation time
//
// Author: Jie Chen
// CEBAF Data Acquisition Group
//
// Revision History:
// rsvcHash.cc,v
// Revision 1.3 1998/02/26 19:10:24 chen
// provide direct access to array of linked list
//
// Revision 1.2 1998/02/20 19:29:54 chen
// Remove debug print
//
// Revision 1.1 1998/01/22 17:08:13 akers
// Addition of new NameServer
//
//
//
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include "rsvcHash.h"
// the following are 10 prime numbers. Each is twice of value of the
// one in front of it.
static unsigned int rsvc_prime_table[] =
{11, 97, 199, 499, 997, 1999, 4999, 9973, 25013, 49999, 99991};
static unsigned int rsvc_prime_table_size = 11;
static unsigned int
rsvc_pick_prime (unsigned max, int* index)
{
unsigned int diff = 12345678;
unsigned int tmp;
for (int i = 0; i < rsvc_prime_table_size; i++) {
tmp = abs ((int)((int)max - (int)rsvc_prime_table[i]));
if (tmp < diff) {
diff = tmp;
*index = i;
}
}
return rsvc_prime_table[*index];
}
// a simple string hash function
unsigned int rsvcHashFunc (const char *src)
{
unsigned int hash = 0, g;
for (int i = 0; src[i] != '\0'; i++){
hash = (hash << 4) + src[i];
// assume 32 bit integer
if (g = hash & 0xf0000000){
hash ^= g >> 24;
hash ^= g;
}
}
return hash;
}
//======================================================================
// class rsvcHash implementation
//======================================================================
// lock_ has default constructor, so compiler will do it for us
rsvcHash::rsvcHash (unsigned int max, unsigned int loadfactor)
:lf (loadfactor)
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcHash Class Objects\n");
#endif
// figure out nearest prime number for max
tablesize = rsvc_pick_prime (max, &primeindex);
#ifdef _RSVC_DEBUG
/*printf ("table size for str hash is %d, index is %d\n", tablesize,
primeindex);*/
#endif
// rsvcSlist has a default constructor, so one can create an array of the list
buckets = new rsvcHSlist[tablesize];
assert (buckets);
}
rsvcHash::~rsvcHash (void)
{
#ifdef _TRACE_OBJECTS
printf ("Delete rsvcHash Class Objects\n");
#endif
delete []buckets;
buckets = 0;
}
void
rsvcHash::rehash (void)
{
if (primeindex == rsvc_prime_table_size - 1) {
fprintf (stderr, "Cannot exapnd the hash table size %d anymore\n",
rsvc_prime_table[primeindex]);
return;
}
// remember old values
unsigned int oldtablesize = tablesize;
rsvcHSlist* oldbuckets = buckets;
// create new values
tablesize = rsvc_prime_table[primeindex + 1];
buckets = new rsvcHSlist[tablesize];
assert (buckets);
#ifdef _RSVC_DEBUG
/* fprintf (stderr, "Expand hash table from %d to %d (reaching lf %d) \n",
oldtablesize, tablesize, lf);*/
#endif
primeindex ++;
rsvcHashable* elem = 0;
for (int i = 0; i < oldtablesize; i++) {
rsvcHSlistIterator site (oldbuckets[i]);
for (site.init (); !site; ++site) {
elem = site ();
add (elem);
}
}
// remove old memory
delete []oldbuckets;
}
int
rsvcHash::isEmpty()
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// if any table is non-empty, return 0
for (int i = 0; i < tablesize; i++)
if (!buckets[i].isEmpty_i())
return 0;
// all empty
return 1;
}
void
rsvcHash::deleteAllValues()
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// delete all values from a hash table
// clear the elements from each of teh buckets
for (int i = 0; i < tablesize; i++)
buckets[i].deleteAllValues_i();
}
unsigned int
rsvcHash::hash(rsvcHashable* ele) const
{
// return hashed value of key
return (ele->hash () % tablesize);
}
void
rsvcHash::add (rsvcHashable* newele)
{
buckets[hash (newele)].add (newele);
if (buckets[hash (newele)].count () > lf) {
#ifdef _RSVC_DEBUG
/* fprintf (stderr, "Hash buckets %d has %d elements > load factor %d, resize\n",
hash (newele), buckets[hash (newele)].count (), lf);*/
#endif
rehash ();
}
}
rsvcHSlist&
rsvcHash::bucketRef (rsvcHashable* ele)
{
return (buckets[hash (ele)]);
}
rsvcHSlist&
rsvcHash::bucketRef (unsigned int hashcode)
{
return (buckets[hashcode % tablesize]);
}
void
rsvcHash::bucketList (rsvcHSlist* &lists, unsigned int& size)
{
lists = buckets;
size = tablesize;
}
void
rsvcHash::asciiDump (FILE* fd)
{
fprintf (fd, "Hash table looks like the following\n");
fprintf (fd, "====================================================\n");
for (int i = 0; i < tablesize; i++)
fprintf (fd, "Bucket[%d] contains %d elements\n", i, buckets[i].count ());
fprintf (fd, "====================================================\n");
}
//======================================================================
// class rsvcHashIterator implementation
//======================================================================
rsvcHashIterator::rsvcHashIterator (rsvcHash& v)
:base(v), currentIndex(0), itr(0)
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcHashIterator Class Object \n");
#endif
// no further initialization
}
rsvcHashIterator::~rsvcHashIterator (void)
{
#ifdef _TRACE_OBJECTS
printf ("Delete rsvcHashIterator Class Object \n");
#endif
currentIndex = 0;
if (itr)
delete itr;
}
int
rsvcHashIterator::init (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// initialize iterator,
// start search with first bucket
currentIndex = 0;
itr = 0;
return getNextIterator();
}
rsvcHashable *
rsvcHashIterator::operator() (void)
{
// return current element
return (*itr)();
}
int
rsvcHashIterator::operator ! (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// test if there is a current element
return itr != 0;
}
int
rsvcHashIterator::operator ++ (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// see if current iterator can be advanced
if (itr && itr->forward_i ())
return 1;
// if not, get next iterator
currentIndex++;
return getNextIterator();
}
void
rsvcHashIterator::operator = (rsvcHashable* val)
{
// change the current value
(*itr) = val;
}
void
rsvcHashIterator::removeCurrent (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
if (itr)
itr->removeCurrent_i ();
}
int
rsvcHashIterator::getNextIterator (void)
{
// if there is an old iterator, delete it
if (itr != 0)
delete itr;
// now search for a new one
for (; currentIndex < base.tablesize; currentIndex++){
// generate a new iterator at the current point
itr = new rsvcHSlistIterator (base.buckets[currentIndex]);
assert(itr != 0);
// if it has at least one element, we're done
if (itr->init_i())
return 1;
// otherwise delete it, try again
delete itr;
}
// all out of iterators, can quit
itr = 0;
return 0;
}
@@ -0,0 +1,38 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
// RSVC Hashable Class
//
// Author: Jie Chen
//
// Revision History:
// rsvcHashable.cc,v
// Revision 1.1 1998/01/22 17:08:13 akers
// Addition of new NameServer
//
//
//
#include <stdio.h>
#include "rsvcHashable.h"
rsvcHashable::rsvcHashable (void)
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcHashable Class Object\n");
#endif
}
rsvcHashable::~rsvcHashable (void)
{
#ifdef _TRACE_OBJECTS
printf ("Delete rsvcHashable Class Object\n");
#endif
}
+354
View File
@@ -0,0 +1,354 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
// Implementation of rsvcNetData Class
//
// Author: Jie Chen
//
// Revision History:
// rsvcNetData.cc,v
// Revision 1.1 1998/01/22 17:08:18 akers
// Addition of new NameServer
//
//
//
#include <rsvcDataStreamer.h>
#include "rsvcNetData.h"
rsvcNetData::rsvcNetData (void)
:cbk_ (), data_ ()
{
#ifdef _TRACE_OBJECTS
printf (" Create rsvcNetData Class Object\n");
#endif
// empty
}
rsvcNetData::rsvcNetData (rsvcData& data, long opcode, long cbkid,
long reqid, long clientid, long socketid,
long status)
:cbk_ (opcode, cbkid, reqid, clientid, socketid, status), data_ (data)
{
#ifdef _TRACE_OBJECTS
printf (" Create rsvcNetData Class Object\n");
#endif
// empty
}
rsvcNetData::rsvcNetData (rsvcData& data, rsvcCbk& cbk)
:cbk_ (cbk), data_ (data)
{
#ifdef _TRACE_OBJECTS
printf (" Create rsvcNetData Class Object\n");
#endif
// empty
}
rsvcNetData::rsvcNetData (rsvcData& data)
: cbk_ (), data_ (data)
{
#ifdef _TRACE_OBJECTS
printf (" Create rsvcNetData Class Object\n");
#endif
// empty
}
rsvcNetData::rsvcNetData (rsvcCbk& cbk)
:cbk_ (cbk), data_ ()
{
#ifdef _TRACE_OBJECTS
printf (" Create rsvcNetData Class Object\n");
#endif
// empty
}
rsvcNetData::rsvcNetData (const rsvcNetData& data)
:cbk_ (data.cbk_), data_ (data.data_)
{
#ifdef _TRACE_OBJECTS
printf (" Create rsvcNetData Class Object\n");
#endif
// empty
}
rsvcNetData::~rsvcNetData (void)
{
#ifdef _TRACE_OBJECTS
printf (" Delete rsvcNetData Class Object\n");
#endif
// empty
}
void
rsvcNetData::set (rsvcData& data, rsvcCbk& cbk)
{
data_ = data;
cbk_ = cbk;
}
void
rsvcNetData::set (rsvcCbk& cbk)
{
cbk_ = cbk;
}
void
rsvcNetData::cleanup (void)
{
cbk_.cleanup ();
data_.remove ();
}
long
rsvcNetData::opcode (void) const
{
return cbk_.opcode ();
}
void
rsvcNetData::opcode (long op)
{
cbk_.opcode (op);
}
long
rsvcNetData::cbkid (void) const
{
return cbk_.cbkid ();
}
void
rsvcNetData::cbkid (long cid)
{
cbk_.cbkid (cid);
}
long
rsvcNetData::reqid (void) const
{
return cbk_.reqid ();
}
void
rsvcNetData::reqid (long req)
{
cbk_.reqid (req);
}
long
rsvcNetData::clientid (void) const
{
return cbk_.clientid ();
}
void
rsvcNetData::clientid (long cid)
{
cbk_.clientid (cid);
}
long
rsvcNetData::socketid (void) const
{
return cbk_.socketid ();
}
void
rsvcNetData::socketid (long sid)
{
cbk_.socketid (sid);
}
void
rsvcNetData::cbkstatus (long status)
{
cbk_.cbkstatus (status);
}
long
rsvcNetData::cbkstatus (void) const
{
return cbk_.cbkstatus ();
}
rsvcData&
rsvcNetData::data (void)
{
return data_;
}
rsvcCbk&
rsvcNetData::cbk (void)
{
return cbk_;
}
size_t
rsvcNetData::streamSize (void)
{
int st = RSVC_SUCCESS;
size_t dataSize = 0;
long size = 0;
// First is magic number
dataSize += rsvcStreamSize (_RSVC_MAGIC_NUM);
// Size of the data to follow after this
dataSize += rsvcStreamSize (size);
// send all cbk information
dataSize += cbk_.streamSize ();
// send data itself
size_t buflen, count;
data_.streamSize (&buflen, &count);
dataSize += buflen;
return dataSize;
}
int
rsvcNetData::streamOut (char** buffer, size_t* len)
{
size_t datasize = streamSize ();
char* buf = new char[datasize];
int i = 0;
if (!buf) {
fprintf (stderr, "Cannot allocate buffer to rsvcNetData streamout\n");
exit (1);
}
*buffer = buf;
*len = datasize;
return streamOut (buf, *len, datasize);
}
int
rsvcNetData::streamOut (char* buffer, size_t buflen, size_t size)
{
int st = RSVC_SUCCESS;
int i = 0;
if (size > buflen) {
fprintf (stderr, "Fatal: rsvcNetData streamout buffer overflow %d > %d\n",
size , buflen);
return RSVC_ERROR;
}
// write magic number first
long tmp = htonl ((long)_RSVC_MAGIC_NUM);
memcpy (&(buffer[i]), &tmp, rsvcStreamSize (_RSVC_MAGIC_NUM));
i += rsvcStreamSize (_RSVC_MAGIC_NUM);
// write data size without header information
size_t real_size = size - rsvcStreamSize (_RSVC_MAGIC_NUM)
- rsvcStreamSize (size);
tmp = htonl (real_size);
memcpy (&(buffer[i]), &tmp, rsvcStreamSize (size));
i += rsvcStreamSize (real_size);
// write cbk data
long cbksize = cbk_.streamSize ();
if (cbk_.streamOut (&(buffer[i]), buflen - i) != RSVC_SUCCESS)
return RSVC_ERROR;
i += (int)cbksize;
// write data itself
size_t databuflen, datacount;
data_.streamSize (&databuflen, &datacount);
if (data_.streamOut (&(buffer[i]), buflen - i, datacount) != RSVC_SUCCESS)
return RSVC_ERROR;
i += databuflen;
if (i != size) {
fprintf (stderr, "Fatal: Overflow rsvcNetData the stream out buffer\n");
return RSVC_ERROR;
}
return RSVC_SUCCESS;
}
int
rsvcNetData::streamOut (char* buffer, size_t len)
{
size_t datasize = streamSize ();
if (datasize > len) {
fprintf (stderr, "Fatal: rsvcNetData streamout buffer overflow %d > %d\n",
datasize, len);
return RSVC_ERROR;
}
return streamOut (buffer, len, datasize);
}
int
rsvcNetData::streamIn (char* buffer, size_t len)
{
int st = RSVC_SUCCESS;
int i = 0;
if ((st = cbk_.streamIn (&(buffer[i]), len)) != RSVC_SUCCESS)
return st;
i += cbk_.streamSize ();
if ((st = data_.streamIn (&(buffer[i]), len - i)) != RSVC_SUCCESS)
return st;
return st;
}
int
rsvcNetData::readHeader (char* buffer, size_t len, size_t* datasize)
{
long magicnum;
size_t size = 0;
if (len < rsvcStreamSize (_RSVC_MAGIC_NUM) + rsvcStreamSize (size)) {
fprintf (stderr, "Fatal: reading rsvcNetData Header error: overflow\n");
return RSVC_ERROR;
}
int i = 0;
long tmp;
// get magic number
memcpy (&tmp, &(buffer[i]), rsvcStreamSize (_RSVC_MAGIC_NUM));
magicnum = ntohl (tmp);
if (magicnum != _RSVC_MAGIC_NUM) {
fprintf (stderr, "Fatal: reading rsvcNetData header error: magic number mismatch\n");
return RSVC_ERROR;
}
i += rsvcStreamSize (_RSVC_MAGIC_NUM);
// get data size
memcpy (&tmp, &(buffer[i]), rsvcStreamSize (size));
size = (unsigned int)ntohl (tmp);
i += rsvcStreamSize (size);
*datasize = size;
return RSVC_SUCCESS;
}
size_t
rsvcNetData::headerLen (void)
{
return rsvcStreamSize (_RSVC_MAGIC_NUM) + rsvcStreamSize ((size_t)1);
}
+903
View File
@@ -0,0 +1,903 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
// Single Linked List for void *
//
// Note: remove and clean operations on the list
// will only remove link nodes without removal of
// the content inside the nodes. It is callers'
// responsiblity to clean up those contents
//
// This is unsafe C++ practice, use this list at you own risk
//
// Reason for this list: It is very difficult to instantiate
// a template class in a stand alone shared library
//
// Author: Jie Chen
// CEBAF Data Acquisition Group
//
// Revision History:
// rsvcSlist.cc,v
// Revision 1.1 1998/01/22 17:08:22 akers
// Addition of new NameServer
//
//
//
#include "rsvcSlist.h"
//======================================================================
// class rsvcSlist implementation
//======================================================================
rsvcSlist::rsvcSlist (void)
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
:ptrToFirstLink(0), count_ (0), lock_ ()
#else
:ptrToFirstLink(0), count_ (0)
#endif
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcSlist Class Object\n");
#endif
// no further initialization
}
rsvcSlist::rsvcSlist (const rsvcSlist & source)
:count_ (source.count_)
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcSlist Class Object\n");
#endif
// duplicate elements from source list
if (source.isEmpty_i())
ptrToFirstLink = 0;
else{
rsvcSlistLink * firstLink = source.ptrToFirstLink;
ptrToFirstLink = firstLink->duplicate();
}
}
rsvcSlist::~rsvcSlist (void)
{
// empty all elements from the list
#ifdef _TRACE_OBJECTS
printf ("Delete rsvcSlist Class Object\n");
#endif
deleteAllValues();
}
void
rsvcSlist::add (rsvcSlistItem val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// add a new value to the front of a linked list
ptrToFirstLink = new rsvcSlistLink(val, ptrToFirstLink);
count_ ++;
assert(ptrToFirstLink != 0);
}
void
rsvcSlist::addToEnd (rsvcSlistItem val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
count_ ++;
if (ptrToFirstLink == 0) {
ptrToFirstLink = new rsvcSlistLink(val, ptrToFirstLink);
return;
}
// loop through until last element
rsvcSlistLink *p = 0;
for (p = ptrToFirstLink; p->ptrToNextLink; p = p->ptrToNextLink)
;
rsvcSlistLink* q = new rsvcSlistLink (val, 0);
p->ptrToNextLink = q;
}
void
rsvcSlist::add_i (rsvcSlistItem val)
{
// add a new value to the front of a linked list
count_ ++;
ptrToFirstLink = new rsvcSlistLink(val, ptrToFirstLink);
assert(ptrToFirstLink != 0);
}
int
rsvcSlist::remove (rsvcSlistItem val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// remove an element from the list
// loop to test each element
rsvcSlistLink *q = ptrToFirstLink;
for (rsvcSlistLink * p = ptrToFirstLink; p; p = p->ptrToNextLink){
if (val == p->value){
if (q == p){
// remove first element
ptrToFirstLink = p->ptrToNextLink;
delete p;
}
else{
q->ptrToNextLink = p->ptrToNextLink;
delete p;
}
count_ --;
return 1;
}
q = p;
}
// not found
return 0;
}
void
rsvcSlist::deleteAllValues (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// clear all items from the list
rsvcSlistLink * next;
for (rsvcSlistLink * p = ptrToFirstLink; p != 0; p = next){
// delete the element pointed to by p
next = p->ptrToNextLink;
p->ptrToNextLink = 0;
delete p;
}
// set count to zero
count_ = 0;
// mark that the list contains no elements
ptrToFirstLink = 0;
}
void
rsvcSlist::deleteAllValues_i (void)
{
// clear all items from the list
rsvcSlistLink * next;
for (rsvcSlistLink * p = ptrToFirstLink; p != 0; p = next){
// delete the element pointed to by p
next = p->ptrToNextLink;
p->ptrToNextLink = 0;
delete p;
}
// set count to zero
count_ = 0;
// mark that the list contains no elements
ptrToFirstLink = 0;
}
int
rsvcSlist::count (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
return count_;
}
rsvcSlist*
rsvcSlist::duplicate (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
rsvcSlist * newlist = new rsvcSlist;
assert(newlist != 0);
// copy list
if (ptrToFirstLink)
newlist->ptrToFirstLink = ptrToFirstLink->duplicate();
// set new list count
newlist->count_ = count_;
// return the new list
return newlist;
}
rsvcSlistItem
rsvcSlist::firstElement (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// return first value in list
assert(ptrToFirstLink != 0);
return ptrToFirstLink->value;
}
rsvcSlistItem
rsvcSlist::firstElement_i (void)
{
// return first value in list
assert(ptrToFirstLink != 0);
return ptrToFirstLink->value;
}
rsvcSlistItem
rsvcSlist::lastElement (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
assert(ptrToFirstLink != 0);
// loop through until last element
rsvcSlistLink *p = 0;
for (p = ptrToFirstLink; p->ptrToNextLink; p = p->ptrToNextLink)
;
return p->value;
}
rsvcSlistItem
rsvcSlist::lastElement_i (void)
{
assert(ptrToFirstLink != 0);
// loop through until last element
rsvcSlistLink *p = 0;
for (p = ptrToFirstLink; p->ptrToNextLink; p = p->ptrToNextLink)
;
return p->value;
}
int
rsvcSlist::includes(rsvcSlistItem v)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// loop to test each element
for (rsvcSlistLink * p = ptrToFirstLink; p; p = p->ptrToNextLink)
if (v == p->value)
return 1;
// not found
return 0;
}
int
rsvcSlist::isEmpty (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// test to see if the list is empty
// list is empty if the pointer to the first link is null
return ptrToFirstLink == 0;
}
int
rsvcSlist::isEmpty_i (void) const
{
// test to see if the list is empty
// list is empty if the pointer to the first link is null
return ptrToFirstLink == 0;
}
void
rsvcSlist::removeFirst (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// make sure there is a first element
assert(ptrToFirstLink != 0);
// save pointer to the removed node
rsvcSlistLink * p = ptrToFirstLink;
// reassign the ptrToFirstLink node
ptrToFirstLink = p->ptrToNextLink;
// decrease the count
count_ --;
// recover memory used by the first element
delete p;
}
void
rsvcSlist::removeFirst_i (void)
{
// make sure there is a first element
assert(ptrToFirstLink != 0);
// save pointer to the removed node
rsvcSlistLink * p = ptrToFirstLink;
// reassign the ptrToFirstLink node
ptrToFirstLink = p->ptrToNextLink;
// decrease the count
count_ --;
// recover memory used by the first element
delete p;
}
//======================================================================
// class slink implementation
// No need to add any mutex protection since all member
// functions are called with lock held
//======================================================================
rsvcSlistLink*
rsvcSlistLink::insert(rsvcSlistItem val)
{
// insert a new link after current node
ptrToNextLink = new rsvcSlistLink(val, ptrToNextLink);
// check that allocation was successful
assert(ptrToNextLink != 0);
return ptrToNextLink;
}
rsvcSlistLink::rsvcSlistLink (rsvcSlistItem val, rsvcSlistLink * nxt)
:value(val), ptrToNextLink(nxt)
{
// create and initialize a new link field
}
rsvcSlistLink*
rsvcSlistLink::duplicate (void)
{
rsvcSlistLink * newlink;
// if there is a next field. copy remainder of list
if (ptrToNextLink != 0)
newlink = new rsvcSlistLink(value, ptrToNextLink->duplicate());
else
newlink = new rsvcSlistLink (value, 0);
// check that allocation was successful
assert(newlink != 0);
return newlink;
}
rsvcSlistLink*
rsvcSlistLink::next (void)
{
return ptrToNextLink;
}
rsvcSlistItem
rsvcSlistLink::data (void)
{
return value;
}
//======================================================================
// class listIterator implementation
//======================================================================
rsvcSlistIterator::rsvcSlistIterator(rsvcSlist & aList)
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
:theList(aList), lock_ ()
#else
:theList(aList)
#endif
{
// create and initialize a new list
init_i();
}
int
rsvcSlistIterator::init_i()
{
// set the iterator to the first element in the list
previousLink = 0;
currentLink = theList.ptrToFirstLink;
return currentLink != 0;
}
int
rsvcSlistIterator::init()
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// set the iterator to the first element in the list
previousLink = 0;
currentLink = theList.ptrToFirstLink;
return currentLink != 0;
}
rsvcSlistItem
rsvcSlistIterator::operator () (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// return value of current element
// check to see if there is a current element
assert(currentLink != 0);
// return value associated with current element
return currentLink->value;
}
int rsvcSlistIterator::operator ! (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// test for termination of the iterator
// if current link references a removed value,
// update current to point to next position
if (currentLink == 0)
if (previousLink != 0)
currentLink = previousLink->ptrToNextLink;
// now see if currentLink is valid
return currentLink != 0;
}
int rsvcSlistIterator::forward_i (void)
{
// move current pointer to nect element
// special processing if current link is deleted
if (currentLink == 0){
if (previousLink == 0)
currentLink = theList.ptrToFirstLink;
else
currentLink = previousLink->ptrToNextLink;
}
else{
// advance pointer
previousLink = currentLink;
currentLink = currentLink->ptrToNextLink;
}
// return true if we have a valid current element
return currentLink != 0;
}
int rsvcSlistIterator::operator ++()
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// move current pointer to nect element
// special processing if current link is deleted
if (currentLink == 0){
if (previousLink == 0)
currentLink = theList.ptrToFirstLink;
else
currentLink = previousLink->ptrToNextLink;
}
else{
// advance pointer
previousLink = currentLink;
currentLink = currentLink->ptrToNextLink;
}
// return true if we have a valid current element
return currentLink != 0;
}
void rsvcSlistIterator::operator = (rsvcSlistItem val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// modify value of current element
assert(currentLink != 0);
// modify value of the current link
currentLink->value = val;
}
void rsvcSlistIterator::removeCurrent_i (void)
{
// remove the current element from a list
// make sure there is a current element
assert(currentLink != 0);
// case 1, removing first element
if (previousLink == 0)
theList.ptrToFirstLink = currentLink->ptrToNextLink;
// case 2, not removing the first element
else
previousLink->ptrToNextLink = currentLink->ptrToNextLink;
// delete current node
delete currentLink;
// and set current pointer to null
currentLink = 0;
// decrease list count element
theList.count_ --;
}
void rsvcSlistIterator::removeCurrent (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// remove the current element from a list
// make sure there is a current element
assert(currentLink != 0);
// case 1, removing first element
if (previousLink == 0)
theList.ptrToFirstLink = currentLink->ptrToNextLink;
// case 2, not removing the first element
else
previousLink->ptrToNextLink = currentLink->ptrToNextLink;
// delete current node
delete currentLink;
// and set current pointer to null
currentLink = 0;
// decrease list count element
theList.count_ --;
}
void rsvcSlistIterator::addBefore(rsvcSlistItem val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard (lock_);
#endif
// add a new element to list before current value
// case 1, not at start
if (previousLink)
previousLink = previousLink->insert(val);
// case 2, at start of list
else{
theList.rsvcSlist::add(val);
previousLink = theList.ptrToFirstLink;
currentLink = previousLink->ptrToNextLink;
}
// increase the count
theList.count_ ++;
}
void rsvcSlistIterator::addAfter(rsvcSlistItem val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// a a new element to list after current value
// case 1, not at start
if (currentLink != 0)
currentLink->insert(val);
// case 2, at end of list
else if (previousLink != 0)
currentLink = previousLink->insert(val);
// case 3, start of list
else
theList.rsvcSlist::add(val);
// increase the count
theList.count_ ++;
}
int rsvcSlistIterator::searchSame(rsvcSlistItem &val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// search the list to find out whether we have this element
// if we do, move cursor to this element return 1
// if we don't return 0
init_i();
if (currentLink == 0){
// empty link
return 0;
}
while (currentLink != 0){
// advance pointer
if (currentLink->value == val)
break;
previousLink = currentLink;
currentLink = currentLink->ptrToNextLink;
}
// return true if we have a valid current element
return currentLink != 0;
}
//========================================================================
// Implementation of rsvcSlistCursor
// Implements of cursor without changing list
//========================================================================
rsvcSlistCursor::rsvcSlistCursor(const rsvcSlist & aList)
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
:theList(aList), lock_ ()
#else
:theList(aList)
#endif
{
// create and initialize a new list
init_i();
}
int
rsvcSlistCursor::init_i()
{
// set the iterator to the first element in the list
previousLink = 0;
currentLink = theList.ptrToFirstLink;
return currentLink != 0;
}
int
rsvcSlistCursor::init()
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// set the iterator to the first element in the list
previousLink = 0;
currentLink = theList.ptrToFirstLink;
return currentLink != 0;
}
rsvcSlistItem
rsvcSlistCursor::operator () (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// return value of current element
// check to see if there is a current element
assert(currentLink != 0);
// return value associated with current element
return currentLink->value;
}
int rsvcSlistCursor::operator ! (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// test for termination of the iterator
// if current link references a removed value,
// update current to point to next position
if (currentLink == 0)
if (previousLink != 0)
currentLink = previousLink->ptrToNextLink;
// now see if currentLink is valid
return currentLink != 0;
}
int rsvcSlistCursor::operator ++ (void)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// move current pointer to nect element
// special processing if current link is deleted
if (currentLink == 0){
if (previousLink == 0)
currentLink = theList.ptrToFirstLink;
else
currentLink = previousLink->ptrToNextLink;
}
else{
// advance pointer
previousLink = currentLink;
currentLink = currentLink->ptrToNextLink;
}
// return true if we have a valid current element
return currentLink != 0;
}
int rsvcSlistCursor::searchSame (rsvcSlistItem &val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// search the list to find out whether we have this element
// if we do, move cursor to this element return 1
// if we don't return 0
init_i();
if (currentLink == 0){
// empty link
return 0;
}
while (currentLink != 0){
// advance pointer
if (currentLink->value == val)
break;
previousLink = currentLink;
currentLink = currentLink->ptrToNextLink;
}
// return true if we have a valid current element
return currentLink != 0;
}
void rsvcSlistCursor::operator = (rsvcSlistItem )
{
// empty
}
//========================================================================
// Implementation of doubleEndedList
//========================================================================
rsvcDoubleEndedSlist::rsvcDoubleEndedSlist()
:rsvcSlist()
{
ptrToLastLink = 0;
}
rsvcDoubleEndedSlist::rsvcDoubleEndedSlist(const rsvcDoubleEndedSlist &v)
:rsvcSlist(v)
{
ptrToLastLink = v.ptrToLastLink;
}
void
rsvcDoubleEndedSlist::add(rsvcSlistItem val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
// add method needs to check one special case when the first element
// is added to the list
if (isEmpty_i()) {
// call parent method
rsvcSlist::add_i (val);
ptrToLastLink = ptrToFirstLink;
}
else{
// always add to the head
rsvcSlist::add_i(val);
}
}
void
rsvcDoubleEndedSlist::addToEnd (rsvcSlistItem val)
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
//add new value T to the end of the list
// if there is an end, add to it
if(ptrToLastLink != 0) {
ptrToLastLink = ptrToLastLink->insert(val);
count_ ++;
}
else {
assert (isEmpty_i ());
// call parent method
rsvcSlist::add_i (val);
ptrToLastLink = ptrToFirstLink;
}
}
void
rsvcDoubleEndedSlist::deleteAllValues()
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
//delete all values from the list
rsvcSlist::deleteAllValues_i();
ptrToLastLink = 0;
}
void
rsvcDoubleEndedSlist::removeFirst()
{
#if defined (RSVC_USE_THREAD) && defined (_REENTRANT)
cpMutexGuard guard(lock_);
#endif
//remove the first element from the list
// invoke the parent method
rsvcSlist::removeFirst_i();
// only do something if we removed last element
if(isEmpty_i())
ptrToLastLink = 0;
}
//========================================================================
// Implementation of queue
//========================================================================
rsvcQueue::rsvcQueue (void)
:rsvcDoubleEndedSlist ()
{
#ifdef _TRACE_OBJECTS
printf (" Create rsvcQueue Class Object\n");
#endif
}
rsvcSlistItem
rsvcQueue::front (void)
{
return firstElement ();
}
void
rsvcQueue::enqueue (rsvcSlistItem val)
{
// add new value val to the end of the list
// if there is an end, add to it
if(ptrToLastLink != 0) {
ptrToLastLink = ptrToLastLink->insert(val);
count_ ++;
}
else {
assert (isEmpty_i ());
// call parent method
rsvcSlist::add_i (val);
ptrToLastLink = ptrToFirstLink;
}
}
rsvcSlistItem
rsvcQueue::dequeue (void)
{
if (isEmpty_i ())
return 0;
// get first element
rsvcSlistItem result = firstElement_i ();
//remove the first element from the list
// invoke the parent method
rsvcSlist::removeFirst_i();
// only do something if we removed last element
if(isEmpty_i())
ptrToLastLink = 0;
return result;
}
@@ -0,0 +1,41 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
// RSVC Streamable class
//
// Author: Jie Chen
//
// Revision History:
// rsvcStreamable.cc,v
// Revision 1.1 1998/01/22 17:08:23 akers
// Addition of new NameServer
//
//
//
#include <stdio.h>
#include <rsvcErr.h>
#include "rsvcStreamable.h"
rsvcStreamable::rsvcStreamable (void)
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcStreamable Class Object\n");
#endif
// empty
}
rsvcStreamable::~rsvcStreamable (void)
{
#ifdef _TRACE_OBJECTS
printf ("Delete rsvcStreamable Class Object\n");
#endif
// empty
}
@@ -0,0 +1,167 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
// RSVC UDP Client
//
// Author: Jie Chen
//
// Revision History:
// rsvcUdpClient.cc,v
// Revision 1.2 1998/02/20 19:37:28 chen
// reset errno after using it (hpux) sometimes not resetting it
//
// Revision 1.1 1998/01/22 17:08:25 akers
// Addition of new NameServer
//
//
//
#include "rsvcUdpClient.h"
#include <errno.h>
rsvcUdpClient::rsvcUdpClient (void)
:fd_ (-1)
{
#ifdef _TRACE_OBJECTS
printf ("Create rsvcUdpClient Class Object\n");
#endif
}
rsvcUdpClient::~rsvcUdpClient (void)
{
#ifdef _TRACE_OBJECTS
printf ("Delete rsvcUdpClient Class Object\n");
#endif
if (fd_ != -1)
close (fd_);
}
int
rsvcUdpClient::connect (char* host, unsigned short port)
{
if ((openUdpPort (host, port)) == -1)
return RSVC_ERROR;
return RSVC_SUCCESS;
}
int
rsvcUdpClient::disconnect (void)
{
if (fd_ != -1)
close (fd_);
return RSVC_SUCCESS;
}
int
rsvcUdpClient::update (rsvcData& data)
{
if (fd_ == -1)
return RSVC_ERROR;
int nbytes;
int nw;
int status = RSVC_SUCCESS;
rsvcCbk cbkid (RSVC_SET, (long)0,
(long)5678, (long)fd_);
// create netdata
rsvcNetData netdata (data, cbkid);
if ((nbytes = streamData (netdata)) <= 0)
status = RSVC_ERROR;
else {
// block write
if ((nw = ::sendto (fd_, obuffer_, nbytes, 0, (sockaddr *)&udp_addr_,
sizeof (udp_addr_))) != nbytes) {
#ifdef _RSVC_DEBUG
printf ("rsvcUdpClient: wrote %d nbytes and expect to write %d bytes\n",
nw, nbytes);
printf ("rsvcUdpClient: errno is %d\n", errno);
perror ("client sendto error ");
// reset errno
errno = 0;
#endif
status = RSVC_ERROR;
}
}
return status;
}
int
rsvcUdpClient::streamData (rsvcNetData& data)
{
size_t datasize = data.streamSize ();
if (datasize > sizeof (obuffer_)) {
#ifdef _RSVC_DEBUG
printf ("rsvcUdpClient: Streamed data size %d is exceeding %d, resize\n",
datasize, sizeof(obuffer_));
#endif
return -1;
}
if (data.streamOut (obuffer_, datasize) != RSVC_SUCCESS) {
#ifdef _RSVC_DEBUG
printf ("rsvcUdpClient: rsvcNetData stream out error\n");
#endif
return -1;
}
return datasize;
}
int
rsvcUdpClient::openUdpPort (char* host, unsigned short port)
{
struct sockaddr_in my_addr;
struct hostent* hp = 0;
// initialize the server inet address structure
::memset (&udp_addr_, 0, sizeof (udp_addr_));
udp_addr_.sin_family = AF_INET;
udp_addr_.sin_port = htons (port);
hp = gethostbyname (host);
if (hp == 0) {
fprintf (stderr, "rsvcUdpClient: Cannot find ip address of host %s\n",
host);
return -1;
}
::memcpy (&udp_addr_.sin_addr, hp->h_addr, hp->h_length);
// open a socket
if ((fd_ = socket (AF_INET, SOCK_DGRAM, 0)) < 0) {
fprintf (stderr, "udp_open: cannot create socket\n");
fd_ = -1;
return -1;
}
// bind local address for us
::memset (&my_addr, 0, sizeof (my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = htonl (INADDR_ANY);
my_addr.sin_port = htons (0);
if (bind (fd_, (struct sockaddr *)&my_addr, sizeof (my_addr)) < 0) {
fprintf (stderr, "rsvcUdpClient : bind error\n");
close (fd_);
fd_ = -1;
return -1;
}
return 0;
}
@@ -0,0 +1,274 @@
#if !defined (_SIMPLE_SERVER_HANDLER_H_)
#define _SIMPLE_SERVER_HANDLER_H_
#include "cdevEventHandler.h"
#include "cdevAddr.h"
#include "cdevSocketConnector.h"
#include "cdevReactor.h"
#include "ErrorReporter.h"
#include "SocketUtil.h"
#include "fifo.h"
#include "clipMagicNumber.h"
#include "cdevMessageBinary.h"
#include "cdevMessage.h"
#include "ClientInfo.h"
const int _CDEV_CONNECTION_RETRIES = 5;
const int MAX_SERVERS = 1024;
extern FifoQueue results [MAX_SERVERS];
extern int completionCodes[MAX_SERVERS];
class DumpAllHandler : public cdevEventHandler,
public SocketReader,
public SocketWriter
{
protected:
char hostName [MAXHOSTNAMELEN + 1];
FifoQueue queue;
cdevSocketConnector stream;
int serverQuitFlag;
cdevReactor & Reactor;
int index;
ClientInfo info;
public:
DumpAllHandler (char * Host, unsigned short Port, cdevReactor & LocalReactor, int Index)
: info(),
SocketReader(CLIP_MAGIC_NUMBER),
SocketWriter(CLIP_MAGIC_NUMBER),
index(Index),
Reactor(LocalReactor),
serverQuitFlag(0)
{
cdevInetAddr addr;
hostName[0] = 0;
addr.set (Port, Host);
if(open(addr)!=0)
{
outputError(CDEV_SEVERITY_ERROR,
"DumpAllHandler::connect",
"Failed to connect to %s on port %i",
Host,
Port);
completionCodes[index]=-1;
}
completionCodes[index] = 0;
cdevData tagMap;
int * tags;
char ** ctags;
int ntags;
char * binary = NULL;
size_t binaryLen = 0;
cdevData::readTagTable(tags, ctags, ntags);
tagMap.insert(1, tags, ntags);
tagMap.insert(2, ctags, ntags);
delete tags;
delete ctags;
cdevMessageBinary packet0(index, 0, 0, 0, 0, CDEV_SERVER_OP, 0, 0,
NULL, "set ClientInfo", &info.getClientData(),
NULL, &tagMap);
packet0.streamOut(&binary, &binaryLen);
packet0.detachData();
enqueue(binary, binaryLen);
cdevMessageBinary packet1(index, 1, 0, 0, 0, CDEV_SERVER_OP, 0, 0,
NULL, "get ServerInfo", NULL, NULL, &tagMap);
packet1.streamOut(&binary, &binaryLen);
packet1.detachData();
enqueue(binary, binaryLen);
cdevMessageBinary packet2(index, 2, 0, 0, 0, CDEV_SERVER_OP, 0, 0,
NULL, "get ClientInfo", NULL, NULL, &tagMap);
packet2.streamOut(&binary, &binaryLen);
packet2.detachData();
enqueue(binary, binaryLen);
}
~DumpAllHandler (void)
{
if(completionCodes[index]!=1) completionCodes[index]=-1;
if(stream.getHandle()>0 && serverQuitFlag==0)
{
writeGoodbye();
}
if(reactor) reactor->extractHandler(this);
handleClose();
}
int open (const cdevAddr &addr)
{
int result = 0;
int count = 0;
result = stream.connect (addr);
if (result != -1)
{
if((result = Reactor.registerHandler(this, READ_MASK|WRITE_MASK|EXCEPT_MASK))==-1)
{
handleClose();
}
}
return result;
}
char * getHostName ( void )
{
if(*hostName==0)
{
cdevInetAddr addr;
if(stream.getRemoteAddress (addr)==0)
{
const char * ptr=addr.getHostName();
if(ptr) strncpy (hostName, ptr, MAXHOSTNAMELEN+1);
}
}
return hostName;
}
char * getName (void) const
{
return "DumpAllHandler";
}
int getHandle (void) const
{
return stream.getHandle();
}
void enqueue (char * buf, size_t len)
{
queue.enqueue(buf, len);
setMask(WRITE_MASK|EXCEPT_MASK);
}
void undequeue (char * buf, size_t len)
{
queue.undequeue(buf, len);
}
int dequeue (char **buf, size_t *len)
{
return queue.dequeue(buf, len);
}
int empty (void)
{
return queue.empty();
}
int handleClose (void)
{
stream.close();
return 0;
}
int handleInput (void)
{
int retval = 0;
char * buf = NULL;
size_t len = 0;
int result = 1;
while(result>0)
{
result = read(&buf, (int *)&len);
switch(result)
{
case SHUTDOWN_CODE:
outputError(CDEV_SEVERITY_INFO, (char *)getName(),
"Connection to %s terminated by client", getHostName());
retval = -1;
break;
case -1:
outputError(CDEV_SEVERITY_WARN, (char *)getName(),
"Error reading from connection to client %s", getHostName());
retval = -1;
break;
case 0:
break;
default:
{
cdevMessage *message = new cdevMessage;
unsigned transIndex = 0;
unsigned clientID = 0;
if(message->streamIn(buf, len)==0 &&
(clientID=message->getClientID())==index &&
(transIndex=message->getTransIndex())>0 &&
transIndex<3)
{
results[index].enqueue((void *)message);
if(transIndex==2) completionCodes[index] = 1;
}
else delete message;
}
break;
}
}
return retval;
}
int handleOutput (void)
{
int retval = 0;
char * buf = NULL;
size_t len = 0;
if(!writing() && dequeue(&buf, &len)==0)
{
int full = 0;
while(!full)
{
if(!(full = writeEnqueue(buf, len)))
{
delete buf;
full = dequeue(&buf, &len);
}
else undequeue(buf, len);
}
if(writeContinue()<0) retval = -1;
}
else if(writing())
{
if(writeContinue()<0) retval = -1;
}
if(retval!=0)
{
outputError(CDEV_SEVERITY_WARN, (char *)getName(),
"Error transmitting to %s", getHostName());
}
if(empty() && !writing())
{
setMask(READ_MASK|EXCEPT_MASK);
}
return retval;
}
int handleExcept (void)
{
stream.close();
serverQuitFlag=1;
return -1;
}
};
#endif /* _SIMPLE_SERVER_HANDLER_H_ */
@@ -0,0 +1,14 @@
ARCH = OS
SHOBJ = YES
include ../../include/makeinclude/Makefile.$(ARCH)
APPNAME = Name Server Query Application
LIBS = -L$(CDEVLIB) -lcdevGenericServer $(CDEVLIBS) $(OSLIBS)
BINARIES = $(CDEVBIN)/dumpServer
targets: $(BINARIES)
$(CDEVBIN)/dumpServer: $(OBJDIR)/dumpServer.o
$(LINK.cc) $^ $(LIBS) -o $@
@@ -0,0 +1,18 @@
.SUFFIXES: .cc .obj
APPNAME = Name Server Query Application
ARCH = WINNT-4.0
BINARIES = $(CDEVBIN)\dumpServer.exe
include ..\..\include\makeinclude\Makefile.WINNT-4.0
targets : $(BINARIES)
$(CDEVBIN)\dumpServer.exe : .exec\$(TARGETDIR)\dumpServer.obj
-@if exist $@ erase $@
@echo ^ ^ ^ ^ ^ ^ =^> Linking $(@F)
$(LINK) $(CDEVLIB)\cdev.lib $(CDEVLIB)\cdevGenericServer.lib \
$(LINK_EXE_FLAGS) /out:$@ $?
@echo ^ ^ ^ ^ ^ ^ ^ ^ ^ Done...
@@ -0,0 +1,16 @@
service rns {
tags {PV}
}
class RNS {
messages {
query rns;
get rns;
monitorOn rns;
monitorOff rns;
}
}
RNS :
NameServer
;
@@ -0,0 +1,705 @@
#include <cdevSystem.h>
#include <cdevRequestObject.h>
#include <cdevData.h>
#include <cdevDirectory.h>
#include "DumpAllHandler.h"
#include "cdevGenericServerTags.h"
FifoQueue results [MAX_SERVERS];
int completionCodes[MAX_SERVERS];
static char * NameServerDefinitionString =
"service rns { tags {PV} }\n\
class RNS { messages { query rns; get rns; monitorOn rns; monitorOff rns; } }\n\
RNS :\nNameServer\n;\n";
cdevReactor DumpAllReactor;
void ReportStandard ( char * Domain, char * Name, char * Server, int Port, int index );
void ReportBrief ( int index );
void ReportServerBrief ( cdevData & data );
void ReportClientBrief ( cdevData & data );
void ReportComplete ( int index );
void ReportServerComplete ( cdevData & data );
void ReportClientComplete ( cdevData & data );
void *getItem ( cdevData & data, char * tag, unsigned defaultItem);
void *getItem ( cdevData & data, char * tag, float defaultItem);
void *findItem ( cdevData & data, char * tag, cdevDataTypes type, size_t maxItems, void *defaultItem);
int main (int argc, char ** argv)
{
char * cdevNameServer = getenv("CDEV_NAME_SERVER");
cdevGenericServerTagDef tags;
typedef enum { STANDARD=0, BRIEF=1, COMPLETE=2, SIMPLE=4, BOGUS=8} ReportType;
ReportType reportType = STANDARD;
if(cdevNameServer==NULL)
{
fprintf(stdout, "-----------------------------------------------------------------------\n");
fprintf(stdout, "ERROR : CDEV_NAME_SERVER is not defined in the local environment.\n");
fprintf(stdout, " Set the CDEV_NAME_SERVER variable to indicate the host where \n");
fprintf(stdout, " the name server is running prior to executing this application.\n");
fprintf(stdout, "-----------------------------------------------------------------------\n");
fflush(stdout);
exit(1);
}
for(int x=1; x<argc; x++)
{
if(!strcmp(argv[x], "-a"))
{
if(reportType==STANDARD || reportType==COMPLETE) reportType = COMPLETE;
else {
fprintf(stderr, "ERROR: Only one of option -a, -b, or -s can be used\n");
fflush(stderr);
reportType = BOGUS;
}
}
else if(!strcmp(argv[x], "-b"))
{
if(reportType==STANDARD || reportType==BRIEF) reportType = BRIEF;
else {
fprintf(stderr, "ERROR: Only one of option -a, -b, or -s can be used\n");
fflush(stderr);
reportType = BOGUS;
}
}
else if(!strcmp(argv[x], "-s"))
{
if(reportType==STANDARD || reportType==SIMPLE) reportType = SIMPLE;
else {
fprintf(stderr, "ERROR: Only one of option -a, -b, or -s can be used\n");
fflush(stderr);
reportType = BOGUS;
}
}
else {
fprintf(stderr, "ERROR: Unknown argument %s passed to %s\n", argv[x], argv[0]);
fflush(stderr);
reportType = BOGUS;
}
if(reportType==BOGUS)
{
fprintf(stderr, "Format is : %s (-a OR -b OR -s)\n", argv[0]);
fprintf(stderr, " -a : print a complete report\n");
fprintf(stderr, " -b : print a brief report\n");
fprintf(stderr, " -s : print a simple report\n");
fprintf(stderr, "\n If neither option is specified\n");
fprintf(stderr, " then a standard report will be\n");
fprintf(stderr, " produced.\n");
fflush(stderr);
exit(1);
}
}
// *********************************************************************
// * Determine if the NameServer has been provided in the CDEVDDL file.
// * If not, add the NameServer to the cdevDirectory.
// *********************************************************************
cdevDirectory & nameServer = cdevSystem::defaultSystem().nameServer();
cdevData request;
cdevData reply;
memset(completionCodes, 0, sizeof(completionCodes));
request.insert("device", "NameServer");
if(nameServer.send("queryClass", request, reply)==CDEV_NOTFOUND)
{
request.insert("file", NameServerDefinitionString);
nameServer.send("update", request, NULL);
}
cdevData in, data;
cdevRequestObject * NameServerQuery = cdevRequestObject::attachPtr("NameServer", "query");
in.insert("queryMsg", "all");
if(NameServerQuery==NULL || NameServerQuery->send(in, data)!=CDEV_SUCCESS)
{
cdevSystem::defaultSystem().reportError(CDEV_SEVERITY_ERROR, "DumpServer", NULL, "Failed to communicate with Name Server");
return 0;
}
size_t cnt = 0, cnt1 = 0;
char ** domainPtr = NULL;
char ** serverPtr = NULL;
char ** hostPtr = NULL;
int * portPtr = NULL;
int * status = NULL;
if(data.getElems("domain", &cnt1)==CDEV_SUCCESS && cnt1>cnt) cnt = cnt1;
if(data.getElems("name", &cnt1)==CDEV_SUCCESS && cnt1>cnt) cnt = cnt1;
if(data.getElems("host", &cnt1)==CDEV_SUCCESS && cnt1>cnt) cnt = cnt1;
if(data.getElems("port", &cnt1)==CDEV_SUCCESS && cnt1>cnt) cnt = cnt1;
if(data.getElems("status", &cnt1)==CDEV_SUCCESS && cnt1>cnt) cnt = cnt1;
if(cnt>0)
{
domainPtr = new char *[cnt];
serverPtr = new char *[cnt];
hostPtr = new char *[cnt];
portPtr = new int [cnt];
status = new int [cnt];
memset(domainPtr, 0, sizeof(char *)*cnt);
memset(serverPtr, 0, sizeof(char *)*cnt);
memset(hostPtr, 0, sizeof(char *)*cnt);
memset(portPtr, 0, sizeof(int)*cnt);
memset(status, 0, sizeof(int)*cnt);
data.get("domain", domainPtr);
data.get("name", serverPtr);
data.get("host", hostPtr);
data.get("port", portPtr);
data.get("status", status);
int i, retry=0;
if(reportType==SIMPLE)
{
fprintf(stdout, "\n================================================================================\n");
fprintf(stdout, " THIS DATA OBTAINED FROM CDEV NAME SERVER AT : %s\n", cdevNameServer);
fprintf(stdout, "================================================================================\n\n");
fprintf(stdout, "\n-------------------------------------------------------------------------------\n");
fprintf(stdout, " DOMAIN NAME HOST PORT \n");
fprintf(stdout, "--------------------------------------------------------------------------------\n");
fflush(stdout);
for(i=0; i<cnt; i++)
{
if(status[i]==0)
{
fprintf(stdout, " %-24s%-24s%-24s% 5i\n", domainPtr[i], serverPtr[i], hostPtr[i], portPtr[i]);
fflush(stdout);
}
}
}
else {
DumpAllHandler ** handlers = new DumpAllHandler *[cnt];
for(i=0; i<cnt && i<MAX_SERVERS; i++)
{
if(status[i]==0) handlers[i]=new DumpAllHandler(hostPtr[i], portPtr[i], DumpAllReactor, i);
else completionCodes[i] = -1;
}
DumpAllReactor.handleEvents(0.01);
for(i=0; i<cnt && retry<100; )
{
if(completionCodes[i]==0)
{
DumpAllReactor.handleEvents(0.01);
retry++;
}
else i++;
}
fprintf(stdout, "\n================================================================================\n");
fprintf(stdout, " THIS DATA OBTAINED FROM CDEV NAME SERVER AT : %s\n", cdevNameServer);
fprintf(stdout, "================================================================================\n\n");
fflush(stdout);
for(i=0; i<cnt; i++)
{
if(completionCodes[i]!=1)
{
fprintf(stdout, "\nERROR : Can't talk to %s in domain %s on %s:%i\n", serverPtr[i], domainPtr[i], hostPtr[i], portPtr[i]);
fflush(stdout);
completionCodes[i] = -1;
}
}
for(i=0; i<cnt; i++)
{
if(completionCodes[i]==1)
{
if(reportType==STANDARD) ReportStandard(domainPtr[i], serverPtr[i], hostPtr[i], portPtr[i], i);
else if(reportType==BRIEF) ReportBrief(i);
else if(reportType==COMPLETE) ReportComplete(i);
}
}
}
}
else {
fprintf(stdout, "-----------------------------------------------------------------------\n");
fprintf(stdout, " No CDEV Servers are currently registered with the CDEV Name Server\n");
fprintf(stdout, " running on %s\n", cdevNameServer);
fprintf(stdout, "-----------------------------------------------------------------------\n");
fflush(stdout);
}
fprintf(stdout, "\n\n");
fflush(stdout);
return 0;
}
void ReportStandard ( char * Domain, char * Name, char * Server, int Port, int index )
{
static int headerDefined = 0;
cdevMessage *ServerInfo=NULL, *ClientInfo=NULL, *temp;
while(completionCodes[index]==1 && (temp = (cdevMessage *)results[index].dequeue())!=NULL)
{
if(temp->getTransIndex()==1)
{
if(ServerInfo!=NULL) delete ServerInfo;
ServerInfo = temp;
}
else if(temp->getTransIndex()==2)
{
if(ClientInfo!=NULL) delete ClientInfo;
ClientInfo = temp;
}
}
char domain[255];
char name [255];
char server[255];
char startTimeStr[255];
int port = 0;
float utilization = 0;
time_t startTime = 0;
int clientCnt = 0;
if(ServerInfo)
{
cdevData * data = ServerInfo->getData();
if(data->get("domain", domain, 255)!=CDEV_SUCCESS) strcpy(domain, Domain);
if(data->get("server", name, 255)!=CDEV_SUCCESS) strcpy(name, Name);
if(data->get("host", server, 255)!=CDEV_SUCCESS) strcpy(server, Server);
if(data->get("port", &port)!=CDEV_SUCCESS) port = Port;
if(data->get("pctcpu", &utilization)!=CDEV_SUCCESS) utilization = 0;
if(data->get("starttime", &startTime)!=CDEV_SUCCESS) startTime = time(NULL);
}
else {
strcpy(domain, Domain);
strcpy(name, Name);
strcpy(server, Server);
port = Port;
utilization = 0;
startTime = time(NULL);
}
sprintf(startTimeStr, "%s", startTime?ctime(&startTime):"UNKNOWN");
if(strchr(startTimeStr, '\n')!=NULL) *(strchr(startTimeStr, '\n'))=0;
if(!headerDefined)
{
fprintf(stdout, "\n--------------------------------------------------------------------------------\n");
fprintf(stdout, " DOMAIN NAME HOST PORT CPU%% START\n");
fprintf(stdout, "--------------------------------------------------------------------------------\n");
fflush(stdout);
headerDefined = 1;
}
fprintf(stdout, " %-17s%-17s%-17s% 5i %5.2f %s\n", domain, name, server, port, utilization*100.0, startTimeStr);
fflush(stdout);
if(ServerInfo) delete ServerInfo;
if(ClientInfo) delete ClientInfo;
}
void ReportBrief ( int index )
{
static int headerDefined = 0;
cdevMessage *ServerInfo=NULL, *ClientInfo=NULL, * temp;
while(completionCodes[index]==1 && (temp = (cdevMessage *)results[index].dequeue())!=NULL)
{
if(temp->getTransIndex()==1)
{
if(ServerInfo!=NULL) delete ServerInfo;
ServerInfo = temp;
}
else if(temp->getTransIndex()==2)
{
if(ClientInfo!=NULL) delete ClientInfo;
ClientInfo = temp;
}
}
cdevData * data;
if(ServerInfo && (data=ServerInfo->getData())!=NULL)
{
if(!headerDefined)
{
fprintf(stdout, "\n--------------------------------------------------------------------------------");
headerDefined = 1;
}
fprintf(stdout, "\n DOMAIN NAME HOST PORT CPU%% START\n");
fprintf(stdout, "--------------------------------------------------------------------------------\n");
fflush(stdout);
ReportServerBrief(*data);
delete ServerInfo;
}
else return;
if(ClientInfo && (data=ClientInfo->getData())!=NULL)
{
ReportClientBrief(*data);
delete ClientInfo;
}
}
void ReportServerBrief ( cdevData & data )
{
char *unknown = "UNKNOWN";
char *domain = (char *)findItem(data, "domain", CDEV_STRING, 1, unknown);;
char *server = (char *)findItem(data, "server", CDEV_STRING, 1, unknown);;
char *host = (char *)findItem(data, "host", CDEV_STRING, 1, unknown);;
int port = *(unsigned *)getItem(data, "port", 0U);
time_t starttime = *(unsigned *)getItem(data, "starttime", (unsigned)time(NULL));
float pctcpu = *(float *)getItem(data, "pctcpu", (float)0.0);
char startTimeStr[255];
sprintf(startTimeStr, "%s", starttime?ctime(&starttime):"UNKNOWN");
if(strchr(startTimeStr, '\n')!=NULL) *(strchr(startTimeStr, '\n'))=0;
fprintf(stdout, " %-17s%-17s%-17s% 5i %5.2f %s\n", domain, server, host, port, pctcpu*100.0, startTimeStr);
fflush(stdout);
return;
}
void ReportClientBrief ( cdevData & data )
{
static char * ClientInfoTags[]=
{
"username", "group", "uid", "gid", "pid", "program",
"commandline", "starttime", "connecttime", "host",
"os", "osversion", "osrelease", "machine", "shell",
"socket", "sendPktCnt", "recvPktCnt", "\0",
};
size_t i, j;
size_t nClients = 0;
data.getElems(ClientInfoTags[0], &nClients);
for(i=0; *ClientInfoTags[i]!=0; i++)
{
data.getElems(ClientInfoTags[i], &j);
if(j!=nClients)
{
fprintf(stdout, "ERROR : Inconsistent data in ClientInfo Structure\n");
fflush(stdout);
return;
}
}
if(nClients==0) return;
unsigned * connecttime = (unsigned *)findItem(data, "connecttime", CDEV_UINT32, nClients, NULL);
char ** username = NULL;
char * usernamePtr = NULL;
char ** program = NULL;
char * programPtr = NULL;
char ** host = NULL;
char * hostPtr = NULL;
if(nClients>1)
{
username = (char **) findItem(data, "username", CDEV_STRING, nClients, NULL);
program = (char **) findItem(data, "program", CDEV_STRING, nClients, NULL);
host = (char **) findItem(data, "host", CDEV_STRING, nClients, NULL);
}
else {
username = &(usernamePtr = (char *)findItem(data, "username", CDEV_STRING, nClients, NULL));
program = &(programPtr = (char *)findItem(data, "program", CDEV_STRING, nClients, NULL));
host = &(hostPtr = (char *)findItem(data, "host", CDEV_STRING, nClients, NULL));
}
if(username==NULL || program==NULL || connecttime==NULL || host==NULL)
{
fprintf(stdout, "ERROR : Inconsistent data in ClientInfo Structure\n");
fflush(stdout);
return;
}
for(i=0; i<nClients; i++)
{
char connectTimeStr[255];
if(connecttime[i]==0) connecttime[i] = (unsigned)time(NULL);
sprintf(connectTimeStr, "%s", connecttime[i]?ctime((time_t *)&connecttime[i]):"UNKNOWN");
if(strchr(connectTimeStr, '\n')!=NULL) *(strchr(connectTimeStr, '\n'))=0;
fprintf(stdout, "\n %s (%s on %s) connected at %s", program[i], username[i], host[i], connectTimeStr);
}
fprintf(stdout, "\n\n");
fflush(stdout);
return;
}
void ReportComplete ( int index )
{
cdevMessage *ServerInfo=NULL, *ClientInfo=NULL, * temp;
while(completionCodes[index]==1 && (temp = (cdevMessage *)results[index].dequeue())!=NULL)
{
if(temp->getTransIndex()==1)
{
if(ServerInfo!=NULL) delete ServerInfo;
ServerInfo = temp;
}
else if(temp->getTransIndex()==2)
{
if(ClientInfo!=NULL) delete ClientInfo;
ClientInfo = temp;
}
}
cdevData * data;
if(ServerInfo && (data=ServerInfo->getData())!=NULL)
{
ReportServerComplete(*data);
delete ServerInfo;
}
else return;
if(ClientInfo && (data=ClientInfo->getData())!=NULL)
{
ReportClientComplete(*data);
delete ClientInfo;
}
}
void ReportServerComplete ( cdevData & data )
{
char *unknown = "UNKNOWN";
char *username = (char *)findItem(data, "username", CDEV_STRING, 1, unknown);
char *group = (char *)findItem(data, "group", CDEV_STRING, 1, unknown);;
unsigned pid = *(unsigned *)getItem(data, "pid", 0U);
unsigned uid = *(unsigned *)getItem(data, "uid", 0U);
unsigned gid = *(unsigned *)getItem(data, "gid", 0U);
char *domain = (char *)findItem(data, "domain", CDEV_STRING, 1, unknown);;
char *server = (char *)findItem(data, "server", CDEV_STRING, 1, unknown);;
char *host = (char *)findItem(data, "host", CDEV_STRING, 1, unknown);;
int port = *(unsigned *)getItem(data, "port", 0U);
char *os = (char *)findItem(data, "os", CDEV_STRING, 1, unknown);;
char *osrelease = (char *)findItem(data, "osrelease", CDEV_STRING, 1, unknown);;
char *osversion = (char *)findItem(data, "osversion", CDEV_STRING, 1, unknown);;
char *machine = (char *)findItem(data, "machine", CDEV_STRING, 1, unknown);;
char *shell = (char *)findItem(data, "shell", CDEV_STRING, 1, unknown);;
char *program = (char *)findItem(data, "program", CDEV_STRING, 1, unknown);;
char *commandline = (char *)findItem(data, "commandline", CDEV_STRING, 1, unknown);;
time_t starttime = *(unsigned *)getItem(data, "starttime", (unsigned)time(NULL));
float pctcpu = *(float *)getItem(data, "pctcpu", (float)0.0);
unsigned datasize = *(unsigned *)getItem(data, "datasize", 0U);
unsigned sendPktCnt = *(unsigned *)getItem(data, "sendPktCnt", 0U);
unsigned recvPktCnt = *(unsigned *)getItem(data, "recvPktCnt", 0U);
char startTimeStr[255];
char userStr[255];
char groupStr[255];
char osStr[255];
sprintf (startTimeStr, "%s", starttime?ctime(&starttime):"UNKNOWN");
if(strchr(startTimeStr, '\n')!=NULL) *(strchr(startTimeStr, '\n'))=0;
sprintf (userStr, "%s (%i)", username, uid);
sprintf (groupStr, "%s (%i)", group, gid);
if(!strcmp(os, "UNKNOWN")) strcpy(osStr, os);
else sprintf (osStr, "%s %s %s %s", os, machine, osrelease, osversion);
fprintf(stdout, "-------------------------------------------------------------------------------\n");
fprintf(stdout, "DOMAIN : %-35s SERVER : %-35s\n", domain, server);
fprintf(stdout, "HOST : %-35s PORT : %i\n", host, port);
fprintf(stdout, "OWNER : %-35s GROUP : %-35s\n", userStr, groupStr);
fprintf(stdout, "OS : %-35s START : %-35s\n", osStr, startTimeStr);
fprintf(stdout, "SHELL : %-35s PROGRAM : %s (%i)\n", shell, program, pid);
fprintf(stdout, "%% CPU : %-35.2f SIZE : %i\n", pctcpu*100.0, datasize);
fprintf(stdout, "PKT SENT: %-35i PKT RECV: %-35i\n", sendPktCnt, recvPktCnt);
fprintf(stdout, "COMMAND : %s\n", commandline);
fflush(stdout);
};
void ReportClientComplete ( cdevData & data )
{
static char * ClientInfoTags[]=
{
"username", "group", "uid", "gid", "pid", "program",
"commandline", "starttime", "connecttime", "host",
"os", "osversion", "osrelease", "machine", "shell",
"socket", "sendPktCnt", "recvPktCnt", "\0",
};
size_t i, j;
size_t nClients = 0;
data.getElems(ClientInfoTags[0], &nClients);
for(i=0; *ClientInfoTags[i]!=0; i++)
{
data.getElems(ClientInfoTags[i], &j);
if(j!=nClients)
{
fprintf(stdout, "ERROR : Inconsistent data in ClientInfo Structure\n");
fflush(stdout);
return;
}
}
if(nClients==0) return;
unsigned * uid = (unsigned *)findItem(data, "uid", CDEV_UINT32, nClients, NULL);
unsigned * gid = (unsigned *)findItem(data, "gid", CDEV_UINT32, nClients, NULL);
unsigned * pid = (unsigned *)findItem(data, "pid", CDEV_UINT32, nClients, NULL);
unsigned * starttime = (unsigned *)findItem(data, "starttime", CDEV_UINT32, nClients, NULL);
unsigned * connecttime = (unsigned *)findItem(data, "connecttime", CDEV_UINT32, nClients, NULL);
unsigned * socket = (unsigned *)findItem(data, "socket", CDEV_UINT32, nClients, NULL);
unsigned * sendPktCnt = (unsigned *)findItem(data, "sendPktCnt", CDEV_UINT32, nClients, NULL);
unsigned * recvPktCnt = (unsigned *)findItem(data, "recvPktCnt", CDEV_UINT32, nClients, NULL);
char ** username = NULL;
char * usernamePtr = NULL;
char ** group = NULL;
char * groupPtr = NULL;
char ** program = NULL;
char * programPtr = NULL;
char ** commandline = NULL;
char * commandlinePtr = NULL;
char ** host = NULL;
char * hostPtr = NULL;
char ** os = NULL;
char * osPtr = NULL;
char ** osversion = NULL;
char * osversionPtr = NULL;
char ** osrelease = NULL;
char * osreleasePtr = NULL;
char ** machine = NULL;
char * machinePtr = NULL;
char ** shell = NULL;
char * shellPtr = NULL;
if(nClients>1)
{
username = (char **) findItem(data, "username", CDEV_STRING, nClients, NULL);
group = (char **) findItem(data, "group", CDEV_STRING, nClients, NULL);
program = (char **) findItem(data, "program", CDEV_STRING, nClients, NULL);
commandline = (char **) findItem(data, "commandline", CDEV_STRING, nClients, NULL);
host = (char **) findItem(data, "host", CDEV_STRING, nClients, NULL);
os = (char **) findItem(data, "os", CDEV_STRING, nClients, NULL);
osversion = (char **) findItem(data, "osversion", CDEV_STRING, nClients, NULL);
osrelease = (char **) findItem(data, "osrelease", CDEV_STRING, nClients, NULL);
machine = (char **) findItem(data, "machine", CDEV_STRING, nClients, NULL);
shell = (char **) findItem(data, "shell", CDEV_STRING, nClients, NULL);
}
else {
username = &(usernamePtr = (char *)findItem(data, "username", CDEV_STRING, nClients, NULL));
group = &(groupPtr = (char *)findItem(data, "group", CDEV_STRING, nClients, NULL));
program = &(programPtr = (char *)findItem(data, "program", CDEV_STRING, nClients, NULL));
commandline = &(commandlinePtr = (char *)findItem(data, "commandline", CDEV_STRING, nClients, NULL));
host = &(hostPtr = (char *)findItem(data, "host", CDEV_STRING, nClients, NULL));
os = &(osPtr = (char *)findItem(data, "os", CDEV_STRING, nClients, NULL));
osversion = &(osversionPtr = (char *)findItem(data, "osversion", CDEV_STRING, nClients, NULL));
osrelease = &(osreleasePtr = (char *)findItem(data, "osrelease", CDEV_STRING, nClients, NULL));
machine = &(machinePtr = (char *)findItem(data, "machine", CDEV_STRING, nClients, NULL));
shell = &(shellPtr = (char *)findItem(data, "shell", CDEV_STRING, nClients, NULL));
}
if(username==NULL || group==NULL || uid==NULL || gid==NULL || pid==NULL || program==NULL ||
commandline==NULL || starttime==NULL || connecttime==NULL || host==NULL || os==NULL ||
osversion==NULL || osrelease==NULL || machine==NULL || shell==NULL || socket==NULL ||
sendPktCnt==NULL || recvPktCnt==NULL)
{
fprintf(stdout, "ERROR : Inconsistent data in ClientInfo Structure\n");
fflush(stdout);
return;
}
fprintf(stdout, "CLIENTS : %i Clients Attached\n", nClients);
for(i=0; i<nClients; i++)
{
char startTimeStr[255];
char connectTimeStr[255];
char architecture[255];
if(starttime[i]==0) starttime[i] = (unsigned)time(NULL);
if(connecttime[i]==0) connecttime[i] = (unsigned)time(NULL);
if(!strcmp(os[i], "UNKNOWN")) strcpy(architecture, "UNKNOWN");
else sprintf(architecture, "%s %s %s %s", os[i], machine[i], osversion[i], osrelease[i]);
sprintf(startTimeStr, "%s", starttime[i]?ctime((time_t *)&starttime[i]):"UNKNOWN");
sprintf(connectTimeStr, "%s", connecttime[i]?ctime((time_t *)&connecttime[i]):"UNKNOWN");
if(strchr(startTimeStr, '\n')!=NULL) *(strchr(startTimeStr, '\n'))=0;
if(strchr(connectTimeStr, '\n')!=NULL) *(strchr(connectTimeStr, '\n'))=0;
fprintf(stdout, " ---------------------------------------------------------------------\n");
fprintf(stdout, " OWNER : %s (%i)\n", username[i], uid[i]);
fprintf(stdout, " GROUP : %s (%i)\n", group[i], gid[i]);
fprintf(stdout, " PROGRAM : %s (%i)\n", program[i], pid[i]);
fprintf(stdout, " COMMAND : %s\n", commandline[i]);
fprintf(stdout, " START TIME : %s\n", startTimeStr);
fprintf(stdout, " CONNECT TIME : %s\n", connectTimeStr);
fprintf(stdout, " HOST : %s\n", host[i]);
fprintf(stdout, " ARCHITECTURE : %s\n", architecture);
fprintf(stdout, " SHELL : %s\n", shell[i]);
fprintf(stdout, " PACKETS SENT : %i\n", sendPktCnt[i]);
fprintf(stdout, " PACKETS READ : %i\n", recvPktCnt[i]);
fflush(stdout);
}
return;
}
void *getItem ( cdevData & data, char * tag, unsigned defaultItem)
{
int actualTag = 0;
size_t actualItems = 0;
static unsigned result;
result = defaultItem;
cdevData::tagC2I(tag, &actualTag);
if(actualTag!=0)
{
data.getElems(actualTag, &actualItems);
}
if(actualTag!=0 && actualItems==1)
{
data.get(actualTag, &result);
}
return (void *)&result;
}
void *getItem ( cdevData & data, char * tag, float defaultItem)
{
int actualTag = 0;
size_t actualItems = 0;
static float result;
result = defaultItem;
cdevData::tagC2I(tag, &actualTag);
if(actualTag!=0)
{
data.getElems(actualTag, &actualItems);
}
if(actualTag!=0 && actualItems==1)
{
data.get(actualTag, &result);
}
return (void *)&result;
}
void *findItem ( cdevData & data, char * tag, cdevDataTypes type, size_t maxItems, void * defaultItem)
{
int actualTag = 0;
cdevDataTypes actualDataType = CDEV_INVALID;
size_t actualItems = 0;
void * item = defaultItem;
cdevData::tagC2I(tag, &actualTag);
if(actualTag!=0)
{
data.getElems(actualTag, &actualItems);
actualDataType = data.getType(actualTag);
}
if(actualTag!=0 && actualDataType==type && actualItems>0 && actualItems<=maxItems)
{
data.find(actualTag, item);
}
return item;
}
+24
View File
@@ -0,0 +1,24 @@
ARCH = OS
SHOBJ = YES
include ../../include/makeinclude/Makefile.$(ARCH)
APPNAME = "Resource Name Server Test"
CXXEXTRA = -D_CDEV_MANAGE_SERVERS
LIBS = -L$(CDEVLIB) -lrsvc $(CDEVLIBS) $(OSLIBS)
BINARIES = $(BASEBIN)/rsvc_cdev_server $(BASEBIN)/rsvc_cdev_client $(BASEBIN)/rsvc_shutdown $(BASEBIN)/queryDataTest
targets: $(BINARIES)
$(BASEBIN)/rsvc_cdev_server: $(OBJDIR)/rsvc_cdev_server.o
$(LINK.cc) $^ $(LIBS) -o $@
$(BASEBIN)/rsvc_cdev_client: $(OBJDIR)/rsvc_cdev_client.o
$(LINK.cc) $^ $(LIBS) -o $@
$(BASEBIN)/rsvc_shutdown: $(OBJDIR)/rsvc_shutdown.o
$(LINK.cc) $^ $(LIBS) -o $@
$(BASEBIN)/queryDataTest: $(OBJDIR)/queryDataTest.o
$(LINK.cc) $^ $(LIBS) -o $@
@@ -0,0 +1,42 @@
.SUFFIXES: .cc .obj
APPNAME = Resource Name Server Test
ARCH = WINNT-4.0
SHOBJ = YES
BINARIES = $(BASEBIN)\rsvc_cdev_server.exe\
$(BASEBIN)\rsvc_cdev_client.exe\
$(BASEBIN)\rsvc_shutdown.exe\
$(BASEBIN)\queryDataTest.exe
include ..\..\include\makeinclude\Makefile.WINNT-4.0
targets : $(BINARIES)
$(BASEBIN)\rsvc_cdev_server.exe : .exec\$(TARGETDIR)\rsvc_cdev_server.obj
-@if exist $@ erase $@
@echo ^ ^ ^ ^ ^ ^ =^> Linking $(@F)
$(LINK) $(CDEVLIB)\cdev.lib $(CDEVLIB)\rsvc.lib \
$(LINK_EXE_FLAGS) /out:$@ $?
@echo ^ ^ ^ ^ ^ ^ ^ ^ ^ Done...
$(BASEBIN)\rsvc_cdev_client.exe : .exec\$(TARGETDIR)\rsvc_cdev_client.obj
-@if exist $@ erase $@
@echo ^ ^ ^ ^ ^ ^ =^> Linking $(@F)
$(LINK) $(CDEVLIB)\cdev.lib $(CDEVLIB)\rsvc.lib \
$(LINK_EXE_FLAGS) /out:$@ $?
@echo ^ ^ ^ ^ ^ ^ ^ ^ ^ Done...
$(BASEBIN)\rsvc_shutdown.exe : .exec\$(TARGETDIR)\rsvc_shutdown.obj
-@if exist $@ erase $@
@echo ^ ^ ^ ^ ^ ^ =^> Linking $(@F)
$(LINK) $(CDEVLIB)\cdev.lib $(CDEVLIB)\rsvc.lib \
$(LINK_EXE_FLAGS) /out:$@ $?
@echo ^ ^ ^ ^ ^ ^ ^ ^ ^ Done...
$(BASEBIN)\queryDataTest.exe : .exec\$(TARGETDIR)\queryDataTest.obj
-@if exist $@ erase $@
@echo ^ ^ ^ ^ ^ ^ =^> Linking $(@F)
$(LINK) $(CDEVLIB)\cdev.lib $(CDEVLIB)\rsvc.lib \
$(LINK_EXE_FLAGS) /out:$@ $?
@echo ^ ^ ^ ^ ^ ^ ^ ^ ^ Done...
@@ -0,0 +1,44 @@
#include "../cdev/rnsQueryCollector.h"
void populate1 ( rnsQueryCollector & collector )
{
cdevData data;
static int index = 0;
cdev_TS_STAMP ts;
ts.nsec = index;
ts.secPastEpoch = index;
char str[50];
sprintf(str, "I am the value - %i", index);
if(index%10==0) {}
else if(index%1==0) data.insert("value", str);
else data.insert("value", index);
data.insert("status", (short) -index);
data.insert("severity", (unsigned short) index);
if(index%1==0) data.insert("controlLow", (double)((double)index)+0.5);
if(index%2==0) data.insert("controlHigh", (float)(((float)index)+0.25));
if(index%3==0) data.insert("displayLow", (long)-(index+10000));
if(index%4==0) data.insert("displayHigh", (unsigned long)index+10000);
data.insert("time", ts);
data.insert("alarmHigh", (unsigned char *)str, 50);
if((index+1)%200==0) data.insert("alarmLow", (unsigned char)index);
collector.collect(data);
index++;
}
int main()
{
cdevData data;
char flat[50];
memset(flat, 0, sizeof(char));
rnsQueryCollector collector(data);
data.insert("controlLow", (unsigned char *)flat, 50);
for(int i=0; i<200; i++) populate1(collector);
data.asciiDump();
}
@@ -0,0 +1,87 @@
// simple example program for cdev client to monitor cdev servers
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <rsvcClient.h>
static void getServerCallback (int status, void* /* arg */, rsvcData* data)
{
if (status == RSVC_SUCCESS) {
printf ("Get server success\n");
data->asciiDump ();
}
else
printf ("cannot get server info\n");
}
static void qcallback (int status, void* /* arg */, rsvcData* data)
{
printf ("---------------------Query callback is called\n");
if (status == RSVC_INCOMPLETE) {
printf ("Single data entry is here\n");
data->asciiDump ();
}
else if (status == RSVC_SUCCESS) {
printf ("Query finished\n");
data->asciiDump ();
}
else
printf ("Query error\n");
printf ("---------------------Query finished\n");
}
static void monitorServerCallback (int status, void* /* arg */, rsvcData* data)
{
if (status == RSVC_SUCCESS) {
printf (">>>>>>>>>>monitor server callback called<<<<<<<<<<<<<<<<\n");
data->asciiDump ();
printf ("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
}
else if (status == RSVC_CBK_FINISHED) {
printf ("server has been deleted\n");
}
else
printf ("server monitor callback has status %d\n", status);
}
int main (int argc, char** argv)
{
if (argc < 4) {
fprintf (stderr, "Usage: %s servername domain rsvcserverhost rsvcserverport\n");
exit (1);
}
rsvcClient client;
if (client.connect (argv[3], atoi (argv[4])) != RSVC_SUCCESS) {
fprintf (stderr, "cannot connect to rsvc server\n");
exit (1);
}
rsvcData serverinfo;
serverinfo.insert ("name", argv[1]);
serverinfo.insert ("domain", argv[2]);
if (client.getValue ("cdevServers", serverinfo,
getServerCallback, 0) != RSVC_SUCCESS) {
fprintf (stderr, "cannot get server %s %s information\n",
argv[1], argv[2]);
exit (1);
}
if (client.query ("cdevServers", "all",
qcallback, 0) != RSVC_SUCCESS) {
fprintf (stderr, "cannot do query callback\n");
exit (1);
}
if (client.monitorValue ("cdevServers", serverinfo,
monitorServerCallback, 0) != RSVC_SUCCESS) {
fprintf (stderr, "cannot do monitor on server %s %s\n",
argv[1], argv[2]);
exit (1);
}
while (1) {
client.pendIO (5.0);
}
}
@@ -0,0 +1,74 @@
// simple program to demonstrate how a cdev server uses rsvc library
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <rsvcClient.h>
#include <rsvcUdpClient.h>
static void rsvcCallback (int status, void* /* arg */, rsvcData* /* data */)
{
if (status == RSVC_SUCCESS) {
printf ("register server success\n");
}
else
printf ("register server failed\n");
}
int main (int argc, char** argv)
{
rsvcData serverinfo;
rsvcData udpinfo;
if (argc < 4) {
fprintf (stderr, "Usage: %s name domain serverhost serverport\n", argv[0]);
exit (1);
}
char hostname[256];
gethostname (hostname, sizeof (hostname));
struct timeval tv;
gettimeofday (&tv, 0);
serverinfo.insert ("name", argv[1]);
serverinfo.insert ("domain", argv[2]);
serverinfo.insert ("host", hostname);
serverinfo.insert ("owner", "chen");
serverinfo.insert ("time", (long)tv.tv_sec);
serverinfo.insert ("port", (long)tv.tv_sec%10000);
serverinfo.insert ("pid", getpid ());
udpinfo.insert ("name", argv[1]);
udpinfo.insert ("domain", argv[2]);
rsvcClient client;
rsvcUdpClient udpclient;
if (client.connect (argv[3], atoi (argv[4]), 2.0) != RSVC_SUCCESS) {
fprintf (stderr, "Cannot connect to rsvc server\n");
exit (1);
}
if (udpclient.connect (argv[3], atoi (argv[4]) + 1024) != RSVC_SUCCESS) {
fprintf (stderr, "Cannot connect to udp port\n");
exit (1);
}
// register server information
if (client.insertValue ("cdevServers", serverinfo, rsvcCallback, 0, 1) !=
RSVC_SUCCESS) {
fprintf (stderr, "Cannot send server information to rsvc\n");
client.disconnect ();
udpclient.disconnect ();
exit (1);
}
int st = 0;
while (1) {
if ((st = client.pendIO (5.0)) != RSVC_SUCCESS && st != RSVC_TIMEOUT)
break;
if (udpclient.update (udpinfo) != RSVC_SUCCESS)
printf ("udp update failed\n");
}
}
@@ -0,0 +1,21 @@
// Simple program to shutdown the rsvcServer
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <rsvcClient.h>
int main (int argc, char** argv)
{
if (argc < 3) {
fprintf (stderr, "Usage: %s host port\n", argv[0]);
exit (1);
}
rsvcClient client;
if (client.connect (argv[1], atoi (argv[2])) != RSVC_SUCCESS) {
fprintf (stderr, "Cannot connect to rsvcServer\n");
exit (1);
}
client.shutdownServer ();
}
@@ -0,0 +1,31 @@
# Makefile for RSVC JAVA Package
.SUFFIXES: .class .java
JAVAC = javac
JAVACFLAGS = -O
CLASSOBJS = rsvcException.class \
rsvcDataTypes.class \
rsvcTimeStamp.class \
rsvcDataEntry.class \
rsvcData.class \
rsvcDataOutputStream.class \
rsvcDataInputStream.class \
rsvcConfig.class \
rsvcEvent.class \
rsvcEventHandler.class \
rsvcClient.class \
rsvcClientReader.class \
rsvcUdpClient.class \
rsvcDisplay.class \
rsvcClientTest.class \
rsvcServerTest.class
all: $(CLASSOBJS)
.java.class:
rm -f $@
$(JAVAC) $(JAVACFLAGS) $<
clean:
rm -f *~ core *.class
@@ -0,0 +1,32 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
//
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: header.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.1 1999/10/18 17:12:39 chen
// *** empty log message ***
//
// Revision 1.1.1.1 1999/09/07 15:29:10 chen
// CMLOG version 2.0
//
//
//
@@ -0,0 +1,639 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// Core part of rsvcClient Java Package
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcClient.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.1 1999/10/18 17:12:39 chen
// *** empty log message ***
//
//
//
import rsvcData;
import rsvcEvent;
import rsvcConfig;
import rsvcEventHandler;
import rsvcClientReader;
import java.io.*;
import java.net.*;
import java.util.*;
public final class rsvcClient
{
// connection flag
private boolean connected_ = false;
// Socket to the server
private Socket tcpsocket_ = null;
// server information
private String server_host_ = null;
private int server_port_ = 0;
// internal request id
private int eventid_ = 1234;
// internal client data reader
private rsvcClientReader reader_ = null;
// internal thread id for reader
private Thread readerthread_ = null;
// output stream
private OutputStream output_ = null;
/**
* Construct an empty rsvcClient object
*/
public rsvcClient ()
{
// empty
}
/**
* Override default finalize method.This allows Java virtual
* machine to clean up resource when this object is no longer
* needed.
*/
protected void finalize() throws Throwable
{
if (tcpsocket_ != null && connected_ == true) {
connected_ = false;
tcpsocket_.close ();
}
}
/**
* Connect to a server that is on a given host at a given port
*/
public synchronized void connect (String host, int port) throws UnknownHostException, IOException
{
try {
tcpsocket_ = new Socket (host, port);
}catch (UnknownHostException ue){
System.err.println (ue);
throw ue;
}catch (IOException e) {
System.err.println(e);
throw e;
}
// set connection flag
connected_ = true;
// cache server information
server_host_ = new String(host);
server_port_ = port;
OutputStream toutput = null;
try {
toutput = tcpsocket_.getOutputStream();
}catch (IOException e) {
System.err.println (e);
throw e;
}
output_ = toutput;
// create a single rsvcClient Data Reader and spawn a new thread
reader_ = new rsvcClientReader (this);
readerthread_ = new Thread (reader_);
readerthread_.start ();
}
/**
* Return underlying socket
*/
public Socket getSocket () throws NullPointerException
{
if (tcpsocket_ == null)
throw new NullPointerException ("Socket is invalid");
return tcpsocket_;
}
/**
* Return underlying reader thread
*/
public Thread getReaderThread () throws NullPointerException
{
if (readerthread_ == null)
throw new NullPointerException ("Reader Thread is not alive");
return readerthread_;
}
/**
* Disconnect from the server
*/
public synchronized void disconnect () throws IOException
{
if (tcpsocket_ == null || connected_ == false)
throw new IOException ("Socket is not connected to the server");
try {
tcpsocket_.close();
}catch (IOException e) {
throw e;
}
connected_ = false;
// remove all event handlers
reader_.cleanupEventHandlers ();
}
/**
* Is connection established
*/
public boolean connected ()
{
return connected_;
}
/**
* Register an event handler to handle disconnection event
*/
public synchronized boolean addDisconnectHandler (rsvcEventHandler handler)
{
return reader_.addDisconnectHandler (handler);
}
/**
* Handle server unexpected close
*/
public int handleClose ()
{
try {
tcpsocket_.close ();
} catch (IOException e) {
System.err.println (e);
connected_ = false;
return -1;
}
connected_ = false;
reader_.dispatchDiscEventHandlers ();
// clean up all callbacks
reader_.cleanupEventHandlers ();
return 0;
}
/**
* Create a memory based database with an event handler.
* Data coming back to the event handler contain table definition
*/
public rsvcEvent createMemDbase (String tablename, rsvcData data,
rsvcEventHandler handler) throws IOException
{
rsvcEvent id = null;
data.insert (rsvcConfig.RSVC_TABLE_NAME, tablename);
try {
id = sendCommand (rsvcConfig.RSVC_CREATE_MEMTABLE, data,
handler);
}catch (IOException e) {
throw e;
}
return id;
}
/**
* Open a database with a given name using an event handler.
* Data retured to the event handler contain definition of database
*/
public rsvcEvent openDatabase (String name, rsvcData data,
rsvcEventHandler handler) throws IOException
{
rsvcEvent id = null;
data.insert (rsvcConfig.RSVC_TABLE_NAME, name);
try {
id = sendCommand (rsvcConfig.RSVC_OPEN_DBASE, data,
handler);
}catch (IOException e) {
throw e;
}
return id;
}
/**
* Insert data into a database with a given name.
* The last argument 'overwrite = 1' selects whether to overwite
* existing items in the database.
* Data must match table definition returned from the openDatabase call.
*/
public rsvcEvent insertValue (String name, rsvcData data,
rsvcEventHandler handler,
boolean overwrite) throws IOException
{
rsvcEvent id = null;
data.insert (rsvcConfig.RSVC_TABLE_NAME, name);
if (overwrite == true) {
try {
id = sendCommand (rsvcConfig.RSVC_OVERWRITE, data,
handler);
}catch (IOException e) {
throw e;
}
}
else {
try {
id = sendCommand (rsvcConfig.RSVC_INSERT, data,
handler);
}catch (IOException e) {
throw e;
}
}
return id;
}
/**
* Get data out from the database with a given name.
* Outbound data either contain a tagged value to denote a key value
* such as : "id", "model+gold" or contain multiple tagged values that
* can be constructed into a key value
*/
public rsvcEvent getValue (String name, rsvcData data,
rsvcEventHandler handler) throws IOException
{
rsvcEvent id = null;
data.insert (rsvcConfig.RSVC_TABLE_NAME, name);
try {
id = sendCommand (rsvcConfig.RSVC_GET, data,
handler);
}catch (IOException e) {
throw e;
}
return id;
}
/**
* Delete a data item from the database with a given name.
* Outbound data either contain a tagged value to denote a key value
* such as : "id", "model+gold" or contain multiple tagged values that
* can be constructed into a key value
*/
public rsvcEvent delValue (String name, rsvcData data,
rsvcEventHandler handler) throws IOException
{
rsvcEvent id = null;
data.insert (rsvcConfig.RSVC_TABLE_NAME, name);
try {
id = sendCommand (rsvcConfig.RSVC_DEL, data,
handler);
}catch (IOException e) {
throw e;
}
return id;
}
/**
* Set value for a datum inside database with a given name.
* The outbound data item either contain a tagged value to denote
* a index value e.g.: "id", "model+gold"
* or contains multiple tagged values which can be constructed
* into a key value
* plus a subset of tagged values defined in the table definition
*/
public rsvcEvent setValue (String name, rsvcData data,
rsvcEventHandler handler) throws IOException
{
rsvcEvent id = null;
data.insert (rsvcConfig.RSVC_TABLE_NAME, name);
try {
id = sendCommand (rsvcConfig.RSVC_SET, data,
handler);
}catch (IOException e) {
throw e;
}
return id;
}
/**
* Monitor on a data item inside a database with a given name.
* Any changes to this item will trigger an event coming back.
* The outbound data either contain a tagged value to denote a index value
* Example: "id", "model+gold"
* or contains multiple tagged values which can be constructed
* into a key value.
*/
public rsvcEvent monitorValue (String name, rsvcData data,
rsvcEventHandler handler) throws IOException
{
rsvcEvent id = null;
data.insert (rsvcConfig.RSVC_TABLE_NAME, name);
try {
id = sendMonitor (rsvcConfig.RSVC_MONITOR_ON, data,
handler);
} catch (IOException e) {
throw e;
}
return id;
}
/**
* Monitor off a data inside a database with a given name
* Outbound data either contain a tagged value to denote a index value
* Example: "id", "model+gold"
* or contains multiple tagged values which can be constructed
* into a key value.
*/
public rsvcEvent monitorOffValue (String name, rsvcData data,
rsvcEvent mid) throws IOException
{
rsvcEvent id = null;
data.insert (rsvcConfig.RSVC_TABLE_NAME, name);
try {
id = sendMonitorOff (rsvcConfig.RSVC_MONITOR_OFF, data, mid);
} catch (IOException e) {
throw e;
}
return id;
}
/**
* monitor a single attribute of a data inside a database with a given name.
* any changes to this attribute will trigger an event.
* Data coming back to the event handler containing a whole data.
* Outbound data either contain a tagged value to denote a index value
* Example: "id", "model+gold"
* or contains multiple tagged values which can be constructed
* into a key value
*/
public rsvcEvent monitorAttr (String name, String attr, rsvcData data,
rsvcEventHandler handler) throws IOException
{
rsvcEvent id = null;
data.insert (rsvcConfig.RSVC_TABLE_NAME, name);
data.insert (rsvcConfig.RSVC_MONITOR_TAG, attr);
try {
id = sendMonitor (rsvcConfig.RSVC_MONITOR_ONATTR, data,
handler);
} catch (IOException e) {
throw e;
}
return id;
}
/**
* Stop monitoring a single attribute of a data inside a database.
* Outbound data either contain a tagged value to denote a index value
* Example: "id", "model+gold"
* or contains multiple tagged values which can be constructed
* into a key value .
*/
public rsvcEvent monitorOffAttr (String name, String attr, rsvcData data,
rsvcEvent mid) throws IOException
{
rsvcEvent id = null;
data.insert (rsvcConfig.RSVC_TABLE_NAME, name);
data.insert (rsvcConfig.RSVC_MONITOR_TAG, attr);
try {
id = sendMonitorOff (rsvcConfig.RSVC_MONITOR_OFFATTR, data,
mid);
} catch (IOException e) {
throw e;
}
return id;
}
/**
* query a particular database 'name'
* query msg can be like regular C logic expression for all
* attributes.
*/
public rsvcEvent query (String name, String qmsg,
rsvcEventHandler handler) throws IOException
{
rsvcEvent id = null;
rsvcData data = new rsvcData ();
data.insert (rsvcConfig.RSVC_TABLE_NAME, name);
data.insert (rsvcConfig.RSVC_QUERY_TAG, qmsg);
try {
id = sendCommand (rsvcConfig.RSVC_QUERY, data,
handler);
}catch (IOException e) {
throw e;
}
return id;
}
/**
* Monitor incoming entries inside database
* any insertion to a database will trigger an event
*/
public rsvcEvent monitorIncomingEntries (String name, rsvcData data,
rsvcEventHandler handler) throws IOException
{
rsvcEvent id = null;
data.insert (rsvcConfig.RSVC_TABLE_NAME, name);
try {
id = sendMonitor (rsvcConfig.RSVC_MONITOR_ENTRIES, data,
handler);
} catch (IOException e) {
throw e;
}
return id;
}
/**
* Stop monitoring the incoming entries inside database.
*/
public rsvcEvent monitorOffIncomingEntries (String name, rsvcData data,
rsvcEvent mid) throws IOException
{
rsvcEvent id = null;
data.insert (rsvcConfig.RSVC_TABLE_NAME, name);
try {
id = sendMonitorOff(rsvcConfig.RSVC_MONITOR_OFFENTRIES, data,
mid);
}catch (IOException e) {
throw e;
}
return id;
}
/**
* Generic monitor on command
*/
private synchronized rsvcEvent sendMonitor (int opcode, rsvcData data,
rsvcEventHandler handler) throws IOException
{
int status = rsvcConfig.RSVC_SUCCESS;
// create an event that is being shipped to server
rsvcEvent cbk = new rsvcEvent (data);
cbk.setEventid (eventid_);
cbk.setOpcode (opcode);
// write this event to server
int len = cbk.streamSize ();
// create a buffered data output
BufferedOutputStream boutput = new BufferedOutputStream (output_, len);
try {
cbk.streamOut (boutput);
}catch (IOException e) {
System.err.println (e);
status = rsvcConfig.RSVC_IOFAILED;
throw e;
}
if (status == rsvcConfig.RSVC_SUCCESS) {
try {
boutput.flush ();
}catch (IOException e) {
System.err.println (e);
status = rsvcConfig.RSVC_IOFAILED;
throw e;
}
}
if (status == rsvcConfig.RSVC_SUCCESS) {
cbk.setHandler (handler);
reader_.addMonitorEventHandler (eventid_, cbk);
}
eventid_ ++;
return cbk;
}
/**
* Generic monitor on command
*/
private synchronized rsvcEvent sendMonitorOff (int opcode, rsvcData data,
rsvcEvent monitorEvent) throws IOException
{
int status = rsvcConfig.RSVC_SUCCESS;
if (reader_.containsMonitorEvent (monitorEvent) != true) {
throw new IOException ("Monitor Off using an invalid event");
}
// create new event with differen opcode
rsvcEvent cbk = new rsvcEvent (monitorEvent);
cbk.setOpcode (opcode);
// write this event to server
int len = cbk.streamSize ();
// create a buffered data output
BufferedOutputStream boutput = new BufferedOutputStream (output_, len);
try {
cbk.streamOut (boutput);
}catch (IOException e) {
System.err.println (e);
status = rsvcConfig.RSVC_IOFAILED;
throw e;
}
if (status == rsvcConfig.RSVC_SUCCESS) {
try {
boutput.flush ();
}catch (IOException e) {
System.err.println (e);
status = rsvcConfig.RSVC_IOFAILED;
throw e;
}
}
return cbk;
}
/**
* Generic command call with ith an event handler.
* Data coming back to the event handler contain table definition
*/
private synchronized rsvcEvent sendCommand (int opcode, rsvcData data,
rsvcEventHandler handler) throws IOException
{
int status = rsvcConfig.RSVC_SUCCESS;
// create an event that is being shipped to server
rsvcEvent cbk = new rsvcEvent (data);
cbk.setEventid (eventid_);
cbk.setOpcode (opcode);
// write this event to server
int len = cbk.streamSize ();
// create a buffered data output
BufferedOutputStream boutput = new BufferedOutputStream (output_, len);
try {
cbk.streamOut (boutput);
}catch (IOException e) {
System.err.println (e);
status = rsvcConfig.RSVC_IOFAILED;
throw e;
}
if (status == rsvcConfig.RSVC_SUCCESS) {
try {
boutput.flush ();
}catch (IOException e) {
System.err.println (e);
status = rsvcConfig.RSVC_IOFAILED;
throw e;
}
}
if (status == rsvcConfig.RSVC_SUCCESS) {
cbk.setHandler (handler);
reader_.addCommandEventHandler (eventid_, cbk);
}
eventid_ ++;
return cbk;
}
}
@@ -0,0 +1,315 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// rsvcClient Reader that is reading data out of socket
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcClientReader.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.2 1999/12/14 15:38:15 chen
// Add scrollbar to display
//
// Revision 1.1 1999/10/18 17:12:39 chen
// *** empty log message ***
//
//
//
//
import java.io.*;
import java.net.*;
import java.util.*;
import rsvcData;
import rsvcEvent;
import rsvcEventHandler;
import rsvcClient;
public final class rsvcClientReader implements Runnable
{
// disconnection callback list (list of event handler)
private Vector discCbkList_ = null;
// all send/get command callback list
private Hashtable cmdCbkList_ = null;
// monitor callback list
private Hashtable monitorCbkTable_ = null;
// Input and output buffer
private DataInputStream input_ = null;
// Pointer back to rsvcClient
private rsvcClient client_;
/**
* Construct a rsvcClientReader from a established client object
*/
public rsvcClientReader (rsvcClient client)
{
client_ = client;
// create lists and a table for event handlers
discCbkList_ = new Vector ();
cmdCbkList_ = new Hashtable (20, (float)0.25);
monitorCbkTable_ = new Hashtable (20, (float)0.25);
InputStream tinput = null;
Socket socket = null;
try {
socket = client_.getSocket();
}catch (NullPointerException e) {
System.err.print (e);
System.exit (-1);
}
try {
tinput = socket.getInputStream();
}catch (IOException e) {
System.err.print (e);
System.exit (-1);
}
input_ = new DataInputStream (tinput);
}
/**
* Add an event handler to handle disconnection event.
* Return true if this event handler is registered successfully.
* Return false if this event handler is already here.
*/
public boolean addDisconnectHandler (rsvcEventHandler handler)
{
if (discCbkList_.contains (handler) == true)
return false;
discCbkList_.addElement (handler);
return true;
}
/**
* Clean up all event handlers
*/
public void cleanupEventHandlers ()
{
discCbkList_.removeAllElements ();
cmdCbkList_.clear ();
monitorCbkTable_.clear ();
}
/**
* Add an event handler to command event handler list
*/
public void addCommandEventHandler (int id,
rsvcEvent oevent)
{
// vector is thread safe
cmdCbkList_.put (new Integer(id), oevent);
}
/**
* Add an event handler to monitor event handler table
*/
public void addMonitorEventHandler (int id, rsvcEvent oevent)
{
// vector is thread safe
monitorCbkTable_.put (new Integer(id), oevent);
}
/**
* Find out whether a particular event is already in the
* monitor event handler table
*/
public boolean containsMonitorEvent (rsvcEvent event)
{
Integer key = new Integer (event.getEventid ());
return monitorCbkTable_.containsKey (key);
}
/**
* Dispatch all event handlers when the server goes down
*/
public void dispatchDiscEventHandlers ()
{
Enumeration list = discCbkList_.elements ();
rsvcEventHandler handler = null;
rsvcEvent event = new rsvcEvent ();
event.setStatus (rsvcConfig.RSVC_DISCONNECTED);
while (list.hasMoreElements ()) {
handler = (rsvcEventHandler)(list.nextElement());
handler.handleEvent (event);
}
}
public void run ()
{
// buffer for header
int headerlen = rsvcEvent.headerLen ();
byte[] header = new byte[headerlen];
ByteArrayInputStream bainput = new ByteArrayInputStream (header);
// buffer for payload
int datasize = 4096;
int prevsize = 4096;
byte[] payload = new byte[datasize];
ByteArrayInputStream plinput = new ByteArrayInputStream (payload);
// event data object
rsvcEvent event = new rsvcEvent ();
while (true) {
// read header
try {
input_.readFully (header);
}catch (IOException e) {
System.err.println ("Server is down");
client_.handleClose ();
break;
}
// reset input stream buffer
bainput.reset ();
try {
datasize = rsvcEvent.readHeader (bainput);
}catch (IOException e) {
System.err.println ("Receiving header error" + e);
client_.handleClose ();
break;
}
if (datasize > prevsize) {
datasize = 2*datasize;
prevsize = datasize;
payload = new byte[datasize];
plinput = new ByteArrayInputStream (payload);
}
// read raw bytes of length 'datasize'
try {
input_.readFully (payload, 0, datasize);
}catch (IOException e) {
System.err.println ("Server is down here");
client_.handleClose ();
break;
}
// convert above raw bytes into an event
plinput.reset ();
try {
event.streamIn (plinput);
}catch (IOException e) {
System.err.println ("Payload data format error: " + e);
client_.handleClose ();
break;
}
// dispatch this event to an appropriate destination
if (dispatchEvent (event) != 0) {
client_.handleClose ();
break;
}
}
System.out.println ("rsvcClientReader Thread is finished");
}
private int dispatchEvent (rsvcEvent event)
{
int op = event.getOpcode ();
int status = 0;
if (op < rsvcConfig.RSVC_MONITOR_ON)
// all simple command transaction events
status = dispatchCmdEventFromServer (event);
else if (op < rsvcConfig.RSVC_OP_UNKNOWN)
// all monitor events
status = dispatchMonitorEventFromServer (event);
else {
System.err.println ("rsvcClient: Invalid option code: " + String.valueOf(op));
status = -1;
}
return status;
}
private int dispatchCmdEventFromServer (rsvcEvent event)
{
Integer key = new Integer (event.getEventid());
int status = event.getStatus ();
Object obj = null;
rsvcEventHandler handler = null;
rsvcEvent oevent = null;
// retrieve object from event which has key value
obj = cmdCbkList_.get (key);
if (obj != null) {
oevent = (rsvcEvent)obj;
if (oevent.match (event) == false) {
System.err.println ("Incoming and outgoing events are not match");
return -1;
}
try {
handler = oevent.getHandler ();
} catch (NullPointerException e) {
System.err.println (e);
return -1;
}
handler.handleEvent (event);
if (status != rsvcConfig.RSVC_INCOMPLETE)
cmdCbkList_.remove (event);
}
else {
System.out.println ("rsvcClient: Event from server does not match");
}
return 0;
}
private int dispatchMonitorEventFromServer (rsvcEvent event)
{
Integer key = new Integer (event.getEventid ());
int status = event.getStatus();
Object obj = null;
rsvcEventHandler handler = null;
rsvcEvent oevent = null;
obj = monitorCbkTable_.get (key);
if (obj != null) {
oevent = (rsvcEvent)obj;
try {
handler = oevent.getHandler ();
}catch (NullPointerException e) {
System.err.println (e);
return -1;
}
handler.handleEvent (event);
if (status != rsvcConfig.RSVC_SUCCESS &&
status != rsvcConfig.RSVC_INCOMPLETE) {
// if an event is bad or finished, remove it
monitorCbkTable_.remove (event);
}
}
else if (status != rsvcConfig.RSVC_SUCCESS) {
System.out.println ("rsvcClient: monitor event from server does not match any");
System.out.println (event.toString());
}
return 0;
}
}
@@ -0,0 +1,110 @@
import java.io.*;
import java.util.*;
import java.net.*;
import rsvcClient;
import rsvcEventHandler;
import rsvcConfig;
public final class rsvcClientTest implements rsvcEventHandler
{
public rsvcClientTest ()
{
// empty
}
public static void main (String[] args)
{
if (args.length < 4) {
System.err.println ("Usage: rsvcClientTest servername domain host port");
System.exit (-1);
}
rsvcClientTest test = new rsvcClientTest ();
String host = args[2];
int port = Integer.valueOf (args[3]).intValue();
String server = args[0];
String domain = args[1];
rsvcClient client = new rsvcClient ();
try {
client.connect (host, port);
}catch (UnknownHostException ue) {
System.err.println (ue);
System.exit (-1);
}catch (IOException e) {
System.err.println (e);
System.exit (-1);
}
// outbound event stream
rsvcEvent oevent = null;
rsvcData serverinfo = new rsvcData ();
serverinfo.insert ("name", server);
serverinfo.insert ("domain", domain);
try {
oevent = client.getValue ("cdevServers", serverinfo,
test);
}catch (IOException e) {
System.err.println (e);
System.exit (-1);
}
try {
oevent = client.query ("cdevServers", "all",
test);
}catch (IOException e) {
System.err.println (e);
System.exit (-1);
}
try {
oevent = client.monitorValue ("cdevServers", serverinfo,
test);
}catch (IOException e) {
System.err.println (e);
System.exit (-1);
}
Thread readerThread = client.getReaderThread ();
try {
readerThread.join ();
} catch (InterruptedException e) {
System.err.println (e);
System.exit (-1);
}
}
public void handleEvent (rsvcEvent event)
{
int status = event.getStatus ();
int opcode = event.getOpcode ();
rsvcData data = event.getData ();
System.out.println ("Handle event is called with status :" + String.valueOf (status));
switch (opcode) {
case rsvcConfig.RSVC_GET:
System.out.println ("Get Value with result :");
break;
case rsvcConfig.RSVC_QUERY:
System.out.println ("Query Value with result :");
break;
default:
System.out.println ("Operation : " + String.valueOf (opcode));
}
if (status == rsvcConfig.RSVC_NOTFOUND)
System.out.println ("Found nothing");
if (status == rsvcConfig.RSVC_SUCCESS)
data.asciiDump ();
}
}
@@ -0,0 +1,169 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// RSVC Client Configuration (Must be compatiable to C++ side)
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcConfig.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.1 1999/10/18 17:12:40 chen
// *** empty log message ***
//
//
//
public final class rsvcConfig
{
public static final int RSVC_SERVER_PORT = 10932;
public static final int RSVC_MAX_KEY_LEN = 256;
public static final String RSVC_KEY_NAME = "key";
public static final String RSVC_TABLE_NAME = "table";
public static final String RSVC_TABLE_NAME_EXT = ".def";
public static final String RSVC_KEY_TYPE_NAME = "keyType";
public static final String RSVC_KEY_EXP_NAME = "keyExp";
public static final String RSVC_MONITOR_TAG = "monitorOn";
public static final String RSVC_QUERY_TAG = "query";
public static final int RSVC_CACHE_MAX = 20;
public static final int RSVC_CACHE_LF = 5;
public static final int RSVC_RLIMIT_NOFILE = 256;
public static final int RSVC_UDP_BUFFER_SIZE = 4096;
public static final int RSVC_OP_UNKNOWN = 2000;
public static final int RSVC_CREATE_TABLE = 1000;
public static final int RSVC_CREATE_MEMTABLE = 1001;
public static final int RSVC_OPEN_DBASE = 1002;
public static final int RSVC_GET = 1010;
public static final int RSVC_SET = 1011;
public static final int RSVC_DEL = 1012;
public static final int RSVC_INSERT = 1013;
public static final int RSVC_OVERWRITE = 1014;
public static final int RSVC_QUERY = 1020;
public static final int RSVC_MONITOR_ON = 1500;
public static final int RSVC_MONITOR_ONATTR = 1501;
public static final int RSVC_MONITOR_OFF = 1600;
public static final int RSVC_MONITOR_OFFATTR = 1601;
public static final int RSVC_MONITOR_ENTRIES = 1650;
public static final int RSVC_MONITOR_OFFENTRIES = 1651;
public static final int RSVC_SERVER_EXIT = 1700;
public static final int RSVC_DATA_IN_MEMORY = 1;
public static final int RSVC_DATA_ON_DISK = 2;
// database name
public static final String _RSVC_CDEV_SERVERS = "cdevServers";
// key name
public static final String _RSVC_CDEV_SERVERS_KEY = "svcid" ;
// if we do not see a server for 30 seconds, we assume it is dead
public static final int RSVC_CDEV_SERVER_TKO = 30;
// frequency of scanning server database
public static final int RSVC_CDEV_SCAN_PERIOD = 10;
// the following are error status from server
/* Failure of function is non-consequential */
public static final int RSVC_WARNING = -2;
/* Errors that are not in any categories */
public static final int RSVC_ERROR = -1;
/* public static final int RSVC success */
public static final int RSVC_SUCCESS = 0;
/* invalid public static final int RSVC objects */
public static final int RSVC_INVALIDOBJ = 1;
/* invalid argument passed to public static final int RSVC calls */
public static final int RSVC_INVALIDARG = 2;
/* wrong service during dynamic loading */
public static final int RSVC_INVALIDSVC = 3;
/* operation is unsupported (collection) */
public static final int RSVC_INVALIDOP = 4;
/* not connected to low network service */
public static final int RSVC_NOTCONNECTED = 5;
/* low level network service IO failed */
public static final int RSVC_IOFAILED = 6;
/* conflicts of data types or tags */
public static final int RSVC_CONFLICT = 7;
/* public static final int RSVC cannot find user request */
/* (public static final int RSVCData) */
public static final int RSVC_NOTFOUND = 8;
/* time out */
public static final int RSVC_TIMEOUT = 9;
/* public static final int RSVCData conversion error */
public static final int RSVC_CONVERT = 10;
/* value out of range for device attribute */
public static final int RSVC_OUTOFRANGE = 11;
/* insufficient access to perform request */
public static final int RSVC_NOACCESS = 12;
/* change in access permission of device */
public static final int RSVC_ACCESSCHANGED = 13;
/* channel has been disconnected */
public static final int RSVC_DISCONNECTED = 60;
/* channel has been reconnected */
public static final int RSVC_RECONNECTED = 61;
/* overflow existing data buffer */
public static final int RSVC_OVERFLOW = 62;
/* the callback object will be deleted */
public static final int RSVC_DELETE_CALLBACK = 70;
/* data has no key in the data */
public static final int RSVC_NOKEY = 80;
/* connection timeout */
public static final int RSVC_CONN_TIMEOUT = 82;
/* messages have been filtered */
public static final int RSVC_FILTERED = 83;
/* no filtering applied */
public static final int RSVC_NOFILTERING = 84;
/* message is dropped */
public static final int RSVC_DROPPED = 85;
/* TCP io is bad file descriptor */
public static final int RSVC_BADIO = 86;
/* data flow will coming (unfinished) */
public static final int RSVC_INCOMPLETE = 88;
/* callback finished (monitor off) */
public static final int RSVC_CBK_FINISHED = 89;
/* query callback is paused */
public static final int RSVC_PAUSED = 90;
/* query message syntax error */
public static final int RSVC_QUERYMSG_ERR = 91;
/* Request object state values */
/* request object is connected to device */
public static final int RSVC_STATE_CONNECTED = 0;
/* request object is not connected */
public static final int RSVC_STATE_NOTCONNECTED = 1;
/* request object is invalid */
public static final int RSVC_STATE_INVALID = 2;
/* Request object access values */
/* no access to specified attribute */
public static final int RSVC_ACCESS_NONE = 0;
/* read-only access to attribute */
public static final int RSVC_ACCESS_READONLY = 1;
/* read-write access to attribute */
public static final int RSVC_ACCESS_WRITE = 2;
/* public static final int RSVCError class severity codes */
/* informative message */
public static final int RSVC_SEVERITY_INFO = 0;
/* warning message */
public static final int RSVC_SEVERITY_WARN = 1;
/* error message */
public static final int RSVC_SEVERITY_ERROR = 2;
/* severe or fatal error message */
public static final int RSVC_SEVERITY_SEVERE = 3;
public static final int RSVC_IOERROR = 6;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,870 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// rsvcDataEntry Class Which is contained inside rsvcData
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcDataEntry.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.1 1999/10/18 17:12:40 chen
// *** empty log message ***
//
//
//
//
import java.io.IOException;
import rsvcDataTypes;
import rsvcTimeStamp;
import rsvcDataOutputStream;
public final class rsvcDataEntry
{
private String tag_;
private short type_;
private short ndims_;
private int nelems_;
private Number []data_;
private String []sdata_;
/**
* Construct an empty data entry
*/
public rsvcDataEntry ()
{
tag_ = null;
type_ = rsvcDataTypes.RSVC_INVALID;
ndims_ = -1;
nelems_ = 0;
}
/**
* Construct a tagged data entry from a double value
*/
public rsvcDataEntry (String tag, double d)
{
tag_ = tag;
ndims_ = 0;
nelems_ = 1;
type_ = rsvcDataTypes.RSVC_DOUBLE;
data_ = new Double[1];
data_[0] = new Double (d);
}
/**
* Construct a tagged data entry from a float value
*/
public rsvcDataEntry (String tag, float f)
{
tag_ = tag;
ndims_ = 0;
nelems_ = 1;
type_ = rsvcDataTypes.RSVC_FLOAT;
data_ = new Float[1];
data_[0] = new Float(f);
}
/**
* Construct a tagged data entry from a long value
*/
public rsvcDataEntry (String tag, long l)
{
tag_ = tag;
ndims_ = 0;
nelems_ = 1;
type_ = rsvcDataTypes.RSVC_LONG;
data_ = new Long[1];
data_[0] = new Long(l);
}
/**
* Construct a tagged data entry from an integer value
*/
public rsvcDataEntry (String tag, int i)
{
tag_ = tag;
ndims_ = 0;
nelems_ = 1;
type_ = rsvcDataTypes.RSVC_INT32;
data_ = new Integer[1];
data_[0] = new Integer(i);
}
/**
* Construct a tagged data entry from a short value
*/
public rsvcDataEntry (String tag, short s)
{
tag_ = tag;
ndims_ = 0;
nelems_ = 1;
type_ = rsvcDataTypes.RSVC_INT16;
data_ = new Short[1];
data_[0] = new Short(s);
}
/**
* Construct a tagged data entry from a byte value
*/
public rsvcDataEntry (String tag, byte b)
{
tag_ = tag;
ndims_ = 0;
nelems_ = 1;
type_ = rsvcDataTypes.RSVC_BYTE;
data_ = new Byte[1];
data_[0] = new Byte(b);
}
/**
* Construct a tagged data entry from a string
*/
public rsvcDataEntry (String tag, String str)
{
tag_ = tag;
ndims_ = 0;
nelems_ = 1;
type_ = rsvcDataTypes.RSVC_STRING;
sdata_ = new String[1];
sdata_[0] = str;
}
/**
* Construct a tagged data entry from a time stamp
*/
public rsvcDataEntry (String tag, rsvcTimeStamp ts)
{
tag_ = tag;
ndims_ = 0;
nelems_ = 1;
type_ = rsvcDataTypes.RSVC_TIMESTAMP;
data_ = new rsvcTimeStamp[1];
data_[0] = ts;
}
/**
* Construct a tagged data entry from an array of byte
*/
public rsvcDataEntry (String tag, byte[] barray)
{
tag_ = tag;
ndims_ = 1;
nelems_ = barray.length;
type_ = rsvcDataTypes.RSVC_BYTE;
data_ = new Byte[nelems_];
for (int i = 0; i < nelems_; i++)
data_[i] = new Byte(barray[i]);
}
/**
* Construct a tagged data entry from an array of short
*/
public rsvcDataEntry (String tag, short[] sarray)
{
tag_ = tag;
ndims_ = 1;
nelems_ = sarray.length;
type_ = rsvcDataTypes.RSVC_INT16;
data_ = new Short[nelems_];
for (int i = 0; i < nelems_; i++)
data_[i] = new Short(sarray[i]);
}
/**
* Construct a tagged data entry from an array of integer
*/
public rsvcDataEntry (String tag, int[] iarray)
{
tag_ = tag;
ndims_ = 1;
nelems_ = iarray.length;
type_ = rsvcDataTypes.RSVC_INT32;
data_ = new Integer[nelems_];
for (int i = 0; i < nelems_; i++)
data_[i] = new Integer(iarray[i]);
}
/**
* Construct a tagged data entry from an array of long
*/
public rsvcDataEntry (String tag, long[] larray)
{
tag_ = tag;
ndims_ = 1;
nelems_ = larray.length;
type_ = rsvcDataTypes.RSVC_LONG;
data_ = new Long[nelems_];
for (int i = 0; i < nelems_; i++)
data_[i] = new Long(larray[i]);
}
/**
* Construct a tagged data entry from an array of float
*/
public rsvcDataEntry (String tag, float[] farray)
{
tag_ = tag;
ndims_ = 1;
nelems_ = farray.length;
type_ = rsvcDataTypes.RSVC_FLOAT;
data_ = new Float[nelems_];
for (int i = 0; i < nelems_; i++)
data_[i] = new Float (farray[i]);
}
/**
* Construct a tagged data entry from an array of double
*/
public rsvcDataEntry (String tag, double[] darray)
{
tag_ = tag;
ndims_ = 1;
nelems_ = darray.length;
type_ = rsvcDataTypes.RSVC_DOUBLE;
data_ = new Double[nelems_];
for (int i = 0; i < nelems_; i++)
data_[i] = new Double(darray[i]);
}
/**
* Construct a tagged data entry from an array of strings
*/
public rsvcDataEntry (String tag, String[] strs)
{
tag_ = tag;
ndims_ = 1;
nelems_ = strs.length;
type_ = rsvcDataTypes.RSVC_STRING;
sdata_ = new String[nelems_];
for (int i = 0; i < nelems_; i++)
sdata_[i] = strs[i];
}
/**
* Construct a tagged data entry from an array of time stamps
*/
public rsvcDataEntry (String tag, rsvcTimeStamp[] tsarray)
{
tag_ = tag;
ndims_ = 1;
nelems_ = tsarray.length;
type_ = rsvcDataTypes.RSVC_TIMESTAMP;
data_ = new rsvcTimeStamp[nelems_];
for (int i = 0; i < nelems_; i++)
data_[i] = tsarray[i];
}
/**
* Hash code for this data entry
*/
public int hashCode()
{
return tag_.hashCode();
}
/**
* Compare two data entries
*/
public boolean equals(rsvcDataEntry dobj)
{
if (dobj.type_ != type_ ||
dobj.nelems_ != nelems_ ||
dobj.ndims_ != ndims_ ||
dobj.tag_.equals(tag_) == false)
return false;
int i, j;
if (type_ != rsvcDataTypes.RSVC_INVALID) {
if (type_ == rsvcDataTypes.RSVC_STRING) {
for (i = 0; i < nelems_; i++) {
if (sdata_[i].equals (dobj.sdata_[i]) == false)
return false;
}
}
else {
for (i = 0; i < nelems_; i++) {
if (data_[i].equals (dobj.data_[i]) == false)
return false;
}
}
}
return true;
}
/**
* Retrieve internal data as a byte value
*/
public byte byteValue ()
{
if (type_ != rsvcDataTypes.RSVC_INVALID &&
type_ != rsvcDataTypes.RSVC_STRING)
return data_[0].byteValue();
else if (type_ == rsvcDataTypes.RSVC_STRING)
return Byte.valueOf(sdata_[0]).byteValue();
else throw new NumberFormatException("Uninitialize rsvcDataEntry Object");
}
/**
* Retrieve internal data as a short value
*/
public short shortValue ()
{
if (type_ != rsvcDataTypes.RSVC_INVALID &&
type_ != rsvcDataTypes.RSVC_STRING)
return data_[0].shortValue();
else if (type_ == rsvcDataTypes.RSVC_STRING)
return Short.valueOf(sdata_[0]).shortValue();
else throw new NumberFormatException("Uninitialize rsvcDataEntry Object");
}
/**
* Retrieve internal data as an integer value
*/
public int intValue ()
{
if (type_ != rsvcDataTypes.RSVC_INVALID &&
type_ != rsvcDataTypes.RSVC_STRING)
return data_[0].intValue();
else if (type_ == rsvcDataTypes.RSVC_STRING)
return Integer.valueOf(sdata_[0]).intValue();
else throw new NumberFormatException("Uninitialize rsvcDataEntry Object");
}
/**
* Retrieve internal data as a long value
*/
public long longValue ()
{
if (type_ != rsvcDataTypes.RSVC_INVALID &&
type_ != rsvcDataTypes.RSVC_STRING)
return data_[0].longValue();
else if (type_ == rsvcDataTypes.RSVC_STRING)
return Long.valueOf(sdata_[0]).longValue();
else throw new NumberFormatException("Uninitialize rsvcDataEntry Object");
}
/**
* Retrieve internal data as a float value
*/
public float floatValue ()
{
if (type_ != rsvcDataTypes.RSVC_INVALID &&
type_ != rsvcDataTypes.RSVC_STRING)
return data_[0].floatValue();
else if (type_ == rsvcDataTypes.RSVC_STRING)
return Float.valueOf(sdata_[0]).floatValue();
else throw new NumberFormatException("Uninitialize rsvcDataEntry Object");
}
/**
* Retrieve internal data as a double value
*/
public double doubleValue ()
{
if (type_ != rsvcDataTypes.RSVC_INVALID &&
type_ != rsvcDataTypes.RSVC_STRING)
return data_[0].doubleValue();
else if (type_ == rsvcDataTypes.RSVC_STRING)
return Double.valueOf(sdata_[0]).doubleValue();
else throw new NumberFormatException("Uninitialize rsvcDataEntry Object");
}
/**
* Retrieve internal data as a string
*/
public String stringValue ()
{
if (type_ != rsvcDataTypes.RSVC_INVALID &&
type_ != rsvcDataTypes.RSVC_STRING)
return String.valueOf (data_[0]);
else if (type_ == rsvcDataTypes.RSVC_STRING)
return sdata_[0];
else throw new NumberFormatException("Uninitialize rsvcDataEntry Object");
}
/**
* Retrieve internal data as an array of byte
*/
public byte[] byteArray ()
{
int i;
if (type_ != rsvcDataTypes.RSVC_INVALID &&
type_ != rsvcDataTypes.RSVC_STRING) {
byte[] barray = new byte[nelems_];
for (i = 0; i < nelems_; i++)
barray[i] = data_[i].byteValue();
return barray;
}
else if (type_ == rsvcDataTypes.RSVC_STRING) {
byte[] barray = new byte[nelems_];
for (i = 0; i < nelems_; i++)
barray[i] = Byte.valueOf(sdata_[i]).byteValue();
return barray;
}
else throw new NumberFormatException("Uninitialize rsvcDataEntry Object");
}
/**
* Retrieve internal data as an array of short
*/
public short[] shortArray ()
{
int i;
if (type_ != rsvcDataTypes.RSVC_INVALID &&
type_ != rsvcDataTypes.RSVC_STRING) {
short[] sarray = new short[nelems_];
for (i = 0; i < nelems_; i++)
sarray[i] = data_[i].shortValue();
return sarray;
}
else if (type_ == rsvcDataTypes.RSVC_STRING) {
short[] sarray = new short[nelems_];
for (i = 0; i < nelems_; i++)
sarray[i] = Short.valueOf(sdata_[i]).shortValue();
return sarray;
}
else throw new NumberFormatException("Uninitialize rsvcDataEntry Object");
}
/**
* Retrieve internal data as an array of integer
*/
public int[] intArray ()
{
int i;
if (type_ != rsvcDataTypes.RSVC_INVALID &&
type_ != rsvcDataTypes.RSVC_STRING) {
int[] iarray = new int[nelems_];
for (i = 0; i < nelems_; i++)
iarray[i] = data_[i].intValue();
return iarray;
}
else if (type_ == rsvcDataTypes.RSVC_STRING) {
int[] iarray = new int[nelems_];
for (i = 0; i < nelems_; i++)
iarray[i] = Integer.valueOf(sdata_[i]).intValue();
return iarray;
}
else throw new NumberFormatException("Uninitialize rsvcDataEntry Object");
}
/**
* Retrieve internal data as an array of float
*/
public float[] floatArray ()
{
int i;
if (type_ != rsvcDataTypes.RSVC_INVALID &&
type_ != rsvcDataTypes.RSVC_STRING) {
float[] farray = new float[nelems_];
for (i = 0; i < nelems_; i++)
farray[i] = data_[i].floatValue();
return farray;
}
else if (type_ == rsvcDataTypes.RSVC_STRING) {
float[] farray = new float[nelems_];
for (i = 0; i < nelems_; i++)
farray[i] = Float.valueOf(sdata_[i]).floatValue();
return farray;
}
else throw new NumberFormatException("Uninitialize rsvcDataEntry Object");
}
/**
* Retrieve internal data as an array of double
*/
public double[] doubleArray ()
{
int i;
if (type_ != rsvcDataTypes.RSVC_INVALID &&
type_ != rsvcDataTypes.RSVC_STRING) {
double[] darray = new double[nelems_];
for (i = 0; i < nelems_; i++)
darray[i] = data_[i].doubleValue();
return darray;
}
else if (type_ == rsvcDataTypes.RSVC_STRING) {
double[] darray = new double[nelems_];
for (i = 0; i < nelems_; i++)
darray[i] = Double.valueOf(sdata_[i]).doubleValue();
return darray;
}
else throw new NumberFormatException("Uninitialize rsvcDataEntry Object");
}
/**
* Retrieve internal data as an array of long
*/
public long[] longArray ()
{
int i;
if (type_ != rsvcDataTypes.RSVC_INVALID &&
type_ != rsvcDataTypes.RSVC_STRING) {
long[] larray = new long[nelems_];
for (i = 0; i < nelems_; i++)
larray[i] = data_[i].longValue();
return larray;
}
else if (type_ == rsvcDataTypes.RSVC_STRING) {
long[] larray = new long[nelems_];
for (i = 0; i < nelems_; i++)
larray[i] = Long.valueOf(sdata_[i]).longValue();
return larray;
}
else throw new NumberFormatException("Uninitialize rsvcDataEntry Object");
}
/**
* Retrieve internal data as an array of strings
*/
public String[] stringArray ()
{
int i;
if (type_ != rsvcDataTypes.RSVC_INVALID &&
type_ != rsvcDataTypes.RSVC_STRING) {
String[] sarray = new String[nelems_];
for (i = 0; i < nelems_; i++)
sarray[i] = String.valueOf (data_[i]);
return sarray;
}
else if (type_ == rsvcDataTypes.RSVC_STRING) {
String[] sarray = new String[nelems_];
for (i = 0; i < nelems_; i++)
sarray[i] = sdata_[i];
return sarray;
}
else throw new NumberFormatException("Uninitialize rsvcDataEntry Object");
}
/**
*convert the data entry into a string representation
*/
public String toString ()
{
StringBuffer result = new StringBuffer();
int i, j;
if (type_ == rsvcDataTypes.RSVC_INVALID)
result.append ("Invalid DataEntry Object");
else {
result.append ("Key: ").append (tag_).append ("\n");
result.append ("Type: ").append (rsvcDataTypes.types[type_]).append("\n");
result.append ("NElems: ").append(nelems_).append("\n");
result.append ("Values: \n");
j = 0;
String[] sarray = stringArray();
for (i = 0; i < nelems_; i++) {
if (j == 0)
result.append ("\t");
result.append(sarray[i]).append(" ");
j++;
if (j >= 8) {
result.append ("\n");
j = 0;
}
}
}
return result.toString();
}
/**
* Provide an exact deep copy of this data entry
*/
public rsvcDataEntry copy ()
{
int i;
rsvcDataEntry de = new rsvcDataEntry();
de.type_ = type_;
de.nelems_ = nelems_;
de.ndims_ = ndims_;
if (tag_ != null)
de.tag_ = new String (tag_);
else
de.tag_ = null;
if (type_ != rsvcDataTypes.RSVC_INVALID) {
switch (type_) {
case rsvcDataTypes.RSVC_STRING:
de.sdata_ = new String[nelems_];
for (i = 0; i < nelems_; i++)
de.sdata_[i] = new String(sdata_[i]);
break;
case rsvcDataTypes.RSVC_BYTE:
de.data_ = new Byte[nelems_];
for (i = 0; i < nelems_; i++)
de.data_[i] = new Byte(data_[i].byteValue());
break;
case rsvcDataTypes.RSVC_INT16:
de.data_ = new Short[nelems_];
for (i = 0; i < nelems_; i++)
de.data_[i] = new Short(data_[i].shortValue());
break;
case rsvcDataTypes.RSVC_INT32:
de.data_ = new Integer[nelems_];
for (i = 0; i < nelems_; i++)
de.data_[i] = new Integer(data_[i].intValue());
break;
case rsvcDataTypes.RSVC_FLOAT:
de.data_ = new Float[nelems_];
for (i = 0; i < nelems_; i++)
de.data_[i] = new Float(data_[i].floatValue());
break;
case rsvcDataTypes.RSVC_DOUBLE:
de.data_ = new Double[nelems_];
for (i = 0; i < nelems_; i++)
de.data_[i] = new Double(data_[i].doubleValue());
break;
case rsvcDataTypes.RSVC_LONG:
de.data_ = new Long[nelems_];
for (i = 0; i < nelems_; i++)
de.data_[i] = new Long(data_[i].longValue());
break;
}
}
return de;
}
/**
* Return tag of this data entry
*/
public String getTag ()
{
return tag_;
}
/**
* Set tag to new tag
*/
public void setTag (String tag)
{
tag_ = tag;
}
/**
* Return data type in numeric value
*/
public short getType ()
{
return type_;
}
/**
* Return data type in Class
*/
public Class getClassType () throws ClassNotFoundException
{
if (type_ == rsvcDataTypes.RSVC_INVALID)
throw new ClassNotFoundException ("Invalid data entry object");
else {
if (type_ == rsvcDataTypes.RSVC_STRING)
return sdata_.getClass();
else
return data_.getClass();
}
}
/**
* Return dimensionality information
*/
public short getDimension ()
{
return ndims_;
}
/**
* Return number of elements
*/
public int getNumElements ()
{
return nelems_;
}
/**
* Return streamed data size for this data entry
*/
public int streamSize ()
{
int datasize = 0;
int i;
if (type_ == rsvcDataTypes.RSVC_INVALID)
return datasize;
// size of tag is fixed
datasize += rsvcDataOutputStream.streamSize (tag_,
rsvcDataTypes.RSVC_TAG_MAX_LEN);
// data type, dim, nelems
datasize += 3*rsvcDataOutputStream.streamSize ((int)1);
if (type_ == rsvcDataTypes.RSVC_STRING) {
if (nelems_ == 1)
datasize += rsvcDataOutputStream.streamSize (sdata_[0]);
else {
for (i = 0; i < nelems_; i++)
datasize += rsvcDataOutputStream.streamSize (sdata_[i]);
}
}
else if(type_ == rsvcDataTypes.RSVC_BYTE)
datasize += nelems_*rsvcDataOutputStream.streamSize ((byte)1);
else if(type_ == rsvcDataTypes.RSVC_INT16)
datasize += nelems_*rsvcDataOutputStream.streamSize ((short)1);
else if(type_ == rsvcDataTypes.RSVC_INT32)
datasize += nelems_*rsvcDataOutputStream.streamSize ((int)1);
else if(type_ == rsvcDataTypes.RSVC_FLOAT)
datasize += nelems_*rsvcDataOutputStream.streamSize ((float)1.0);
else if(type_ == rsvcDataTypes.RSVC_DOUBLE)
datasize += nelems_*rsvcDataOutputStream.streamSize ((double)1.0);
else if(type_ == rsvcDataTypes.RSVC_TIMESTAMP){
rsvcTimeStamp ts = new rsvcTimeStamp();
datasize += nelems_*rsvcDataOutputStream.streamSize (ts);
}
else if(type_ == rsvcDataTypes.RSVC_LONG)
datasize += nelems_*rsvcDataOutputStream.streamSize ((long)1);
return datasize;
}
/**
* Convert this data entry into a byte stream
*/
public void streamOut (rsvcDataOutputStream output) throws IOException
{
int i;
if (type_ != rsvcDataTypes.RSVC_INVALID) {
try {
output.write (tag_, rsvcDataTypes.RSVC_TAG_MAX_LEN);
}catch (IOException e) {
throw e;
}
try {
output.write (type_);
}catch (IOException e) {
throw e;
}
try {
output.write (ndims_);
}catch (IOException e) {
throw e;
}
// to make stream data compatible to output generated
// by C++ code
int numelems;
if (type_ == rsvcDataTypes.RSVC_STRING) {
if (ndims_ == 0)
numelems = sdata_[0].length() + 1;
else
numelems = nelems_;
}
else {
if (ndims_ == 0)
numelems = 0;
else
numelems = nelems_;
}
try {
output.write (numelems);
}catch (IOException e) {
throw e;
}
if (type_ == rsvcDataTypes.RSVC_STRING) {
for (i = 0; i < nelems_; i++) {
try {
output.write (sdata_[i]);
}catch (IOException e) {
throw e;
}
}
}
else if (type_ == rsvcDataTypes.RSVC_BYTE) {
for (i = 0; i < nelems_; i++) {
try {
output.write (data_[i].byteValue());
}catch (IOException e) {
throw e;
}
}
}
else if (type_ == rsvcDataTypes.RSVC_INT16) {
for (i = 0; i < nelems_; i++) {
try {
output.write (data_[i].shortValue());
}catch (IOException e) {
throw e;
}
}
}
else if (type_ == rsvcDataTypes.RSVC_INT32) {
for (i = 0; i < nelems_; i++) {
try {
output.write (data_[i].intValue());
}catch (IOException e) {
throw e;
}
}
}
else if (type_ == rsvcDataTypes.RSVC_LONG) {
for (i = 0; i < nelems_; i++) {
try {
output.write (data_[i].longValue());
}catch (IOException e) {
throw e;
}
}
}
else if (type_ == rsvcDataTypes.RSVC_FLOAT) {
for (i = 0; i < nelems_; i++) {
try {
output.write (data_[i].floatValue());
}catch (IOException e) {
throw e;
}
}
}
else if (type_ == rsvcDataTypes.RSVC_DOUBLE) {
for (i = 0; i < nelems_; i++) {
try {
output.write (data_[i].doubleValue());
}catch (IOException e) {
throw e;
}
}
}
else if (type_ == rsvcDataTypes.RSVC_TIMESTAMP) {
for (i = 0; i < nelems_; i++) {
try {
output.write ((rsvcTimeStamp)data_[i]);
}catch (IOException e) {
throw e;
}
}
}
}
}
}
@@ -0,0 +1,240 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// rsvcDataInputStream that converts a byte stream into a rsvcData
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcDataInputStream.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.1 1999/10/18 17:12:41 chen
// *** empty log message ***
//
//
//
import java.io.*;
import java.math.*;
public class rsvcDataInputStream
{
// for 32 bit machine
public static final int _RSVC_STREAM_BYTE_UNIT = 4;
/**
* Return a long word (32 bit) aligned size from original size
*/
public static final int _RSVC_RNDUP (int x)
{
return ((x + _RSVC_STREAM_BYTE_UNIT - 1)/_RSVC_STREAM_BYTE_UNIT)
* _RSVC_STREAM_BYTE_UNIT;
}
// underlying data output stream
private DataInputStream input = null;
/**
* Construct a data output stream
*/
public rsvcDataInputStream (InputStream stream)
{
try {
input = new DataInputStream (stream);
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* Read a single byte char from stream
*/
public byte readByte () throws IOException
{
int tmp;
try {
tmp = input.readInt ();
}catch (IOException e) {
throw e;
}
return (byte)tmp;
}
/**
* Read a value of short from the stream
*/
public short readShort () throws IOException
{
int tmp;
try {
tmp = input.readInt ();
}catch (IOException e) {
throw e;
}
return (short)tmp;
}
/**
* Read a value of int from stream
*/
public int readInt () throws IOException
{
int tmp;
try {
tmp = input.readInt ();
}catch (IOException e) {
throw e;
}
return tmp;
}
/**
* Read a value of long from stream
*/
public long readLong () throws IOException
{
long tmp;
try {
tmp = input.readLong ();
}catch (IOException e) {
throw e;
}
return tmp;
}
/**
* Read a value of float from stream
*/
public float readFloat () throws IOException
{
float tmp;
try {
tmp = input.readFloat ();
}catch (IOException e) {
throw e;
}
return tmp;
}
/**
* Read a value of double to stream
*/
public double readDouble () throws IOException
{
double tmp;
try {
tmp = input.readDouble ();
}catch (IOException e) {
throw e;
}
return tmp;
}
/**
* Read a string as series of byte using default encoding
*/
public String readString () throws IOException
{
int len, rlen, i;
// first find out str size
try {
len = input.readInt ();
}catch (IOException e) {
throw e;
}
// readout next bytes of strlen
byte[] tmp = new byte[len];
try {
input.readFully (tmp, 0, len);
}catch (IOException e) {
throw e;
}
// find out read length of this string by looking for the first 0
// in this byte array
rlen = 0;
for (i = 0; i < len; i++) {
if (tmp[i] == 0)
break;
}
rlen = i;
return new String (tmp, 0, rlen);
}
/**
* Read a series of byte
*/
public byte[] readBytes () throws IOException
{
int len;
try {
len = input.readInt();
}catch (IOException e){
throw e;
}
byte[] result = new byte[len];
try {
input.readFully (result, 0, len);
}catch (IOException e){
throw e;
}
return result;
}
/**
* Read a number of bytes: blocked until all bytes are read
*/
public byte[] readBytes (int len) throws IOException
{
byte[] result = new byte[len];
try {
input.readFully (result, 0, len);
}catch (IOException e){
throw e;
}
return result;
}
/**
* Read a time stamp from the stream
*/
public rsvcTimeStamp readTimeStamp () throws IOException
{
rsvcTimeStamp ts = new rsvcTimeStamp ();
try {
ts.secPastEpoch = input.readInt();
}catch (IOException e){
throw e;
}
try{
ts.nsec = input.readInt();
}catch (IOException e){
throw e;
}
return ts;
}
}
@@ -0,0 +1,416 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// rsvcDataOutputStream that converts a rsvcData into byte stream
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcDataOutputStream.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.1 1999/10/18 17:12:41 chen
// *** empty log message ***
//
//
//
import java.io.*;
public class rsvcDataOutputStream
{
// for 32 bit machine
public static final int _RSVC_STREAM_BYTE_UNIT = 4;
/**
* Return a long word (32 bit) aligned size from original size
*/
public static final int _RSVC_RNDUP (int x)
{
return ((x + _RSVC_STREAM_BYTE_UNIT - 1)/_RSVC_STREAM_BYTE_UNIT)
* _RSVC_STREAM_BYTE_UNIT;
}
/**
* Return size information for a single byte
*/
public static int streamSize (byte c)
{
return rsvcDataOutputStream._RSVC_RNDUP ((int)1);
}
/**
* Return size information for a short
*/
public static int streamSize (short c)
{
return rsvcDataOutputStream._RSVC_RNDUP ((int)2);
}
/**
* Return size information for a int
*/
public static int streamSize (int c)
{
return rsvcDataOutputStream._RSVC_RNDUP ((int)4);
}
/**
* Return size information for a long
*/
public static int streamSize (long c)
{
return rsvcDataOutputStream._RSVC_RNDUP ((int)8);
}
/**
* Return size information for a float
*/
public static int streamSize (float c)
{
return rsvcDataOutputStream._RSVC_RNDUP ((int)4);
}
/**
* Return size information for a double
*/
public static int streamSize (double c)
{
return rsvcDataOutputStream._RSVC_RNDUP ((int)8);
}
/**
* Return size information for a string
*/
public static int streamSize (String c)
{
return rsvcDataOutputStream.streamSize ((int)4) +
rsvcDataOutputStream._RSVC_RNDUP ((int)(c.length() + 1));
}
/**
* Return size information for a fix buffer of string
*/
public static int streamSize (String str, int buflen)
{
return rsvcDataOutputStream.streamSize (buflen) +
rsvcDataOutputStream._RSVC_RNDUP(buflen);
}
/**
* Return size information for a double
*/
public static int streamSize (rsvcTimeStamp ts)
{
return 2*rsvcDataOutputStream._RSVC_RNDUP ((int)4);
}
// underlying data output stream
private DataOutputStream out = null;
/**
* Construct a data output stream
*/
public rsvcDataOutputStream (OutputStream stream)
{
try {
out = new DataOutputStream (stream);
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* Return how many bytes have been written to this stream
*/
public final int size ()
{
return out.size ();
}
/**
* Write a single byte char to stream
*/
public void write (char c) throws IOException
{
int tmp = (int)c;
try {
out.writeInt (tmp);
}catch (IOException e) {
throw e;
}
}
/**
* Write a value of short to stream
*/
public void write (short c) throws IOException
{
int tmp = (int)c;
try {
out.writeInt (tmp);
}catch (IOException e) {
throw e;
}
}
/**
* Write a value of int to stream
*/
public void write (int c) throws IOException
{
try {
out.writeInt (c);
}catch (IOException e) {
throw e;
}
}
/**
* Write a value of float to stream
*/
public void write (float c) throws IOException
{
try {
out.writeFloat (c);
}catch (IOException e) {
throw e;
}
}
/**
* Write a value of double to stream
*/
public void write (double c) throws IOException
{
try {
out.writeDouble (c);
}catch (IOException e) {
throw e;
}
}
/**
* Write a value of long to stream
*/
public void write (long c) throws IOException
{
try {
out.writeLong (c);
}catch (IOException e) {
throw e;
}
}
/**
* Write a string as series of byte using default encoding
*/
public void write (String str) throws IOException
{
byte []barray = str.getBytes();
int len = barray.length + 1;
int rlen = rsvcDataOutputStream._RSVC_RNDUP (len);
// first write out how many bytes that follow
try {
out.writeInt (rlen);
}catch (IOException e) {
throw e;
}
// write out string as bytes
try {
out.writeBytes (str);
}catch (IOException e) {
throw e;
}
// write out remainder as 0
for (int i = 0; i < rlen - len + 1; i++) {
try {
out.writeByte (0);
}catch (IOException e) {
throw e;
}
}
}
/**
* Write a string as series of byte using default encoding
* to a maximum length len
*/
public void write (String str, int len) throws IOException
{
if (len % rsvcDataOutputStream._RSVC_STREAM_BYTE_UNIT != 0) {
throw new IOException ("Fix buffer len is not long word aligned");
}
byte []barray = str.getBytes();
if (barray.length >= len) {
// need last 0 for out string buffer
throw new IOException ("Overflow fix buffer");
}
// first write out how many bytes that follow
try {
out.writeInt (len);
}catch (IOException e) {
throw e;
}
// write out string as bytes
try {
out.writeBytes (str);
}catch (IOException e) {
throw e;
}
// write out remainder as 0
for (int i = 0; i < len - barray.length; i++) {
try {
out.writeByte (0);
}catch (IOException e) {
throw e;
}
}
}
/**
* Write a series of byte
*/
public void write (byte[] c) throws Exception
{
if (c == null) throw new NullPointerException();
int len = c.length;
int rlen = rsvcDataOutputStream._RSVC_RNDUP (len);
try {
out.writeInt (rlen);
}catch (IOException e){
throw e;
}
try {
out.write (c, 0, len);
}catch (IOException e){
throw e;
}
for (int i = 0; i < rlen - len; i++) {
try {
out.writeByte (0);
}catch (IOException e){
throw e;
}
}
}
/**
* Write out a time stamp to the stream
*/
public void write (rsvcTimeStamp ts) throws IOException
{
try {
out.writeInt (ts.secPastEpoch);
}catch (IOException e) {
throw e;
}
try {
out.writeInt (ts.nsec);
}catch (IOException e) {
throw e;
}
}
/**
* Write out Byte to the stream
*/
public void write (Byte c) throws IOException
{
try {
write (c.byteValue());
}catch (IOException e) {
throw e;
}
}
/**
* Write out Short to the stream
*/
public void write (Short c) throws IOException
{
try {
write (c.shortValue());
}catch (IOException e) {
throw e;
}
}
/**
* Write out Integer to the stream
*/
public void write (Integer c) throws IOException
{
try {
write (c.intValue());
}catch (IOException e) {
throw e;
}
}
/**
* Write out Float to the stream
*/
public void write (Float c) throws IOException
{
try {
write (c.floatValue());
}catch (IOException e) {
throw e;
}
}
/**
* Write out Double to the stream
*/
public void write (Double c) throws IOException
{
try {
write (c.doubleValue());
}catch (IOException e) {
throw e;
}
}
/**
* Flush data out calling underlying real data stream flush method
*/
public final void flush () throws IOException
{
try {
out.flush ();
}catch (IOException e) {
throw new IOException (e.toString());
}
}
}
@@ -0,0 +1,408 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// rsvc data package test
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcDataTest.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.1 1999/10/18 17:12:41 chen
// *** empty log message ***
//
//
//
//
import java.io.*;
import rsvcData;
public class rsvcDataTest
{
public static final byte bdata = 1;
public static final short sdata = 2;
public static final int idata = 3;
public static final long ldata = 4;
public static final float fdata = (float)5.0;
public static final double ddata = 6.0;
public static final String strdata = new String ("Hello World I am Here");
public static final String file = new String ("/home/chen/java/rsvc/test.dat");
public static final String coutputfile = new String ("/home/chen/java/rsvc/coutput.dat");
public static final String cinputfile = new String ("/home/chen/java/rsvc/cinput.dat");
static public void integerConvTest ()
{
// test array insert
int []iarray = new int[127];
for (int i = 0; i < 127; i++)
iarray[i] = i;
rsvcData data = new rsvcData ();
data.insert ("value", iarray);
// get data test
rsvcDataEntry de = data.get ("value");
// byte converstion
byte[] ba = de.byteArray ();
rsvcData data1 = new rsvcData ();
data1.insert ("value", ba);
de = data1.get ("value");
int []ia = de.intArray();
rsvcData data2 = new rsvcData();
data2.insert ("value", ia);
if (data.equals (data2))
System.out.print ("Integer -> Byte -> Integer OK\n");
else
System.out.print ("Integer -> Byte -> Integer Failed\n");
// short conversion
de = data.get ("value");
short[] sa = de.shortArray ();
rsvcData data3 = new rsvcData ();
data3.insert ("value", sa);
de = data3.get ("value");
ia = de.intArray ();
rsvcData data4 = new rsvcData();
data4.insert ("value", ia);
if (data.equals (data4))
System.out.print ("Integer -> Short -> Integer OK\n");
else
System.out.print ("Integer -> Short -> Integer Failed\n");
// long conversion
de = data.get ("value");
long[] la = de.longArray ();
rsvcData data5 = new rsvcData ();
data5.insert ("value", la);
de = data5.get ("value");
ia = de.intArray ();
rsvcData data6 = new rsvcData();
data6.insert ("value", ia);
if (data.equals (data6))
System.out.print ("Integer -> Long -> Integer OK\n");
else
System.out.print ("Integer -> Long -> Integer Failed\n");
// float conversion
de = data.get ("value");
float[] fa = de.floatArray ();
rsvcData data7 = new rsvcData ();
data7.insert ("value", fa);
de = data7.get ("value");
ia = de.intArray ();
rsvcData data8 = new rsvcData();
data8.insert ("value", ia);
if (data.equals (data8))
System.out.print ("Integer -> Float -> Integer OK\n");
else
System.out.print ("Integer -> Float -> Integer Failed\n");
// Double conversion
de = data.get ("value");
double[] da = de.doubleArray ();
rsvcData data9 = new rsvcData ();
data9.insert ("value", da);
de = data9.get ("value");
ia = de.intArray ();
rsvcData data10 = new rsvcData();
data10.insert ("value", ia);
if (data.equals (data10))
System.out.print ("Integer -> Double -> Integer OK\n");
else
System.out.print ("Integer -> Double -> Integer Failed\n");
}
static public void floatConvTest ()
{
// test array insert
float []farray = new float[127];
for (int i = 0; i < 127; i++)
farray[i] = (float)i;
rsvcData data = new rsvcData ();
data.insert ("value", farray);
// get data test
rsvcDataEntry de = data.get ("value");
// byte converstion
byte[] ba = de.byteArray ();
rsvcData data1 = new rsvcData ();
data1.insert ("value", ba);
de = data1.get ("value");
float []ia = de.floatArray();
rsvcData data2 = new rsvcData();
data2.insert ("value", ia);
if (data.equals (data2))
System.out.print ("Float -> Byte -> Float OK\n");
else
System.out.print ("Float -> Byte -> Float Failed\n");
// short conversion
de = data.get ("value");
short[] sa = de.shortArray ();
rsvcData data3 = new rsvcData ();
data3.insert ("value", sa);
de = data3.get ("value");
ia = de.floatArray ();
rsvcData data4 = new rsvcData();
data4.insert ("value", ia);
if (data.equals (data4))
System.out.print ("Float -> Short -> Float OK\n");
else
System.out.print ("Float -> Short -> Float Failed\n");
// long conversion
de = data.get ("value");
long[] la = de.longArray ();
rsvcData data5 = new rsvcData ();
data5.insert ("value", la);
de = data5.get ("value");
ia = de.floatArray ();
rsvcData data6 = new rsvcData();
data6.insert ("value", ia);
if (data.equals (data6))
System.out.print ("Float -> Long -> Float OK\n");
else
System.out.print ("Float -> Long -> Float Failed\n");
// Integer conversion
de = data.get ("value");
int[] fa = de.intArray ();
rsvcData data7 = new rsvcData ();
data7.insert ("value", fa);
de = data7.get ("value");
ia = de.floatArray ();
rsvcData data8 = new rsvcData();
data8.insert ("value", ia);
if (data.equals (data8))
System.out.print ("Float -> Integer -> Float OK\n");
else
System.out.print ("Float -> Integer -> Float Failed\n");
// Double conversion
de = data.get ("value");
double[] da = de.doubleArray ();
rsvcData data9 = new rsvcData ();
data9.insert ("value", da);
de = data9.get ("value");
ia = de.floatArray ();
rsvcData data10 = new rsvcData();
data10.insert ("value", ia);
if (data.equals (data10))
System.out.print ("Float -> Double -> Float OK\n");
else
System.out.print ("Float -> Double -> Float Failed\n");
}
public static rsvcData arrayData ()
{
rsvcData data = new rsvcData ();
int i;
// insert array of double
double[] darray = new double[127];
for (i = 0; i < 127; i++)
darray[i] = 123.232 + i*121.121 + i/89.12;
data.insert ("value0", darray);
// insert array of string
String[] sarray = new String[211];
for (i = 0; i < 211; i++)
sarray[i] = new String("value plus " + String.valueOf(i));
data.insert ("value1", sarray);
return data;
}
public static void main (String[] args)
{
rsvcData data = new rsvcData();
// test scaler data insert
data.insert ("value0", bdata);
data.insert ("value1", sdata);
data.insert ("value2", idata);
data.insert ("value3", ldata);
data.insert ("value4", fdata);
data.insert ("value5", ddata);
data.insert ("value6", strdata);
try {
data.dup ("value4", "value3");
}catch (rsvcException e) {
data.remove ("value3");
data.dup ("value4", "value3");
}
data.asciiDump ();
rsvcData data1 = new rsvcData (data);
if (data.equals (data1))
System.out.print ("Data == Data1\n");
else
System.out.print ("Data != Data1\n");
data1.insert ("value0", (byte)12);
if (data.equals (data1))
System.out.print ("Data == Data1\n");
else
System.out.print ("Data != Data1\n");
data1.changeTag ("value2", "value12");
data1.asciiDump ();
rsvcTimeStamp ts = new rsvcTimeStamp();
data1.insert ("value1", ts);
data1.asciiDump ();
integerConvTest ();
floatConvTest();
// test stream out and stream in
File outputfile = new File (rsvcDataTest.file);
FileOutputStream output = null;
try {
output = new FileOutputStream (outputfile);
}catch (IOException e) {
System.out.println (e);
System.exit (-1);
}
// find out how big stream rsvcData will be
// rsvcData olddata = arrayData ();
rsvcData olddata = new rsvcData ();
olddata.insert ("value0", (double)129.01);
olddata.insert ("value1", (double)142323.01);
int dsize = olddata.streamSize ();
System.out.print ("Data size is " + String.valueOf(dsize) + "\n");
// Create Buffered output stream
BufferedOutputStream boutput = new BufferedOutputStream (output, dsize);
try {
olddata.streamOut (boutput);
}catch (IOException e) {
System.out.println (e);
System.exit (-1);
}
try {
boutput.flush();
}catch (IOException e) {
System.out.println (e);
System.exit (-1);
}
// create a buffered input stream
rsvcData newdata = new rsvcData ();
FileInputStream input = null;
try {
input = new FileInputStream (outputfile);
}catch (IOException e) {
System.out.println (e);
System.exit (-1);
}
BufferedInputStream binput = new BufferedInputStream(input, dsize);
try {
newdata.streamIn (binput);
}catch (IOException e) {
System.out.println (e);
System.exit (-1);
}
newdata.asciiDump ();
// test equality between newdata and data
if (olddata.equals (newdata) )
System.out.print ("Data == newdata\n");
else
System.out.print ("Data != newdata\n");
// test whether we can read from a file generated by C code
// create a buffered input stream
rsvcData cdata = new rsvcData ();
try {
input = new FileInputStream (coutputfile);
}catch (IOException e) {
System.out.println (e);
System.exit (-1);
}
binput = new BufferedInputStream(input, 2400);
try {
cdata.streamIn (binput);
}catch (IOException e) {
System.out.println (e);
System.exit (-1);
}
cdata.asciiDump ();
// output some data stream let C++ to pick it up
try {
output = new FileOutputStream (cinputfile);
}catch (IOException e) {
System.out.println (e);
System.exit (-1);
}
boutput = new BufferedOutputStream(output, 2400);
try {
cdata.streamOut (boutput);
}catch (IOException e) {
System.out.println (e);
System.exit (-1);
}
try {
boutput.flush();
}catch (IOException e) {
System.out.println (e);
System.exit (-1);
}
}
}
@@ -0,0 +1,60 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// rsvcDataType Class
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcDataTypes.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.1 1999/10/18 17:12:42 chen
// *** empty log message ***
//
//
//
//
public final class rsvcDataTypes
{
static public final short RSVC_BYTE = 0;
static public final short RSVC_INT16 = 1;
static public final short RSVC_UINT16 = 2;
static public final short RSVC_INT32 = 3;
static public final short RSVC_UINT32 = 4;
static public final short RSVC_FLOAT = 5;
static public final short RSVC_DOUBLE = 6;
static public final short RSVC_STRING = 7;
static public final short RSVC_TIMESTAMP = 8;
static public final short RSVC_INVALID = 9;
static public final short RSVC_ULONG = 10;
static public final short RSVC_LONG = 11;
static public final short RSVC_TAG_MAX_LEN = 16;
static final String[] types = {"Byte",
"Short",
"Unsigned Short",
"Integer",
"Unsigned Integer",
"Float",
"Double",
"Char String",
"TimeStamp",
"Invalid",
"Unsigned long 64",
"Long 64"
};
}
@@ -0,0 +1,4 @@
<applet name="CDEV Name Server" code=rsvcDisplay width=400 height=100>
<param name=host value=talitha>
<param name=port value=10932>
</applet>
@@ -0,0 +1,592 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// JAVA Applet for rsvc name server
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcDisplay.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.3 1999/12/14 15:38:16 chen
// Add scrollbar to display
//
// Revision 1.2 1999/10/18 17:16:06 chen
// minor changes
//
// Revision 1.1 1999/10/18 17:12:42 chen
// *** empty log message ***
//
//
//
//
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;
import rsvcData;
import rsvcDataEntry;
import rsvcClient;
import rsvcEventHandler;
import rsvcConfig;
public class rsvcDisplay extends Applet implements Runnable, rsvcEventHandler
{
// display tag names
private final String[] tags_ = {"name","domain","status","host", "port", "owner"};
private final int numtags_ = 6;
// top level scroll pane
private ScrollPane sclp_ = null;
// top level panel
private Panel dpanel_ = null;
// title field of display
private Label title_ = null;
// information field of display
private Label info_ = null;
// maximum number of entries
private final int size_ = 40;
// current number of entries
private int num_ = 0;
// category filed labels
private Label nameLabel_ = null;
private Label domainLabel_ = null;
private Label statusLabel_ = null;
private Label hostLabel_ = null;
private Label portLabel_ = null;
private Label userLabel_ = null;
// diffrent fields
private TextField[] name_;
private TextField[] domain_;
private TextField[] status_;
private TextField[] host_;
private TextField[] port_;
private TextField[] user_;
// layout
private GridBagLayout layout_ = null;
private GridBagConstraints c_ = null;
// network connection
private rsvcClient client_ = null;
private String serverHost_ = null;
private int serverPort_ = 0;
// seperate thread to handle clean up information box
private Thread timerThread_ = null;
public void setServerHost (String host)
{
serverHost_ = host;
}
public void setServerPort (int p)
{
serverPort_ = p;
}
private void startTimerThread ()
{
if (timerThread_ == null) {
timerThread_ = new Thread (this);
timerThread_.start();
}
else
timerThread_.resume ();
}
private void createLabel (String label)
{
Font lfont = new Font ("times", Font.BOLD, 14);
Color lc = Color.blue;
c_.weightx = 0;
c_.gridwidth = GridBagConstraints.REMAINDER;
title_ = new Label (label, Label.CENTER);
title_.setFont (lfont);
title_.setForeground (lc);
layout_.setConstraints(title_, c_);
dpanel_.add(title_);
}
private void createInfoLabel ()
{
Font lfont = new Font ("times", Font.BOLD, 12);
c_.weightx = 0;
c_.gridwidth = GridBagConstraints.REMAINDER;
info_ = new Label ();
info_.setFont (lfont);
layout_.setConstraints(info_, c_);
dpanel_.add (info_);
}
private void setInformation (String info)
{
info_.setText (info);
}
private void clearInformation ()
{
info_.setText (null);
}
private void createFieldLabels ()
{
Font lfont = new Font ("helvetica", Font.ITALIC, 12);
c_.weightx = 1;
c_.gridwidth = 1;
nameLabel_ = new Label ("Name", Label.CENTER);
nameLabel_.setFont (lfont);
layout_.setConstraints(nameLabel_, c_);
dpanel_.add(nameLabel_);
domainLabel_ = new Label ("Domain", Label.CENTER);
domainLabel_.setFont (lfont);
layout_.setConstraints(domainLabel_, c_);
dpanel_.add(domainLabel_);
statusLabel_ = new Label ("Status", Label.CENTER);
statusLabel_.setFont (lfont);
layout_.setConstraints(statusLabel_, c_);
dpanel_.add(statusLabel_);
c_.gridwidth = 2;
hostLabel_ = new Label ("Host", Label.CENTER);
hostLabel_.setFont (lfont);
layout_.setConstraints(hostLabel_, c_);
dpanel_.add(hostLabel_);
c_.gridwidth = 1;
portLabel_ = new Label ("Port", Label.CENTER);
portLabel_.setFont (lfont);
layout_.setConstraints(portLabel_, c_);
dpanel_.add(portLabel_);
c_.gridwidth = GridBagConstraints.REMAINDER;
userLabel_ = new Label ("User Name", Label.CENTER);
userLabel_.setFont (lfont);
layout_.setConstraints(userLabel_, c_);
dpanel_.add(userLabel_);
}
private void createEmptyFields (int index)
{
c_.gridwidth = 1;
name_[index] = new TextField (10);
name_[index].setEditable (false);
layout_.setConstraints(name_[index], c_);
dpanel_.add(name_[index]);
domain_[index] = new TextField (10);
domain_[index].setEditable (false);
layout_.setConstraints(domain_[index], c_);
dpanel_.add(domain_[index]);
status_[index] = new TextField (10);
status_[index].setEditable (false);
layout_.setConstraints(status_[index], c_);
dpanel_.add(status_[index]);
c_.gridwidth = 2;
host_[index] = new TextField (20);
host_[index].setEditable (false);
layout_.setConstraints(host_[index], c_);
dpanel_.add(host_[index]);
port_[index] = new TextField (10);
port_[index].setEditable (false);
layout_.setConstraints(port_[index], c_);
dpanel_.add(port_[index]);
c_.gridwidth = GridBagConstraints.REMAINDER;
user_[index] = new TextField (10);
user_[index].setEditable (false);
layout_.setConstraints(user_[index], c_);
dpanel_.add(user_[index]);
// force to display
validate ();
}
private void updateEntryAt (rsvcData data, int index)
{
String dispval = null;
int i = 0;
rsvcDataEntry dentry = data.get (tags_[i++]);
dentry = data.get (tags_[i++]);
dentry = data.get (tags_[i++]);
int statusval;
if (dentry != null) {
statusval = dentry.intValue ();
if (statusval == 0) {
status_[index].setBackground (Color.green);
status_[index].setText ("Alive");
}
else if (statusval == 2) {
status_[index].setBackground (Color.red);
status_[index].setText ("Dead");
}
else if (statusval == 1) {
status_[index].setBackground (Color.yellow);
status_[index].setText ("Dormant");
}
else {
status_[index].setBackground (Color.white);
status_[index].setText ("Unknown");
}
}
dentry = data.get (tags_[i++]);
if (dentry != null) {
dispval = dentry.stringValue ();
host_[index].setText (dispval);
}
dentry = data.get (tags_[i++]);
if (dentry != null) {
dispval = dentry.stringValue ();
port_[index].setText (dispval);
}
dentry = data.get (tags_[i++]);
if (dentry != null) {
dispval = dentry.stringValue ();
user_[index].setText (dispval);
}
}
public void updateEntry (rsvcData data, boolean create)
{
int i = 0;
String dispval = null;
String name = null;
String domain = null;
rsvcDataEntry dentry = data.get (tags_[i++]);
if (dentry != null) {
dispval = dentry.stringValue ();
name = dispval;
}
dentry = data.get (tags_[i++]);
if (dentry != null) {
dispval = dentry.stringValue ();
domain = dispval;
}
i = 0;
String tname = null;
String tdomain = null;
int found = 0;
if (name != null && domain != null) {
for (i = 0; i < num_; i++) {
tname = name_[i].getText ();
tdomain = domain_[i].getText ();
if (name.compareTo (tname) == 0 &&
domain.compareTo (tdomain) == 0) {
updateEntryAt (data, i);
found = 1;
break;
}
}
}
if (found == 0 && create == true)
addEntry (data);
}
public void addEntry (rsvcData data)
{
String dispval = null;
int i = 0;
String name = null;
String domain = null;
createEmptyFields (num_);
rsvcDataEntry dentry = data.get (tags_[i++]);
if (dentry != null) {
dispval = dentry.stringValue ();
name_[num_].setText (dispval);
name = dispval;
}
dentry = data.get (tags_[i++]);
if (dentry != null) {
dispval = dentry.stringValue ();
domain_[num_].setText (dispval);
domain = dispval;
}
dentry = data.get (tags_[i++]);
int statusval;
if (dentry != null) {
statusval = dentry.intValue ();
if (statusval == 0) {
status_[num_].setBackground (Color.green);
status_[num_].setText ("Alive");
}
else if (statusval == 2) {
status_[num_].setBackground (Color.red);
status_[num_].setText ("Dead");
}
else if (statusval == 1) {
status_[num_].setBackground (Color.yellow);
status_[num_].setText ("Dormant");
}
else {
status_[num_].setBackground (Color.white);
status_[num_].setText ("Unknown");
}
}
dentry = data.get (tags_[i++]);
if (dentry != null) {
dispval = dentry.stringValue ();
host_[num_].setText (dispval);
}
dentry = data.get (tags_[i++]);
if (dentry != null) {
dispval = dentry.stringValue ();
port_[num_].setText (dispval);
}
dentry = data.get (tags_[i++]);
if (dentry != null) {
dispval = dentry.stringValue ();
user_[num_].setText (dispval);
}
num_ ++;
if (name != null && domain != null) {
rsvcData serverinfo = new rsvcData ();
rsvcEvent oevent = null;
serverinfo.insert ("name", name);
serverinfo.insert ("domain", domain);
try {
oevent = client_.monitorValue ("cdevServers", serverinfo,
this);
}catch (IOException e) {
;
}
}
}
private void cleanupEntries ()
{
for (int i = 0; i < num_; i++) {
remove (name_[i]);
remove (domain_[i]);
remove (status_[i]);
remove (host_[i]);
remove (port_[i]);
remove (user_[i]);
}
num_ = 0;
validate ();
}
public void init ()
{
// create a border layout for applet
setLayout(new BorderLayout ());
// create top level scroll pane
sclp_ = new ScrollPane (ScrollPane.SCROLLBARS_ALWAYS);
add (sclp_);
sclp_.setSize (400, 100);
// create layout manager
layout_ = new GridBagLayout();
c_ = new GridBagConstraints();
c_.fill = GridBagConstraints.BOTH;
// create top level panel
dpanel_ = new Panel (layout_);
dpanel_.setSize (700, 100);
// add this panel to scroll pane
sclp_.add (dpanel_);
// create array of text fields
name_ = new TextField[size_];
domain_ = new TextField[size_];
status_ = new TextField[size_];
host_ = new TextField[size_];
port_ = new TextField[size_];
user_ = new TextField[size_];
num_ = 0;
// create top label
createLabel ("CDEV Name Server Information");
// create information label
createInfoLabel ();
// create category labels
createFieldLabels ();
// create network handler to rsvcServer
client_ = new rsvcClient();
if (serverHost_ == null) {
// get parameters for server host and server port
serverHost_ = getParameter ("host");
serverPort_ = Integer.valueOf (getParameter ("port")).intValue();
}
}
public void start ()
{
// start timer thread
startTimerThread ();
setInformation ("Connecting to server on " + serverHost_ + " at port " + String.valueOf (serverPort_));
try {
client_.connect (serverHost_, serverPort_);
}catch (UnknownHostException ue) {
setInformation ("Unknown Host " + serverHost_);
}catch (IOException e) {
setInformation ("Cannot connect to the server");
}
// if connected
if (client_.connected() == true) {
setInformation ("Connection to the server is established");
// get all
rsvcEvent oevent = null;
try {
oevent = client_.query ("cdevServers", "all", this);
}catch (IOException e) {
setInformation ("Cannot send out query information to the server");
}
// monitor on new entries
rsvcData noused = new rsvcData();
try {
oevent = client_. monitorIncomingEntries ("cdevServers",
noused, this);
} catch (IOException e) {
setInformation ("Cannot send out monitor request to the server");
}
// add disconnection handler
client_.addDisconnectHandler (this);
}
}
public void stop ()
{
if (client_.connected () == true) {
try {
client_.disconnect ();
}catch (IOException e) {
;
}
}
timerThread_.suspend ();
}
public void handleEvent (rsvcEvent event)
{
int status = event.getStatus ();
int opcode = event.getOpcode ();
rsvcData data = event.getData ();
if (status == rsvcConfig.RSVC_DISCONNECTED) {
setInformation ("Server is Gone");
cleanupEntries ();
}
else {
if (opcode == rsvcConfig.RSVC_QUERY) {
if (status == rsvcConfig.RSVC_INCOMPLETE ||
status == rsvcConfig.RSVC_SUCCESS)
addEntry (data);
}
else if (opcode == rsvcConfig.RSVC_MONITOR_ON) {
if (status == rsvcConfig.RSVC_SUCCESS)
updateEntry (data, false);
}
else if (opcode == rsvcConfig.RSVC_MONITOR_ENTRIES) {
if (status == rsvcConfig.RSVC_SUCCESS && data.isEmpty() != true)
updateEntry (data, true);
}
}
}
public void run ()
{
while (true) {
// check to see whether there is something in the
// information display area. If there is, clean out
String infotext = info_.getText ();
if (infotext != null)
info_.setText (null);
// sleep 3 seconds
try {
Thread.sleep (3000);
} catch (InterruptedException e) {
;
}
}
}
public static void main(String args[]) {
if (args.length < 2) {
System.err.println ("Usage: rsvcDisplay host port");
System.exit (-1);
}
Frame f = new Frame("CDEV Name Server Information");
rsvcDisplay display = new rsvcDisplay();
display.setServerHost (args[0]);
display.setServerPort (Integer.valueOf (args[1]).intValue());
display.init();
display.start ();
f.add("Center", display);
f.pack();
f.setSize(f.getPreferredSize());
f.show();
}
}
@@ -0,0 +1,548 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// RSVC Server/Client Protocol Information and Data Information
// This class contains protocol information related to callbacks
// 1. operation code
// 2. request id
// 3. socket id -->for server only
// 4. client id
// 5. callback id -->from client to server
//
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcEvent.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.1 1999/10/18 17:12:42 chen
// *** empty log message ***
//
//
//
import java.io.*;
import rsvcConfig;
import rsvcData;
import rsvcEventHandler;
public final class rsvcEvent
{
private int opcode_;
private int cbkid_;
private int eventid_;
private int clientid_;
private int socketid_;
private int status_;
private rsvcData data_;
private rsvcEventHandler handler_ = null;
/**
* Construct an emtpy rsvcEvent object
*/
public rsvcEvent ()
{
opcode_ = rsvcConfig.RSVC_OP_UNKNOWN;
cbkid_ = 0;
eventid_ = 0;
clientid_ = 0;
socketid_ = 0;
status_ = rsvcConfig.RSVC_SUCCESS;
data_ = new rsvcData ();
handler_ = null;
}
/**
* Construct a rsvcEvent Object with given parameters
*/
public rsvcEvent (rsvcData data, int opcode, int cbkid)
{
data_ = new rsvcData (data);
opcode_ = opcode;
cbkid_ = cbkid;
eventid_ = 0;
clientid_ = 0;
socketid_ = 0;
status_ = rsvcConfig.RSVC_SUCCESS;
handler_ = null;
}
/**
* Construct a rsvcEvent Object with given parameters
*/
public rsvcEvent (rsvcData data, int opcode, int cbkid,
int eventid, int clientid, int socketid,
int status)
{
data_ = new rsvcData (data);
opcode_ = opcode;
cbkid_ = cbkid;
eventid_ = eventid;
clientid_ = clientid;
socketid_ = socketid;
status_ = status;
handler_ = null;
}
/**
* Construct a rsvcEvent Object without data object
*/
public rsvcEvent (int opcode, int cbkid,
int eventid, int clientid, int socketid,
int status)
{
data_ = new rsvcData();
opcode_ = opcode;
cbkid_ = cbkid;
eventid_ = eventid;
clientid_ = clientid;
socketid_ = socketid;
status_ = status;
handler_ = null;
}
/**
* Construct a rsvcEvent Object with data object only
*/
public rsvcEvent (rsvcData data)
{
data_ = new rsvcData(data);
opcode_ = 0;
cbkid_ = 0;
eventid_ = 0;
clientid_ = 0;
socketid_ = 0;
status_ = rsvcConfig.RSVC_SUCCESS;
handler_ = null;
}
/**
* Construct a rsvcEvent Object using an exising rsvcEvent
*/
public rsvcEvent (rsvcEvent event)
{
data_ = new rsvcData (event.data_);
opcode_ = event.opcode_;
cbkid_ = event.cbkid_;
eventid_ = event.eventid_;
clientid_ = event.clientid_;
socketid_ = event.socketid_;
status_ = event.status_;
handler_ = event.handler_;
}
/**
* Check whether two events have the same signature
*/
public boolean match (rsvcEvent event)
{
if (opcode_ == event.opcode_ &&
cbkid_ == event.cbkid_ &&
eventid_ == event.eventid_)
return true;
return false;
}
/**
* Set data and other paremeters
*/
public void set (rsvcData data,
int opcode, int cbkid,
int eventid, int clientid,
int socketid, int status)
{
data_ = new rsvcData (data);
opcode_ = opcode;
cbkid_ = cbkid;
eventid_ = eventid;
clientid_ = clientid;
socketid_ = socketid;
status_ = status;
}
/**
* Set data and other paremeters
*/
public void set (int opcode, int cbkid,
int eventid, int clientid,
int socketid, int status)
{
opcode_ = opcode;
cbkid_ = cbkid;
eventid_ = eventid;
clientid_ = clientid;
socketid_ = socketid;
status_ = status;
}
/**
* Clean up everything
*/
public void cleanup ()
{
data_.remove ();
cbkid_ = 0;
eventid_ = 0;
clientid_ = 0;
socketid_ = 0;
status_ = rsvcConfig.RSVC_SUCCESS;
handler_ = null;
}
/**
* Get Opcode of this event
*/
public int getOpcode ()
{
return opcode_;
}
/**
* Set opcode of this event
*/
public void setOpcode (int opcode)
{
opcode_ = opcode;
}
/**
* Get request id
*/
public int getEventid ()
{
return eventid_;
}
/**
* Set request id
*/
public void setEventid (int eventid)
{
eventid_ = eventid;
}
/**
* Get client id
*/
public int getClientid ()
{
return clientid_;
}
/**
* Set client id
*/
public void setClientid (int clientid)
{
clientid_ = clientid;
}
/**
* Get cbk id
*/
public int getCbkid ()
{
return cbkid_;
}
/**
* Set cbk id
*/
public void setCbkid (int cbkid)
{
cbkid_ = cbkid;
}
/**
* Get socket id
*/
public int getSocketid ()
{
return socketid_;
}
/**
* Set socket id
*/
public void setSocketid (int socketid)
{
socketid_ = socketid;
}
/**
* Get Status of event
*/
public int getStatus ()
{
return status_;
}
/**
* Set Status Field
*/
public void setStatus (int status)
{
status_ = status;
}
/**
* Get Data Field
*/
public rsvcData getData ()
{
return data_;
}
/**
* Set Data Field
*/
public void setData (rsvcData data)
{
data_ = new rsvcData (data);
}
/**
* Set Handler field
*/
public void setHandler (rsvcEventHandler handler)
{
handler_ = handler;
}
/**
* Get handler field
*/
public rsvcEventHandler getHandler () throws NullPointerException
{
if (handler_ == null) {
throw new NullPointerException ("rsvcEvent has a null handler");
}
return handler_;
}
/**
* Return binary data stream size for this event
*/
public int streamSize ()
{
int dsize = 0;
int size = 0;
// magic number first
dsize += rsvcDataOutputStream.streamSize (rsvcData._RSVC_MAGIC_NUM);
// size of the data to follow after this
dsize += rsvcDataOutputStream.streamSize (size);
// size of 6 integer fields
dsize += 6*rsvcDataOutputStream.streamSize ((int)0);
dsize += data_.streamSize ();
return dsize;
}
/**
* Convert object into a binary data stream
*/
public void streamOut (OutputStream output) throws IOException
{
// calculate total size of this binary stream
int binarysize = streamSize ();
// payload size without magic number and size information
int rsize = binarysize -
rsvcDataOutputStream.streamSize (rsvcData._RSVC_MAGIC_NUM) -
rsvcDataOutputStream.streamSize (binarysize);
rsvcDataOutputStream writer = new rsvcDataOutputStream (output);
// write out magic number first
try{
writer.write (rsvcData._RSVC_MAGIC_NUM);
}catch (IOException e) {
throw e;
}
try {
writer.write (rsize);
}catch (IOException e) {
throw e;
}
// write out six integer field
try {
writer.write (opcode_);
}catch (IOException e) {
throw e;
}
try {
writer.write (cbkid_);
}catch (IOException e) {
throw e;
}
try {
writer.write (eventid_);
}catch (IOException e) {
throw e;
}
try {
writer.write (clientid_);
}catch (IOException e) {
throw e;
}
try {
writer.write (socketid_);
}catch (IOException e) {
throw e;
}
try {
writer.write (status_);
}catch (IOException e) {
throw e;
}
// finally data item itself
try {
data_.streamOut (writer);
}catch (IOException e) {
throw e;
}
}
/**
* Read header information of an incoming stream to find out
* size information of data stream n
*/
public static int readHeader (InputStream stream) throws IOException
{
// attach input stream
rsvcDataInputStream input = new rsvcDataInputStream (stream);
// read magic number first
int magic;
try {
magic = input.readInt ();
}catch (IOException e){
throw e;
}
if (magic != rsvcData._RSVC_MAGIC_NUM) {
throw new IOException ("Magic number mismatch");
}
// get data size
int datasize;
try {
datasize = input.readInt ();
}catch (IOException e) {
throw e;
}
return datasize;
}
/**
* Return streamed event header length
*/
public static int headerLen ()
{
return rsvcDataOutputStream.streamSize (rsvcData._RSVC_MAGIC_NUM) +
rsvcDataOutputStream.streamSize ((int)1);
}
/**
* Convert a stream into an event object
*/
public void streamIn (InputStream stream) throws IOException
{
// clean up this object
cleanup ();
// attach input stream
rsvcDataInputStream input = new rsvcDataInputStream (stream);
try {
opcode_ = input.readInt ();
} catch (IOException e) {
throw e;
}
try {
cbkid_ = input.readInt ();
} catch (IOException e) {
throw e;
}
try {
eventid_ = input.readInt ();
} catch (IOException e) {
throw e;
}
try {
clientid_ = input.readInt ();
} catch (IOException e) {
throw e;
}
try {
socketid_ = input.readInt ();
} catch (IOException e) {
throw e;
}
try {
status_ = input.readInt ();
} catch (IOException e) {
throw e;
}
try {
data_.streamIn (input);
}catch (IOException e) {
throw e;
}
}
public String toString ()
{
StringBuffer result = new StringBuffer ();
result.append ("Event Contains \n");
result.append ("opcode: ").append (opcode_).append ("\n");
result.append ("cbkid: ").append (cbkid_).append ("\n");
result.append ("eventid: ").append (eventid_).append ("\n");
result.append ("clientid: ").append (clientid_).append ("\n");
result.append ("socketid: ").append (socketid_).append ("\n");
result.append ("status: ").append (status_).append ("\n");
result.append (data_.toString());
return result.toString();
}
}
@@ -0,0 +1,34 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// RSVC Client Event Handler
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcEventHandler.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.1 1999/10/18 17:12:42 chen
// *** empty log message ***
//
//
//
//
public interface rsvcEventHandler
{
public void handleEvent (rsvcEvent event);
}
@@ -0,0 +1,41 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// Simple RSVC Package Exception Class
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcException.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.1 1999/10/18 17:12:43 chen
// *** empty log message ***
//
//
//
public class rsvcException extends RuntimeException
{
rsvcException ()
{
super ();
}
rsvcException (String s)
{
super (s);
}
}
@@ -0,0 +1,35 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// RSVC Net Data (Protocol Part for RSVC Client)
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcNetData.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.1 1999/10/18 17:12:43 chen
// *** empty log message ***
//
//
//
//
import rsvcData;
public final class rsvcNetData
{
private rsvcData data_ = null;
private rsvc
@@ -0,0 +1,127 @@
import java.io.*;
import java.util.*;
import java.net.*;
import rsvcClient;
import rsvcEventHandler;
import rsvcConfig;
public final class rsvcServerTest implements rsvcEventHandler
{
public rsvcServerTest ()
{
// empty
}
public static void main (String[] args)
{
if (args.length < 4) {
System.err.println ("Usage: rsvcServerTest name domain host port");
System.exit (-1);
}
rsvcServerTest test = new rsvcServerTest ();
String host = args[2];
int port = Integer.valueOf (args[3]).intValue();
int udpport = port + 1024;
String server = args[0];
String domain = args[1];
rsvcData serverinfo = new rsvcData ();
rsvcData udpinfo = new rsvcData ();
serverinfo.insert ("name", server);
serverinfo.insert ("domain", domain);
serverinfo.insert ("host", host);
serverinfo.insert ("owner", "chen");
serverinfo.insert ("time", (int)(System.currentTimeMillis()/1000));
serverinfo.insert ("port", (int)(System.currentTimeMillis()%65535));
serverinfo.insert ("pid", (int)1234);
udpinfo.insert ("name", server);
udpinfo.insert ("domain", domain);
rsvcClient client = new rsvcClient ();
rsvcUdpClient udpclient = new rsvcUdpClient();
try {
client.connect (host, port);
}catch (UnknownHostException ue) {
System.err.println (ue);
System.exit (-1);
}catch (IOException e) {
System.err.println (e);
System.exit (-1);
}
try {
udpclient.connect (host, udpport);
}catch (UnknownHostException ue) {
System.err.println (ue);
System.exit (-1);
}catch (IOException e) {
System.err.println (e);
System.exit (-1);
}
// outbound event stream
rsvcEvent oevent = null;
try {
oevent = client.insertValue ("cdevServers", serverinfo,
test, true);
}catch (IOException e) {
System.err.println (e);
System.exit (-1);
}
Thread readerThread = client.getReaderThread ();
while (true) {
try {
udpclient.update (udpinfo);
} catch (IOException e) {
System.err.println (e);
System.exit (-1);
}
// wait for 5 seconds
try {
readerThread.join (5000);
} catch (InterruptedException e) {
System.err.println (e);
System.exit (-1);
}
}
}
public void handleEvent (rsvcEvent event)
{
int status = event.getStatus ();
int opcode = event.getOpcode ();
rsvcData data = event.getData ();
System.out.println ("Handle event is called with status :" + String.valueOf (status));
switch (opcode) {
case rsvcConfig.RSVC_GET:
System.out.println ("Get Value with result :");
break;
case rsvcConfig.RSVC_QUERY:
System.out.println ("Query Value with result :");
break;
case rsvcConfig.RSVC_SET:
System.out.println ("Set Value with result :");
break;
default:
System.out.println ("Operation : " + String.valueOf (opcode));
}
if (status == rsvcConfig.RSVC_NOTFOUND)
System.out.println ("Found nothing");
if (status == rsvcConfig.RSVC_SUCCESS)
data.asciiDump ();
}
}
@@ -0,0 +1,114 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// Data Type Of Time Stamp
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcTimeStamp.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.1 1999/10/18 17:12:44 chen
// *** empty log message ***
//
//
//
import java.util.Date;
public final class rsvcTimeStamp extends Number
{
public int secPastEpoch; // seconds since Jan. 1, 1970
public int nsec; // nano seconds
/**
* Construct a time stamp with current time
*/
public rsvcTimeStamp ()
{
Date d = new Date();
long t = d.getTime();
secPastEpoch = (int)(t/1000);
nsec = (int)(t - secPastEpoch)*1000;
}
/**
* Construct a time stamp with provided second and nano second fields
*/
public rsvcTimeStamp (int sec, int nsec)
{
secPastEpoch = sec + nsec/1000000000;
nsec = nsec - nsec/1000000000 * 1000000000;
}
// all inherited functions
/**
* Return byte value of time stamp
*/
public byte byteValue ()
{
return (byte)secPastEpoch;
}
/**
* Return short value of time stamp
*/
public short shortValue ()
{
return (short)secPastEpoch;
}
/**
* Return integer value of time stamp
*/
public int intValue ()
{
return secPastEpoch;
}
/**
* Return long value of time stamp
*/
public long longValue ()
{
return (long)secPastEpoch;
}
/**
* Return float value of time stamp
*/
public float floatValue ()
{
return (secPastEpoch + nsec/(float)1000000000.0);
}
/**
* Return double value of time stamp
*/
public double doubleValue ()
{
return (secPastEpoch + nsec/1000000000.0);
}
/**
* Return string representation
*/
public String toString ()
{
Date d = new Date ((long)((long)secPastEpoch*1000));
return d.toString();
}
}
@@ -0,0 +1,135 @@
//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
// Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
// Jefferson Lab HPC Group, 12000 Jefferson Ave., Newport News, VA 23606
//-----------------------------------------------------------------------------
//
// Description:
// RSVC UDP Client for Servers to update their time stamps
//
// Author:
// Jie Chen
// Jefferson Lab HPC Group
//
// Revision History:
// $Log: rsvcUdpClient.java,v $
// Revision 1.1.1.1 2000/05/23 15:12:50 pal
// cdev_psi_1.7.2
//
// Revision 1.1 1999/10/18 17:12:44 chen
// *** empty log message ***
//
//
//
import java.io.*;
import java.util.*;
import java.net.*;
import rsvcEvent;
import rsvcData;
import rsvcConfig;
public final class rsvcUdpClient
{
// UDP Socket
private DatagramSocket udpsocket_ = null;
// Destination address for packets
private InetAddress dest_ = null;
// Destination port for packets
private int port_ = 0;
/**
* Construct an empty rsvcUdpClient Object
*/
public rsvcUdpClient ()
{
// empty
}
/**
* Override default finalize method.This allows Java virtual
* machine to clean up resource when this object is no longer
* needed.
*/
protected void finalize() throws Throwable
{
if (udpsocket_ != null)
udpsocket_.close ();
}
/**
* Connect to a server that is on a given host at a given port
*/
public synchronized void connect (String host, int port) throws UnknownHostException, IOException
{
try {
udpsocket_ = new DatagramSocket ();
}catch (IOException e) {
System.err.println(e);
throw e;
}
try {
dest_ = InetAddress.getByName (host);
}catch (UnknownHostException ue) {
throw ue;
}
port_ = port;
}
/**
* A server that is being managed by RSVC sends a very simple data
* to the rsvcServer to manifest itself being alive.
* data is in the form of two tagged ("name", "domain") values or
* anything that will make up an index
*/
public synchronized int update (rsvcData data) throws IOException
{
if (udpsocket_ == null)
return rsvcConfig.RSVC_ERROR;
rsvcEvent cbk = new rsvcEvent (data);
cbk.setOpcode (rsvcConfig.RSVC_SET);
cbk.setEventid (0);
int datasize = cbk.streamSize ();
ByteArrayOutputStream baoutput = new ByteArrayOutputStream (datasize);
try {
cbk.streamOut (baoutput);
}catch (IOException e) {
throw e;
}
// return underlying byte from this byteArrayStream
byte[] obuffer = baoutput.toByteArray ();
if (datasize != obuffer.length) {
throw new IOException ("Streamed out buffer size != original calculated stream size");
}
// construct a datapacket to send data out
DatagramPacket packet = new DatagramPacket (obuffer, datasize,
dest_, port_);
try {
udpsocket_.send (packet);
} catch (IOException e) {
throw e;
}
return rsvcConfig.RSVC_SUCCESS;
}
/**
* Shutdown connection (close socket)
*/
public void disconnect ()
{
if (udpsocket_ != null)
udpsocket_.close ();
}
}

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