Friday, December 18, 2015

Enhanced for loop and Immutability?

There I find a twist in the enhanced for loop and immutable nature. Where it does not change the data in an array of primitives, here I can see a clear variation.
Here is a Person class.
package test;
public class Person {
      private int pId;
      private String name;
      public Person(int pId, String name) {
          this.pId = pId;
          this.name = name;
     }
    public String toString(){
            return "Id : "+pId+" Name : "+name;
    }
    public int getpId() {
           return pId;
    }
    public void setpId(int pId) {
         this.pId = pId;
   }
   public String getName() {
         return name;
   }
   public void setName(String name) {
        this.name = name;
    }
}
And here is a tester class with enhanced for loop.
package test;
import static java.lang.Math.random;
import java.util.ArrayList;
import java.util.List;
public class PersonList {
      public static void main(String[] args) {
           List<Person> pList = new ArrayList<>();
           pList.add( new Person(101,"John"));
           pList.add( new Person(102,"James"));
           pList.add( new Person(103,"Dan"));
           pList.add( new Person(104,"Mathew"));
           pList.add( new Person(105,"Sam"));

          System.out.println("Added List elements : "+pList);
         /* To perfomr element wise operation */
          for(Person p : pList){
                System.out.println(p);
          }
         /* you try to modify the data in pList through enhanced for loop */
                System.out.println("List elements now : ");
                for(Person p : pList){
                     if(p.getName().equals("Sam"))
                          p.setName("Samuel");
                 }
/* OOPs... it has not changed...But let us conform it once again by using enhanced for loop */
          System.out.println("After Updation : view element in the list : ");
          for(Person p : pList){
                 System.out.println(p);
          }
  }
}
When I run this I see something different.
Added List elements : [Id : 101 Name : John, Id : 102 Name : James, Id : 103 Name : Dan, Id : 104 Name : Mathew, Id : 105 Name : Sam]
Id : 101 Name : John
Id : 102 Name : James
Id : 103 Name : Dan
Id : 104 Name : Mathew
Id : 105 Name : Sam
List elements now : 
After Updation : view element in the list : 
Id : 101 Name : John
Id : 102 Name : James
Id : 103 Name : Dan
Id : 104 Name : Mathew
Id : 105 Name : Samuel
Now the question is why the name gets changed from within the enhanced for loop. Now in previous post x reads data from ArrayList, and value change in x does not reflect in ArrayList. But in current example, p holds the reference to an object and using reference, it change the value. Rest is left to your imagination... :) !!!


Wednesday, December 16, 2015

Enhanced for Loop : Collections and Immutability

Enhanced for loop was added in Java SE 1.5. It can be used with Arrays and collections to iterate item-wise/element-wise. It works like read data of very ancient programming language called BASIC... atleast to me it looks like that... You can define read element of the collection element type and do operations on data. The amazing part is whatever you do to the read element, it does not disturb the original collection, that is data in for loop is immutable...
package test;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Math.random;
/**
*
* @author nkan
*/
public class EnhancedForLoop {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>();
for (int i=0;i<5;i++){
intList.add((int) (random() * 100));
}

System.out.println("Added List elements : "+intList);
/* To perfomr element wise operation */
for(int x : intList){
x++;
System.out.println("x = "+x);
}
/* you have incremented x, may be you are thinking that ArrayList : intList has be modified */
System.out.println("List elements now : "+intList);
/* OOPs... it has not changed...But let us conform it once again by using enhanced for loop */
System.out.println("After Updation : incremented element list is : ");
for(int x : intList){
System.out.println("x = "+x);
}
}
}
When I executed this program :
Added List elements : [98, 14, 30, 34, 43]
x = 99
x = 15
x = 31
x = 35
x = 44
List elements now : [98, 14, 30, 34, 43]
After Updation : incremented element list is : 
x = 98
x = 14
x = 30
x = 34
x = 43

Created and posted by Nancy @ 12/17/2015 2:25 am

Friday, October 16, 2015

Understanding mysterious static - 2

Oh! that was interesting, if you tried executing the program in the previous post. For a second may be it gave a food for thought to your mind. Why main is not executing first? Why am i getting output as:

In static block...InterestingStatic1
In main...InterestingStatic1

May be something is happening before main is executing. I must know it. Everything is mystery until understood. So let me take you to another interesting and mysterious scenario :

Here is what you do. Nothing much. Add InterestingStatic1Test class to the project you created yesterday. Let the class InterestingStatic1 be there in the project without any changes.

package teststatic;
public class InterestingStatic1Test {
    static{
        System.out.println("In static block...InterestingStatic1Test");
    }
    public void printSomething(){
        System.out.println("Just printing ... Welcome to Mysteries of Java");
    }
    public static void main(String[] args) {
        System.out.println("In main...InterestingStatic1Test");
        InterestingStatic1Test justObject = new InterestingStatic1Test();
        justObject.printSomething();
        InterestingStatic1 newObject = new InterestingStatic1();
    }
}

Yes, you are right. I am going to ask you to guess the output first and then run the program. Does it match your guess? Why the output is what it is.  wait... there is more to come ... See you...

©K.A.N. Nancy

Thursday, October 15, 2015

Understanding mysterious static - 1

package teststatic;
public class InterestingStatic1 {
    static{
        System.out.println("In static block...InterestingStatic1");
    }
    public static void main(String[] args) {
        System.out.println("In main...InterestingStatic1");
    }
}
What do you think should be the output. Normal understanding is main is executed first by JVM. Run this code. Do you find something unexpected?
More interesting code … tomorrow… let the mystery of static be resolved slowly, so that you enjoy…

©K.A.N. Nancy

Wednesday, October 14, 2015

static in Java - 1

When static block in java class is executed ?
     a) when the class is compiled
     b) when the first method in class is executed
     c) when the object is created, but before the constructor is called
     d) when the object is created and after the constructor is called
     e) when the class is loaded

©K.A.N. Nancy

Tuesday, October 13, 2015

Adding 2 numbers using Java

Let us have fun to add two numbers in variety of ways :

public class FunWithAdd {
   private int num1;
   private int num2;
  public FunWithAdd(int num1, int num2){
       this.num1=num1;
       this.num2=num2;
   }
   public int getNum1(){
       return num1;
   }
    public int getNum2(){
       return num2;
   }
    public void setNum1(int num1){
        this.num1=num1;
    }
    public void setNum2(int num2){
        this.num2=num2;
    }
   int sum(){
       return num1+num2;
   }
   int sum(int n1, int n2){
       return n1+n2;
   }
   int sumWithItr (int n1, int n2){
      int s=n1;
     
      for(int i=1;i<=n2;i++){
          s++;
      }
      return s;
   }
   int sumRecursive(int n1, int n2){
        if (n2 ==0){
            return n1;
        }
        return sumRecursive(++n1,--n2);
      }
   }

Create a class to test variety of sum methods.

public class Add2Nums {
    public static void main(String[] args) {
        /* Summing Locals */
        int num1=25;
        int num2=12;
        System.out.println("sum : "+(num1+num2));
        /* Sum using Object of FunWithAdd*/
        FunWithAdd numsObject= new FunWithAdd(30,60);
        System.out.println("Adding the numbers in Object : "+numsObject.sum());
        System.out.println("Adding the numbers in Object by sending data from outside :"+numsObject.sum(19,20));
        numsObject.setNum1(7);
        numsObject.setNum2(9);
        System.out.println("sum using sumWithItr method : "  +numsObject.sumWithItr(numsObject.getNum1(),numsObject.getNum2()));
         numsObject.setNum1(43);
        numsObject.setNum2(2);
        System.out.println("sum using sumRecursive: "+numsObject.sumRecursive(numsObject.getNum1(),numsObject.getNum2()));
    }
}

Output :
sum : 37
Adding the numbers in Object : 90
Adding the numbers in Object by sending data from outside :39
sum using sumWithItr method : 16
sum using sumRecursive: 45

Change the values and have fun… :)
©Nancy : created at 2:07 am IST

Java EE 6 Collocated Model

EJB 3.1 provides subset of EJB. This subset is known as EJBLite. EJBLite is available as a part of Java EE6 Web Container. You can create local EJBs with and without interface view. 


EJB 3.1 The benefit is when Web component and EJB component need to access the object for business processing, no marshaling is required. If an EJB makes changes in the object state , web component can view the changes. 

The local EJBs can be packaged in a WAR file. This is called as Collocated model of Java EE 6.

Sunday, June 21, 2015

Interesting Facts about JAVA - 2

Did you know ? (These were later removed from java)
1. All exceptions were unchecked
2. unprotect keyword could be used to avoid signaling asynchronous exceptions

Friday, June 19, 2015

Interesting facts about JAVA - 1

Did you know that the first name given to Java was OAK. And it is NOT an acronym. The name OAK was inspired by the  Oak tree that was seen from the office window.

Sunday, April 26, 2015

First Spring Application from scratch

Step – 0

Download and Install java 7 from http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html . Accept License Agreement. Install from zip file.

Step – 1


Step – 2


To install eclipse, unzip eclipse-jee-luna-SR2-win32-x86_64.zip in d:\eclipse.


Step – 3
To start eclipse double click eclipse.exe
Step – 4


Download spring-framework-4.1.6RELEASE-dist.zip file. Unzip this file in d:\spring folder.

Step – 5

Download Apache Commons Logging commons-logging-1.2-bin.zip. Unzip commons-logging-1.2-bin.zip to d:\ commons-logging-1.2 folder.

Step – 6

Download Apache Tomcat Web Application Server from http://tomcat.apache.org/download-70.cgi .
You will get apache-tomcat-7.0.61-windows-x64.zip file. Unzip apache-tomcat-7.0.61-windows-x64.zip to d:\ apache-tomcat-7.0.61.

Step – 7

Start eclipse by double clicking eclipse.exe. You can give a new name for the workspace you want to use for your Spring applications.


Step – 8

Create a new Java project in eclipse Luna IDE.


Select web Dynamic project.


Click Next and give the project name as MyFirstSpringWebApp.


Click next and next. At this point select Generate web.xml deployment descriptor.


And click Finish.

Step – 8 

Prepare your project to be spring web application. You need to add spring libraries to your web project.

Select lib folder in WEB-INF folder in webContent in your Web Application project.


Open d:\spring ( this is the folder where you have unzipped spring jars). Go to the lib folder, you will see all the jars. Select all the jars and copy (ctrl+A and CTRL+C), and then go to eclipse project and paste all these jars in lib folder.


It will look like this.

You need to add Common logging lib too. To do this go to D:\commons-logging-1.2 and copy commons-logging-1.2.jar. and paste this jar to WEB-INF\lib  in your project.

Step – 9 You need to add Application Server to your application. In eclipse IDE, select window ->showview ->others. SelectServer-> servers.


In eclipse IDE you will see server window with the following message…



Click on this link to add Server. Select Apache Tomcat 7.


Click on Add link. Give the path where you have unzipped the Tomcat Apapche 7 server.


Click Finish.

Step – 10

Right click your project and select properties. Select Target Runtime as Apache Tomcat 7.


Step - 11

Create Controller class. Right click your Spring project and select new -> class


Create a class MySpringTestController in package com.nancy.testspringapp.


Click Finish.

Add the following code to the class

package com.nancy.testspringapp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class MySpringTestController extends AbstractController {
      
       @Override
       protected ModelAndView handleRequestInternal(HttpServletRequest request,
              HttpServletResponse response) throws Exception {

              ModelAndView modelandview = new ModelAndView("MyGreetingsPage");
              modelandview.addObject("mygreetingMessage", "hello Welcome to Spring Learning !!!");

              return modelandview;
       }
}


Step – 12 

Add a new jsp page and name it MyGreetingsPage.jsp in WEB-INF and add the following code.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>My First Spring Web App</h1>
<h2> ${mygreetingMessage }</h2>
</body>
</html>

Step – 13

 Configure web.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>MyFirstSpringWebApp</display-name>
  <servlet>
  <servlet-name>spring-dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>spring-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

Step – 14

 Create spring-dispatcher-servlet.xml file in WEB-INF folder. Add the xml code to the file as:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
      
       <bean id="MyHandlerMapping"
       class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
      
    <bean name="/greetings.html"
       class="com.nancy.testspringapp.MySpringTestController" />    
      
       <bean id="viewResolver"
       class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
   </bean>
</beans>

You are ready to run your first Spring web application. 

Right click the project and Run As -> Run on Server.


You can run the application in internal or external browser by using the url http://localhost:8088/MyFirstSpringWebApp/greetings.html

Enjoy your first Spring Web Application... :)


Friday, April 24, 2015

Information As A Service - IAAS

Information As A Service enables reuse.  Layers of IAAS :

  • Data Sources
  • Data management, Data processing, Data movement
  • Data virtualization
  • Information services
  • Information access

Thursday, April 23, 2015

Ingestion Latency

Ingestion latency can be – 
  • Batch – Data is ingested at regular intervals
  • Micro Batch – ingests delta of data (since last ingestion)
  • Trickle Feed – Continuously ingests data

Saturday, April 18, 2015

Hybrid Enterprise Architecture Framework

Do you know that Hybrid Enterprise Architecture Framework is influenced by ...

a)     TOGAF (The Open Group Architecture Framework)
b)     FEA (Federal Enterprise Architecture)
c)     Gartner Methodology

Friday, April 17, 2015

QoS Matters

Here are some factors that contribute to QoS (Quality of Service).
  • System architecture
  • Data resource layout
  • Utilization profiles
  • Load factors
Any thoughts?

Thursday, April 16, 2015

It is about Integration

Do you agree that integration must consider every part of Enterprise system i.e. hardware, software, processes and architecture.

  • Yes
  •  No

Wednesday, April 15, 2015

Web Service Security

Here are some XML based Security schemes for Web Services... Can you add something more to this?

XML Encryption
XML Signatures
XACML (Extensible Access Control Markup Language)
SAML (Security Assertion Markup Language)



Tuesday, April 14, 2015

Web Service Security - A Question

SSL provides transport as well as message level security for web Services.
  • True
  •  False

Monday, April 13, 2015

Just a Question - Integration

You have created a stateless session bean for distributed logic. You want to access this EJB from Non-Java  client. You want to create a single reusable solution

  •          Create a Non-Java component with required Technology
  •              Expose it as a web service
  •              Other ( if you answer other… specify, what would you like to do…)

Friday, April 10, 2015

AtomicOperations

Atomic operations are singular ( an operation which cannot be stopped in between). Just like a transaction it happens completely or does not happen at all. The operations which are atomic :
  1. Read and write for reference variables
  2. Read and write for byte, short, int, char, float and Boolean
  3. Read and write for all variables declared with volatile qualifier ( this include all primitive types)
Operations like increment and decrement looks like atomic operations, but there is guarantee for the same. As any increment operation x++ can be a group of three operations
a)      Temporary copy of x will be created
b)      Temporary copy will be incremented
c)       Newly incremented value will be written back to variable x

Variables of type double and long are 64 bit and can be accessed by 2 32-bit operations. During concurrent programming, this can create compromise integrity of data. Java.util.concurrent provides atomic APIs to solve this problem. Let us take a look at an example:

package atomicops;

import java.util.concurrent.atomic.AtomicLong;

/**
 *
 * @author Nancy
 */
public class TestAtomicLong {
    public static void main(String[] args) {
        AtomicLong myLong= new AtomicLong(25);
     
        long x = myLong.getAndAdd(20);
        System.out.println("x ="+x);
        x=myLong.get();
        System.out.println("x ="+x);
     
        x = myLong.addAndGet(30);
        System.out.println("x ="+x);
     
        boolean b = myLong.compareAndSet(75,100);
        System.out.println("b ="+b);
        x=myLong.get();
        System.out.println("x ="+x);
     
        x= myLong.incrementAndGet();
        System.out.println("x="+x);
     
         x= myLong.decrementAndGet();
        System.out.println("x="+x);
    }  
}

Output :
x =25
x =45
x =75
b =true
x =100
x=101
x=100

Other Atomic operation classes are : 

©Nancy
11th April, 2015
2:34 am

Thursday, January 1, 2015

SOA Question 4

Web Service contains

a) Contract
b) A mandatory Java class
c) Interface
d) Implementation