Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Wednesday 31 July 2013

Spring Security - Authentication & Authorization for web applications

Spring Security (or Acegi) is a powerful authentication and authorization framework for securing Spring-based applications.It provides option for web request level and at the method invocation level as well. Spring Security utilizes dependency injection (DI) and aspect oriented techniques effectively.

There are many useful links which provide helps, reference, tutorials etc. to getting started with Spring Security:

http://static.springsource.org/spring-security/site/start-here.html
http://www.mularien.com/blog/2008/07/07/5-minute-guide-to-spring-security/
http://www.gigaspaces.com/wiki/display/XAP71/Authenticating+against+a+database
http://teja.tejakantamneni.com/2008/08/spring-security-using-custom.html
http://blog.solidcraft.eu/2011/03/spring-security-by-example-set-up-and.html

You can customize it for pre-authenticated scenarios as well.

Common Spring Security (SS) interview questions:
1) What is spring security? How will you implement it in your project OR How will you secure your Spring application?
2) What are the main components or Architecture of SS?
3) What is difference between Spring Security 2.x & 3.0?
4) What are AuthenticationManager, ProviderManager, AuthenticationProviders & AccessDecisionManager?
5) What is PreAuthenticatedAuthenticationProvider?
6) What is Security namespace?
7) What is the element? How do you configure it?
8) How would you integrate security with LDAP or OpenId?
9) What are SecurityContextHolder, SecurityContext and Authentication Objects?
10) What is UserDetailsService?


Answers will follow soon.

How will you write an own immutable class in java ?

Writing an immutable class is generally easy but there can be some tricky situations. Follow the following guidelines:

1. A class is declared final (i.e. final classes cannot be extended).
public final class MyImmutable { ? }

2. All its fields are final (final fields cannot be mutated once assigned).
private final int[] myArray; //do not declare as Æ private final int[] myArray = null;

3. Do not provide any methods that can change the state of the immutable object in any way ? not just setXXX
methods, but any methods which can change the state.

4. The ?this? reference is not allowed to escape during construction from the immutable class and the immutable

class should have exclusive access to fields that contain references to mutable objects like arrays, collections
and mutable classes like Date etc by:

Declaring the mutable references as private.

Not returning or exposing the mutable references to the caller (this can be done by defensive copying)

Wrong way to write a constructor:

public final class MyImmutable {
private final int[] myArray;
public MyImmutable(int[] anArray) {
this.myArray = anArray; // wrong
}
public String toString() {
StringBuffer sb = new StringBuffer("Numbers are: ");
for (int i = 0; i < myArray.length; i++) {
sb.append(myArray[i] + " ");
}
return sb.toString();
}
}
// the caller could change the array after calling the
constructor.
int[] array = {1,2};
MyImmutable myImmutableRef = new MyImmutable(array) ;
System.out.println("Before constructing " + myImmutableRef);
array[1] = 5; // change (i.e. mutate) the element
System.out.println("After constructing " + myImmutableRef);
Out put:
Before constructing Numbers are: 1 2
Right way is to copy the array before assigning in the constructor.
public final class MyImmutable {
private final int[] myArray;
public MyImmutable(int[] anArray) {
this.myArray = anArray.clone(); // defensive copy
}
public String toString() {
StringBuffer sb = new StringBuffer("Numbers are: ");
for (int i = 0; i < myArray.length; i++) {
sb.append(myArray[i] + " ");
}
return sb.toString();
}
}
// the caller cannot change the array after calling the constructor.
int[] array = {1,2};
MyImmutable myImmutableRef = new MyImmutable(array) ;
System.out.println("Before constructing " + myImmutableRef);
array[1] = 5; // change (i.e. mutate) the element
System.out.println("After constructing " + myImmutableRef);
Out put:
Before constructing Numbers are: 1 2
After constructing Numbers are: 1 5
As you can see in the output that the ?MyImmutable? object
has been mutated. This is because the object reference gets

After constructing Numbers are: 1 2
As you can see in the output that the ?MyImmutable? object has not
been mutated.

Wrong way to write an accessor. A caller could get the array
reference and then change the contents:
public int[] getArray() {
return myArray;
}
Right way to write an accessor by cloning.
public int[] getAray() {
return (int[]) myArray.clone();
}

Concept : Beware of using the clone() method on a collection like a Map, List, Set etc because they are not only difficult
to implement but also the default behavior of an object?s clone() method automatically
yields a shallow copy. You have to deep copy the mutable objects referenced by your immutable class.
section for deep vs. shallow cloning and for why you will be modifying the original object if you do not
deep copy.

Social bookmarking

I came know of this quite recently. I find it quite useful. Apart from being able share your bookmarks across browsers, you can now share them with others too. del.icio.us offers quite cool features for sharing your favorite bookmarks. You can share your bookmarks, tag them (i.e. use keywords to categorize them), find other users with similar interests and browse through their bookmarks. I find it a very good source for finding resources - a selective search for the topics you are interested in.
And to add to that, you can even have browser buttons to quickly add any bookmarks you find to your online bookmarks.

Here is my delicious:

My delicious

Smells to refactorings cheat sheet

Smells to Refactorings Cheat Sheet is freely available -- see the top item on the industriallogic site.

Abstract class concept in Java

Concept :
we know object of abstract class can not be created. but when we create an obj
of subclass of abstract class then the constructer of super class must be run and since constucter run obj must be created then how can we say obj of abst class can not be created.

Explanation:

Regarding the Abstract Class problem, it's not that an object of an abstract class is never created. By saying that an object of an abstract classes can't be created we mean that they can't be created explicitly and independently. That means you can't have any code creating them independently.

But, as you have mentioned that while creating a subclass object the object of superclass is always created first and abstract classes are also no exceptions in this case. Otherwise you can't access the accessible members of an abstract superclass in an object of any of its subclasses. All right?

You might have noticed that any code trying to instantiate an abstract class explicitly throws a compile-time error, which means the compiler checks the corresponding classes for every direct instantiation and reports errors whenever it finds any of them being anything other than a concrete class. The error may be thrown if it's an abstract class or an interface or something of that sort. Right?

The moral is that the objects of abstract classes are certainly created (otherwise the whole concept of superclass-subclass object creation would go awry), but only implicitly :-)

What I understand is that this check is only at the compiler level, so what'll happen if somebody manages to temper the bytecodes somehow with the addition of direct instantiation code of an abstract class without disturbing the allowed bytecodes format (otherwise the Verifier component of Linker would throw an error)? I'm not sure if that's possible at all. The Verifier is quite conservative in nature and I believe it should be able to recognize even a slight bytecode tempering.

Why wait(), notify() and notifyAll() methods have been defined in the Object class?

Java concurrency model uses locks to implement mutually exclusive access to objects in a multi-threaded environment and locks are associated with every object in Java (of type 'Object'), not only with Threads.

wait, notify/notifyAll methods are used by threads to communicate with each other while trying to access a common object. Putting it differently, objects become a medium via which threads communicate with each other. For example: suppose there is a 'telephone' object, which at one point of time can be used by only one thread. Like every other object in Java, 'telephone' object would also have an intrinsic lock (monitor) associated with it which at one point of time can be acquired by only one thread. Suppose the 'telephone' object requires activation before it can be used and suppose only a few admin threads can activate the 'telephone' object.

As soon as a thread needs access to the 'telephone' object, it checks if the lock on that 'telephone' object is available or not, if yes, it acquires that and checks if the 'telephone' is active or not. If yes, it starts using it otherwise it calls 'wait()' on the telephone object which effectively releases the monitor of the 'telephone' object (eventually to be acquired by one of the admin threads for its activation) and puts the requester thread into the wait-set of the 'telephone' object. The requester thread goes into WAITING state. The way every object in Java has an intrinsic lock associated with it, it has an intrinsic wait-set associated with it as well.

Every other non-admin requester thread goes through the same process as discussed above till one of the admin threads acquire lock on the 'telephone' object and eventually activates it and subsequently calls 'notify()' or 'notifyAll()' on the 'telephone' object. 'notify()' will simply pick one of the threads from the wait-set of the 'telephone' object (which one will be picked is an implementation dependent stuff and Java Language specification doesn't enforce any restriction on which one to be picked) and the chosen thread will now get out of WAITING mode and start trying to acquire the monitor/lock of the 'telephone' object along with any other thread that might be vying to access the 'telephone' at that point of time.

The only difference between 'notify' and 'notifyAll' is that in case of the latter all the threads of the corresponding wait-set are picked and they all start trying to acquire the lock on the object (with any other incoming requester thread) at the same time.

Evidently you see that these three methods are essentially object-related and not thread-related and hence the designers of Java Language considered it wise to put them in the Object class instead of putting them into the Thread class. The usage of the 'object' (in our case 'telephone') is the particular object's prerogative and not that of the requester threads'. Putting these three methods in the Object class helps the objects owning/controlling their usage in a better way as in that case a thread needs to first acquire the lock on the object (kind of getting a license to use the object) and then calling either wait (in case the thread doesn't find the object in the state it would have wished it to be in and hence thought of waiting for some time to let the object become useful for it) or notify/notifyAll to alert other threads waiting on the object once it finishes using the object (of course in the case when the thread find the object useful in its current state).

Additionally, the communication among the interested threads becomes far too easier when the control is kept at the object's level - one common shared resource/medium and all interested threads communicating via it. Not that the communication won't be possible if these methods are kept in the Thread class, but the handling of the communication and usage of the objects in a multi-threaded environment will probably become more complex and less flexible in that case.

Use of Equals() method in ArrayList in C# | Importance of Equals() method in C# .NET

ArrayList contains method  in c#

Concept : Use of Equals()  method in C#

Look the below code and output

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class employee
    {
        public string name;
        public string id;
        public employee(String name, String id)
        {
            this.name = name;
           
            this.id = id;
        }
      
    }
   
    class ArrayTest
    {
    static void Main()
        {
            ArrayList ar = new ArrayList();
           ar.Add("kumud");
           ar.Add("Raju");
           ar.Add("yugdeep");
      
          Console.WriteLine("Array Contain " + ar.Contains("kumud");
    }

    }
}


Output :
 
   Array Contain  True


Now again look the code below :

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class employee
    {
        public string name;
        public string id;
        public employee(String name, String id)
        {
            this.name = name;
           
            this.id = id;
        }
   
    }
   
    class ArrayTest
    {
    static void Main()
        {
              ar.Add(new employee("sandeep","3"));
              ar.Add(new employee("yugdeep", "3"));
              ar.Add(new employee("kumud", "3"));
           
               Console.WriteLine("Array Contain " + ar.Contains(new employee("sandeep","3"));

        }

    }
}
 

Output :

Array Contain False

Concept :  In case of when we adding string object its come true but in case of adding employe and searching for that particular
           object it comes false , reason behind is that string by default override the object's Equal() method in such way that
          it compare two string and return true but in case of employee class object there is no equals() method override
          ArrayList contain method search the Equals() method in object .so in case of employee there is no Equals() method mechanism
          so it coming False

Now we override Equals() method


using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class employee
    {
        public string name;
        public string id;
        public employee(String name, String id)
        {
            this.name = name;
           
            this.id = id;
        }
        public override bool Equals(Object o)
        {
           
            employee e = (employee)o;
          return (e.name.Equals(this.name));
          
        }
      
    }
   
    class ArrayTest
    {
    static void Main()
        {
             ArrayList ar = new ArrayList();
           ar.Add(new employee("sandeep","3"));
             ar.Add(new employee("yugdeep", "3"));
             ar.Add(new employee("kumud", "3"));
      
              Console.WriteLine("Array Contain " + ar.Contains(new employee("sandeep","3"));    }

    }
}

Output :

Array Contain True

IBM DB2 Free

IBM has released a free version of DB2 named DB2 express-C. It is free for development, deployment, and redistribution. It is supported on the x86 and x86-64 architectetures and is runs on Linux and Windows (2000, 2003, XP). Added to that, this version is seamlessly upgradable to DB2 UDB, if the requirements change. The catch here is: DB2 Express-C is designed to only run on systems with a maximum of two processor cores, or dual-core processors and upto 4GB memory.
It is available for download on IBM downloads.
There is also a DB2 express forum, where you can get community support for this product.

Testing Struts Applications

In the latest article in the "In pursuit of code quality" series, Andrew Glover discusses a quality-centered approach to the test on Struts, using JUnit's StrutsTestCase, DbUnit. Here is a brief summary :Since the struts Action classes are the entry point to the business logic, there is too much coupling associated with them. Testing struts based application needs the use of a servlet container, HttpServletRequest and HttpServletResponse classes. Simpler tools are available for testing such applications:
  • StrutsTestCase is a JUnit extension that specifically targets Struts applications. This framework essentially mocks a servlet container, such that you can run and test a Struts application virtually rather than having to run it in Tomcat. The framework also has a handy MockStrutsTestCase class, which extendsTestCase and handles a lot of the Struts configuration aspects for you (such as loading the struts-config.xml configuration file).
  • DbUnit is a JUnit extension that facilitates placing a database into a known state between test runs. Using XML seed files, you can insert specific data into a database, which a test case can then rely on. Moreover, using the DbUnit API, you can easily compare the contents of the database to the contents of an XML file, thus providing a mechanism to verify expected database results outside of application code.
Using these two frameworks together lets you do integration-level testing on Struts apps without the need for browser simulations in JWebUnit etc.

File Upload with Servlet 3.0

This code works on Glassfish 3.
This is a simple example of how to upload files using JSP and Servlet 3.0 which is a part of Java EE 6. While in earlier versions of Servlets we had to use commons fileupload or other libraries, this feature has been integrated into the Servlet 3.0 specification. Here is the code for a simple servlet and a JSP file that makes a file upload request to the servlet.

Full post
  1. FileUploadServlet.java
    package com.blogspot.aoj.servlet3;

    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;

    import org.apache.log4j.Logger;

    @WebServlet(urlPatterns = "/fileUpload")
    @MultipartConfig
    public class FileUploadServlet extends HttpServlet {
    private static Logger logger = Logger.getLogger(FileUploadServlet.class);

    public FileUploadServlet() {
    super();
    }

    protected void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    for (Part part : request.getParts()) {
    logger.info(part.getName());
    InputStream is = request.getPart(part.getName()).getInputStream();
    int i = is.available();
    byte[] b = new byte[i];
    is.read(b);
    logger.info("Length : " + b.length);
    String fileName = getFileName(part);
    logger.info("File name : " + fileName);
    FileOutputStream os = new FileOutputStream("c:/temp/logs/" + fileName);
    os.write(b);
    is.close();
    }

    }

    private String getFileName(Part part) {
    String partHeader = part.getHeader("content-disposition");
    logger.info("Part Header = " + partHeader);
    for (String cd : part.getHeader("content-disposition").split(";")) {
    if (cd.trim().startsWith("filename")) {
    return cd.substring(cd.indexOf('=') + 1).trim()
    .replace("\"", "");
    }
    }
    return null;

    }

    protected void doPost(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
    }

    }
    Note:
    • There is no need to use a deployment descriptor the @WebServlet annotation is enough, which uses the urlPatterns property to define servlet mappings
    • The @MultipartConfig is used to indicate that the servlet expects requests wof multipart/form-data MIME type which is required for file upload. Using @MultipartConfig allows you to use the request.getParts get the parts of the request
    • The getFileName method gets the file name from the content-disposition header.
  2. upload.jsp
    <html>
    <head>
    <title>File Upload with Servlet 3.0</title>
    </head>
    <body>
    <form action="fileUpload" enctype="multipart/form-data" method="post">
    <input type="file" name="uploadFile" /> <input type="submit" /></form>
    </body>
    </html>

Multiple Scenario of try , catch and finally in exception handling in java

Following Below multiple scenario question related to try, catch and finally block in exception handling in java
Scenario #1: try throwing an exception; catch and finally both having return statements


public class TestFinally {

/**
* @param args
*/
public static void main(String[] args) {

System.out.println("Inside main method!");
int iReturned = new TestFinally().testMethod();
System.out.println("Returned value of i = " + iReturned);

}

public int testMethod(){

int i = 0;
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i;
}
}
}


Output: a return (or any control transfer for that matter) in finally always rules!



Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Returned value of i = 300


Scenarios #2: try having exception-free code and a return; catch and finally both have return




...
try{
System.out.println("Inside try block of testMethod!");
i = 100;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i;
}
...


Output: did you get the first one right? This is a cakewalk then. With the same logic that any control transfer in finally always rules we can easily predict the output to be similar to that of Scenario #1 with the only difference that in this case the catch block won't be executed as no exception thrown... all right? Here is the output:



Inside main method!
Inside try block of testMethod!
Inside finally block of testMethod!
Returned value of i = 300


Scenario #3: try having exception; finally doesn't have a return



...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
//return i;
}
...


Output: no return in finally means whatever executable return encountered on the way to finally will be executed once finally completes its execution, so the output would be:



Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Returned value of i = 200


Scenario #4: try and catch both having exception; finally having a return



...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200/0;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i;
}
...


Output: control transfer in finally overrules the exceptions thrown in try/catch, hence the output would be:



Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Returned value of i = 300


Scenario #5: try and catch both having exception; finally NOT having any return



...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200/0;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
//return i;
}
...


Output: since no return in finally, hence after the execution of the finally block the sheer need to have an executable return statement (which doesn't exist in this case as catch also has an exception) would throw the exception encountered right before the finally execution started, which would be the exception in catch block in our case...right? So, the output would be:



Exception in thread "main" java.lang.ArithmeticException: / by zero
at TestFinally.testMethod(TestFinally.java:24)
at TestFinally.main(TestFinally.java:10)
Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!


Scenario #6: try, catch, and finally all three having exceptions



...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200/0;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i/0;
}
...


Output: evidently the exception would be thrown, but which one? The one which was encountered last i.e., the one encountered in the finally block. Output would be:



Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TestFinally.testMethod(TestFinally.java:30)
at TestFinally.main(TestFinally.java:10)


Scenario #7: try and catch both fine; finally doesn't have any return



...
try{
System.out.println("Inside try block of testMethod!");
i = 100;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
//return i;
}
...


Output: well... first thing first. If try is fine, do we need to even think about catch? A BIG No... right? Okay, so we have try and finally blocks to focus on. Let me first show you the output and then we would discuss if you have any doubts. Here is it:



Inside main method!
Inside try block of testMethod!
Inside finally block of testMethod!
Returned value of i = 100

Welcome

Hi friends.
A place for things i would like to share with you!
bye!!

Rails: Rails vs Tapestry

Rails vs Tapestry
check this java guys
plz comment out ur opinion!
bye

Cognizant's Combined Campus Freshers Recruitment Drive



Eligibility Criteria for IT:
  1. Open only to the students with following degrees
    • Category 1: BE / B Tech / ME / M Tech / MCA / M Sc (Computer Science / IT / Software Engg)

    • Category 2: B Sc / BCA / M Sc (except Computer Science / IT / Software Engg)


  2. Year of graduation:  2011 batch only

  3. Consistent First Class (over 60%) in X, XII, UG and PG (if applicable)

  4. No outstanding arrears

  5. Candidates with degrees through correspondence/ part-time courses are not eligible to apply

  6. Good interpersonal, analytical and communication skills


Eligibility Criteria for IT IS:

  1. Open only to the students with following degrees

    • BSC - Computer Science/Computer Technology/ IT /Maths/Statistics/Electronics and BCA

    • MSC - Maths/Statistics/Electronics

  2. Year of graduation: 2011  batch only

  3. Consistent First Class (over 60%) in X, XII, and UG

  4. Candidates holding correspondence or part time degrees are not eligible to apply

  5. Good interpersonal and excellent communication skills

  6. Willingness to work in shifts (including night shifts)

  7. Willing to work at any Cognizant location across India


Eligibility Criteria for BPO:

  1. Any Arts & Science graduate except BSC – IT/CS, Electronics, Maths & Statistics

  2. Hotel Management & MBA graduates are also eligible

  3. Year of Graduation: 2011  batch only

  4. Consistency of 50% in X, XII, and UG

  5. Good verbal and excellent communication skills

  6. Willingness to work in shifts (including night shifts)


Click Here to apply for the above jobs.
or click the below link.



All the best,
Regards,
Chandrasekhara.

Session tracking in Java application | session concept in java

Plainly because HTTP is a stateless protocol. That means a Web Server handling HTTP requests doesn't maintain contextual info about the client requests coming to it. Putting it differently, the Web Server doesn't have a built-in way to recognize whether the current request is coming from a new client or from a client which has been communicating with it for a while now. This happens because every HTTP request is treated as an altogether new request.


As we can easily imagine that such a behavior can cause so many problems - for example, if a user has logged into his Bank Account and after a successful login if he wishes to go to the Funds Transfer page then he would be required to login again as Funds Transfer would be a login-protected page and the Web Server doesn't have any built-in support for recognizing if the clinet requesting this page is the one who is alraedy logged in or if it's coming from a new client. This is just a simple example... we can easily imagine how difficult will it be to develop a Web-Application without maintaining contextual information about the clients.


What are the various ways of tracking Sessions?


There are three ways of tracking sessions. In other words, there are three ways of maintaining contextual information about clients as a session is nothing but a collection of various information about the particular client the session has been built and maintained for. Three ways of session tracking in servlets are:-

    Using Cookies - Cookies are stored at the client side (in the browser's cache) and they are used to maintain the current session. Every cookie object stores contextual information for that particular session and it's always associated with a unique Session ID, which is sent to the server on creation of the cookie. The server uses that Session ID to locate the cookie at the clinet machine and then it uses the contextual information stored in that cookie object for various purposes including client authentication, client authorization, retrieving/saving data which the client may require in subsequent steps, etc. A timeout period for the cookie objects can be set after which they will become expired. Cookies may be a security threat as the Session ID may be used to track the particular cookie and then to retrieve secure information from it. This is the reason why all the browsers provide options to either enable or disable cookies at the user's discretion. You can simply disable Cookies by updating your browser options.

    Using URL Rewriting - This approach of maintaining sessions requires an extra peice of data to be appended to each URL. This extra info is used to identify the session and the server associates this identifier with the data it has stored for that particular session. The advantage of this approach is that it works even in those cases where the user has disabled cookied for their browsers. In this approach nothing is actually stored at the client side and all the sessio tracking info travels via URLs back and forth. SO, you may obviously lose the session information (the session would have been invalid due to timeout) if you bookmark an URL first and then try to access that later on.

    Using Hidden Form Fields - This is another approach of maintaining session where the contextual data travels via hidden form fields (<INPUT TYPE="hidden" ...). There are two main disadvantages of this approach: One, one can easily see all the data (maybe some secret info) by looking at the HTML Source of the page and Two, this approach will probaly work only for dynamic web pages (how would we maintain different session with unique identifiers otherwise?).

Exception Concept in Java | how try , catch and finally block work in java during exception found

Exception Concept in java

Exception

    +--------+
                    | Object |
                    +--------+
                |
                |
                   +-----------+
           | Throwable |
                   +-----------+
                    /         \
           /           \
          +-------+          +-----------+
          | Error |          | Exception |
          +-------+          +-----------+
       /  |  \           / |        \
         \________/      \______/         \
                            +------------------+
    unchecked     checked    | RuntimeException |
                    +------------------+
                      /   |    |      \
                     \_________________/
                      
                       unchecked


Exception hadling using try, catch, finally


    try {
       // statements that might cause exceptions
       // possibly including function calls
    } catch ( exception-1 id-1 ) {
       // statements to handle this exception
    } catch ( exception-2 id-2 ) {
       // statements to handle this exception
    .
    .
    .
    } finally {
       // statements to execute every time this try block executes
    }

concept:

    Each catch clause specifies the type of one exception, and provides a name for it (similar to the way a function header specifies the type and name of a parameter). Java exceptions are objects, so the statements in a catch clause can refer to the thrown exception object using the specified name.

    The finally clause is optional.

    In general, there can be one or more catch clauses. If there is a finally clause, there can be zero catch clauses.


concept 1;


what will output :

package com.exception;
import java.util.ArrayList;
public class exceptionTest {
   
    public String getName() {
  
    try{
   
     return "kumud";
   
    }
    catch(Exception ex)
    {
    System.out.println("Finally Exception##  try in getName method");
       
    }
    finally
    {
        System.out.println("Finally Exception## finally in getName method");
        return "kumud5";
    }
   
   
    }
   
    public static void main(String [] args)
    {
        ArrayList ar= new ArrayList();
        exceptionTest exp= new exceptionTest();
        try
        {
            System.out.println("Exception is"+exp.getName());
           
               
        }
        catch(Exception ex)
        {
            System.out.println("Exception##"+ex);
           
        }
        finally
        {
            System.out.println("Finally Exception##");
        }
       
    }

}

Output:

Finally Exception## finally in getName method
Exception iskumud5
Finally Exception##

Exp:
    in try block there is return method as well as in finally block also . but output is return from finally block reason behind that finally will execute either
    exception is found or not in any any condition while return value is given in try or catch block.


concept 2:

In which case finally block will not executed

package com.exception;
import java.util.ArrayList;
public class exceptionTest {
   
    public String getName() {
 
    try{
   
        System.exit(0);
     return "kumud";
   
    }
    catch(Exception ex)
    {
    System.out.println("Finally Exception##  try in getName method");
       
    }
    finally
    {
        System.out.println("Finally Exception## finally in getName method");
        return "kumud5";
    }
   
   
    }
   
    public static void main(String [] args)
    {
        ArrayList ar= new ArrayList();
        exceptionTest exp= new exceptionTest();
        try
        {
            System.out.println("Main Try block");
            System.out.println("Exception is"+exp.getName());
           
               
        }
        catch(Exception ex)
        {
            System.out.println("Exception##"+ex);
           
        }
        finally
        {
            System.out.println("Finally Exception##");
        }
       
    }

}


Output:

Main Try block

Expl: if you written System.exit(0) in try block in only that condition finally block will not execute

Tuesday 30 July 2013

Core concept of Volatile keyword in java multithreading | Java concurrency tutorial

Read full Article before leave thr blog.  It will really helpfull for Java Interview on multithreading topic

First, you have to understand a little something about the Java memory model. I've struggled a bit over the years to explain it briefly and well. As of today, the best way I can think of to describe it is if you imagine it this way:


  •     Each thread in Java takes place in a separate memory space (this is clearly untrue, so bear with me on this one).

  •     You need to use special mechanisms to guarantee that communication happens between these threads, as you would on a message passing system.

  •     Memory writes that happen in one thread can "leak through" and be seen by another thread, but this is by no means guaranteed. Without explicit communication, you can't guarantee which writes get seen by other threads, or even the order in which they get seen.

The Java volatile modifier is an example of a special mechanism to guarantee that communication happens between threads. When one thread writes to a volatile variable, and another thread sees that write, the first thread is telling the second about all of the contents of memory up until it performed the write to that volatile variable.

At this point, I usually rely on a visual aid, which we call the "two cones" diagram, but which my officemate insists on calling the "two trapezoids" diagram, because he is picky. ready is a volatile boolean variable initialized to false, and answer is a non-volatile int variable initialized to 0.




The first thread writes to ready, which is going to be the sender side of the communications. The second thread reads from ready and sees the value the first thread wrote to it. It therefore becomes a receiver. Because this communication occurs, all of the memory contents seen by Thread 1, before it wrote to ready, must be visible to Thread 2, after it reads the value true for ready.

This guarantees that Thread 2 will print "42", if it prints anything at all.

If ready were not volatile, what would happen? Well, there wouldn't be anything explicitly communicating the values known by Thread 1 to Thread 2. As I pointed out before, the value written to the (now non-volatile) ready could "leak through" to Thread 2, so Thread 2 might see ready as true. However, the value for answer might not leak through. If the value for ready does leak through, and the value for answer doesn't leak through, then this execution will print out 0.

We call the communications points "happens-before" relationships, in the language of the Java memory model.

(Minor niggle: The read of ready doesn't just ensure that Thread 2 sees the contents of memory of Thread 1 up until it wrote to ready, it also ensures that Thread 2 sees the contents of memory of any other thread that wrote to ready up until that point.)



With this in mind, let's look at the Double-Checked Locking example again. To refresh your memory, it goes like this:


class Foo {
  private volatile Helper helper = null;
  public Helper getHelper() {
    if (helper == null) {
      synchronized(this) {
        if (helper == null) {
          helper = new Helper();
        }
      }
    }
  return helper;
}

The object of the double-checked locking pattern is to avoid synchronization when reading a lazily constructed singleton that is shared between threads. If you have already constructed the object, the helper field will not be null, so you won't have to perform the synchronization.

However, this is only part of the solution. If one thread creates the object, it has to communicate the contents of its memory to another thread. Otherwise, the object will just sit in the first thread's memory. How do we communicate the contents of memory to another thread? Well, we can use volatile variables. That's why helper has to be volatile -- so that other threads see the fully constructed object.

Locking in Java also forms these "happens-before" communication points. An unlock is the sender side, and a lock on the same variable is the receiver side. The reason that doesn't work for (non-volatile) double-checked locking is that only the writing thread ever performs the locking. The whole point of the idiom is that the reader side doesn't do the locking. Without the explicit communication in the form of the volatile variable, the reading thread will never see the update performed by the writer thread.

LinkWithin

Related Posts Plugin for WordPress, Blogger...