osmocom
/
vovida-gsml
Archived
11
0
Fork 0

import source code of Vovida GSML project (from www.vovida.org)

This is the source code as it was published on vovida.org a couple
of years ago. The filename was gsml-1_0.tar.bz2
This commit is contained in:
Harald Welte 2010-07-09 16:09:18 +02:00
commit 903a15fc26
1482 changed files with 398521 additions and 0 deletions

135
LICENSE.txt Normal file
View File

@ -0,0 +1,135 @@
Cisco-style Mozilla Public License 1.1
1. Definitions.
1.1. "Commercial Use" means distribution or otherwise making the Covered Code available to a third party.
1.2. ''Contributor'' means each entity that creates or contributes to the creation of Modifications.
1.3. ''Contributor Version'' means the combination of the Original Code, prior Modifications used by a Contributor, and the Modifications made by that particular Contributor.
1.4. ''Covered Code'' means the Original Code or Modifications or the combination of the Original Code and Modifications, in each case including portions thereof.
1.5. ''Electronic Distribution Mechanism'' means a mechanism generally accepted in the software development community for the electronic transfer of data.
1.6. ''Executable'' means Covered Code in any form other than Source Code.
1.7. ''Initial Developer'' means the individual or entity identified as the Initial Developer in the Source Code notice required by Exhibit A.
1.8. ''Larger Work'' means a work which combines Covered Code or portions thereof with code not governed by the terms of this License.
1.9. ''License'' means this document.
1.9.1. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein.
1.9. ''Modifications'' means any addition to or deletion from the substance or structure of either the Original Code or any previous Modifications. When Covered Code is released as a series of files, a Modification is:
A. Any addition to or deletion from the contents of a file containing Original Code or previous Modifications.
B. Any new file that contains any part of the Original Code or previous Modifications.
1.10. ''Original Code'' means Source Code of computer software code which is described in the Source Code notice required by Exhibit A as Original Code, and which, at the time of its release under this License is not already Covered Code governed by this License.
1.11."Patent Claims" means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor.
1.12. ''Source Code'' means the preferred form of the Covered Code for making modifications to it, including all modules it contains, plus any associated interface definition files, scripts used to control compilation and installation of an Executable, or source code differential comparisons against either the Original Code or another well known, available Covered Code of the Contributor's choice. The Source Code can be in a compressed or archival form, provided the appropriate decompression or de-archiving software is widely available for no charge.
1.13. "You'' (or "Your") means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License or a future version of this License issued under Section 6.1. For legal entities, "You'' includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, "control'' means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
2. Source Code License.
2.1. The Initial Developer Grant. The Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license, subject to third party intellectual property claims:
(a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer to use, reproduce, modify, display, perform, sublicense and distribute the Original Code (or portions thereof) with or without Modifications, and/or as part of a Larger Work; and
(b) under Patents Claims infringed by the making, using or selling of Original Code, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Code (or portions thereof).
(c) the licenses granted in this Section 2.1(a) and (b) are effective on the date Initial Developer first distributes Original Code under the terms of this License.
(d) Notwithstanding Section 2.1(b) above, no patent license is granted: 1) for code that You delete from the Original Code; 2) separate from the Original Code; or 3) for infringements caused by: i) the modification of the Original Code or ii) the combination of the Original Code with other software or devices.
2.2. Contributor Grant. Subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:
(a) under intellectual property rights (other than patent or trademark) Licensable by Contributor, to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof) either on an unmodified basis, with other Modifications, as Covered Code and/or as part of a Larger Work; and
(b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: 1) Modifications made by that Contributor (or portions thereof); and 2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination).
(c) the licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first makes Commercial Use of the Covered Code.
(d) Notwithstanding Section 2.2(b) above, no patent license is granted: 1) for any code that Contributor has deleted from the Contributor Version; 2) separate from the Contributor Version; 3) for infringements caused by: i) third party modifications of Contributor Version or ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or 4) under Patent Claims infringed by Covered Code in the absence of Modifications made by that Contributor.
3. Distribution Obligations.
3.1. Application of License. The Modifications which You create or to which You contribute are governed by the terms of this License, including without limitation Section 2.2. The Source Code version of Covered Code may be distributed only under the terms of this License or a future version of this License released under Section 6.1, and You must include a copy of this License with every copy of the Source Code You distribute. You may not offer or impose any terms on any Source Code version that alters or restricts the applicable version of this License or the recipients' rights hereunder. However, You may include an additional document offering the additional rights described in Section 3.5.
3.2. Availability of Source Code. Any Modification which You create or to which You contribute must be made available in Source Code form under the terms of this License either on the same media as an Executable version or via an accepted Electronic Distribution Mechanism to anyone to whom you made an Executable version available; and if made available via Electronic Distribution Mechanism, must remain available for at least twelve (12) months after the date it initially became available, or at least six (6) months after a subsequent version of that particular Modification has been made available to such recipients. You are responsible for ensuring that the Source Code version remains available even if the Electronic Distribution Mechanism is maintained by a third party.
3.3. Description of Modifications. You must cause all Covered Code to which You contribute to contain a file documenting the changes You made to create that Covered Code and the date of any change. You must include a prominent statement that the Modification is derived, directly or indirectly, from Original Code provided by the Initial Developer and including the name of the Initial Developer in (a) the Source Code, and (b) in any notice in an Executable version or related documentation in which You describe the origin or ownership of the Covered Code.
3.4. Intellectual Property Matters
(a) Third Party Claims. If Contributor has knowledge that a license under a third party's intellectual property rights is required to exercise the rights granted by such Contributor under Sections 2.1 or 2.2, Contributor must include a text file with the Source Code distribution titled "LEGAL'' which describes the claim and the party making the claim in sufficient detail that a recipient will know whom to contact. If Contributor obtains such knowledge after the Modification is made available as described in Section 3.2, Contributor shall promptly modify the LEGAL file in all copies Contributor makes available thereafter and shall take other steps (such as notifying appropriate mailing lists or newsgroups) reasonably calculated to inform those who received the Covered Code that new knowledge has been obtained.
(b) Contributor APIs. If Contributor's Modifications include an application programming interface and Contributor has knowledge of patent licenses which are reasonably necessary to implement that API, Contributor must also include this information in the LEGAL file.
(c) Representations. Contributor represents that, except as disclosed pursuant to Section 3.4(a) above, Contributor believes that Contributor's Modifications are Contributor's original creation(s) and/or Contributor has sufficient rights to grant the rights conveyed by this License.
3.5. Required Notices. You must duplicate the notice in Exhibit A in each file of the Source Code. If it is not possible to put such notice in a particular Source Code file due to its structure, then You must include such notice in a location (such as a relevant directory) where a user would be likely to look for such a notice. If You created one or more Modification(s) You may add your name as a Contributor to the notice described in Exhibit A. You must also duplicate this License in any documentation for the Source Code where You describe recipients' rights or ownership rights relating to Covered Code. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Code. However, You may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear than any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer.
3 .6. Distribution of Executable Versions. You may distribute Covered Code in Executable form only if the requirements of Section 3.1-3.5 have been met for that Covered Code, and if You include a notice stating that the Source Code version of the Covered Code is available under the terms of this License, including a description of how and where You have fulfilled the obligations of Section 3.2. The notice must be conspicuously included in any notice in an Executable version, related documentation or collateral in which You describe recipients' rights relating to the Covered Code. You may distribute the Executable version of Covered Code or ownership rights under a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable version does not attempt to limit or alter the recipient's rights in the Source Code version from the rights set forth in this License. If You distribute the Executable version under a different license You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer or any Contributor. You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of any such terms You offer.
3.7. Larger Works.You may create a Larger Work by combining Covered Code with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Code.
4. Inability to Comply Due to Statute or Regulation. If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Code due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be included in the LEGAL file described in Section 3.4 and must be included with all distributions of the Source Code. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.
5. Application of this License. This License applies to code to which the Initial Developer has attached the notice in Exhibit A and to related Covered Code.
6. Versions of the License.
6.1. New Versions. Netscape Communications Corporation (''Netscape'') may publish revised and/or new versions of the License from time to time. Each version will be given a distinguishing version number.
6.2. Effect of New Versions. Once Covered Code has been published under a particular version of the License, You may always continue to use it under the terms of that version. You may also choose to use such Covered Code under the terms of any subsequent version of the License published by Netscape. No one other than Netscape has the right to modify the terms applicable to Covered Code created under this License.
6.3. Derivative Works. If You create or use a modified version of this License (which you may only do in order to apply it to code which is not already Covered Code governed by this License), You must (a) rename Your license so that the phrases ''Mozilla'', ''MOZILLAPL'', ''MOZPL'', ''Netscape'', "MPL", ''NPL'' “Cisco”, “Cisco Systems, Inc.” “Cisco Systems”, “Cisco MPL” or any confusingly similar phrase do not appear in your license (except to note that your license differs from this License) and (b) otherwise make it clear that Your version of the license contains terms which differ from the Cisco-style MPL. (Filling in the name of the Initial Developer, Original Code or Contributor in the notice described in Exhibit A shall not of themselves be deemed to be modifications of this License.)
7. DISCLAIMER OF WARRANTY. COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS'' BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
8. TERMINATION.
8.1. This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. All sublicenses to the Covered Code which are properly granted shall survive any termination of this License. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive.
8.2. If You initiate litigation by asserting a patent infringement claim (excluding declatory judgment actions) against Initial Developer or a Contributor (the Initial Developer or Contributor against whom You file such action is referred to as "Participant") alleging that:
(a) such Participant's Contributor Version directly or indirectly infringes any patent, then any and all rights granted by such Participant to You under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively, unless if within 60 days after receipt of notice You either: (i) agree in writing to pay Participant a mutually agreeable reasonable royalty for Your past and future use of Modifications made by such Participant, or (ii) withdraw Your litigation claim with respect to the Contributor Version against such Participant. If within 60 days of notice, a reasonable royalty and payment arrangement are not mutually agreed upon in writing by the parties or the litigation claim is not withdrawn, the rights granted by Participant to You under Sections 2.1 and/or 2.2 automatically terminate at the expiration of the 60 day notice period specified above.
(b) any software, hardware, or device, other than such Participant's Contributor Version, directly or indirectly infringes any patent, then any rights granted to You by such Participant under Sections 2.1(b) and 2.2(b) are revoked effective as of the date You first made, used, sold, distributed, or had made, Modifications made by that Participant.
8.3. If You assert a patent infringement claim against Participant alleging that such Participant's Contributor Version directly or indirectly infringes any patent where such claim is resolved (such as by license or settlement) prior to the initiation of patent infringement litigation, then the reasonable value of the licenses granted by such Participant under Sections 2.1 or 2.2 shall be taken into account in determining the amount or value of any payment or license.
8.4. In the event of termination under Sections 8.1 or 8.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or any distributor hereunder prior to termination shall survive termination.
9. LIMITATION OF LIABILITY. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
10. U.S. GOVERNMENT END USERS. The Covered Code is a ''commercial item,'' as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of ''commercial computer software'' and ''commercial computer software documentation,'' as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Code with only those rights set forth herein.
11. MISCELLANEOUS. This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by California law provisions (except to the extent applicable law, if any, provides otherwise), excluding its conflict-of-law provisions. With respect to disputes in which at least one party is a citizen of, or an entity chartered or registered to do business in the United States of America, any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California, with venue lying in Santa Clara County, California, with the losing party responsible for costs, including without limitation, court costs and reasonable attorneys' fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License.
12. RESPONSIBILITY FOR CLAIMS. As between Initial Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability.
13. MULTIPLE-LICENSED CODE. Initial Developer may designate portions of the Covered Code as Multiple-Licensed. Multiple-Licensed means that the Initial Developer permits you to utilize portions of the Covered Code under Your choice of the NPL or the alternative licenses, if any, specified by the Initial Developer in the file described in Exhibit A.
----------
EXHIBIT A
Cisco-style Mozilla Public License.
``The contents of this file are subject to the Cisco-style Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at _vovida.org_
Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License.
The Original Code is _all code in the zip file labelled _gsml-1_0.zip_.
The Initial Developer of the Original Code is __Cisco Systems, Inc___. Portions created by __Cisco Systems, Inc_ are Copyright (C) __2005_ __Cisco Systems, Inc_. All Rights Reserved.
Contributor(s): _Cisco Systems, Inc and James Forster___.

54
Scrubbed_File_List.txt Normal file
View File

@ -0,0 +1,54 @@
The following files were 'scrubbed' from the archived Cisco codebase due to questions about re-distribution rights.
Common\apm\include\msgDefs.h:// (c) Copyright JetCell 2000
Common\apm\include\msgProc.h:// (c) Copyright JetCell 1998
Common\apm\src\debug.cpp:// (c) Copyright JetCell 1998
Common\bssgp\win32test\dbgout.cpp: * Copyright JetCell, Inc. 1999-2000 All rights reserved *
Common\bssgp\win32test\dbgout.h: * Copyright JetCell, Inc. 1999-2000 All rights reserved *
Common\cdr\include\FTClient.h:// (c) Copyright JetCell 2000
Common\cdr\src_server\FTClient.cpp:// (c) Copyright JetCell 2000
Common\Pm\src\socketutil.cpp:// (c) Copyright JetCell 1998
GP10\Dsp\Driver\Drv6x.c:/* (C) Copyright 1997,1998 by DNA Enterprises, Inc. */
GP10\Dsp\include\COMMON.H:/* (C) Copyright 1997,1998 by DNA Enterprises, Inc. */
GP10\Dsp\include\DMA_UTIL.H:/* (C) Copyright 1997,1998 by DNA Enterprises, Inc. */
GP10\Dsp\include\MCBSPDRV.H:/* (C) Copyright 1997,1998 by DNA Enterprises, Inc. */
GP10\Host\Alarm\Test\alarm_test.cpp:* (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
GP10\Host\Cdc_bsp\ads860.h:/* Copyright 1984-1997 Wind River Systems, Inc. */
GP10\Host\Cdc_bsp\ataDrv.c:/* Copyright 1989-1998 Wind River Systems, Inc. */
GP10\Host\Cdc_bsp\cdcim.h:/* Copyright 1984-1997 Wind River Systems, Inc. */
GP10\Host\Cdc_bsp\config.h:/* Copyright 1984-1997 Wind River Systems, Inc. */
GP10\Host\Cdc_bsp\configdb.h: * Copyright 1984-1996 Wind River Systems, Inc.
GP10\Host\Cdc_bsp\configNet.h:/* Copyright 1984-1998 Wind River Systems, Inc. */
GP10\Host\Cdc_bsp\motfecend.c:/* Copyright 1989-1998 Wind River Systems, Inc. */
GP10\Host\Cdc_bsp\sysLib.c:/* Copyright 1984-1997 Wind River Systems, Inc. */
GP10\Host\Cdc_bsp\sysSerial.c:/* Copyright 1984-1996 Wind River Systems, Inc. */
GP10\Host\Common_To_Host\include\logmodules.h: * Copyright JetCell, Inc. 1999-2000 All rights reserved *
GP10\Host\Common_To_Host\Logging\VCLOGGING.H: * Copyright JetCell, Inc. All rights reserved *
GP10\Host\Common_To_Host\Logging\VcModules.h: * Copyright JetCell, Inc. 1999-2000 All rights reserved *
GP10\Host\Common_To_Host\TcpServer\TcpSrvApi.h:* (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
GP10\Host\Http\include\enum_tab.h: * Copyright (C) 1998 Rapid Logic, Inc.
GP10\Host\Http\include\http_feedback.h:* (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
GP10\Host\Http\include\options.h: * Copyright (C) 1998 Rapid Logic, Inc.
GP10\Host\Http\src\http_event.c:* (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
GP10\Host\Http\src\http_feedback.c:* (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
GP10\Host\Http\src\http_main.c:* (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
GP10\Host\Http\src\http_oamOperation.c:* (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
GP10\Host\Http\src\http_post.c:* (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
GP10\Host\Http\src\http_security.c:* (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
GP10\Host\Http\src\ignition.c: * Copyright (C) 1999 Rapid Logic, Inc.
GP10\Host\Http\src\main.c:* Copyright (C) 1998 Rapid Logic, Inc.
GP10\Host\l1proxy\include\cdcim.h:/* Copyright 1984-1997 Wind River Systems, Inc. */
GP10\Host\logging\src\l3MsLog.cpp:// (c) Copyright JetCell 1998
GP10\Host\TcpServer\Include\queue.h:* (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
GP10\Host\TcpServer\Src\queue.cpp:* (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
GP10\Host\TcpServer\Src\TcpServer.cpp:* (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
GP10\Host\TimeSync\src\time_userTime.cpp:* (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
GP10\Host\voip\include\gkadd.h:* Copyright RADVision 1998. *
GP10\Host\voip\include\gkcci.h:* Copyright RADVision 1998. *
GP10\Host\voip\include\gklrqi.h:* Copyright RADVision 1998. *
GP10\Host\voip\include\gkmain.h:* Copyright RADVision 1998. *
GP10\Host\voip\include\gkrgi.h:* Copyright RADVision 1998. *
GP10\Host\voip\include\gkstorage.h:* Copyright RADVision 1998. *
GP10\Host\voip\include\gkTypes.h:* Copyright RADVision 1998. *

View File

@ -0,0 +1,47 @@
##########################################################
#
# (c) Copyright Cisco 2000
# All Rights Reserved
#
# Use Examples:
#
# Case 1:
# make all VOB=GP10 -
# Places .out in VOB/bin directory
#
# Case 2:
# make all VOB=GP10 APPDIR=Host\<Application Name>\<Source Directory> -
# Places .o file(s) in VOB\$(APPDIR)\bin directory.
#
# <Application Name> = Name of Application directory
# <Source Directory> = application sub directory where the calling
# Makefile resides.
#
# Example: make all VOB=GP10 APPDIR=Host\vxTemplate\src
#
# (OPTIONAL) Append REPLACE - Replaces the List of directories
# to be used in the SUBDIRS variable
#
# Example: make all VOB=GP10 APPDIR=Host\vxTemplate\src REPLACE=src
#
# Note: This make file must reference a VOB that
# has a defs.mk in the top level directory.
#
##########################################################
SUBDIRS = src
# TOP_OF_VOB must be defined before including l3defs.mk
TOP_OF_VOB = ..\..
VOBDIR = $(TOP_OF_VOB)/$(VOB)
# Allows a sub-set of the source code directories to be used
ifneq ($(REPLACE),)
SUBDIRS = $(REPLACE)
endif
include $(VOBDIR)/l3defs.mk

View File

@ -0,0 +1,151 @@
/*********************************************************************/
/* */
/* (c) Copyright Cisco 2000 */
/* All Rights Reserved */
/* */
/*********************************************************************/
/*********************************************************************/
/* */
/* Version : 1.0 */
/* Status : Under development */
/* File : AlarmTask.h */
/* Author(s) : Bhawani Sapkota */
/* Create Date : 9/18/2000 */
/* Description : This file contains Alarm task routines */
/* */
/*********************************************************************/
/* REVISION HISTORY
/*___________________________________________________________________*/
/*----------+--------+-----------------------------------------------*/
/* Name | Date | Reason */
/*----------+--------+-----------------------------------------------*/
/* Bhawani |09/28/00| Initial Draft */
/*----------+--------+-----------------------------------------------*/
/*********************************************************************/
#ifndef _ALARMTASK_H_
#define _ALARMTASK_H_ /* include once only */
#include "Alarm.h"
/* Include product specific code here */
#if defined (MNET_PRODUCT_SPECIFIC_GS)
#include "GSOsTune.h"
#elif defined (MNET_PRODUCT_SPECIFIC_GMC)
#include "vclogging.h"
#elif defined (MNET_PRODUCT_SPECIFIC_GP10)
#include "Logging/vclogging.h"
#endif
typedef struct _AlarmEntry_t
{
AlarmCode_t code; // last error code
int id; // first alarm ID
Alarm_severity_t severity; // severity
ubyte4 utc; // outstanding since this time
int count;
struct _AlarmEntry_t *next;
}AlarmEntry_t;
class AlarmTask:public JCTask {
public:
AlarmTask(char *);
~AlarmTask();
int InitAlarmTask();
static int bootupTimeoutHandler();
static int entryPoint();
static int AlarmMain(void);
static char *srcName();
static AlarmTask *theAlarmTask;
// disk operation
STATUS saveAlarm(const char* msg);
STATUS renameOldLogFile();
STATUS getLastId(unsigned long *id);
int generateNextId();
AlarmEntry_t *findAlarmEntry(MNET_MODULE_ID mid, AlarmCode_t errorCode);
bool addAlarmEntry(MNET_MODULE_ID mid, MibTag moduleErrorTag, AlarmCode_t code, char *arg1=NULL, char *arg2=NULL);
bool delAlarmEntry(MNET_MODULE_ID mid, MibTag moduleErrorTag, AlarmCode_t code);
EnableDisableState_t updateOperationalState();
// module handling
AlarmCode_t getMdlStatus(MNET_MODULE_ID mid);
AlarmEntry_t *allocEntry(MNET_MODULE_ID id);
void printStatus();
void getOutstandingAlarmCount(ubyte1 &, ubyte1 &, ubyte1 &);
// message q operation
JC_STATUS msgqSend( unsigned int msgType, char * buffer, unsigned int nBytes);
JC_STATUS alarmSend(InterModuleAlarmMsgType_t mtype,
MNET_MODULE_ID mid,
MibTag moduleErrorTag=0,
AlarmCode_t alarm_code=EC_COMMON_NOERROR,
char *arg1=NULL,
char *arg2=NULL
);
//AMS Operation
bool sendSummaryUpdateToAms();
void reportNewAlarm(int id, MNET_MODULE_ID mid, AlarmCode_t ecode,
Alarm_severity_t severity, char * arg1=0, char * arg2=0);
//Operational State Management
EnableDisableState_t getOperationState();
void setOperationState(EnableDisableState_t opstate );
// Mib access control status
EnableDisableState_t getMibAcessControlState();
void setMibAcessControlState(EnableDisableState_t opstate);
void updateModuleLastError(MNET_MODULE_ID mid, MibTag moduleErrorTag);
void setModuleLastError(MibTag moduleErrorTag, AlarmCode_t alarm_code);
// startup and quit
void quit();
int startup();
void closeSocket();
private:
JCMsgQueue *jcMsgQ;
JCCTimer *initTimer;
char *_mnetbase; /* holds MNET_BASE environment variable */
char *_logfilename; /* holds absolute path of the logfilename */
char *_sourceName; /* holds the source name */
char *_sourceType; /* type of the source (Gp, Gmc, Itp, */
char *_msgRecvBuff; /* holds received message */
AlarmEntry_t *_ms[MNET_MAX_MODULE_IDS]; /* current module Alarm Status */
AlarmEntry_t *_ap; /* Alarm pools */
int _statistics[2][Alarm_max_severity];
void populateSourceName();
//status variables
bool _quit;
bool _mibAccessState;
static bool isOneCreated;
// Disallow the following functions
AlarmTask();
AlarmTask(const AlarmTask&);
AlarmTask& operator=(const AlarmTask&);
int operator== (const AlarmTask&) const;
};
#endif

View File

@ -0,0 +1,168 @@
/*********************************************************************/
/* */
/* (c) Copyright Cisco 2000 */
/* All Rights Reserved */
/* */
/*********************************************************************/
/*********************************************************************/
/* */
/* Version : 1.0 */
/* Status : Under development */
/* File : AlarmTask.h */
/* Author(s) : Bhawani Sapkota */
/* Create Date : 9/18/2000 */
/* Description : This file contains alarm task basic defination */
/* routines */
/* */
/*********************************************************************/
/* REVISION HISTORY
/*___________________________________________________________________*/
/*----------+--------+-----------------------------------------------*/
/* Name | Date | Reason */
/*----------+--------+-----------------------------------------------*/
/* Bhawani |07/14/00| Initial Draft */
/* Bhawani |11/20/00| resturctured to share among GP, GMS and GS */
/*----------+--------+-----------------------------------------------*/
/*********************************************************************/
#if !defined(_ALARM_H_)
#define _ALARM_H_
#include "AlarmCode.h"
#include "Os/JCMsgQueue.h"
#include "Os/JCModule.h"
#include "Os/JCCTimer.h"
#include "Os/JCTask.h"
#include "alarm_prodSpec.h"
typedef unsigned short ubyte2;
typedef unsigned long ubyte4;
typedef unsigned char ubyte1;
typedef short sbyte2;
typedef long sbyte4;
#define ALARM_q_maxMsgs 32
#define ALARM_q_maxMsgLength 100
#define ALARM_q_option MSG_Q_PRIORITY
#define ALARM_q_timeout 18000 /* 5 minutes */
#define ALARM_task_name "tAlarm"
#define ALARM_mib_lock_timeout 7200 /* 2 minutes */
#define ALARM_record_length 70
#define ALARM_max_records 58
#define ALARM_max_outstanding 50
/* It is assumeed that current working directory is ViperCall */
#define ALARM_logFile "/Alarm/alarm.log"
#define ALARM_logFileMaxSize 128
#define ALARM_dirChar '/'
#define ALARM_maxMsgSize 1024
#define ALARM_defaultRecvBuffer 128
#define ALARM_optionalArgSize 40
#define ALARM_monStation "QSEvent"
#define ALARM_mchResponse "mchResponse"
typedef enum Alarm_severity
{
Alarm_critical=0,
Alarm_major,
Alarm_minor,
Alarm_info,
Alarm_max_severity
} Alarm_severity_t;
typedef enum
{
InterModuleAlarmMsgTypeClearAlarm = 0,
InterModuleAlarmMsgTypeRaiseAlarm,
InterModuleAlarmMsgTypeShutdown,
InterModuleAlarmMsgTypeReboot
}InterModuleAlarmMsgType_t;
typedef struct
{
ubyte1 senderId; /* message originator */
InterModuleAlarmMsgType_t msgType; /* message type (MT_TRAP) */
MNET_MODULE_ID srcModuleId; /* Alarm source module ID */
MibTag errorTag; /* This module's ErrorTag */
AlarmCode_t code; /* Alarm code */
char arg1[ALARM_optionalArgSize]; /* argument 1 */
char arg2[ALARM_optionalArgSize]; /* argument 2 */
}InterModuleAlarmMsg_t;
typedef enum
{
stateDisabled=0,
stateEnabled=1
} EnableDisableState_t;
/* Printing and sending to logging module */
void alarm_print(char *format, ...);
#ifdef _UT
void HexDumper(ubyte1 *buffer, int length);
#define alarm_debug(XX) printf("[ALARM TRACE] %s ->", fname); alarm_print XX
#define alarm_error(XX) printf("[Alarm Error] %s ->", fname); alarm_print XX
#define alarm_warning(XX) printf("[Alarm Warning] %s ->", fname); alarm_print XX
#define alarm_dump(x,y); HexDumper(x, y);
#define alarm_fenter(XX); static char fname[] = XX;
#define alarm_fexit();
#else
#define alarm_fenter(XXX); \
DBG_FUNC(XXX, MY_LOGID); \
DBG_ENTER(); \
#define alarm_fexit(); DBG_LEAVE();
#define alarm_debug(XX) DBG_TRACE XX
#define alarm_error(XX) DBG_ERROR XX
#define alarm_warning(XX) DBG_WARNING XX
#define alarm_dump(x,y); DBG_HEXDUMP(x,y);
#endif
/* defined at alarm_main module */
int alarmTask();
int alarm_taskCreate();
void alarm_taskQuit ();
void alarm_msgPrint(char *format, ...);
void alarm_rebootHandler ( int startType );
/* In file alarm_modules.cpp */
void alarm_rptMdlStatus(int id, int mid, int ecode, int severity=Alarm_critical,
char* arg1= (char *) NULL, char* arg2= (char *) NULL);
void alarm_printStatus();
/* In file alarm_message.cpp */
void alarm_processMsg(char *inComingMsg);
/* It will go to alarm_event.cpp */
void alarm_clientMsg (char *, short, unsigned long);
void alarm_broadcast(const char *msg);
int alarm_generateNextId();
/* alarm_diskFile.cpp */
STATUS alarm_renameOldLogFile();
/* TimeSync api from Time Sync module */
extern void time_syncTime();
#endif

View File

@ -0,0 +1,127 @@
/*********************************************************************/
/* */
/* (c) Copyright Cisco 2000 */
/* All Rights Reserved */
/* */
/*********************************************************************/
/*********************************************************************/
/* */
/* Version : 1.0 */
/* Status : Under development */
/* File : AlarmTask.h */
/* Author(s) : Bhawani Sapkota */
/* Create Date : 9/18/2000 */
/* Description : This file contains interface defination between */
/* Alarm Source (GP, GMC, GS) and Alarm Monitoring */
/* Server (APM1) */
/* */
/*********************************************************************/
/* REVISION HISTORY
/*___________________________________________________________________*/
/*----------+--------+-----------------------------------------------*/
/* Name | Date | Reason */
/*----------+--------+-----------------------------------------------*/
/* Bhawani |07/14/00| Initial Draft */
/* Bhawani |11/20/00| resturctured to share among GP, GMS and GS */
/* Bhawani |12/05/00| Added UDP server and client port so that the */
/* | | server and clients can reside on the same IP */
/* Bhawani |12/05/00| swaped the server and client port to make the */
/* | | original port as the server port. */
/*----------+--------+-----------------------------------------------*/
/*********************************************************************/
#if !defined(_ALARM_INTERFACE_H_)
#define _ALARM_INTERFACE_H_
#if defined(__cplusplus)
extern "C" {
#endif
#define ALARM_viperCellNameMaxSize 41
#define ALARM_viperCellIpMaxSize 16
#define ALARM_unknownAlarmId 0x00
/* Alarm Server's IP address is Gate Keeper's IP address */
/* Alarm Client/Server's Universal UPD ports */
#define ALARM_interfaceUdpPortClient 12791
#define ALARM_interfaceUdpPortServer 11788
#define ALARM_periodicUpdateInterval 300 /* seconds */
/* Alarm Source Type */
#define ALARM_srcTypViperCell 128
#define ALARM_srcTypViperBase 129
/* Alarm Message Type */
#define ALARM_msgTypSummaryUpdate 1
#define ALARM_msgTypAlarmEvent 2
typedef char sbyte1;
typedef short sbyte2;
typedef long sbyte4;
typedef unsigned char ubyte1;
typedef unsigned short ubyte2;
typedef unsigned long ubyte4;
/* Message header */
typedef struct AlarmInterfaceMsgHeader_{
ubyte1 alarmSrcType;
ubyte1 alarmMsgType;
ubyte2 alarmMsgLen;
}AlarmInterfaceMsgHeader;
#define ALARM_interfaceMsgHdrLen 4
/* Summary update data */
typedef struct AlarmSummaryUpdateData_{
ubyte4 alarmSrcIp;
sbyte1 alarmSrcName[ALARM_viperCellNameMaxSize];
ubyte1 alarmCriticalCount;
ubyte1 alarmMajorCount;
ubyte1 alarmMinorCount;
}AlarmSummaryUpdateData;
#define ALARM_summaryUpdateDataLen (7 + ALARM_viperCellNameMaxSize)
#define ALARM_summaryUpdateMsgLen (ALARM_interfaceMsgHdrLen + ALARM_summaryUpdateDataLen + sizeof(long))
#define ALARM_eventDataLen (28 + ALARM_viperCellNameMaxSize)
#define ALARM_eventMsgLen (ALARM_interfaceMsgHdrLen + ALARM_eventDataLen + sizeof(long))
/* Stubs for new event data */
typedef struct AlarmEventData_ {
ubyte4 alarmId;
ubyte4 alarmCode;
ubyte4 alarmTimestamp;
ubyte4 alarmSrcIp;
sbyte1 alarmSrcModuleName[ALARM_viperCellNameMaxSize];
ubyte4 alarmSrcModuleId;
ubyte4 opt1;
ubyte4 opt2;
}AlarmEventData;
/* Alarm Complete message */
typedef long Align;
typedef struct Alarm
{
AlarmInterfaceMsgHeader hdr;
union {
AlarmSummaryUpdateData summaryUpdateData;
AlarmEventData eventData;
}body;
Align x;
}AlarmViperCellToAmsMsg;
#if defined(__cplusplus)
}
#endif
#endif /* _ALARM_INTERFACE_H_ */

View File

@ -0,0 +1,44 @@
##########################################################
#
# (c) Copyright Cisco 2000
# All Rights Reserved
#
# Use Examples:
#
# Case 1:
# make all VOB=GP10 -
# Places .out in VOB/bin directory
#
# Case 2:
# make all VOB=GP10 APPDIR=Host\<Application Name>\<Source Directory> -
# Places .o file(s) in VOB\$(APPDIR)\bin directory.
#
# <Application Name> = Name of Application directory
# <Source Directory> = application sub directory where the calling
# Makefile resides.
#
# Example: make all VOB=GP10 APPDIR=Host\vxTemplate\src
#
#
# Note: This make file must reference a VOB that
# has a defs.mk in the top level directory.
#
##########################################################
# TOP_OF_VOB must be defined before including l3defs.mk
TOP_OF_VOB = ..\..
# Name of this App's Directory
THIS_APP_DIR = Alarm
VOB2DIR = $(TOP_OF_VOB)\..\$(VOB)
BINDIR = ..\bin
include $(VOB2DIR)\l3defs.mk
all: $(MODULE_OBJS)
cleanall:
@for %f in ($(notdir $(MODULE_OBJS))) do \
$(RM) ..\bin\%f

View File

@ -0,0 +1,198 @@
/*********************************************************************/
/* */
/* (c) Copyright Cisco 2000 */
/* All Rights Reserved */
/* */
/*********************************************************************/
/*********************************************************************/
/* */
/* Version : 1.0 */
/* Status : Under development */
/* File : AlarmTask.h */
/* Author(s) : Bhawani Sapkota */
/* Create Date : 07/11/99 */
/* Description : This file contains routines to perform disk I/O to */
/* save alarm to the disk file. */
/* */
/*********************************************************************/
/* REVISION HISTORY
/*___________________________________________________________________*/
/*----------+--------+-----------------------------------------------*/
/* Name | Date | Reason */
/*----------+--------+-----------------------------------------------*/
/* Bhawani |09/28/00| Initial Draft */
/* Bhawani |11/20/00| resturctured to share among GP, GMS and GS */
/*----------+--------+-----------------------------------------------*/
/*********************************************************************/
#include "AlarmTask.h"
#include "dirent.h"
#include "stat.h"
#include "time.h"
#include "string.h"
static unsigned long CyclicFileRecordIndex = 0;
STATUS AlarmTask::saveAlarm(const char* msg)
{
FILE *alarmfd;
alarm_fenter("AlarmTask::saveAlarm");
// Opens for reading and writing;
alarmfd = fopen(_logfilename, "r+");
if (alarmfd == NULL)
{
alarm_error(("Could not open alarm log file %s (Reason: %s)\n", _logfilename, strerror(errno)));
alarm_fexit();
return ERROR;
}
long fpos = ALARM_record_length*CyclicFileRecordIndex++;
CyclicFileRecordIndex = CyclicFileRecordIndex%ALARM_max_records;
fseek(alarmfd, fpos, SEEK_SET);
fputs(msg, alarmfd);
fclose(alarmfd);
alarm_debug(("Alarm Message successfully saved\n"));
alarm_fexit();
return OK;
}
STATUS AlarmTask::renameOldLogFile()
{
struct stat fileStat;
alarm_fenter("alarm_renameOldLogFile");
/* check if old Alarrm log file exists */
if (stat (_logfilename, &fileStat) == OK)
{
/* The file exist */
struct tm localTime;
struct tm *ltime = &localTime;
time_t longTime;
char *pdest;
char newFileName[ALARM_logFileMaxSize];
longTime = time(NULL);
ltime = localtime(&longTime);
strcpy(newFileName, _logfilename);
/* Assumes that file name is long enough */
pdest = strrchr(newFileName, ALARM_dirChar);
if( pdest != NULL )
{
sprintf(pdest+1, "AlarmLogAsOf_%d-%d-%d,%d:%d", ltime->tm_mon+1, ltime->tm_mday,
ltime->tm_year+1900,ltime->tm_hour, ltime->tm_min);
} else {
sprintf(newFileName, "AlarmLogAsOf_%d-%d-%d,%d:%d", ltime->tm_mon+1, ltime->tm_mday,
ltime->tm_year+1900,ltime->tm_hour, ltime->tm_min);
}
alarm_debug(("Renaming %s file to %s\n", _logfilename, newFileName));
if (rename(_logfilename, newFileName) == ERROR)
{
/* rename failed */
FILE *alarmfd;
alarm_error(("Could not rename old file (Reason: %s)\n", strerror(errno)));
alarm_warning(("Truncating the old alarm file: %s\n", _logfilename));
alarmfd = fopen(_logfilename, "w");
if (alarmfd == NULL)
{
alarm_error(("Could not truncate file(Reason: %s)\n",strerror(errno)));
} else {
fclose(alarmfd);
}
} else {
alarm_debug(("Old alarm file successfully renamed to %s\n", newFileName));
}
} else {
alarm_warning(("Old alarm log file \"%s\" does not exist.\n", _logfilename));
}
alarm_fexit();
return OK;
}
STATUS AlarmTask::getLastId(unsigned long *id)
{
FILE *alarmfd;
struct stat statBuff;
alarm_fenter("AlarmTask::getLastId");
STATUS status;
status = stat(_logfilename, &statBuff);
if ( status == ERROR // file does not exist
|| statBuff.st_size == 0 // newly created
|| statBuff.st_size % ALARM_record_length != 0 // corrupt file
|| statBuff.st_size > ALARM_max_records*ALARM_record_length // corrupt file
)
{
// if size is a zero, there was no alarm file
*id = 1;
CyclicFileRecordIndex = 0;
alarmfd = fopen(_logfilename, "w"); // truncate file
if (alarmfd != NULL)
fclose(alarmfd);
else
{
alarm_error(("Could not create %s for writing: %s\n", _logfilename, strerror(errno)));
}
} else {
alarm_debug(("Current Alarm disk file size = %d\n", statBuff.st_size));
if (statBuff.st_size < ALARM_max_records*ALARM_record_length)
{
// the size less then max size
CyclicFileRecordIndex = statBuff.st_size / ALARM_record_length;
*id = CyclicFileRecordIndex+1;
} else {
unsigned long id1, id2, i;
alarmfd= fopen(_logfilename, "r");
if (alarmfd == NULL)
{
alarm_error(("Cannot open() Alarm disk file %s to read (Reason: %s)\n", _logfilename, strerror(errno)));
*id =1;
CyclicFileRecordIndex = 0;
status = ERROR;
} else {
// file is ALARM_max_records*ALARM_record_length size
fseek(alarmfd, 0, SEEK_SET);
fscanf(alarmfd, "%u", &id1);
for(i=1; i< ALARM_max_records; i++)
{
fseek(alarmfd, i*ALARM_record_length, SEEK_SET);
fscanf(alarmfd, "%u", &id2);
if(id1> id2)
{
break;
} else {
id1 = id2;
}
}
CyclicFileRecordIndex = i % ALARM_max_records;
*id = id1+1;
}
}
}
alarm_fexit();
return status;
}

View File

@ -0,0 +1,196 @@
/*********************************************************************/
/* */
/* (c) Copyright Cisco 2000 */
/* All Rights Reserved */
/* */
/*********************************************************************/
/*********************************************************************/
/* */
/* Version : 1.0 */
/* Status : Under development */
/* File : AlarmTask.h */
/* Author(s) : Bhawani Sapkota */
/* Create Date : 07/11/99 */
/* Description : contains alarm module message that interact with */
/* other module . */
/* */
/*********************************************************************/
/* REVISION HISTORY
/*___________________________________________________________________*/
/*----------+--------+-----------------------------------------------*/
/* Name | Date | Reason */
/*----------+--------+-----------------------------------------------*/
/* Bhawani |07/11/99| Initial Draft */
/* Bhawani |11/20/00| resturctured to share among GP, GMS and GS */
/*----------+--------+-----------------------------------------------*/
#ifndef _ALARM_EVENT_CPP_
#define _ALARM_EVENT_CPP_
#include "AlarmTask.h"
void alarm_clientMsg ( char * message, // the message from the client
short size, // size of the message
unsigned long clientId // unique client ID of the requester client
)
{
alarm_fenter("alarm_clientMsg");
alarm_debug(("Message receive from client (ID = %d)", clientId));
alarm_debug(("%s\n", message));
alarm_fexit();
}
void alarm_broadcast(const char *msg)
{
int len;
alarm_fenter("alarm_broadcast");
fflush(stdout);
len = strlen(msg);
//TcpSrvSendResponse(msg, len, kAlarmGpName);
alarm_debug(("Alarm message was sent\n"));
alarm_fexit();
}
JC_STATUS AlarmTask::msgqSend(unsigned int msgType, char * buffer, unsigned int nBytes)
{
return jcMsgQ->JCMsgQSend(this->jcMsgQ, msgType, MY_MODULE_ID, buffer, nBytes, JC_NO_WAIT, JC_MSG_Q_FIFO);
}
JC_STATUS AlarmTask::alarmSend
(
InterModuleAlarmMsgType_t mtype,
MNET_MODULE_ID mid,
MibTag moduleErrorTag,
AlarmCode_t alarm_code,
char *arg1,
char *arg2
)
{
InterModuleAlarmMsg_t alarmMsg;
memset(&alarmMsg, 0, sizeof(InterModuleAlarmMsg_t));
alarmMsg.errorTag = moduleErrorTag;
alarmMsg.code = alarm_code;
alarmMsg.senderId = (ubyte1) MY_MODULE_ID;
alarmMsg.msgType = mtype;
alarmMsg.srcModuleId = mid;
if (NULL != arg1)
{
strncpy(alarmMsg.arg1, arg1, ALARM_optionalArgSize-1);
}
if (NULL != arg2)
{
strncpy(alarmMsg.arg2, arg2, ALARM_optionalArgSize-1);
}
return AlarmTask::theAlarmTask->msgqSend
(InterModuleAlarmMsgTypeRaiseAlarm,
(char *) &alarmMsg,
sizeof(InterModuleAlarmMsg_t));
}
extern "C" JC_STATUS alarm_raise(MNET_MODULE_ID mid, MibTag moduleErrorTag, AlarmCode_t alarm_code)
{
return AlarmTask::theAlarmTask->alarmSend(InterModuleAlarmMsgTypeRaiseAlarm, mid, moduleErrorTag, alarm_code);
}
extern "C" JC_STATUS alarm_raise_args(MNET_MODULE_ID mid, MibTag moduleErrorTag, AlarmCode_t alarm_code, int arg1, int arg2)
{
char pszArg1[ALARM_optionalArgSize];
char pszArg2[ALARM_optionalArgSize];
sprintf (pszArg1, "%d", arg1);
sprintf (pszArg2, "%d", arg2);
return AlarmTask::theAlarmTask->alarmSend(InterModuleAlarmMsgTypeRaiseAlarm, mid, moduleErrorTag, alarm_code, pszArg1, pszArg2);
}
extern "C" JC_STATUS alarm_clear(MNET_MODULE_ID mid, MibTag moduleErrorTag, AlarmCode_t alarm_code)
{
return AlarmTask::theAlarmTask->alarmSend(InterModuleAlarmMsgTypeClearAlarm, mid, moduleErrorTag, alarm_code);
}
EnableDisableState_t AlarmTask::getOperationState()
{
long opState;
oam_getMibIntVar(MY_MIB_OPERATION_STATE, &opState);
return (EnableDisableState_t) opState;
}
void AlarmTask::setOperationState(EnableDisableState_t opstate )
{
EnableDisableState_t state = getOperationState();
if(state != opstate)
{
oam_setMibIntVar(MY_MODULE_ID, MY_MIB_OPERATION_STATE, opstate);
}
}
EnableDisableState_t AlarmTask::getMibAcessControlState()
{
long opState;
oam_getMibIntVar(MY_MIB_ACCESS_CONTROL_TAG, &opState);
return (EnableDisableState_t) opState;
}
void AlarmTask::setMibAcessControlState(EnableDisableState_t opstate )
{
EnableDisableState_t state = getMibAcessControlState();
alarm_fenter("AlarmTask::setMibAcessControlState");
if(state != opstate)
{
oam_setMibIntVar(MY_MODULE_ID, MY_MIB_ACCESS_CONTROL_TAG, opstate);
}
// local mib status
_mibAccessState = (opstate == stateEnabled);
if (_mibAccessState)
{
// This is the first time
initTimer->cancelTimer();
alarm_debug (("Mib access is now enabled\n"));
}
alarm_fexit();
}
void AlarmTask::setModuleLastError(MibTag moduleErrorTag, AlarmCode_t alarm_code)
{
oam_setMibIntVar(MY_MODULE_ID, moduleErrorTag, alarm_code);
}
void AlarmTask::populateSourceName()
{
const int kDisplayStringSize = 256;
char name[kDisplayStringSize];
memset(name, 0, kDisplayStringSize);
oam_getMibByteAry(MY_MIB_SOURCE_NAME, (ubyte1 *) name, kDisplayStringSize-1);
_sourceName = new char[strlen(name+1)];
strcpy(_sourceName, name);
}
char * AlarmTask::srcName()
{
return theAlarmTask->_sourceName;
}
#endif /* _ALARM_EVENT_CPP_ */

View File

@ -0,0 +1,187 @@
/*********************************************************************/
/* */
/* (c) Copyright Cisco 2000 */
/* All Rights Reserved */
/* */
/*********************************************************************/
/*********************************************************************/
/* */
/* Version : 1.0 */
/* Status : Under development */
/* File : AlarmTask.h */
/* Author(s) : Bhawani Sapkota */
/* Create Date : 9/18/2000 */
/* Description : This file contains main routines for the alarm task */
/* */
/*********************************************************************/
/* REVISION HISTORY
/*___________________________________________________________________*/
/*----------+--------+-----------------------------------------------*/
/* Name | Date | Reason */
/*----------+--------+-----------------------------------------------*/
/* Bhawani |09/28/00| Initial Draft */
/* Bhawani |11/20/00| resturctured to share among GP, GMS and GS */
/*----------+--------+-----------------------------------------------*/
/*********************************************************************/
#include "AlarmTask.h"
#include "ctype.h"
#if defined( _TCP_SERVER_EXIST)
#include "TcpServer/TcpSrvApi.h"
#endif
AlarmTask * AlarmTask::theAlarmTask = NULL;
bool AlarmTask::isOneCreated = false;
AlarmTask::~AlarmTask()
{
alarm_fenter("AlarmTask::~AlarmTask");
alarm_debug(("Alarm Task instance is being deleted"));
delete jcMsgQ;
delete initTimer;
alarm_fexit();
}
int AlarmTask::entryPoint()
{
return theAlarmTask->startup();
}
int AlarmTask::startup()
{
int status;
unsigned int msgType;
MNET_MODULE_ID senderId;
unsigned int recvMsgsize;
alarm_fenter("alarmTask");
// Rename the old alarm file
// alarm_renameOldLogFile();
#if defined( _TCP_SERVER_EXIST)
// Register TCP server call back function
TcpSrvRegHand(kAlarmGpName, // Client Group Name (<= kClientGpNameMax)
alarm_clientMsg); // Function pointer to be called
#endif
/* now go into the message loop */
JCTaskEnterLoop();
_quit = false;
while(_quit == false)
{
/* get message from queue; if necessary wait for a maximum of ALARM_q_timeout ticks */
status = jcMsgQ->JCMsgQReceive(&jcMsgQ, &msgType, &senderId, _msgRecvBuff, &recvMsgsize, ALARM_q_timeout);
if (status == ERROR)
{
if (errno == S_objLib_OBJ_TIMEOUT)
{
/* Send heartbeat message to AMS in case it was down and now it has been up */
sendSummaryUpdateToAms();
continue;
}
}
else
{
alarm_processMsg(_msgRecvBuff);
sendSummaryUpdateToAms();
}
}
JCTaskNormExit();
closeSocket();
isOneCreated = false;
//delete theAlarmTask;
theAlarmTask = NULL;
/* The application need to unsunscribe trap before exiting. */
alarm_debug(("Alarm Task is exiting ... \n"));
alarm_fexit();
return OK;
}
/* print alarm messages */
void alarm_print(char *format, ...)
{
va_list marker;
va_start( marker, format ); /* Initialize variable arguments. */
vprintf(format, marker);
fflush(stdout);
va_end( marker ); /* Reset variable arguments. */
return;
}
#ifdef _UT
void HexDumper(ubyte1 *buffer, int length )
/*++ Purpose:
Put the inbound data in a hex dump format
Arguments:
buffer - points to the extension control block
length - specifies the number of bytes to dump --*/
{
int size;
int i;
int dwPos = 0;
while (length > 0) {
//
// Take min of 16 or length
//
size = min(16, length );
//
// Build text line
//
printf(" %04X ", dwPos );
for (i = 0; i < size; i++)
{
printf("%02X ", buffer[i] );
}
//
// Add spaces for short lines
//
while (i < 16)
{
printf(" " );
i++;
}
//
// Add ASCII chars
//
for (i = 0; i < size; i++)
{
if (isprint(buffer[i]))
{
printf("%c", buffer[i] );
} else {
printf("." );
}
}
printf("\n");
//
// Advance positions
//
length -= size;
dwPos += size;
buffer += size;
}
}
#endif /* _UT */

View File

@ -0,0 +1,101 @@
/*********************************************************************/
/* */
/* (c) Copyright Cisco 2000 */
/* All Rights Reserved */
/* */
/*********************************************************************/
/*********************************************************************/
/* */
/* Version : 1.0 */
/* Status : Under development */
/* File : AlarmTask.h */
/* Author(s) : Bhawani Sapkota */
/* Create Date : 9/18/2000 */
/* Description : This file contains alarm task message processing */
/* routines */
/* */
/*********************************************************************/
/* REVISION HISTORY
/*___________________________________________________________________*/
/*----------+--------+-----------------------------------------------*/
/* Name | Date | Reason */
/*----------+--------+-----------------------------------------------*/
/* Bhawani |07/14/00| Initial Draft */
/* Bhawani |11/20/00| resturctured to share among GP, GMS and GS */
/*----------+--------+-----------------------------------------------*/
/*********************************************************************/
#ifndef _ALARM_MESSAGE_CPP_
#define _ALARM_MESSAGE_CPP_
#include "AlarmTask.h"
void alarm_processTrap(TrapMsg *trapMsg)
{
/* The Oam Message */
MibTag tag = trapMsg->mibTag;
int table = MIB_TBL(tag);
int mid = MIB_ITM(tag) - 1; // need to do this
alarm_fenter("alarm_processOamMsg");
alarm_fexit();
return;
}
void alarm_processAlarmMsg(InterModuleAlarmMsg_t * alarmMsg)
{
alarm_fenter("alarm_processAlarmMsg");
switch(alarmMsg->msgType)
{
case InterModuleAlarmMsgTypeClearAlarm:
AlarmTask::theAlarmTask->delAlarmEntry(alarmMsg->srcModuleId, alarmMsg->errorTag, alarmMsg->code);
break;
case InterModuleAlarmMsgTypeRaiseAlarm:
AlarmTask::theAlarmTask->addAlarmEntry(alarmMsg->srcModuleId, alarmMsg->errorTag, alarmMsg->code, alarmMsg->arg1, alarmMsg->arg2);
break;
case InterModuleAlarmMsgTypeShutdown:
AlarmTask::theAlarmTask->quit();
break;
case InterModuleAlarmMsgTypeReboot:
AlarmTask::theAlarmTask->quit();
break;
default:
alarm_warning(("Not recognized alarm message type (message type = %d)", alarmMsg->msgType));
break;
}
alarm_fexit();
return;
}
void alarm_processMsg(char *inComingMsg)
{
/* process the trap message here*/
alarm_fenter("alarm_processMsg");
alarm_debug(("A new message has just arrived.\n"));
switch(inComingMsg[0])
{
case MNET_MODULE_SNMP:
alarm_processTrap((TrapMsg *) inComingMsg);
break;
case MY_MODULE_ID:
alarm_processAlarmMsg((InterModuleAlarmMsg_t *) inComingMsg);
break;
default:
alarm_error(("Message from unsupported module (ID = %d)\n", inComingMsg[0]));
}
alarm_fexit();
}
#endif /* _ALARM_MESSAGE_CPP_ */

View File

@ -0,0 +1,441 @@
/*********************************************************************/
/* */
/* (c) Copyright Cisco 2000 */
/* All Rights Reserved */
/* */
/*********************************************************************/
/*********************************************************************/
/* */
/* Version : 1.0 */
/* Status : Under development */
/* File : AlarmTask.h */
/* Author(s) : Bhawani Sapkota */
/* Create Date : 9/18/2000 */
/* Description : This file contains alarm task module handling */
/* routines */
/* */
/*********************************************************************/
/* REVISION HISTORY
/*___________________________________________________________________*/
/*----------+--------+-----------------------------------------------*/
/* Name | Date | Reason */
/*----------+--------+-----------------------------------------------*/
/* Bhawani |07/14/00| Initial Draft */
/* Bhawani |11/20/00| resturctured to share among GP, GMS and GS */
/*----------+--------+-----------------------------------------------*/
/*********************************************************************/
#ifndef _ALARM_MODULE_CPP_
#define _ALARM_MODULE_CPP_
#include "AlarmTask.h"
#include <time.h>
Alarm_severity_t getSeverity(AlarmCode_t acode)
{
Alarm_severity_t severity = Alarm_info;
int tmp = (acode & 0xFFFF);
if (tmp < ALARM_CRITICAL_START_POINT)
{
severity = Alarm_info;
} else if (tmp < ALARM_MAJOR_START_POINT) {
severity = Alarm_critical;
} else if (tmp < ALARM_MINOR_START_POINT) {
severity = Alarm_major;
} else if (tmp < ALARM_INFO_START_POINT) {
severity = Alarm_minor;
} else {
severity = Alarm_info;
}
return severity;
}
int AlarmTask::generateNextId()
{
alarm_fenter("AlarmTask::generateNextId");
static unsigned long id = 0;
if(id == 0)
{
getLastId( &id);
alarm_debug(("Last Module ID = %d\n", id ));
}
alarm_fexit();
return id++;
}
AlarmCode_t AlarmTask::getMdlStatus(MNET_MODULE_ID mid)
{
if (mid >=0 && mid < MNET_MAX_MODULE_IDS)
{
if (_ms[mid])
return (_ap[mid].code);
}
return EC_COMMON_NOERROR;
}
AlarmEntry_t *AlarmTask::allocEntry(MNET_MODULE_ID mid)
{
int i = 0;
while ( _ap[i].code != EC_COMMON_NOERROR)
{
if ( i == ALARM_max_outstanding)
return NULL;
i++;
}
_ap[i].next = NULL;
if (mid >=0 && mid < MNET_MAX_MODULE_IDS)
{
if (_ms[mid] == NULL)
{
_ms[mid] = &_ap[i];
}
else
{
AlarmEntry_t * tmpentry = _ms[mid];
while ( tmpentry->next != NULL)
tmpentry = tmpentry->next;
tmpentry->next = &_ap[i];
}
return &_ap[i];
}
return NULL;
}
EnableDisableState_t AlarmTask::updateOperationalState()
{
int i = 0;
EnableDisableState_t state = stateEnabled;
while ((state == stateEnabled) && (i < MNET_MAX_MODULE_IDS))
{
AlarmEntry_t * tmpentry = _ms[i];
while(tmpentry)
{
if (tmpentry->severity == Alarm_critical)
{
state = stateDisabled;
break;
}
tmpentry = tmpentry->next;
}
i++;
}
if ( (state == stateEnabled) && (i == MNET_MAX_MODULE_IDS))
{
// enable operational state
setOperationState(stateEnabled);
// set mib control state enable (in case this is first time)
if (_mibAccessState == false)
{
setMibAcessControlState(stateEnabled);
}
} else {
// disable operation state
setOperationState(stateDisabled);
}
return state;
}
void AlarmTask::updateModuleLastError(MNET_MODULE_ID mid, MibTag moduleErrorTag)
{
AlarmEntry_t * curnode = _ms[mid];
AlarmCode_t errorcode = EC_COMMON_NOERROR;
alarm_fenter("AlarmTask::updateModuleLastError");
while(curnode)
{
errorcode = curnode->code;
curnode = curnode->next;
}
setModuleLastError(moduleErrorTag, errorcode);
alarm_fexit();
}
bool AlarmTask::addAlarmEntry(MNET_MODULE_ID mid, MibTag moduleErrorTag, AlarmCode_t errorCode, char *arg1, char *arg2)
{
bool status = true;
Alarm_severity_t severity;
int id;
AlarmEntry_t *aentry;
alarm_fenter("addAlarmEntry");
aentry = findAlarmEntry(mid, errorCode);
if (aentry != NULL)
{
alarm_warning(("Alarm (code = 0x%06x) was raised %d times by %s, since UTC %s",
errorCode, ++aentry->count, GetMnetModuleName(mid), ctime(&aentry->utc)));
return true;
}
severity = getSeverity(errorCode);
if (severity < Alarm_max_severity)
{
_statistics[0][severity]++;
_statistics[1][severity]++;
}
switch (severity)
{
case Alarm_critical:
/* disable Network Elelemt Operational state if it is not already disabled */
setOperationState(stateDisabled);
case Alarm_major:
case Alarm_minor:
case Alarm_info:
aentry = allocEntry(mid);
id = generateNextId();
if (aentry )
{
aentry->count = 1;
aentry->code = errorCode;
aentry->id = id;
aentry->severity = severity;
aentry->utc = time(NULL);
} else {
alarm_error(("Too many alarm entries.\n"));
}
updateModuleLastError(mid, moduleErrorTag);
reportNewAlarm(id, mid, errorCode, severity, arg1, arg2);
break;
default:
alarm_error(("Illegle Severity code\n"));
break;
}
alarm_fexit();
return status;
}
AlarmEntry_t * AlarmTask::findAlarmEntry(MNET_MODULE_ID mid, AlarmCode_t errorCode)
{
AlarmEntry_t * curnode = _ms[mid];
while (curnode )
{
if (curnode->code == errorCode)
return curnode;
curnode= curnode->next;
}
return NULL;
}
bool AlarmTask::delAlarmEntry(MNET_MODULE_ID mid, MibTag moduleErrorTag, AlarmCode_t errorCode)
{
bool status = true;
char prevAlarm[20];
char prevId[20];
AlarmCode_t lastError = (AlarmCode_t) 0;
Alarm_severity_t severity;
int lastId = 0;
memset(prevAlarm, 0, 20);
if ((mid >=0) && (mid < MNET_MAX_MODULE_IDS))
{
AlarmEntry_t * curnode = _ms[mid];
AlarmEntry_t * prevnode = curnode;
if (errorCode == EC_COMMON_NOERROR)
{
// clear all the error for this module
_ms[mid] = NULL;
while (curnode )
{
prevnode = curnode;
curnode = curnode->next;
severity = getSeverity(prevnode->code);
if (severity < Alarm_max_severity)
{
_statistics[1][severity]--;
}
lastError = prevnode->code;
lastId = prevnode->id;
prevnode->code = EC_COMMON_NOERROR;
prevnode->next = NULL;
}
} else {
while (curnode && (curnode->code != errorCode))
{
prevnode = curnode;
curnode = curnode->next;
}
if (curnode)
{
if (curnode == prevnode)
{
// the first node
_ms[mid] = curnode->next;
} else {
prevnode->next = curnode->next;
}
severity = getSeverity(curnode->code);
if (severity < Alarm_max_severity)
{
_statistics[1][severity]--;
}
lastError = prevnode->code;
lastId = prevnode->id;
curnode->code = EC_COMMON_NOERROR;
curnode->next = NULL;
}
}
int id = generateNextId();
sprintf(prevAlarm,"%d", lastError);
sprintf(prevId, "%d", lastId);
reportNewAlarm(id, mid, EC_COMMON_NOERROR, Alarm_info, prevAlarm, prevId);
updateOperationalState();
updateModuleLastError(mid, moduleErrorTag);
} else {
status = false;
}
return status;
}
void AlarmTask::reportNewAlarm(int id, MNET_MODULE_ID mid, AlarmCode_t ecode, Alarm_severity_t severity,
char * arg1, char * arg2)
{
extern bool alarm_sendAlarmEventToAms(ubyte4, ubyte4, ubyte4, ubyte4, char*, char*);
char strMsg[ALARM_maxMsgSize];
time_t ltime;
int posCount = 0;
alarm_fenter("AlarmTask::reportNewAlarm");
alarm_debug(("Formating alarm message to the GUI\n"));
memset((void *) strMsg,0,ALARM_maxMsgSize);
posCount += sprintf(strMsg + posCount, "%d|", id);
/* Get current local time */
time( &ltime );
posCount += sprintf(strMsg + posCount, "%ld|", ltime);
posCount += sprintf(strMsg + posCount, "%d|", severity);
posCount += sprintf(strMsg + posCount, "%d|", mid);
posCount += sprintf(strMsg + posCount, "%s|", GetMnetModuleName(mid));
posCount += sprintf(strMsg + posCount, "%d", ecode);
if (arg1 != NULL)
posCount += sprintf(strMsg + posCount, "|%s", arg1);
if(arg2 != NULL)
posCount += sprintf(strMsg + posCount, "|%s", arg2);
for (int i = posCount; i < ALARM_record_length-1; i++)
strMsg[i] = ' ';
strMsg[ALARM_record_length-1] = '\n';
strMsg[ALARM_record_length] = '\0';
// Broadcast message to all the Java Client Applets
alarm_broadcast(strMsg);
// we write to flash for all events
saveAlarm(strMsg);
// Send message to First AMS server
alarm_sendAlarmEventToAms(id, ecode, ltime, mid, arg1, arg2);
if (ecode == 0)
{
alarm_warning(("Alarm (Id = %d) in module \"%s\" has been cleared\n", id, GetMnetModuleName( mid)));
} else {
alarm_warning(("The module \"%s\" has raised an alarm (Id= %d, Code = %d)\n", GetMnetModuleName(mid), id, ecode));
}
alarm_fexit();
}
extern "C" void AlarmPrintStatus()
{
AlarmTask::theAlarmTask->printStatus();
}
void AlarmTask::printStatus()
{
int i;
AlarmEntry_t * tmpentry;
printf("\nNetwork Element Operational State: %d\n", getOperationState());
printf("Mib Access Status: %d\n", _mibAccessState);
printf("\nAlarm Statistics:\n");
printf("Total Alarms in this session:\n");
printf("\tCritical: %d\n", _statistics[0][Alarm_critical]);
printf("\tMajor: %d\n", _statistics[0][Alarm_major]);
printf("\tMinor: %d\n", _statistics[0][Alarm_minor]);
printf("\tInformational: %d\n", _statistics[0][Alarm_info]);
printf("Total Outstanding Alarms:\n");
printf("\tCritical: %d\n", _statistics[1][Alarm_critical]);
printf("\tMajor: %d\n", _statistics[1][Alarm_major]);
printf("\tMinor: %d\n", _statistics[1][Alarm_minor]);
if (_statistics[1][Alarm_critical]
+ _statistics[1][Alarm_major]
+ _statistics[1][Alarm_minor])
{
printf("%20s%20s\n", "MODULE NAME", "Outstanding Alarms");
printf("%20s%20s\n", "===========", "===================");
for(i=0; i< MNET_MAX_MODULE_IDS; i++)
{
if (_ms[i])
{
tmpentry = _ms[i];
printf("%20s ", GetMnetModuleName((MNET_MODULE_ID)i));
while(tmpentry)
{
printf(" %06x", tmpentry->code);
tmpentry = tmpentry->next;
}
printf("\n");
}
}
}
}
void AlarmTask::getOutstandingAlarmCount(ubyte1 &critical, ubyte1 &major, ubyte1 &minor)
{
critical = _statistics[1][Alarm_critical];
major= _statistics[1][Alarm_major];
minor= _statistics[1][Alarm_minor];
}
#endif /* _ALARM_MODULE_CPP_ */

View File

@ -0,0 +1,445 @@
/*********************************************************************/
/* */
/* (c) Copyright Cisco 2000 */
/* All Rights Reserved */
/* */
/*********************************************************************/
/*********************************************************************/
/* */
/* Version : 1.0 */
/* Status : Under development */
/* File : AlarmTask.h */
/* Author(s) : Bhawani Sapkota */
/* Create Date : 9/18/2000 */
/* Description : This file contains alarm task socket handling */
/* routines */
/* */
/*********************************************************************/
/* REVISION HISTORY
/*___________________________________________________________________*/
/*----------+--------+-----------------------------------------------*/
/* Name | Date | Reason */
/*----------+--------+-----------------------------------------------*/
/* Bhawani |07/14/00| Initial Draft */
/* Bhawani |11/20/00| resturctured to share among GP, GMS and GS */
/* Bhawani |03/10/01| Added alarm_raiseForGp10 Api */
/*----------+--------+-----------------------------------------------*/
/*********************************************************************/
#ifndef _ALARM_SOCKET_CPP_
#define _ALARM_SOCKET_CPP_
#include "AlarmTask.h"
#include "alarm_interface.h"
#include <time.h>
#include <selectLib.h>
typedef int OS_SPECIFIC_SOCKET_HANDLE;
/*-----------------------------------------------------------------------*/
static OS_SPECIFIC_SOCKET_HANDLE SOCKET_UdpCreate()
{
alarm_fenter("SOCKET_UdpCreate");
OS_SPECIFIC_SOCKET_HANDLE soc = socket(AF_INET, SOCK_DGRAM, 0);
if (ERROR == soc)
{
alarm_error(("Could not open datagram socket %s\n", strerror(errno)));
}
alarm_fexit();
return soc;
}
/*-----------------------------------------------------------------------*/
static bool SOCKET_UdpBind(OS_SPECIFIC_SOCKET_HANDLE soc, ubyte2 port)
{
struct sockaddr_in LocalAddr;
bool status = true;
alarm_fenter("SOCKET_UdpBind");
/* ask the system to allocate a port and bind to INADDR_ANY */
memset(&LocalAddr, 0x00, sizeof(LocalAddr));
/* get system to allocate a port number by binding a host address */
LocalAddr.sin_family = AF_INET;
LocalAddr.sin_addr.s_addr = htonl(INADDR_ANY);
LocalAddr.sin_port = htons(port);
/* bind socket to local address */
if (ERROR == bind(soc, (struct sockaddr *) &LocalAddr, sizeof(LocalAddr)))
{
alarm_error(("Could not bind datagram socket to port %d: %s\n", port, strerror(errno)));
status = false;
}
alarm_fexit();
return status;
}
/*-----------------------------------------------------------------------*/
static bool SOCKET_SetRecvBuffer(OS_SPECIFIC_SOCKET_HANDLE soc, int nBytes)
{
alarm_fenter("SOCKET_SetRecvBuffer");
bool status = true;
if (ERROR == setsockopt(soc, SOL_SOCKET, SO_RCVBUF, (char *) &nBytes, sizeof(int)))
{
alarm_error(("Could not set Receive buffer to %d\n", nBytes));
status = false;
}
alarm_fexit();
return status;
}
/*-----------------------------------------------------------------------*/
void SOCKET_UdpClearRecvQ(OS_SPECIFIC_SOCKET_HANDLE sock)
{
struct timeval timeout;
fd_set readFdSet;
static char buffer[512];
int bufferlen = 512;
struct sockaddr_in Addr;
int iAddrLen;
alarm_fenter("SOCKET_UdpClearInQueue");
timeout.tv_sec = 0;
timeout.tv_usec = 0;
FD_ZERO(&readFdSet);
FD_SET(sock, &readFdSet);
if(select(FD_SETSIZE, &readFdSet, NULL, NULL, &timeout) > 0)
{
/* Socket is ready for reading */
bufferlen = recvfrom(sock, buffer, bufferlen, 0, (struct sockaddr *)&Addr, &iAddrLen);
if (bufferlen > 0)
{
alarm_warning (("Cleared %d bytes of unexpected data from %s:%u\n",
bufferlen, inet_ntoa(Addr.sin_addr), Addr.sin_port));
}
}
alarm_fexit();
}
/*-----------------------------------------------------------------------*/
extern bool
SOCKET_UdpSendTo(OS_SPECIFIC_SOCKET_HANDLE sock,
struct sockaddr_in *pAddrTo,
char *message,
ubyte4 msglen)
{
alarm_fenter("SOCKET_UdpSendTo");
bool status = true;
char pszIPbuf[20];
if (ERROR == sendto(sock, message, msglen, 0,
(struct sockaddr *) pAddrTo,
sizeof(struct sockaddr)) )
{
status = false;
}
inet_ntoa_b(pAddrTo->sin_addr, pszIPbuf);
alarm_debug(( "Sending %d bytes to Alarm server (ip=%s, port=%d) \n", msglen, pszIPbuf, ntohs(pAddrTo->sin_port)));
alarm_dump((ubyte1 *) message, msglen);
// clear any message in the incoming queue
SOCKET_UdpClearRecvQ(sock);
alarm_fexit();
return status;
}
/*-----------------------------------------------------------------------*/
extern bool
SOCKET_UdpReceive(OS_SPECIFIC_SOCKET_HANDLE sock,
char *msg,
ubyte4 *msgSize,
ubyte4 *peerAddr)
{
struct sockaddr_in pAddr;
int iAddrLen;
int retval = recvfrom(sock, msg, *msgSize, 0, (struct sockaddr *)&pAddr, &iAddrLen );
if (retval == ERROR)
{
*msgSize = 0;
return false;
}
*msgSize = retval;
*peerAddr = pAddr.sin_addr.s_addr;
return true;
}
/*-----------------------------------------------------------------------*/
extern bool SOCKET_Close(OS_SPECIFIC_SOCKET_HANDLE sock)
{
bool retval = true;
alarm_fenter("SOCKET_Close");
if (ERROR == close(sock) )
{
alarm_error(("Could not close socket %s\n", strerror(errno)));
retval = false;
}
alarm_fexit();
return retval;
}
/*-----------------------------------------------------------------------*/
ubyte4 GetHostAddress(char *pszHostName)
{
return hostGetByName ( pszHostName );
}
/*-----------------------------------------------------------------------*/
static ubyte4 GetLocalHostAddress()
{
#define MAX_PATH 80
char szHostName[MAX_PATH];
ubyte4 ulHostAddr = 0;
if (ERROR != gethostname(szHostName, MAX_PATH-1))
ulHostAddr = GetHostAddress ( szHostName );
return (ulHostAddr);
}
/*-----------------------------------------------------------------------*/
static bool initialized = false;
/*
static AlarmViperCellToAmsMsg amsMsg;
*/
static struct sockaddr_in addrTo;
static OS_SPECIFIC_SOCKET_HANDLE sock;
bool
initSocketAndMsgHdr()
{
char pszIpBuf[20];
alarm_fenter("initSocketAndMsgHdr");
if (!initialized)
{
int ip;
/* 1. prepare udp socket */
sock = SOCKET_UdpCreate();
if (sock == ERROR)
{
alarm_fexit();
return false;
}
if (SOCKET_UdpBind(sock, ALARM_interfaceUdpPortClient) != true)
{
SOCKET_Close(sock);
alarm_fexit();
return false;
}
/* 2. get IP address from MIB */
if (oam_getMibIntVar(MY_MIB_APM1_IP_ADDRESS, (long *) &ip) != STATUS_OK)
{
// alarm_error(("Unable to get alarm server's IP from the MIB\n"));
SOCKET_Close(sock);
return false;
}
/* 3. prepare the the server's address */
memset (&addrTo, 0, sizeof(sockaddr_in));
addrTo.sin_family = AF_INET;
addrTo.sin_addr.s_addr = ip;
addrTo.sin_port = htons((ubyte2)ALARM_interfaceUdpPortServer);
inet_ntoa_b( addrTo.sin_addr, pszIpBuf);
/* Set small receive buffer */
SOCKET_SetRecvBuffer(sock, ALARM_defaultRecvBuffer);
alarm_debug (("APM1 server: ip = %s, port=%d\n", pszIpBuf, ALARM_interfaceUdpPortServer));
initialized = true;
}
alarm_fexit();
return true;
}
/*-----------------------------------------------------------------------*/
bool
alarm_sendAlarmEventToAms(ubyte4 id, ubyte4 code, ubyte4 timestamp, ubyte4 moduleId, char* opt1, char* opt2)
{
AlarmViperCellToAmsMsg amsMsg;
ubyte4 opt;
alarm_fenter("alarm_sendAlarmMsgToAms");
if (!initSocketAndMsgHdr())
{
alarm_fexit();
return false;
}
memset(&amsMsg, 0, sizeof(AlarmViperCellToAmsMsg));
amsMsg.hdr.alarmSrcType = (ubyte1) MY_PRODUCT_ID;
amsMsg.hdr.alarmMsgType = ALARM_msgTypAlarmEvent;
amsMsg.hdr.alarmMsgLen = htons(sizeof(AlarmEventData));
strncpy(amsMsg.body.eventData.alarmSrcModuleName, GetMnetModuleName((MNET_MODULE_ID)moduleId),
ALARM_viperCellNameMaxSize);
amsMsg.body.eventData.alarmSrcIp = GetLocalHostAddress();
amsMsg.body.eventData.alarmId = htonl(id);
amsMsg.body.eventData.alarmCode = htonl(code);
amsMsg.body.eventData.alarmTimestamp = htonl(timestamp);
amsMsg.body.eventData.alarmSrcModuleId = htonl(moduleId);
if (NULL != opt1)
{
opt = atoi(opt1);
amsMsg.body.eventData.opt1 = htonl(opt);
}
if (NULL != opt1)
{
opt = atoi(opt2);
amsMsg.body.eventData.opt2 = htonl(opt);
}
SOCKET_UdpSendTo(sock, &addrTo, (char *) &amsMsg, ALARM_eventMsgLen);
alarm_fexit();
return true;
}
/*-----------------------------------------------------------------------*/
#ifdef MNET_PRODUCT_SPECIFIC_GMC
JC_STATUS alarm_raiseForGp10
(
MNET_MODULE_ID mid, /* Gp10 source module ID */
AlarmCode_t alarm_code, /* Gp10 Alarm code */
unsigned long ip, /* GP10 IP address */
char *sourceName /* GP10's official name */
)
{
AlarmViperCellToAmsMsg amsMsg;
const int MODULE_VBLINK = 0x11; /* ViperBase - ViperCell link client */
static char gp10SrcName[] = "VBLink"; /* GP10's Module name */
alarm_fenter("alarm_raiseForGp10");
if (!initSocketAndMsgHdr())
{
alarm_fexit();
return JC_ERROR;
}
memset(&amsMsg, 0, sizeof(AlarmViperCellToAmsMsg));
amsMsg.hdr.alarmSrcType = (ubyte1) MNET_PRODUCT_GP10;
amsMsg.hdr.alarmMsgType = ALARM_msgTypAlarmEvent;
amsMsg.hdr.alarmMsgLen = htons(sizeof(AlarmEventData));
strncpy(amsMsg.body.eventData.alarmSrcModuleName, gp10SrcName, ALARM_viperCellNameMaxSize);
amsMsg.body.eventData.alarmSrcIp = ip;
amsMsg.body.eventData.alarmId = htonl(ALARM_unknownAlarmId);
amsMsg.body.eventData.alarmCode = htonl(alarm_code);
amsMsg.body.eventData.alarmTimestamp = htonl(time(NULL));
amsMsg.body.eventData.alarmSrcModuleId = htonl(mid);
SOCKET_UdpSendTo(sock, &addrTo, (char *) &amsMsg, ALARM_eventMsgLen);
alarm_fexit();
return true;
}
#endif
/*-----------------------------------------------------------------------*/
bool AlarmTask::sendSummaryUpdateToAms()
{
AlarmViperCellToAmsMsg amsMsg;
alarm_fenter("AlarmTask::sendSummaryUpdateToAms");
ubyte1 critical, major, minor;
if (!initSocketAndMsgHdr())
{
alarm_fexit();
return false;
}
/* 4. initialize the fixed fields */
memset(&amsMsg, 0, sizeof(AlarmViperCellToAmsMsg));
// populate the header
amsMsg.hdr.alarmSrcType = ALARM_srcTypViperCell;
amsMsg.hdr.alarmMsgType = ALARM_msgTypSummaryUpdate;
amsMsg.hdr.alarmMsgLen = htons(sizeof(AlarmSummaryUpdateData));
strncpy(amsMsg.body.summaryUpdateData.alarmSrcName, AlarmTask::srcName(),
ALARM_viperCellNameMaxSize);
amsMsg.body.summaryUpdateData.alarmSrcIp = GetLocalHostAddress();
getOutstandingAlarmCount(critical, major, minor);
amsMsg.body.summaryUpdateData.alarmCriticalCount = critical;
amsMsg.body.summaryUpdateData.alarmMajorCount = major;
amsMsg.body.summaryUpdateData.alarmMinorCount = minor;
SOCKET_UdpSendTo(sock, &addrTo, (char *) &amsMsg, ALARM_summaryUpdateMsgLen);
alarm_fexit();
return true;
}
void AlarmTask::quit ()
{
_quit = true;
}
void AlarmTask::closeSocket ()
{
initialized = false;
SOCKET_Close(sock);
}
#endif /* _ALARM_SOCKET_CPP_ */

View File

@ -0,0 +1,173 @@
/*********************************************************************/
/* */
/* (c) Copyright Cisco 2000 */
/* All Rights Reserved */
/* */
/*********************************************************************/
/*********************************************************************/
/* */
/* Version : 1.0 */
/* Status : Under development */
/* File : AlarmTask.h */
/* Author(s) : Bhawani Sapkota */
/* Create Date : 9/18/2000 */
/* Description : This file contains alarm task syscommand handling */
/* routines */
/* */
/*********************************************************************/
/* REVISION HISTORY
/*___________________________________________________________________*/
/*----------+--------+-----------------------------------------------*/
/* Name | Date | Reason */
/*----------+--------+-----------------------------------------------*/
/* Bhawani |07/14/00| Initial Draft */
/* Bhawani |11/20/00| resturctured to share among GP, GMS and GS */
/* Bhawani |03/09/01| Changed alarm log directory to match others */
/*----------+--------+-----------------------------------------------*/
/*********************************************************************/
#ifndef __ALARM_SYSCMD_CPP__
#define __ALARM_SYSCMD_CPP__
#include "AlarmTask.h"
/*
*********************************************************************
** Global variables
********************************************************************
*/
/* Initialize the alarm task */
AlarmTask::AlarmTask(char *name): JCTask(name)
{
alarm_fenter("AlarmTask::AlarmTask");
if (isOneCreated == false)
{
int size, i,j;
// Initialize the message queue first
jcMsgQ = new JCMsgQueue(ALARM_q_maxMsgs, ALARM_q_maxMsgLength, MSG_Q_FIFO);
#ifdef MNET_PRODUCT_SPECIFIC_GP10
// Initialize the timer
initTimer = new JCCTimer( (FUNCPTR ) &AlarmTask::bootupTimeoutHandler);
initTimer->setTimer(ALARM_mib_lock_timeout);
#else
_mibAccessState = stateEnabled;
#endif
// message receive buffer
_msgRecvBuff = new char[ALARM_q_maxMsgLength];
_mnetbase = getenv( "MNET_BASE" );
// compute the log file size
size = strlen(_mnetbase) + strlen(ALARM_logFile) + 1;
_logfilename = new char[size];
sprintf(_logfilename, "%s%s", _mnetbase, ALARM_logFile);
// initialize the module status table
for (i = 0; i < MNET_MAX_MODULE_IDS; i++)
_ms[i] = NULL;
// initialize the alarm pool
_ap = new AlarmEntry_t[ALARM_max_outstanding];
for (i =0; i <ALARM_max_outstanding; i++)
{
_ap[i].code = EC_COMMON_NOERROR;
_ap[i].next = NULL;
}
for (i=0; i <2; i++)
for (j=0; j< Alarm_max_severity; j++)
_statistics[i][j] = 0;
theAlarmTask = this;
populateSourceName();
isOneCreated = true;
}
alarm_fexit();
}
int AlarmTask::bootupTimeoutHandler()
{
alarm_fenter("alarm_bootupTimeoutHandler");
/* The timer has expired and mib access needs to be enabled. */
theAlarmTask->setMibAcessControlState(stateEnabled);
alarm_warning(("The system did not complete reboot. Mib access has been re-enabled\n"));
alarm_fexit();
return 0;
}
int SysCommand_Alarm (T_SYS_CMD action)
{
char *home;
JC_STATUS status = OK;
alarm_fenter("SysCommand_Alarm");
switch(action)
{
case SYS_SHUTDOWN:
break;
case SYS_REBOOT:
alarm_warning(("Reboot notification has been received\n"));
AlarmTask::theAlarmTask->alarmSend(InterModuleAlarmMsgTypeReboot, MY_MODULE_ID);
break;
case SYS_START:
alarm_debug(("Alarm initialization has been invoked\n"));
/* Get the value of the MNET_BASE environment variable. */
home = getenv( "MNET_BASE" );
if( home == NULL )
{
alarm_error(("Environment variable \"MNET_BASE\" must be defined!!\n"));
alarm_fexit();
return ERROR;
}
{
AlarmTask *mytask = new AlarmTask(ALARM_task_name);
#ifdef MNET_PRODUCT_SPECIFIC_GP10
/* block the mib access */
mytask->setMibAcessControlState(stateDisabled);
#endif
status = mytask->JCTaskSpawn(
ALARM_TASK_PRIORITY,
ALARM_TASK_OPTION,
ALARM_TASK_STACK_SIZE,
(FUNCPTR) AlarmTask::entryPoint,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
MY_MODULE_ID, JC_CRITICAL_TASK);
if(status == JC_ERROR)
{
alarm_error(("Alarm task spawn failure\n"));
status = ERROR;
}
}
break;
default:
alarm_warning(("Unknown SysCommand: %d\n", action));
status = ERROR;
break;
}
alarm_fexit();
return status;
}
#endif /* __ALARM_SYSCMD_CPP__ */

View File

@ -0,0 +1,102 @@
import java.awt.*;
import java.awt.event.*;
import java.lang.String;
import javax.swing.*;
import javax.swing.event.*;
import java.net.UnknownHostException;
import com.jetcell.MibWM.*;
import java.net.*;
public class Alarm{
public AlarmPanel alarmPanel = null;
JFrame f = null;
AlarmTCPThread commObj = null;
FilterFrame filterFrame = null;
public final static int AM_APPLET_PORT2 = 11798;
JPanel jpanel = null;
// Shrinivas 23rd Apr 01
public Alarm(String viperbaseIp, final String vipercellIp){
// Shrinivas end
JButton setFilterButton = new JButton("Set Filter");
final Dimension d = new JFrame().getToolkit().getScreenSize();
if (f == null){
alarmPanel = new AlarmPanel(viperbaseIp);
jpanel = alarmPanel.createPanel();
alarmPanel.setViperCellIp(vipercellIp);//passing on viperCellIp to panel
JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
southPanel.add(setFilterButton);
f = new JFrame("Alarm List for source: "+vipercellIp);
// Shrinivas 23rd Apr 01
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent evt){
AlarmStatusTable.removeAlarmSrcIp(vipercellIp);
destroy();
}
});
// Shrinivas end
if(Util.applet == null){
f.setIconImage(Toolkit.getDefaultToolkit().getImage("../Images/app_icon.gif"));
}
else{
String iconPath = Util.applet.getCodeBase().toString();
iconPath += "Images/app_icon.gif";
URL iconPathURL = null;
try{
iconPathURL = new URL(iconPath);
}
catch(MalformedURLException exc){
System.out.println("Bad URL.");
}
System.out.println(iconPathURL);
f.setIconImage(Toolkit.getDefaultToolkit().getImage(iconPathURL));
}
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(southPanel,BorderLayout.SOUTH);
f.getContentPane().add(jpanel,BorderLayout.CENTER);
f.setBounds(0,0, 720,400);
f.setLocation(d.width/5,d.height/5);
f.setVisible(true);
}
else
f.setVisible(true);
if (commObj == null)
commObj = new AlarmTCPThread(viperbaseIp, AM_APPLET_PORT2);
commObj.startReadThread(alarmPanel, vipercellIp, true);
setFilterButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
AlarmStatusApplet.logDM("Launch filter screen");
filterFrame = new FilterFrame(alarmPanel);
filterFrame.setLocation(d.width/4,d.width/5);
if(Util.applet == null){
filterFrame.setTitle("Filter for user : " + AlarmTCPThread.user.toUpperCase());
}
else{
filterFrame.setTitle("Filter Screen");
}
filterFrame.setResizable(false);
filterFrame.setVisible(true);
}
});
}
public void start(String vipercellIp){
f.setTitle("Alarm List for source: "+vipercellIp);
f.setVisible(true);
alarmPanel.setViperCellIp(vipercellIp);//passing on viperCellIp to panel
commObj.startReadThread(alarmPanel, vipercellIp, false);
}
public void destroy(){
System.out.println("Destroy method has been called");
commObj.finishReadThread();
}
}

View File

@ -0,0 +1,139 @@
/*
* AlarmStatusApplet.java
* Kevin Lim
* 03/20/00
*/
import com.jetcell.MibWM.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;
import java.lang.String;
import javax.swing.*;
import javax.swing.text.Document;
import javax.swing.event.*;import java.net.*;
import java.net.UnknownHostException;
public class AlarmStatusApplet extends JApplet{
public static String ip = null;
public static int port = 11798; /*11800;*/
AlarmStatusPanel alarmPanel = null;
JFrame f = null;
static AlarmTCPThread commObj = null;
public static boolean isDebug = false;
public void init(){
Util.applet = this;
String newin = getParameter("NEWWINDOW");
ip = getParameter("HOST");
port = Integer.parseInt(getParameter("PORT"));
createUIPanel(newin);
}
// changes by Shrinivas : the code under this method were under the above init() method
// earlier. Function split was done so that the code could run both as an applet and an application
protected void createUIPanel(String newin){
alarmPanel = new AlarmStatusPanel();
if (f != null){
f.setVisible(true);
}
else {
if (newin != null){
System.out.println("NEWWINDOW VALUE = " +newin);
if(newin.equals("FALSE") || newin.equals("false")){
getContentPane().setLayout(new BorderLayout());
getContentPane().add(alarmPanel.createPanel(this),BorderLayout.CENTER);
}
else {
f = new JFrame("Alarm Status List for " + ip);
f.setIconImage(Toolkit.getDefaultToolkit().getImage("../Images/app_icon.gif"));
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(alarmPanel.createPanel(this));
f.setBounds(0,0, 720,400);
f.setVisible(true);
}
}
else {
System.out.println("Please set NEWWINDOW parameter to TRUE or FALSE");
System.out.println("Assuming - no new window");
getContentPane().setLayout(new BorderLayout());
getContentPane().add(alarmPanel.createPanel(this),BorderLayout.CENTER);
}
}
commObj = new AlarmTCPThread(ip, port);
commObj.startReadThread(alarmPanel);
}
public void start(){
System.out.println("Applet started");
}
public void stop(){
System.out.println("Applet stopped");
if (commObj != null){
commObj.finishReadThread();
commObj = null;
}
}
public void destroy(){
System.out.println("Destroy method has been called");
}
public void sendRemoveReq(AlarmStatusData data){
commObj.sendRemoveReq(data);
}
public void sendUpdateReq(){
commObj.sendUpdateReq();
}
public static void logDM(String message){
if(isDebug){
System.out.println(message);
}
}
public static void stopAPM1(){
if(commObj != null)
commObj.finishReadThread();
}
public static void startAPM1(String ipStr,boolean debug,String user){
isDebug = debug;
final JFrame frame = new JFrame();
try {
InetAddress.getByName(ipStr);
}
catch (UnknownHostException ex) {
JOptionPane.showMessageDialog(frame,"Invalid Host ID:","Error",JOptionPane.ERROR_MESSAGE);
return;
}
ip = ipStr;
final JApplet applet = new AlarmStatusApplet();
((AlarmStatusApplet)applet).createUIPanel("false");
AlarmTCPThread.user = user;
frame.setContentPane(applet.getContentPane());
frame.setBounds(0,0, 720,400);
frame.setTitle("Alarm Status List for " + ip);
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("../Images/app_icon.gif"));
Dimension d = new JFrame().getToolkit().getScreenSize();
frame.setLocation(d.width/10,d.height/10);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e){
applet.stop();
}
});
}
}

View File

@ -0,0 +1,139 @@
/*
* AlarmStatusData.java
* Kevin Lim
* 03/20/00
*/
import java.util.StringTokenizer;
public class AlarmStatusData
{
final static byte ALARM_SRC_TYPE_VC = (byte)128;
final static byte ALARM_SRC_TYPE_VB = (byte)129;
String source_type;
String source_ip;
String source_name;
String critical;
String major;
String minor;
public AlarmStatusData( String source_type, String source_ip, String source_name,
String critical, String major, String minor)
{
this.source_type = source_type;
this.source_ip = source_ip;
this.source_name = source_name;
this.critical = critical;
this.major = major;
this.minor = minor;
}
public AlarmStatusData(byte[] msg){
int i = AlarmTCPThread.ALARM_HEAD_SRC_TYPE_POS;
extractSrcType (msg, i);
i = AlarmTCPThread.ALARM_MSG_HEADER_LEN;
extractSrcIP (msg, i);
i += AlarmTCPThread.ALARM_MSG_SRC_IP_SIZE;
extractSrcName (msg, i);
i += AlarmTCPThread.ALARM_MSG_SRC_NAME_SIZE;
extractCriCount(msg, i);
i += AlarmTCPThread.ALARM_MSG_CRITICAL_SIZE;
extractMajCount(msg, i);
i += AlarmTCPThread.ALARM_MSG_MAJOR_SIZE;
extractMinCount(msg, i);
}
public byte[] getSrcIPByte(){
byte[] ip = new byte[AlarmTCPThread.ALARM_MSG_SRC_IP_SIZE];
StringTokenizer st = new StringTokenizer(source_ip, ".");
if(st.countTokens() != 4){
System.out.println("Error on getSrcIPByte: ip token count");
return null;
}
else{
int i = 0;
while (st.hasMoreTokens()) {
ip[i++] = (byte) Integer.parseInt(st.nextToken());
}
}
return ip;
}
public byte getSrcTypeByte(){
byte type = (byte)0xFF;
if(source_type.equals("ViperCell"))
type = AlarmStatusData.ALARM_SRC_TYPE_VC;
else if(source_type.equals("ViperBase"))
type = AlarmStatusData.ALARM_SRC_TYPE_VB;
return type;
}
public int extractSrcType(byte[] msg, int i){
switch(msg[i]){
case AlarmStatusData.ALARM_SRC_TYPE_VC:
this.source_type = new String("ViperCell");
break;
case AlarmStatusData.ALARM_SRC_TYPE_VB:
this.source_type = new String("ViperBase");
break;
default:
this.source_type = new String("Unknown");
}
return (int)msg[i];
}
public void extractSrcIP(byte[] msg, int i) {
int h1 = (int)msg[i] & 0x00FF;
int h2 = (int)msg[i+1] & 0x00FF;
int h3 = (int)msg[i+2] & 0x00FF;
int h4 = (int)msg[i+3] & 0x00FF;
this.source_ip = "" + (new Integer(h1)).toString() +
"." + (new Integer(h2)).toString() +
"." + (new Integer(h3)).toString() +
"." + (new Integer(h4)).toString();
}
public void extractSrcName(byte[] msg, int i){
byte[] name = new byte[AlarmTCPThread.ALARM_MSG_SRC_NAME_SIZE];
for(int j=0; j<AlarmTCPThread.ALARM_MSG_SRC_NAME_SIZE; j++)
name[j] = msg[i+j];
this.source_name = (new String(name)).trim();
}
public void extractCriCount(byte[] msg, int i){
this.critical = (new Integer((int)msg[i] & 0x00FF)).toString();
}
public void extractMajCount(byte[] msg, int i){
this.major = (new Integer((int)msg[i] & 0x00FF)).toString();
}
public void extractMinCount(byte[] msg, int i){
this.minor = (new Integer((int)msg[i] & 0x00FF)).toString();
}
public void dump(){
System.out.println("*****************************");
System.out.println("Source Type : " + source_type);
System.out.println("Source IP : " + source_ip);
System.out.println("Source Name : " + source_name);
System.out.println("Critical Count: " + critical);
System.out.println("Major Count : " + major);
System.out.println("Minor Count : " + minor);
System.out.println("*****************************");
}
public static void main(String[] argv){
byte[] msg = { (byte)128, 1, 0, 48, 10, 1, 2, (byte)250,
(byte)'V', (byte)'i', (byte)'p', (byte)'e', (byte)'r', (byte)'1', 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3 };
AlarmStatusData data = new AlarmStatusData(msg);
data.dump();
}
}

View File

@ -0,0 +1,53 @@
/*
* AlarmStatusPanel.java
* Kevin Lim
* 03/20/00
*/
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.text.Document;
import javax.swing.event.*;
import java.net.UnknownHostException;
import java.awt.*;
import java.util.*;
public class AlarmStatusPanel{
static String host = null;
AlarmStatusTable alarmStatusTable = null;
JLabel statLabel = null;
public AlarmStatusPanel(){
}
public JPanel createPanel(JApplet applet){
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
panel.setLayout(new BorderLayout());
AlarmStatusTableModel model = new AlarmStatusTableModel();
alarmStatusTable = new AlarmStatusTable(model, applet);
JScrollPane scroller= new JScrollPane( alarmStatusTable,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED ,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(scroller, BorderLayout.CENTER);
statLabel = new JLabel("Server Status");
panel.add(statLabel, BorderLayout.SOUTH);
return panel;
}
public void addEvent(AlarmStatusData alarm){
alarmStatusTable.setAlarmStatusData(alarm);
}
public void dispStatus(String status){
statLabel.setText(status);
}
public void clearEvents() {
alarmStatusTable.RemoveAll();
}
}

View File

@ -0,0 +1,221 @@
/*
* AlarmStatusTable
* Kevin Lim
* 03/20/00
*/
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JTable;
import javax.swing.table.*;
import javax.swing.event.*;
import java.util.Hashtable;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.applet.*;
import com.jetcell.MibWM.Util;
// Shrinivas 23rd Apr 01
import java.util.*;
// Shrinivas end
public class AlarmStatusTable extends JTable {
DefaultTableModel model;
JPopupMenu popupMenu = null;
JApplet applet = null;
// Shrinivas 23rd Apr 01
//Alarm alarm = null;
static Vector alarmSrcIpList = null;
// Shrinivas end
final int [] columnMinWidth = { 30, 60, 30, 30, 30, 0};
final int [] columnMaxWidth = {200, 150, 150, 150, 150, 0};
Hashtable alarmHashTable = null;
public AlarmStatusTable(DefaultTableModel model, JApplet applet){
super(model);
// Shrinivas 23rd Apr 01
alarmSrcIpList = new Vector(8,3);
// Shrinivas end
popupMenu = AlarmStatusTablePopupMenu.getPopupMenu();
this.applet = applet;
addMouseListener(new MouseHandler(this));
alarmHashTable = new Hashtable();
for (int i=0; i < model.getColumnCount(); i++ )
setColumnWidth(i, columnMinWidth[i], columnMaxWidth[i]);
TableColumnModel colModel = getColumnModel();
colModel.getColumn(AlarmStatusTableModel.CRITICAL).setCellRenderer(new CountCellRenderer());
colModel.getColumn(AlarmStatusTableModel.MAJOR).setCellRenderer(new CountCellRenderer());
colModel.getColumn(AlarmStatusTableModel.MINOR).setCellRenderer(new CountCellRenderer());
setRowSelectionAllowed(true);
setColumnSelectionAllowed(false);
setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
setShowGrid(true);
setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
getTableHeader().setReorderingAllowed(false);
}
public void setColumnWidth(int columnIndex, int minWidth, int maxWidth){
TableColumn column = (TableColumn)getColumn(getColumnName(columnIndex));
column.setMinWidth(minWidth);
column.setMaxWidth(maxWidth);
}
public boolean isCellEditable(int i, int j){
return false;
}
public AlarmStatusData getAlarmStatusData(String source_ip){
if (alarmHashTable != null)
return (AlarmStatusData) alarmHashTable.get(source_ip);
return null;
}
public int rowAlarmStatusData(String source_ip){
int row_count = ((DefaultTableModel)getModel()).getRowCount();
for(int i=0; i<row_count; i++){
String ip = (String)getValueAt(i, AlarmStatusTableModel.SRC_IP);
if(ip.equals(source_ip))
return i;
}
return -1;
}
public void setAlarmStatusData(AlarmStatusData alarm){
int row_index;
if (getAlarmStatusData(alarm.source_ip) != null){
alarmHashTable.remove(alarm.source_ip);
alarmHashTable.put(alarm.source_ip, alarm);
row_index = rowAlarmStatusData(alarm.source_ip);
setValueAt(alarm.source_ip, row_index, AlarmStatusTableModel.SRC_IP);
setValueAt(alarm.source_name, row_index, AlarmStatusTableModel.SRC_NAME);
setValueAt(alarm.critical, row_index, AlarmStatusTableModel.CRITICAL);
setValueAt(alarm.major, row_index, AlarmStatusTableModel.MAJOR);
setValueAt(alarm.minor, row_index, AlarmStatusTableModel.MINOR);
}
else{
alarmHashTable.put(alarm.source_ip, alarm);
row_index = ((DefaultTableModel)getModel()).getRowCount();
Object [] row = new Object[AlarmStatusTableModel.NUM_COL];
row[AlarmStatusTableModel.SRC_IP] = alarm.source_ip;
row[AlarmStatusTableModel.SRC_NAME] = alarm.source_name;
row[AlarmStatusTableModel.CRITICAL] = alarm.critical;
row[AlarmStatusTableModel.MAJOR] = alarm.major;
row[AlarmStatusTableModel.MINOR] = alarm.minor;
((DefaultTableModel)getModel()).insertRow(row_index, row);
}
}
// Shrinivas 23rd Apr 01
public static void removeAlarmSrcIp(String ip){
alarmSrcIpList.remove(ip);
}
// Shrinivas end
public void OpenEvent(){
int selectedRow = getSelectedRow();
if(selectedRow == -1){
System.out.println("Open Event: no selection made");
return;
}
String ip = (String)getValueAt(selectedRow, AlarmStatusTableModel.SRC_IP);
//System.out.println("Open Event: " +ip);
// Shrinivas 23rd Apr 01
if(alarmSrcIpList.contains(ip)){
return;
}
else{
alarmSrcIpList.add(ip);
}
Alarm alarmList = new Alarm(AlarmStatusApplet.ip, ip);
/*if (alarm == null){
alarm = new Alarm(AlarmStatusApplet.ip, ip);
}
else
alarm.start(ip); */
// Shrinivas end
} // end OpenEvent()
public void Remove(){
int selectedRow = getSelectedRow();
if(selectedRow == -1){
System.out.println("Remove Event: no selection made");
return;
}
String ip = (String)getValueAt(selectedRow, AlarmStatusTableModel.SRC_IP);
System.out.println("Remove Event: " +ip);
AlarmStatusData data = getAlarmStatusData(ip);
if(data == null){
System.out.println("Remove Event: data not found");
}
else{
alarmHashTable.remove(ip);
int row_index = rowAlarmStatusData(ip);
((DefaultTableModel)getModel()).removeRow(row_index);
}
((AlarmStatusApplet)applet).sendRemoveReq(data);
}
public void RemoveAll(){
int row_count = ((DefaultTableModel)getModel()).getRowCount();
while(row_count != 0){
String ip = (String)getValueAt(0, AlarmStatusTableModel.SRC_IP);
alarmHashTable.remove(ip);
((DefaultTableModel)getModel()).removeRow(0);
row_count = ((DefaultTableModel)getModel()).getRowCount();
}
}
public void Refresh(){
((AlarmStatusApplet)applet).sendUpdateReq();
}
class MouseHandler extends MouseAdapter{
public AlarmStatusTable table;
public MouseHandler(AlarmStatusTable table){
this.table = table;
}
public void mouseReleased(MouseEvent e){
if (e.getClickCount() == 2 ){
OpenEvent();
}
if ( e.isPopupTrigger()){
// changes by Shrinivas on 17th Oct 2k
System.out.println("Event : Popup menu");
int selectedRow = rowAtPoint(new Point(e.getX(),e.getY()));
setRowSelectionInterval(selectedRow,selectedRow);
// end of changes
popupMenu.show(table, e.getX(), e.getY());
}
}
}
class CountCellRenderer extends JLabel implements TableCellRenderer{
Font defaultFont = new Font("Helvetica", Font.BOLD,12);
Font empFont = new Font("TimesRoman", Font.BOLD,18);
public CountCellRenderer(){
super("Unknown");
setHorizontalAlignment(JLabel.CENTER);
}
public Component getTableCellRendererComponent( JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column ){
setText((String)value);
return this;
}
}
}

View File

@ -0,0 +1,34 @@
/*
* AlarmStatusTableModel.java
* Kevin Lim
* 03/20/00
*/
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class AlarmStatusTableModel extends DefaultTableModel
{
final static int SRC_IP = 0;
final static int SRC_NAME = 1;
final static int CRITICAL = 2;
final static int MAJOR = 3;
final static int MINOR = 4;
static String ColumnTitle[] = {"Source IP", "Source Name", "Critical Alarm", "Major Alarm", "Minor Alarm"};
final static int NUM_COL = ColumnTitle.length;
public AlarmStatusTableModel()
{
super(ColumnTitle, 0);
}
}

View File

@ -0,0 +1,126 @@
/*
* AlarmStatusTablePopupMenu.java
* Kevin Lim
* 03/20/00
*/
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class AlarmStatusTablePopupMenu extends JPopupMenu implements ActionListener{
static JMenuItem openMenuItem;
static JMenuItem removeMenuItem;
static JMenuItem refreshMenuItem;
static boolean iconsLoaded = false;
protected static AlarmStatusTablePopupMenu popupMenu = new AlarmStatusTablePopupMenu();
static AlarmStatusTable invoker ;
static int x;
static int y;
/**
* You cannot instantiate this class. Use getPopupMenu() to get
* a shared instance!
*/
protected AlarmStatusTablePopupMenu(){
openMenuItem = new JMenuItem(new String("Open Alarm"));
openMenuItem.setMnemonic('O');
openMenuItem.registerKeyboardAction(null, KeyStroke.getKeyStroke('O', Event.ALT_MASK, false),
JComponent.WHEN_IN_FOCUSED_WINDOW);
openMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
openMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
openMenuItem.addActionListener(this);
add(openMenuItem);
removeMenuItem = new JMenuItem(new String("Remove"));
removeMenuItem.setMnemonic('m');
removeMenuItem.registerKeyboardAction(null, KeyStroke.getKeyStroke('m', Event.ALT_MASK, false),
JComponent.WHEN_IN_FOCUSED_WINDOW);
removeMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
removeMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
removeMenuItem.addActionListener(this);
add(removeMenuItem);
// Shrinivas 20th Apr 01
/*refreshMenuItem = new JMenuItem(new String("Refresh"));
refreshMenuItem.setMnemonic('R');
refreshMenuItem.registerKeyboardAction(null, KeyStroke.getKeyStroke('R', Event.ALT_MASK, false),
JComponent.WHEN_IN_FOCUSED_WINDOW);
refreshMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
refreshMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
refreshMenuItem.addActionListener(this);
add(refreshMenuItem);*/
// Shrinivas end
}
/**
* returns shared instance of popupMenu
*/
public static AlarmStatusTablePopupMenu getPopupMenu(){
return popupMenu;
}
/**
* update to use difference icons later!
*/
void loadIcons(){
}
/**
* update to use shared clipboard access later
*/
public void actionPerformed(ActionEvent e){
Object obj = e.getSource();
String selection = null;
if (obj == openMenuItem) {
invoker.OpenEvent();
}
else if (obj == removeMenuItem) {
invoker.Remove();
}
else if (obj == refreshMenuItem) {
invoker.Refresh();
}
}
/**
* force JTable only later
*/
public void show(Component c, int x, int y){
invoker = (AlarmStatusTable)c;
Point p = new Point(x,y);
int row = invoker.rowAtPoint(p);
int col = invoker.columnAtPoint(p);
this.x = x;
this.y = y;
super.show(c,x,y);
}
void disableMenu() {
openMenuItem.setEnabled(false);
removeMenuItem.setEnabled(false);
refreshMenuItem.setEnabled(false);
}
void enableMenu(){
openMenuItem.setEnabled(true);
removeMenuItem.setEnabled(true);
refreshMenuItem.setEnabled(true);
}
}

View File

@ -0,0 +1,469 @@
/*
* AlarmTCPThread.java
* Kevin Lim
* 03/21/00
*/
import java.net.*;
import java.io.*;
import javax.swing.*;
import javax.swing.*;
import javax.swing.text.Document;
import javax.swing.event.*;
import com.jetcell.MibWM.*;
public class AlarmTCPThread extends Thread{
static private boolean FILTER = false;
private String filterVipercellIp = null;
static final int MAX_IN_BUF_SIZE = 4096;
static final int MAX_MSG_BUF_SIZE = 1024;
static final int ALARM_HEAD_SRC_TYPE_POS = 0;
static final int ALARM_HEAD_MSG_TYPE_POS = 1;
static final int ALARM_HEAD_MSG_SIZE_POS = 2;
static final int ALARM_MSG_HEADER_LEN = 4;
static final int ALARM_MSG_SRC_IP_SIZE = 4;
static final int ALARM_MSG_SRC_NAME_SIZE = 41;
static final int ALARM_MSG_CRITICAL_SIZE = 1;
static final int ALARM_MSG_MAJOR_SIZE = 1;
static final int ALARM_MSG_MINOR_SIZE = 1;
static final byte ALARM_MSG_TYPE_UPDATE_REQ = 1;
static final byte ALARM_MSG_TYPE_UPDATE_RSP = 2;
static final byte ALARM_MSG_TYPE_REMOVE_REQ = 3;
static final byte ALARM_MSG_TYPE_EVENT_REQ = 4;
static final byte ALARM_MSG_TYPE_EVENT_RSP = 5;
static final byte ALARM_MSG_TYPE_ACK = 6;
static final byte ALARM_MSG_SRC_TYPE_APPLET = (byte)0xFF;
static final int MAX_MODULE_SPECIC_ALARM = 0xFFFF;
static final int ALARM_CRITICAL_START_POINT = 0x0001;
static final int ALARM_MAJOR_START_POINT = 0x0100;
static final int ALARM_MINOR_START_POINT = 0x0800;
static final int ALARM_INFO_START_POINT = 0x1000;
static final int ALARM_CRITICAL = 0;
static final int ALARM_MAJOR = 1;
static final int ALARM_MINOR = 2;
static final int ALARM_INFO = 3;
public static String user = null;
Socket socket;
String host;
int port;
int appletVipercellIp = 0;
int msgVipercellIp = 0;
AlarmStatusPanel panel = null;
AlarmPanel alarmPanel = null;
AlarmData alarmData = null;
BufferedInputStream in = null;
InputStreamReader isr = null;
public static BufferedOutputStream out = null;
boolean running;
public AlarmTCPThread(String host, int port) {
this.host = host;
this.port = port;
System.out.println("Connecting to the Server " + host + " at port " + port);
try {
socket = new Socket(host, port);
} catch(IOException e) {
System.out.println("Could not connect to the Server");
socket = null;
}
if(socket != null){
try {
in = new BufferedInputStream(socket.getInputStream()); // reading is done to byte arrays
out = new BufferedOutputStream(socket.getOutputStream()); // writing is done from byte arrays
out.flush();
} catch(IOException e) {
System.out.println("IO exception in AlarmTCPThread: ");
close_socket();
}
}
}
public void sendRemoveReq(AlarmStatusData data)
{
if(out == null) return;
try {
byte[] msg = {ALARM_MSG_SRC_TYPE_APPLET,
ALARM_MSG_TYPE_REMOVE_REQ,
0, 5, 0, 0, 0, 0, 0};
int i = AlarmTCPThread.ALARM_MSG_HEADER_LEN;
byte[] ip_addr = data.getSrcIPByte();
if(ip_addr == null){
System.out.println("Error on sendRemoveReq: getSrcIPByte failed");
return;
}
for(int j=0; j<AlarmTCPThread.ALARM_MSG_SRC_IP_SIZE; j++){
msg[i++] = ip_addr[j];
System.out.println("ip_addr "+ip_addr[j]);
}
byte type = data.getSrcTypeByte();
if(type == (byte)0xFF){
System.out.println("Error on sendRemoveReq: getSrcTypeByte returned unknown");
return;
}
msg[i++] = type;
out.write(msg, 0, i);
out.flush();
} catch(IOException ioe) {
System.out.println("IO exception in AlarmTCPThread:send "+ioe);
}
}
public void sendUpdateReq(){
if(out == null) return;
try {
byte[] msg = {ALARM_MSG_SRC_TYPE_APPLET,
ALARM_MSG_TYPE_UPDATE_REQ,
0, 0};
out.write(msg, 0, ALARM_MSG_HEADER_LEN);
out.flush();
} catch(IOException ioe) {
System.out.println("IO exception in AlarmTCPThread:send "+ioe);
}
}
// send alarm event msg update request to AlarmServer
static public void sendEventReq(String vipercellIp){
int index = 0;
String tmpStr = vipercellIp;
String valueStr;
Short [] ip = new Short[4];
if (out == null)
return;
// converting IP string into 4 octets
for (int i = 0; i < 4; i++){
index = tmpStr.indexOf(".");
valueStr = i == 3 ? tmpStr : tmpStr.substring(0, index);
ip[i] = new Short(valueStr);
tmpStr = tmpStr.substring(index + 1);
}
try {
byte[] msg = {ALARM_MSG_SRC_TYPE_APPLET,
ALARM_MSG_TYPE_EVENT_REQ,
0x00, 0x04, // length of data
ip[0].byteValue(), ip[1].byteValue(), ip[2].byteValue(),
ip[3].byteValue()};
out.write(msg, 0, ALARM_MSG_HEADER_LEN + 4);
out.flush();
}
catch(IOException ioe) {
System.out.println("IO exception in AlarmTCPThread:send "+ioe);
}
FILTER = false;
}
public static void sendAck(String srcIp,String alarmId,String recordNum){
int index = 0;
String tmpStr = srcIp;
String valueStr;
Short [] ip = new Short[4];
byte aid[] = new byte[4];
byte rec[] = new byte[4];
// converting IP string into 4 octets
for (int i = 0; i < 4; i++){
index = tmpStr.indexOf(".");
valueStr = i == 3 ? tmpStr : tmpStr.substring(0, index);
ip[i] = new Short(valueStr);
tmpStr = tmpStr.substring(index + 1);
}
// converting alarmID to bytes
aid = AlarmTCPThread.extractBytes(alarmId);
rec = AlarmTCPThread.extractBytes(recordNum);
try {
byte[] msg = {ALARM_MSG_SRC_TYPE_APPLET,
ALARM_MSG_TYPE_ACK,
0x00, 0x0c, // length of data
ip[0].byteValue(), ip[1].byteValue(), ip[2].byteValue(),
ip[3].byteValue(),
aid[3],aid[2],aid[1],aid[0],
rec[3],rec[2],rec[1],rec[0]};
out.write(msg, 0, msg.length);
out.flush();
}
catch(IOException ioe) {
AlarmStatusApplet.logDM("IO exception in AlarmTCPThread: ack "+ioe);
}
}
public static byte[] extractBytes(String s){
byte store[] = new byte[4];
int intValue = Integer.parseInt(s);
store[0] = (byte)(intValue & 0x000000ff);
store[1] = (byte)((intValue >> 8) & 0x000000ff);
store[2] = (byte)((intValue >> 16) & 0x000000ff);
store[3] = (byte)((intValue >> 24) & 0x000000ff);
return store;
}
public void alarmMsgHandler(byte[] msg) {
int index = AlarmTCPThread.ALARM_HEAD_MSG_TYPE_POS;
switch(msg[index]){
case ALARM_MSG_TYPE_UPDATE_RSP:
if (panel != null)
{
AlarmStatusData alarm = new AlarmStatusData(msg);
panel.addEvent(alarm);
}
break;
case ALARM_MSG_TYPE_EVENT_RSP:
if (alarmPanel != null)
{
try {
alarmData = new AlarmData(parseEventData(msg));
}
catch(Exception e) {}
if (appletVipercellIp == msgVipercellIp){
alarmPanel.addEvent(alarmData);
}
}
break;
default:
System.out.println("Unknown message received "+(int)msg[index]);
int size = 0x00FF & (int)msg[AlarmTCPThread.ALARM_HEAD_MSG_SIZE_POS];
size = (size << 8) | (0x00FF & (int)msg[AlarmTCPThread.ALARM_HEAD_MSG_SIZE_POS+1]);
size += AlarmTCPThread.ALARM_MSG_HEADER_LEN;
if(size > AlarmTCPThread.MAX_MSG_BUF_SIZE) size = AlarmTCPThread.MAX_MSG_BUF_SIZE;
for(int i=0; i<size; i++) System.out.print(" " + (int)(msg[i] & 0x00FF));
System.out.println(" ");
}
}
public void close_socket() {
if(socket != null){
try {
socket.close();
System.out.println("closing socket at third window level...");
}
catch(IOException e) {
System.out.println("Couldn't close socket " + e);
}
}
}
public void reconnect() {
boolean done = false;
while(!done){
try {
if (panel != null)
panel.dispStatus("Attempting to reconnect to the Server...");
socket = new Socket(host, port);
done = true;
if (panel != null)
panel.dispStatus("Server on-line");
}
catch(IOException e) {
if (panel != null)
panel.dispStatus("Server off-line");
}
try {
sleep(1000);
}
catch (InterruptedException ie) {
System.out.println(" Interrupted Excution = " + ie);
}
}
if(socket != null){
try {
in = new BufferedInputStream(socket.getInputStream()); // reading is done to byte arrays
out = new BufferedOutputStream(socket.getOutputStream()); // writing is done from byte arrays
out.flush();
if (panel != null) {
panel.clearEvents();
sendUpdateReq();
}
}
catch(IOException e) {
System.out.println("IO exception in AlarmTCPThread: ");
close_socket();
}
}
}
public void run() {
// Shrinivas 01 June 01
if(socket == null && running ) reconnect();
byte[] buf = new byte[AlarmTCPThread.MAX_IN_BUF_SIZE];
byte[] msg = new byte[AlarmTCPThread.MAX_MSG_BUF_SIZE];
running = true;
int readBytes;
int index;
int msg_size;
int header_size = AlarmTCPThread.ALARM_MSG_HEADER_LEN;
while(running){
try {
readBytes = in.read(buf, 0, AlarmTCPThread.MAX_IN_BUF_SIZE);
if(readBytes == -1){
System.out.println("End of stream reached!");
close_socket();
// Shrinivas 01 June 01'
if(running){
reconnect();
}
// Shrinivas end
}
index = 0;
while ((index + header_size) <= readBytes){ // while there are msg at least size of header
msg_size = 0x00FF & (int)buf[index+AlarmTCPThread.ALARM_HEAD_MSG_SIZE_POS];
msg_size = (msg_size << 8)
| (0x00FF & (int)buf[index+AlarmTCPThread.ALARM_HEAD_MSG_SIZE_POS+1]);
if((header_size + msg_size) <= (readBytes - index)){ // about to copy msg within valid range
for(int i=0; i<(header_size + msg_size); i++){
msg[i] = buf[index++];
}
AlarmStatusApplet.logDM("Received msg with length: " + msg_size);
alarmMsgHandler(msg);
}
else{
System.out.println("Length Err. Msg Length specified : "+msg_size);
System.out.println("Length Err. Bytes left in read buf: "+(readBytes - index));
index = readBytes; // finish while
}
}
}
catch(IOException e) {
close_socket();
if(running != false){
reconnect();
}
System.out.println("Stopping thread.");
}
}
}
public void startReadThread(AlarmStatusPanel panel){
this.panel = panel;
start();
panel.dispStatus("Server on-line");
sendUpdateReq();
}
public void startReadThread(AlarmPanel panel, String vipercellIp, boolean startThread){
alarmPanel = panel;
alarmPanel.removeAllEvents();
setAppletVipercellIp(vipercellIp);
if (startThread)
start();
this.filterVipercellIp = vipercellIp;
sendEventReq(vipercellIp);
}
public void finishReadThread(){
System.out.println("TCP thread is being shutdown");
running = false;
close_socket();
stop();
}
private void setAppletVipercellIp(String vipercellIp){
String valueStr;
Short octetVal;
String tmpStr = vipercellIp;
int index = 0;
appletVipercellIp = 0;
for (int i = 0; i < 4; i++)
{
index = tmpStr.indexOf(".");
valueStr = i == 3 ? tmpStr : tmpStr.substring(0, index);
if (i > 1) // we use only last two octets
{
octetVal = new Short(valueStr);
if (i == 2)
appletVipercellIp = octetVal.shortValue() << 8;
else
appletVipercellIp += octetVal.shortValue();
}
tmpStr = tmpStr.substring(index + 1);
}
}
private int extractNumber(byte[] msg, int pos){
return ((msg[pos] << 24 & 0xff000000) +
(msg[pos+1] << 16 & 0xff0000) +
(msg[pos+2] << 8 & 0xff00) +
(msg[pos+3] & 0xff));
}
private int extractIp(byte[] msg, int pos){
// for now, we are only extracting last 2 octets of an IP address
return((msg[pos+2] << 8 & 0xff00) + (msg[pos+3] & 0xff));
}
public String extractSrcIP(byte[] msg, int i){
int h1 = (int)msg[i] & 0x00FF;
int h2 = (int)msg[i+1] & 0x00FF;
int h3 = (int)msg[i+2] & 0x00FF;
int h4 = (int)msg[i+3] & 0x00FF;
String source_ip = "" + (new Integer(h1)).toString() +
"." + (new Integer(h2)).toString() +
"." + (new Integer(h3)).toString() +
"." + (new Integer(h4)).toString();
return source_ip;
}
private int getSeverity(int errorCode){
int severity;
if (errorCode == 0)
return ALARM_INFO;
int tmp = (errorCode & MAX_MODULE_SPECIC_ALARM);
if (tmp < ALARM_MAJOR_START_POINT)
{
severity = ALARM_CRITICAL;
} else if (tmp < ALARM_MINOR_START_POINT) {
severity = ALARM_MAJOR;
} else if (tmp < ALARM_INFO_START_POINT) {
severity = ALARM_MINOR;
} else {
severity = ALARM_INFO;
}
return severity;
}
private String parseEventData(byte[] msg) {
int id = extractNumber(msg, 4);
int code = extractNumber(msg, 8);
int severity = getSeverity(code);
int timestamp = extractNumber(msg, 12);
int srcIp = extractIp(msg, 16);
String srcIpString = extractSrcIP(msg, 16);
if (0 == appletVipercellIp){
appletVipercellIp = srcIp;
msgVipercellIp = srcIp;
}
else
msgVipercellIp = srcIp;
int srcModule = extractNumber(msg, 64);
int opt1 = extractNumber(msg, 68);
int opt2 = extractNumber(msg, 72);
int ack = extractNumber(msg,76);
int recNumber = extractNumber(msg,80);
String srcName = new String(msg, 20, 41);
srcName = srcName.trim();
String eventData = new String(id+"|"+timestamp+"|"+severity+"|"+srcModule+"|"+
srcName+"|"+code+"|"+opt1+"|"+opt2+"|"+srcIpString+"|"+ack+"|"+recNumber+"|");
return eventData;
}
}

View File

@ -0,0 +1,337 @@
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.UIManager.*;
import java.net.*;
import com.jetcell.MibWM.*;
public class FilterFrame extends JFrame{
final FilterFrame ff = this;
Container contentPane = null;
JPanel centerPanel = null;
JPanel southPanel = null;
// Labels
JLabel alarms = null;
JLabel time = null;
JLabel severity = null;
JLabel acknowledge = null;
// Combo Boxes
JComboBox alarmCombo = new JComboBox();
JComboBox timeCombo = new JComboBox();
JComboBox severityCombo = new JComboBox();
JComboBox acknowledgeCombo = new JComboBox();
// Reference to "AlarmPanel"
AlarmPanel alarmPanel = null;
public static FilterObject filterObject = null;
public static FilterObject tempFilterObject = null;
public FilterFrame(){
if(Util.applet == null){
setIconImage(Toolkit.getDefaultToolkit().getImage("../Images/app_icon.gif"));
}
else{
String iconPath = Util.applet.getCodeBase().toString();
iconPath += "Images/app_icon.gif";
URL iconPathURL = null;
try{
iconPathURL = new URL(iconPath);
}
catch(MalformedURLException exc){
System.out.println("Bad URL.");
}
System.out.println(iconPathURL);
setIconImage(Toolkit.getDefaultToolkit().getImage(iconPathURL));
}
}
public FilterFrame(AlarmPanel panel){
this.alarmPanel = panel;
if(tempFilterObject == null)
tempFilterObject = filterObject;
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception ex){
System.out.println("Error setting Look and Feel for Filter frame");
}
if(Util.applet == null){
setIconImage(Toolkit.getDefaultToolkit().getImage("../Images/app_icon.gif"));
}
else{
String iconPath = Util.applet.getCodeBase().toString();
iconPath += "Images/app_icon.gif";
URL iconPathURL = null;
try{
iconPathURL = new URL(iconPath);
}
catch(MalformedURLException exc){
System.out.println("Bad URL.");
}
System.out.println(iconPathURL);
setIconImage(Toolkit.getDefaultToolkit().getImage(iconPathURL));
}
JButton ok = new JButton(" OK ");
JButton cancel = new JButton("CANCEL");
JButton saveDefault = new JButton("Save As Default");
contentPane = getContentPane();
getCenterPanel(tempFilterObject);
if(tempFilterObject != null){
mapFilterOnFrame(tempFilterObject);
}
southPanel = new JPanel();
southPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
southPanel.add(ok);
southPanel.add(cancel);
if(Util.applet == null){
southPanel.add(saveDefault);
}
contentPane.add(centerPanel,BorderLayout.CENTER);
contentPane.add(southPanel,BorderLayout.SOUTH);
setSize(400,200);
addWindowListener(new windowListener());
ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
AlarmStatusApplet.logDM("Handle filter selection");
handleFilterSave();
}
});
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
dispose();
AlarmStatusApplet.logDM("No filter selection");
}
});
saveDefault.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
handleFilterSave();
filterObject = tempFilterObject;
}
});
}
public void handleFilterSave(){
// alarms selected
tempFilterObject = new FilterObject();
String alarms = (String)alarmCombo.getSelectedItem();
if(alarms.equals("All")){
tempFilterObject.NUM_ALARMS = FilterObject.NONE;
}
else{
try{
tempFilterObject.NUM_ALARMS = Integer.parseInt(alarms);
}
catch(NumberFormatException nfex){
JOptionPane.showMessageDialog(ff,"Bad Alarm number criteria.Default value assumed. ","Invalid number",JOptionPane.ERROR_MESSAGE);
tempFilterObject.NUM_ALARMS = FilterObject.NONE;
}
}
// time selected
int timeIndex = timeCombo.getSelectedIndex();
if(timeIndex == 1){
tempFilterObject.TIME = FilterObject.MIN_15;
}
else if(timeIndex == 2){
tempFilterObject.TIME = FilterObject.HR_1;
}
else if(timeIndex == 3){
tempFilterObject.TIME = FilterObject.HR_12;
}
else if(timeIndex == 4){
tempFilterObject.TIME = FilterObject.HR_24;
}
else
tempFilterObject.TIME = FilterObject.NONE;
// severity selected
int severityIndex = severityCombo.getSelectedIndex();
if(severityIndex == 1){
tempFilterObject.SEVERITY = FilterObject.CRITICAL;
}
else if(severityIndex == 2){
tempFilterObject.SEVERITY = FilterObject.MAJOR;
}
else if(severityIndex == 3){
tempFilterObject.SEVERITY = FilterObject.MINOR;
}
else
tempFilterObject.SEVERITY = FilterObject.NULL;
// acknowledge selected
int ackIndex = acknowledgeCombo.getSelectedIndex();
if(ackIndex == 1){
tempFilterObject.ACKNOWLEDGE = FilterObject.ALL_ACK;
}
else if(ackIndex == 2){
tempFilterObject.ACKNOWLEDGE = FilterObject.NO_ACK;
}
else
tempFilterObject.ACKNOWLEDGE = FilterObject.NONE;
this.dispose();
// Ananth
/*if (tempFilterObject.NUM_ALARMS == FilterObject.NONE &&
tempFilterObject.SEVERITY == FilterObject.NULL &&
tempFilterObject.TIME == FilterObject.NONE &&
tempFilterObject.ACKNOWLEDGE == FilterObject.NONE){
Util.setBorderTitle("Alarm List");
}
else{
Util.setBorderTitle("Alarm List (Filtered)");
}*/
if(alarmPanel!=null){
alarmPanel.handleFilterEvent(tempFilterObject);
alarmPanel.getAlarmTable().Refresh();
}
else{
filterObject = tempFilterObject;
}
}
private void mapFilterOnFrame(FilterObject tempFilterObject){
if(tempFilterObject.NUM_ALARMS != FilterObject.NONE){
String alarms = Integer.toString(tempFilterObject.NUM_ALARMS);
alarmCombo.getEditor().setItem(alarms);
}
else{
alarmCombo.setSelectedIndex(0);
}
if(tempFilterObject.TIME != FilterObject.NONE){
if(tempFilterObject.TIME == FilterObject.MIN_15)
timeCombo.setSelectedIndex(1);
else if(tempFilterObject.TIME == FilterObject.HR_1)
timeCombo.setSelectedIndex(2);
else if(tempFilterObject.TIME == FilterObject.HR_12)
timeCombo.setSelectedIndex(3);
else if(tempFilterObject.TIME == FilterObject.HR_24)
timeCombo.setSelectedIndex(4);
}
else{
timeCombo.setSelectedIndex(0);
}
if(!tempFilterObject.SEVERITY.equals(FilterObject.NULL)){
if(tempFilterObject.SEVERITY.equals(FilterObject.CRITICAL))
severityCombo.setSelectedIndex(1);
else if(tempFilterObject.SEVERITY.equals(FilterObject.MAJOR))
severityCombo.setSelectedIndex(2);
else if(tempFilterObject.SEVERITY.equals(FilterObject.MINOR))
severityCombo.setSelectedIndex(3);
}
else{
severityCombo.setSelectedIndex(0);
}
if(tempFilterObject.ACKNOWLEDGE != FilterObject.NONE){
if(tempFilterObject.ACKNOWLEDGE == FilterObject.ALL_ACK)
acknowledgeCombo.setSelectedIndex(1);
else if(tempFilterObject.ACKNOWLEDGE == FilterObject.NO_ACK)
acknowledgeCombo.setSelectedIndex(2);
}
else{
acknowledgeCombo.setSelectedIndex(0);
}
}
public JPanel getCenterPanel(FilterObject filterObj){
centerPanel = Util.makeBorderPanel("Filter Screen");
centerPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
alarms = new JLabel(" Alarms ");
alarms.setToolTipText("Check to set Alarm filter / Uncheck to set Default (All)");
time = new JLabel(" Time ");
time.setToolTipText("Check to set Time filter / Uncheck to set Default(All)");
severity = new JLabel(" Severity ");
severity.setToolTipText("Check to set Severity filter / Uncheck to set Default (All)");
acknowledge = new JLabel(" Acknowledge ");
acknowledge.setToolTipText("Check to set Acknowledge filter / Uncheck to set Default (All)");
// Alarms
alarmCombo.setPreferredSize(new Dimension(50,20));
alarmCombo.setEditable(true);
alarmCombo.addItem("All");
for(int i=1;i<=20;i++){
alarmCombo.addItem(Integer.toString(i));
}
// Time
timeCombo.addItem("All");
timeCombo.addItem("15 mins");
timeCombo.addItem("1 hour");
timeCombo.addItem("12 hours");
timeCombo.addItem("24 hours");
// Severity
severityCombo.addItem("All");
severityCombo.addItem("Critical");
severityCombo.addItem("Critical-Major");
severityCombo.addItem("Critical-Minor");
// Acknowledge
acknowledgeCombo.addItem("All");
acknowledgeCombo.addItem("Acknowledged");
acknowledgeCombo.addItem("Unacknowledged");
// Alarms
final JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout(FlowLayout.LEFT));
p1.add(alarms);
p1.add(alarmCombo);
p1.add(acknowledge);
p1.add(acknowledgeCombo);
// Time
final JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout(FlowLayout.LEFT));
p2.add(severity);
p2.add(severityCombo);
p2.add(time);
p2.add(timeCombo);
// Severity
// Acknowledge
centerPanel.add(p1);
centerPanel.add(p2);
if(filterObj != null){
mapFilterOnFrame(filterObj);
}
return centerPanel;
}
class windowListener extends WindowAdapter{
public void windowClosing(WindowEvent evt){
dispose();
AlarmStatusApplet.logDM("Closing Filter Screen");
}
}
}

View File

@ -0,0 +1,35 @@
import java.io.Serializable;
public class FilterObject implements Serializable{
// filter criteria
public int NUM_ALARMS;
public int TIME;
public String SEVERITY;
public int ACKNOWLEDGE;
public static int NONE = 0;
// Alarm number constants
public static int N1 = 2;
public static int N2 = 4;
public static int N3 = 6;
public static int N4 = 8;
// Severtiy constants
public static String CRITICAL = "CRITICAL";
public static String MAJOR = "MAJOR";
public static String MINOR = "MINOR";
public static String WARNING = "WARNING";
public static String NULL = "NULL";
// Ack constants
public static int NO_ACK = 1;
public static int ALL_ACK = 2;
// Time stamp constants
public static int MIN_15 = 1;
public static int HR_1 = 2;
public static int HR_12 = 3;
public static int HR_24 = 4;
}

View File

@ -0,0 +1,41 @@
####################################################################
#
# FILE NAME: Makefile
#
# DESCRIPTION: This makefile creates the vipercell related class
# files
# COMPONENTS:
#
#
# NOTES:
#
# (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
#
# REVISION HISTORY
#__________________________________________________________________
#----------+--------+----------------------------------------------
# Name | Date | Reason
#----------+--------+----------------------------------------------
# Kevin Lim|03/28/00| Initial Draft
#----------+--------+----------------------------------------------
####################################################################
#/
CODEBASE = ..
ALARMARCH = $(CODEBASE)\Java\AlarmStatus.jar
include $(CODEBASE)\java.mk
all: $(CLASS_LIST) $(ALARMARCH)
$(ALARMARCH):
$(JAR) cvf $@ *.class com\jetcell\MibWM\*.class
clean:
-$(RM) *.class
cleanall:
-$(RM) *.class
-$(RM) $(ALARMARCH)

View File

@ -0,0 +1,40 @@
####################################################################
#
# FILE NAME: Makefile
#
# DESCRIPTION: This makefile creates the vipercell related class
# files
# COMPONENTS:
#
#
# NOTES:
#
# (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
#
# REVISION HISTORY
#__________________________________________________________________
#----------+--------+----------------------------------------------
# Name | Date | Reason
#----------+--------+----------------------------------------------
# Bhawani |11/28/99| Initial Draft
#----------+--------+----------------------------------------------
####################################################################
#/
CODEBASE = ../../../../
include $(CODEBASE)/java.mk
all: $(CLASS_LIST)
clean:
-$(RM) *.java
-$(RM) *.class
cleanall:
-$(RM) *.java
-$(RM) *.class

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 370 B

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 341 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 477 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 897 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 341 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 337 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 840 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 370 B

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 845 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 341 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 897 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 341 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 337 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

View File

@ -0,0 +1,177 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : AlarmApplet
// Desc :
// Author : George Zhao
// Hist : 06/17/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
package Java;
import java.applet.Applet;
import java.awt.*;
import java.util.Calendar;
import java.lang.String;
import javax.swing.*;
import javax.swing.text.Document;
import javax.swing.event.*;
import java.net.UnknownHostException;
import com.jetcell.MibWM.*;
public class AlarmApplet extends JApplet implements DocumentListener
{
public static String ip = null;
JTextField eventField = null;
AlarmPanel alarmPanel = null;
JFrame f = null;
AlarmCommThread commObj;
public final static short TCP_SERVER_PORT = 10977;
public void init()
{
Util.applet = this;
Util.debug = true;
eventField = new JTextField();
Document doc = eventField.getDocument();
doc.addDocumentListener(this);
/*
setBrokerOptions();
Broker.addMagicMarkup("QSEvent", "java.lang.String", false);
RlBeanProperty beanProp = Broker.wrapBeanProperty(eventField, "text", java.lang.String.class);
Broker.bindMarkupToBeanProperty("QSEvent", "", null, beanProp, true, false, true, null);
*/
if(getParameter("TEST") != null)
{
String event1="1111|123456789|0|123|RRM|0|op1|op2";
String event2="1111|4321999|1|123|RRM|1|op1";
String event3="1111|3432213|3|123|RRM|2";
eventField.setText(event1);
eventField.setText(event2);
eventField.setText(event3);
} else {
commObj = new AlarmCommThread(getCodeBase().getHost(), TCP_SERVER_PORT);
commObj.startReadThread(eventField);
}
alarmPanel = new AlarmPanel();
String newin = getParameter("NEWINDOW");
if (f != null)
{
f.setVisible(true);
}
else {
if (newin != null)
{
System.out.println("NEWINDOW VALUE = " +newin);
if(newin.equals("FALSE") || newin.equals("false"))
{
getContentPane().setLayout(new BorderLayout());
getContentPane().setBackground(Color.white);
setBackground(Color.white);
getContentPane().add(alarmPanel.createPanel(),BorderLayout.CENTER);
}
else {
f = new JFrame("Alarm List for ViperCell: "+ip);
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(alarmPanel.createPanel());
f.setBounds(0,0, 720,400);
f.setVisible(true);
}
}
else {
System.out.println("Please set NEWINDOW parameter to TRUE or FALSE");
}
}
try
{
getRootPane().putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
}
catch(Exception ex)
{
//Util.showDialog(f, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void start()
{
}
public void stop()
{
}
public void destroy()
{
commObj.finishReadThread();
System.out.println("Destroy method has been called");
}
public void changedUpdate(DocumentEvent e)
{
}
public void insertUpdate(DocumentEvent e)
{
/*
System.out.println("insertUpdate");
java.util.Random r = new java.util.Random();
Calendar d = Calendar.getInstance();
*/
String alarmId = eventField.getText();
System.out.println("Receiving Alarm: "+alarmId);
// for test only. -gz
/*
int eventId = Integer.parseInt(alarmId.substring(alarmId.indexOf('r')+2, alarmId.length()));
String severity = null;
try {
d.add(Calendar.SECOND, java.lang.Math.abs(r.nextInt()));
if (eventId-eventId/3*3 == 0)
severity = new String("Critical");
else if (eventId-eventId/3*3 == 1)
severity = new String("Minor");
else if (eventId - eventId/3*3 == 2)
severity = new String("Info");
String date = d.getTime().toString();
String object = "Object_"+String.valueOf(java.lang.Math.abs(r.nextInt()));
String message = eventField.getText();
//AlarmData alarm = new AlarmData(String.valueOf(eventId), date, severity, null, object, message, null);
AlarmData alarm = new AlarmData(alarmId);
alarmPanel.addEvent(alarm);
Thread.sleep(1000);
System.out.println("Event: " +alarmId);
}
catch(Exception ex)
{
System.out.println(ex);
ex.printStackTrace();
}
*/
if(!alarmId.startsWith("Event Number"))
{
try {
AlarmData alarm = new AlarmData(alarmId);
alarmPanel.addEvent(alarm);
}
catch(Exception ex) {}
}
}
public void removeUpdate(DocumentEvent e)
{
}
}
//$History:$

View File

@ -0,0 +1,121 @@
////////////////////////////////////////////////////////////////////////////
//
// FILE NAME: AlarmCommThread.java
//
// DESCRIPTION: This file contains a class that allow the applet to
// communicate with the Tcp Server at the ViperCell
// COMPONENTS:
//
//
// NOTES:
//
// (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
//
// REVISION HISTORY
//__________________________________________________________________
//----------+--------+----------------------------------------------
// Name | Date | Reason
//----------+--------+----------------------------------------------
// Bhawani |2/08/00 | Initial Draft
//----------+--------+----------------------------------------------
//////////////////////////////////////////////////////////////////////////
//
package Java;
import java.net.*;
import java.io.*;
import javax.swing.*;
import javax.swing.*;
import javax.swing.text.Document;
import javax.swing.event.*;
public class AlarmCommThread extends Thread {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private JTextField p_eventField;
private boolean running;
public AlarmCommThread(String addr, short port) {
System.out.println("Initializing TCP/Ip socket environment");
try {
socket = new Socket(addr, port);
} catch(IOException e) {
// If the creation of the socket fails,
// nothing needs to be cleaned up.
System.out.println("Could not connect to the Server" + addr + "at port " + port + ": " + socket);
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Enable auto-flush:
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
// register client's message group
out.print("AlarmAsyncUpdate");
out.flush();
// digest the hello message
String str = in.readLine();
System.out.println("Server's Greeting: " + str);
} catch(IOException e) {
// The socket should be closed on any
// failures other than the socket
// constructor:
System.out.println("IO error in AlarmCommThread: ");
try {
socket.close();
} catch(IOException e2) {}
}
// Otherwise the socket will be closed by
// the run() method of the thread.
}
public void send(String str)
{
out.print(str);
out.flush();
}
public void startReadThread(JTextField eventField)
{
p_eventField = eventField;
start();
}
public void run() {
try {
running = true;
while (running) {
if(in.ready())
{
String str = in.readLine();
this.p_eventField.setText(str);
} else {
try {
this.sleep(100);
} catch (InterruptedException ie) {
System.out.println(" Interrupted Excution = " + ie);
}
}
}
} catch(IOException e3) {
System.out.println(" IO expection at read thread" + e3 );
} finally {
// Always close it:
try {
System.out.println("Socket is closing");
socket.close();
} catch(IOException e) {}
// Ending this thread
}
}
public void finishReadThread()
{
System.out.println("The read thread is being shutdown");
running = false;
}
}

View File

@ -0,0 +1,53 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : ConfigApplet
// Desc :
// Author : George Zhao
// Hist : 08/25/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
package Java;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.util.Hashtable;
import java.awt.*;
import com.jetcell.MibWM.*;
import com.jetcell.MibWM.ViperBase.*;
public class ConfigApplet extends JApplet
{
public void init()
{
try {
String host = getParameter("HOST");
int port = Integer.parseInt(getParameter("PORT"));
Configuration base = new Configuration(host, port);
getContentPane().setLayout(new BorderLayout());
getContentPane().setBackground(Color.white);
setBackground(Color.white);
getContentPane().add(base.mainPanel,BorderLayout.CENTER);
}
catch(Exception e)
{
System.out.println("Exception : "+ e.toString());
}
}
public void start()
{
}
public void stop()
{
}
public void destroy()
{
}
}
//$History:$

View File

@ -0,0 +1,70 @@
/////////////////////////////////////////////////////////////////////////////
//
// Class : ConfigAppletBeanInfo
// Desc :
// Author : George Zhao
// Hist : 08/27/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
package Java;
import java.beans.*;
import java.beans.SimpleBeanInfo;
public class ConfigAppletBeanInfo extends java.beans.SimpleBeanInfo
{
public ConfigAppletBeanInfo()
{
}
/**
* Gets a BeanInfo for the superclass of this bean.
* @return BeanInfo[] containing this bean's superclass BeanInfo
*/
public BeanInfo[] getAdditionalBeanInfo()
{
try
{
BeanInfo[] bi = new BeanInfo[1];
bi[0] = Introspector.getBeanInfo(beanClass.getSuperclass());
return bi;
}
catch (IntrospectionException e)
{
throw new Error(e.toString());
}
}
/**
* Gets the BeanDescriptor for this bean.
* @return an object of type BeanDescriptor
* @see java.beans.BeanDescriptor
*/
public BeanDescriptor getBeanDescriptor()
{
BeanDescriptor bd = new BeanDescriptor(beanClass);
return bd;
}
/**
* Gets an image that may be used to visually represent this bean
* (in the toolbar, on a form, etc).
* @param iconKind the type of icon desired, one of: BeanInfo.ICON_MONO_16x16,
* BeanInfo.ICON_COLOR_16x16, BeanInfo.ICON_MONO_32x32, or BeanInfo.ICON_COLOR_32x32.
* @return an image for this bean
* @see BeanInfo#ICON_MONO_16x16
* @see BeanInfo#ICON_COLOR_16x16
* @see BeanInfo#ICON_MONO_32x32
* @see BeanInfo#ICON_COLOR_32x32
*/
public java.awt.Image getIcon(int nIconKind)
{
java.awt.Image img = null;
return img;
}
private final Class beanClass = ConfigApplet.class;
}
//$History:$

View File

@ -0,0 +1,69 @@
####################################################################
#
# FILE NAME: Makefile
#
# DESCRIPTION: This makefile creates the common class files and the
# common jar file.
#
# COMPONENTS:
#
#
# NOTES:
#
# (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
#
# REVISION HISTORY
#__________________________________________________________________
#----------+--------+----------------------------------------------
# Name | Date | Reason
#----------+--------+----------------------------------------------
# Bhawani |11/28/99| Initial Draft
# Kevin Lim|03/28/00| add AlarmStatus.jar
#----------+--------+----------------------------------------------
####################################################################
#/
CODEBASE = ..
include $(CODEBASE)/java.mk
MIBWMPATH = $(CODEBASE)/com/jetcell/MibWM
VIPERCELL = $(MIBWMPATH)
VIPERBASE = $(MIBWMPATH)/ViperBase
ALARMPATH = $(CODEBASE)/AlarmApplet
MIBWM = ./MibWM.jar
ALARMARCH = ./AlarmStatus.jar
VIPERCELL_JAVA = $(wildcard $(VIPERCELL)/*.java)
VIPERCELL_CLASS = $(subst /,/, $(VIPERCELL_JAVA:.java=.class))
VIPERBASE_JAVA = GudbData.java EncodeMessage.java \
Configuration.java RoamingNumberTable.java
VIPERBASE_TMP = $(VIPERBASE_JAVA:.java=.class)
VIPERBASE_CLASS = $(foreach file, $(VIPERBASE_TMP), $(VIPERBASE)/$(file))
all: $(MIBWM) $(CLASS_LIST) $(ALARMARCH)
$(MIBWM): $(VIPERCELL_CLASS) $(VIPERBASE_CLASS)
@$(RM) $@
$(MAKE) -C $(CODEBASE) mibwm
$(ALARMARCH): $(ALARMPATH)/*.class
@$(RM) $@
$(MAKE) -C $(CODEBASE) alarm
viperCell:
$(MAKE) -C $(VIPERCELL) all
viperBase:
$(MAKE) -C $(VIPERBASE) all
cleanall:
-$(RM) $(subst /,\, $(VIPERBASE)/*.class)
-$(RM) $(subst /,\, $(MIBWM) $(CLASS_LIST))

View File

@ -0,0 +1,58 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : SubscriberApplet
// Desc :
// Author : George Zhao
// Hist : 08/25/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
package Java;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.util.Hashtable;
import java.awt.*;
import com.jetcell.MibWM.*;
import com.jetcell.MibWM.ViperBase.*;
public class SubscriberApplet extends JApplet
{
public void init()
{
try {
String host = getParameter("HOST");
int port = Integer.parseInt(getParameter("PORT"));
//test. -begin
Subscriber sub = new Subscriber(host, port);
//Subscriber sub = new Subscriber();
// test. -end.
getContentPane().setLayout(new BorderLayout());
getContentPane().setBackground(Color.white);
setBackground(Color.white);
getContentPane().add(((Subscriber)sub).mainPanel ,BorderLayout.CENTER);
}
catch(Exception e)
{
System.out.println("Exception : " +e.toString());
}
}
public void start()
{
}
public void stop()
{
}
public void destroy()
{
}
}
//$History:$

View File

@ -0,0 +1,69 @@
/////////////////////////////////////////////////////////////////////////////
//
// Class : SubscriberAppletBeanInfo
// Desc :
// Author : George Zhao
// Hist : 08/27/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
package Java;
import java.beans.*;
import java.beans.SimpleBeanInfo;
public class SubscriberAppletBeanInfo extends java.beans.SimpleBeanInfo
{
public SubscriberAppletBeanInfo()
{
}
/**
* Gets a BeanInfo for the superclass of this bean.
* @return BeanInfo[] containing this bean's superclass BeanInfo
*/
public BeanInfo[] getAdditionalBeanInfo()
{
try
{
BeanInfo[] bi = new BeanInfo[1];
bi[0] = Introspector.getBeanInfo(beanClass.getSuperclass());
return bi;
}
catch (IntrospectionException e)
{
throw new Error(e.toString());
}
}
/**
* Gets the BeanDescriptor for this bean.
* @return an object of type BeanDescriptor
* @see java.beans.BeanDescriptor
*/
public BeanDescriptor getBeanDescriptor()
{
BeanDescriptor bd = new BeanDescriptor(beanClass);
return bd;
}
/**
* Gets an image that may be used to visually represent this bean
* (in the toolbar, on a form, etc).
* @param iconKind the type of icon desired, one of: BeanInfo.ICON_MONO_16x16,
* BeanInfo.ICON_COLOR_16x16, BeanInfo.ICON_MONO_32x32, or BeanInfo.ICON_COLOR_32x32.
* @return an image for this bean
* @see BeanInfo#ICON_MONO_16x16
* @see BeanInfo#ICON_COLOR_16x16
* @see BeanInfo#ICON_MONO_32x32
* @see BeanInfo#ICON_COLOR_32x32
*/
public java.awt.Image getIcon(int nIconKind)
{
java.awt.Image img = null;
return img;
}
private final Class beanClass = SubscriberApplet.class;
}
//$History:$

View File

@ -0,0 +1,58 @@
####################################################################
#
# FILE NAME: Makefile
#
# DESCRIPTION: This is root make file that genetates java classes
# and jar file.
#
# COMPONENTS:
#
#
# NOTES:
#
# (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
#
# REVISION HISTORY
#__________________________________________________________________
#----------+--------+----------------------------------------------
# Name | Date | Reason
#----------+--------+----------------------------------------------
# Bhawani |11/28/99| Iniitial Draft
# Kevin Lim|03/28/00| added AlarmStatusApplet
#----------+--------+----------------------------------------------
####################################################################
CODEBASE = .
include $(CODEBASE)/java.mk
VIPERCELL = $(MIBWMPATH)
VIPERBASE = $(MIBWMPATH)/ViperBase
PACKPATH = $(ALARMAPPLETDIR)\com\jetcell\MibWM
MIBWM = ./Java/MibWM.jar
ALARMARCH = ./Java/AlarmStatus.jar
all:
$(CP) $(MIBWMPATH)\*.java $(PACKPATH)
$(MAKE) -C $(ALARMAPPLETDIR) all
alarm: $(ALARMARCH)
$(ALARMARCH):
$(CP) AlarmApplet\AlarmStatus.jar Java\AlarmStatus.jar
# mibwm: $(MIBWM)
$(MIBWM): ./Java/AlarmCommThread.class
# $(JAR) cvf $@ $(VIPERCELL)/*.class $(VIPERBASE)/*.class ./Java/AlarmCommThread.class
$(JAR) cvf $@ $(VIPERCELL)/*.class ./Java/AlarmCommThread.class
cleanall:
$(MAKE) -C $(ALARMAPPLETDIR) cleanall
$(MAKE) -C $(PACKPATH) cleanall
$(MAKE) -C $(COMMON) cleanall

View File

@ -0,0 +1,154 @@
// AlarmCode.English
// Copyright (C) 2000 Cisco Systems, Inc.
// All rights reserved
// WARNING: This file is automatically generated by an AlarmCode tool
// Any changes made to this file will be overwritten by
// subsequent uses of the tool.
//
// ALARM_ERROR_CODE | "ALARM_SYNOPSIS" | "ALARM_DETAIL_MESSAGE"
0 | Module alarm with ID %2 has cleared | The alarm ID %2 (error code %1) was cleared by module %module. The operational state of GSM Port depends on alarm status from all modules.
131074 | First DSP/FPGA Hardware Failure | Bit clock at the first DSP/Fpga is not functioning. GSM Port must be rebooted to recover from this situation.
131075 | Second DSP/FPGA Hardware Failure | Bit clock at the second DSP/Fpga is not functioning. GSM Port must be rebooted to recover from this situation.
131076 | First DSP not responding | Link between RM and first DSP is broken. GSM Port must be rebooted to recover from this situation.
131077 | Second DSP not responding | Link between RM and second DSP is broken. GSM Port can function in a reduced-Capacity mode if the first DSP can function properly. GSM Port must be rebooted to recover from this situation.
131078 | Cell Broadcast Channel unusable | Cell broadcast channel initialization failed. Cell broadcast will not be supported until the next reboot. This channel, however, does not affect the operational state of the GSM Port.
131079 | No usable traffic channel | Initialization of all the traffic channels failed. Please unlock them if they are locked. If the their admin state is already unlocked, please reboot the system.
131080 | No TRX enabled | Initialization of both TRX failed. Please unlock them if they are locked. If the their admin state is already unlocked, please reboot the system.
131081 | Illegal Configuration - No BCCH Channel | No BCCH channel combination is specified in the MIB. Please check the first TRX configuration through GP Manager.
131082 | Illegal Configuration - Unsupported Channel | Unsupported channel combination is detected in the MIB. Please check both first and second TRX configuration through GP Manager
131083 | Illegal Configuration - Two BCCH Channel | Only one BCCH channel is supported at this time but two BCCH channel configuration found. Please correct this problem through GP Manager.
131084 | Illegal Configuration - Too many Channel Combination I | Too many channel combination I configuration found. Please correct this problem through GP Manager.
131085 | Illegal Configuration - Multiple BCCH Channels | Only one BCCH channel is supported at this time but more than two BCCH channels have been configured. Please correct this problem through GP Manager.
131086 | System Call Failure - Watchdog timer create | RM module detects failure in creating WatchDog Timer which is essential for proper software operation. GSM Port must be rebooted to recover from this situation.
131087 | System Call Failure - Message queue receive | RM module encountered failure in receiving message. GSM Port must be rebooted to recover from this situation.
131088 | OAM Api Failure | Could not set a field of a MIB table entry.
131089 | Oam Api Failure | Could not set a MIB integer variable.
131090 | RF board not detected | Failed to detect RF board. Please check if it is there.
135169 | GSM Port Locked | The GSM Port was locked successfully. Existing calls (if any) were aborted. No new calls can be made through GSM Port.
135170 | GSM Port Unlocked | The GSM Port was unlocked successfully. GSM Port can accept new calls if its operational state is enabled.
135171 | GSM Port Shutting Down | The GSM Port is being shutdown. No new calls can be made through GSM Port. Existing calls are maintained until terminates normally.
135172 | First TRX Locked | The first TRX was locked successfully. Locking of first TRX is equivalent of locking of GSM Port. Existing calls (if any) were aborted. No new calls can be made through GSM Port.
135173 | Second TRX Locked | The second TRX was locked successfully. Existing calls (if any) were aborted. No new calls will be made through this TRX.
135174 | First TRX Unlocked | The first TRX was unlocked successfully. New calls can be made through this TRX.
135175 | Second TRX Unlocked | The second TRX was unlocked successfully. New calls can be made through this TRX.
135176 | First TRX shutting down | The first TRX is being shutting down. Shutting down first TRX is equivalent of shutting down GSM Port. No new calls can be made through GSM Port. Existing calls are maintained until terminates normally.
135177 | Second TRX shutting down | The second TRX is being shutting down. No new calls can be made through this TRX. Existing calls are maintained until terminates normally.
135178 | First TRX Time Slot 0 locked | Locking of Time Slot 0 of first TRX is equivalent of locking GSM Port. Existing calls (if any) were aborted. No new calls can be made through GSM Port.
135179 | First TRX Time Slot 1 locked | Time slot 1 of the first TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135180 | First TRX Time Slot 2 locked | Time slot 2 of the first TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135181 | First TRX Time Slot 3 locked | Time slot 3 of the first TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135182 | First TRX Time Slot 4 locked | Time slot 4 of the first TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135183 | First TRX Time Slot 5 locked | Time slot 5 of the first TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135184 | First TRX Time Slot 6 locked | Time slot 6 of the first TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135185 | First TRX Time Slot 7 locked | Time slot 7 of the first TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135186 | Second TRX Time Slot 0 locked | Time slot 0 of the second TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135187 | Second TRX Time Slot 1 locked | Time slot 1 of the second TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135188 | Second TRX Time Slot 2 locked | Time slot 2 of the second TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135189 | Second TRX Time Slot 3 locked | Time slot 3 of the second TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135190 | Second TRX Time Slot 4 locked | Time slot 4 of the second TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135191 | Second TRX Time Slot 5 locked | Time slot 5 of the second TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135192 | Second TRX Time Slot 6 locked | Time slot 6 of the second TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135193 | Second TRX Time Slot 7 locked | Time slot 7 of the second TRX was locked successfully. Existing call (if any) was aborted. No new call can be made through this time slot.
135194 | First TRX Time Slot 0 Unlocked | Time slot 0 of the first TRX was unlocked successfully. New calls can be made through this time slot.
135195 | First TRX Time Slot 1 Unlocked | Time slot 1 of the first TRX was unlocked successfully. New calls can be made through this time slot.
135196 | First TRX Time Slot 2 Unlocked | Time slot 2 of the first TRX was unlocked successfully. New calls can be made through this time slot.
135197 | First TRX Time Slot 3 Unlocked | Time slot 3 of the first TRX was unlocked successfully. New calls can be made through this time slot.
135198 | First TRX Time Slot 4 Unlocked | Time slot 4 of the first TRX was unlocked successfully. New calls can be made through this time slot.
135199 | First TRX Time Slot 5 Unlocked | Time slot 5 of the first TRX was unlocked successfully. New calls can be made through this time slot.
135200 | First TRX Time Slot 6 Unlocked | Time slot 6 of the first TRX was unlocked successfully. New calls can be made through this time slot.
135201 | First TRX Time Slot 7 Unlocked | Time slot 7 of the first TRX was unlocked successfully. New calls can be made through this time slot.
135202 | Second TRX Time Slot 0 Unlocked | Time slot 0 of the second TRX was unlocked successfully. New calls can be made through this time slot.
135203 | Second TRX Time Slot 1 Unlocked | Time slot 1 of the second TRX was unlocked successfully. New calls can be made through this time slot.
135204 | Second TRX Time Slot 2 Unlocked | Time slot 2 of the second TRX was unlocked successfully. New calls can be made through this time slot.
135205 | Second TRX Time Slot 3 Unlocked | Time slot 3 of the second TRX was unlocked successfully. New calls can be made through this time slot.
135206 | Second TRX Time Slot 4 Unlocked | Time slot 4 of the second TRX was unlocked successfully. New calls can be made through this time slot.
135207 | Second TRX Time Slot 5 Unlocked | Time slot 5 of the second TRX was unlocked successfully. New calls can be made through this time slot.
135208 | Second TRX Time Slot 6 Unlocked | Time slot 6 of the second TRX was unlocked successfully. New calls can be made through this time slot.
135209 | Second TRX Time Slot 7 Unlocked | Time slot 7 of the second TRX was unlocked successfully. New calls can be made through this time slot.
135210 | First TRX Time Slot 0 shutting down | Time slot 0 of the first TRX is being shutdown. Shutting down Time Slot 0 of First TRX is equivalent of shutting down GSM Port. Existing calls will be maintained until terminate normally. No new calls can be made through GSM Port.
135211 | First TRX Time Slot 1 shutting down | Time slot 1 of the first TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135212 | First TRX Time Slot 2 shutting down | Time slot 2 of the first TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135213 | First TRX Time Slot 3 shutting down | Time slot 3 of the first TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135214 | First TRX Time Slot 4 shutting down | Time slot 4 of the first TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135215 | First TRX Time Slot 5 shutting down | Time slot 5 of the first TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135216 | First TRX Time Slot 6 shutting down | Time slot 6 of the first TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135217 | First TRX Time Slot 7 shutting down | Time slot 7 of the first TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135218 | Second TRX Time Slot 0 shutting down | Time slot 0 of the second TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135219 | Second TRX Time Slot 1 shutting down | Time slot 1 of the second TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135220 | Second TRX Time Slot 2 shutting down | Time slot 2 of the second TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135221 | Second TRX Time Slot 3 shutting down | Time slot 3 of the second TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135222 | Second TRX Time Slot 4 shutting down | Time slot 4 of the second TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135223 | Second TRX Time Slot 5 shutting down | Time slot 5 of the second TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135224 | Second TRX Time Slot 6 shutting down | Time slot 6 of the second TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135225 | Second TRX Time Slot 7 shutting down | Time slot 7 of the second TRX is being shutdown. Existing call (if any) will be maintained until terminate normally. No new call can be made through this time slot.
135226 | Radio for the first TRX is off | Radio for the first TRX is off
135227 | Radio for the second TRX is off | Radio for the second TRX is off
135228 | RM detects corrupted Layer 1 message | RM module detected a corrupted message from Layer 1.
327681 | LAPDm Internal Failure | Data corruption in the LAPDm Layer software. The system needs a reboot
327936 | LAPDm Resource Exhausted | LAPDm Layer ran out of available frame buffer. This is most likely caused by radio link problem with MS.
462848 | (Re)Load MIB | New MIB have been loaded on %1. You most likely need to reboot the GSM Port
462850 | MIB save option Change - Timer enabled | MIB save timer has been disabled on %1.
462849 | MIB save option Change - Timer disabled | MIB save timer has been disabled on %1.
462851 | MIB Option Change - Duplicate save allowed | MIB save option change on %1.
462852 | MIB option change - Duplicate save not allowed | Duplicate saving of the MIB is now disabled. This will improve the response time of the set operation at GP Manager
458753 | GSM Port Operator-Initiated Reboot | The operator has initiated a reboot on %1. GSM Port will reboot within a few seconds.
524289 | GMC Link Down | Detected link lost to GMC. Please check the operational status of GMC and the physical network connectivity between GMC and GSM Port.
917505 | MPC SRAM test failure | MCH Module's Test results indicates that there was a failure in MPC SRAM Test.
917506 | DSP0 internal data RAM test failure | MCH Module's Post Test results indicates that there was a failure in DSP0's internal data RAM Test.
917507 | DSP1 internal data RAM test failure | MCH Module's Post Test results indicates that there was a failure in DSP1's internal data RAM Test.
917508 | DSP0 internal program RAM test failure | MCH Module's Post Test results indicates that there was a failure in DSP0's internal program RAM Test.
917509 | DSP1 internal program RAM test failure | MCH Module's Post Test results indicates that there was a failure in DSP1's internal program RAM Test.
917510 | DSP0 external RAM test failure | MCH Module's Post Test results indicates that there was a failure in DSP0's external RAM Test.
917511 | DSP1 external RAM test failure | MCH Module's Post Test results indicates that there was a failure in DSP1's external RAM Test.
917512 | FPGA0 test failure | MCH Module's Post Test results indicates that there was a failure in FPGA0 Test.
917513 | FPGA1 test failure | MCH Module's Post Test results indicates that there was a failure in FPGA1 Test.
917514 | I2C test failure | MCH Module's Post Test results indicates that there was a failure in I2C Test.
917515 | ViperTask startup delay detected | One or more ViperTask has a delay on startup, reporting readiness late.
917516 | SysCommand_xxx symbol not found | One or more module's SysCommand_xxx() function symbol is not found. Check module loading logs.
917517 | Critical Task suspension detected | Critical Task suspension from ModuleId %1 detected.
917518 | Critical exit abnormally detected | Critical Task abnormally exited from ModuleID %1 detected.
917519 | LoadModule failure | Loading module object codes had problems. Check startup logs.
917761 | Non-Critical Task suspension detected | Non-Critical Task suspension from ModuleId %1 detected.
917762 | Non-Critical exit abnormally detected | Non-Critical Task abnormally exited from ModuleID %1 detected.
16711681 | Module booting up | Module %module is booting up now
16711682 | Module shutting down | Module %module is shutting down now
16711683 | Out of Internal Memory Error | The GSM Port ran out of memory. Module %module did not complete its intended operation. GSM Port must be rebooted to recover from this situation.
16711684 | System Internal Error | GSM Port software system encountered an unexpected error, which resulted in data corruption. GSM Port must be rebooted to recover from this situation.
16711685 | Reboot Started | The GSM Port is rebooting now.
17039362 | GMC Link Down | Could not get a list of active GP10s from GMC. The link is down. Please verify if the GMC is up and running at the localhost
17039617 | CBC Index File Read Failure | Either CBC index file is missing or it is not readable.
17039618 | CBC Message File Read Failure | CBC message file could not be completely read and decoded. Some of the previously scheduled messages may have been lost.
17236226 | ITP link is down | Verify: 1) network connection to ITP; 2) whether ITP is running
17236227 | Roaming number not available | Add more roaming numbers
17236229 | Can't save config file | Check available space on hard drive
17236230 | Can't open config file | jcvbase.dat is missing or damaged. Note: created after first configuration changes
17236228 | Duplicated GP CellID | Two GPs with the same CellID. Change CellID on GP. Check the error logs for details.
17235970 | Internal failure to initialize | GMC can't initialize. Try power off reboot first. See error log for more details
17236231 | GP Disconnected | Check GP status and network connection
17236232 | Can't open translations data file for reading | Check if vnxlndb.dat is missing or has wrong permissions. vnxlndb.dat file is not needed if no previous translations data exists. It will be created after the first changes.
17236233 | Error during translations data file read | vnxlndb.dat may be corrupted. Try to import a known good ASCII translations data file, if available, through the Translations Manager.
17236234 | Can't open translations data file for writing | Check if vnxlndb.dat has wrong permissions. If not, try rebooting the GMC.
17236235 | Can't save translations data file changes | Check available space on the hard drive. Try to export current data to an ASCII translations data file from the Translations Manager for backup. Try rebooting GMC if this failure is repeated. Try importing the backed up ASCII file after GMC reboot.
17235971 | Can't get OS resources for Translations | Try rebooting the GMC.
17236236 | IN link down | Check that the IN server and connectivity are Ok
17236237 | No Heartbeat on IN link | Check that the IN server is OK
17367042 | Tones&Announcements Application failed to initialize | Validate the configuration information for the Tones & Announcements.
17367298 | Announcements configuration problem for Tones&Announcements. | (Either) no announcements are configured (or) Configuration data is incorrect. Ensure the name & presence of announcement files in the right directory(/sd0/gmc/IVR)
17432578 | CDR Server failed to start off. | Ensure that SNMP daemon is running and initialized
17432834 | CCS did not recognize CDR Server name. | Add this CDR/MNET name to CCS config file(cdr2.conf) and restart CCS.
17432835 | The communication between CDR Server and CCS is lost. | Ensure that CCS is running.
17436674 | File Tranmission problem between CDR Server and CCS.Retramsmitting file. | No correction mechanism required.
17301506 | APM Server failed to start off. | Ensure that SNMP daemon is running and initialized
17301762 | APM Server name not recognized by CAPS. | Add this APM/MNET name to CAPS through the CAM.
17498113 | ViperTask startup delay detected | One or more ViperTask has a delay on startup, reporting readiness late.
17498114 | SysCommand_xxx symbol not found | One or more module's SysCommand_xxx() function symbol is not found. Check module loading logs.
17498115 | Critical Task suspension detected | Critical Task suspension from ModuleId %1 detected.
17498116 | Critical exit abnormally detected | Critical Task abnormally exited from ModuleID %1 detected.
17498117 | LoadModule failure | Loading module object codes had problems. Check startup logs.
17498369 | Non-Critical Task suspension detected | Non-Critical Task suspension from ModuleId %1 detected.
17498370 | Non-Critical exit abnormally detected | Non-Critical Task abnormally exited from ModuleID %1 detected.
33488897 | Module booting up | Module %module is booting up now
33488898 | Module shutting down | Module %module is shutting down now
33488899 | Out of Internal Memory Error | The GSM Port ran out of memory. Module %module did not complete its intended operation. GSM Port must be rebooted to recover from this situation.
33488900 | System Internal Error | GSM Port software system encountered an unexpected error, which resulted in data corruption. GSM Port must be rebooted to recover from this situation.
33488901 | Reboot Started | The GSM Port is rebooting now.

View File

@ -0,0 +1,216 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : AlarmData
// Desc :
// Author : George Zhao
// Hist : 06/17/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
package com.jetcell.MibWM;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.text.*;
import java.awt.*;
import java.util.*;
public class AlarmData
{
static int AlarmIndex = 0;
String alarmId;
String timestamp;
String severity;
String objectId;
String object;
String errorNo;
String subject;
String message;
Integer alarmIndex;
String optional1;
String optional2;
String acknowledge;
String recordNumber;
String srcIp;
static int NUM_REQUIRED_FIELDS = 8;
static int NUM_OPTIONAL_FIELDS = 3;
static int OP1 = 6;
static int OP2 = 7;
static int SRCIP = 8;
static int ACK = 9;
static int REC_NUM = 10;
static final String OP1Field = "%1";
static final String OP2Field = "%2";
static final String OPModule = "%module";
static String[] AlarmSeverity = { "Critical",
"Major",
"Minor",
"Information"
};
public static SimpleDateFormat formatter = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss z" );
public static SimpleDateFormat myFormatter = new SimpleDateFormat("dd.MM.yyyy/HH:mm:ss");
static final char dilim = '|';
public AlarmData( String alarmId, String timestamp, String severity,
String objectId, String object, String subject, String message)
{
this.alarmId = alarmId;
this.timestamp = timestamp;
this.severity = severity;
this.objectId = objectId;
this.object = object;
this.subject = subject;
this.message = message;
}
public AlarmData(String event) throws Exception
{
// event are in the format of:
// eventId|timestamp|severity|objectid|object name|event no |optional 1 |optional 2 | optional 3
String[] values = new String[NUM_REQUIRED_FIELDS+NUM_OPTIONAL_FIELDS];
int index = 0;
int pos = 0;
int i = 0;
boolean end = false;
while(!end)
{
index = event.indexOf(dilim, pos);
if (index == -1)
{
index = event.length();
end = true;
continue;
}
values[i++] = event.substring(pos,index);
pos = index+1;
}
try {
alarmId = values[0].trim();
timestamp = formatter.format(new Date(1000*Long.parseLong(Util.trimSpaces(values[1]))));
//timestamp = Util.trimSpaces(values[1]);
if(Util.debug)
{
System.out.println("values[1] " + values[1]);
System.out.println("Util.trimSpaces(values[1])) " + Util.trimSpaces(values[1]));
System.out.println("Long.parseLong(Util.trimSpaces(values[1])) " + Long.parseLong(Util.trimSpaces(values[1])));
Date d = new Date(1000*Long.parseLong(Util.trimSpaces(values[1])));
System.out.println("date " + d.toString());
System.out.println("date.gettime() "+d.getTime());
}
severity = AlarmSeverity[Integer.parseInt(Util.trimSpaces(values[2]))];
objectId = values[3].trim();
object = values[4];
errorNo = values[5].trim();
int error = Integer.parseInt(errorNo);
Vector alarmMsg = AlarmMessageMap.Get(error);
subject = (String) alarmMsg.elementAt(AlarmMessageMap.SUBJECT);
message = (String) alarmMsg.elementAt(AlarmMessageMap.MESSAGE);
alarmIndex = new Integer(AlarmIndex++);
subject = Replace(subject, object, OPModule);
message = Replace(message, object, OPModule);
optional1 = values[OP1].trim();
optional2 = values[OP2].trim();
srcIp = values[SRCIP].trim();
acknowledge = values[ACK].trim();
recordNumber = values[REC_NUM].trim();
if(values[OP1] != null)
{
optional1 = values[OP1];
subject = Replace(subject, optional1, OP1Field);
message = Replace(message, optional1, OP1Field);
}
if(values[OP2] != null)
{
optional2 = values[OP2];
subject = Replace(subject, optional2, OP2Field);
message = Replace(message, optional2, OP2Field);
}
}
catch(Exception e)
{
System.out.println("Invalid error No. " +errorNo);
e.printStackTrace();
throw e;
}
}
public Object getValueAt(int column)
{
switch (column)
{
case AlarmTableModel.ALARMID:
return alarmId;
case AlarmTableModel.TIMESTAMP:
return timestamp;
case AlarmTableModel.SEVERITY:
return severity;
case AlarmTableModel.OBJECT:
return object;
case AlarmTableModel.SUBJECT:
return subject;
default:
return "Unknown";
}
}
public void dump()
{
if(Util.debug)
{
System.out.println("Alarm ID : " +alarmId);
System.out.println("Timestamp : " +timestamp);
System.out.println("Severity : " +severity);
System.out.println("Object ID : " +objectId);
System.out.println("Object : " +object);
System.out.println("Error No : " +errorNo);
System.out.println("Subject : " +subject);
System.out.println("Message : " +message);
System.out.println("Optional1 : " +optional1);
System.out.println("Optional2 : " +optional2);
System.out.println("Index: " +alarmIndex);
}
}
String Replace(String field, String opfield, String op)
{
String message = null;
int pos = field.indexOf(op);
if(pos != -1) message = field.substring(0, pos) + opfield + field.substring(pos+op.length(), field.length());
else message = field;
return message;
}
public static void main(String[] argv)
{
// alarmId|timestamp|severity|objectId|objectName|error code|op 1| op 2
String event1="12323|10:23:34 1999|Critical|123|RRM|0|op1|op2";
String event2="12323|10:23:34 1999|Critical|123|RRM|1|op1";
String event3="12323|10:23:34 1999|Critical|123|RRM|2";
try {
AlarmData data = new AlarmData(event1);
data.dump();
data = new AlarmData(event2);
data.dump();
data = new AlarmData(event3);
data.dump();
}
catch(Exception e) {}
}
}
//$History:$

View File

@ -0,0 +1,131 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : AlarmMessageMap
// Desc :
// Author : George Zhao
// Hist : 06/17/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
package com.jetcell.MibWM;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;
import java.net.URL;
import Java.AlarmApplet;
abstract class AlarmMessageMap
{
static String file = "Text/AlarmCode.English";
static String Comments = "//";
static String delim = "|";
static Hashtable alarmTable = null;
static final int SUBJECT = 0;
static final int MESSAGE = 1;
static final int VECTOR_SIZE= 2;
static final int LENGTH = 3;
static boolean readfile = false;
static String[] ErrorCode = {
"0|subect for alarm code 0| detail message for alarm code 0 wdsdsa fdsafdsafs adfdsa fdsafsad fsaf sadfdsaf sadfdsfsa fds dfsa asfa sfasf asdf sadfasfadf sa fasf asfa dsaf asasfdsafa a afasdfdsaf dsafds afitsdfsfdsafsdfsafjksa;lkfjsalkfjsaf;lksajfsaklfsa;lkfasjfa;lksjfsadlkfjas;lkfjsfalksfjsa;lkfjsafkljdsfkldsafjdskfjflksajflksfj;safjas;lfjsafjsaklfsajflkdsafjsalkfah optional field %1",
"1|subect for alarm code 1| detail message for alarm code 1 ddsfsdfsafsfaskf;lsjflsfskdl fjsalkfsaflksafwith optional field %1",
"2|subect for alarm code 2| detail message for alarm code 2 with optional field %1"
};
static Vector Get(long errorNo)
{
if (alarmTable == null)
{
Init();
}
Vector object = (Vector) alarmTable.get(new Long(errorNo));
if (object == null)
{
object = new Vector();
object.addElement(new String("No entry for data file for error code " +errorNo));
object.addElement(new String("No entry for data file for error code " +errorNo));
}
return object;
}
static void Init()
{
alarmTable = new Hashtable();
URL cfg_url;
try {
if(Util.applet != null) {
System.out.println("Running applet");
System.out.println("codebase : " + Util.applet.getCodeBase());
System.out.println("documentbase : " + Util.applet.getDocumentBase());
System.out.println("file : " + Util.applet.getCodeBase().getFile());
//BufferedReader in = new BufferedReader(new FileReader(new File(Util.applet.getDocumentBase().getFile(), file)));
cfg_url = new URL(Util.applet.getCodeBase()+file);
//cfg_url = new URL("http://"+ ((AlarmApplet)Util.applet).ip+"/"+file);
}
else {
System.out.println("Running application");
String sep = System.getProperty("file.separator");
String pwd = "file:"+".."+sep+"Text"+sep+"AlarmCode.English";
cfg_url = new URL(pwd);
}
System.out.println("Open File: " +cfg_url);
BufferedReader in = new BufferedReader(new InputStreamReader(cfg_url.openStream()));
String line = null;
while( (line = in.readLine()) != null)
{
ProcessErrorCode(line);
readfile = true;
}
}
catch(FileNotFoundException e)
{
System.out.println(e.toString());
System.out.println("Cannot open alarm code file " + file);
}
catch(IOException ex)
{
System.out.println("IO Exception: " + ex.toString());
}
if(!readfile)
{
for(int i=0; i< ErrorCode.length; i++)
{
ProcessErrorCode(ErrorCode[i]);
}
}
}
static void ProcessErrorCode(String line)
{
if(line.startsWith(Comments)) return;
StringTokenizer token = new StringTokenizer(line, delim);
if(token.countTokens() != LENGTH)
{
return;
}
Long errorNo = new Long(Util.trimSpaces(token.nextToken(delim)));
Vector alarmMsg = new Vector(VECTOR_SIZE);
alarmMsg.insertElementAt(token.nextToken(delim), SUBJECT);
alarmMsg.insertElementAt(token.nextToken(delim), MESSAGE);
alarmTable.put(errorNo, alarmMsg);
}
static void dump()
{
if(Util.debug)
for (Enumeration e = alarmTable.elements() ; e.hasMoreElements() ;) {
System.out.println(e.nextElement());
}
}
}
//$History:$

View File

@ -0,0 +1,467 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : AlarmPanel
// Desc :
// Author : George Zhao
// Hist : 04/27/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
package com.jetcell.MibWM;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.text.Document;
import javax.swing.event.*;
import java.net.UnknownHostException;
import java.awt.*;
import java.util.*;
import rl.clbroker.Broker;
import rl.clbroker.RlBeanProperty;
import rl.clbroker.RlError;
import FilterObject;
import FilterFrame;
import java.text.*;
import AlarmStatusApplet;
public class AlarmPanel implements DocumentListener,Cloneable{
static String host = null;
JPanel mainPanel = null;
AlarmTable alarmTable = null;
FilterObject filterObject = null;
int alarmFilterCount = 0;
Date filterDate = null;
Date alarmDate = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z");
String viperCellIp = null; // gp10 ip for this panel.
private static JTextField eventField = null;
public AlarmPanel(){
filterObject = FilterFrame.filterObject;
AlarmMessageMap.Init();
/*
Thread t = new LoadFileThread();
t.start();
*/
if(Util.applet == null)
{
System.out.println("Running as application");
Document doc = eventField.getDocument();
doc.addDocumentListener(this);
}
}
// Instantiated from another applet
public AlarmPanel(String viperbaseIp){
filterObject = FilterFrame.filterObject;
host = viperbaseIp;
AlarmMessageMap.Init();
}
public void setViperCellIp(String viperCell){
this.viperCellIp = viperCell;
alarmTable.setViperCellIp(viperCell);
}
public AlarmTable getAlarmTable(){
return alarmTable;
}
public JPanel createPanel(){
JPanel panel;
panel = Util.makeBorderPanel("Alarm List");
//Ananth
/*if (filterObject.NUM_ALARMS == FilterObject.NONE &&
filterObject.SEVERITY == FilterObject.NULL &&
filterObject.TIME == FilterObject.NONE &&
filterObject.ACKNOWLEDGE == FilterObject.NONE){
panel = Util.makeBorderPanel("Alarm List");
}
else{
panel = Util.makeBorderPanel("Alarm List (Filtered)");
}*/
panel.setLayout(new BorderLayout());
AlarmTableModel model = new AlarmTableModel();
alarmTable = new AlarmTable(model);
alarmTable.setViperCellIp(viperCellIp);
JScrollPane scroller= new JScrollPane( alarmTable,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED ,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(scroller, BorderLayout.CENTER);
if (host == null) // applet is run against GP10 instead of GMC
alarmTable.Refresh();
return panel;
}
public void removeRows(int start,int end){
DefaultTableModel model = (DefaultTableModel)alarmTable.getSorter().getModel();
AlarmTableSorter sorter = alarmTable.getSorter();
int row = 0;
int indexAtRow = 0;
AlarmStatusApplet.logDM("Row : " + row + " Index : " + indexAtRow);
for(int i = 0;i < (end-start); i++){
row = model.getRowCount();
indexAtRow = alarmTable.getSorter().getIndexAtRow(row-1);
AlarmStatusApplet.logDM("Row : " + row + " Index : " + indexAtRow);
sorter.filteredRemoveRow(row-1);
}
}
public void handleFilterEvent(FilterObject filter){
DefaultTableModel model = (DefaultTableModel)alarmTable.getModel();
AlarmTableSorter sorter = alarmTable.getSorter();
this.filterObject = filter;
int rowCount = model.getRowCount();
String severity = null;
String date = null;
Boolean acknowledge = null;
// filtering num of Alarms
if(filterObject.NUM_ALARMS != FilterObject.NONE){
AlarmStatusApplet.logDM("Filtering num: of Alarms");
if(rowCount > filterObject.NUM_ALARMS){
AlarmStatusApplet.logDM("Filtering no: of Alarms");
removeRows(filterObject.NUM_ALARMS,rowCount);
}
}
int newRowCount = model.getRowCount();
MyCalendar myCalendar = new MyCalendar();
filterDate = myCalendar.calculateDate();
for(int i=0;i<newRowCount;i++){
// filtering Severity
if(!filterObject.SEVERITY.equals(FilterObject.NULL)){
AlarmStatusApplet.logDM("Filtering severity");
severity = (String)model.getValueAt(i,AlarmTableModel.SEVERITY);
if(filterObject.SEVERITY.equals(FilterObject.CRITICAL)){
if(!severity.toUpperCase().equals(filterObject.CRITICAL)){
sorter.filteredRemoveRow(i);
i--;
newRowCount--;
continue;
}
}
else if(filterObject.SEVERITY.equals(FilterObject.MAJOR)){
if(!(severity.toUpperCase().equals(filterObject.CRITICAL)
|| severity.toUpperCase().equals(filterObject.MAJOR))){
sorter.filteredRemoveRow(i);
i--;
newRowCount--;
continue;
}
}
else if(filterObject.SEVERITY.equals(FilterObject.MINOR)){
if(!(severity.toUpperCase().equals(filterObject.CRITICAL)
|| severity.toUpperCase().equals(filterObject.MAJOR)
|| severity.toUpperCase().equals(filterObject.MINOR))){
sorter.filteredRemoveRow(i);
i--;
newRowCount--;
continue;
}
}
}
// filtering Date/Time
if(!(filterObject.TIME == FilterObject.NONE)){
AlarmStatusApplet.logDM("Checking timestamp");
date = (String)model.getValueAt(i,AlarmTableModel.TIMESTAMP);
try{
alarmDate = formatter.parse(date);
}
catch(ParseException ex){
System.out.println("Cudn't parse date ...");
}
if(!alarmDate.after(filterDate)){
sorter.filteredRemoveRow(i);
i--;
newRowCount--;
continue;
}
}
// filtering Ack
if(!(filterObject.ACKNOWLEDGE == FilterObject.NONE)){
AlarmStatusApplet.logDM("Filtering ack");
acknowledge = (Boolean)model.getValueAt(i,AlarmTableModel.ACK);
if(filterObject.ACKNOWLEDGE == FilterObject.NO_ACK){
if(acknowledge.booleanValue()){
sorter.filteredRemoveRow(i);
i--;
newRowCount--;
}
continue;
}
else if(filterObject.ACKNOWLEDGE == FilterObject.ALL_ACK){
if(!acknowledge.booleanValue()){
sorter.filteredRemoveRow(i);
i--;
newRowCount--;
}
continue;
}
}
} // end "for loop"
// addEvent(alarm);
}
public void addEvent(AlarmData alarm){
String severity;
Boolean acknowledge;
int ack;
String date;
DefaultTableModel model = (DefaultTableModel)alarmTable.getModel();
if(filterObject != null){
// filtering Severity
if(!filterObject.SEVERITY.equals(FilterObject.NULL)){
AlarmStatusApplet.logDM("Filtering severity");
severity = alarm.severity;
if(filterObject.SEVERITY.equals(FilterObject.CRITICAL)){
if(!severity.toUpperCase().equals(filterObject.CRITICAL)){
return;
}
}
else if(filterObject.SEVERITY.equals(FilterObject.MAJOR)){
if(!(severity.toUpperCase().equals(filterObject.CRITICAL)
|| severity.toUpperCase().equals(filterObject.MAJOR))){
return;
}
}
else if(filterObject.SEVERITY.equals(FilterObject.MINOR)){
if(!(severity.toUpperCase().equals(filterObject.CRITICAL)
|| severity.toUpperCase().equals(filterObject.MAJOR)
|| severity.toUpperCase().equals(filterObject.MINOR))){
return;
}
}
}
// filtering Ack
ack = Integer.parseInt(alarm.acknowledge);
if(ack == 0){
acknowledge = new Boolean(false);
}
else{
acknowledge = new Boolean(true);
}
if(!(filterObject.ACKNOWLEDGE == FilterObject.NONE)){
AlarmStatusApplet.logDM("Filtering ack");
if(filterObject.ACKNOWLEDGE == FilterObject.NO_ACK){
if(acknowledge.booleanValue()){
return;
}
}
else if(filterObject.ACKNOWLEDGE == FilterObject.ALL_ACK){
if(!acknowledge.booleanValue()){
return;
}
}
}
// filtering Date/Time
MyCalendar myCalendar = new MyCalendar();
filterDate = myCalendar.calculateDate();
if(!(filterObject.TIME == FilterObject.NONE)){
AlarmStatusApplet.logDM("Checking timestamp");
date = alarm.timestamp;
try{
alarmDate = formatter.parse(date);
}
catch(ParseException ex){
System.out.println("Cudn't parse date ...");
}
if(!alarmDate.after(filterDate)){
return;
}
}
// Shrinivas 05 jun 01'
// filtering NUM_ALARMS
if(filterObject.NUM_ALARMS != FilterObject.NONE){
int rowCount = model.getRowCount();
AlarmStatusApplet.logDM("Filtering num: of Alarms");
if(rowCount > filterObject.NUM_ALARMS-1){
AlarmStatusApplet.logDM("Filtering no: of Alarms");
removeRows(filterObject.NUM_ALARMS-1,rowCount);
}
}
// Shrinivas end
}
Object [] row = new Object[AlarmTableModel.NUM_COL];
row[AlarmTableModel.INDEX] = alarm.alarmIndex;
row[AlarmTableModel.READ] = new Boolean(false);
row[AlarmTableModel.ALARMID] = alarm.alarmId;
row[AlarmTableModel.TIMESTAMP] = alarm.timestamp;
row[AlarmTableModel.SEVERITY] = alarm.severity;
row[AlarmTableModel.OBJECT] = alarm.object;
row[AlarmTableModel.SUBJECT] = alarm.subject;
if(Integer.parseInt(alarm.acknowledge) == 0)
row[AlarmTableModel.ACK] = new Boolean(false);
else
row[AlarmTableModel.ACK] = new Boolean(true);
((DefaultTableModel)alarmTable.getModel()).insertRow(0, row);
alarmTable.setAlarmData(alarm);
}
public void removeAllEvents()
{
while (((DefaultTableModel)alarmTable.getModel()).getRowCount() > 0)
((DefaultTableModel)alarmTable.getModel()).removeRow(0);
}
static public void main(String[] argv)
{
eventField = new JTextField();
host = argv[0];
try
{
boolean useTCP = true;
int portNum = 80;
int maxLen = 4096;
System.out.println("Connect to " + host + " prot " +portNum);
Broker.setOptions(host, portNum, maxLen, useTCP);
}
catch(UnknownHostException e) { e.printStackTrace(); }
Broker.addMagicMarkup("QSEvent", "java.lang.String", false);
RlBeanProperty beanProp = Broker.wrapBeanProperty(eventField, "text", java.lang.String.class);
Broker.bindMarkupToBeanProperty("QSEvent", "", null, beanProp, true, false, true, null);
Broker.start();
JFrame f = new JFrame("ViperCell Event List");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(1);
}
});
f.getContentPane().setLayout(new BorderLayout());
AlarmPanel base = new AlarmPanel();
f.getContentPane().add(base.createPanel());
f.setBounds(0,0, 720,400);
try
{
UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI(f);
}
catch(Exception ex)
{
Util.showDialog(f, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
f.setVisible(true);
/*
Random r = new Random();
Calendar d = Calendar.getInstance();
String severity = null;
for(int i=0; i<20; i++)
{
try {
d.add(Calendar.SECOND, java.lang.Math.abs(r.nextInt()));
if (i-i/3*3 == 0)
severity = new String("Critical");
else if (i-i/3 == 1)
severity = new String("Minor");
else if (i - i/3*3 == 2)
severity = new String("Info");
String date = d.getTime().toString();
String object = "Object_"+String.valueOf(java.lang.Math.abs(r.nextInt()));
String message = " Event messages ....";
AlarmData alarm = new AlarmData(String.valueOf(i), date, severity, null, object, message, null);
base.addEvent(alarm);
Thread.sleep(10000);
System.out.println("Event: " +i);
}
catch(Exception e)
{}
}
*/
}
public void changedUpdate(DocumentEvent e)
{
}
public void insertUpdate(DocumentEvent e)
{
String alarmId = eventField.getText();
alarmId.trim();
System.out.println("Receiving Alarm: " + alarmId);
if(!alarmId.startsWith("Event Number"))
{
try {
AlarmData alarm = new AlarmData(alarmId);
addEvent(alarm);
}
catch(Exception ex) {}
}
}
public void removeUpdate(DocumentEvent e)
{
}
class LoadFileThread extends Thread
{
public void run()
{
AlarmMessageMap.Init();
}
}
class MyCalendar extends GregorianCalendar{
public Date calculateDate(){
MyCalendar myCalen = new MyCalendar();
long currentMillis = myCalen.getTimeInMillis();
long temp;
Date pDate = null;
if(filterObject.TIME == FilterObject.MIN_15){
temp = 15 * 60 * 1000;
pDate = new Date(currentMillis - temp);
}
else if(filterObject.TIME == FilterObject.HR_1){
temp = 60 * 60 * 1000;
pDate = new Date(currentMillis - temp);
}
else if(filterObject.TIME == FilterObject.HR_12){
temp = (12 * 60 ) * 60 * 1000;
pDate = new Date(currentMillis - temp);
}
else if(filterObject.TIME == FilterObject.HR_24){
temp = (24 * 60 ) * 60 * 1000;
pDate = new Date(currentMillis - temp);
}
return pDate;
}
}
}
//$History:$

View File

@ -0,0 +1,588 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : AlarmTable
// Desc :
// Author : George Zhao
// Hist : 06/17/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
package com.jetcell.MibWM;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.util.Hashtable;
import java.awt.*;
import java.io.*;
import java.awt.image.*;
import java.net.*;
import AlarmTCPThread;
public class AlarmTable extends JTable {
DefaultTableModel model;
JPopupMenu popupMenu = null;
final int [] columnMinWidth = {25, 30, 150, 50, 80, 250, 0,25};
final int [] columnMaxWidth = {40, 60, 200, 100, 150, 800, 0,40};
AlarmTableSorter sorter = null;
Hashtable alarmHashTable = null;
DetailFrame detailFrame = new DetailFrame();
String viperCellIp = null;
public AlarmTable(DefaultTableModel model)
{
super(model);
popupMenu = AlarmTablePopupMenu.getPopupMenu();
sorter = new AlarmTableSorter(model);
super.setModel( sorter );
addMouseListener(new MouseHandler(this));
alarmHashTable = new Hashtable();
for (int i=0; i < model.getColumnCount(); i++ )
setColumnWidth(i, columnMinWidth[i], columnMaxWidth[i]);
TableColumnModel colModel = getColumnModel();
colModel.getColumn(AlarmTableModel.READ).setCellRenderer(new ReadCellRenderer());
colModel.getColumn(AlarmTableModel.SEVERITY).setCellRenderer(new SeverityRenderer());
colModel.getColumn(AlarmTableModel.ACK).setCellRenderer(new ReadCellRenderer());
setRowSelectionAllowed(true);
setColumnSelectionAllowed(false);
setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
setShowGrid(true);
setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
setShowVerticalLines(false);
setGridColor(new Color(153,153,255));
}
public AlarmTableSorter getSorter(){
return this.sorter;
}
public void setViperCellIp(String viperCell){
this.viperCellIp = viperCell;
}
public void setColumnWidth(int columnIndex, int minWidth, int maxWidth)
{
TableColumn column = (TableColumn)getColumn(getColumnName(columnIndex));
column.setMinWidth(minWidth);
column.setMaxWidth(maxWidth);
}
public boolean isCellEditable(int i, int j)
{
return false;
}
public AlarmData getAlarmData(Integer index)
{
if (alarmHashTable != null)
return (AlarmData) alarmHashTable.get(index);
return null;
}
public void setAlarmData(AlarmData alarmdata){
if(AlarmMessageMap.readfile){
alarmHashTable.put(alarmdata.alarmIndex, alarmdata);
}
}
public void OpenEvent()
{
Integer index = (Integer)getValueAt(getSelectedRow(), AlarmTableModel.INDEX);
System.out.println("Open Event: " +index);
AlarmData data = (AlarmData) alarmHashTable.get(index);
data.dump();
detailFrame.setData(data);
Dimension d = new JFrame().getToolkit().getScreenSize();
detailFrame.setLocation(d.width/4,d.height/3);
detailFrame.setResizable(false);
if(Util.applet == null){
detailFrame.setIconImage(Toolkit.getDefaultToolkit().getImage("../Images/app_icon.gif"));
}
else{
String iconPath = Util.applet.getCodeBase().toString();
iconPath += "Images/app_icon.gif";
URL iconPathURL = null;
try{
iconPathURL = new URL(iconPath);
}
catch(MalformedURLException exc){
System.out.println("Bad URL.");
}
System.out.println(iconPathURL);
detailFrame.setIconImage(Toolkit.getDefaultToolkit().getImage(iconPathURL));
}
//detailFrame.setIconImage(Toolkit.getDefaultToolkit().getImage("../Images/app_icon.gif"));
detailFrame.setVisible(true);
setValueAt(new Boolean(true), getSelectedRow(), AlarmTableModel.READ);
}
public void RemoveAllEvents()
{
System.out.println("Remove All");
while( getRowCount()> 0)
{
((DefaultTableModel) getModel()).removeRow(0);
}
}
public void RemoveInfoEvents()
{
System.out.println("Remvoe Info");
sorter.reallocateIndexes();
sorter.sortByColumn(AlarmTableModel.ALARMID, false);
for (int i=0; i< getRowCount(); i++)
{
if (((String) getValueAt(i, AlarmTableModel.SEVERITY)).equals("Info"))
{
System.out.println("removing row " + i);
((DefaultTableModel) getModel()).removeRow(i);
}
}
}
public void RemoveReadEvents()
{
System.out.println("RemoveRead");
sorter.reallocateIndexes();
sorter.sortByColumn(AlarmTableModel.READ, false);
for (int i=0; i< getRowCount(); i++)
{
if (((Boolean) getValueAt(i, AlarmTableModel.READ)).booleanValue())
{
System.out.println("removing row " + i);
((DefaultTableModel) getModel()).removeRow(i);
i--;
}
}
}
public void RemoveEvent()
{
String alarmId = (String)getValueAt(getSelectedRow(), AlarmTableModel.INDEX);
System.out.println("Remove Event: " +alarmId);
sorter.reallocateIndexes();
sorter.sortByColumn(AlarmTableModel.ALARMID, false);
for (int i=0; i< getRowCount(); i++)
{
if (((String) getValueAt(i, AlarmTableModel.INDEX)).equals(alarmId))
{
System.out.println("removing row " + i);
((DefaultTableModel) getModel()).removeRow(i);
break;
}
}
}
public void Refresh(){
RemoveAllEvents();
java.net.URL cfg_url = null;
// Shrinivas Feb 28th
AlarmTCPThread.sendEventReq(viperCellIp);
/*if(Util.applet == null){
AlarmTCPThread.sendEventReq(viperCellIp);
}
// original applet code : Refresh logic as it was before
else{
try {
if(Util.applet != null)
cfg_url = new java.net.URL(Util.applet.getDocumentBase()+"Text/alarm.log");
else
cfg_url = new java.net.URL("http://"+AlarmPanel.host+"/Text/alarm.log");
System.out.println("Open File: " +cfg_url);
java.io.BufferedReader in = new java.io.BufferedReader(new InputStreamReader(cfg_url.openStream()));
String line = null;
while( (line = in.readLine()) != null){
try {
System.out.println("Line : " +line);
AlarmData alarm = new AlarmData(line);
setAlarmData(alarm);
Object [] row = new Object[AlarmTableModel.NUM_COL];
row[AlarmTableModel.INDEX] = alarm.alarmIndex;
row[AlarmTableModel.READ] = new Boolean(false);
row[AlarmTableModel.ALARMID] = alarm.alarmId;
row[AlarmTableModel.TIMESTAMP] = alarm.timestamp;
row[AlarmTableModel.SEVERITY] = alarm.severity;
row[AlarmTableModel.OBJECT] = alarm.object;
row[AlarmTableModel.SUBJECT] = alarm.subject;
((DefaultTableModel)getModel()).insertRow(0, row);
}
catch(Exception ex) {}
}
}
catch(FileNotFoundException e){
System.out.println(e.toString());
System.out.println("Cannot open alarm code file Text/alarm.log");
}
catch(IOException ex){
System.out.println("IO Exception: " + ex.toString());
}
}*/
// Shrinivas end
}
public void Acknowledge(){
Integer index = (Integer)getValueAt(getSelectedRow(), AlarmTableModel.INDEX);
AlarmData data = (AlarmData) alarmHashTable.get(index);
if(data == null)
System.out.println("unable to get Alarm data");
AlarmTCPThread.sendAck(data.srcIp,data.alarmId,data.recordNumber);
setValueAt(new Boolean(true), getSelectedRow(), AlarmTableModel.ACK);
}
class MouseHandler extends MouseAdapter
{
AlarmTable holder = null;
public MouseHandler(AlarmTable table){
this.holder = table;
}
public void mouseReleased(MouseEvent e){
if (e.getClickCount() == 2 )
{
System.out.println("Process Double click");
OpenEvent();
}
if ( e.isPopupTrigger()){
int selectedRow = rowAtPoint(new Point(e.getX(),e.getY()));
setRowSelectionInterval(selectedRow,selectedRow);
popupMenu.show(holder, e.getX(), e.getY());
}
}
}
class ReadCellRenderer extends JCheckBox implements TableCellRenderer
{
Color mHighlightedBackground = (Color) (new Color(0, 0, 255)).darker().darker();
Color mDefaultBackground = SystemColor.window;
public ReadCellRenderer()
{
setBackground(Color.white);
setHorizontalAlignment(JLabel.CENTER);
}
public Component getTableCellRendererComponent( JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column )
{
Boolean b = (Boolean) value;
if(b != null){
setSelected(b.booleanValue());
}
return this;
}
}
class SeverityRenderer extends JLabel implements TableCellRenderer
{
Color mHighlightedBackground = (Color) (new Color(0, 0, 255)).darker().darker();
Color mDefaultBackground = SystemColor.window;
Font defaultFont = new Font("Helvetica", Font.BOLD,12);
Font empFont = new Font("TimesRoman", Font.BOLD,18);
ImageIcon severityIcon = null;
ImageIcon criticalIcon = null;
ImageIcon majorIcon = null;
ImageIcon minorIcon = null;
ImageIcon infoIcon = null;
public SeverityRenderer(){
super("");
loadIcons();
setHorizontalAlignment(JLabel.CENTER);
}
private void loadIcons(){
String fileSep = System.getProperty("file.separator");
String codeBase = null;
String imagePath = "file:" +".."+fileSep+"Images"+fileSep;
String imageFile = null;
if(Util.applet != null){
codeBase = Util.applet.getCodeBase().toString();
System.out.println(codeBase);
}
try{
if(Util.applet != null){
imageFile = codeBase + "Images/scritical.gif";
}
else{
imageFile = imagePath+"scritical.gif";
}
criticalIcon = new ImageIcon(new URL(imageFile));
if(Util.applet != null){
imageFile = codeBase + "Images/smajor.gif";
}
else
imageFile = imagePath+"smajor.gif";
majorIcon = new ImageIcon(new URL(imageFile));
if(Util.applet != null){
imageFile = codeBase + "Images/sminor.gif";
}
else
imageFile = imagePath+"sminor.gif";
minorIcon = new ImageIcon(new URL(imageFile));
if(Util.applet != null){
imageFile = codeBase + "Images/sinformation.gif";
}
else
imageFile = imagePath + "sinformation.gif";
infoIcon = new ImageIcon(new URL(imageFile));
}
catch(MalformedURLException malEx){
System.out.println("Bad URL");
}
}
public Component getTableCellRendererComponent( JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column ){
String severity = (String) value;
if(value != null){
if(severity.equals(AlarmData.AlarmSeverity[0])) {
setIcon(criticalIcon);
criticalIcon.setImageObserver(new CellImageObserver(table, row, column));
}
else if(severity.equals(AlarmData.AlarmSeverity[1])){
setIcon(majorIcon);
majorIcon.setImageObserver(new CellImageObserver(table, row, column));
}
else if (severity.equals(AlarmData.AlarmSeverity[2])){
setIcon(minorIcon);
minorIcon.setImageObserver(new CellImageObserver(table, row, column));
}
else if (severity.equals(AlarmData.AlarmSeverity[3])){
setIcon(infoIcon);
infoIcon.setImageObserver(new CellImageObserver(table, row, column));
}
}
if (isSelected){
setBackground(mHighlightedBackground);
}
else{
setBackground(mDefaultBackground);
}
return this;
}
}
class CellImageObserver implements ImageObserver {
JTable table;
int row;
int col;
CellImageObserver(JTable table,int row, int col) {
this.table = table;
this.row = row;
this.col = col;
}
public boolean imageUpdate(Image img, int flags,int x, int y, int w, int h){
if ((flags & (FRAMEBITS|ALLBITS)) != 0) {
Rectangle rect = table.getCellRect(row,col,false);
table.repaint(rect);
}
return (flags & (ALLBITS|ABORT)) == 0;
}
}
class DetailFrame extends JFrame implements ActionListener
{
JPanel mainPanel = null;
final int WIDTH = 520;
final int HEIGHT = 360;
final int rows = 4;
final int columns = 40;
JTextField alarmIdField = Util.makeTextField(false);
JTextField severityField = Util.makeTextField(false);
JTextField timestampField = Util.makeTextField(false);
JTextField objectField = Util.makeTextField(false);
JTextField subjectField = Util.makeTextField(false);
JTextArea messageArea = Util.makeTextArea(rows, columns, false);
JButton closeButton = new JButton("Close");
public DetailFrame ()
{
mainPanel = createPanel();
getContentPane().add(mainPanel, BorderLayout.CENTER);
pack();
setSize(getPreferredSize());
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
close();
}
});
closeButton.addActionListener(this);
try
{
UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
}
catch(Exception ex)
{
Util.showDialog(this, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
public JPanel createPanel()
{
JPanel panel = Util.makeBorderPanel();
panel.setLayout(new BorderLayout(0, 0));
panel.add(makeDetailPanel(), BorderLayout.CENTER);
panel.add(makeMessagePanel(), BorderLayout.SOUTH);
return panel;
}
JPanel makeDetailPanel()
{
JPanel panel = Util.makeBorderPanel("Event Data");
GridBagConstraints gbc;
GridBagLayout gridbag = new GridBagLayout();
gbc = new GridBagConstraints();
JLabel label;
panel.setLayout(gridbag);
label = new JLabel("Event ID ", JLabel.RIGHT);
label.setToolTipText("Alarm ID");
Util.constrain(label, panel, gbc, 0,0,1,1,
GridBagConstraints.VERTICAL,GridBagConstraints.WEST,
0.0,0.0,0,5,5,0);
Util.constrain(alarmIdField, panel, gbc, 1,0,1,1,
GridBagConstraints.HORIZONTAL,GridBagConstraints.WEST,
100.0,100.0,0,5,5,0);
label = new JLabel("Severity ",JLabel.RIGHT);
label.setToolTipText("Severity of the Event");
Util.constrain(label, panel, gbc, 2,0,1,1,
GridBagConstraints.VERTICAL,GridBagConstraints.WEST,
0.0,0.0,0,5,5,0);
Util.constrain(severityField, panel, gbc, 3,0,1,1,
GridBagConstraints.HORIZONTAL,GridBagConstraints.WEST,
100.0,100.0,0,5,5,0);
label = new JLabel("Time Stamp ",JLabel.RIGHT);
label.setToolTipText("Event time stamp");
Util.constrain(label, panel, gbc, 0,1,1,1,
GridBagConstraints.VERTICAL,GridBagConstraints.WEST,
0.0,0.0,0,5,5,0);
Util.constrain(timestampField, panel, gbc, 1,1,1,1,
GridBagConstraints.HORIZONTAL,GridBagConstraints.WEST,
100.0,100.0,0,5,5,0);
label = new JLabel("Object ",JLabel.RIGHT);
label.setToolTipText("Name of the object that generated this event");
Util.constrain(label, panel, gbc, 2,1,1,1,
GridBagConstraints.VERTICAL,GridBagConstraints.WEST,
0.0,0.0,0,5,5,0);
Util.constrain(objectField, panel, gbc, 3,1,1,1,
GridBagConstraints.HORIZONTAL,GridBagConstraints.WEST,
100.0,100.0,0,5,5,0);
label = new JLabel("Subject ",JLabel.RIGHT);
label.setToolTipText("Subject of the Event");
Util.constrain(label, panel, gbc, 0,2,1,1,
GridBagConstraints.VERTICAL,GridBagConstraints.WEST,
0.0,0.0,0,5,5,0);
Util.constrain(subjectField, panel, gbc, 1,2,3,1,
GridBagConstraints.HORIZONTAL,GridBagConstraints.WEST,
100.0,100.0,0,5,5,0);
return panel;
}
JPanel makeMessagePanel()
{
JPanel panel = Util.makeEmptyBorderPanel();
panel.setLayout(new BorderLayout(0,0));
panel.add(messageAreaPanel(), BorderLayout.CENTER);
panel.add(makeButtonPanel(), BorderLayout.SOUTH);
return panel;
}
JPanel messageAreaPanel()
{
JPanel panel = Util.makeBorderPanel("Message");
panel.setLayout(new BorderLayout(0,0));
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
JScrollPane scroller = new JScrollPane(messageArea);
panel.add(scroller, BorderLayout.CENTER);
return panel;
}
JPanel makeButtonPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(closeButton);
return panel;
}
public Dimension getPreferredSize()
{
return new Dimension(WIDTH, HEIGHT);
}
public void actionPerformed(ActionEvent event)
{
Object obj = event.getSource();
if (obj == closeButton)
close();
}
public void close()
{
setVisible(false);
}
public void setData(AlarmData data)
{
setTitle("Event Detail for Event Id: " +data.alarmId);
alarmIdField.setText(data.alarmId);
severityField.setText(data.severity);
timestampField.setText(data.timestamp);
objectField.setText(data.object);
subjectField.setText(data.subject);
messageArea.setText(data.message);
}
}
}
//$History:$

View File

@ -0,0 +1,43 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : AlarmTableModel
// Desc :
// Author : George Zhao
// Hist : 06/17/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
package com.jetcell.MibWM;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class AlarmTableModel extends DefaultTableModel
{
final static int INDEX = 6;
final static int READ = 0;
final static int ALARMID = 1;
final static int TIMESTAMP = 2;
final static int SEVERITY = 3;
final static int OBJECT = 4;
final static int SUBJECT = 5;
final static int MESSAGE = 6;
final static int ACK = 7;
static String ColumnTitle[] = {"Read", "Alarm ID", "Time Stamp", "Severity", "Object", "Message Subject", "","Ack"};
final static int NUM_COL = ColumnTitle.length;
public AlarmTableModel()
{
super(ColumnTitle, 0);
}
}
//$History:$

View File

@ -0,0 +1,218 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : AlarmTablePopupMenu
// Desc :
// Author : George Zhao
// Hist : 06/17/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
package com.jetcell.MibWM;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.table.*;
public class AlarmTablePopupMenu extends JPopupMenu implements ActionListener
{
static JMenuItem openMenuItem;
static JMenuItem removeMenuItem;
static JMenuItem removeAllMenuItem;
static JMenuItem removeReadMenuItem;
static JMenuItem removeInfoMenuItem;
static JMenuItem refreshMenuItem;
static JMenuItem acknowledgeMenuItem;
static boolean iconsLoaded = false;
protected static AlarmTablePopupMenu popupMenu = new AlarmTablePopupMenu();
static AlarmTable invoker ;
static int x;
static int y;
/**
* You cannot instantiate this class. Use getPopupMenu() to get
* a shared instance!
*/
protected AlarmTablePopupMenu()
{
openMenuItem = Util.makeMenuItem("Open Event",'O');
openMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
openMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
openMenuItem.addActionListener(this);
add(openMenuItem);
addSeparator();
/*
removeMenuItem = Util.makeMenuItem("Remove Event",'R');
removeMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
removeMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
removeMenuItem.addActionListener(this);
add(removeMenuItem);
addSeparator();
removeAllMenuItem = Util.makeMenuItem("Remove All Events", 'A');
removeAllMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
removeAllMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
removeAllMenuItem.addActionListener(this);
add(removeAllMenuItem);
removeReadMenuItem = Util.makeMenuItem("Remove Read Events", 'E');
removeReadMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
removeReadMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
removeReadMenuItem.addActionListener(this);
add(removeReadMenuItem);
removeInfoMenuItem = Util.makeMenuItem("Remove Clear Events", 'C');
removeInfoMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
removeInfoMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
removeInfoMenuItem.addActionListener(this);
add(removeInfoMenuItem);*/
// Shrinivas 20th Apr 01
/*addSeparator();
refreshMenuItem = Util.makeMenuItem("Refresh", 'R');
refreshMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
refreshMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
refreshMenuItem.addActionListener(this);
add(refreshMenuItem);*/
// Shrinivas 20th Apr 01
addSeparator();
addSeparator();
acknowledgeMenuItem = Util.makeMenuItem("Acknowledge", 'A');
acknowledgeMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
acknowledgeMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
acknowledgeMenuItem.addActionListener(this);
add(acknowledgeMenuItem);
}
/**
* returns shared instance of popupMenu
*/
public static AlarmTablePopupMenu getPopupMenu()
{
return popupMenu;
}
/**
* update to use difference icons later!
*/
void loadIcons()
{
openMenuItem.setIcon(new ImageIcon(ImageLoader.loadImage("opengray.gif")));
removeAllMenuItem.setIcon(new ImageIcon(ImageLoader.loadImage("delete.gif")));
removeReadMenuItem.setIcon(new ImageIcon(ImageLoader.loadImage("delete.gif")));
removeInfoMenuItem.setIcon(new ImageIcon(ImageLoader.loadImage("delete.gif")));
refreshMenuItem.setIcon(new ImageIcon(ImageLoader.loadImage("reset.gif")));
}
/**
* update to use shared clipboard access later
*/
public void actionPerformed(ActionEvent e)
{
Object obj = e.getSource();
String selection = null;
if (obj == openMenuItem)
{
invoker.OpenEvent();
}
else if (obj == removeMenuItem)
{
invoker.RemoveEvent();
}
else if (obj == removeAllMenuItem)
{
invoker.RemoveAllEvents();
}
else if (obj == removeReadMenuItem)
{
invoker.RemoveReadEvents();
}
else if (obj == removeInfoMenuItem)
{
invoker.RemoveInfoEvents();
}
else if (obj == refreshMenuItem){
invoker.Refresh();
}
else if (obj == acknowledgeMenuItem){
invoker.Acknowledge();
}
}
/**
* force JTable only later
*/
public void show(Component c, int x, int y)
{
invoker = (AlarmTable)c;
/*
if (iconsLoaded == false)
{
loadIcons();
iconsLoaded = true;
}
*/
Point p = new Point(x,y);
int row = invoker.rowAtPoint(p);
int col = invoker.columnAtPoint(p);
/*
if ((row >= 0) && (col >= 0))
enableMenu();
else
{
disableMenu();
return;
}
*/
DefaultTableModel model = (DefaultTableModel)invoker.getModel();
Boolean acknowledge = (Boolean) model.getValueAt(row,AlarmTableModel.ACK);
if(acknowledge.booleanValue()){
acknowledgeMenuItem.setEnabled(false);
}
else{
acknowledgeMenuItem.setEnabled(true);
}
this.x = x;
this.y = y;
super.show(c,x,y);
}
void disableMenu()
{
openMenuItem.setEnabled(false);
removeAllMenuItem.setEnabled(false);
removeReadMenuItem.setEnabled(false);
removeInfoMenuItem.setEnabled(false);
}
void enableMenu()
{
openMenuItem.setEnabled(true);
removeAllMenuItem.setEnabled(true);
removeReadMenuItem.setEnabled(true);
removeInfoMenuItem.setEnabled(true);
}
}
//$History:$

View File

@ -0,0 +1,97 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : AlarmTableSorter
// Desc : table sorter for Order explorer request table.
// Author : George Zhao
// Hist : June 18, 1999
//
//////////////////////////////////////////////////////////////////////////////
package com.jetcell.MibWM;
import java.awt.*;
import java.util.*;
import javax.swing.table.*;
class AlarmTableSorter extends TableSorter
{
public AlarmTableSorter (TableModel model)
{
super (model);
}
public int compareRowsByColumn(int row1, int row2, int column)
{
TableModel data = model;
// Check for nulls
Object o1 = data.getValueAt(row1, column);
Object o2 = data.getValueAt(row2, column);
// If both values are null return 0
if (o1 == null && o2 == null) {
return 0;
}
else if (o1 == null) { // Define null less than everything.
return -1;
}
else if (o2 == null) {
return 1;
}
try {
if (column == AlarmTableModel.ALARMID ) {
float id1 = (new Float (((String)data.getValueAt(row1, AlarmTableModel.ALARMID)).trim())).floatValue();
float id2 = (new Float (((String)data.getValueAt(row2, AlarmTableModel.ALARMID)).trim())).floatValue();
if (id1 < id2)
return -1;
else if (id1 > id2)
return 1;
else
return 0;
}
else if (column == AlarmTableModel.READ)
{
boolean b1 = ((Boolean) data.getValueAt(row1, column)).booleanValue();
boolean b2 = ((Boolean) data.getValueAt(row2, column)).booleanValue();
if(b1 && !b2) return -1;
else if(!b1 && b2) return 1;
else return 0;
}
else if (column == AlarmTableModel.ACK)
{
boolean b1 = ((Boolean) data.getValueAt(row1, column)).booleanValue();
boolean b2 = ((Boolean) data.getValueAt(row2, column)).booleanValue();
if(b1 && !b2) return -1;
else if(!b1 && b2) return 1;
else return 0;
}
else {
String s1 = (String)data.getValueAt(row1, column);
String s2 = (String)data.getValueAt(row2, column);
int result = s1.compareTo(s2);
if (result < 0)
return -1;
else if (result > 0)
return 1;
else return 0;
}
}
catch (NumberFormatException e)
{
System.out.println(e);
}
return 0;
}
}
//$History:$

View File

@ -0,0 +1,312 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : BaseTable
// Desc :
// Author : George Zhao
// Hist : 06/17/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
package com.jetcell.MibWM;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import javax.swing.event.*;
public class BaseTable extends JTable
{
static final int KEY_UP = 1;
static final int KEY_DOWN = 2;
static final int KEY_HOME = 3;
static final int KEY_END = 4;
static final int KEY_PGUP = 5;
static final int KEY_PGDN = 6;
JTableHeader tableHeader;
TableModel model;
TableSorter sorter;
static JPopupMenu popupMenu;
public BaseTable()
{
super();
modTable();
}
public BaseTable(Object[][] data, Object[] cols)
{
super(data,cols);
modTable();
}
public BaseTable(TableModel dm)
{
super();
model = dm;
modTable();
}
public BaseTable(TableModel dm, TableColumnModel cm)
{
super(dm, cm);
model = dm;
modTable();
}
public BaseTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm)
{
super(dm, cm, sm);
model = dm;
modTable();
}
public BaseTable(int numRows, int numColumns)
{
super(numRows, numColumns);
modTable();
}
public BaseTable(Vector rowData, Vector columnNames)
{
super(rowData, columnNames);
modTable();
}
public void setPopupMenu (JPopupMenu popupMenu)
{
this.popupMenu = popupMenu;
}
public JPopupMenu getPopupMenu()
{
return popupMenu;
}
void modTable()
{
addKeyboardHooks();
addHeaderHooks();
popupMenu = TablePopupMenu.getPopupMenu();
add(popupMenu);
addMouseListener(new MouseHandler() );
}
void addHeaderHooks()
{
if( model != null )
{
sorter = new TableSorter( model );
sorter.addMouseListenerToHeaderInTable( this );
super.setModel( sorter );
}
}
public boolean isCellEditable(int i, int j)
{
return false;
}
public void makeCurrentRowVisible()
{
scrollRectToVisible(getCellRect(getSelectedRow(),0 , true));
}
public void selectFirstRow()
{
getSelectionModel().setSelectionInterval(0,0);
}
void addKeyboardHooks()
{
//debug("adding table hooks");
int criteria;
criteria = WHEN_IN_FOCUSED_WINDOW;
//criteria = WHEN_FOCUSED;
registerKeyboardAction(new TableKeyboardHandler(KEY_UP) , KeyStroke.getKeyStroke(KeyEvent.VK_UP,0), criteria);
registerKeyboardAction(new TableKeyboardHandler(KEY_DOWN), KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0), criteria);
registerKeyboardAction(new TableKeyboardHandler(KEY_HOME), KeyStroke.getKeyStroke(KeyEvent.VK_HOME,0), criteria);
registerKeyboardAction(new TableKeyboardHandler(KEY_END) , KeyStroke.getKeyStroke(KeyEvent.VK_END,0), criteria);
registerKeyboardAction(new TableKeyboardHandler(KEY_PGUP), KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP,0), criteria);
registerKeyboardAction(new TableKeyboardHandler(KEY_PGDN), KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN,0), criteria);
}
class TableKeyboardHandler extends AbstractAction
{
int key;
int pageInc = 5; // fix later to found out number of visible rows!
int row;
int lastRow;
public TableKeyboardHandler(int key)
{
this.key = key;
}
public void actionPerformed(ActionEvent e)
{
switch(key)
{
case KEY_UP :
//debug("Up arrow");
row = getSelectedRow();
if (row <= 0)
getToolkit().beep();
else
{
row=row-1;
setRowSelectionInterval (row,row);
updateUI();
}
break;
case KEY_DOWN :
//debug("Down arrow");
row = getSelectedRow();
if ((row == getRowCount()-1) || (row < 0))
getToolkit().beep();
else
{
row++;
setRowSelectionInterval (row,row);
updateUI();
}
break;
case KEY_HOME :
//debug("Home key");
row = getSelectedRow();
if (row <= 0)
getToolkit().beep();
else
{
setRowSelectionInterval (0,0);
updateUI();
}
break;
case KEY_END :
//debug("End key");
lastRow = getRowCount()-1;
row = getSelectedRow();
if ((row == lastRow) || (row < 0))
getToolkit().beep();
else
{
setRowSelectionInterval (lastRow,lastRow);
updateUI();
}
break;
case KEY_PGUP :
//debug("Page up");
row = getSelectedRow();
if (row <= 0)
getToolkit().beep();
else if (row-pageInc <= 0)
{
setRowSelectionInterval (0,0);
updateUI();
}
else
{
row=row-pageInc;
setRowSelectionInterval (row,row);
updateUI();
}
break;
case KEY_PGDN :
//debug("Page down");
int lastRow = getRowCount()-1;
row = getSelectedRow();
if ((row == lastRow) || (row < 0))
getToolkit().beep();
else if (row+pageInc >= lastRow)
{
setRowSelectionInterval (lastRow,lastRow);
updateUI();
}
else
{
row+=pageInc;
setRowSelectionInterval (row,row);
updateUI();
}
break;
default :
System.out.println("Key not handled " + key);
break;
}
makeCurrentRowVisible();
}
}
class MouseHandler extends MouseAdapter
{
public void mouseReleased(MouseEvent e)
{
if ( e.isPopupTrigger())
{
popupMenu.show(BaseTable.this, e.getX(), e.getY());
}
}
}
public void setScrollPane(JScrollPane p)
{
// only here for compatibility with drop1 code. remove later!
}
public void setColumnWidth(int columnIndex, int minWidth, int maxWidth)
{
TableColumn column = (TableColumn) getColumn( getColumnName( columnIndex ) );
column.setMinWidth(minWidth);
column.setMaxWidth(maxWidth);
}
public String getDataFromTable( int col )
{
if ( getRowCount() > 0 )
{
int row = getSelectedRow();
if (row < 0)
{
setRowSelectionInterval(0,0);
row = getSelectedRow();
}
return (String) getModel().getValueAt( row, col );
}
else
return "";
}
public void setColumnHeaderTitle( int column, String value )
{
DefaultTableColumnModel cm = (DefaultTableColumnModel)getColumnModel();
TableColumn tc = cm.getColumn( column );
tc.setHeaderValue( value );
}
}
//$History:$

View File

@ -0,0 +1,136 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : ImageLoader
// Desc : Use to load images from the Images directory.
// Author : George Zhao
// History: April 22, 1999 Intial Creation.
//////////////////////////////////////////////////////////////////////////////
package com.jetcell.MibWM;
import java.awt.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import com.jetcell.MibWM.Images.ImageStub;
public class ImageLoader
{
private static Hashtable imageCache = new Hashtable();
/**
* load image from com/jetcell/MibWM/Images
*/
public synchronized static Image loadImage(String filename)
{
Image image = null;
/*
if (ImageLoader.imageInCache(filename))
image = ImageLoader.getImageFromCache(filename);
else*/
{
if ( Util.applet != null )
{
/**
* load using applet method
*/
try {
URL url = new URL(Util.applet.getCodeBase()+ "com/jetcell/MibWM/Images/" + filename);
image = Util.applet.getImage(url);
}
catch(Exception e) {}
//image = Util.applet.getImage(Util.applet.getCodeBase(), "com/jetcell/MibWM/Images/" + filename);
if (image == null) System.out.println("Image is NULL: " +filename);
}
else
{
/**
* load using application method
*/
URL url = new ImageStub().getClass().getResource(filename);
Toolkit tk = java.awt.Toolkit.getDefaultToolkit();
try
{
image = tk.createImage((java.awt.image.ImageProducer) url.getContent());
}
catch (java.io.IOException e)
{
System.out.println("[ImageLoader] " + e.toString());
}
}
/**
* block while waiting for image to load
*/
if (image != null)
{
MediaTracker tracker = new MediaTracker(new Component() {} );
tracker.addImage(image, 0);
try
{
tracker.waitForID(0);
}
catch (InterruptedException e)
{
System.out.println("[ImageLoader] " + e.toString());
}
/**
* add to cache
*/
ImageLoader.putImageInCache(filename, image);
}
}
return image;
}
/**
* load icon from com/mci/vdds/Images
*/
public synchronized static ImageIcon loadIcon(String filename)
{
return new ImageIcon(loadImage(filename));
}
private static boolean imageInCache(String filename)
{
if (imageCache.containsKey(filename))
return true;
else
return false;
}
private static Image getImageFromCache(String filename)
{
return (Image)imageCache.get(filename);
}
private static void putImageInCache(String filename, Image image)
{
imageCache.put(filename, image);
}
public static void main(String argv[])
{
JFrame f = new JFrame();
ImageIcon icon = ImageLoader.loadIcon("closed.gif");
JButton b = new JButton(icon);
System.out.println("after new messagepanel");
f.setBounds(0,0,100,100);
f.getContentPane().add(b);
f.setVisible(true);
}
}
//$History:$

View File

@ -0,0 +1,38 @@
####################################################################
#
# FILE NAME: Makefile
#
# DESCRIPTION: This makefile creates the vipercell related class
# files
# COMPONENTS:
#
#
# NOTES:
#
# (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
#
# REVISION HISTORY
#__________________________________________________________________
#----------+--------+----------------------------------------------
# Name | Date | Reason
#----------+--------+----------------------------------------------
# Bhawani |11/28/99| Initial Draft
#----------+--------+----------------------------------------------
####################################################################
#/
CODEBASE = ../../..
include $(CODEBASE)/java.mk
all: $(CLASS_LIST)
clean:
$(RM) *.class
cleanall:
$(RM) *.class

View File

@ -0,0 +1,104 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : TableMap
// Desc :
// Author : George Zhao
// Hist : 06/17/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
/**
* based on Sun TableMap. -gz
* @version 1.4 12/17/97
* @author Philip Milne */
package com.jetcell.MibWM;
import javax.swing.table.*;
import javax.swing.event.TableModelListener;
import javax.swing.event.TableModelEvent;
public class TableMap extends DefaultTableModel implements TableModelListener
{
protected TableModel model;
public TableModel getModel() {
return model;
}
public void setModel(TableModel model) {
this.model = model;
model.addTableModelListener(this);
}
// By default, Implement TableModel by forwarding all messages
// to the model.
public Object getValueAt(int aRow, int aColumn) {
return model.getValueAt(aRow, aColumn);
}
public void setValueAt(Object aValue, int aRow, int aColumn) {
model.setValueAt(aValue, aRow, aColumn);
}
public int getRowCount() {
return (model == null) ? 0 : model.getRowCount();
}
public int getColumnCount() {
return (model == null) ? 0 : model.getColumnCount();
}
public String getColumnName(int aColumn) {
return model.getColumnName(aColumn);
}
public Class getColumnClass(int aColumn)
{
if (model.getColumnCount() == 0)
return model.getColumnClass(aColumn);
Object value = model.getValueAt(0,aColumn);
return value == null ? Object.class : value.getClass();
}
public boolean isCellEditable(int row, int column) {
return model.isCellEditable(row, column);
}
public void addColumn(Object col)
{
if ( model instanceof DefaultTableModel )
( (DefaultTableModel)model).addColumn( col );
else
throw new RuntimeException("ERROR: Subclass of DefaultTableModel required.");
}
public void addRow(Object rowData[])
{
( (DefaultTableModel)model).addRow( rowData );
}
public void removeRow(int rowIndex)
{
( (DefaultTableModel)model).removeRow( rowIndex );
}
//
// Implementation of the TableModelListener interface,
//
// By default forward all events to all the listeners.
public void tableChanged(TableModelEvent e) {
fireTableChanged(e);
}
public void insertRow(int row, Object rowData[])
{
( (DefaultTableModel)model).insertRow(row, rowData);
}
}
//$History:$

View File

@ -0,0 +1,195 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : TablePopupMenu
// Desc :
// Author : George Zhao
// Hist : 06/17/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
package com.jetcell.MibWM;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class TablePopupMenu extends JPopupMenu implements ActionListener
{
static JMenuItem copyCellMenuItem;
static JMenuItem copyRowMenuItem;
static JMenuItem copyColumnMenuItem;
static JMenuItem copyTableMenuItem;
static boolean iconsLoaded = false;
static JTable invoker ;
static int x;
static int y;
protected static TablePopupMenu popupMenu = new TablePopupMenu();
/**
* You cannot instantiate this class. Use getPopupMenu() to get
* a shared instance!
*/
protected TablePopupMenu()
{
copyCellMenuItem = Util.makeMenuItem("Copy Cell",'C');
copyCellMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
copyCellMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
copyCellMenuItem.addActionListener(this);
add(copyCellMenuItem);
copyRowMenuItem = Util.makeMenuItem("Copy Row", 'R');
copyRowMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
copyRowMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
copyRowMenuItem.addActionListener(this);
add(copyRowMenuItem);
copyColumnMenuItem = Util.makeMenuItem("Copy Column", 'L');
copyColumnMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
copyColumnMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
copyColumnMenuItem.addActionListener(this);
add(copyColumnMenuItem);
copyTableMenuItem = Util.makeMenuItem("Copy Table", 'T');
copyTableMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
copyTableMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
copyTableMenuItem.addActionListener(this);
add(copyTableMenuItem);
}
/**
* returns shared instance of popupMenu
*/
public static TablePopupMenu getPopupMenu()
{
return popupMenu;
}
/**
* update to use difference icons later!
*/
void loadIcons()
{
if(Util.applet == null)
{
copyCellMenuItem.setIcon(new ImageIcon(ImageLoader.loadImage("copy.gif")));
copyRowMenuItem.setIcon(new ImageIcon(ImageLoader.loadImage("copy.gif")));
copyColumnMenuItem.setIcon(new ImageIcon(ImageLoader.loadImage("copy.gif")));
copyTableMenuItem.setIcon(new ImageIcon(ImageLoader.loadImage("copy.gif")));
}
}
/**
* update to use shared clipboard access later
*/
public void actionPerformed(ActionEvent e)
{
Object obj = e.getSource();
Point p = new Point(x,y);
int row = invoker.rowAtPoint(p);
int col = invoker.columnAtPoint(p);
String selection = null;
if (obj == copyCellMenuItem)
{
selection = invoker.getValueAt(row,col).toString();
}
else if (obj == copyRowMenuItem)
{
for(int i=0; i < invoker.getColumnCount(); i++)
{
Object cell = invoker.getValueAt(row,i);
if (cell != null)
selection += cell.toString() + " ";
}
}
else if (obj == copyColumnMenuItem)
{
for(int i=0; i < invoker.getRowCount(); i++)
{
Object cell = invoker.getValueAt(i,col);
if (cell != null)
selection += cell.toString() + " ";
}
}
else if (obj == copyTableMenuItem)
{
for(int i=0; i < invoker.getRowCount(); i++)
{
for(int j=0; j < invoker.getColumnCount(); j++)
{
Object cell = invoker.getValueAt(i,j);
if (cell != null)
selection += cell.toString() + " ";
}
selection += "\n";
}
}
TextClipboard.setText(selection);
}
/**
* force JTable only later
*/
public void show(Component c, int x, int y)
{
invoker = (JTable)c;
if (iconsLoaded == false)
{
loadIcons();
iconsLoaded = true;
}
Point p = new Point(x,y);
int row = invoker.rowAtPoint(p);
int col = invoker.columnAtPoint(p);
if ((row >= 0) && (col >= 0))
enableMenu();
else
{
disableMenu();
return;
}
this.x = x;
this.y = y;
super.show(c,x,y);
}
void disableMenu()
{
copyCellMenuItem.setEnabled(false);
copyRowMenuItem.setEnabled(false);
copyColumnMenuItem.setEnabled(false);
copyTableMenuItem.setEnabled(false);
}
void enableMenu()
{
copyCellMenuItem.setEnabled(true);
copyRowMenuItem.setEnabled(true);
copyColumnMenuItem.setEnabled(true);
copyTableMenuItem.setEnabled(true);
}
}
//$History:$

View File

@ -0,0 +1,360 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : TableSorter
// Desc :
// Author : George Zhao
// Hist : 06/17/1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
/**
* based on Sun TableSorter. -gz
* @version 1.5 12/17/97
* @author Philip Milne
*/
package com.jetcell.MibWM;
import java.util.*;
import javax.swing.table.TableModel;
import javax.swing.event.TableModelEvent;
// Imports for picking up mouse events from the JTable.
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.InputEvent;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class TableSorter extends TableMap
{
int indexes[];
Vector sortingColumns = new Vector();
boolean ascending = true;
int compares;
int sortByColumnInd = 1;
public TableSorter()
{
indexes = new int[0]; // For consistency.
}
public TableSorter(TableModel model)
{
setModel(model);
}
public void setModel(TableModel model) {
super.setModel(model);
reallocateIndexes();
}
public int compareRowsByColumn(int row1, int row2, int column)
{
Class type = model.getColumnClass(column);
TableModel data = model;
// Check for nulls
Object o1 = data.getValueAt(row1, column);
Object o2 = data.getValueAt(row2, column);
// If both values are null return 0
if (o1 == null && o2 == null) {
return 0;
}
else if (o1 == null) { // Define null less than everything.
return -1;
}
else if (o2 == null) {
return 1;
}
/* We copy all returned values from the getValue call in case
an optimised model is reusing one object to return many values.
The Number subclasses in the JDK are immutable and so will not be used in
this way but other subclasses of Number might want to do this to save
space and avoid unnecessary heap allocation.
*/
if (type.getSuperclass() == java.lang.Number.class)
{
Number n1 = (Number)data.getValueAt(row1, column);
double d1 = n1.doubleValue();
Number n2 = (Number)data.getValueAt(row2, column);
double d2 = n2.doubleValue();
if (d1 < d2)
return -1;
else if (d1 > d2)
return 1;
else
return 0;
}
else if (type == java.util.Date.class)
{
Date d1 = (Date)data.getValueAt(row1, column);
long n1 = d1.getTime();
Date d2 = (Date)data.getValueAt(row2, column);
long n2 = d2.getTime();
if (n1 < n2)
return -1;
else if (n1 > n2)
return 1;
else return 0;
}
else if (type == String.class)
{
String s1 = (String)data.getValueAt(row1, column);
String s2 = (String)data.getValueAt(row2, column);
int result = s1.compareTo(s2);
if (result < 0)
return -1;
else if (result > 0)
return 1;
else return 0;
}
else if (type == Boolean.class)
{
Boolean bool1 = (Boolean)data.getValueAt(row1, column);
boolean b1 = bool1.booleanValue();
Boolean bool2 = (Boolean)data.getValueAt(row2, column);
boolean b2 = bool2.booleanValue();
if (b1 == b2)
return 0;
else if (b1) // Define false < true
return 1;
else
return -1;
}
else
{
Object v1 = data.getValueAt(row1, column);
String s1 = v1.toString();
Object v2 = data.getValueAt(row2, column);
String s2 = v2.toString();
int result = s1.compareTo(s2);
if (result < 0)
return -1;
else if (result > 0)
return 1;
else return 0;
}
}
public int compare(int row1, int row2)
{
compares++;
for(int level = 0; level < sortingColumns.size(); level++)
{
Integer column = (Integer)sortingColumns.elementAt(level);
int result = compareRowsByColumn(row1, row2, column.intValue());
if (result != 0)
return ascending ? result : -result;
}
return 0;
}
public void reallocateIndexes()
{
int rowCount = model.getRowCount();
// Set up a new array of indexes with the right number of elements
// for the new data model.
indexes = new int[rowCount];
// Initialise with the identity mapping.
for(int row = 0; row < rowCount; row++)
indexes[row] = row;
}
public void tableChanged(TableModelEvent e)
{
reallocateIndexes();
super.tableChanged(e);
sortByColumnInd();
}
public void checkModel()
{
if ( indexes.length == 0 )
reallocateIndexes();
if (indexes.length != model.getRowCount()) {
System.out.println("Sorter not informed of a change in model.");
}
}
public void sort(Object sender)
{
checkModel();
compares = 0;
// n2sort();
// qsort(0, indexes.length-1);
shuttlesort((int[])indexes.clone(), indexes, 0, indexes.length);
}
public void n2sort() {
for(int i = 0; i < getRowCount(); i++) {
for(int j = i+1; j < getRowCount(); j++) {
if (compare(indexes[i], indexes[j]) == -1) {
swap(i, j);
}
}
}
}
// This is a home-grown implementation which we have not had time
// to research - it may perform poorly in some circumstances. It
// requires twice the space of an in-place algorithm and makes
// NlogN assigments shuttling the values between the two
// arrays. The number of compares appears to vary between N-1 and
// NlogN depending on the initial order but the main reason for
// using it here is that, unlike qsort, it is stable.
public void shuttlesort(int from[], int to[], int low, int high) {
if (high - low < 2) {
return;
}
int middle = (low + high)/2;
shuttlesort(to, from, low, middle);
shuttlesort(to, from, middle, high);
int p = low;
int q = middle;
/* This is an optional short-cut; at each recursive call,
check to see if the elements in this subset are already
ordered. If so, no further comparisons are needed; the
sub-array can just be copied. The array must be copied rather
than assigned otherwise sister calls in the recursion might
get out of sinc. When the number of elements is three they
are partitioned so that the first set, [low, mid), has one
element and and the second, [mid, high), has two. We skip the
optimisation when the number of elements is three or less as
the first compare in the normal merge will produce the same
sequence of steps. This optimisation seems to be worthwhile
for partially ordered lists but some analysis is needed to
find out how the performance drops to Nlog(N) as the initial
order diminishes - it may drop very quickly. */
if (high - low >= 4 && compare(from[middle-1], from[middle]) <= 0) {
for (int i = low; i < high; i++) {
to[i] = from[i];
}
return;
}
// A normal merge.
for(int i = low; i < high; i++) {
if (q >= high || (p < middle && compare(from[p], from[q]) <= 0)) {
to[i] = from[p++];
}
else {
to[i] = from[q++];
}
}
}
public void swap(int i, int j) {
int tmp = indexes[i];
indexes[i] = indexes[j];
indexes[j] = tmp;
}
public boolean getAscending()
{
return ascending;
}
// The mapping only affects the contents of the data rows.
// Pass all requests to these rows through the mapping array: "indexes".
public Object getValueAt(int aRow, int aColumn)
{
checkModel();
if (aRow >= 0 && aRow <model.getRowCount())
return model.getValueAt(indexes[aRow], aColumn);
return null;
}
public void setValueAt(Object aValue, int aRow, int aColumn)
{
checkModel();
model.setValueAt(aValue, indexes[aRow], aColumn);
}
public void sortByColumn(int column) {
sortByColumn(column, true);
}
public void sortByColumn(int column, boolean ascending) {
this.ascending = ascending;
sortingColumns.removeAllElements();
sortingColumns.addElement(new Integer(column));
sort(this);
super.tableChanged(new TableModelEvent(this));
}
// There is no-where else to put this.
// Add a mouse listener to the Table to trigger a table sort
// when a column heading is clicked in the JTable.
public void addMouseListenerToHeaderInTable(JTable table) {
final TableSorter sorter = this;
final JTable tableView = table;
tableView.setColumnSelectionAllowed(false);
MouseAdapter listMouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
sortByColumnInd = tableView.convertColumnIndexToModel(viewColumn);
if(e.getClickCount() == 1 && sortByColumnInd != -1) {
int shiftPressed = e.getModifiers()&InputEvent.SHIFT_MASK;
//boolean ascending = (shiftPressed == 0);
boolean ascending = getAscending();
sorter.sortByColumn(sortByColumnInd, ascending);
}
}
};
JTableHeader th = tableView.getTableHeader();
th.addMouseListener(listMouseListener);
}
public void sortByColumnInd(){
sortByColumn(sortByColumnInd);
}
public void filteredRemoveRow(int row){
checkModel();
super.removeRow(indexes[row]);
}
public int getIndexAtRow(int row){
return indexes[row];
}
}
// $Log: TableSorter.java,v $
// Revision 1.2 1999-12-21 13:35:06-08 klim
// Fixes sorting reset problem
//
// Revision 1.1 1999-11-28 22:51:20-08 bsapkota
// Initial revision
//
//
// Rev 1.6 Jun 23 1998 12:13:00 GZHAO
//add boundary check.
//
// Rev 1.5 Jun 02 1998 14:11:22 GZHAO
//toggle the ascending for table sort.
//
// Rev 1.4 Jun 02 1998 12:52:10 GZHAO
//modify System.out to Debug.out.

View File

@ -0,0 +1,80 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : TextClipboard
// Desc : Clipboard abstraction for working in both applet and application
// Author : George Zhao
// Created: 6/8/98
//
//////////////////////////////////////////////////////////////////////////////
package com.jetcell.MibWM;
import java.io.*;
import java.awt.*;
import java.awt.datatransfer.*;
public abstract class TextClipboard
{
private static String clipboard;
private static ClipboardOwner defaultClipboardOwner = new ClipboardObserver();
static class ClipboardObserver implements ClipboardOwner
{
public void lostOwnership(Clipboard clipboard, Transferable contents)
{
}
}
/**
* Set the value of the clipboard
* @param s string value
*/
public static synchronized void setText(String s)
{
if (s == null)
s = "";
if (Util.applet != null)
clipboard = s;
else
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(s), defaultClipboardOwner);
}
/**
* Get the string contents of the clipboard
*/
public static synchronized String getText()
{
if (Util.applet != null)
return clipboard;
else
{
String s = null;
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(defaultClipboardOwner);
if (t == null)
return "";
else
try
{
s = (String)(t.getTransferData(DataFlavor.stringFlavor));
}
catch (UnsupportedFlavorException e)
{
System.out.println(e);
}
catch (IOException e)
{
System.out.println(e);
}
finally
{
return s;
}
}
}
}
//$History:$

View File

@ -0,0 +1,280 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : TextComponentPopupMenu
// Desc : Specialized popup menu for subclasses of JTextComponent
// Author : George Zhao
//
//////////////////////////////////////////////////////////////////////////////
package com.jetcell.MibWM;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
/**
* Custom popup menu for subclasses of JTextComponent. Includes cut,copy,paste,
* paste recent, and delete.
*
* @see VDDSTextField
* @version 1.0
* @author Semir Patel
*/
public class TextComponentPopupMenu extends JPopupMenu implements ActionListener
{
/**
* Maximum number of elements in Paste Recent submenu
*/
static final int RECENT_LIST_SIZE = 4;
/**
* Popup menu items
*/
static JMenuItem cutMenuItem;
static JMenuItem copyMenuItem;
static JMenuItem pasteMenuItem;
static JMenu pasteRecentMenu;
static JMenuItem deleteMenuItem;
static JMenuItem descriptionMenuItem;
static boolean iconsLoaded = false;
/**
* JTextComponent that invokes this popup menu
*/
static JTextComponent invoker;
/**
* Starting and ending selection indices for the text component
*/
static int start;
static int end;
/**
* shared instance of popup menu
*/
protected static TextComponentPopupMenu popupMenu = new TextComponentPopupMenu();
private TextComponentPopupMenu()
{
cutMenuItem = Util.makeMenuItem("Cut",'t');
cutMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
cutMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
cutMenuItem.addActionListener(this);
add(cutMenuItem);
copyMenuItem = Util.makeMenuItem("Copy",'C');
copyMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
copyMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
copyMenuItem.addActionListener(this);
add(copyMenuItem);
pasteMenuItem = Util.makeMenuItem("Paste",'P');
pasteMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
pasteMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
pasteMenuItem.addActionListener(this);
add(pasteMenuItem);
pasteRecentMenu = new JMenu("Paste Recent");
pasteRecentMenu.setHorizontalTextPosition(SwingConstants.RIGHT);
pasteRecentMenu.setHorizontalAlignment(SwingConstants.LEFT);
pasteRecentMenu.registerKeyboardAction(null, KeyStroke.getKeyStroke('R',java.awt.Event.ALT_MASK,false),
JComponent.WHEN_IN_FOCUSED_WINDOW);
add(pasteRecentMenu);
deleteMenuItem = Util.makeMenuItem("Delete",'D');
deleteMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
deleteMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
deleteMenuItem.addActionListener(this);
add(deleteMenuItem);
addSeparator();
descriptionMenuItem = Util.makeMenuItem("Description", 'P');
descriptionMenuItem.setHorizontalTextPosition(SwingConstants.RIGHT);
descriptionMenuItem.setHorizontalAlignment(SwingConstants.LEFT);
descriptionMenuItem.addActionListener(this);
add(descriptionMenuItem);
}
/**
* accessor for shared instance of popup menu
*/
public static TextComponentPopupMenu getPopupMenu()
{
return popupMenu;
}
void loadIcons()
{
cutMenuItem.setIcon(new ImageIcon(ImageLoader.loadImage("cut.gif")));
copyMenuItem.setIcon(new ImageIcon(ImageLoader.loadImage("copy.gif")));
pasteMenuItem.setIcon(new ImageIcon(ImageLoader.loadImage("paste.gif")));
pasteRecentMenu.setIcon(new ImageIcon(ImageLoader.loadImage("pasterecent.gif")));
deleteMenuItem.setIcon(new ImageIcon(ImageLoader.loadImage("delete.gif")));
}
/**
* Action listener for menu items
*/
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == cutMenuItem)
{
invoker.select(start,end);
TextClipboard.setText(invoker.getSelectedText());
invoker.replaceSelection("");
}
else if (e.getSource() == copyMenuItem)
{
invoker.select(start,end);
TextClipboard.setText(invoker.getSelectedText());
}
else if (e.getSource() == pasteMenuItem)
{
invoker.replaceSelection(TextClipboard.getText());
}
else if (e.getSource() == deleteMenuItem)
{
invoker.select(start,end);
invoker.replaceSelection("");
}
else if (e.getSource() == descriptionMenuItem)
{
/*
JOptionPane.showMessageDialog(Util.browser,
"Description of this field, range, detail meaning etc goes here.",
"Description", JOptionPane.INFORMATION_MESSAGE);
*/
}
else if (e.getSource() instanceof JMenuItem)
{
invoker.select(start,end);
invoker.replaceSelection(((JMenuItem)e.getSource()).getText());
}
}
/**
* Shows popup menu at specified coords with text component selection info
* @param c Invoker
* @param x Absolute x location
* @param y Absolute y location
* @param start Start index of selection
* @param end End index of selection
*/
public void show(Component c, int x, int y, int start, int end)
{
this.start = start;
this.end = end;
show(c,x,y);
}
public void show(Component c, int x, int y)
{
if (iconsLoaded == false)
{
loadIcons();
iconsLoaded = true;
}
if (c instanceof JTextComponent)
{
invoker = (JTextComponent)c;
int len = invoker.getText().length();
if (!invoker.isEditable())
{
cutMenuItem.setEnabled(false);
pasteMenuItem.setEnabled(false);
pasteRecentMenu.setEnabled(false);
deleteMenuItem.setEnabled(false);
if (len > 0)
copyMenuItem.setEnabled(true);
else
copyMenuItem.setEnabled(false);
}
else
{
if ((len > 0) && (start != end))
{
cutMenuItem.setEnabled(true);
copyMenuItem.setEnabled(true);
deleteMenuItem.setEnabled(true);
}
else
{
cutMenuItem.setEnabled(false);
copyMenuItem.setEnabled(false);
deleteMenuItem.setEnabled(false);
}
pasteMenuItem.setEnabled(true);
if (pasteRecentMenu.getMenuComponentCount() > 0)
pasteRecentMenu.setEnabled(true);
else
pasteRecentMenu.setEnabled(false);
}
super.show(invoker,x,y);
}
}
/**
* Adds entry to Paste Recent menu. List works like FIFO queue.
* @param s String to add to the paste recent menu
*/
void addToMostRecentList(String s)
{
int cnt = pasteRecentMenu.getItemCount();
for (int i=0; i<cnt; i++)
if (pasteRecentMenu.getItem(i).getText().equals(s))
return;
if (cnt < RECENT_LIST_SIZE)
{
JMenuItem menuItem = Util.makeMenuItem();
pasteRecentMenu.add(menuItem);
menuItem.addActionListener(this);
cnt = pasteRecentMenu.getMenuComponentCount();
if (cnt == 1)
pasteRecentMenu.getItem(0).setText(s);
else
{
for (int i=cnt-1; i>=1; i--)
pasteRecentMenu.getItem(i).setText(pasteRecentMenu.getItem(i-1).getText());
pasteRecentMenu.getItem(0).setText(s);
}
}
else
{
for (int i=cnt-1; i>=1; i--)
pasteRecentMenu.getItem(i).setText(pasteRecentMenu.getItem(i-1).getText());
pasteRecentMenu.getItem(0).setText(s);
}
}
public void setVisible(boolean b)
{
/**
* Workaround for swing 0.7 bug.
* Get rid of visible submenu if showing
*/
if (b == false)
pasteRecentMenu.setPopupMenuVisible(false);
super.setVisible(b);
}
}
//$History:$

View File

@ -0,0 +1,779 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : Util
// Desc : Utility class for MIB Web Management
// Author : George Zhao
// History: April 22, 1999
//
//////////////////////////////////////////////////////////////////////////////
package com.jetcell.MibWM;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.applet.*;
import java.util.*;
public abstract class Util
{
public static TitledBorder titleBorder;
static JPanel p;
public static Applet applet = null;
//undo
public static boolean debug = false;
public static final int BORDER_INSET = 5;
public static final Border EMPTY_BORDER_STYLE = new EmptyBorder(BORDER_INSET, BORDER_INSET, BORDER_INSET, BORDER_INSET);
public static final Border BORDER_STYLE = new CompoundBorder(new EmptyBorder(BORDER_INSET, BORDER_INSET, BORDER_INSET, BORDER_INSET),
new CompoundBorder(new EtchedBorder(Color.gray, Color.white),
new EmptyBorder(BORDER_INSET, BORDER_INSET, BORDER_INSET, BORDER_INSET)));
static final int BUTTON_TOP = 1;
static final int BUTTON_BOTTOM = 1;
static final int BUTTON_LEFT = 1;
static final int BUTTON_RIGHT = 1;
/**
* The default number of characters for text field.
*/
public static int TEXTFIELD_NUM_CHARS = 12;
/**
* The default number of characters for text field.
*/
public static int DATEFIELD_NUM_CHARS = 10;
/**
* The default number of characters for text field.
*/
public static int TIMEFIELD_NUM_CHARS = 12;
/**
* Creates a popup menu with items in an array of string.
* No action listener is to be added for this method.
* @param items an array of String for the menu items
*/
public static PopupMenu makePopupMenu(String[] items)
{
PopupMenu popup = new PopupMenu();
for (int i=0; i < items.length; i++) {
popup.add(new MenuItem(items[i]));
}
MenuItem mItem = new MenuItem("Copy");
popup.add(mItem);
return popup;
}
/**
* Creates a menu with a name of your choice, items in an array of strings, acttionCommands being
* items with spaces trimmed, and an action listener for all items.
* @param menuName the name of the menu
* @param items an array of String for the items
* @param listener action listener
*/
public static JMenu makeMenu(String menuName, char hotkey, String[] items, ActionListener listener)
{
JMenu menu = makeMenu(menuName, hotkey);
JMenu submenu = null;
JMenuItem menuItem = null;
String itemString;
String queryName;
String submenuItems;
int comma;
for (int i=0; i < items.length; i++) {
//parse the items string
int index;
if ( (index = items[i].indexOf(":")) >= 0 ) {
//has submenu
queryName = items[i].substring(0,index).trim();
submenu = makeMenu( queryName );
submenuItems = items[i].substring(index+1).trim();
while ( submenuItems.length() > 0 ) {
comma = submenuItems.indexOf(",");
if ( comma >= 0 ) {
itemString = submenuItems.substring(0, comma).trim();
submenuItems = submenuItems.substring(comma+1).trim();
} else {
itemString = submenuItems;
submenuItems = "";
}
menuItem = makeMenuItem(itemString);
menuItem.setActionCommand( trimSpaces(queryName + ":" + itemString) );
if ( listener != null ) {
menuItem.addActionListener( listener );
}
submenu.add(menuItem);
}
menu.add( submenu );
} else { //no submenu
menuItem = makeMenuItem(items[i]);
menuItem.setActionCommand( trimSpaces(items[i]) );
if ( listener != null ) {
menuItem.addActionListener( listener );
}
menu.add( menuItem );
}
}
return menu;
}
/**
* Creates a menu with a name of your choice, items and action commands in an array of strings,
* and an action listener for all items.
* @param menuName the name of the menu
* @param items an array of String for the items
* @param commands action commands in an array of strings
* @param listener action listener
*/
public static JMenu makeMenu(String menuName, char hotkey, String[] items, String[] commands, ActionListener listener)
{
JMenu menu = makeMenu(menuName, hotkey);
int index;
for (int i=0; i < items.length; i++) {
if ( (index = items[i].indexOf("_") ) >= 0 ) {
JMenu subMenu = makeMenu(items[i].substring(0, index));
JMenuItem item = makeMenuItem(items[i].substring(index+1) );
if ( listener != null ) {
item.addActionListener( listener );
}
subMenu.add(item);
menu.add(subMenu);
} else {
JMenuItem menuItem = makeMenuItem(items[i]);
menuItem.setActionCommand( commands[i] );
if ( listener != null )
menuItem.addActionListener( listener );
menu.add( menuItem );
}
}
return menu;
}
public static JMenu makeMenu(String name)
{
JMenu menu = new JMenu(name);
return menu;
}
public static JMenu makeMenu (String name, char mnemonic)
{
JMenu menu = new JMenu(name);
menu.setMnemonic(mnemonic);
return menu;
}
/**
* Creates a Swing label with preferred size and Style Guide conforming attributes
* @param text the text of Label
*/
public static JLabel makeLabel(String text)
{
JLabel label = new JLabel(text,JLabel.RIGHT);
//label.setSize(label.getPreferredSize());
label.setVerticalAlignment(SwingConstants.CENTER);
return label;
}
/**
* Creates a label with alignment
* @param text the text of Label
* @alignment alignment horizontal alignment - JLabel.{LEFT,RIGHT,CENTER}
*/
public static JLabel makeLabel(String text, int alignment)
{
JLabel label = makeLabel(text);
label.setHorizontalAlignment(alignment);
return label;
}
public static JLabel makeLabel(String text, char hotkey)
{
JLabel label = makeLabel(text);
label.setDisplayedMnemonic(hotkey);
return label;
}
public static JLabel makeLabel(String text, char hotkey, int alignment)
{
JLabel label = makeLabel(text, alignment);
label.setDisplayedMnemonic(hotkey);
return label;
}
public static JLabel makeLabel(String text, char hotkey, Component target)
{
JLabel label = makeLabel(text, hotkey);
label.setLabelFor(target);
return label;
}
public static JLabel makeLabel(String text, char hotkey, Component target, int alignment)
{
JLabel label = makeLabel(text, hotkey, target);
label.setHorizontalAlignment(alignment);
return label;
}
public static JTextField makeTextField()
{
return makeTextField(TEXTFIELD_NUM_CHARS);
}
/**
* Creates an non-editable Swing text field for holding numChars characters
* @param numChars holding numChars characters in width
*/
public static JTextField makeTextField(int numChars)
{
return makeTextField("", numChars, false);
}
/**
* Creates a non-editable Swing text field with content text and default width
* @param text the text of field
*/
public static JTextField makeTextField(String text)
{
return makeTextField(text, TEXTFIELD_NUM_CHARS, false);
}
/**
* Creates a Swing text field with intial content text, numChars in width, editable as set
* @param text the text of field
* @param numChars holding numChars characters for width
* @param editable to set editable or not
*/
public static JTextField makeTextField(String text, int numChars, boolean editable)
{
WMTextField textField = new WMTextField( text, numChars );
textField.setEditable(editable);
return textField;
}
/**
* Creates a Swing text field with intial content text, numChars in width, editable as set
* @param dateDocument the date formating document
* @param text the text of field
* @param numChars holding numChars characters for width
* @param editable to set editable or not
*/
/*
public static JTextField makeTextField( Document dateDocument, String text, int numChars, boolean editable)
{
JTextField textField = new WMTextField( dateDocument, text, numChars);
textField.setEditable(editable);
return textField;
}
*/
/**
* Creates a Swing non-editable text field with intial content text, numChars in width
* @param text the text of field
* @param numChars holding numChars characters for width
*/
public static JTextField makeTextField(String text, int numChars)
{
return makeTextField(text, numChars, false);
}
/**
* Creates a Swing text field with editability settable
* @param editable to set editable or not
*/
public static JTextField makeTextField(boolean editable)
{
return makeTextField("", TEXTFIELD_NUM_CHARS, editable);
}
public static JTextField makeTextField(boolean editable, String markup)
{
WMTextField field= (WMTextField) makeTextField("", TEXTFIELD_NUM_CHARS, editable);
field.setMagicMarkup(markup);
return field;
}
/**
* Creates a Swing text field with editability settable and with numChars in width
* @param numChars holding numChars characters for width
* @param editable to set editable or not
*/
public static JTextField makeTextField(int numChars, boolean editable)
{
return makeTextField("", numChars, editable);
}
/**
* Creates a Swing button
* @param text the text on the button
*/
public static JButton makeButton(String text)
{
JButton button = new JButton(text);
button.setMargin(new Insets(BUTTON_TOP,BUTTON_BOTTOM,BUTTON_LEFT,BUTTON_RIGHT));
return button;
}
/**
* Creates a Swing button with shortcut
* @param text the text on the button
* @param hotkey mnemonic character (underlined)
*/
public static JButton makeButton(String text, char hotkey)
{
JButton button = makeButton(text);
button.registerKeyboardAction(null, KeyStroke.getKeyStroke(hotkey,java.awt.Event.ALT_MASK,false),
JComponent.WHEN_IN_FOCUSED_WINDOW);
button.setMnemonic(hotkey);
return button;
}
/**
* Creates a Swing button with shortcut and tooltip
* @param text the text on the button
* @param hotkey mnemonic character (underlined)
* @param tooltip text for the button's tooltip
*/
public static JButton makeButton(String text, char hotkey, String tooltip)
{
JButton button = makeButton(text);
button.setMnemonic(hotkey);
button.setToolTipText(tooltip);
return button;
}
/**
* Creates a Swing button with shortcut, tooltip, and listener
* @param text the text on the button
* @param hotkey mnemonic character (underlined)
* @param tooltip text for the button's tooltip
* @param listener actionlistener
*/
public static JButton makeButton(String text, char hotkey, String tooltip, ActionListener listener)
{
JButton button = makeButton(text, hotkey, tooltip);
button.addActionListener(listener);
return button;
}
/**
* Create a JButton with Icon
* @param text the text on the button
* @param icon the image on the button
*/
public static JButton makeButton(String text, ImageIcon icon)
{
JButton button = new JButton(text, icon);
button.setMargin(new Insets(BUTTON_TOP,BUTTON_BOTTOM,BUTTON_LEFT,BUTTON_RIGHT));
return button;
}
/**
* create JButton with icon and hot key
*/
public static JButton makeButton(String text, ImageIcon icon, char hotkey)
{
JButton button = makeButton(text, icon);
button.setMnemonic(hotkey);
return button;
}
/**
* create JButton with icon, hotkey and tooltip
* @param text
* @param icon
* @param hotkey
* @param tooltip
*/
public static JButton makeButton(String text, ImageIcon icon, char hotkey, String tooltip)
{
JButton button = makeButton(text, icon, hotkey);
button.setToolTipText(tooltip);
return button;
}
/**
* create JButton with icon, hotkey and tooltip, and listener
* @param text
* @param icon
* @param hotkey
* @param tooltip
* @param listener
*/
public static JButton makeButton(String text, ImageIcon icon, char hotkey, String tooltip, ActionListener listener)
{
JButton button = makeButton(text, icon, hotkey, tooltip);
button.addActionListener(listener);
return button;
}
/**
* create JButton with icon and tooltip
*/
public static JButton makeButton(ImageIcon icon, String tooltip)
{
JButton button = new JButton(icon);
button.setMargin(new Insets(BUTTON_TOP,BUTTON_BOTTOM,BUTTON_LEFT,BUTTON_RIGHT));
button.setToolTipText(tooltip);
return button;
}
/**
* Creates a Swing panel
*/
public static JPanel makePanel()
{
JPanel p = new JPanel();
return p;
}
/**
* Creates a panel with layout
*/
public static JPanel makePanel(LayoutManager layout)
{
JPanel p = makePanel();
p.setLayout(layout);
return p;
}
/**
* Creates a Swing bordered panel
* @param title the title of the border
*/
public static JPanel makeBorderPanel(String title)
{
p = makePanel();
p.setBorder(BORDER_STYLE);
titleBorder = new TitledBorder(p.getBorder(), title);
p.setBorder(titleBorder);
return p;
}
public static void setBorderTitle(String title){
System.out.println("setting title" + title);
titleBorder.setTitle(title);
p.validate();
}
public static String getBorderTitle(){
return titleBorder.getTitle();
}
/**
* Creates a Swing bordered panel with layout
* @param title the title of the border
* @param layout layout
*/
public static JPanel makeBorderPanel(String title, LayoutManager layout)
{
JPanel p = makeBorderPanel(title);
p.setLayout(layout);
return p;
}
/**
* Creates a Swing bordered panel with no title
*/
public static JPanel makeBorderPanel()
{
return makeBorderPanel("");
}
/**
* Creates a Swing bordered panel with NO border
* Why this ? to add the space of border to line up with other bordered panels
*/
public static JPanel makeEmptyBorderPanel()
{
JPanel p = makePanel();
p.setBorder(EMPTY_BORDER_STYLE);
return p;
}
/**
* Creates a Swing bordered panel with NO border
* Is this different from makeEmptyBorderPanel ?
* To be answered....
*/
public static JPanel makeHugeEmptyBorderPanel()
{
JPanel p = makePanel();
p.setBorder(new CompoundBorder(EMPTY_BORDER_STYLE,
EMPTY_BORDER_STYLE));
return p;
}
/**
* Remove all space characters in a given string.
* @param s the string to be trimmed
*/
public static String trimSpaces(String s)
{
String r="";
if ( s == null )
return null;
for (int i=0; i < s.length(); i++)
if ( s.charAt(i) != ' ' )
r = r + s.charAt(i);
return r;
}
/**
* Makes a JRadioButton showing text with key as the accelerator
* @param text the text of the button
* @param key the accelerator key
*/
public static JRadioButton makeRadioButton(String text, char key)
{
JRadioButton rb = new JRadioButton(text);
rb.setMnemonic(key);
return rb;
}
/**
* Makes a JRadioButton showing text without key accelerator
* @param text the text of the button
*/
public static JRadioButton makeRadioButton(String text)
{
JRadioButton rb = new JRadioButton(text);
return rb;
}
public static JTextArea makeTextArea(int r, int c, boolean editable)
{
JTextArea area = new JTextArea(r,c);
area.setEditable(editable);
return area;
}
public static JTextArea makeTextArea()
{
return makeTextArea("");
}
/**
* Makes a text area with a populated string
* @param text populate area with string
*/
public static JTextArea makeTextArea(String s)
{
return new JTextArea(s);
}
public static JComboBox makeComboBox(boolean editable)
{
JComboBox cb = new JComboBox();
cb.setEditable( editable );
return cb;
}
/**
* Makes a JComboBox with an array of String for items with default size
* @param items an array of strings
* @param selectedItemIndex the index of the item to be selected by default
* @param editable editable or not
*/
public static JComboBox makeComboBox(String[] items, int selectedItemIndex,
boolean editable)
{
return makeComboBox(items, selectedItemIndex, editable, null);
}
/**
* Makes a JComboBox with an array of String for items
* @param items an array of strings
* @param selectedItemIndex the index of the item to be selected by default
* @param editable editable or not
* @param dimension the dimension of the box
*/
public static JComboBox makeComboBox(String[] items, int selectedItemIndex,
boolean editable, Dimension dimension)
{
JComboBox cb = new JComboBox();
for (int i=0; i < items.length; i++)
cb.addItem(items[i]);
cb.setEditable( editable );
cb.setSelectedItem( items[selectedItemIndex] );
if ( dimension != null )
cb.setPreferredSize( dimension );
return cb;
}
/**
* Makes an empty menu item.
*/
public static JMenuItem makeMenuItem()
{
return makeMenuItem("");
}
/**
* Makes a menu item with an icon.
* @param icon image icon
*/
public static JMenuItem makeMenuItem(Icon icon)
{
JMenuItem m = makeMenuItem();
m.setIcon(icon);
return m;
}
/**
* Makes a menu item with a label and icon.
* @param text menu label
* @param icon image icon
*/
public static JMenuItem makeMenuItem(String text,Icon icon)
{
JMenuItem m = makeMenuItem(text);
m.setIcon(icon);
return m;
}
/**
* Makes a menu item with a label and shortcut key.
* @param text menu label
* @param mnemonic underlined character in label
*/
public static JMenuItem makeMenuItem(String text, char mnemonic)
{
JMenuItem m = makeMenuItem(text);
m.setMnemonic(mnemonic);
m.registerKeyboardAction(null, KeyStroke.getKeyStroke(mnemonic,java.awt.Event.ALT_MASK,false),
JComponent.WHEN_IN_FOCUSED_WINDOW);
return m;
}
/**
* Makes a menu item with a label
* @param text menu label
*/
public static JMenuItem makeMenuItem(String text)
{
return new JMenuItem(text);
}
public static JMenuItem makeMenuItem(String text, Icon icon, char mnemonic)
{
JMenuItem m = new JMenuItem(icon);
m.setText(text);
m.setMnemonic(mnemonic);
return m;
}
/**
* Makes a text area that looks like a multiline
* wrapping label that word wraps
* @param initial value of textarea
*/
public static JTextArea makeWrappingLabel(String s)
{
JTextArea ta = new JTextArea(s);
ta.setLineWrap(true);
//ta.setWrapStyleWord(true);
ta.setOpaque(false);
ta.setEditable(false);
ta.setBorder(new EmptyBorder(0,0,0,0));
ta.setSelectionColor(UIManager.getDefaults().getColor("Label.background"));
ta.setFont(UIManager.getDefaults().getFont("Label.font"));
return ta;
}
static public void constrain(Component component, Container container, GridBagConstraints gbc,
int grid_x, int grid_y, int grid_width, int grid_height,
int fill, int anchor, double weight_x, double weight_y,
int top, int left, int bottom, int right)
{
gbc.gridx = grid_x;
gbc.gridy = grid_y;
gbc.gridwidth = grid_width;
gbc.gridheight = grid_height;
gbc.fill = fill;
gbc.anchor = anchor;
gbc.weightx = weight_x;
gbc.weighty = weight_y;
if (top+bottom+left+right > 0)
gbc.insets = new Insets(top, left, bottom, right);
((GridBagLayout)container.getLayout()).setConstraints(component, gbc);
container.add(component);
}
static public void showDialog(JFrame frame, String message, String title, int type)
{
JOptionPane.showMessageDialog(frame, message, title, type);
}
static public void showDialog(String message, String title)
{
showDialog(message, title, JOptionPane.INFORMATION_MESSAGE);
}
static public void showDialog(String message, String title, int type)
{
showDialog(new JFrame(), message, title, type);
}
static public void showDialog(String message)
{
showDialog(message, "");
}
static public void showDialog(Exception e)
{
showDialog(e.toString(), "Exception");
}
static public String average(Vector v)
{
int sum =0;
for(int i=0; i< v.size(); i++)
{
try {
sum += Integer.parseInt((String) v.elementAt(i));
}
catch(Exception e) {}
}
return String.valueOf(sum/v.size());
}
static public boolean IsDigit(String s)
{
for (int i=0; i< s.length(); i++)
{
if (!Character.isDigit(s.charAt(i)))
return false;
}
return true;
}
}
//$History:$

View File

@ -0,0 +1,156 @@
//////////////////////////////////////////////////////////////////////////////
//
// Class : WMTextField
// Desc : TextField widget for Web Management Browser
// Author : George Zhao
// History: April 22, 1999 Initial Creation.
//
//////////////////////////////////////////////////////////////////////////////
package com.jetcell.MibWM;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* Subclass of JTextfield that add a right mouse button triggered
* popupmenu for cut/copy/paste/delete functionality.
*
* @see TextComponentPopupMenu
* @version 1.0
* @author George Zhao
*/
public class WMTextField extends JTextField implements FocusListener
{
static TextComponentPopupMenu popupMenu = TextComponentPopupMenu.getPopupMenu();
/**
* Previous value is tracked to make sure duplicates don't make it into
* the paste recent menu.
*/
String previousValue="";
String magicMarkup = "";
public WMTextField()
{
super();
init();
}
public WMTextField(String text)
{
super(text);
init();
}
public WMTextField(int columns)
{
super(columns);
init();
}
public WMTextField(String text, int columns)
{
super(text,columns);
init();
}
/**
* Adds focusListener to textfield
*/
void init()
{
addFocusListener(this);
//{{INIT_CONTROLS
//}}
}
public void focusGained(FocusEvent e) {};
/**
* Listens for focusLost event to trigger updates to
* the paste recent popup menu
* @param e FocusEvent
*/
public void focusLost(FocusEvent e)
{
String value = getTrimmedText();
if ((value.length() > 0) && (!value.equals(previousValue)))
{
previousValue = value;
popupMenu.addToMostRecentList(value);
}
}
/**
* Captures right mouse button mouse events to invoke popup menu.
* @param e MouseEvent
*/
public void processMouseEvent(MouseEvent e)
{
if (e.getModifiers() == InputEvent.BUTTON3_MASK)
{
if (e.isPopupTrigger())
{
popupMenu.show(e.getComponent(),
e.getX(),
e.getY(),
getSelectionStart(),
getSelectionEnd());
}
}
else
super.processMouseEvent(e);
}
/**
* Returns text without with leading and trailing spaces
*/
public String getTrimmedText()
{
return getText().trim();
}
/**
* Sets the text. Keeps track of previous value.
*/
public void setText(String s)
{
super.setText(s);
previousValue = s;
repaint();
}
/**
* Swing bug - force repaint on setEditable() to refresh color
*/
public void setEditable(boolean b)
{
super.setEditable(b);
if(b) {
//setBackground(UIManager.getDefaults().getColor("TextField.background"));
setBackground(Color.white);
}
else {
//setBackground(UIManager.getDefaults().getColor("Label.background"));
setBackground(Color.lightGray);
}
repaint();
}
public void setMagicMarkup(String markup)
{
magicMarkup = markup;
}
public String getMagicMarkup()
{
return magicMarkup;
}
}
//$History:$

View File

@ -0,0 +1,60 @@
####################################################################
#
# FILE NAME: Java.mk
#
# DESCRIPTION: This file needs to be included by every makefile that
# compiles Java source files.
#
# COMPONENTS:
#
#
# NOTES:
#
# (C) Copyright 1999 JetCell Inc., CA, USA http://www.jetcell.com/
#
# REVISION HISTORY
#__________________________________________________________________
#----------+--------+----------------------------------------------
# Name | Date | Reason
#----------+--------+----------------------------------------------
# Bhawani |11/28/99| Iniitial Draft
#----------+--------+----------------------------------------------
####################################################################
#/
# Hard-coded path should point to the network drive
RLROOT = ..\..\..\THIRD_PARTY\OamTools
RLROOT2 = ..\..\THIRD_PARTY\OamTools
RLIROOT = $(RLROOT)\rl
RLIROOT2 = $(RLROOT2)\rl
JDKROOT = $(CODEBASE)\..\..\THIRD_PARTY\OamTools\jdk1.3
RM = del
CP = copy
MIBWMPATH = $(CODEBASE)\com\jetcell\MibWM
VIPERCELL = $(MIBWMPATH)
VIPERBASE = $(MIBWMPATH)\ViperBase
COMMON = $(CODEBASE)\Java
OUTPUTDIR = $(CODEBASE)\..\..\GMC\GMCManager
ALARMAPPLETDIR = $(CODEBASE)\AlarmApplet
ifeq ($(SOURCE_LIST),)
SOURCE_LIST = $(wildcard *.java)
endif
CLASS_LIST = $(SOURCE_LIST:.java=.class)
# java compiler and archive maker
JAR = $(JDKROOT)\bin\jar.exe
JAVAC = $(JDKROOT)\bin\javac.exe
CLASSPATH = .;$(ALARMAPPLETDIR);$(CODEBASE);$(JDKROOT)/lib;$(JDKROOT)/lib/classes.zip;$(RLROOT);/$(RLIROOT)/jcit/symbeans.jar;$(RLIROOT)/jcit/Jars/Gauges.jar;$(RLIROOT)/jcit/Jars/RLBeans.jar
# rule to compile Java source files
%.class : %.java
# - @ $(RM) $(subst /,$(DIRCHAR),$@)
$(JAVAC) -classpath $(CLASSPATH) $(subst /,\, $<)

View File

@ -0,0 +1,28 @@
##########################################################
#
# (c) Copyright Cisco 2000
# All Rights Reserved
#
# Use Examples:
#
# Case 1: make all VOB=GP10 -
# Places .out in VOB/bin directory
#
# Case 2: make all VOB=GP10 APPDIR=Host\vxTemplate\bin -
# Places .o file(s) in VOB/$(APPDIR) directory.
#
# Note: This make file must reference a VOB that
# has a defs.mk in the top level directory.
#
##########################################################
SUBDIRS = src loadmodule
# TOP_OF_VOB must be defined before including l3defs.mk
TOP_OF_VOB = ..\..
VOBDIR = $(TOP_OF_VOB)\$(VOB)
include $(VOBDIR)\l3defs.mk

View File

@ -0,0 +1,40 @@
// *******************************************************************
//
// (c) Copyright Cisco 2000
// All Rights Reserved
//
// *******************************************************************
// *******************************************************************
//
// Version : 1.0
// Status : Under development
// File : JCMsgQDefs.h
// Author(s) : Tim Olson
// Create Date : 9/18/2000
// Description :
//
// *******************************************************************
#ifndef _JCMSGQDEFS_H_
#define _JCMSGQDEFS_H_ /* include once only */
#include "Os/JCMsgQueue.h"
#include "MnetModuleId.h"
/* THIS IS FOR MESSAGE QUEUE INTERNAL ONLY!!!! */
typedef struct jc_msg_hdr {
JCMsgQueue *rplyQ; /* identifier of queue to which to reply,
if any */
unsigned int msgType; /* module dependent message type */
MNET_MODULE_ID modId; /* module ID of sender */
int bytes; /* size of associated data */
} JC_MSG_HDR;
/* data follows header */
#define JC_MSG_HDR_SIZE sizeof(JC_MSG_HDR)
#endif

View File

@ -0,0 +1,195 @@
// *******************************************************************
//
// (c) Copyright Cisco 2000
// All Rights Reserved
//
// *******************************************************************
// *******************************************************************
//
// Version : 1.0
// Status : Under development
// File : LoadModule.cpp
// Author(s) : Kevin Lim
// Create Date : 04-14-99
// Description : Functions to load modules
//
// *******************************************************************
// *******************************************************************
// Include Files.
// *******************************************************************
#include "vxWorks.h"
#include "dosFsLib.h"
#include "loadLib.h"
#include "ioLib.h"
#include "stdio.h"
#include "string.h"
#ifdef GMC_VOB_SPECIFIC
#include <oam_api.h>
#include <vipermib.h>
#endif /* GMC_VOB_SPECIFIC */
#define UNIX_FILE_EOFS
#ifdef UNIX_FILE_EOFS
#define EOL_TRUNC_LEN 1
#else
#define EOL_TRUNC_LEN 2
#endif
// *******************************************************************
int viperLoad(char * filename)
{
int fd;
MODULE_ID mId;
#ifdef NEVER // changed from GMC_VOB_SPECIFIC by oleg
Ss7Type* networkType;
char* fn;
if ((fn = strstr(filename, "gmccpapp.out"))
!= NULL)
{
if( NULL != ( networkType = (Ss7Type*)oam_getMibAddress( MIB_ss7NetworkType ) ))
{
if (*networkType == ansi)
{
printf ("Mib returned ansi for loading.\n");
strcpy(fn, "gmccpapp-ansi.out");
}
else
{
printf ("Mib returned itu for loading.\n");
strcpy(fn, "gmccpapp-itu.out");
}
}
else
{
printf ("Major Error reading network type from the Mib. Cannot load GMC CP.\n");
return (-1);
}
}
#endif /* GMC_VOB_SPECIFIC */
printf("Loading %s\n", filename);
fd = open (filename, 0, 0);
if(fd == ERROR)
{
// error on open object file
printf("[loadMod] Fatal Error on fopen(%s) return ERROR\n", filename);
return ERROR;
}
mId = loadModule (fd, LOAD_ALL_SYMBOLS);
if(mId == NULL)
{
// error on loading module
printf("[loadMod] Fatal Error on loadModule() return NULL\n");
return (-1);
}
close (fd);
return (int)mId;
}
// *******************************************************************
#define VIPER_MAX_BASE_PREFIX 100
#define VIPER_MAX_MODULE_LINE 180
// *******************************************************************
extern "C"
{
void viperLoadList(char * filename, char * base, int append)
{
char base_line[VIPER_MAX_MODULE_LINE];
char line[VIPER_MAX_MODULE_LINE];
FILE * fd;
char * lp;
int base_len = strlen(base);
int i, line_len;
bool done = false;
if(base_len > VIPER_MAX_BASE_PREFIX){
printf("[viperLoadList] base string too long %d\n", base_len);
return;
}
else{
for(i=0; i<base_len; i++) base_line[i] = base[i];
base_line[i]='/';
base_len++;
}
if(append){
int filename_len = strlen(filename);
if((base_len+filename_len)>VIPER_MAX_MODULE_LINE){
printf("[viperLoadList] base + module list name too long: %d\n", base_line+filename_len);
printf("%s%s\n", base_line, filename);
return;
}
for(i=0; i<filename_len; i++) base_line[base_len+i] = filename[i];
// mark null
base_line[base_len+i] = '\0';
fd = fopen(base_line, "r");
if(fd == NULL){
printf("[viperLoadList] Error on openning module list file: %s\n", base_line);
return;
}
else{
printf("[viperLoadList] Loading modules from: %s\n", base_line);
}
}
else{
fd = fopen(filename, "r");
if(fd == NULL){
printf("[viperLoadList] Error on openning module list file: %s\n", filename);
return;
}
else{
printf("[viperLoadList] Loading modules from: %s\n", filename);
}
}
while(!done){
lp = fgets(line, 80, fd);
if(lp == NULL){
done = true;
}
else{ // parse the line
line_len = strlen(lp);
if(lp[0] == '#'){ // do not append base
if(line_len>VIPER_MAX_MODULE_LINE){
printf("[viperLoadList] module line too long: %d\n", line_len);
printf("%s\n", line);
fclose(fd);
return;
}
// mark null at eol
lp[line_len-EOL_TRUNC_LEN] = '\0';
viperLoad(&line[1]); // exclude #
}
else if(lp[0] == '!'){ // comment fields
printf("%s", lp);
}
else if(line_len<3){ // probably blank line
}
else{ //append to the line
if((base_len+line_len)>VIPER_MAX_MODULE_LINE){
printf("[viperLoadList] base + module line too long: %d\n", base_line+line_len);
printf("%s%s\n", base_line, line);
fclose(fd);
return;
}
for(i=0; i<line_len; i++) base_line[base_len+i] = lp[i];
// mark null
base_line[base_len+i-EOL_TRUNC_LEN] = '\0';
viperLoad(base_line);
}
} // end parse
}
fclose(fd);
}
}

View File

@ -0,0 +1,62 @@
##########################################################
#
# (c) Copyright Cisco 2000
# All Rights Reserved
#
# Use Examples:
#
# Case 1:
# make all VOB=GP10 -
# Places .out in VOB/bin directory
#
# Case 2:
# make all VOB=GP10 APPDIR=Host\<Application Name>\<Source Directory> -
# Places .o file(s) in VOB\$(APPDIR)\bin directory.
#
# <Application Name> = Name of Application directory
# <Source Directory> = application sub directory where the calling
# Makefile resides.
#
# Example: make all VOB=GP10 APPDIR=Host\vxTemplate\src
#
#
# Note: This make file must reference a VOB that
# has a defs.mk in the top level directory.
#
##########################################################
# TOP_OF_VOB must be defined before including l3defs.mk
TOP_OF_VOB = ..\..
# Name of this App's Directory
COMMON_APP_DIR = loadmodule
VOB2DIR = $(TOP_OF_VOB)\..\$(VOB)
BINDIR = ..\bin
ifeq ($(APPDIR),)
MY_OUTPUT = $(VOB2DIR)\bin\$(COMMON_APP_DIR).out
else
MY_OUTPUT = $(OBJDIR)\$(COMMON_APP_DIR).out
endif
include $(VOB2DIR)\l3defs.mk
all: $(MY_OUTPUT)
$(MY_OUTPUT): $(MODULE_OBJS)
$(LD) -r -o $@.tmp $(MODULE_OBJS)
$(NM) $@.tmp | munch > _ctdt.c
$(CC) -traditional $(CC_ARCH_SPEC) -c _ctdt.c
$(LD) -r -o $@ _ctdt.o $@.tmp
$(RM)$(subst /,$(DIRCHAR), _ctdt.c _ctdt.o $@.tmp)
cleanall:
@for %f in ($(notdir $(MODULE_OBJS))) do \
$(RM) ..\bin\%f
$(RM) $(MY_OUTPUT)

View File

@ -0,0 +1,91 @@
// *******************************************************************
//
// (c) Copyright Cisco 2000
// All Rights Reserved
//
// *******************************************************************
// *******************************************************************
//
// Version : 1.0
// Status : Under development
// File : JCCTimer.cpp
// Author(s) : Bhava Nelakanti
// Create Date : 10-19-98
// Description : interface specification for - JCCTimer
//
// *******************************************************************
// *******************************************************************
// Include Files.
// *******************************************************************
#include <stdio.h>
#include "Os/JCCTimer.h"
extern "C" int sysClkRateGet (void);
#define JCCLog printf
int JCCTimer::tickPerSec = sysClkRateGet();
void JCCTimer::cancelTimer()
{
if (timerSet_ == true)
{
wdCancel(timerId_);
timerSet_ = false;
}
}
JCCTimer::~JCCTimer()
{
wdDelete(timerId_);
}
JCCTimer::JCCTimer (FUNCPTR fPtr ,
int timerData)
:timerData_(timerData),
funcPtr_ (fPtr) ,
timerSet_ (false)
{
init ();
}
JCCTimer::JCCTimer (FUNCPTR fPtr)
:timerData_(-1) ,
funcPtr_ (fPtr) ,
timerSet_ (false)
{
init ();
}
void JCCTimer::setTimer(int howLong)
{
if (timerSet_ == true)
{
cancelTimer();
}
wdStart(timerId_, howLong, funcPtr_, timerData_);
timerSet_ = true;
}
void JCCTimer::init()
{
if (!tickPerSec)
tickPerSec = sysClkRateGet ();
if ((timerId_ = wdCreate()) == NULL)
{
// Handle Operating System Resource Allocation Error
JCCLog("JCC Error - Operating System Resource Allocation Error:\n");
JCCLog(" - WatchDog Timer could not be created.\n");
}
}

View File

@ -0,0 +1,470 @@
// *******************************************************************
//
// (c) Copyright Cisco 2000
// All Rights Reserved
//
// *******************************************************************
// *******************************************************************
//
// Version : 1.0
// Status : Under development
// File : JCModule.cpp
// Author(s) : Tim Olson
// Create Date : 10/18/2000
// Description :
//
// *******************************************************************
#include <stdio.h>
#include <errNoLib.h>
#include <string.h>
#include <ioLib.h>
#include <dbgLib.h>
#include <usrLib.h>
#include "Os/JCModule.h"
#include "AlarmCode.h"
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCModule constructor
**
** PURPOSE: Initialize data members for JCModule object.
**
** INPUT PARAMETERS: id - module id
**
** RETURN VALUE(S): none
**
**----------------------------------------------------------------------------*/
JCModule::JCModule
(
MNET_MODULE_ID id,
JC_SYSCMD_FUNC cmdFunc,
char *cmdFuncStr
) : modId(id), numRun(0), numSub(0)
{
char *name = GetMnetModuleName(id);
if (name)
{
modName = new char[strlen(name) + 1];
if (modName)
{
strcpy(modName, name);
}
else
{
printf("JCModule::JCModule ERROR: Unable to allocate memory\n");
}
}
else
{
modName = 0;
}
if (!TestSym(cmdFuncStr))
{
syscmd = cmdFunc;
isModuleLoaded = TRUE;
}
else
{
isModuleLoaded = FALSE;
}
for (int i=0; i < MAX_NUM_SUB_TASKS; i++)
{
tasks[i] = 0;
}
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCModule destructor
**
** PURPOSE: Delete data members for JCModule object.
**
** INPUT PARAMETERS: none
**
** RETURN VALUE(S): none
**
**----------------------------------------------------------------------------*/
JCModule::~JCModule ()
{
delete [] modName;
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCModule InsertTaskInfo
**
** PURPOSE: InsertTaskInfo adds the task object to the list of tasks
** currently running under this module.
**
** INPUT PARAMETERS: id - module id
** pTask - pointer to the new task object
**
** RETURN VALUE(S): none
**
**----------------------------------------------------------------------------*/
void JCModule::InsertTaskInfo(MNET_MODULE_ID id, JCTask *pTask)
{
for (int j=0; j < MNET_MAX_MODULE_IDS; j++)
{
if (systemModules[j])
{
if (systemModules[j]->modId == id)
{
for (int i=0; i < MAX_NUM_SUB_TASKS; i++)
{
if (!systemModules[j]->tasks[i])
{
systemModules[j]->tasks[i] = pTask;
systemModules[j]->numSub++;
break;
}
}
break;
}
}
}
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCModule StartModule
**
** PURPOSE: StartModule sends a SYS_START system command to the module.
**
** INPUT PARAMETERS: none
**
** RETURN VALUE(S): TRUE - if module is loaded
** FALSE - if module is not loaded
**
**----------------------------------------------------------------------------*/
bool JCModule::StartModule()
{
bool ret = FALSE;
if (isModuleLoaded)
{
if (!numRun)
{
printf("SysCommand(SYS_START): %s\n", modName);
syscmd(SYS_START);
numRun++;
}
else
{
printf("Module %d already started\n", modId);
}
ret = TRUE;
}
return(ret);
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCModule ShutdownModule
**
** PURPOSE: StartModule sends a SYS_SHUTDOWN system command to the module.
**
** INPUT PARAMETERS: none
**
** RETURN VALUE(S): none
**
**----------------------------------------------------------------------------*/
void JCModule::ShutdownModule()
{
if (isModuleLoaded)
{
printf("SysCommand(SYS_SHUTDOWN): %s\n", modName);
syscmd(SYS_SHUTDOWN);
}
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCModule RebootModule
**
** PURPOSE: StartModule sends a SYS_REBOOT system command to the module.
**
** INPUT PARAMETERS: none
**
** RETURN VALUE(S): none
**
**----------------------------------------------------------------------------*/
void JCModule::RebootModule()
{
if (isModuleLoaded)
{
printf("SysCommand(SYS_REBOOT): %s\n", modName);
syscmd(SYS_REBOOT);
}
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCModule CheckModule
**
** PURPOSE: CheckModule verifies that all tasks associated with this module
** are currently running.
**
** INPUT PARAMETERS: pTask - if problems a pointer to the troubled task
** with the highest criticality
**
** RETURN VALUE(S): SYSTEM_MODULE_STATUS
**
**----------------------------------------------------------------------------*/
SYSTEM_MODULE_STATUS JCModule::CheckModule(JCTask **pTask)
{
SYSTEM_MODULE_STATUS retCode = MODULE_OK;
*pTask = 0;
if (isModuleLoaded)
{
char *tName;
for(int i=0; i < numSub; i++){
// check for exit abnormal
tName = taskName(tasks[i]->GetTaskId());
if(tName == NULL)
{
printf("Alert! found missing task(%s)\n", tasks[i]->GetTaskName());
if (!*pTask)
{
retCode = TASK_MISSING;
*pTask = tasks[i];
}
else if ((tasks[i]->GetTaskImportance() == JC_CRITICAL_TASK) &&
((*pTask)->GetTaskImportance() == JC_NON_CRITICAL_TASK))
{
retCode = TASK_MISSING;
*pTask = tasks[i];
}
}
// check for suspended
else if(taskIsSuspended(tasks[i]->GetTaskId()))
{
char coreFileName[128];
char *pMnetBase;
int coreFd = ERROR;
int stdoutFd, stderrFd;
// Create a core file for this task.
pMnetBase = getenv("MNET_BASE");
if (pMnetBase && !tasks[i]->GetTaskAlarmStatus())
{
strcpy(coreFileName, pMnetBase);
strcat(coreFileName, "\\");
strcat(coreFileName, tasks[i]->GetTaskName());
strcat(coreFileName, ".dmp");
// If the file was created replace stdout and stderr with the
// file descriptor for the task core file.
if ((coreFd = creat(coreFileName, O_RDWR)) != ERROR)
{
stdoutFd = ioGlobalStdGet(1);
stderrFd = ioGlobalStdGet(2);
ioGlobalStdSet(1, coreFd);
ioGlobalStdSet(2, coreFd);
}
}
printf("Alert! found suspended task(%s)\n", tasks[i]->GetTaskName());
tt(tasks[i]->GetTaskId());
ti(tasks[i]->GetTaskId());
tasks[i]->ExecuteCoreDumpFunc();
// If a core file was created then return stdout and stderr.
if (coreFd != ERROR)
{
ioGlobalStdSet(1, stdoutFd);
ioGlobalStdSet(2, stderrFd);
close(coreFd);
printf("Alert! found suspended task(%s)\n", tasks[i]->GetTaskName());
tt(tasks[i]->GetTaskId());
ti(tasks[i]->GetTaskId());
tasks[i]->ExecuteCoreDumpFunc();
}
if (!*pTask)
{
retCode = TASK_SUSPENDED;
*pTask = tasks[i];
}
else if ((tasks[i]->GetTaskImportance() == JC_CRITICAL_TASK) &&
((*pTask)->GetTaskImportance() == JC_NON_CRITICAL_TASK))
{
retCode = TASK_SUSPENDED;
*pTask = tasks[i];
}
}
}
}
return(retCode);
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCModule AllTasksInMainLoop
**
** PURPOSE: Check to see if all tasks are in the main loop.
**
** INPUT PARAMETERS: none
**
** RETURN VALUE(S): TRUE - all in main
** FALSE - not all tasks in main loop
**
**----------------------------------------------------------------------------*/
bool JCModule::AllTasksInMainLoop()
{
for (int i=0; i < MNET_MAX_MODULE_IDS; i++)
{
if (systemModules[i])
{
for (int j=0; j < MAX_NUM_SUB_TASKS; j++)
{
if (systemModules[i]->tasks[j])
{
if (systemModules[i]->tasks[j]->GetTaskStatus() != JC_TASK_LOOP)
{
return (FALSE);
}
}
}
}
}
return (TRUE);
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCModule ShowModuleStat
**
** PURPOSE: Display module status.
**
** INPUT PARAMETERS: none
**
** RETURN VALUE(S): none
**
**----------------------------------------------------------------------------*/
extern "C"
{
void ShellShowModuleStat()
{
JCModule::ShowModuleStat();
}
}
void JCModule::ShowModuleStat()
{
int totalTasks, totalInit, totalIdle, totalLoop, totalExit, totalUnknown;
printf ("System Module Status\n");
for (int i=0; i < MNET_MAX_MODULE_IDS; i++)
{
if (systemModules[i])
{
totalTasks = 0;
totalInit = 0;
totalIdle = 0;
totalLoop = 0;
totalExit = 0;
totalUnknown = 0;
for (int j=0; j < MAX_NUM_SUB_TASKS; j++)
{
if (systemModules[i]->tasks[j])
{
totalTasks++;
switch (systemModules[i]->tasks[j]->GetTaskStatus())
{
case JC_TASK_IDLE :
totalIdle++;
break;
case JC_TASK_INIT :
totalInit++;
break;
case JC_TASK_LOOP :
totalLoop++;
break;
case JC_TASK_EXIT :
totalExit++;
break;
default :
totalUnknown++;
}
}
}
printf("\tModule - %s\n", systemModules[i]->modName);
printf("\t\tTotalTasks(%d) Idle(%d) Init(%d) Loop(%d) Exit(%d) Unknown(%d)\n",
totalTasks, totalIdle, totalInit, totalLoop, totalExit, totalUnknown);
}
}
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCModule CheckSym
**
** PURPOSE: CheckSym does a string compare to see if against the symbol.
**
** INPUT PARAMETERS: none
**
** RETURN VALUE(S): 0 - string match
** 1 - no string match
**
**----------------------------------------------------------------------------*/
int JCModule::CheckSym(char *name, int val, SYM_TYPE type, int arg, UINT16 group)
{
if(strstr(name, (char *)arg))
{
return 0; // exit symEach
}
return 1; // continue
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCModule TestSym
**
** PURPOSE: Loop through each symbol in the symbol table testing if the
** string given matches a valid symbol.
**
** INPUT PARAMETERS: none
**
** RETURN VALUE(S): 0 - symbol found
** 1 - symbol not found
**
**----------------------------------------------------------------------------*/
int JCModule::TestSym(char *str)
{
SYMBOL *symbol = symEach(sysSymTbl, (FUNCPTR)JCModule::CheckSym, (int)str);
if(symbol) return 0;
else
{
printf("[WARNING] function not found from symbol table: %s\n", str);
return 1;
}
}

View File

@ -0,0 +1,197 @@
// *******************************************************************
//
// (c) Copyright Cisco 2000
// All Rights Reserved
//
// *******************************************************************
// *******************************************************************
//
// Version : 1.0
// Status : Under development
// File : JCMsgQueue.cpp
// Author(s) : Tim Olson
// Create Date : 10/18/2000
// Description :
//
// *******************************************************************
//
// Revision history:
// ===================================================================
// Igal | 11/30/00 | Fixed incorrect max message size acceptable by the queue
// -------------------------------------------------------------------
//
//
#include <stdio.h>
#include <errNoLib.h>
#include <string.h>
#include "Os/JCMsgQueue.h"
#include "JCMsgQDefs.h"
#define PADDING 4
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCMsgQueue constructor
**
** PURPOSE: Initialize data members for JCMsgQueue object. A message
** queue for the native operating system will be created.
**
** INPUT PARAMETERS: maxMsgs - max msgs that can be queued
** maxMsgLength - max bytes in a msg
** options - message queue options (MSG_Q_FIFO or
** MSG_Q_PRIORITY)
**
** RETURN VALUE(S): none
** Note: If the message queue cannot be created msgQId will be set to NULL
**
**----------------------------------------------------------------------------*/
JCMsgQueue::JCMsgQueue
(
int maxMsgs, /* max msgs that can be queued */
int maxMsgLength, /* max bytes in a msg */
int options /* message queue options */
) : msgQMaxLen(maxMsgLength+PADDING)
{
if (!(msgQId = msgQCreate(maxMsgs, msgQMaxLen + JC_MSG_HDR_SIZE, options)))
{
printf("Error creating message queue %s\n", errnoGet());
}
if (!(msgQSndBuf = new char[msgQMaxLen + JC_MSG_HDR_SIZE]))
{
printf("Error: unable to allocate msg buffer memory\n");
}
if (!(msgQRcvBuf = new char[msgQMaxLen + JC_MSG_HDR_SIZE]))
{
printf("Error: unable to allocate msg buffer memory\n");
}
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCMsgQueue destructor
**
** PURPOSE: Delete data members for JCMsgQueue object.
**
** INPUT PARAMETERS: none
**
** RETURN VALUE(S): none
**
**----------------------------------------------------------------------------*/
JCMsgQueue::~JCMsgQueue ()
{
if (msgQDelete(msgQId) != OK)
{
printf("Error deleting message queue %s\n", errnoGet());
}
delete [] msgQSndBuf;
delete [] msgQRcvBuf;
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCMsgQueue::JCMsgQSend
**
** PURPOSE: JCMsgQSend sends the specified message to the specified message
** queue. The buffer given will be copied into a local send buffer prior
** to sending the message.
**
** INPUT PARAMETERS: replyMsgQ - message queue to use for sending a reply
** msgType - type of message being sent
** modId - module ID of sender
** buffer - message to send
** nBytes - number of bytes in the message
** timeout - ticks to wait
** priority - priority of the message (normal or urgent)
**
** RETURN VALUE(S): JC_STATUS
**
**----------------------------------------------------------------------------*/
JC_STATUS JCMsgQueue::JCMsgQSend
(
JCMsgQueue *replyMsgQ,
unsigned int msgType,
MNET_MODULE_ID modId,
char * buffer,
unsigned int nBytes,
int timeout,
int priority
)
{
// Verify a few parameters first.
if (nBytes && !buffer)
return JC_PARAM_INVALID;
if (nBytes > msgQMaxLen-PADDING)
return JC_MSG_LENGTH_ERROR;
// Build message in the receive message buffer for this queue.
JC_MSG_HDR *pMsg = (JC_MSG_HDR *)msgQSndBuf;
pMsg->rplyQ = replyMsgQ;
pMsg->msgType = msgType ;
pMsg->modId = modId ;
pMsg->bytes = nBytes ;
if (buffer)
memcpy (msgQSndBuf + JC_MSG_HDR_SIZE, buffer, nBytes);
return (msgQSend(msgQId, msgQSndBuf, nBytes + JC_MSG_HDR_SIZE, timeout, priority));
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCMsgQueue::JCMsgQReceive
**
** PURPOSE: JCMsgQReceive.
**
** INPUT PARAMETERS: replyMsgQ - message queue to use for sending a reply
** msgType - type of message being sent
** modId - module ID of sender
** buffer - message to send
** nBytes - number of bytes in the message
** timeout - ticks to wait
**
** RETURN VALUE(S): number of bytes received
**
**----------------------------------------------------------------------------*/
int JCMsgQueue::JCMsgQReceive
(
JCMsgQueue **replyMsgQ,
unsigned int *msgType,
MNET_MODULE_ID *modId,
char * buffer,
unsigned int *nBytes,
int timeout
)
{
int bytesRcvd;
// Verify a few parameters first.
if ((!buffer) || (!replyMsgQ) || (!msgType) || (!nBytes))
return JC_PARAM_INVALID;
// Wait here for a message to arrive or timeout number of ticks to expire.
if ((bytesRcvd = msgQReceive(msgQId, msgQRcvBuf, msgQMaxLen + JC_MSG_HDR_SIZE,
timeout)) != ERROR)
{
// Access the message header at the start of the buffer.
JC_MSG_HDR *pMsg = (JC_MSG_HDR *)msgQRcvBuf;
*replyMsgQ = pMsg->rplyQ;
*msgType = pMsg->msgType;
*modId = pMsg->modId;
*nBytes = pMsg->bytes;
// Message contents should follow the message header.
memcpy(buffer, msgQRcvBuf + JC_MSG_HDR_SIZE, bytesRcvd - JC_MSG_HDR_SIZE);
}
return (bytesRcvd);
}

View File

@ -0,0 +1,43 @@
// *******************************************************************
//
// (c) Copyright CISCO Systems, 2000
// All Rights Reserved
//
// *******************************************************************
// *******************************************************************
//
// Version : 1.0
// Status : Under development
// File : JCMutex.cpp
// Author(s) : Igal Gutkin
// Create Date : 11/06/00
// Description : JCMutex class (Mutual-Exclusion Semapore) implementation
//
// *******************************************************************
#include "Os\JCMutex.h"
JCMutex::JCMutex ()
{
semId_ = semMCreate (SEM_Q_PRIORITY | SEM_DELETE_SAFE | SEM_INVERSION_SAFE);
}
bool JCMutex::take ()
{
return (semId_ && semTake (semId_, WAIT_FOREVER) == OK);
}
bool JCMutex::give ()
{
return (semId_ && semGive (semId_) == OK);
}
JCMutex::~JCMutex ()
{
semDelete (semId_);
}

View File

@ -0,0 +1,193 @@
// *******************************************************************
//
// (c) Copyright Cisco 2000
// All Rights Reserved
//
// *******************************************************************
// *******************************************************************
//
// Version : 1.0
// Status : Under development
// File : JCTask.cpp
// Author(s) : Tim Olson
// Create Date : 10/18/2000
// Description :
//
// *******************************************************************
#include <stdio.h>
#include <errNoLib.h>
#include <string.h>
#include "Os/JCTask.h"
#include "Os/JCModule.h"
SEM_ID *pMnetSyncSem;
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCTask constructor
**
** PURPOSE: Initialize data members for JCTask object.
**
** INPUT PARAMETERS: name - name of the task
**
** RETURN VALUE(S): none
**
**----------------------------------------------------------------------------*/
JCTask::JCTask
(
char *name /* name of the task */
) : taskStatus(JC_TASK_IDLE), taskAlarmed(FALSE)
{
if (name)
{
taskName = new char[strlen(name) + 1];
if (taskName)
{
strcpy(taskName, name);
}
else
{
printf("JCTask::JCTask ERROR: Unable to allocate memory\n");
}
}
else
{
taskName = 0;
}
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCTask destructor
**
** PURPOSE: Delete data members for JCTask object.
**
** INPUT PARAMETERS: none
**
** RETURN VALUE(S): none
**
**----------------------------------------------------------------------------*/
JCTask::~JCTask ()
{
delete [] taskName;
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCTask::JCTaskSpawn
**
** PURPOSE: Spawn a task.
**
** INPUT PARAMETERS: priority - (0-255)
** options - option word
** stackSize - size in bytes of stack
** entryPt - entry point of task
** arg1 - argument 1 passed to entryPt
** arg2 - argument 1 passed to entryPt
** arg3 - argument 1 passed to entryPt
** arg4 - argument 1 passed to entryPt
** arg5 - argument 1 passed to entryPt
** arg6 - argument 1 passed to entryPt
** arg7 - argument 1 passed to entryPt
** arg8 - argument 1 passed to entryPt
** arg9 - argument 1 passed to entryPt
** arg10 - NOT AN ARGUMENT!!!! This parameter can be used
** to pass a function pointer to a function that
** will be called if the task is suspended.
** modId - module id number
** importance - critical or non-critical
**
** RETURN VALUE(S): taskId or ERROR
**
**----------------------------------------------------------------------------*/
int JCTask::JCTaskSpawn
(
int priority, /* priority of new task */
int options, /* task option word */
int stackSize, /* size (bytes) of stack needed plus name */
FUNCPTR entryPt, /* entry point of new task */
int arg1, /* 1st of 10 req'd task args to pass to func */
int arg2,
int arg3,
int arg4,
int arg5,
int arg6,
int arg7,
int arg8,
int arg9,
int arg10,
MNET_MODULE_ID modId,
JC_TASK_IMPORTANCE importance
)
{
JCModule::InsertTaskInfo(modId, this);
taskPri = priority;
taskOpt = options;
taskStackSize = stackSize;
taskEntryPt = entryPt;
taskArg1 = arg1;
taskArg2 = arg2;
taskArg3 = arg3;
taskArg4 = arg4;
taskArg5 = arg5;
taskArg6 = arg6;
taskArg7 = arg7;
taskArg8 = arg8;
taskArg9 = arg9;
taskArg10 = arg10;
taskImportance = importance;
moduleId = modId;
taskStatus = JC_TASK_INIT;
coreDumpFunc = (FUNCPTR)arg10;
taskId = taskSpawn(taskName, priority, options, stackSize, entryPt,
arg1, arg2, arg3, arg4, arg5,
arg6, arg7, arg8, arg9, 0);
return(taskId);
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCTask::JCTaskEnterLoop()
**
** PURPOSE:
**
** INPUT PARAMETERS: none
**
** RETURN VALUE(S): none
**
**----------------------------------------------------------------------------*/
void JCTask::JCTaskEnterLoop()
{
taskStatus = JC_TASK_LOOP;
// Spin here waiting for all other tasks to call enter loop.
if (pMnetSyncSem)
semBTake(*pMnetSyncSem, WAIT_FOREVER);
}
/*----------------------------------------------------------------------------**
**
** METHOD NAME: JCTask::JCTaskNormExit()
**
** PURPOSE:
**
** INPUT PARAMETERS: none
**
** RETURN VALUE(S): none
**
**----------------------------------------------------------------------------*/
void JCTask::JCTaskNormExit()
{
taskStatus = JC_TASK_EXIT;
}

View File

@ -0,0 +1,62 @@
##########################################################
#
# (c) Copyright Cisco 2000
# All Rights Reserved
#
# Use Examples:
#
# Case 1:
# make all VOB=GP10 -
# Places .out in VOB/bin directory
#
# Case 2:
# make all VOB=GP10 APPDIR=Host\<Application Name>\<Source Directory> -
# Places .o file(s) in VOB\$(APPDIR)\bin directory.
#
# <Application Name> = Name of Application directory
# <Source Directory> = application sub directory where the calling
# Makefile resides.
#
# Example: make all VOB=GP10 APPDIR=Host\vxTemplate\src
#
#
# Note: This make file must reference a VOB that
# has a defs.mk in the top level directory.
#
##########################################################
# TOP_OF_VOB must be defined before including l3defs.mk
TOP_OF_VOB = ..\..
# Name of this App's Directory
COMMON_APP_DIR = os
VOB2DIR = $(TOP_OF_VOB)\..\$(VOB)
BINDIR = ..\bin
ifeq ($(APPDIR),)
MY_OUTPUT = $(VOB2DIR)\bin\$(COMMON_APP_DIR).out
else
MY_OUTPUT = $(OBJDIR)\$(COMMON_APP_DIR).out
endif
include $(VOB2DIR)\l3defs.mk
all: $(MY_OUTPUT)
$(MY_OUTPUT): $(MODULE_OBJS)
$(LD) -r -o $@.tmp $(MODULE_OBJS)
$(NM) $@.tmp | munch > _ctdt.c
$(CC) -traditional $(CC_ARCH_SPEC) -c _ctdt.c
$(LD) -r -o $@ _ctdt.o $@.tmp
$(RM)$(subst /,$(DIRCHAR), _ctdt.c _ctdt.o $@.tmp)
cleanall:
@for %f in ($(notdir $(MODULE_OBJS))) do \
$(RM) ..\bin\%f
$(RM) $(MY_OUTPUT)

View File

@ -0,0 +1,65 @@
##########################################################
#
# (c) Copyright Cisco 2000
# All Rights Reserved
#
# Use Examples:
#
# Case 1:
# make all VOB=GP10 -
# Places .out in VOB/bin directory
#
# Case 2:
# make all VOB=GP10 APPDIR=Host\<Application Name>\<Source Directory> -
# Places .o file(s) in VOB\$(APPDIR)\bin directory.
#
# <Application Name> = Name of Application directory
# <Source Directory> = application sub directory where the calling
# Makefile resides.
#
# Example: make all VOB=GP10 APPDIR=Host\vxTemplate\src
#
#
# Note: This make file must reference a VOB that
# has a defs.mk in the top level directory.
#
##########################################################
# TOP_OF_VOB must be defined before including l3defs.mk
TOP_OF_VOB = ..\..\..
# Name of this App's Directory
COMMON_APP_DIR = Os
VOB2DIR = $(TOP_OF_VOB)\$(VOB)
BINDIR = ..\bin
ifeq ($(APPDIR),)
MY_OUTPUT = $(VOB2DIR)\bin\OsTest.out
else
MY_OUTPUT = $(OBJDIR)\OsTest.out
endif
include $(VOB2DIR)\l3defs.mk
all: $(MY_OUTPUT)
$(MY_OUTPUT): $(MODULE_OBJS)
$(LD) -r -o $@.tmp $(MODULE_OBJS)
$(NM) $@.tmp | munch > _ctdt.c
$(CC) -traditional $(CC_ARCH_SPEC) -c _ctdt.c
$(LD) -r -o $@ _ctdt.o $@.tmp
$(RM)$(subst /,$(DIRCHAR), _ctdt.c _ctdt.o $@.tmp)
ifneq ($(APPDIR),)
$(CP) $(BINDIR)\*.o $(VOB2DIR)\$(APPDIR)\bin\*.o
endif
cleanall:
@for %f in ($(notdir $(MODULE_OBJS))) do \
$(RM) ..\bin\%f
$(RM) $(MY_OUTPUT)

View File

@ -0,0 +1,91 @@
// *******************************************************************
//
// (c) Copyright Cisco 2000
// All Rights Reserved
//
// *******************************************************************
// *******************************************************************
//
// Version : 1.0
// Status : Under development
// File : MsgQTest.cpp
// Author(s) : Tim Olson
// Create Date : 10/18/2000
// Description :
//
// *******************************************************************
#include <stdio.h>
#include "Os/JCMsgQueue.h"
JCMsgQueue *pMsgQ;
bool isTestComplete = FALSE;
extern "C"
{
void InitializeQueue()
{
pMsgQ = new JCMsgQueue(10, 256, JC_MSG_Q_FIFO);
if (pMsgQ->JCGetMsgQId() == 0)
{
printf("Error creating test message queue\n");
return;
}
JC_MSG_Q_ID replyMsgQ;
unsigned int msgType;
char buffer[256];
unsigned int nBytes;
MNET_MODULE_ID modId;
while (!isTestComplete)
{
JC_STATUS status;
if ((status = pMsgQ->JCMsgQReceive(&replyMsgQ, &msgType, &modId, buffer, &nBytes,
JC_WAIT_FOREVER)) == JC_OK)
{
printf("Received a test message!\n");
printf("\treplyMsgQ = %x\n", replyMsgQ);
printf("\tmsgType = %x\n", msgType);
printf("\tmodId = %x\n", modId);
printf("\tnBytes = %x\n", nBytes);
printf("\tbuffer = ");
for (int i=0; i < nBytes; i++)
printf("%02x ", buffer[i]);
printf("\n");
}
else
{
printf("Error receiving message - errcode %x\n", status);
}
}
}
void SendToQueue()
{
char msg[256];
JC_STATUS status;
// build a test message
for (int i=0; i < 16; i++)
{
msg[i] = (char)i;
}
isTestComplete = TRUE;
unsigned int msgType = 13;
unsigned int msgLen = 16;
if ((status = pMsgQ->JCMsgQSend((JC_MSG_Q_ID)0xabcd0123, msgType, LOGGER, msg, msgLen, JC_WAIT_FOREVER,
JC_MSG_PRI_NORMAL)) != JC_OK)
{
printf("Error sending test message - errcode %x\n", status);
}
}
}

View File

@ -0,0 +1,47 @@
##########################################################
#
# (c) Copyright Cisco 2000
# All Rights Reserved
#
# Use Examples:
#
# Case 1:
# make all VOB=GP10 -
# Places .out in VOB/bin directory
#
# Case 2:
# make all VOB=GP10 APPDIR=Host\<Application Name>\<Source Directory> -
# Places .o file(s) in VOB\$(APPDIR)\bin directory.
#
# <Application Name> = Name of Application directory
# <Source Directory> = application sub directory where the calling
# Makefile resides.
#
# Example: make all VOB=GP10 APPDIR=Host\vxTemplate\src
#
# (OPTIONAL) Append REPLACE - Replaces the List of directories
# to be used in the SUBDIRS variable
#
# Example: make all VOB=GP10 APPDIR=Host\vxTemplate\src REPLACE="src_api src_debug"
#
# Note: This make file must reference a VOB that
# has a defs.mk in the top level directory.
#
##########################################################
SUBDIRS = src
# TOP_OF_VOB must be defined before including l3defs.mk
TOP_OF_VOB = ..
VOBDIR = $(TOP_OF_VOB)/../$(VOB)
# Allows a sub-set of the source code directories to be used
ifneq ($(REPLACE),)
SUBDIRS = $(REPLACE)
endif
include $(VOBDIR)\l3defs.mk

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