Friday, April 17, 2015

Angular

AngularJs, commonly called as "Angular" is an open source web application framework mainly maintained by Google and community of developers, which helps a lot in development of SPA, Single Page Application.

You  can download Angular from
https://angularjs.org/

and for more information
http://en.wikipedia.org/wiki/AngularJS
http://www.w3schools.com/angular/

Here i am going to discuss few key words associated with Angular. Those include


  • Directives, Filters, and Data Binding , Expressions
  • Views, Controllers and Scope
  • Modules, Routers and Factories


Why Angular ??? It's framework... Good SPA framework
SPA ????   Single Page Application

As a framework it gives
Data Binding, MVC, Routing , Testing,  jqLite, Templates, History, Factories  etc.
jqLite - for DOM manipulation.

So it has
ViewModel , Controllers , Views , Directives , Services , Dependency Injection , Validation much more..


First we create simple html page and add the angular to it.

----------------------------------------------------------------------------------------------------

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>

</body>
</html>

----------------------------------------------------------------------------------------------------


I have added the reference to the web, you can download the angular from site https://angularjs.org/ and give the reference straight.

----------------------------------------------------------------------------------------------------

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="angular.min.js"></script>
</head>
<body>

</body>
</html>

----------------------------------------------------------------------------------------------------


Now we are ready to go with the Angular, So once we add the Angular to page.. Next we will look at key concepts... Directive , Data Binding ...

Directive
Angular extend HTML with ng-directive. So directive start with ng-
angular has various directives and some are
ng-app  = directive defines AngularJs application
ng-model = directive binds the value of the HTML control (input, slect, textarea..) to application data
ng-bind = directive binds application data to the HTML view


Now let's write a simple angular application with directives

----------------------------------------------------------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>


<div ng-app="">
  <p>Name: <input type="text" ng-model="name"></p>
  <p ng-bind="name"></p>
</div>

</body>
</html>
----------------------------------------------------------------------------------------------------


You can see above, highlighted, i have used few directives.
ng-app - declares this as an angular application
then we have we have input text box and we have bind the value of the text box to application using ng-model directive , we have use "name" as the reference.
Now we need to show the application data back into HTML view.
ng-bind directive binds that application data to the HTML view.

That's how angular application is defined and it's data been bind into application and show application bound data back into HTML view.

Behind the scene : What ng-model does behind the scene is, it's going to add a property up in the memory called 'name' into what's called the "scope". you will understand this concept, as you will read through.


Now we have learnt three basic angular directives.

Note : without using ng-bind , we can use {{}} to bind application data to HTML view.

----------------------------------------------------------------------------------------------------

<div ng-app="">
  <p>Name: <input type="text" ng-model="name"></p>
  {{name}}
</div>

----------------------------------------------------------------------------------------------------

This will have the same results

{{name}}  , this is known as data binding expression.
So we now know expressions also, this is much similar to JavaScript expressions..

Now we have learnt four key words, Next ..
let's do the iteration.. key feature in any language..


----------------------------------------------------------------------------------------------------

<!DOCTYPE html>
<html data-ng-app="">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>


<div >
  <p>Name: <input type="text" data-ng-model="name"></p>
  {{name}}
</div>

<div data-ng-init="names=['Shaun','Dilan', 'Mike', 'Paul']">
  <h3>Looping with the ng-repeat Directive</h3>
  <ul>
  <li data-ng-repeat="personName in names">{{personName}}</li>
  </ul>
 
</div>

</body>
</html>

----------------------------------------------------------------------------------------------------


As you can see we have defines a new angular application.
Previously we have defined ng-app directive inside the div tag
so if we need to define a new application then we need to define ng-app in the next div tag also.
to avoid that we have added the ng-app directive to the html root element.
by doing, we have defined the whole app as a angular application.

second div tag contains the repeated elements.

here we have defined an array of elements. to do that we have used another angular directive,
data-ng-init  , this directive initializes the names array in to the application.
Now we have initialized the elements of array.
let's repeat the elements and show that inside the HTML view.
to that we have used data-ng-repeat  directive, this helps us to define and loop or iterate over the elements. we are now iterating over the elements in the names array.
we have defined the repeat element with "personName in names"
Here "personName" is the temp[orary holder while "names" is the array of elements we are using to repeat. This is much similar to foreach loop we are using in javascipt or Java.
Then we bind the application data inside the iteration, or the repeat element with data binding expression {{personName}}
Note : we have used the temporary value holder to bind data to the HTML view from the angular application.

This will have output as below, above the "Looping with the ng-repeat Directive" will have the text box of previous application. you can see the output by saving the code into notepad and save as html file and running ina browser.

output
===========================================================


Looping with the ng-repeat Directive

  • Shaun
  • Dilan
  • Mike
  • Paul
===========================================================


So we have learnt few directives.
go to  https://docs.angularjs.org/api
you will have all the directive list with their documentation.

Now let's look at filters
To discuss filters we define new set of data elements as Customers and do the filtering for properties of customer.
we can use the ng-init to initialize the customers data.
First we initialize data and print that.

----------------------------------------------------------------------------------------------------
<!DOCTYPE html>
<html data-ng-app="">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>


<div>
<p>
Name: <input type="text" data-ng-model="name">
</p>
{{name}}
</div>

<div data-ng-init="names=['Shaun','Dilan', 'Mike', 'Paul']">
<h3>Looping with the ng-repeat Directive</h3>
<ul>
<li data-ng-repeat="personName in names">{{personName}}</li>
</ul>

</div>

<div
data-ng-init="customers=[{name:'Shaun',city:'Phoenix'},{name:'Dilan',city:'Chicago'},{name:'Mike',city:'NewYork'}]">
<h3>Looping with the ng-repeat Directive</h3>
<ul>
<li data-ng-repeat="customer in customers">{{customer.name}}- {{customer.city}}</li>
</ul>

</div>

</body>
</html>
----------------------------------------------------------------------------------------------------


This will print the name and city pairs of customers.
Now let's add the filter.
We have the name text filed , which we had added in the first application. this is third application.
let's use name as a filter.

----------------------------------------------------------------------------------------------------

data-ng-init="customers=[{name:'Shaun',city:'Phoenix'},{name:'Dilan',city:'Chicago'},{name:'Mike',city:'NewYork'}]">

Looping with the ng-repeat Directive





  • {{customer.name}}- {{customer.city}}





  • ----------------------------------------------------------------------------------------------------

    it's very simple.
    Just add the pipe character and filter word as shown in highlighted text above.
    After the filter, give the property you are using to filter. Here we have used "name", that is data reference used to bind html text box data to application.
    you can see the dynamically list will change in the HTML view.
    very smooth and simple.

    we can give order by filter also.
    let's put order by to city

    ----------------------------------------------------------------------------------------------------

    <div
    data-ng-init="customers=[{name:'Shaun',city:'Phoenix'},{name:'Dilan',city:'Chicago'},{name:'Mike',city:'NewYork'}]">
    <h3>Looping with the ng-repeat Directive</h3>
    <ul>
    <li data-ng-repeat="customer in customers | filter:name | orderBy : 'city'">{{customer.name}}- {{customer.city}}</li>
    </ul>

    </div>
    ----------------------------------------------------------------------------------------------------

    Note : we have given order by field property value inside single quotes.
    This will arrange data order by city name.

    we can use more filters.
    let's add uppercase to names and lowercase to city values.

    the whole code will be as follows

    ----------------------------------------------------------------------------------------------------
    <!DOCTYPE html>
    <html data-ng-app="">
    <head>
    <meta charset="ISO-8859-1">
    <title>Insert title here</title>
    <script
    src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    </head>
    <body>


    <div>
    <p>
    Name: <input type="text" data-ng-model="name">
    </p>
    {{name}}
    </div>

    <div data-ng-init="names=['Shaun','Dilan', 'Mike', 'Paul']">
    <h3>Looping with the ng-repeat Directive</h3>
    <ul>
    <li data-ng-repeat="personName in names">{{personName}}</li>
    </ul>

    </div>

    <div
    data-ng-init="customers=[{name:'Shaun',city:'Phoenix'},{name:'Dilan',city:'Chicago'},{name:'Mike',city:'NewYork'}]">
    <h3>Looping with the ng-repeat Directive</h3>
    <ul>
    <li
    data-ng-repeat="customer in customers | filter:name | orderBy:'city'">{{customer.name
    | uppercase}}- {{customer.city | lowercase}}</li>
    </ul>

    </div>

    </body>
    </html>
    ----------------------------------------------------------------------------------------------------

    you can define your own custom filters. to look at all the filters provided by the angular go to
    https://docs.angularjs.org/api and goto filters section.
    https://docs.angularjs.org/api/ng/filter
    you will see the list of filters provided by the angular.


    Thursday, April 16, 2015

    Spring Expression Language

    http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html

    You can find very descriptive details from the above mention link in the spring docs. The definition include as below..

    The Spring Expression Language (SpEL for short) is a powerful expression language that supports querying and manipulating an object graph at runtime. The language syntax is similar to Unified EL but offers additional features, most notably method invocation and basic string templating functionality.


    I am not going to rewrite what has already being well described with the spring docs, instead i thought of sharing some exceptions which might you experience.

    This is about the initial example of "Hello world " as Spring expression.

    You can simply create a class and inside main method you can directly run the code. I have just included inside static method.

    So below is the code


    ExpressionEvaluationWithSEI.java
    ------------------------------------------------------------------------------------------------------
    package com.spel;



    import org.springframework.expression.Expression;
    import org.springframework.expression.ExpressionParser;
    import org.springframework.expression.spel.standard.SpelExpressionParser;

    /**
     * http://docs.spring.io/spring/docs/current/spring-framework-reference/html/
     * expressions.html
     *
     * Expression Evaluation using Spring’s Expression Interface
     *
     * @author APrasad
     *
     */
    public class ExpressionEvaluationWithSEI {

    public static void evaluateLiteralStringExpression() {
    ExpressionParser parser = new SpelExpressionParser();
    Expression expression = parser.parseExpression("'Hello World'");
    String message = (String)expression.getValue();
    System.out.println("message ="+message);

    }

    public static void main(String[] args) {
    ExpressionEvaluationWithSEI.evaluateLiteralStringExpression();
    }
    }


    ------------------------------------------------------------------------------------------------------
    This will have simple output

    output
    =============================================================
    message =Hello World
    =============================================================


    Note : The word "Hello World"  is within the single quotes..... So if any case if you miss the single quotes , then you will probably witness below exception.

    change new code

    ------------------------------------------------------------------------------------------------------
    Expression expression = parser.parseExpression("Hello World");
    //Note :: I have remove the single quotes around the literal expression Hello World
    ------------------------------------------------------------------------------------------------------

    output
    =============================================================
    Exception in thread "main" org.springframework.expression.spel.SpelParseException: EL1041E:(pos 6): After parsing a valid expression, there is still more data in the expression: 'World'
    at org.springframework.expression.spel.standard.InternalSpelExpressionParser.doParseExpression(InternalSpelExpressionParser.java:118)
    at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:56)
    at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:1)
    at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpression(TemplateAwareExpressionParser.java:66)
    at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpression(TemplateAwareExpressionParser.java:56)
    at com.spel.ExpressionEvaluationWithSEI.evaluateLiteralStringExpression(ExpressionEvaluationWithSEI.java:22)
    at com.spel.ExpressionEvaluationWithSEI.main(ExpressionEvaluationWithSEI.java:29)

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



    Now let's also check other functionality given with the expression.


    ExpressionEvaluationWithSEI.java
    ------------------------------------------------------------------------------------------------------
    package com.spel;



    import org.springframework.expression.Expression;
    import org.springframework.expression.ExpressionParser;
    import org.springframework.expression.spel.standard.SpelExpressionParser;

    /**
     * http://docs.spring.io/spring/docs/current/spring-framework-reference/html/
     * expressions.html
     *
     * Expression Evaluation using Spring’s Expression Interface
     *
     * @author APrasad
     *
     */
    public class ExpressionEvaluationWithSEI {

    public static void evaluateLiteralStringExpression() {
    ExpressionParser parser = new SpelExpressionParser();
    Expression expression = parser.parseExpression("'Hello World'");
    String message = (String)expression.getValue();
    System.out.println("message ="+message);

    //newly added
    System.out.println("getExpressionString ="+expression.getExpressionString());
    System.out.println("toString ="+expression.toString());
    System.out.println("getValueType ="+expression.getValueType());
    }

    public static void main(String[] args) {
    ExpressionEvaluationWithSEI.evaluateLiteralStringExpression();
    }
    }

    ------------------------------------------------------------------------------------------------------

    output
    =============================================================
    message =Hello World
    getExpressionString ='Hello World'
    toString =org.springframework.expression.spel.standard.SpelExpression@18019707
    getValueType =class java.lang.String

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



    Friday, April 10, 2015

    Tricky Codes used to test your knowledge on Java

    I have came a cross few tricky Java coding. It's not difficult stuff, but pretty much tricky, where anybody will easily miss.

    1.

    package array;

    public class ChangeIt {

    static void doIt(int[] z) {
    z = null;
    }
    }


    package array;

    public class TestIt {
    public static void main(String[] args) {

    int[] myArray = { 1, 2, 3, 4, 5 };

    ChangeIt.doIt(myArray);

    for (int i = 0; i < myArray.length; i++) {
    System.out.print(myArray[i] + " ");
    }
    }
    }


    Output :::
    ----------------

    1 2 3 4 5 


    inside method "ChangeIt.doIt(myArray);" array reference is set to null. But it will be  a copy of the object , not the reference.

    But if you try to loop array inside method, then there will be NullPointerException
     eg : I have highlighted the code which will make NullPointerException.
    package array;

    public class ChangeIt {

    static void doIt(int[] z) {
    z = null;
    for (int i = 0; i < z.length; i++) {
    System.out.print(z[i] + " ");
    }
    }
    }

    Output
    ------------

    Exception in thread "main" java.lang.NullPointerException
    at array.ChangeIt.doIt(ChangeIt.java:8)
    at array.TestIt.main(TestIt.java:8)

    ---------------

    2. Above ChangeIt class sets the for "null", let's look at copying to separate array.


    package array;

    public class ChangeIt {

    static void doIt(int[] z){
    int A[] =z;
    A[0] =99;
    }
    }

    package array;

    public class TestIt {
    public static void main(String[] args) {

    int[] myArray = { 1, 2, 3, 4, 5 };

    ChangeIt.doIt(myArray);

    for (int i = 0; i < myArray.length; i++) {
    System.out.print(myArray[i] + " ");
    }
    }
    }

    output
    ==============================
    99 2 3 4 5

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

    Even though  we are changing the value of newly create array, it still has the reference to passes array (in this case "myArray" or the array comes from the parameter of that method). you may miss that it still has the reference and give output something like "1 2 3 4 5 " which is wrong.




    3. Using "this"  inside static context -  this will not allowed inside static context.
    This will have compile error.

    ----------------------------------------------------------------------

    public static void main(String[] args) {
    System.out.println(this);

    }

    ----------------------------------------------------------------------

    But you can use "this" out of static context.

    -----------------------------------------------------------------------
    public class Circle {
    private String name;

    public String getName() {
                   // this is allowed
    System.out.println(this);
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    }
    ---------------------------------------------------------------------------


    4. Java uses the call by value. What is the value that is being passed into routine by the method call in the following ??

    double[] rats ={1,2,3};

    routine(rats);

    correct Answer : A reference to the array object rats.

    you may try to deviate with first sentence  all by value and may give an answer like "A copy of the array rats" , which would be wrong.

    5. Array length
    ---------------------------------------

    int[] myArray = { 1, 2, 3, 4, 5 };

    ChangeIt.doIt2(myArray.length);

    ------------------------------------------

    length of the array is taken as property with "lenght" , but with our normal method standards ,we might choose an option like "myArray.length()" - word length with parenthesis.
    Remember : length does not have parenthesis.

    6. Retrieve values from an array
    Most important point in an array is its index starts with "0" - zero. We all know , but some how down the line we miss it. when thing become complicated you will probably my lose this fact.
    Output of the below code segment is 12, but you may miss it and select 13, which is wrong- you miss with the index.
    So array values starts with 5  and goes with 5,6,7,8,  ... until the end.
    we retrieve the index "7", that means 8th element , which is value equal to 12.
    -----------------------------------------------
                    int[] num5 = new int[9];
    for (int i = 0; i < num5.length; i++) {
    num5[i] = i+5;
    }
    System.out.println(num5[7]);
    ------------------------------------------------

    output
    =========================
    12
    ======================

    So the highest value associated with the array would be one less than length.
    eg : if we define array like

    byte[] value = new byte[x];

    the highest value for the index would be "x-1"


    Wednesday, April 8, 2015

    Relearning the Art of Asking Questions

    Relearning the Art of Asking Questions

    Proper questioning has become a lost art. The curious four-year-old asks a lot of questions — incessant streams of “Why?” and “Why not?” might sound familiar — but as we grow older, our questioning decreases. In a recent poll of more than 200 of our clients, we found that those with children estimated that 70-80% of their kids’ dialogues with others were comprised of questions. But those same clients said that only 15-25% of their own interactions consisted of questions. Why the drop off?
    Think back to your time growing up and in school. Chances are you received the most recognition or reward when you got the correct answers. Later in life, that incentive continues. At work, we often reward those who answer questions, not those who ask them. Questioning conventional wisdom can even lead to being sidelined, isolated, or considered a threat.
    Because expectations for decision-making have gone from “get it done soon” to “get it done now” to “it should have been done yesterday,” we tend to jump to conclusions instead of asking more questions. And the unfortunate side effect of not asking enough questions is poor decision-making. That’s why it’s imperative that we slow down and take the time to ask more — and better — questions. At best, we’ll arrive at better conclusions. At worst, we’ll avoid a lot of rework later on.
    Aside from not speaking up enough, many professionals don’t think about how different types of questions can lead to different outcomes. You should steer a conversation by asking the right kinds of questions, based on the problem you’re trying to solve. In some cases, you’ll want to expand your view of the problem, rather than keeping it narrowly focused. In others, you may want to challenge basic assumptions or affirm your understanding in order to feel more confident in your conclusions.
    Consider these four types of questions — Clarifying, Adjoining, Funneling, and Elevating — each aimed at achieving a different goal:
    W150324_POHLMANN_FOURTYPES
    Clarifying questions help us better understand what has been said. In many conversations, people speak past one another. Asking clarifying questions can help uncover the real intent behind what is said. These help us understand each other better and lead us toward relevant follow-up questions. “Can you tell me more?” and “Why do you say so?” both fall into this category. People often don’t ask these questions, because they tend to make assumptions and complete any missing parts themselves.
    Adjoining questions are used to explore related aspects of the problem that are ignored in the conversation. Questions such as, “How would this concept apply in a different context?” or “What are the related uses of this technology?” fall into this category. For example, asking “How would these insights apply in Canada?” during a discussion on customer life-time value in the U.S. can open a useful discussion on behavioral differences between customers in the U.S. and Canada. Our laser-like focus on immediate tasks often inhibits our asking more of these exploratory questions, but taking time to ask them can help us gain a broader understanding of something.
    Funneling questions are used to dive deeper. We ask these to understand how an answer was derived, to challenge assumptions, and to understand the root causes of problems. Examples include: “How did you do the analysis?” and “Why did you not include this step?” Funneling can naturally follow the design of an organization and its offerings, such as, “Can we take this analysis of outdoor products and drive it down to a certain brand of lawn furniture?” Most analytical teams – especially those embedded in business operations – do an excellent job of using these questions.
    Elevating questions raise broader issues and highlight the bigger picture. They help you zoom out. Being too immersed in an immediate problem makes it harder to see the overall context behind it. So you can ask, “Taking a step back, what are the larger issues?” or “Are we even addressing the right question?” For example, a discussion on issues like margin decline and decreasing customer satisfaction could turn into a broader discussion of corporate strategy with an elevating question: “Instead of talking about these issues separately, what are the larger trends we should be concerned about? How do they all tie together?” These questions take us to a higher playing field where we can better see connections between individual problems.
    In today’s “always on” world, there’s a rush to answer. Ubiquitous access to data and volatile business demands are accelerating this sense of urgency. But we must slow down and understand each other better in order to avoid poor decisions and succeed in this environment. Because asking questions requires a certain amount of vulnerability, corporate cultures must shift to promote this behavior. Leaders should encourage people to ask more questions, based on the goals they’re trying to achieve, instead of having them rush to deliver answers. In order to make the right decisions, people need to start asking the questions that really matter.

    The Science Of Why You Should Spend Your Money On Experiences, Not Things

    The Science Of Why You Should Spend Your Money On Experiences, Not Things


    You don't have infinite money. Spend it on stuff that research says makes you happy.
    Most people are in the pursuit of happiness. There are economists who think happiness is the best indicator of the health of a society. We know that money can make you happier, though after your basic needs are met, it doesn't make you that much happier. But one of the biggest questions is how to allocate our money, which is (for most of us) a limited resource.
    There's a very logical assumption that most people make when spending their money: that because a physical object will last longer, it will make us happier for a longer time than a one-off experience like a concert or vacation. According to recent research, it turns out that assumption is completely wrong.
    "One of the enemies of happiness is adaptation," says Dr. Thomas Gilovich, a psychology professor at Cornell University who has been studying the question of money and happiness for over two decades. "We buy things to make us happy, and we succeed. But only for a while. New things are exciting to us at first, but then we adapt to them."
    German skydiver via Shutterstock
    So rather than buying the latest iPhone or a new BMW, Gilovich suggests you'll get more happiness spending money on experiences like going to art exhibits, doing outdoor activities, learning a new skill, or traveling.
    Gilovich's findings are the synthesis of psychological studies conducted by him and others into the Easterlin paradox, which found that money buys happiness, but only up to a point. How adaptation affects happiness, for instance, was measured in a study that asked people to self-report their happiness with major material and experiential purchases. Initially, their happiness with those purchases was ranked about the same. But over time, people's satisfaction with the things they bought went down, whereas their satisfaction with experiences they spent money on went up.
    It's counterintuitive that something like a physical object that you can keep for a long time doesn't keep you as happy as long as a once-and-done experience does. Ironically, the fact that a material thing is ever present works against it, making it easier to adapt to. It fades into the background and becomes part of the new normal. But while the happiness from material purchases diminishes over time, experiences become an ingrained part of our identity.
    "Our experiences are a bigger part of ourselves than our material goods," says Gilovich. "You can really like your material stuff. You can even think that part of your identity is connected to those things, but nonetheless they remain separate from you. In contrast, your experiences really are part of you. We are the sum total of our experiences."
    One study conducted by Gilovich even showed that if people have an experience they say negatively impacted their happiness, once they have the chance to talk about it, their assessment of that experience goes up. Gilovich attributes this to the fact that something that might have been stressful or scary in the past can become a funny story to tell at a party or be looked back on as an invaluable character-building experience.
    Another reason is that shared experiences connect us more to other people than shared consumption. You're much more likely to feel connected to someone you took a vacation with in Bogotá than someone who also happens to have bought a 4K TV.
    Greg Brave via Shutterstock
    "We consume experiences directly with other people," says Gilovich. "And after they're gone, they're part of the stories that we tell to one another."
    And even if someone wasn't with you when you had a particular experience, you're much more likely to bond over both having hiked the Appalachian Trail or seeing the same show than you are over both owning Fitbits.
    You're also much less prone to negatively compare your own experiences to someone else's than you would with material purchases. One study conducted by researchers Ryan Howell and Graham Hill found that it's easier to feature-compare material goods (how many carats is your ring? how fast is your laptop's CPU?) than experiences. And since it's easier to compare, people do so.
    "The tendency of keeping up with the Joneses tends to be more pronounced for material goods than for experiential purchases," says Gilovich. "It certainly bothers us if we're on a vacation and see people staying in a better hotel or flying first class. But it doesn't produce as much envy as when we're outgunned on material goods."
    Gilovich's research has implications for individuals who want to maximize their happiness return on their financial investments, for employers who want to have a happier workforce, and policy-makers who want to have a happy citizenry.
    "By shifting the investments that societies make and the policies they pursue, they can steer large populations to the kinds of experiential pursuits that promote greater happiness," write Gilovich and his coauthor, Amit Kumar, in their recent article in the academic journal Experimental Social Psychology.
    If society takes their research to heart, it should mean not only a shift in how individuals spend their discretionary income, but also place an emphasis on employers giving paid vacation and governments taking care of recreational spaces.
    "As a society, shouldn't we be making experiences easier for people to have?" asks Gilovich.

    Tuesday, April 7, 2015

    Creating SOAP client

    1. create simple maven project.
    You can create directly if you use STS(Spring Tool Suite), Eclipse, you have maven plugin , or directly create using maven tool.

    2. Now you need to create subs for the client. To access the webservice.
    We will use the web service which was taken from the mkyong.
    http://www.mkyong.com/webservices/jax-ws/jax-ws-java-web-application-integration-example/

    This has some issues, missing jaxws-rt.jar etc. I have explained what you should do in
    http://cgenit.blogspot.com/2015/04/error-deploying-soap-application.html

    best thing is to add jaxws-rt.jar as maven dependency. you can get the maven dependency by simply doing a google search for maven dependency.

    let's get back  into building client stubs

    3. Now you need apache cxf libraries to build the stubs. These libs will give you access for specific set of commands where you can use for various purposes.
    You can donload this from apache cxf site.
    http://cxf.apache.org/docs/tools.html
    here i will be using wsdl2java , where this will help me to build the stubs.
    I have downloaded whole set. you can unzip where ever you need.
    I have unzip it to the "C:\Softwares\Apache" folder
    so my location for wsdl2java will looks like "C:\Softwares\Apache\apache-cxf-3.0.4\bin"
    this will have lots of

    Next use of the command "wsdl2java"

    4. set path to "wsdl2java"  tool
    take command prompt.
    you get the command prompt from the programs menu in windows or simply get the run (windows + R) , then type "cmd" and press enter.

    type "wsdl2java" in the command prompt.
    It will give the message
    =================================================================
    'wsdl2java' is not recognized as an internal or external command,
    operable program or batch file.
    =================================================================

    you need to set the path to the commands.

    below is the commad

    ===================================================================
    >set path=C:\Softwares\Apache\apache-cxf-3.0.4\bin
    ===================================================================

    bin folder is the directory, where you have all the apache tools including "wsdl2java"

    Now if you run the same command, you will get the output like as below.
    this is same as setting path to java bin

    note : i am executing the command from respective to the directory i have created
    "C:\waste\webservices\client\WebClientTest>" and it will prompt straight away for missing argument list.

    I have create "WebClientTest" directory to include the created stubs from "wsdl2java"


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

    C:\waste\webservices\client\WebClientTest>wsdl2java
    Missing argument: wsdlurl

    Usage : wsdl2java -fe|-frontend -db|-databinding -wv -p <[wsdl-namespace =]package-name>
    * -sn -b * -reserveClass * -catalog -d -compile -classd
    ir -impl -server -client -clientjar -all -autoNameResolution -allowElementReferences|-aer<=true>
     -defaultValues<=class-name-for-DefaultValueProvider> -ant -nexclude * -exsh <(true, false)> -noType
    s -dns -dex <(true, false)> -validate<[=all|basic|none]> -keep -wsdlLocation -xjc* -as
    yncMethods<[=method1,method2,...]>* -bareMethods<[=method1,method2,...]>* -mimeMethods<[=method1,method2,...]>* -noAddressBinding -faultSeri
    alVersionUID -encoding -exceptionSuper -mark-generated -h|-?|-help -version|-v -verbose
    |-V -quiet|-q|-Q -wsdlList


    WSDLToJava Error: org.apache.cxf.tools.common.toolspec.parser.BadUsageException: Missing argument: wsdlurl



    C:\waste\webservices\client\WebClientTest>

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



    5. create stubs

    run the command "wsdl2java -client http://localhost:8080/webservices/hello?wsdl"

    wsdl2java   - is the tool from apache cxf
    -clent -  choice given by apache tool wsdl2java to create client stubs
    http://localhost:8080/webservices/hello?wsdl  - is the location for wsdl, here i have used locally developed and deployed service in the tomcat, you can give any location to the wsdl file

    Note: I have not given the output directory for client stubs. stubs will be created in the directory where you are running the command.
    In my case it will be "C:\waste\webservices\client\WebClientTest"

    So my command and output will be
    Note: empty command return after execution of the command.
    This will create structure for stubs inside "C:\waste\webservices\client\WebClientTest" directory.

    ===================================================================
    C:\waste\webservices\client\WebClientTest>wsdl2java -client http://localhost:8080/webservices/hello?wsdl

    C:\waste\webservices\client\WebClientTest>

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



    6. Copy paste the created directory sructure to the src folder inside your maven project.
    Normally it has "src\main\java" folder structure.
    I have created the maven project with "WebClientTest" , so the structure would be "C:\eclipseWorkSpace\2015-01-19_SpringSecurity\WebClientTest\src\main\java"

    copy the stubs to "C:\eclipseWorkSpace\2015-01-19_SpringSecurity\WebClientTest\src\main\java"

    Note : stubs will have below folder structure
    "C:\waste\webservices\client\WebClientTest\com\mkyong\ws"

    where "C:\waste\webservices\client\WebClientTest\"  is the created folder for include stubs file by running "wsdl2java" command
    It will create stubs inside folder / or package structure "com\mkyong\ws" , this is the webservice code structure we have deployed in the tomcat.

    structure would be as below , where you will have 7 java files.
    ==============================================================

    C:\waste\webservices\client\WebClientTest\com\mkyong\ws>dir
     Volume in drive C is Windows
     Volume Serial Number is 76A1-C302

     Directory of C:\waste\webservices\client\WebClientTest\com\mkyong\ws

    04/07/2015  03:33 PM              .
    04/07/2015  03:33 PM              ..
    04/07/2015  03:33 PM             1,398 GetHelloWorld.java
    04/07/2015  03:33 PM             1,532 GetHelloWorldResponse.java
    04/07/2015  03:33 PM             1,219 HelloWorld.java
    04/07/2015  03:33 PM             3,417 HelloWorldService.java
    04/07/2015  03:33 PM             1,934 HelloWorld_HelloWorldPort_Client.java
    04/07/2015  03:33 PM             2,488 ObjectFactory.java
    04/07/2015  03:33 PM                99 package-info.java
                   7 File(s)         12,087 bytes
                   2 Dir(s)  386,769,772,544 bytes free

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

    7. Write main class / client  to test the created client and web service.

    create "ClientHello.java" class under package "com.webservices.client".
    We write the main method inside here.

    * first we create service object. Stubs will have a class with name "service". In this case it is "HelloWorldService" , this is an extension of "Service" provided by "javax.xml.ws" inside the "rt.jar"

                    // create service
    HelloWorldService helloWorldService =  new HelloWorldService();

    * Then we create the port object
                    // create soap object from service which is port. 
    HelloWorld helloWorld = helloWorldService.getHelloWorldPort();

    * once we create the port, we access the web service methods via the port. This time we have only one.
                   // through the port we call the methods.
    String output = helloWorld.getHelloWorld("John");

    * you ill see the out put as
                         Hello World JAX-WS John

    Below is the main method

    ClientHello.java
    =-==================================================================
    package com.webservices.client;

    import com.mkyong.ws.HelloWorld;
    import com.mkyong.ws.HelloWorldService;

    public class ClientHello {
    public static void main(String[] args) {

    // create service
    HelloWorldService helloWorldService =  new HelloWorldService();
    // create soap object from service which is port.
    HelloWorld helloWorld = helloWorldService.getHelloWorldPort();

    // through the port we call the methods.
    String output = helloWorld.getHelloWorld("John");

    System.out.println(output);
    }
    }

    =-==================================================================



    8. wsdl2java generates test client itself to test the generated stubs and webservice.
    In this case you have seen java class with the name "HelloWorld_HelloWorldPort_Client.java"
    This has the main method which has been design to test the webservice

    code will looks like below

    HelloWorld_HelloWorldPort_Client.java
    =-==================================================================

    package com.mkyong.ws;

    /**
     * Please modify this class to meet your needs
     * This class is not complete
     */

    import java.io.File;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.xml.namespace.QName;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebResult;
    import javax.jws.WebService;
    import javax.xml.bind.annotation.XmlSeeAlso;
    import javax.xml.ws.Action;
    import javax.xml.ws.RequestWrapper;
    import javax.xml.ws.ResponseWrapper;

    /**
     * This class was generated by Apache CXF 3.0.4
     * 2015-04-07T15:33:01.951+05:30
     * Generated source version: 3.0.4
     *
     */
    public final class HelloWorld_HelloWorldPort_Client {

        private static final QName SERVICE_NAME = new QName("http://ws.mkyong.com/", "HelloWorldService");

        private HelloWorld_HelloWorldPort_Client() {
        }

        public static void main(String args[]) throws java.lang.Exception {
            URL wsdlURL = HelloWorldService.WSDL_LOCATION;
            if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
                File wsdlFile = new File(args[0]);
                try {
                    if (wsdlFile.exists()) {
                        wsdlURL = wsdlFile.toURI().toURL();
                    } else {
                        wsdlURL = new URL(args[0]);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
         
            HelloWorldService ss = new HelloWorldService(wsdlURL, SERVICE_NAME);
            HelloWorld port = ss.getHelloWorldPort();
           
            {
            System.out.println("Invoking getHelloWorld...");
            java.lang.String _getHelloWorld_arg0 = "";
            java.lang.String _getHelloWorld__return = port.getHelloWorld(_getHelloWorld_arg0);
            System.out.println("getHelloWorld.result=" + _getHelloWorld__return);


            }

            System.exit(0);
        }

    }

    =-==================================================================


    output will be as below
    =-==================================================================

    Invoking getHelloWorld...
    getHelloWorld.result=Hello World JAX-WS
    =-==================================================================


    Note : we have invoked the "getHelloWorld" method with empty string. Default values has been set to empty string in the creation time from the "wsdl2java"

    so if you assign a value to "_getHelloWorld_arg0" it will have output with the given value.
    let's assign "John"

    the new code and value would be as below.


    HelloWorld_HelloWorldPort_Client.java
    =-==================================================================


    package com.mkyong.ws;

    /**
     * Please modify this class to meet your needs
     * This class is not complete
     */

    import java.io.File;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.xml.namespace.QName;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebResult;
    import javax.jws.WebService;
    import javax.xml.bind.annotation.XmlSeeAlso;
    import javax.xml.ws.Action;
    import javax.xml.ws.RequestWrapper;
    import javax.xml.ws.ResponseWrapper;

    /**
     * This class was generated by Apache CXF 3.0.4
     * 2015-04-07T15:33:01.951+05:30
     * Generated source version: 3.0.4
     *
     */
    public final class HelloWorld_HelloWorldPort_Client {

        private static final QName SERVICE_NAME = new QName("http://ws.mkyong.com/", "HelloWorldService");

        private HelloWorld_HelloWorldPort_Client() {
        }

        public static void main(String args[]) throws java.lang.Exception {
            URL wsdlURL = HelloWorldService.WSDL_LOCATION;
            if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
                File wsdlFile = new File(args[0]);
                try {
                    if (wsdlFile.exists()) {
                        wsdlURL = wsdlFile.toURI().toURL();
                    } else {
                        wsdlURL = new URL(args[0]);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
         
            HelloWorldService ss = new HelloWorldService(wsdlURL, SERVICE_NAME);
            HelloWorld port = ss.getHelloWorldPort();
           
            {
            System.out.println("Invoking getHelloWorld...");
            java.lang.String _getHelloWorld_arg0 = "John";
            java.lang.String _getHelloWorld__return = port.getHelloWorld(_getHelloWorld_arg0);
            System.out.println("getHelloWorld.result=" + _getHelloWorld__return);


            }

            System.exit(0);
        }

    }

    =-==================================================================

    output will be as below
    =-==================================================================

    Invoking getHelloWorld...
    getHelloWorld.result=Hello World JAX-WS John

    =-==================================================================

    Error deploying soap application : org.apache.catalina.core.StandardContext.listenerStart Error configuring application listener of class com.sun.xml.ws.transport.http.servlet.WSServletContextListener

    i have mkyong project to test web application deployment in tomcat. it was not working properly. So thought of sharing my thoughts.
    link is shown as below.
    http://www.mkyong.com/webservices/jax-ws/jax-ws-java-web-application-integration-example/


    Following is the error you will get when you try to deploy the web application in Tomcat.


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

    org.apache.catalina.core.StandardContext.listenerStart Error configuring application listener of class com.sun.xml.ws.transport.http.servlet.WSServletContextListener
     java.lang.ClassNotFoundException: com.sun.xml.ws.transport.http.servlet.WSServletContextListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1284)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1132)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:549)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:530)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:150)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4652)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5158)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:726)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:702)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:697)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:976)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1762)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)


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

    Solution : Add jaxws-rt.jar to the lib folder of the tomcat.

    you can download whole project from the
     https://jax-ws.java.net/
    Download jax-ws ri distribution
    unzip it and copy paste jaxws-rt.jar to tomcat lib folder
    restart tomcat.

    But there can be issue with 64 and 32 bit platforms.

    My suggestion is to add jaxws-rt as a maven dependency.

            <dependency>
    <groupId>com.sun.xml.ws</groupId>
    <artifactId>jaxws-rt</artifactId>
    <version>2.2.10</version>
    </dependency>


    This will add below list of dependencies to the lib folder inside "WEB-INF" in the built war file (maven build project war file). Numbers represent the size of each jar file and those might change with the time.

             296,714 FastInfoset-1.2.13.jar
              21,820 gmbal-api-only-3.1.0-b001.jar
              36,383 ha-api-3.1.9.jar
              26,366 javax.annotation-api-1.2.jar
              41,135 javax.xml.soap-api-1.3.7.jar
             102,308 jaxb-api-2.2.12-b140109.1041.jar
             234,226 jaxb-core-2.2.10-b140802.1033.jar
           1,040,864 jaxb-impl-2.2.10-b140802.1033.jar
              50,360 jaxws-api-2.2.11.jar
           2,505,911 jaxws-rt-2.2.10.jar
               7,989 jsr181-api-1.0-MR1.jar
              42,212 management-api-3.0.0-b012.jar
              63,134 mimepull-1.9.4.jar
             161,631 policy-2.4.jar
              68,177 resolver-20050927.jar
             474,791 saaj-impl-1.3.25.jar
              33,739 stax-ex-1.7.7.jar
             182,112 stax2-api-3.1.1.jar
              65,851 streambuffer-1.5.3.jar
             482,245 woodstox-core-asl-4.2.0.jar

    Once you do this you will get the output as "Hello World"
    This is what we have included inside the index.html page.
    ======================================================
    <html>
    <body>
    <h2>Hello World!</h2>
    </body>
    </html>
    ======================================================


    The link to the service also http://localhost:8080/webservices/  not " http://localhost:8080/WebServicesExample/hello "

    so if you need to access the wsdl use below link
    http://localhost:8080/webservices/hello?wsdl

    we are using hello?wsdl cause the webmethod is configured to 'hello' in the endpoint inside the "sun-jaxws.xml" where the configurations for the endpoints are given.


    java class

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

    package com.mkyong.ws;

    import javax.jws.WebMethod;
    import javax.jws.WebService;

    @WebService
    public class HelloWorld{

    @WebMethod(operationName="getHelloWorld")
    public String getHelloWorld(String name) {
    return "Hello World JAX-WS " + name;
    }

    }

    ===============================================
    sun-jaxws.xml
    =================================================


    <?xml version="1.0" encoding="UTF-8"?>
    <endpoints
      xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
      version="2.0">
      <endpoint
          name="HelloWorldWs"
          implementation="com.mkyong.ws.HelloWorld"
          url-pattern="/hello"/>
    </endpoints>
    ===========================================================



    the wsdl will looks like below
    http://localhost:8080/webservices/hello?wsdl
    ========================================================================
    This XML file does not appear to have any style information associated with it. The document tree is shown below.
    <!--
     Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.10 svn-revision#919b322c92f13ad085a933e8dd6dd35d4947364b.
    -->
    <!--
     Generated by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.10 svn-revision#919b322c92f13ad085a933e8dd6dd35d4947364b.
    -->
    <definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://ws.mkyong.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://ws.mkyong.com/" name="HelloWorldService">
    <types>
    <xsd:schema>
    <xsd:import namespace="http://ws.mkyong.com/" schemaLocation="http://localhost:8080/webservices/hello?xsd=1"/>
    </xsd:schema>
    </types>
    <message name="getHelloWorld">
    <part name="parameters" element="tns:getHelloWorld"/>
    </message>
    <message name="getHelloWorldResponse">
    <part name="parameters" element="tns:getHelloWorldResponse"/>
    </message>
    <portType name="HelloWorld">
    <operation name="getHelloWorld">
    <input wsam:Action="http://ws.mkyong.com/HelloWorld/getHelloWorldRequest" message="tns:getHelloWorld"/>
    <output wsam:Action="http://ws.mkyong.com/HelloWorld/getHelloWorldResponse" message="tns:getHelloWorldResponse"/>
    </operation>
    </portType>
    <binding name="HelloWorldPortBinding" type="tns:HelloWorld">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
    <operation name="getHelloWorld">
    <soap:operation soapAction=""/>
    <input>
    <soap:body use="literal"/>
    </input>
    <output>
    <soap:body use="literal"/>
    </output>
    </operation>
    </binding>
    <service name="HelloWorldService">
    <port name="HelloWorldPort" binding="tns:HelloWorldPortBinding">
    <soap:address location="http://localhost:8080/webservices/hello"/>
    </port>
    </service>
    </definitions>
    ========================================================================