Java 8 New Features

1.Lamda Expressions
The point of lambda is to be able to pass some code to a method rather than objects. Until java 8, the way to achieve this in java would be to use callbacks. The issue with callbacks is that it leads to verbose code. Like you would write 5 lines of code when the real job is in 1 of these 5 lines.

we started with lambda expressions as this is probably the most sought after feature in the language after probably Generics/Annotations in Java 5.
Here’s the syntax:
1        (argtype arg...) -> { return some expression.. probably using these arguments }
What it does is that it reduces the code where it is obvious, such as in an anonymous innerclass. 

So, a thread can be changed as:
          Runnable oldRunner = new Runnable(){
              public void run(){
                  System.out.println("I am running");
              }
          };
          Runnable java8Runner = () ->{
              System.out.println("I am running");
          };
Similar to Scala, type inference is also possible in Lambdas. Consider the following available example:
1        Comparator c = (a, b) -> Integer.compare(a.length(), b.length());
Here, the types of a,b (In this case String, from the Comparator interface) are inferred as the compare method is implemented.
The symbol used to separate the block from arguments, -> is quite similar to => already used in Scala and if you are good at it, there is not much reason to switch as you will feel the way lambdas are implemented in java is inadequate(and verbose), but for a good ‘ol java programmer, this is the way to go.

2.Generic Type changes and improvements
Taking clues from Lambdas, generic collections can also infer the data types to be used to an extent. The methods for instance using a generic collection need not specify genric types. Hence, the following method
1  SomeClass.method();
Can be called simply ignoring the type information:
1   SomeClass.method();
The type can be inferred by the method signature, which is helpful in nested calls like
1  myCollection.sort().removeUseless().beautify();

3. Stream Collection Types (java.util.stream)
A stream is a iterator that allows a single run over the collection it is called on. Along with Lambdas, this is another noteworthy feature to watch out for. You can use streams to perform functional operations like filer or map/reduce over collections which can be streamed as individual elements using Stream objects. Streams can run sequentially or parallely as desired. The parallel mode makes use of fork/join framework and can leverage power of multiple cores.
Example:
          List guys = list.getStream.collect(Collectors.toList())
can also be implemented parallely as
          List guys = list.getStream.parallel().collect(Collectors.toList()
Another nice example that reduces the collection to a single item is by calling reduce algorithem.
          int sum = numberList.stream().reduce(0, (x, y) -> x+y);
or,
          int sum = numberList.stream().reduce(0, Integer::sum);

4. Functional Interfaces (java.util.function)

These interfaces contain some default methods which need not be implemented and can run directly from the interface. This helps with existing code – changing interfaces need not make all the classes implementing it implement new methods. This is similar to Traits in Scala and functional interfaces will be compatible with lambdas.

5.Date/Time changes (java.time)

The Date/Time API is moved to java.time package and Joda time format is followed. Another goodie is that most classes are Threadsafe and immutable.

6. Type Annotations

Now annotations can be used to decorate generic types itself.
Eg:
          List<@Nullable String>
which is not desired always, but can prove to be useful in certain circumstances. Apart from decorating Generic types, it can also be used in constructors and casting.
          new @NonEmpty @Readonly List(myNonEmptyStringSet)
          new @Interned MyObject()
           
          myString = (@NonNull String) myObject;
Even the array objects can be annoted:
          @NotNull String[] arr;

The inclusion of RuntimeVisibleTypeAnnotations and RuntimeInvisibleTypeAnnotations attributes which cause the .class file to save the annotation information.

ATG REST MVC Basics

ATG REST MVC Basics

A lot of us might've heard the term ATG REST or REST API but a lot of us don't get a chance to work on it OR don't exactly know what it is OR why do we exactly use it.
We will cover everything right from the basics as we always do.

What is REST?

You might've googled it a lot of times, and a lot of websites simply say REST stands for Representation State Transfer, along with some weird content which none of us understand. Let us understand what is REST and why is it used.

Let's take a basic scenario, wherein an order is submitted on a website, and all the details of the order (items, cost of each item, order total, time of placing order etc.) has to be sent to another system (for auditing purposes). The two systems are entirely different, one that hosts an eCommerce website with all the eCommerce functionality; and another system just takes order details and saves it for auditing purposes for calculation of monthly revenue, monthly profit, calculation of most sold items etc.
The architectures of these two systems are entirely different, and there may be a possibility that two different organizations handle them. The architecture of one system may not be known by another system.
In such a case, the order details have to be sent in a format which can be read by both the systems. For this purposes, XML or JSONs are used.
This is the example of order details in XML or JSON formats:

orderDetails: { "orderId":"ord123456", "orderTotal": 400, "orderSubmitDate": "23-NOV-2018 13:33:44:00"
 "items": [{  "itemId": "itm100002",  "itemName": "Sun Shine",  "listPrice": 300,  "discount": 0 }, {
  "itemId": "itm100003",  "itemName": "Sun Shine",  "listPrice": 200,  "discount": 0 } ]}

These pre-packages services are available in below modules.
1.       DAS.WebServices
2.       DPS.WebServices
3.       DCS.WebServices 
ATG supports two types of REST webservices (webservices APIs).
1.       Legacy REST API
2.       REST MVC API


Here I am going to explain REST MVC.

Steps to create New REST MVC Call
1.Create Actor.
2.Define Actor chain(s) for that actor.
3.Register Actor with ActorChainRestRegistry.
4.Create Bean filter (optional).
Steps to create REST Actor
1.Create Component of atg.service.actor.ActorChainService class.
2.Define actor chains for this component (xml configuration).
3.Point definitionFile property of the component to xml file created in step 2.
Below is the example of Hello World Actor

#/com/test/web/actor/HelloWorldActor.properties
$class=atg.service.actor.ActorChainService
definitionFile=/com/test/web/actor/helloWorldActor.xml

Actor Chain definition file (helloWorldActor.xml)
 

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
                  method="sayHello">
     

  
Registering this actor with ActorChainRestRegistry 
To register this actor you need to add the actor path with chain id to registeredUrls property of /atg/rest/registry/ActorChainRestRegistry component.

One important thing to remember here is ,that you are registering actor chain not actor. In the case there are more then one chains defined for that actor you need to register each one here. In  other words you can say each chain ID should be registered separately.

By default, no actors are registered.

In below code snippet we are registering sayHello chain.  

#/atg/rest/registry/ActorChainRestRegistry.properties 
registeredUrls=\
         /com/test/web/actor/HelloWorldActor/sayHello 

 
 ATG REST MVC Supports below Actor Types.
1.Component Actor 
2.Droplet Actor
3.Form Actor
4.JSP Actor
5. Nested Actor
6.Variable Actor 
Filtering in MVC REST
Filtering is used in REST MVC to control the property in the response object. In other words filter is way to configure which properties will be available in the response object. This is to avoid unnecessary data in the response.

REST MVC support two types of filters.
1.                   Java bean filtering.
2.                   Repository item filtering.
3.                    
Steps to configure filter
1.Layer /atg/dynamo/service/filter/bean/beanFilteringConfiguration.xml 
2.Configure filter in this file
3. Refer this filter in actor chain
4.ATG recommends 3 types of filters
                   Short
                   Summary
                   Detailed


Once filter is defined you can use filter in actor chain using filter-id attribute.

Filter definition example.

    

   



  
     
         
    
  Using filter in actor chain.  

       
 
 



Note : It is best to define a filter for every object, so that you can control its output. Note that if an object has no filters defined, it will output all properties.

Configure Security in REST MVC 

Once REST call is implemented then It is time to secure it. Security is crucial to avoid unauthorized access.  

Follow below steps to secure rest webservice 
·                     Create the RuleSetService.
·                     Create Access Controller.
·                     Add mapping from actor chain to Access Controller in /atg/dynamo/servlet/dafpipeline/AccessControlServlet. 

CustomRuleService (Only logged in user can access).

#/atg/rest/CustomRuleSetService.properties
$class=atg.targeting.RuleSetService
updatesEnabled=true
rulesFileCheckSeconds=0

# Use must have securityStatus 4 or higher (EXPLICIT-SIGNIN, SECURE-SIGNIN, CERTIFICATE)
ruleSet=\n  \n    \n      \n      \n      \n        \n          \n          \n        \n      \n    \n  \n

CustomAccessController

#/atg/userprofiling/CustomAccessController.properties
$class=atg.userprofiling.RuleAccessController
enabled=true
# Rules used to determine whether access should be allowed
ruleSetService=/atg/rest/CustomRuleSetService
# URL to redirect to if access is denied
deniedAccessURL=/rest/model/atg/userprofiling/SecurityStatusActor/authenticationRequired

 AccessControlServlet

#/atg/dynamo/servlet/dafpipeline/AccessControlServlet.properties
accessControllers=\
    /com/test/web/actor/HelloWorldActor/sayHello=\
         /atg/userprofiling/CustomAccessController

      
ATG REST MVC Key Points
·                     Get and Post are supported.
·                     Access restriction  by AccessControllerService.
·                     Also support implicit objects (session, request).
·                     URL syntax http://host:port/rest/model/actor_component/tail.

ATG REST MVC Key Components
·                     /atg/rest/Configuration/ 
·                     /atg/rest/registry/ActorChainRestRegistry/
·                     /atg/dynamo/service/filter/bean/XmlFilterService
·                     /atg/dynamo/service/actor/ActorChainValidationService


Java 8 Lambda Expression

What is a Lambda Expression?
Java Lambda expression are new in JAVA 8.Java lambda expression are java's first step into functional programming.A Java lambda expression is thus a function which can be created without belonging to any class.A lambda expression can be passed around as if it was an object and executed on demand.A lambda expression represents an anonymous function, it comprises of a set of paramater,a lambda operator (->) and function body.

The following are example of Java lambda expression:

1. (x,y) ->x+y;
  - Two numbers x and y returns another number with their summation.
2. (char c) -> == 'y';
  - A character c returns a boolean indicating if it is equal to ‘y’.
3. (int a,int b) -> a * a+b * b
  - Two integers a and b returns another integer with the sum of their squares.
4. () -> 45
  - No parameters returns the integer 45
5. n -> n% 2 !=0;
  - A number n returns a boolean indicating if it is odd.
6.(String s) -> {System.out.println(s);};
  - A string s prints the string to the main output and returns void.
7. -> { System.out.println("Hello Word "); };
  -No parameters prints Hello World! to the main output and returns void.

package com.Java8;

public class Java8Sample {

            public static void main(String args[]) {
                        Java8Sample java8Sample = new Java8Sample();
                        // Type of Declaration add
                        MathOperation add = (int a, int b) -> a + b;
                        // Type of declaration subtraction
                        MathOperation sub = (int a, int b) -> a - b;

                        System.out.println("Addition of the two Number: " + java8Sample.testResult(10, 20, add));
                        System.out.println("subtraction of the two Number: " + java8Sample.testResult(10, 2, sub));

                        //// without parenthesis
                        StringResult result = message -> System.out.println("Hello " + message);
                        result.sayMessage("Working on Lambda Expression");

            }

            interface MathOperation {
                        int operation(int a, int b);
            }

            interface StringResult {
                        void sayMessage(String message);
            }

            public int testResult(int a, int b, MathOperation mathOperation) {
                        return mathOperation.operation(a, b);
            }

}

In Above example we have used various type of lambda expression with interface MethodOperation and then define the implementation of sayMessage

StringResult

ATG Interview Question Part-2

Question: Explain the steps for writing Custom Droplet? 
Answer:
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.SayHelloDroplet
$scope=global
$description=print the value under droplet

Step 3: Declare the droplet in the JSP



Input Parameter JSP Side:
- Using value tag
- Using param tag Note: use here page parameter name.
- Using bean tag
Input Paramater Java Side:
- String current=pRequest.getParamater(PARAM_CURRENT_PAGE);

Question: Difference between CartModifierformHandler and shoppingCartfrom handler?
Answer:
CartModifierFromHandler: Used to modify the shopping cart by adding item, deleting items and modifying the item quantities of item in cart and preparing for checkout process. Typically when using this you would have to handle checkout flow yourself by ExpressChecoutFromHandler in case of express checkout and in case of full checkout by using ShippingGroup and PaymentGroup from handlers and finally commitFromHanlder to confirm and commit the order.
ShoppingCartFormHandler - Used for handling cart management (add/remove/adjust item quantity) and checkout process (shipping, billing, committing order). This provides an easier and simpler interface than using CartModifierFormHandler along other form handlers because in ShoppingCartFormHandler various functions for cart management to checkout are exposed via different handleXXX methods each having a preXXX and postXXX to extend the functionality if required. There is one Full ShoppingCartFormHandler also which extends ShoppingCartFormHandler and adds the functionality like handling multiple payment groups, split shipping, express checkout.
To summarize, ShoppingCartFormHandler provides simpler cart management and checkout implementation all in itself. Whereas CartModifierFormHandler doesn't provide you the checkout flow and therefore CartModifierFormHandler based implementation would not be that simple and require other form handlers. But CartModifierFormHandler would provide some benefits like better handling and security for concurrent updates of orders, a more flexible payment/shipping group management for use with multiple shipping or payment groups along with other things.

Question: In ATG Order State?
Answer:
INCOMPLIT_ORDER Order is undefined and has not been checkout by customer yet. 
SUBMIT_ORDER The order has been submitted to the warehouse staff to begin fulfilment.
REMOVE The order has been cancelled. It will not be shipped to the customer.
APPROVED This order has been approved by either an approver of the organization or an agent. 
PENDING_APPROVAL The order requires the approval of an approver of the organization or the agent before it can complete the checkout process.
PRENDING_REMOVE The order is in the process of being cancelled.
INPROCESS When fulfilment server will start it will capture all SUBMIT_ORDER and change the state INPROCESS.
PROCESSED When all the order has shipped, Change the state PROCESSED.

Question; What is MutableRepository?
Answer: 
Some repository services implement MutableRepository, a subclass of Repository. The SQL repository implements this interface. The MutableRepository interface defines functions for four operations: creating, adding, updating, and removing repository items:

1. createItem();
2. addItem();
3. removeItem();
4. updateItem();

Question: Repository API?
Answer: 
- set of interfaces that are used for generic data access.
- use to manipulate repository items within Java code, including retrieving, creating, updating, deleting, and querying for items.
- provides generic data access calls that mask the underlying data store from the developer.(any database can be use as it convert the data in repository objects)

Interface Method
Repository getItem();getView();
RepositoryItem getPropertyvalue( );
RepositoryView executeQuery( );
MutableRepository addItem,CreateItem,getItemForUpdate();updateItem(); removeItem(); 
MutableRepositoryItem setPropertyValue();


  • Repository: Is used to gain access to a given RepositoryItem when the ID is known; is also used to obtain a RepositoryView
  • RepositoryItem: Returns the property values for an individual item from the repository.
  • RepositoryView: Used to execute queries to return an array of RepositoryItem objects
  • MutableRepository: Provides methods used to insert, update, and delete RepositoryItem objects
  • MutableRepositoryItem: Is used to change or set the values of a RepositoryItem

The API provides generic data access calls so that the ATG developer can use the same method calls for LDAP and SQL data stores.
MutableRepository

  • Repository and RepositoryItem provide a read-only view of repository elements.
  • MutableRepository is an extension that enables repository elements to be Created, Updated, Deleted.
  • MutableRepository also provides appropriate cache synchronization.
  • MutableRepository objects are copies of the real objects that can be altered by the application. Because changes are not written back on each change, performance is not affected. On a call to update the repository, a new transaction is started in which its contents are written back to the repository.

Question: Scopes in ATG component?
Answer:
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.)
One component copy shares every user.
Example: $class=com.mypackage.Person
                 $scope=global
                  Name=Surya
                  Age=20 
NOTE: If we do not specify $ scope variable, and it is not specifies in any of the upper-layer of the component. Nucleuses 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.myPackage.Person
                 $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.
Window: Share for every browser base.
Note: By Default Droplet has Global Scope and Formhandler has request or session. 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.
Example: A global scope component CANNOT refer to session or request component.


Question: what are ATG Components follow rules ?
Answer:
  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.


Question: How to maintain profile for guest or anonymous user?
Answer: Guest are anonymous users who have not registered have not login.
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)

Question: What is the layering in ATG?
Answer: This is one of the most important topics without which customization in ATG is simply not possible.
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
rock
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/SunShine global
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