Search This Blog

Oracle Fusion Middleware Administration Course

Oracle Fusion Middleware Administration Course
OFMW Admin Course

Thursday, October 27, 2011

WLST Errors and Exceptions

When first time you started using WLST you might get many of these Python based WLST Errors. Here I had collected few of them which are very simple to handle them with care. Only thing you need to understand when what kind of errors raises, and what need to do to handle them. When there is error on your flow of WLST Script or prompt don't be panic, relax for a moment then after a while take a deep breath and focus on your error and map with one of the following and do the required workaround.

In Jython we have issubclass() to check superclass, subclass relation we can verify class relationship. You can find parent-child relationship with it. As per my understanding the Error hierarchy can be defined in WLST(Jython) as follows:

This WLST(Jython) Error tree I prepared and posted for your reference, so that you can make your script in perfect manner, here you can find what is going wrong why it is happen while working out your script.
 # WLST code Block 
 # perform some tasks that may throw an exception
except ExceptionType, ExceptionVar:
 # WLST code or
 # perform some exception handling
    # perform tasks that must always be completed (Will be performed before the exception is # raised.)
 # execute code that must always be invoked

The pass statement in WLST

While writing WLST scripts, there are some situations where you need ‘do nothing’ statement syntactically. That is provided by the pass statement. When you start working on Exception handling this statement will be the first experimenting statement for you.

WLST raise statement

In WLST raise is used to generate or invoke an exception condition. The syntax of this statement allows three comma separated expressions which are optional. If no expression is present, WLST attempt to re-raise the last exception that was raised. This raise statement we can use when we need exception handling with robust scripts. When you pass the expressions to the raise statement, the first two expressions are evaluated to get the objects. These objects are then used to determine the type and value of the exception. Omitted expressions are treated as None. The third expression could be used for traceback objects.

wls:/offline> try:
...     raise Exception('SituationalResponse')
...except Exception, e:
...     print e
java.lang.Exception: SituationalResponse


This you cannot be handled with the try-except block, because it will be thrown when your syntax is not in properly arranged, that is in the statement missing indentation or improper arguments. SyntaxError could be raised when the script lines are given for parsing, it will do token by token parsing wherever the improper syntax given WLST Shell points with cap char under the token.

Now let us see the sample indentation issue that raises the Syntax Error.
wls:/offline>; try:
Traceback (innermost last):
(no code object)
at line 0
"", line 2
SyntaxError: invalid syntax

Another option for Syntax Error
This Error I have observed when I tried to migrate the WebLogic domain with createDomain() command.

wls:/offline/wdomain>createDomain('/home/backup/olddomain.jar', '/home/otherusr/domains/newdomain',’system', 'weblogic103')
Traceback (innermost last):
  (no code object) at line 0
  File "", line 1
        createDomain('/home/backup/olddomain.jar', '/home/otherusr/domains/newdomain',?system', 'weblogic103')
SyntaxError: Lexical error at line 1, column 99.  Encountered: "\ufffd" (65533), after : ""

This "Lexical error" got due to the copying from the webpage which has single quotes in different unicode value. When I retype the single quotes it was resolved.

Here in the above sample after issuing try block starting we must use a tab or 4 spaces before connect() command. When it found that is not
having proper indentation it raised the SyntaxError.


When the name used to do something like print or use in some other expression without assigning the value before it was defined then WLST will raises NameError. When first time scripting most of the time user encounters this unknowingly.

The following example might give you an idea how to resolve your issue.

wls:/offline> var1=100
wls:/offline> var3=var1+var2
Traceback (innermost last):
  File "", line 1, in ?

You can handle this kind of error with our try-except block
wls:/offline> try: var3=var1+var2
...except NameError, e:
...     print "Please check there is: ", sys.exc_info()[0], sys.exc_info()[1]
Please check there is:  exceptions.NameError var2

The beauty of handling your Exception/Error more transparent and easy to understand with sys.exc_info() list.


This error can be raised by the WLST while using the dictionary objects or map objects accessed with non-matching key.
wls:/offline> urls['b']
Traceback (innermost last):
"", line 1, in ?
KeyError: b


The ValueError is raised by the WLST shell when there is a inappropriate element is accessed in a list or a variable, that is such as the value specified for searching in the list with index() method. Removing the element which is not really exists in the list.
wls:/offline> L.index('web2')
Traceback (innermost last):
"<console>", line 1, in ?
ValueError: list.index(x): x not in list
I was working on thread and JVM monitoring script, encountered with the ValueError in different way. After storing the ThreadPool values, JVM values into local variables I was using C type of formatting to display the data in a row of Table. Some of the attribute values are Long integers, some of them plain integers some of them are strings.
 cd('/ServerRuntimes/'+ svr +'/ThreadPoolRuntime/ThreadPoolRuntime')
 thid= `get('ExecuteThreadIdleCount')`
 hog= `get('HoggingThreadCount')`
 sbth= `get('StandbyThreadCount')`
 cr =`get('CompletedRequestCount')`
 pr =`get('PendingUserRequestCount')`
 ql =`get('QueueLength')`
 th= `get('Throughput')`
        freejvm = long(get('HeapFreeCurrent'))/(1024*1024)
        totaljvm = long(get('HeapSizeCurrent'))/(1024*1024)
        usedjvm = (totaljvm - freejvm)

When I ran with all numbered values with format as %5d it was shouted as follows:
ValueError: unsupported format character ' ' (0x20) at index 23
Don't know what attribute requires which format ... Initially to resolve this display without any format for all attributes values from the MBean.
print svr, thtot, thid, hog, sbth, cr, pr, ql, th, hs, totaljvm, freejvm, usedjvm
But still ValueError was exists, when I updated with formatter it was stuck with CompletedRequestCount that was not integer type, it is actually Long integer type and that was causing the Error. So, changed the format for that attribute it resolved one issue. Now the issue with different index number came... I have an idea that, if I found all the attributes and their data types then it will be easy to fix the right format for each. I tried the following way
print type(thtot),type(thid), type(hog), type(sbth), type(cr), type(pr), type(ql), type(th),type(freejvm), type(totaljvm), type(usedjvm)
formatted accordingly the ValueError is resolved.
print '%14s %10s %5s %5s %5s %5s %8s %5s %5s %8s %5dMB %5dMB %5dMB' %  (svr, hs, thtot, thid, hog, sbth, cr, pr, ql, th, totaljvm, freejvm, usedjvm) 
So now you can take care of Values of variables for your WLST code before use them for any operation!!


You might be on MBean tree where there is no such attribute defined and you tried to access it then WLST Shell raises AttributeError. Let us see an Example you can easily understand.

wls:/demodom/serverConfig> cmo.State()
Traceback (innermost last):
  File "", line 1, in ?
AttributeError: State


The IndexError will be raised by the WLST shell, when thelist object is accessed with a out of range index value.

Let us see the example a list is defined with 5 elements

wls:/offline> L['app1', 'app2', 'app3', 'app4', 'web1']
when it is accessed with out of range index value say 7 then you get the IndexError.
wls:/offline> L[7]
Traceback (innermost last):
"<console>", line 1, in ?
IndexError: index out of range: 7


The basic python object types int, str assignments or expressions or print statements with
concatenation does not allows you, raises the TypeError.

wls:/offline> print 'Number of servers:', 5
Number of servers: 5
wls:/offline>print 'Number of servers:'+ 5
Traceback (innermost last):
"<console>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects

Thanks for reading this post, Give your feedback in comments. cheers!!

Good References:

Monday, July 25, 2011

Wanna get the status of the applications in domain

In most of WebLogic domain environments we might have seen multiple applications deployed on WebLogic servers. It is difficult to check their status when server uses high CPU utilization. We can get the complete details by giving one input i.e., target-name.

We use navigate MBean tree more frequently while using interactive mode of WLST and in scripting. Here we can call any attribute from any MBean tree by using colon ':' at the MBean tree root. Here we go with a sample of  for you who struggling to understand navigate each and every time.

Please check the below code snippet and you can change as per your requirement.

 This script will get you status of the applications which are deployed 
 in your WebLogic Domain.         
 script get you the colorful output                         
 NOTE : You need to give target name as an input to the script                
 Author: Krishna Sumanth Naishadam                         
import sys

for i in apps:
    if(sts == "STATE_ACTIVE"):
        print "\033[1;32m Status of " + i.getApplicationName() + ": " + sts + "\033[1;m"
        print "\033[1;31m Status of " + i.getApplicationName() + ": " + sts + "\033[1;m"

# set up common environment
. "${WL_HOME}/server/bin/"

read -p "Enter Target Name : " value1

"${JAVA_HOME}/bin/java" -Xmx124m -Dprod.props.file=${WL_HOME}/ weblogic.WLST $value1 $*

The lifecycle of deployment process happen in the following way:

The following Colors I had chosen for reflecting what state for a application on a server.
Status of APPNAME1: STATE_ACTIVE (Green Color)
Status of APPNAME2: STATE_FAILED (Red Color)
Status of APPNAME3: STATE_NEW (Red Color)

Please see below screenshot for exact output


Sunday, March 20, 2011

WLST Tricks & Tips

Here I prepared few of the "Tips" and some commonly useful "Tricks" for developing the huge WLST scripts. These are all the learnings which I have came across in my daily working experiments with Programming Python commands for WLST scripts. These WLST commands can be applicable from WebLogic 9.x to WebLogic 10.3.6 and latest trending WebLogic 12c as well.
  1. Tip 1: Know about Where are you in WLST?

  2. On some situations you might need a clarity about which WebLogic version you are using. WebLogic 11g (10.3) has different subsequent versions 10.3.1,10.3.2,10.3.3 and 10.3.4, for all these the directory structure is ~/Oracle/Middleware/wlserver_10.3 which does not tells you about sub versions. Here WLST  is having a solution for this problem,

    You can find the current WebLogic version to which WLST is connected.

    wls:/offline> print version
    WebLogic Server  Fri Apr 9 00:05:28 PDT 2010 1321401

    How do you know that the WLST Shell running on which JVM version? The simple solution is you this following Python command that will gives you:

    wls:/offline> sys.platform

  3. Tip 2. How to know Jython version is used by WLST?

  4. To get the Jython version you can use sys.version_info method that will returns. or you can use sys.version exact version.

    wls:/offline> import sys
    wls:/offline> sys.version_info
    (2, 2, 1, 'final', 0)

    Tip 3. Introspection in WLST

    You might understand that using WLST provided help() sometimes you cannot reach your desired level of script code. Some thing that won't be documented but you might need it to develop the prototype in your WLST script. Often I found this could be a need, most helpful way to reach depth of WLST classes, modules, functions. Best way is we need to use Python introspection methods. It is a wonderful way to resolve your coding clues to use best performing script as outcome.

    In some of the situations, I felt using Jython (Java method) is lengthy than using Python. When Python giving you desired outcome in two lines of code why do you choose Java imports and classes and code become 6-10 lines.

    You might be confused sometimes, brain storm about something why a MBean not working or giving the value of an attribute etc. In your mind there could be a question "what is this actually??" Best solution for this is using Python introspection built-in methods.

    dir([WLST/Python Object])
    If your WLST MBean or module or a function has documented then you use the following to get that:

    In Jython there could be classes or interfaces

    Tip 4. Naming Rules for WLST

    WLST script can have names are case sensitive and cannot start with a number.  They can contain letters, numbers, and underscore symbols. Let us see few examples here:
     state  State  _state  _2_state_  state_2  StatE

    Most of us face an issue what name makes sense for a variable, module or classwhile writing the WLST scripts. Just like Java Language you can follow specific naming rules, we can also find keyword list available in WLST with the following commands

    wls:/offline> import keyword
    wls:/offline> keyword.kwlist
    ['and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'yield']

    Modules, packages: use lowercase
    Classes: use Capitalized first letters in the Words also follow for exceptions that you create
    Methods, attributes: use lowercase_words
    Local variables: use alphanumeric i, j, sum, x0, etc.
    Globals: use alphanumeric long_descriptive_names

    wls:/offline> sys.modules
    {'': , ...'sys': sys module, '': }

    Introspection reveals useful information about your program's objects

    Tip 4 Write a readable script

    While writing a script think about the human readers, Question yourself can you still read your own code ???
    next month?
    next year?
    • Be consistent (but not too consistent!)
    • Use white-space judiciously
    • Write appropriate comments
    • Write helpful doc strings -- not stories or novels
    • Confirm to the existing style even if it’s not your favorite style!
    • local consistency overrides global
    • Update the comments!!and the doc strings!!!

    """Brief one-line description.
    Longer description, documenting
    argument values, defaults,
    return values, and exceptions.

    When to use classes in WLST? (...and when not!)
    If your script objective is going to have multiple object creation then go for Object-Orientation.

      • You could choose class members or attribute  at the first time
      • name clashes between attribute

    Tip 5 Convene print statement with str()

Most of us from Java/JEE development background common attitude is that using the + operator overloading for strings. Sometimes your WLST script might need to have a print statement, that could include values from a variable or some mathematical expression that might be int type or some other object type. Then such cases, better to use that variable type must be converted to string type by using Python built-in function str() as shown :

print 'Heap Size' + str(totalHeap)

Tip 6: Create single properties file

Every Middleware admin whoever uses this WLST in their environment builds, they must create/use a single properties file where you can have:

  1. Domain properties - username, password, admin url, cluster list
  2. Database configuration properties
  3. JMS configuration properties
  4. WorkManager properties
  5. Monitoring Threshold properties

Tip 7: Using time in WLST

In my daily news updates from social medias I found in in the Python community doing excellent there is lots of news about the changes happening with Python programming. One of the blog found very nice examples with date and time functions in Python this can be applicable for our WLST too.

Setting UTC time zone in Python

WLST Tricks

We have come across many situations where it is simple trick works faster to work with WLST scripting. some of them collected here and future also we will update this WLST tricks

Trick 1. Multiple Assignment

In WLST you can assign multiple variables with corresponding multiple values at the same statement or command line.

wls:/offline> cl, ms = ['appclstr','webclstr'], ['app01','app02','web01','web02']
wls:/offline> cl
['appclstr', 'webclstr']
wls:/offline> ms
['app01', 'app02', 'web01', 'web02']

Trick 2. Connect admin without Credentials

When you use storeUserConfig() command for your WebLogic domain environment, the trick here is when you don't specifying any arguments such as user security file, key file paths. WebLogic system automatically generates the following two files:

For example, Let us assume your user name is 'padmin' then storeUserConfig() command will generates two files as:

Once you got this auto-generated files in you home ($HOME in Unix) directory, WLST Shell automatically detects its existance from this location. You don't need to give the userConfig, Key file paths while connecting. Simply you can connect by giving the adminurl as url value.

wls:/offline> connect(url='t3://')
Connecting to t3:// with userid weblogic ...
Successfully connected to Admin Server 'wadmn' that belongs to domain 'mydomain'.

Warning: An insecure protocol was used to connect to the
server. To ensure on-the-wire security, the SSL port or
Admin port should be used instead.

Trick 3: Command Trials

The interactive mode is great for getting instant feedback on the behavior of each WLST command. Having the whole startup, connection, session-init is time-consuming and the interactive mode of WLST avoids this.

First time if you are making a script better idea is have duplicate windows of the host. In one window you can edit and save according to your required changes, on the other hand you can execute the file with execfile('').

Trick 4: Using loadProperties

One of my blog follower Raghu asked me how to use properties in the WLST script. Though I had used different types of properties from properties file, but his requirement is something different he want to reuse the WLST script only by changing the properties file.


Here is the WLST script snippet that uses above defined properties using loadProperties() built-in function call
print serverlist[1]

for i in serverlist:
    print i

Remember that properties are just like Java language properties or C/C++ define constants, which holds name, and corresponding the string values. So when you store portno in properties file better convert using int().
Hope this is useful for your reusable scripts.

Trick 5: How to debug WLST script?

The best way to identify the WLST script bugs using dumpStack(). This works only when you are running interactive mode. If you found a script (such as my blog) or from somewhere after you update all properties you wish to test and it doesn't works! then you wish to debug it.

1. Using simple print variable values
2. Using Python exception values
3. Double check indentations
4. Casting values (converting values str to int or str to bool)

Some of the cases you need to understand that casting fails the values are not allowed to change because WLST variables are created in Runtime. The datatypes are strong type like Java and C++ languages and dynamic type while running it will be assigned to a datatype.

You can enable debug flag at the time of invocation of WLST shell.

java -Dpython.verbose=debug weblogic.WLST

Also you have one more option using debug("true") or set('DebugEnabled', 'true') in the starting of WLST script that will force debug output

If you are using OEPE (Eclipse for developing WLST) then you have much scope to debug every variable content. Right click on the WLST script select 'Debug As', choose 'WLST run' from the list Menu. Please check the screenshot that give you more clear idea on this Oracle link.

Trick Cancel the Edit in WLST

Today while working on WLST in interactive mode to fix the JMS configuration issue, sometime you start editing the configuration you might need to undo the changes you did on the edit tree. This is possible using cancelEdit() give the answer y to confirm when it prompts you. Else you can use cancelEdit('y') as a trick.

Trick 6: Suppress Junk Output in WLST

There is junk when you capture the list from ls(returnMap='true') command execution.
If you are running WLST in *nix based environment you can use /dev/null path for suppressing the junk outputs as shown below redirect command.


Trick 7: Resolve indentation/dedent issue with vi setting

WLST Code copied from NotePad++ to vi editor tabspace issue
when you write few lines in the notepad++ it takes 4 spaces as tabspace, but in the vi editor it is 8 it mismatches and cannot fit into the block. So when run the script it throws 'dedent' issue. To resolve this in vi editor you can set the tabspace=4

: set tabspace=4

Keep writing your valuable comments and great suggestions to improve this blog tutorial ...

  1. 1. Dive into Python
  2. Python Library link

Monday, February 21, 2011

Configuring GridLink DataSources

WebLogic 10.3.4 is having new feature as High availability and fail over control with Oracle Notifying Service (ONS) as client at WebLogic sever side. Which enables your environment to track if one of RAC node is down or Listener down.



set('JNDINames',jarray.array([String('GLDS01')], String))


cmo.setTestTableName('SQL SELECT 1 FROM DUAL\r\n\r\n')



set('Targets',jarray.array([ObjectName('com.bea:Name=appclstr,Type=Cluster')], ObjectName))



Before you configure this, make sure ONS service configure at RAC nodes. So, please confirm it from your ORACLE DBA. One more things, this is applicable only when your environment have Oracle Database 10.2.+ for RAC.

This GridLink datasource is the alternative for Multi datasource. You don't need to configure individual data sources for each node. In this GridLink you can enter all the RAC node details at once. Targeting and testing is same as generic data source you can verify on your WebLogic console.

Best References

Thursday, February 17, 2011

OEPE the best WLST Editor

Now we have, Oracle given a nice GUI editor for WLST scripts. I started looking about it one of my blog commenter Lukas was asked me about it. Oracle released two versions of this Eclipse editor:
  1. Eclipse 3.6 (Helios) Edition
  2. Eclipse 3.5.2 (Galileo) Edition
It has built support for Python scripts and PyDev. Recently I had downloaded new OEPE-Galileo-All-In-One- It is really “All in One” why because it has connectivity to WebLogic Server Local/Remote options with all categories of versions supported by WLST. It is included WLST MBean Explorer, built-in WLST Help provided in one of tab.

Here I am going to tell about that what you need to look in this because introductory blog already given by Edwin Biemond from Oracle

Video blog...
There is nothing to know about much about hidden MBean hierarchies. WLST on OEPE (Eclipse) makes more fun in creating new scripts. More over the OEPE Templates are awesome!! God bless this template creator.  Oracle WLST people given commonly used scripts as templates. Which makes you no efforts to write the line-by-line script writing. GUI makes more work in less time meaning increasing productivity and performance!!!

Ready made Templates
OEPE gave us the following templates as ready-made script templates. You need to change the values or parameters to whatever you want to name for your environment or WebLogic domain. 

  1. Default: WLST online
  2. Create Basic WebLogic Domain
  3. Create WebLogic Cluster
  4. Create WebLogic Domain with JMS and JDBC Resources
  5. Configuring JMS System Resource
  6. Configuring JDBC DataSource Delete  JDBC Data Source
  7. Delete JMS System Resource
  8. Delete WebLogic Cluster
You might be using WebLogic portal or WebLogic Integration or some other WebLogic domain these are core common scripts templates can be applicable to any of them.

Most of the developers requires the Deleting JDBC resources and want to create a fresh DataSource with changed database parameters.

In production environment some of the sites you might need to remove the machines due to their utter performance. “Delete WebLogic Cluster” is the wonderful script for you. You need to give the managed servers list, cluster(s) you want to remove from the domain.
Cons of OEPE
  1. To run OEPE on your desktop requires good amount of MEMORY (RAM).
  2. Sometimes iexplorer stuck you cannot open OEPE anyway it is Windows issue.
  3. JVM Settings of eclipse.ini file need to be updated according to your operating environment. Anyway I found the best reference to solve JVM settings issue at
Expecting more exciting things from WLST users so…keep writing your comments, updates about OEPE using WLST.

In these amazon ads you can click on 'Look inside' give you some idea about the above books. And don't forget to enjoy the sample chapters of these books.

While working on eclipse there could be need to pass arguments to your WLST script. Yes!! You can do that goto Run As options select Run Configuration. In the Run Configuration window select the Arguments tab,  you can give Program Arguments.

Good References:

Popular Posts

Oracle WebLogic Administration Course

Oracle WebLogic Administration Course
WebLogic Training