Tuesday, September 24, 2013

JAX WS SSL Configuration to solve wsdl certificate problems

Hi friends,

Back to you after a long time. This past 2 months , i had been crazy busy and hence, did  not  have enough time to discuss anything.

Today , i am going to discuss a very important topic. This is regarding the invocation of  a JAX-WS or JAX-RPC  service.

PROBLEM :
Some time back i was trying to invoke a JAX WS service from a stand alone java application (an application having a java class with the main method and having no application server at all). The problem was, every time i was trying to invoke any service operation, it was giving me a SSL CONFIGURATION EXCEPTION .

REASON :
Now the reason behind it was that, every service call requires to validated . So how is that done ? It's done with the help of certificates. So what i  did was that, i got a hold of those certificates(the service i was using needed 2 of them) and integrated them with my java environment to make the WSDL hoster realize that it was a valid invocation.

SOLUTION (THE JAVA WAY):
My certificate names were cert1.cer and cert2.cer . And this how i integrated them in my  java  environment(In use RAD-Rational Application Developer) :

1. Place the below cry certificates in the path "C:\Program Files\IBM\SDP\jdk\jre\lib\security"

   cert1.cer, cert2.cer 

2. cacerts is the trusStore file. It's present in :
   C:/Program Files/IBM/SDP/jdk/jre/lib/security/cacerts

3. In command prompt perform the below execution :
C:\Program Files\IBM\SDP\jdk\jre\lib\security>"C:\Program Files\IBM\SDP\jdk\jre\bin\keytool" -import -alias cert1 -file cert1.cer -keystore cacerts

4. If it asks keystore password, mention changeit, which is the default keystore password

Enter keystore password: changeit

Trust this certificate? [no]:  yes
Certificate was added to keystore

5. Peform the steps 3 and 4 for the second certificate(cert2.cer).

And , i thought that was the end of it, but apparently it was not to be so. It seems , you have to configure the
"javax.net.ssl"  in your program to make it work, and this is how you have got to do it :

System.setProperty("javax.net.ssl.trustStore", "C:\\Program Files\\IBM\\SDP\\jdk\\jre\\lib\\security\\cacerts");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

Now,the problem will be that the above piece of code will configure only the truststore, but that's not all; you have got to configure  the keystore as well. So for this , you have gotta add the following lines of code :

System.setProperty("javax.net.ssl.keyStore", "C:\\Program Files\\IBM\\SDP\\jdk\\jre\\lib\\security\\cacerts");
System.setProperty("javax.net.ssl.keyStorePassword", "changeit");

And voila, everything will start working for you.
In case you are wondering how to add the certificates pro grammatically instead of adding them manually, then you can use this link : http://stackoverflow.com/questions/18764122/how-to-integrate-wsdl-certificates-to-the-cacerts-file-in-jdk-jre-security-folde

THE UNIX WAY( no--check--certificates) :

Now if you are writing a shell script and you are invoking a particular operation of the web service , then you can actually tell the host not to validate the invocation for any certificates.
In my case, i normally use the CURL  command to do my bidding  , though other times it's the WGET command. So for example , my invocation of a service operation using a schell script will look something like this :

#! /bin/sh
ENDPOINT="http://mathertel.de/AJAXEngine/S01_AsyncSamples/CalcService.asmx"
VALUE=1234567890
if [ -n "${1}" ]; then
    VALUE=${1}
fi

curl --silent \
     --data \
     @- \
     --header 'Content-Type: application/soap+xml; charset=utf-8' \
     --user-agent "" \
     ${ENDPOINT} <<EOF | xmllint --format -
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <CalcPrimeFactors xmlns="http://www.mathertel.de/S01_AsyncSamples/">
      <inputText>${VALUE}</inputText>
    </CalcPrimeFactors>
  </soap12:Body>
</soap12:Envelope>
EOF

DON'T BE AFRAID  or alarmed , this is not a complicated code. Curl's just a command(you have to have it installed though in your linux distro), where you pass the end point and the request structure . Once that is done , this will give an out put , which for brevity , we can parse it using XMLLINT,  which is a command that parses the response in XML format. In case, you do not want to be validated for certificates, you just need to add the option no--check--certificates to the command invocation and you will get the response without   any  certificate hassles .

In my case, the output looks like this :

RESPONSE FROM THE SERVICE :
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <CalcPrimeFactorsResponse xmlns="http://www.mathertel.de/S01_AsyncSamples/">
      <CalcPrimeFactorsResult>2 3 3 5 3607 3803</CalcPrimeFactorsResult>
    </CalcPrimeFactorsResponse>
  </soap:Body>
</soap:Envelope>

Hope this will be  fun to know for you all as it was for me.
Good bye.

Saturday, July 13, 2013

The magic of CSSPIE3 library


Hi friends,

Today i am gonna talk about an interesting tidbit that i came to know very recently.

The Problem :

I was working on installing a gradient for a page. For mozilla, the gradient was written as :

background: linear-gradient(to bottom, #ffffff 18%,#ecedeb 18%,#d1d5d0 100%);

And the pictorial view of that block of code comes up as something like this :

As you can see from above that the effect of the block of code is : the thick continuous red line that borders the element .

Now linear gradient cannot be used for the browser like IE8, as IE8 does not understand what it is. Hence we need to use filter here like :

filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#d1d5d0',GradientType=0 );

The element gradientType = 0 signifies that we here are talking about a linear gradient. That's how IE understands a linear gradient. Now the problem with that is, once such a style is implemented, IE super  imposes that with it's own styles, thus marring the whole effect , like in here :


As you can see from the picture above we get discontinuous red lines even after applying the filter.
So for a long time i was languishing under the knowledge that IE 8 is not letting me bring up the gradient properly.

Reason :

The problem with using filters is that they are old pieces of code of a bygone era. They are not very reliable/good. No one really used them until recently when we got first class gradients/opacity etc. IE's old filter styles are well known for having major bugs and quirks. Hence  i was pondering on the possible solutions when i suddenly came across the CSSPIE3  library.

The way out :

CSS3Pie library is a little Javascript lib that tries to add a few standard CSS features to old IE versions, including CSS gradients. It works internally by using VML graphics, not filter styles, which means that you don't get the bugs thatfilter causes . Hence all i needed to do here was use the linear gradient and couple it to PIE.js. 

I downloaded the PIE.js from : http://css3pie.com/ .

Now to use it , first i described my style in jsp inside a class like :

<Style type="text/css">

   .ieMasterStyle{
     background: linear-gradient(to bottom, #ffffff 18%,#ecedeb 18%,#d1d5d0 100%);
   }

<Style>

In my jsp , i referred to it as :

<td class='ieMasterStyle'>Border</td>

Now calling this one is a bit tricky and it is a two step process :

STEP 1 :

Include the PIE.js script in your page, surrounded by a conditional comment to prevent it from being downloaded in other browsers:

<!--[if IE]>
<script type="text/javascript" src="path/to/PIE.js"></script>

<![endif]-->

or, in case, you don't want to download it , but just want to refer it from a CDN than do this :


<!--[if IE]>
<script type="text/javascript" src="http://cdn.jsdelivr.net/css3pie/1.0.0/PIE.js"></script>
<![endif]-->

NOTE : Remeber to use PIE.js version 1.0 as it's the most stable version around.

STEP 2 :

Invoke the PIE.attach(el) function for each element that needs CSS3 styling. Make sure you do this after the page's DOM has been fully loaded. For example, using jQuery:


$(function() {
    if (window.PIE) {
        $('.ieMasterStyle').each(function() {
            PIE.attach(this);
        });
    }
});

As you can see from above , i have fed the ieMasterStyle that i created directly o PIE.js, where in the PIE.js will do it's magic and apply the linear gradient for us . Hence the finished product in IE 8 looks like this :



And thus i achieved browser consitency and PIE.js saved my bacon.

That's it guys. Bye .

Thursday, July 4, 2013

Android : Layouts

Back to you guys after a long time. From today we will go inside in depth of android features and try to learn some new stuff along the way . The next few days, we will feverishly try to cover a lot of topics pertaining to android.  So let's get cracking .

What's an android layout ?

Well, a lay out is what it actually means. It's the main UI of your app and will contain several UI controls of your app. You can define your lay out height, width and orientation , add text views , buttons etc and when you run the app , all of them will come up in your app UI . Layouts are presented in XML. When you first create a layout, the main.xml  is created. In case you are wondering that's your lay out .

This is how a typical layout is created :

<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
   
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</LinearLayout >

I know, i know, you are very confused . Let's break it up then :

1> fill_parent --> means fill the parent window

2> vertical --> That's your typical orientation , you can specify 'horizontal' as well and no one will kill you.

3> wrap_content --> means wrap the content , kind of works like html wrap attribute, quite cool , huh !

Okay, kidding aside, these are very important attributes that define your layout, which means they tell your mobile / tablet that this is the way you want the app to be shown .

So let's run this one in eclipse, once we do that , this is what we will get in the emulator :


If  you look clearly up above , you will see the hello world string is coming twice and vertically one below the other. It's coming twice because we have two text views and vertically because the  orientation is vertical, duh......

So there you go....it's been laid out for you. Till next time ....

Saturday, April 27, 2013

How to Set up an environment for Android Development

Hi friends,

Back to you after a long time. Today we are going to look into a very important technology  namely : Android. 

Now the android programming language is very useful for app development . A lot  of us want to be app developers but we are not sure about how to progress.  Well the upcoming few weeks , we will look deeply into this technology and try to learn a lot of things.

However, what good is this , if we don't have an application development environment to test what we have learnt ? So i am gonna tell you how how to set up a local work space for Android . Hang tight.


For the most part, you'll figure out pretty quickly through trial and error what you'll need. If you're using Eclipse, it will yell at you when you're missing things, and you simply find what you're missing in the SDK Manager and install it.
That said, here's what I needed to get up and running with a very basic setup (this assumes using Android 4.1, if you plan on building for an earlier version, then you'll need to download the corresponding libraries from that version):
  • SDK Platform
  • ARM EABI v7a System Image (optional, you can also grab the Intel x86 Atom and/or Mips System images if you plan on developing for one of those platforms; ARM is the default, from what I've seen)
  • Android SDK Platform-tools
You get these simply by going to the Android SDK Manager (your SDK folder/tools/android; or click the "SDK Manager" button in Eclipse), selecting what you need, and clicking "Install Packages". Once you do that, you can follow the rest of the guide that you linked for building your first app (I highly recommend it, it's extraordinarily beneficial), and your app should run with no problem.

Here's a snapshot to get you started :


Now all you gotta do , is install the packages that I have checked in and that creates your basic set up. The other stuff you can install later.

Hope that was useful. Very soon we will dive in to the world of Android.

Good Bye .

Sunday, April 7, 2013

BASH COMMANDS - PART 1


Hi friends,

Today  we are gonna go in  a different direction . After some time , i thought of coming out with a series of tutorials on BASH scripting , which is a must if you wanna write complex scripts. My try outs here will
consist of commands written in UBUNTU 12.04 PP LTS as this is what i am using right now. So let us open up our terminal and begin our wonderful journey :

Finding out where the inbuilt commands lie :


Type :
bash$ : cd /bin
bash$/bin : ls


Creating my own directory and seeing the permissions it has :
mkdir kunal
ls -ld kunal → drwxrwxr-x 2 atri atri 4096 Apr 3 02:00 kunal

Consider these shell operations :



Consider the next set of shell commands :

How to make use of manual in Unix :
bash$ : man man
O/P :


What if we give :
bash$ : man cp




What is Shebang ? :

The shebang is the first line in a script because it is interpreted by the kernel, which looks at the two bytes at the start of an executable file. If these are #! the rest of the line is interpreted as the executable to run and with the script file available to that program on stdin. Since the kernel will only look at the first two characters and has no notion of further lines, you must place the hash bang in line 1.
Let us consider the script below :


This script does a listing of files and in between the first and last listing , it tries to read a file. So if you try to execute the file without changing its permissions it won't run. Hence first you gotta do this :

bash $ : ls -lrt yourFile --> get the available permissions
bash $ : chmod a+x yourFile --> make the file executable.
Voila, now you are ready to run it. Just do :
bash $ :  ./yourFile

 or

bash $: sh yourFile.sh

That's  all for today. Next time we will delve deeper .

Good Bye .


Wednesday, March 13, 2013

Keeping a healthy Mind and Body


Hi Friends,

I am back again. These upcoming weeks we will look into various aspects of different technologies.
However, before doing that i thought i will publish this article.

The last few weeks had been the worst days of my life. Why ? Because  I had been ill. So here goes :

I know all of us are busy doing this and that. But if we do not keep a healthy body, none of this will matter. So listen to what i have got to say here as it is more important than all the articles that i have published during my life time.

As we get older the body’s tissues and organs start to work less efficiently. We have to work harder and harder to stay fit and active. But keeping well is also about anticipating what’s increasingly likely to go wrong, and taking steps to prevent harmful events from happening. This may mean not just eating the right foods and taking regular exercise, but also changing your living environment and watching out for possible dangers.
Preventative tactics are particularly important because our health doesn't just decline in a gradual way. Instead what’s often more important is a step-by-step decline on top of a slow deterioration in health. Every so often we have a major illness or event from which we never quite recover to previous levels of fitness. The most common causes include:
As we get older we have more and more of these acute episodes of illness and drop further and further back down the scale of general health. If we could dodge the acute illness we could stay well for longer even as ageing takes a general toll.


Listed below are ten essential elements of good health. If you take all of the actions listed below, you will be much healthier.

  • Eat a Healthy Breakfast
  • Drink at Least 8 Glasses of Water
  • Take a Good Quality Multiple Vitamin/Mineral
  • Connect with Other People
  • Express Your Emotions Appropriately
  • Eat Fruits and Vegetables
  • Spend at Least 30 Minutes Outdoors
  • Do Something Physically Active
  • Take Some Quiet Time for Yourself
  • Keep Regular Sleep Hours
  • Establish a Relationship with a Doctor You Can Trust

Lastly, this is helping me a lot : Meditate properly for at least half an hour.

Hence try to keep yourself healthy folks. This is the primary wealth for which you are fighting with the world. 

Sunday, February 17, 2013

Google glasses augmenting our reality

I have always wanted to write an article about the google glasses. Today I got a chance and hence here goes .

What is Augmented Reality :

Huh, i feel like i am in a new world, though everything around looks the same.

You may think you don’t know “augmented reality” but unconsciously dealing with it everyday. It is found in computer games. news cast, television shows, sports live telecast etc. Its a new way of presenting physical reality plus virtual reality.This is not a new technology. In fact, it was first introduced in 1990.

Augmented reality (AR) is a term for a live direct or an indirect view of a physical, real-world environment whose elements are augmented by computer-generated sensory input, such as sound or graphics.

Where is Augmented Reality Used :

1.  There are a lot of applications or uses of augmented reality today it helps ease our way of life. Lets start with American Football. When you watch a football game on tv, you may wonder a yellow line (super imposed first down line) which looks amazing because it adjusts by itself as the downs change.



2.  In February 2009, at the TED conference, Pattie Maes and Pranav Mistry presented their augmented-reality system, which they developed as part of MIT Media Lab’s Fluid Interfaces Group. They call it Sixth Sense, and it relies on some basic components that are found in many augmented reality systems:

Camera
Small projector
Smartphone
Mirror

These components are strung together in a lanyard-like apparatus that the user wears around his neck. The user also wears four colored caps on the fingers, and these caps are used to manipulate the images that the projector emits.



The image above demonstrates augmented reality in action, dialing a phone pad projected to your hand and phone a friend. This is part of the Sixth sense augmented reality systems.

3.  A more advanced application of Augmented reality. This was viewed on a digital camera capable of AR. When you point out a building or certain location, it provides you information on restaurants, shops etc information available on that area. This is the same augmented reality being advertised by Samsung Galaxy Tab as its key features.



4.  Augmented reality is also used on medical operations where its difficult to identify organs on a difficult and bloody situations.

5. AR displays can be rendered on devices resembling eyeglasses. Versions include eye wear that employ cameras to intercept the real world view and re-display its augmented view through the eye pieces and devices in which the AR imagery is projected through or reflected off the surfaces of the eye wear lens pieces. This is where google glasses come handy .

Google Glasses :



It All started with Project Glass :

Project Glass is a research and development program by Google to develop an augmented reality head-mounted display (HMD). Project Glass products would display information in smartphone-like format hands-free and could interact with the Internet via natural language voice commands.The prototype's functionality and minimalist appearance (aluminium strip with 2 nose pads) has been compared to Steve Mann's Eye Tap. The operating system software used in the glasses will be Google's Android.



The New York Times originally reported that the glasses would be available to the public for "around the cost of current smartphones" by the end of 2012,but other reports have stated that the glasses are not expected to be available for purchase soon.The product (Google Glass Explorer Edition) will be available to United States Google I/O developers for $1,500, to be delivered in early 2013, while a consumer version is slated to be ready within a year of that.


So , in a very near future you are going to get your hands on google glasses and i am sure they are gonna change the way we view our world.



Friday, January 11, 2013

Problems due to Same Origin Policy -- printing contents of a pdf from a url

This is one of the biggest problems .

Let us consider this scenario :

We have a url which hosts a pdf and we want  to print it from our web page on click of a button. It's at that point of time that we must look at Same Origin Policy.

What is Same Origin Policy : 

In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site – a combination of scheme, hostname, and port number – to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites. Same origin policy also applies to XMLHttpRequest.

Let us consider these two urls :

http://www.example.com/dir/page.html  /  http://www.example.com/dir2/other.html --> Success since Same protocol and host

Since the above two urls have same protocol, host and domain, hence resource sharing is a possibility here .

However, if it would have been something like :

http://www.example.com/dir/page.html  /  http://www.goIbibo.com/dir2/other.html --> Failure

Now the above two links either don't share the same host or domain and hence it violates the same origin policy. So resource sharing here is not possible .

Workarounds :

To enable developers to, in a controlled manner, circumvent the same origin policy, a number of "hacks" such as using the fragment identifier or the window.name property have been used to pass data between documents residing in different domains. With the HTML5 standard, a method was formalized for this: the postMessage interface, which is only available on recent browsers. JSONP can also be used to enable ajax-like calls to other domains.

In other words, it is really difficult when you try to do that .

Consider a classic scenario :

As stated earlier you want to print a pdf hosted in another site from your web page. How can you do this ?

Well , let us say you have fished out a code like this ::

Inside your body tag you have this ::


<input type="submit" class="btn-red" value="Print"
name="Submit" id="printbtn"
onclick="printPDF('http://www.irs.gov/pub/irs-pdf/fw4.pdf')" />

Inside your head tag you have this ::


function printPDF(pdfUrl)
    {

    if ((navigator.appName == 'Microsoft Internet Explorer') )
    window.print(pdfUrl,"_self");
    else
    {
    var w = window.open(pdfUrl,"_self");
    w.print();
    w.close();
    }
    }

So you are trying to print the contents of the URL in  http://www.irs.gov/pub/irs-pdf/fw4.pdf using javascript. However, your web site and the host which hosts the pdf  are different . Hence this does not work.

Further more, window.print() always will print just the content of the current window and hence all you will see is your html mark ups and not the pdf.

So what do you do ?

Probably , now you will think, hang on, i can use this idea :


I can open an iframe and then call window.print() inside of it. I can probably get away with hiding the iframe by giving it position: absolute; left: -9999px.

This is the code that you make up :


function printPDF(pdfUrl) {

var iframe = document.createElement('iframe'),
iframeDocument;

iframe.style.postion = 'absolute';
iframe.style.left = '-9999px';
iframe.src = pdfUrl;
document.body.appendChild(iframe);

if ('contentWindow' in iframe) {
iframeDocument = iframe.contentWindow;
} else {
iframeDocument = iframe.contentDocument;
}

var script = iframeDocument.createElement('script');

script.type = 'text/javascript';

script.innerHTML = 'window.print();';

iframeDocument.getElementsByTagName('head')[0].appendChild(script);

}





But even this idea will not work as the pdf contents will never be available for windows to print, since it's a different host altogether.

Idea No  2 ::

Some people might think , let's have a print.css and let's set the display for every element to none except what i want to print. But whatever you do you are going to try to print using : window.print() only. So this will not work as well.

Idea No 3 ::

Now you will say that, alright man, okay i will use pdf.js and extract the pdf into text . Then i will re construct the pdf from the text on my side and then print it. But that idea will be a flop idea as well. It's because even pdf.js follows the same origin policy .

So is there no way of doing this ?
Hang on, now i did not say that.

The costliest way ::

The same origin policy can be bypassed using : CORS .

What is CORS :

It means Cross-site HTTP requests .

Cross-site HTTP requests are HTTP requests for resources from a different domain than the domain of the resource making the request.  For instance, a resource loaded from Domain A (http://domaina.example) such as an HTML web page, makes a request for a resource on Domain B (http://domainb.foo), such as an image, using the img element (http://domainb.foo/image.jpg).  This occurs very commonly on the web today : pages load a number of resources in a cross-site manner, including CSS stylesheets, images and scripts, and other resources.

How it works :

The Web Applications Working Group within the W3C has proposed the new Cross-Origin Resource Sharing (CORS) recommendation, which provides a way for web servers to support cross-site access controls, which enable secure cross-site data transfers.  Of particular note is that this specification is used within an API container such as XMLHttpRequest as a mitigation mechanism, allowing the crossing of the same-domain restriction in modern browsers.  The information in this article is of interest to web administrators, server developers and web developers.  Another article for server programmers discussing cross-origin sharing from a server perspective (with PHP code snippets) is supplementary reading.  On the client, the browser handles the components of cross-origin sharing, including headers and policy enforcement.  The introduction of this new capability, however, does mean that servers have to handle new headers, and send resources back with new headers.

So all this is fine and dandy but it is extremely difficult

Moral of the story : Don't try to do this. If you have a url , the contents of which you want to print , then host the same thing from your end. Things become much easier then. Otherwise, it will become very difficult a problem to handle .

I recently faced a similar problem, hence i have shared all my knowledge that i gathered while researching this . I sincerely hope it helps other people who are trying similar stuffs .

Good Bye .

Thursday, January 3, 2013

The JAX RPC way of using a SOAP Handler

Back to you guys after a long time. Hope you are doing well. Today we are going  to look in to some important aspects of the JAX RPC way of servicing the web.

So first things first ::

What is JAX RPC :  Jax Rpc is a java standard way of communicating with web services.Java API for XML-based RPC (JAX-RPC) allows a Java application to invoke a Java-based Web Service with a known description while still being consistent with its WSDL description. It can be seen as Java RMIs over Web services.

It works as follows:
  1. A Java program invokes a method on a stub (local object representing the remote service)
  2. The stub invokes routines in the JAX-RPC Runtime System (RS)
  3. The RS converts the remote method invocation into a SOAP message
  4. The RS transmits the message as an HTTP request
The advantage of such a method is that it allows the Web Service to be implemented at server-side as a Servlet or EJB container. Thus, Servlet or EJB applications are made available through Web services.

What is a Service Handler :  When designing a web service that accepts or returns SOAP messages,  the SOAP messages should be processed by message handlers Handlers on incoming messages are invoked before the message is delivered to the web service operation, and handlers on outgoing messages are invoked after the web service operation has completed. The web service itself is unaware of the presence of handlers. SOAP message handlers are sometimes referred to as interceptors.


Now suppose you have a SOAP request like this ::


<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ch="urn://mfots.com/xmlmessaging/CH" xmlns:oas="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<soapenv:Header>
<ch:MFprofileMnt>
<ch:myID>1458</ch:myID>
<ch:bigID>raptool</ch:bigID>
<ch:matID>5689</ch:matID>
</ch:MFprofileMnt>
</soapenv:Header>
</soapenv:Envelope



Now suppose you have got to create a message handler where you will have to construct the SOAP header MFprofileMnt and its children.
Now how do you do it :: Keep patience we are coming there.
See the code snippet given below :
 Name headerContextName = soapEnvelope.createName("MFprofileMnt", "ch","urn://mfots.com/xmlmessaging/CH");
SOAPHeaderElement soapHeaderElement = soapHeader.addHeaderElement(headerContextName);
// mustUnderstand attribute is used to indicate
// whether the header entry is mandatory or optional for the
// recipient to process.
soapHeaderElement.setMustUnderstand(true);
//Now set the attribute children
// create the first child element and set the value
SOAPElement element1 = soapHeaderElement.addChildElement("myID", "ch");
element1.addTextNode("1458");
//create the second child element and set the value
SOAPElement element2 = soapHeaderElement.addChildElement("bigID", "ch");
element2.addTextNode("raptool");
//create the third child element and set the value
SOAPElement element3 = soapHeaderElement.addChildElement("matID", "ch");
element3.addTextNode("5689");
So what i am doing here is that i am creating a name object where i am feeding the header  name , the prefix and the prefix-namespace-URL . After that in the next line i am setting mustUnderstand as "true", which means the header entry is mandatory.
Now we have got to create the children elements. To do that i am creating 3 SOAPElement objects for the 3 children and adding the child elements using the method addChildElement() and then to pass the value i am using the addTextNode() method and voila you have created the header with its children.

How to get the operation name :


Now suppose you need to get the operation name . Only depending on this you will construct your header . So how do you go about doing this ? This is how :


protected String getMethodName(MessageContext mc)

{

String operationName = null;

try

{

SOAPMessageContext messageContext = (SOAPMessageContext) mc;

// assume the operation name is the first element

// after SOAP:Body element

Iterator i = messageContext.

getMessage().getSOAPPart().getEnvelope().getBody().getChildElements();

while ( i.hasNext() )

{

Object obj = i.next();

if(obj instanceof SOAPElement)

{

SOAPElement e = (SOAPElement) obj;

operationName = e.getElementName().getLocalName();

break;

}

}

}

catch(Exception e)

{

e.printStackTrace();

}

return operationName;

}

Explanation : 

What i am assuming here is that the first element after the soap body tag is my operation name . So for that i am getting the body part of the request by using the getBody() on the messageContext. Then i am getting all the children of the body attribute and after iterating through that list i am only collecting the first element and then breaking away. Now that element is also my operation name. Thus we can get the  operation name  as well.

The purpose of this post is to tell people how to make handlers work in JAX RPC. Since , now a days people use more and more JAX WS , so RPC related stuffs are very less in the internet. Hope this helps some of the folks. Stay tuned , i will come soon again with more exiting stuffs.


Sunday, October 21, 2012

In Linux, Kill many instances of a process with a single command .

Hi guys back to you after a long time.

However, the English that i am typing in here, might be a little murky  as i am typing this one from chennai airport and there's no space to sit on .

Today we are going to look into  a very important question which is :

Suppose you are running thousand or more instances of the VI editor process in your linux. Now you want to kill them in a single shot. How do you do it ?

Let's look at the good old grep-awk :


for pid in $(ps -ef | grep "some search" | awk '{print $2}'); do kill -9 $pid; done
There are ways to make that more efficient,
for pid in $(ps -ef | awk '/some search/ {print $2}'); do kill -9 $pid; done
and other variations, but at the basic level, it's always worked for me.
The problem with this method, however, is that you often end up killing more than you intended. Writing a reliable “some search” is tricky. 

Use Killall :
killall vi
This will kill all command named 'vi'
You might also add a signal as well, e.g SIGKILL
killall -9 vi
The  problem :
  •  Killing by file only works for executables that are kept open during execution, i.e. impure executables can't be killed this way.
  •  Typing killall name may not have the desired effect on non-Linux systems, especially when done by a privileged user.What if i am trying to delete a lot of instances of some non-linux process ?
  •  killall -w doesn't detect if a process disappears and is replaced by a new process with the same PID between scans. If processes change their name, killall may not be able to match them correctly.
But, please be aware that this only works on Linux and BSD. On Solaris and some other systems killalldoes exactly what the name suggests...it kills the init-process.

On AIX, it "cancels all processes that you started, except those producing the killall process."

Use Pkill :

pkill is available on Linux, BSD and Solaris. So it has a bigger spread thankillall. 
But, 

The problem :

pkill doesn't exist on AIX or HP-UX and despite what some people like to believe, there's still a significant based  non-Linux UNIX out in the world.

What does pkill do :

pkill is  available in  (LinuxFreeBSDNetBSDOpenBSDSolaris). You can specify processes by the command name, by the full command line or other criteria. For example,pkill vi kills all programs whose command name contains the substring vi. To kill only processes called vi, use pkill -x vi. To kill only processes called vi with a last argument ending in .conf, use pkill -fx 'vi.*\.conf'.
To see the list of PIDs that pkill would send a signal to, use pgrep, which has exactly the same syntax except that it doesn't accept a signal name or number. To see more information about these processes, run
ps -p "$(pgrep …)"
Under Linux, you need ps -p $(pgrep -d, …) instead (that's a bug: Linux's ps isn't POSIX-compliant).
Another common way to identify processes to kill is the processes that have a certain file open (which can be the process's executable). You can list these with fuser; use fuser -k to send them a signal. For example, fuser -k /usr/bin/find kills all running isntances of find.
If there's a runaway process that keeps forking, you may need to kill the whole process group at once. A process group is identified by the negative of its leader, which is the ancestor process of all the processes in the group. To see the process group that a process belongs to, run ps -o pgid (plus any option to select which process(es) to display). If you determine that you want to kill the process group leader 1234 and all its children, run kill -1234 or kill -HUP -1234 or any other signal.
If you can't find a better way, use ps with proper options to list all processes and filter it with grep or some other text filtering command. Take care not to accidentally match other processes that happen to be running a command with a similar name, or with an argument that contains that name. For example:
kill $(ps -o pid -o comm | awk '$2 == "vi" {print $1}')
Remember that your grep or awk command itself may be listed in the ps output (ps and the filtering command are started in parallel, so whether it will show up or not is dependent on timing). This is particularly important if the command arguments are included in the ps output.
All right that's all guys, i have to get my boarding pass now, or i will miss my flight .

See you next time .