Quantcast
Channel: WebSphere Blog by Steve Robinson » WebSphere Jython Examples
Viewing all 10 articles
Browse latest View live

Jython Exception: KeyError

$
0
0

Example Error while using a Dictionary Object in Jython.
Error:

WASX7017E: Exception received while running file "f:\script\jython\mbean.py"; exception information: com.ibm.bsf.BSFException: exception from Jython:
Traceback (innermost last):
  File "", line 79, in ?
KeyError:  platformVersion

Bad Code:

fields='name,platformName, platformVersion,processType'
for name in fields.split(','):
	print '%-15s : %s' % (name, svrDict[ name ] )

Solution:

You will notice that there is a space before the “,” in the fields string and so the split result is returning ” platformVersion” as opposed to “platformVersion”.

Fixed code:

fields='name,platformName,platformVersion,processType'
for name in fields.split(','):
	print '%-15s : %s' % (name, svrDict[ name ] )


SyntaxError: Lexical error at line – Jython

$
0
0

When running a jython script in wsadmin.bat/.sh we get this error: SyntaxError: Lexical error
A common reason is missing “quotes”. As you can see by this error column 35 has an error and a carriage return was found before the end quote. The fix is to add a set of quotes.
Problem code:

print "Entering exception catch

 

WASX7017E: Exception received while running file "f:\script\jython\getCell.py"; exception information: com.ibm.bsf.BSFException: exception from Jython:
Traceback (innermost last):
  (no code object) at line 0
  File "", line 27
           print "Entering exception catch
                                          ^
SyntaxError: Lexical error at line 27, column 35.  Encountered: "\r" (13), after : ""

Solution:

print "Entering exception catch

Show a simple Jython try / catch example of how to catch WAS being down and wsadmin cannot connect to the WAS AdminTask object

$
0
0

#Created 09:14 10-October-2011
#Created by Steve Robinson
#References: WebSphere Application Server Administration Using Jython
#Purpose - Show a simple example of how to catch WAS being down ie wsadmin cannot connect to the WAS AdminTask object to run jython script to get the cell name
################# SAMPLE ERROR ######################
#f:\script\jython>"C:\PROGRAM FILES\IBM\WebSphere\AppServer\profiles\AppSrv01"\bin\wsadmin.bat -lang jython -f f:\script\jython\schedule_mbean.py
#WASX7023E: Error creating "SOAP" connection to host "localhost"; exception information: 
#com.ibm.websphere.management.exception.ConnectorNotAvailableException: com.ibm.websphere.management.exception.Co#nnectorNotAvailableException: ADMC0016E: 
#The system cannot create a SOAP connector to connect to host localhost at port 8880.
#WASX7213I: This scripting client is not connected to a server process; please refer to the log file 
#c:\Program Files\IBM\WebSphere\AppServer\profiles\AppSrv01\logs\wsadmin.traceout for additional information.
#WASX8011W: AdminTask object is not available.
#WASX7017E: Exception received while running file "f:\script\jython\schedule_mbean.py"; exception information: com.ibm.ws.scripting.ScriptingException: AdminControl service not available
###################################################

#MAIN
print "entering main"
try :
   #Get cell name
   cellName = AdminControl.getCell()
   print "Cell name = " + cellName
   #Get cell id
   cells = AdminConfig.list("Cell" )
   print "cell variable contains: "+ cells

except :
   print "Entering exception catch"
   notavail = 'AdminControl service not available'
   ( kind, value ) = sys.exc_info()[ :2 ]
   ( kind, value ) = str( kind ), str( value )
   print "kind = " + kind
   print "value = " + value
   if value.endswith( notavail ) :
     print "System modules"
     print 50 * "*"
     print "sys.modules.keys()="
     print sys.modules.keys()
     print 50 * "*"
     print "Local variables"
     print 50 * "*"
     print "locals()="
     print locals()
     print 50 * "*"
     print '"%(notavail)s": wsadmin isn\'t connected to a server.' % locals()
     
     if 'AdminTask' in sys.modules.keys() :
       print '%(funName)s "%(notavail)s": WAS wsadmin started with "-conntype none"?' % locals()
      
   elif value.find( 'WASX7025E' ) > -1 :
     print '%(funName)s: Invalid mbean identifier: %(mbean)s' % locals()
   else :
     print 'Exception  type: ' + kind
     print 'Exception value: ' + value

Result:

F:\script\jython>"C:\PROGRAM FILES\IBM\WebSphere\AppServer\profiles\AppSrv01"\bin\wsadmin.bat -lang jython -f
WASX7023E: Error creating "SOAP" connection to host "localhost"; exception information: com.ibm.websphere.mana
nnectorNotAvailableException: ADMC0016E: The system cannot create a SOAP connector to connect to host localhos
WASX7213I: This scripting client is not connected to a server process; please refer to the log file c:\Program
rmation.
WASX8011W: AdminTask object is not available.
entering main
Entering exception catch
kind = com.ibm.ws.scripting.ScriptingException
value = com.ibm.ws.scripting.ScriptingException: AdminControl service not available
System modules
**************************************************
sys.modules.keys()=
['time', 'java', '__builtin__', 'exceptions', 'sys']
**************************************************
Local variables
**************************************************
locals()=
{'AdminConfig': com.ibm.ws.scripting.AdminConfigClient@246e246e, '__doc__': None, 'flag': '', 'Help': com.ibm.
Mechanism at 1226590492>, 'getSecurityAdminMbean': <function getSecurityAdminMbean at 1206929392>, 'sleep': <j
r.coordinator.impl.jmx.ProxyScriptExtension@49f049f0, 'LTPA_LDAPSecurityOn': <function LTPA_LDAPSecurityOn at
 1206142948>, 'ltpaId': '', 'forceSync': <function forceSync at 1229736268>, 'ldapPort': '', 'nodeName': '', '
atEnv': <function whatEnv at 1203783616>, 'AdminControl': com.ibm.ws.scripting.AdminControlClient@48124812, 'd
SecId at 1204570060>, 'notavail': 'AdminControl service not available', 'sys': sys module, 'doGlobalSecurityDi
.bsf.util.BSFFunctions@5b785b78, 'exportLTPAKey': <function exportLTPAKey at 1225804048>, 'securityoff': <func
yOff': <function LTPA_LDAPSecurityOff at 1231964526>, 'java': <java package java at 1657823952>, 'cellName': '
on getLTPAId at 1205356504>, 'lineSeparator': '\r\n', 'generateLTPAKeys': <function generateLTPAKeys at 122501
checkuserpw at 1271417800>, 'ldapUserRegistryId': '', 'securityon': <function securityon at 1279806536>, 'ldap
**************************************************
"AdminControl service not available": wsadmin isn't connected to a server.

SyntaxError: inconsistent dedent

$
0
0

When running a WAS jython script you get the following error:

WASX7017E: Exception received while running file &quot;f:\script\jython\getCell.py&quot;; exception information: com.ibm.bsf.BSFException: exception from
Traceback (innermost last):
  (no code object) at line 0
  File &quot;&quot;, line 36
            elif value.find( 'WASX7017E' ) &gt; -1 :
            ^
SyntaxError: inconsistent dedent

 

In this example screen shot below you can see that the elif statement has been indented by one space too much. It is wise to use a text editor which provides and option to show tabs and space characters, so you can sort out our jython indentation.

 

 

Solution:

 

Delete the extra space, and remember that if you want to use tabs it is best to set your editor if it is possible to use spaces for tab characters, this will save you many late nights debugging tab based indentation vs space based indentation in your jython scripts

TypeError: __add__ nor __radd__ defined for these operands

$
0
0

Jython Error: TypeError: __add__ nor __radd__ defined for these operands

heduler_jndi.myschedule,cell=LW621LX6026649Node01Cell,spec=1.0
WASX7017E: Exception received while running file &quot;f:\script\jython\schedule_mbean.py&quot;; exception information: com.ibm.bsf.BSFException: exception from Jython:
Traceback (innermost last):
  File &quot;&lt;string&gt;&quot;, line 121, in ?
TypeError: __add__ nor __radd__ defined for these operands

Reason:
Jython code was trying to concatenate an Object with a String

Offending Code:

schedMbeanO = AdminControl.makeObjectName(schedMbeanString)
print &quot;schedMbeanO=&quot; + schedMbeanO

Solution:

schedMbeanO = AdminControl.makeObjectName(schedMbeanString)
print &quot;schedMbeanO=&quot;
print schedMbeanO

ADMF0003E: Invalid parameter value

$
0
0

I was coding a jython class to alter some JVM params and I had the following error:

D:\was8dev\bin&gt;wsadmin.bat -f d:\scripts\websphere\jvm.py -lang jython -username wasadmin -password
WASX7209I: Connected to process &quot;server1&quot; on node node01 using SOAP connector;  The type of process

*** Loading Class JVMModifier...
*** Completed Loading Class JVMModifier
METHOD: verboseModeClass
JVMModifier - Modifying attributes: [-nodeName Node01 -serverName server1 -verboseModeClass false]
WASX7017E: Exception received while running file &quot;d:\scripts\websphere\jvm.py&quot;; exception informatio
.management.cmdframework.InvalidParameterValueException: ADMF0003E: Invalid parameter value server1
Name for command setJVMProperties.

Reason, well it was quite simple the name I had passed as the node name was “Node01″ instead of “node01″ all about case. But the error was very misleading as I was passing a nodeName variable and a serverName variable and the code was reporting to me the wrong parameter. I guess it got confused about how to display the appropriate param error. Well I thought I would add the error and my solution to help those jython enthusiasts trying to tame WAS.
Result:

*** Loading Class JVMModifier...
*** Completed Loading Class JVMModifier
METHOD: verboseModeClass
JVMModifier - Modifying attributes: [-nodeName node01 -serverName server1 -verboseModeClass false]
JVMModifier - Saving configuration after setting new attributes to JVM (node01:server1)
JVMModifier - COMPLETED SUCCESSFULLY

WASX7017E: Exception received while running file; exception information: com.ibm.bsf.BSFException: exception from Jython

$
0
0

While testing a jython script on WebSphere Application Server for Windows I got the following error:

C:\scripts&gt;&quot;C:/Program Files/IBM/WebSphere/AppServer/profiles/AppSrv01/bin/wsadmin.bat&quot; -lang jython -f &quot;C:/scripts/jvm.
py&quot; &quot;c:/scripts/jvm.props&quot;
WASX7209I: Connected to process &quot;server1&quot; on node LW621LX6026649Node01 using SOAP connector;  The type of process is: Un
ManagedProcess
WASX7303I: The following options are passed to the scripting environment and are available as arguments that are stored
in the argv variable: &quot;[c:/scripts/jvm.props]&quot;
*** Loading Class JVMModifier...
*** Completed Loading Class JVMModifier
METHOD: verboseModeClass
WASX7017E: Exception received while running file &quot;C:/scripts/jvm.py&quot;; exception information: com.ibm.bsf.BSFException: exception from Jython:
Traceback (innermost last):
File &quot;&lt;string&gt;&quot;, line 115, in ?
NameError: myVM

When looking at the code, I was able to see that I had a call to an object’s method. My Jython  had an error where the jython class method I was using was miss-spelt.

Error:

myJVM =JVMModifier(“LW621LX6026649Node01″,”server1″)
myJVM.verboseModeClass(“false”)
myJVM.verboseModeGarbageCollection(“false”)
myJVM.verboseModeJNI(“false”)
myJVM.initialHeapSize(“512″)
myJVM.maximumHeapSize(“1024″)
myJVM.modfy()

Solution:

myJVM =JVMModifier(“LW621LX6026649Node01″,”server1″)
myJVM.verboseModeClass(“false”)
myJVM.verboseModeGarbageCollection(“false”)
myJVM.verboseModeJNI(“false”)
myJVM.initialHeapSize(“512″)
myJVM.maximumHeapSize(“1024″)
myJVM.modify()

AttributeError: instance of ‘Class’ has no attribute ‘_ClassName__InstanceVariable’

$
0
0

When coding some jython I get the following error:

C:\scripts&gt;"C:/Program Files/IBM/WebSphere/AppServer/profiles/AppSrv01/bin/wsadmin.bat" -lang jython -f "C:/scripts/jvm.
py" "c:/scripts/jvm.props"
WASX7209I: Connected to process "server1" on node LW621LX6026649Node01 using SOAP connector;  The type of process is: Un
ManagedProcess
*** Loading Class JVMModifier...
*** Completed Loading Class JVMModifier
METHOD: verboseModeClass
WASX7017E: Exception received while running file "C:/scripts/jvm.py"; exception information: com.ibm.bsf.BSFException: e
xception from Jython:
Traceback (innermost last):
File "&lt;string&gt;", line 141, in ?
File "&lt;string&gt;", line 116, in modify
File "&lt;string&gt;", line 105, in getAttributes
AttributeError: instance of 'JVMModifier' has no attribute '_JVMModifier__eJFN'

Solution:

In this example, I had declared in my classes instance variable but it had a syntax error. AttributeError: instance of ‘JVMModifier’ has no attribute ‘_JVMModifier__eJFN’. What this means Is that the class called JVMModifier has an attribute or class instance variable that does not exist. So in this case __eJFN did not exist. This was because I had declared, self.eJFN  when self.__eJFN was being referred to in my code.


syntaxError: Lexical error at line

$
0
0

When running Jython code I get the following error.


C:\scripts>"C:/Program Files/IBM/WebSphere/AppServer/profiles/AppSrv01/bin/wsadmin.bat" -lang jython -f "C:/scripts/gen.py" "c:/scripts/gen.props"
 WASX7209I: Connected to process "server1" on node LW621LX6026649Node01 using SOAP connector;  The type of process is: UnManagedProcess
WASX7303I: The following options are passed to the scripting environment and are available as arguments that are stored in the argv variable: "

"
 WASX7017E: Exception received while running file "C:/scripts/gen.py"; exception information: com.ibm.bsf.BSFException: exception from Jython:
 Traceback (innermost last):
 (no code object) at line 0
 File "<string>", line 253
 x += indent*3 + "print "@ClassName@: COMPLETED SUCCESSFULLY";
 ^
 SyntaxError: Lexical error at line 253, column 27.  Encountered: "@" (64), after : ""

The solution is simply that the Jython string has an extra ” in the code.

x += indent*3 + ‘print “@ClassName@: Saving configuration after setting new attributes

WebSphere Jython Examples – File Handler Class

$
0
0

Very Basic example of a Jython File-Handler class


Jython File Handler Class

class FileHandler :
    def __init__(self, fileName) :
    self.fileName = fileName
    return
#endDef

# a file exists if you can open and close it
def exists(self):
    try:
        f = open(self.fileName)
        f.close()
        return True
    except:
        return False
    #endTry
#endDef

def writeText(self,text) :
    try :
        self.outputfile.write(text)
    except :
        print "ERROR writing text to file name: " + self.fileName
    #endTry
    return
#endDef

def open(self) :
    print "opening: " + self.fileName
    try :
        self.outputfile=open(self.fileName,'w')
    except :
        print "ERROR opening file name: " + self.fileName + " for writing!"
    #endTry
    print self.fileName + " was sucessfully opened"
    return
#endDef

def close(self) :
    print "closing: " + self.fileName
    try :
        self.outputfile.close()
    except :
        print "ERROR closing file name: " + self.fileName + "!"
    #endTry
        print self.fileName + " was sucessfully closed"
    return
#endDef
#endClass

==============

Example of use....

#Get handle to file
myFh = fileHandler("c:\temp\output.txt")
#open file for writing
myFh.open()
#Overwrites file as this is what we want
myFh.writeText("this is some text 1")
#close file as we have finished with it
myFh.close()

Viewing all 10 articles
Browse latest View live