Java Exception Handling

Answer: In Java exception is an event that occurs during the execution of the program that disrupts the normal flow of instruction. In Java API throwable is a parent class of all Exception and Error classes. There are two types of exceptions  CheckedExceptions ( known as Compile-time exceptions) and  UncheckedExceptions ( known as runtimeExceptions) both type of exceptions extends Exception class.

CheckException: Checked exceptions must be explicitly caught or propagated as described in Basic try-catch-finally Exception Handling.
 Example:
import java.io.File;
import java.io.FileReader;
 public class FileDemo {
    public static void main(String args[]){                     
      File file=new File("E://file.txt");
      FileReader fr = new FileReader(file);
   }
 }

If you try to compile the above program you will get exceptions.”FileNotFoundException”, and which forces the programmer to catch them explicitly.

UncheckedException : Unchecked exception is an exception that occurs at time of execution, these include programming bugs such logic in error or in-proper used API
Example:If you have declared an array 5 and trying to call 6th element of the array the ArrayIndexOutOfBoundsExceptionexception .
public class ArrayOutBoundDemo{
     public static void main(String args[]){
      int num[]={1,2,3,4};
      System.out.println(num[5]);
   }
}
Errorindicate serious problems and abnormal conditions that most applications should not try to handle. Error defines problems that are not expected to be caught under normal circumstances by our program. For example memory error, hardware error, JVM error etc.

see in below diagram The exception hierarchy in Java:
We can handle the java exception in three way:

Throw: Sometime we might want to generate exception explicitly in our code, for example in a user authentication program we should throw exception to client if the password is null. throw keyword is used to throw exception to the runtime to handle it.

Throws: When we are throwing any exception in a method and not handling it, then we need to use throws keyword, We can provide multiple exceptions in the throws clause and it can be used with main() method.

Try-catch: Java try block is used to enclose the code that might throw an exception. It must be used within the method.
Syntax:
Try{
}catch(Exception e){
}finaly{
}
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in try block.In finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurred or not

Java Collection With Short Notes

A collection in java is framework that provides architecture to store and manipulate the group of Object.All the operation that you perform on a data such as searching, sorting, insertion .manipulation, deletion etc.Java collation is simply means a single unit of the object, java collection provide may interface(Set,List,Queue,Deque,SortedSet,SortedMap) and class(ArrayList,vector,LiskedList, PriorityQueue, HashSet, HashMap, LinkedHashSet, TreeSet,TreeMap).



ATG Form handler Basic.

Answer:
1. If you are creating the custom formhandler, make sure it extends GenericeFomhandler.

2. In your custom formhandler must be define properties successURL, errorUrl and every property submitted with this formhandler  must be respectively getters/setters method.

3. Each Submit button should have a preXXX(),handleXXX() and validation () method. In preXXX() avoid the most of cases but if you needed to specifically clear formException vector, in the session scope component you can added you logic here.

4. Formhandlers scope must be request or session , request scope is always recommended. Sometimes we can define session scope.  

5. Each and every jsp page should be associated with one formhandler; it may be custom OOTB formhandler.

6. Formhandler should only refer to same scope or higher scope component i.e. session scope formhandler should never refer to any request scope component;

7. All page data should be passed through formhandler, avoid passing any attribute through request and session.

8. Set the priority of the field to "-10" for required input fields other than submit button, so that it gets invoked after all of the setters have been called.

9. Set  the priority of the field to “-10” for required input fields other then submit button ,so that it gets invoked after all of the setters have been called.

10.Return true to be redirect to success page, the follow will be something like this handleXXX(),preXXX()return super.checkfromRedirect(successURL,errorURL,request,responce);

ATG Custom Price Engine

In the following example, you have decided you want to create a new pricing engine that prices handling costs separately from shipping. You create a SamplePricingEngine that acts independently of the ShippingPricingEngine.



1.
Create an interface called SamplePricingEngine that extends PricingEngine.

2.
Create an implementation called SamplePricingEngineImpl that extends PricingEngineService.

3.
Create a SamplePricingInfo that extends the AmountInfo price holding class.

4.
Create a calculator called SamplePricingCalculator and implementations of it that calculate and discount handling as your business requires.

5.
Modify the Promotions repository definition file (by default, pricingModels.xml). Add an item-descriptor for the Handling discount type and sub-descriptors for the various 
implementations of the SamplePricingCalculator that you created.

6.
Create properties files for the SamplePricingEngine and each of the calculators.

7.
Depending on your needs, configure the new engine with some preCalculators that calculate the base cost of handling.

Pricing Engine Class Diagram :




SONAR Setup on Local Environment

Below are the steps for configuring SONAR on your local setup-

1. Download SONAR from http://www.sonarsource.org/downloads/ (latest version 3.4.1).
2. Download sonar runner from http://repository.codehaus.org/org/codehaus/sonar-plugins/sonar-runner/2.0/sonar-runner-2.0.zip and paste it in Sonar home directory as mentioned in previous step.
3. Download “apache-maven-3.0.5” from apache site.
4. Define SONAR_RUNNER_HOME (e.g.-  C:\sonar-3.4.1\sonar-runner-2.0) in system environment variable.
5. Add entry-  %SONAR_RUNNER_HOME%\bin;C:\apache-maven-3.0.5\bin in PATH system environment variable.
6. Go to C:\sonar-3.4.1\bin\windows-x86-32 directory and run startsonar.bat.
7. Hit http://localhost:9000 to check server has been successfully started or not.
8. Create “sonar-project.properties” and “pom.xml” file in your project root folder (Attached with email for your reference).
9. Navigate to your project using command prompt and run sonar-runner.bat. This will start analysing your project using Sonar rules.
10.Refresh url http://localhost:9000 and you will see your project configured on the sonar dashboard. Click on the project and analyse quality report for the project.
11.   For generating pdf report for project, execute below command-
mvn org.codehaus.sonar-plugins.pdf-report:maven-pdfreport-plugin:1.3:generate
12.   A pdf report will be generated in ${project-home}/target directory.

ATG Application Between Session

You can run multiple ATG applications in the form of WAR files within a single EAR. In this case, you should share session-scoped Nucleus components so that your application will always have access to the same instance of session scoped components.
When multiple web applications exist in the ATG EAR file, one of them must be designated as the parent application. Being the parent means that that application’s session ID is used as the basis for creating the ATG session scope root.your web applications should define the atg.session.parentContextName and atg.dafear.bootstrapContextName parameters in their web.xml to point to the parent web-application as shown:

   atg.session.parentContextName
   /dyn

   atg.dafear.bootstrapContextName
   /dyn
   The name of the DAF bootstrap WAR context.


The context path the context-param points to must be for a WAR file with the SessionNameContextServlet defined in its web.xml:

   SessionNameContextServlet

   atg.nucleus.servlet.SessionNameContextServlet
  
Note : that there can be only one parent web application specified per EAR file. Therefore, if you change the parent application, be sure to set the context-param to the same values in all web.xml files within your EAR file:

   atg.session.parentContextName
   /portal

Note: This information applies only to session-scoped Nucleus components,

You must be set the same in ALL web.xml in the same ear file and the URL it points to must be a .war file with the SessionNameContextServlet defined in the web.xml.
In general if you leave “atg_bootstrap.war” in your big ear and do not change its context root from /dyn there is nothing to configure except making sure the nucleus servlet is defined in all web.xml files.

ATG Scenarios and Targeters different



Sr.no
Scenarios
Targeters
1.
Scenarios are triggered by events.
Targeters are not event based.
2.
If we want to personalize content as a result of a site visitor's doing something specific (for example, logging in), use a scenario.
The business rules we can set up through Targeters are more flexible in some cases than scenarios. For this reason, if we need to set up highly complex rules to match content  to  visitors, use Targeters.
3.
Scenarios use a feature called slots to display dynamic content. Slots provide some powerful advantages over Targeters (for example, we can set up empty slots that generate their own requests for content).
Targeters don’t use slots.
4.
If we want to set up a long-term approach to content and visitor management, use scenarios.




ATG Maintain Profile for Guest or Anonymous User

Guest are anonymous users, who have not registered.

1 .Set  “persistenceAnonymousProfile” property of the  /atg/dynamo/servlet/dafpipeline/ProfileServletRequest to true with new profile will create in database for each anonymous.


2. Set “persistAfterLogout”  property of the /atg/dynamo/servlet/dafpipeline/ProfileServletRequest to true.


3.Set the “profileRequestTools property of the /atg/dynamo/servlet/dafpipeline/ProfileRequestServlet component to /atg/userprofiling/ProfileRequestTools.


4. Enable auto-login by setting the “autoLogin property to true in the userprofile.xml file.

    Example: Store anonymous users:
    # /atg/dynamo/servlet/dafpipeline/ProfileServletRequest
       persistAfterLogout=true
        persisteAnonymousProfiles=true
   
Note: If you set up the auto-login.

    #CookiesManage
     sendProfileCookies=true
    #ProfileRequestServlet
      varifyBasicAuthantication=false  (check password verification,Password are store in(SHA-256) rehashes)

ATG Implicitly Modules

1. atg_bootstrap.war: Nucleus is started by the module this also runs the servlet pipeline for DAF and DAS (for JHTML) modules.

DAF servlet pipeline will be used for serving JSP Pages and J2EE Servlet.(Pagefilter define in web.xml)
DAS Pipeline will be used for serving JHTML pages and Dynamo Servlet (proxyservlet define in web.xml)

2. atg_bootstrap_ejb.jar: You know how the ATG classes are loaded by the application which you can see inside the atg lib folder generally; there will be a EJB with a single session inside this module. The class loader of this session EJB will take care of loading the classes for ATG application.


3. atg_admin.war: ATG Component Browser or Dynamo Administration UI will be started using this module.



Droplet ,ATG Servlet Bean And Custom Droplet

What is custom droplet:
A custom droplet s nothing but a new customized component i.e. a java class implementing business logic and a property file which registers it to nucleus.
It’s generally made by extending existing/given ATG OOTB component.
As part of custom droplet, new java (class) file and a property file need to be created.

Why it is required:
When existing functionality of ATG given OOTB component is not sufficient or
-   Customization is required based on requirement or
-   More specific implementation of given functionality need to be provided (like creating custom droplet for tax calculation which will override ATG given tax calculations).

A droplet is basically ATG's custom servlet which has some atg-specific customization. Just like we use HttpServlet in J2EE, we have have DynamoServlet class which implements javax.servlet.Servlet interface in ATG.
 Step 1: Create a java class extending atg.servlet.DynamoServlet and overriding the service (DynamoHttpServletRequest pRequest, DynamoHttpServletResponce pResponse) throw ServletException, IOException method.


Step 2:Create ATG Component for the class, The scope of the component should be global.
          $class = com.test.droplet.ParamaterDroplet
          $scope=global
          $description=print the value under droplet
Step 3:Declare the droplet in the JSP


Step 4:I Three way we can pass input Parameter into JSP Side:
          - Using value tag
          - Using param tag
          - Using bean tag
           Input Paramater Java Side:
           -   String current=pRequest.getParamater(PARAM_CURRENT_PAGE);




ATG Component Scopes And Rules

Scope is a nucleus variable.The nucleus properties are processed by $ sign in the configuration files.

Global: If a component has a global scope, its’ instance is shared by users across all the session that exist for the application. Any user which accesses the application can change the value of the global scope component. (This means that the state of the component is the same for all users of the application.).Global Scope componets are generally used for Droplet.
One component copy shares every user.
Example: $class=com.jungle.Animal
                $scope=global
                 Name=Lion
                 Age=15

NOTE: If we do not specify $ scope variable, and it is not specifies in any of the upper-layer of the component. Nucleus consider is scope as “global” by default.

Session: For a component scoped as session, a separate instance is providing for each session (or user). ATG uses cookies and re-written URL’s to identify requests originating a single browser session. If session is inactive (request are not made) for a specific period time. Session scoped components are remove from that session and any runtime value of these component are last.
One component copy shares only one user.
Example :$class = com.jungle.Animal
                 $scope = session

Request: For each request for component, a new instance will be generated for that component. After the request completes, the instance is lost and all it’s runtime value with it. Even if two requests are generated for a component in same session, nucleus will create two separate instance for the requested component. Request scope components are generally used for from handling. This is because, we don’t want our from to manipulated by multiple request in same session or globally by user across the world. the same session come in at the same time.
One Component copy share for every request..
Example: $class=com.jungle.Animal
                $Scope=request

Note:  A very important point which needed to here is that, a component can always refer to component which a scope equal to greater then it’s own scope.
 See in below component scope diagram:




Rules:
1.You can inject request/session/global scoped component into a request scope component Ex: ProfileFromHandler can have Tools/manager.
2.You can inject session/global scoped component into a session scope component EX: Session scope Manager should have only session scope component or global scoped Tools/Manager injected in it.
3.You can inject only global scope component into global scope component Ex: Droplet which is global Scope can only hold other global scoped component injected into it.
4.Always pass the request or session scope objects to global scope component method instead of resolve component.

ATG Configuration Layering


This is one of the most important topics without which customization in ATG is simply not possible. Configuration layering in ATG refers to overriding component property not component when we place the component at the same config path.The property in the component picked up at the last in configure path, overrides the properties define in the previous property file. ATG Support left to write relationship for this: 

Like As DAS DAF DPS DSS DCS
-          set CLASSPATH=”c:\test ; c:\testInfo”
A c:\music\artists\d\SunShine.properties file containing
$class= atg.music.Artist
$scope=global
name=Sun Shine
genre=folk/pop

We have defined a single global nucleus component of class atg.music.Artist which can be referenced by the name /artists/d/Sun Shine from within Dynamo. Then name property of the instance will be set to Sun Shine and the genre property will be set to folk/pop. In this case even though our Artist bean has website and email properties we have not set these properties so they remain uninitialized.

Nucleus nameScopeJava instance (the bean)/artists/d/SunShine global



atg.music.Artist
name
Sun Shine
genre
folk/pop
website

email


Multiple CONFIGPATH directories.

 set CONFIGPATH="c:\music;c:\moreinfo"
  A c:\music\artists\d\SunShine.properties file containing
  $class= atg.music.Artist
  $scope=global
  name=Sun Shine
  genre=folk/pop

A second c:\moreinfo\artists\d\SunShine.properties file containing
  website=http://www.dmb.com
  email=dave@dmb.com
  genre=rock
  Nucleus nameScopeJava instance (the bean)/artists/d/DaveMathewsglobal

atg.music.Artist
name
Sun Shine
genre
rock
website
http://www.dmb.com
email
dave@dmb.com

Configuration Layering for Arrays, Given the following
  set CONFIGPATH="c:\music;c:\moreinfo"
  A c:\music\albums\c\Crash.properties file containing
  $class= atg.music.Album
  $scope=global
  title=Crash
  tracks=#34, Lay Down Lover
sessionPlayers= Raj kumar, Suraj Kumar

A second c:\moreinfo\albums\c\Crash.properties file containing
tracks=Two Step, Crash
sessionPlayers+=krishna,Jon kupper

Nucleus name
Scope
Java instance (the bean)
/albums/c/Crash
global
atg.music.Album
title
Crash
tracks
Two Step
Crash
sessionPlayers
Raj kumar
Suraj Kumar
Krishna  
Jon kupper