Monday, April 28, 2014

Test 'me' ..err cookies are not that complex to test with Selenium.

If we talk in simple terms Cookies are some thing which parents always teach their child 'Not to have'.
And same applies to some web sites .They can make life tougher of user when cookies are hiding in the web pages and no one can understand 'what the heck is making my web page to react so weird!!!'

Let me first start why cookies are required and why/ when are not required. There are several types of cookies (of course not chocolate , strawberry , butter ,etc ) which can comes and lives on the web.
For an example, if I want to log into a system and want to stay in the system for ever until I explicitly log out from it , then to maintain this session go live I always requires some sort of cookies which will make this happen for me. This you can count as an advantage , with out a doubt !
But what about this , when I am working on a web page and trying to search for some one and it will navigate me to some stranger's profile which has no connection with the name i searched for . It is all about the game which cookies does for us :)
Without a doubt such behaviour will cause multiple issues when we talk in terms of automation.
Lets talk more in terms of selenium , how we can get rid of extra unwanted cookies from web page which are not required at all while executing test cases.
Ofcourse there are some manual actions which we can do to remove cookies from browser but yeah its a tedious task and then it will not add any value to our test automation framework.
We can start making a new maven project (following the concepts of Page Object model) and make a class in such format:

Now make a class which can test cookies in the application you are testing, or any sample application like http://www.compendiumdev.co.uk/selenium/search.php.
Now all you need to do is some basic set up require to make your application interact with selenium server.
You will require Junit to write test cases and class as a template to write test cases.
Start with instantiating the driver:
@BeforeClass
public static void startChrome() {
driver = new FirefoxDriver();
}
 
@AfterClass
public static void closeFireFox() {
driver.quit();
}
Now you need to open the application such that it will navigate user to the required URL. For this you need a method :
@Before
public void openTestURL() {
driver.navigate().to(testURL); // navigate to URl which is required.

And then what you need to do is to wait for page to get load and then delete all cookies which will come on run time on this web page

wait = new WebDriverWait(driver, 10); //Implicit wait appiled to driver
driver.manage().deleteAllCookies();// delete all cookies which is in browser for fresh start

Thats not all , what if the page has more cookies ?
For this you need to make a set of all such cookies and remove them like this :
@Test
public void searchAndCheckForCookies() {
queryBox = driver.findElement(By.cssSelector("input[title='Search']"));
queryButton = driver.findElement(By.name("btnG"));
queryBox.clear();
queryBox.sendKeys("monkey buns");
queryButton.click();

Set<Cookie> cookies = driver.manage().getCookies();
for (Cookie aCookie : cookies) {
if (aCookie.getName().contentEquals(
"seleniumSimplifiedSearchNumVisits")) {
assertEquals("should be my first visit", "1",
aCookie.getValue());
}
if (aCookie.getName().contentEquals(
"seleniumSimplifiedSearchLastSearch")) {
assertEquals("should equal 'monkey buns'", "monkey buns",
aCookie.getValue());
}
}
}

And if you want to remove any specific cookie/s from the web page then you can use this method :

@Test
public void getOneSpecificCookie() {
queryBox.clear();
queryBox.sendKeys("monkey buns");
queryButton.click();
refreshPageObjects();
queryBox.clear();
queryBox.sendKeys("testing 123");
queryButton.click();

Cookie cookie = driver.manage().getCookieNamed(
"seleniumSimplifiedLastSearch");
// %20 is a space in the raw data that is returned
assertEquals("should equal 'testing 123'", "testing%20123",
cookie.getValue());
}
}


Lets do Fitnium together!

In my last post on fitnium , I have described all the basic needs which one need to know when he/she is starting or even thinking to work on fitnium.
Those are some very basic concepts which user should know before getting into the technicalities of the tool.
So as of now , we know why and when to use fitnium and along with this the base tools which fitnium uses in the backend while executing the test cases.
Lets start with how we can start working with this weapon of testing.
Fitnium is a free tool and can be downloaded from the fitnium website (Source http://www.fitnesse.org/ ).
It is a simple , very easy-to-use tool on which you can start writing test cases if you have some basic knowledge of any one the popular programming languages like Java, Ruby , etc.
It requires a sinlge click download to start working on fitnium , you can download the jar from http://sourceforge.net/projects/fitnium/files/latest/download
. Once its downloaded at your local all you need to do is to extract this rar file into a folder.
You will get a structure like this :

Here you can get 2 executables , one is fitnium librarry having all libraries fitnium requires to run test suites and cases. The other jar is the one which will be of more importance , all we need is to execute this jar. Like this:
java -jar fitnesse.jar
It will give some obvious problems like :

As generally in local systems everything by default works on 8080 port , so no two person can sit on one seat . Hence system will complain and ask for some new port, You can simply change the port to some other port by using -p command :

Once this is done , you can see awesome UI on your local system and can explore new things . UI will looks like this :

Will continue how we can write our test scripts in next blog, till then stay tuned :)


Thursday, April 24, 2014

They say "How about the architectural difference between Selenium versions"

I have seen many people asking a repetitive question in interviews if they see Selenium written on any Curriculum Vitae of a Test Engineer. Though I believe theoretical and conceptual knowledge is equally important as hand-on experience. As a part of hiring panel I have observed this as a pet question of our hiring team : 'How about the architectural difference between Selenium versions.' Of-course , once they are done with questions like 'What you know all about selenium' ?
Selenium generally comes in four different flavours :
Selenium IDE , Selenium RC , Selenium Grid and Selenium Webdriver.
I will be sharing the best answer I got and the research which I did so as to understand the architecture of selenium.

Selenium Remote Control:
Selenium RC or Selenium 1 is the first version of Selenium which is equally efficient as Selenium Webdriver. But there is a difference in architecture which both has. Along with a fact that selenium RC requires a server jar start-up every-time user wants to execute test cases/suite. This is just a one time effort which is required only in selenium RC , unlike Selenium Webdriver.

Selenium RC works on the principle of client - server . The client sends the request ( in Programming languages like Java , Python ,etc ) to the Server . The requests are in the form of commands like click , select , wait , etc.

And here Server takes the responsibility of granting the request to the Web browser. As we know Selenium is a Web Automation tool so the job will complete only when browser is able to respond on the requests which client is asking for.
At browser the Selenium core is residing which actually performs Java Script injections and hence-forth requests get executed.

RC-Selenium.PNG


Selenium Webdriver:

There are some differences which user can observe while working with Selenium Webdriver or if user is switching from Selenium RC to Selenium Webdriver.
First of all , it does not need any over-head like server start up etc.
If we talk about architecture then the major difference is Selenium Webdriver API is responsible for storing all commands and conversion of the commands in JSON format. The flow is Client sends the request in a Programming language and sends the command to the selenium Webdriver. This request is then send to the Selenium API where-in Selenium API restores the commands in the JSON format and send the request from the JSon format to the http, RESTful service. This conversion happens on the browser level where-in all the commands will work. Commands like select , click , etc which will be placed in the test suite and test case.


Webdriver-Selenium.PNG

Selenium Grid:
Selenium Grid is used majorly when user wants to run test cases parallely at the same time on same browser or on different browsers .

Here , There would be a selenium grid -hub where selenium server needs to be running and up all the time. All other machines which connects this machine will work as a client as this hub will work as a server to all the clients. Client will send the request to the server - hub and hub is responsible to cater all requests and respond on the all requests which are coming from the clients.




Happy testing ! :)

Caused by: java.lang.NoClassDefFoundError: javax.wsdl.Definition

Exception Caused by: java.lang.NoClassDefFoundError: javax.wsdl.Definition

Reason : This exception occur while accessing  SOAP client in java application from jdeveloper, and it is due to the missing orawsdl.jar.

Workaround :  Add the jar file to the project classpath. you can find this jar file at

%JDEV_HOME%\oracle_common\modules\oracle.webservices_11.1.1\orawsdl.jar

Also add this jar in the deployment profile.

Caused by: java.lang.ClassNotFoundException: oracle.j2ee.ws.saaj.soap.MessageFactoryImpl

Exception Caused by: java.lang.ClassNotFoundException: oracle.j2ee.ws.saaj.soap.MessageFactoryImpl

Reason : This exception occur while accessing  SOAP client in java application from jdeveloper, and it is due to the missing orasaaj.jar.

Workaround :  Add the jar file to the project classpath. you can find this jar file at

%JDEV_HOME%\oracle_common\modules\oracle.webservices_11.1.1\orasaaj.jar

Also add this jar in the deployment profile.

Monday, April 21, 2014

Previously reported error [IllegalStateException in o.i.explorer.IconOverlayTracker$NodeWatcher:802]

Sometimes when you open the Jdeveloper and try to move on to the folder or open any file you are getting the following error

Previously reported error [IllegalStateException in o.i.explorer.IconOverlayTracker$NodeWatcher:802]

and you are not able to do any activity.

Solution:

  1. Go to Tools -> Preferences -> Versioning -> Sub Version -> General
  2. Uncheck the "Use Navigator State Overlay Icons" and "Use Navigator State Overlay Labels"
  3. Restart the Jdeveloper.

Sunday, April 20, 2014

How to add syntax highlighter to blogger


Syntax Highlighter is a utility used to highlight the code from rest of the content in a web page so that the code readability is enhanced.In this blogpost we are going to add syntax highlighter to blogger.

SyntaxHighlighter by Alex Gorbatche is one of the most popular syntax highlighter available.
It is developed in javascript and can be easily installed in the blogger blogs.
It is used by Apache, Aptana, Wordpress, Smashing Magazine and others.
It supports almost all the major languages used.

It is highly modular in architecture and there are different javascript files for highlighting different languages code.For example for highlighting javascript code you need to include shBrushJScript.js
The javascript files used for different languages is know by alias of shBrush or Brush files.

There are two flavors of this plugin.

1. In the first flavor all the brushes you need will be loaded at once whether you are going to utilize it in that page or not.
2. In the second flavor the brushes that are actually needed will be only loaded.This is lazy loading of the brushes files.

Setup

For both the flavor we need to include the shCore.min.css, any theme css  and shCore.min.js

 
<link href='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shCore.min.css' rel='stylesheet' type='text/css'/>

<!-- Default Theme -->

<link href='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shThemeDefault.min.css

' rel='stylesheet' type='text/css'/> 

<script src='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shCore.min.js' type='text/javascript'/>

Before continuing further go to your blog dashboard, click on the template, then edit HTML and go to the </body> tag in the template.
All the code mentioned in the below flavors need to be pasted just above the </body> tag of your template

1. First Flavor

In the first flavor we need to include individually the brushes that we required. If we want to highlight javascript code we include shBrushJScript.min.js
 
<script src='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushJScript.min.js' type='text/javascript'/>
For highlighting HTML / XML  we need to include shBrushXml.min.js
 
<script src='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushXml.min.js

' type='text/javascript'/>
 Then we need to start the plugin
 
<script type="text/javascript">

     SyntaxHighlighter.all()

</script>

Overall Code

<!-- Core css -->

<link href='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shCore.min.css' rel='stylesheet' type='text/css'/>

<!-- Default Theme -->

<link href='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shThemeDefault.min.css

' rel='stylesheet' type='text/css'/> 

<!-- Core javascript-->

<script src='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shCore.min.js' type='text/javascript'/>

<!-- Javascript brush-->

<script src='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushJScript.min.js' type='text/javascript'/>

<!-- HTML brush-->

<script src='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushXml.min.js

' type='text/javascript'/>

<!-- Start the syntax highlighter-->

<script type="text/javascript">

     SyntaxHighlighter.all()

</script>


2. Second Flavor

In the second approach we will include an Autoloader script. In that script we will tell which brushes we are going to use and where that brushes javascript files are located. This autoloader will only load those brushes files that are being actually used in the page rather than loading all the brushes.
 
<script src='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shAutoloader.min.js' type='text/javascript'/>
We start the plugin by using below javascript
 
<script type='text/javascript'>

      SyntaxHighlighter.autoloader(

        &#39;javascript  //cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushJScript.min.js&#39;,

        &#39;html            //cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushXml.min.js&#39;

      );

      

      SyntaxHighlighter.all();

      </script>

Overall Code

<!-- Core css -->

<link href='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shCore.min.css' rel='stylesheet' type='text/css'/>

<!-- Default Theme -->

<link href='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shThemeDefault.min.css

' rel='stylesheet' type='text/css'/> 

<!-- Core javascript-->

<script src='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shCore.min.js' type='text/javascript'/>

<!-- Autoloader javascript-->

<script src='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shAutoloader.min.js' type='text/javascript'/>

<!-- Start the autoloader script and syntax highlighter -->

<script type='text/javascript'>

      SyntaxHighlighter.autoloader(

        &#39;js jscript javascript  //cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushJScript.min.js&#39;,

        &#39;xml html            //cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushXml.min.js&#39;

      );

      

      SyntaxHighlighter.all();

      </script>


Usage

Now wrap the code that you wanted to highlight within <pre class="brush: javascript"></pre> like
 
<pre class="brush: javascript">

function Employee(){

    this.getName = function(){

            console.log("Calling getName of Employee class");

    };

};

</pre>


Themes

There are various themes present for the syntax highlighter.We just need to replace it with the default theme css in our code Some of them are

Default    (shThemeDefault.css)

<link href='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shThemeDjango.min.css' rel='stylesheet' type='text/css'/> 


Django    (shThemeDjango.css)
 
<link href='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shThemeDjango.min.css' rel='stylesheet' type='text/css'/> 

Eclipse    (shThemeEclipse.css)


<link href='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shThemeEclipse.min.css' rel='stylesheet' type='text/css'/> 


Emacs    (shThemeEmacs.css)

<link href='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shThemeEmacs.min.css' rel='stylesheet' type='text/css'/> 


Fade To Grey    (shThemeFadeToGrey.css)

<link href='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shThemeFadeToGrey.min.css' rel='stylesheet' type='text/css'/> 


Midnight    (shThemeMidnight.css)

<link href='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shThemeMidnight.min.css' rel='stylesheet' type='text/css'/> 


RDark    (shThemeRDark.css)

<link href='//cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shThemeRDark.min.css' rel='stylesheet' type='text/css'/>


All the files used for this syntax highlighter is hosted on cdnjs (public cdn for javascript) To find more brushes and themes browse https://cdnjs.com/libraries/syntaxhighlighter Special thanks to SyntaxHighlighter creator

Alex Gorbatchev for this very useful plugin.

Kindly share your feedback in the comments section

Friday, April 18, 2014

Fitnium - What a Wonder!

Den her Romeo bløder
Men du kan ikke se hans blod
Det her er kun følelser
Som denne gamle hund gravede op



Ce Roméo saigne
Mais on ne peut voir son sang
Ce ne sont rien d'autre que quelques sentiments
Que ce vieux chien a réveillé


Bu Romeo kanıyor
Ama kanını göremezsiniz
Bazı duygulardan fazlası değildir
Bu yaşlı köpeğin tekmelediği


Nice song , yeah !!!


Which one of the above translation you find easy to understand. And how you can actually make this understand to all other unheralded persons who does not know ‘Always’ song or Bon Jovi for that matter.
The answer is you will translate the same in to a common language which everyone can understand like ‘English’ in a similar manner like this :


This Romeo is bleeding
But you can't see his blood
It's nothing but some feelings
That this old dog kicked up


I am going to talk about a tool which does the same but other way around, in this post.
Fitnium is combination of FitNesse and Selenium, providing a domain specific language that allows non-developers to write selenium tests in plain english that are executed through the Fitnesse framework.


This tool basically focused and covers integration and acceptance testing along with the web browser testing .It is a fusion of tool one which has capability to automate browser and other which can perform acceptance testing.
Selenium comes in 3 various forms: Selenium IDE which comes as an add on to browser FF only.
Selenium RC - in which you can write your code in programming languages like java and by just starting server on your local you can imitate user actions.


Selenium Grid : It gives the capabilities to user to perform different test steps parallely in multiple browsers and machines.


Selenium Webdriver which is the latest version of selenium and on top of selenium RC it doesn't require any browser start up. And you can start making your test suite in framework like Page object model , other approaches to make framework depends on how you want to fetch data either from keywords directly or data -driven or hybrid which would be the mixture of both.


Other tool which fitnium has is fitnesse which works on the principle of wiki.Fitnesse is an Acceptance Testing Framework, designed to be implemented ideally at start of a project, when user stories and scenarios are being defined.  Fitnesse works on the principle of Test Driven Development(TDD) where tests are written before the actual code. This can further be used as a reference of Acceptance Test Driven Development (ATDD).
It uses combinations of fit and slim. All the commands work on these principles.
Both selenium and fitnesse are easy to install on local . It just needs a jar which get downloaded on local and will drive the further set up automatically.
Fitnium thus combines both the features which selenium and fitnesse provides henceforth user can actually perform UAT and Web automation on setting up fitnium. Fitnium follows the principle of BDD for writing test cases which are in simple english format.
Fitnesse concentrate on the correct actions of Business Logic. Fitnesse does this without the need for a GUI, but it emphasis is much spread out than a single building block of effort.

Wednesday, April 16, 2014

OOP in Javascript

In this post we are going to discuss the object oriented side of Javascript and how it is different from the traditional OOP approach.

Class
Javascript is prototype based language and it doesn’t contain any class keyword to demonstrate the concept of Class. However in Javascript the concept of class can be easily demonstrated by using Functions. Defining a class is as simple as defining a function in Javascript.
Example
Function Employee ( ) { };
 
Object
To create the instance of a class (function) declared we can use “new” operator.
Example
function Employee(){ };

var emp1  = new Employee();
var emp2  = new Employee();
 
Constructor
In Javascript there is no need to explicitly define constructor method. Everything inside the function gets executed at the time of instantiation. In Javascript we have constructor as a property which return a reference to the object function that created the instance's prototype
Example
function Employee(){
    console.log("Employee instantiated");
};
var emp1  = new Employee();
// In the console Employee instantiated will be printed.
 
Property
Variables declared inside class is a property. Each instance of the class will have those properties.
Inside class(function) property is accessed by using “this” keyword and outside the class it can be used by instanceName.propertyName.
Example
function Employee(name){
    this.name = name;
};
var emp1  = new Employee("Ankit");
console.log("The Employee Name Is : " + emp1.name);
//This will print The Employee Name Is : Ankit in console
 
Methods
Methods are like properties except however they are functions and defined as functions.
Example
function Employee(name ){ 
        this.name = name;              
        this.getName = function(){
               return this.name;
        };
};

var emp1  = new Employee("Ankit");

console.log("The Employee Name Is : " + emp1.getName());
//This will print The Employee Name Is : Ankit in console
 
Prototype
Every function has a prototype property and it contains an object. We can add methods and properties to this empty object.
Example
function Employee(name ){ 
        this.name = name;              
};

Employee.prototype.getName = function getName(){
               return this.name;
    };

var emp1  = new Employee("Ankit");

console.log("The Employee Name Is : " + emp1.getName());
//This will print The Employee Name Is : Ankit in console
 
Inheritance
Javascript supports single class inheritance by using prototype property.
Example
function Employee(){
    this.getEmpId = function(){
            console.log("Fetching emp id");
    };
};

function Manager(){
    this.getManagerId = function(){
        console.log("Fetching Manger id");
    };
}
Manager.prototype = new Employee();// Inheritance
var manager = new Manager();
manager.getEmpId();// Fetching emp id
manager.getManagerId();//Fetching Manger id
 
Overriding
Example
function Employee(){
    this.getName = function(){
            console.log("Calling getName of Employee class");
    };
};

function Manager(){
    this. getName = function(){
        console.log("Calling getName of Manager class");
    };
}
Manager.prototype = new Employee();// Inheritance
var manager = new Manager();
manager.getName();// Calling getName of Manager class is printed

Multithreading in Javascript using Web Workers

In the past JavaScript use to be single-threaded, meaning multiple scripts cannot run at the same time due to which UI can block many times.
To overcome this problem now Web Workers have been introduced. Web Workers run in an isolated thread.

There are two types of web worker.
1. Dedicated web worker
2. Shared web worker

What is the difference between the two

Dedicated Workers are linked with the script that created them but Shared workers are created so that any script running in the same origin can communicate with them, either by the URL of the script used to create it, or by name.

How to spawn a dedicated worker and communicate with it.

var dedicatedWorker = new Worker('task.js');

The task.js file is now async loaded and the new dedicated worker is available.
In case of task.js file is not present, the worker will fail silently.

After the spawning of the worker thread we can start worker by using postMessage()

dedicatedWorker.postMessage();

postMessage method can accept a string or JSON depending upon the browser support.
We communicate between worker and its parent page through message passing.
We define a listener in the worker as well in the parent page so that both can communicate with each other by passing messages.

Parent page

var dedicatedWorker = new Worker('task.js');
dedicatedWorker.addEventListener('message', function(e) {
console.log('Message replied by Worker : ', e.data);
}, false);
dedicatedWorker.postMessage("Hi Worker");

task.js

self.addEventListener('message', function(e) {
console.log("Message received by Worker : " + e.data);
self.postMessage("Hi Master");
}, false);

Console
Message received by Worker : Hi Worker
Message replied by Worker : Hi Master</code>

We can terminate a web worker by calling the terminate method

dedicatedWorker.terminate();

How to spawn a shared worker and communicate with it.

page 1


var sharedWorker = new SharedWorker('task.js');
sharedWorker.port.addEventListener("message", function(e) {
console.log('Page 1 received message: '+ e.data);
}
}, false);
sharedWorker.port.start();
// post a message to the shared web worker
sharedWorker.port.postMessage("Master 1");

page 2

var sharedWorker = new SharedWorker('task.js');
sharedWorker.port.addEventListener("message", function(e) {
console.log('Page 2 received message: '+ e.data);
}
}, false);
sharedWorker.port.start();
// post a message to the shared web worker
sharedWorker.port.postMessage("Master 2");

task.js

var ports = [] ;
self.addEventListener("connect", function (e) {
var port = e.ports[0];
ports.push(port);
port.start();
port.addEventListener("message",function(e) {
port.postMessage("Reply from SharedWorker to: " + e.data + ". Total number of connections : " + ports.length)
});
}, false);

When the page 1 loads it starts the shared web worker.In console the output is

Reply from SharedWorker to: Master 1. Total number of connections : 1

When the page 2 loads the console would be

Reply from SharedWorker to: Master 2. Total number of connections : 2

Features Available to Workers

Web workers only have access to a subset of JavaScript's features:
  The navigator object
  The location object (read-only)
  XMLHttpRequest
  setTimeout()/clearTimeout() and setInterval()/clearInterval()
  The Application Cache
  Importing external scripts using the importScripts() method
  Spawning other web workers

Workers do NOT have access to:

  The DOM (it's not thread-safe)
  The window object
  The document object
  The parent object

Metaprogramming in Java : Java code that writes code

Metaprogramming is the ability of the program to write or modify the other program (or themselves) as their data.
It is a programming approach which outputs another program. There are many ways in which metaprogramming can be implemented however we are going to discuss the one way to do so in java using byte code manipulation.

The code that we are going to generate programmatically is below
package in.xebia.metaprogramming;

public class ToBeGeneratedCode implements Cloneable {
   public String name;
   public ToBeGeneratedCode() {
      System.out.println("Constructor");
   }
   public String lowerCaseName() {
      return name.toLowerCase();
  }
}
In this approach we are going to generate a program from our code using byte code manipulation, utilizing javassist library.

Through Javassist Java programs can create a new class file or modify an existing one at run time when the JVM loads. Javassist provides two kinds of API, one is source code level while the other is byte code level. The major advantage of Javassist is that it can ease the developers works who are not comfortable with Java bytecodes hence giving the power of ByteCode instrumentation to everyone. Javassist methods helps in compiling the source code to Java bytecode while instrumenting hence one can avoid writing ByteCode directly.

Javassit is currently heavily used by hibernate framework for constructing proxies which are lazily loaded along with various different frameworks

The starting point of Javassist program is to get a CtClass which represents a compile class through javassist.ClassPool class.
javassist.ClassPool class acts much like a classloader moreover providing us ability to instrument classes.

In Javassist CtClass stands for compile time class. It is a handle for dealing with a class file.CtClass object is obtained through ClassPool in Javassist.

ClassPool pool = ClassPool.getDefault();
CtClass toBeGeneratedCode = pool.makeClass("output.GeneratedCode");


Once we get a CtClass object we add to it whatever we want our generated code to be like.

To add a modifier to our class we use setModifiers method.


toBeGeneratedCode.setModifiers(Modifier.PUBLIC);


Now we will make our newly generated class to implement interface by using addInterface method


toBeGeneratedCode.addInterface(pool.get("java.lang.Cloneable"));


In the similar way constructor, field and methods are added.


// Creating a constructor
CtConstructor toBeGeneratedCodeConstructor = new CtConstructor(
new CtClass[] {}, toBeGeneratedCode);
toBeGeneratedCodeConstructor .setBody("System.out.println(\"Constructor\");");
toBeGeneratedCodeConstructor.setModifiers(Modifier.PUBLIC);
toBeGeneratedCode.addConstructor(toBeGeneratedCodeConstructor);

// Creating a new field
CtField toBeGeneratedField = new CtField(pool.get(String.class
.getName()), "name", toBeGeneratedCode);
toBeGeneratedField.setModifiers(Modifier.PUBLIC);
toBeGeneratedCode.addField(toBeGeneratedField);

// Creating a method
CtMethod toBeGeneratedMethod = CtNewMethod.make(
"public String lowerCaseName() {return name.toLowerCase();}",toBeGeneratedCode);
toBeGeneratedCode.addMethod(toBeGeneratedMethod);


After adding all these we write the code to file


toBeGeneratedCode.writeFile();


Complete code


package in.xebia.metaprogramming;

import java.io.IOException;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.Modifier;
import javassist.NotFoundException;

public class UsingJavassist {

   public static void main(String[] args) throws NotFoundException,
   IOException, CannotCompileException {
      UsingJavassist ja = new UsingJavassist();
      ja.generateProgram();
   }

   public void generateProgram() throws NotFoundException, IOException,
   CannotCompileException {

      ClassPool pool = ClassPool.getDefault();
      CtClass toBeGeneratedCode = pool
      .makeClass("output.GeneratedCode");
      toBeGeneratedCode.setModifiers(Modifier.PUBLIC);

      // Implementing the Interface
      toBeGeneratedCode.addInterface(pool.get("java.lang.Cloneable"));

      // Creating a constructor
      CtConstructor toBeGeneratedCodeConstructor = new CtConstructor(
      new CtClass[] {}, toBeGeneratedCode);
      toBeGeneratedCodeConstructor
      .setBody("System.out.println(\"Constructor\");");
      toBeGeneratedCodeConstructor.setModifiers(Modifier.PUBLIC);
      toBeGeneratedCode.addConstructor(toBeGeneratedCodeConstructor);

      // Creating a new field
      CtField toBeGeneratedField = new CtField(pool.get(String.class
      .getName()), "name", toBeGeneratedCode);
      toBeGeneratedField.setModifiers(Modifier.PUBLIC);
      toBeGeneratedCode.addField(toBeGeneratedField);

      // Creating a method
      CtMethod toBeGeneratedMethod = CtNewMethod.make(
      "public String lowerCaseName() {return name.toLowerCase();}",
      toBeGeneratedCode);
      toBeGeneratedCode.addMethod(toBeGeneratedMethod);

      toBeGeneratedCode.writeFile();
   }
}


When we run this program a newly generated class file is available to us which can be loaded at run time and is available to use.

Monday, April 14, 2014

Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [cas.properties] cannot be opened because it does not exist

In the Installtion of Oracle Webcenter Sites, in between there is a step in which you need to deploy the CAS as application on application server (weblogic, websphere etc.). But after deploying the status of the cas application is failed due to following reason:
org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [cas.properties] cannot be opened because it does not exist.[2014-04-11 19:05:34,373 IST] [ERROR] [.kernel.Default (self-tuning)'] [cs.core.db.DBTransaction] TransactionUnit failed to execute 
com.fatwire.cs.core.db.TransactionAbortException: replacerows failed

Reason: This is due to the <sites_installation_directory>/bin directory is not in the classpath. And the cas.properties file is stored in the bin directory.

Solution: Add the <sites_installation_directory>/bin in the classpath i.e. make the class path entry in setDomainEnv.cmd/setDomainEnv.sh

  1. Open the setDomainEnv.cmd in edit mode i.e. "Oracle\Middleware\user_projects\domains\soa_domain\bin\setDomainEnv.cmd"
  2. Add the following line "set CLASSPATH=%CLASSPATH%;D:\Oracle\webcenter\sites\bin" at the end of setDomainEnv.cmd file. Here "<sites_installation_directory> = D:\Oracle\webcenter\sites".
  3. Start the server.

Oracle Webcenter Sites : java.sql.SQLException: ORA-12899: value too large for column "CSUSER"."TT1397223334151"."VALUE" (actual: 2306, maximum: 2000)

While installing the Oracle Webcenter Sites 11.1.1.6.0 or later you are getting the below error :
Exception executing prepared statement: INSERT INTO tt1397223334151 (NAME,LOCALE,VALUE) VALUES (?,?,?)NAME = fatwire/wem/admin/user/edit/DescriptionBodyLOCALE = ja_JPVALUE = <p>�存�れ�ユーザー���を変更�る�������ん。ユーザー�残り�プロパティ�修正����。</p><p>ACL: ユーザー�Browser�ElementReader�PageReader�UserReader�よ�xceleditor ACL��る��を確����。一般管�者�よ�サイト管�者�もxceladmin�必���。一般管�者��ら�TableEditor�よ�UserEditor(Engageを使用�る場��VisitorAdmin)�必���。ACL�詳細��<i>管�者ガイド</i>を�照������。</p><p>グループ: ��ユーザー�アプリケーション・リソースを管��る権�を必���る場��リソース�権�を��グループ�ユーザーを割り当���。グループを作��る������権�を構��る���<i>WEM�管�者ガイド</i>を�照������。</p><p>��ユーザー�アプリケーション�接続�る���(「サイト�ページ�ら)��サイト���ロールを両方�割り当���。</p>java.sql.SQLException: ORA-12899: value too large for column "CSUSER"."TT1397223334151"."VALUE" (actual: 2306, maximum: 2000)
Reason: In webcenter sites 11.1.1.6.0 and later, language pack is automatically installed and file.encoding is not set for weblogic server i.e. the JVM argument -Dfile.encoding=UTF-8 is not set.

Solution:

  1. Open startWeblogic.cmd in edit mode i.e. Oracle\Middleware\user_projects\domains\soa_domain\bin\startWeblogic.cmd
  2. Find -Djava.security.policy=%WL_HOME%\server\lib\weblogic.policy %JAVA_OPTIONS%.
  3. Then append "-Dfile.encoding=UTF-8"
  4. Final string look like this -Djava.security.policy=%WL_HOME%\server\lib\weblogic.policy %JAVA_OPTIONS% -Dfile.encoding=UTF-8.
  5. Save and start the server.
Note: For further information please followed the document 1539055.1 on oracle support.

Friday, April 11, 2014

JTA transaction is not in active state: The transaction status is "MARKED_ROLLBACK".

This issue generally comes due to low value (default value i.e. 30) set for JTA transaction timeout. To solve the above problem try the following things.

Setting syncMaxWaitTime: 

1.     Login into em console i.e http://<IP>:<PORT>/em
2.     Expand SOA and right click on "soa-infra" and select SOA Administration -> BPEL Properties
3.     Click on "More BPEL configuration Properties..." link
4.     Locate syncMaxWaitTime and increase the time value.

Setting the global transaction timeout at weblogic domain

1.     Log into Oracle WebLogic Administration Console.
2.     Click Services -> JTA.   
3.     Change the value of Timeout Seconds (the default is 30).
4.      Click Save.
5.      Restart Oracle WebLogic Server.

Note: For more information please follow the document Doc ID 1524757.1  and Doc ID 880313.1 on oracle support.


Tuesday, April 8, 2014

Weblogic Webservice Test client :http://localhost:7001/wls_utc not working

When you test the webservice that you have created in java and deployed on weblogic server in the browser you will get the following error:


Reason: The possible reason could be wlstestclient.ear is not deployed on the weblogic server. So deployed the application on server.

Solution:

  1. Go to the server/lib directory i.e. \Oracle\Middleware\wlserver_10.3\server\lib
  2. In that directory search for wlstestclient.ear.
  3. Deploy this wlstestclient.ear as an application on administration server (or target on to any server).
  4. Now test the client. you will some thing like this : 


Sunday, April 6, 2014

How to enable "--rest" option in Mongo DB after installation

Many people install the mongo db either as a service or instance but they forget to enable the default rest interface that mongo db provides.
Well to enable rest interface in mongo db as instance is nothing but just stop the instance and re-run the instance with "--rest" option.
i.e. E:\mongodb\bin\mongod.exe --rest --logpath E:\mongoData\log\mongo.log --dbpath E:\mongoData\data\db

But when you install the mongo db as service the how to enable rest interface without creating new service.
  1. Stop the mongo db service.
  2. Open run (window key+r), type regedit (i.e. open registry to edit).
     
  3. In the registry editor, go to the HKEY_LOCAL_MACHINE -> SYSTEM -> CurrentControlSet -> Services -> MongoDB
     
  4. Now double click on ImagePath and add the --rest option in the value.
  5. Click Ok.
  6. Exit regedit and start the mongo db service.

MongoDB not able to start :cause of : exception in initAndListen: 12596 old lock file, terminating

Some times when you start the mongo db server then it is not able to start because of following exception:

exception in initAndListen: 12596 old lock file, terminating

Solution

In this case just use the mongo db "--repair" command fix this issue.

  1. Go to bin directory in mongo db folder i.e E:\MongoDB\bin
  2. Delete the mongod.lock file. (this step is optional)
  3. Now open the command prompt and run this command i.e. "E:\mongodb\bin>mongod.exe --repair --dbpath=E:\mongoData\data\db"
  4. Now start the mongo db service.
  5. Verify that mongo db is running successfully.

Saturday, April 5, 2014

Oracle SOA : How to deploy multiple composite in oracle soa

Yesterday I just completed the SOA development and next thing I have to move all the deployed composite on to the UAT enviornment and then production. But I think it is very cumbersome to deploy each composite one by one on to the soa server, so to overcome this problem I am using the different SOA bundles, each soa bundle consist of multiple composite of particular partition.

Steps to create SOA Bundle
  1. In the jdeveloper create a New Deployment Profile.
  2. Select Soa Bundle from the list.
  3. Name the soa bundle, "MongodbRestBundle" in this case.
  4. Click Ok. Choose dependencies on this bundle, so check all those composites that you want to deploy in single partition.
  5. Click Ok and finish the wizard. SOA bundle is configured now.

How to deploy SOA bundle on SOA server

  1. Just click on the deployment profile that you have created in above steps.
  2. select "Deploy to Application Server" and click next.
  3. Attached the config plans, select appropriate plans like UAT plan in this case similarly select for other composite by navigating through the tabs.And click next
  4. Select application server connection and click next.
  5. Select the soa server and partition in which you want to deploy the bundle.
  6. Click next and finish the wizard.
Note: you can also deploy the soa bundle by creating the SAR file and deploy on to the soa server using em console. Use this guide for further information on deployment : http://docs.oracle.com/cd/E12839_01/integration.1111/e10224/sca_lifecycle.htm