AngularJS

 

 

angularjs

Introduction to  AngularJS

AngularJS version 1.0 was released in 2012.

Misko Hevery, a Google employee, started to work with AngularJS in 2009.

AngularJS is a JavaScript framework designed for creating single page web application.

AngularJS is entirely based on HTML and JavaScript, so there is no need to learn any other syntax or language.

What is AngularJS?

AngularJS is structural framework for dynamic web apps. It lets you use HTML as your template language and lets you HTML’s syntax to your application’s components clearly and succinctly. AngularJS’s data binding and dependency injection eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it an ideal partner with any server technology.

Features of AngularJS

1.You don’t need to write special code to bind data to the HTML controls. This can be done by just adding few snippets of code.

2.When carrying out DOM(document object model) manipulation a lot of JavaScript was required to be written to design any application. But with AngularJS, you will be amazed with the lesser amount of code need to write for DOM manipulation.

3.AngularJS provides developers options to write client side application(using JavaScript) in clean MVC(model view controller).

4.AngularJS is open source, completely free, and used by thousands of developers around the world

 

Advantages of AngularJS

1.MVC(Model view controller)

Most frameworks require programmers to splitting the app into multiple MVC components. After that, the programmer has to write a code to put them together again. AngularJS, however, strings it together automatically. That saves you time, and reduces the app’s time to market.

2.Two way Binding

It is possible to do two way binding with AngularJS, meaning you can make any data related  changes and would immediately be propagated to the corresponding views and when any change is made in the view, that would happen in the underlying models as well. As soon as the app data changes, there will be corresponding changes in the UI as well.

3.Dependency Injection

The built in dependency injection is something most developers love about AngularJS. This feature helps them to develop, test and understood application in a better way.

Dependency Injection is a software design pattern in which components are given their dependencies  instead of hard coding them within the component. This relieves a component from locating the dependency and makes dependencies configurable. This helps in making component reusable, maintainable and testable.

4.Routing

AngularJS can take care of routing which means moving from one view to another. This is the key fundamental of single page application, wherein you can move to different functionalities in your web application based on user interaction but still stay on the same page.

Disadvantages of AngularJS

Though AngularJS comes with lots plus points but same time we should consider the following points:-

1.Confusing

There are multiple ways to do the same thing with AngularJS sometimes, it can be hard for novices to say which way is better for a task. Hence it is imperative for programmers to develop an understanding of the various components and how they help.

2.Not secure

Being JavaScript only framework, application written in AngularJS are not safe. Server side an authentication is must to keep an application secure.

3.Not degradable

If your application user disables JavaScript then user will just see the basic page and nothing.

First AngularJS program

Before we start with creating our first AngularJS program, let us see what are the important part of a AngularJS application

1.ng-app

This directive defines AngularJS application.

2.ng-model

This directive bind the value of HTML controls to application data.

3.ng-bind

This directive bind the application data to HTML view.

4.Expression

AngularJS expression can be written inside double braces.{{expression}}

NOTE:

AngularJS lets you extend HTML with new attribute called directive.

AngularJS directive are prefix with ng-.

Steps to create AngularJS program

1.Load framework

framework

 2.Declare HTML body as an AngularJS application using ng-app

ngapp

3.Define model name using ng-model directive

ngmodel

4.Accesing member varible

expression

Now our first AngularJS program

first

output

output1

output2

 

 

Java 8 | Lambda Expression

The lambda expression feature reshaped the Java language. Lambda expression comes with the functional programming construct to the object oriented programming. Lambda is nothing but an anonymous method.

Features:

  • Lambda expression reduces the number of lines of code.
  • Lambda expression provides implementation to the functional interface.
  • New capabilities are added to the API library.
  • Parallel processing of multi-core environments, especially handling of the for-each style of operations.

 Example:  


@FunctionalInterface

package in.co.bitbyte.java8;

public interface Developer {

public void writeReadableCode();

}

 Implementation of Functional Interface(without lambda expression):


package in.co.bitbyte.java8;

public class Test {

public static void main(String[] args) {

Developer d = new Developer() {

@Override

public void writeReadableCode() {

System.out.println(“At bitbyte, developers  think simple”);

}

};

d.writeReadableCode();

}

}

Implementation of Functional Interface(with lambda expression):


package in.co.bitbyte.java8;

public class Test {

public static void main(String[] args) {

Developer d = () -> {

System.out.println("At bitbyte developers think simple");

};

d.writeReadableCode();

}

}

 This feature changing the way that code is written. Two primary reasons to change the style of coding:

Added new syntax elements that expressive power of the language.

In addition to this added new capabilities to the API library, a big step into the collection API for iteration.

Syntax:

Lambda operator:         (parameters)  -> {actions}

The left side of lambda operator indicates “parameters” right side of the lambda operator lambda body specifies the “actions” need to be performed by the lambda expression.

Lambda expressions are not executed on its own. It works with the implementation of the functional interface.

Before lambda expression, we used the anonymous inner class to implement a functional interface (Single Abstract Method). So many built-in interfaces in Java 7 Runnable, Comparable and so on… Java 8 called this interfaces as functional interface some of the added functional interfaces are BiConsumer, Bi

Example:


package in.co.bitbyte.java8;

public class TestingBuiltInFunctionalInterface {

public static void main(String[] args) {

Runnable r = new Runnable() {

@Override

public void run() {

System.out.println("I am from run method of Runnable interface using anonymous inner class");

}

};

r.run();

}

}

We can implement the above same Runnable interface by using the lambda expression in a very simple way.

Example:


package in.co.bitbyte.java8;

public class TestingBuiltInFunctionalInterface {

public static void main(String[] args) {

Runnable r = () -> {

System.out.println("I am run method from Runnable interface using lambda expression");

};

r.run();

}

}

In the above example, we didn’t mention the method name of the interface because in the functional interface having exactly only one abstract method. We implemented the functional interface using the lambda expression.

If we want to do iteration in the collection, we will do iteration one of the following way.


package in.co.bitbyte.java8;

import java.util.ArrayList;

import java.util.List;

public class Ecommerce {

public static void main(String[] args) {

List list = new ArrayList();

list.add("Hybris");

list.add("ATG");

list.add("DemandWare");

list.add("Intershop");

for(String ecommerceTech : list)

{

System.out.println(ecommerceTech);

}

}

}

But the lambda expression defines a new style for the for-each operation. The main advantage here is we can achieve parallel processing. Without lambda, expression iteration is like processing each element.

Example:


package in.co.bitbyte.java8;

import java.util.ArrayList;

import java.util.List;

public class Ecommerce {

public static void main(String[] args) {

List list = new ArrayList();

list.add("Hybris");

list.add("ATG");

list.add("DemandWare");

list.add("Intershop");

list.forEach(ecommerceTech ->{System.out.println(ecommerceTech);});

}

}

Java 8 | Functional Interface

An interface which is having only one abstract method then it is called as a functional interface. (only one abstract method, one or more default methods or static methods)

Example:

package in.co.bitbyte.java8;

@FunctionalInterface

public interface Mobile {

public void makeCall();

}

We can use the annotation @FunctionalInterface to declare the interface as a functional interface. If it is not valid functional interface, Compiler will throw an error.

This annotation is optional. The compiler will consider interface as a functional interface if it contains exactly one abstract method.

Uses:

  • The functional interfaces are used extensively in lambda expressions.
  • The functional interface acts as a function. We can pass the interface as a parameter this is the functional programming approach.
  • So many interfaces in Java are functional interfaces (built in functional interfaces) like Comparator, Runnable and so on.
  • The main advantage of using functional interface is backward compatibility.

Note: we can declare abstract methods that are overriding the public methods of Object class. These methods did not consider as abstract methods in a functional interface. [Reason behind this thing is any implementation of the interface will have an implementation from Object class]

Example:

package in.co.bitbyte.java8;
@FunctionalInterface
public interface Mobile {  

public void makeCall(); 

public String toString(); 

boolean equals(Object obj);

static useInternetServices()
{
  System.out.println("use whats app");
}
default void mailServices()
{
System.out.println("Use e-mail service");
}

Java 8 | Default methods in interface

Every developer in office is instructed to write no-nonsense code. That’s a protocol.

So when there is no exception, why should every developer create their own creative ways to code. Every one should follow a consistent methodology. Let that manager of your’s define the PMDs for you. I know you will gonna hate it. But then…

It makes sense to have some non abstract methods in an interface. This may be conveniently called default implementation.

Java 8 let you do this. Now you can define a default implementation, which is available to all implementing classes.

Below is a sample.

Interface

package com.bitbyte;

public interface Developer {
	
	public void writeReadableCode();
	
	default void thinkSimple(){
		System.out.println("At bitbyte, Developers think Simple");
	}

}

Implementing class

package com.bitbyte;

public class JavaDeveloper implements Developer {

	@Override
	public void writeReadableCode() {
		System.out.println("Please write Simple and readable code");
	}
}

Client Class

package com.bitbyte;

public class Client {

	public static void main(String args[]) {

		JavaDeveloper coolDeveloper = new JavaDeveloper();
		
		// abstract method call
		coolDeveloper.writeReadableCode();
		// Non abstract method call
		coolDeveloper.thinkSimple();
	}
}

Since you always have a jackAss in team, who still want his own implementation. He can do so.


package com.bitbyte;

public class CoolDeveloper implements Developer {

	@Override
	public void writeReadableCode() {
		System.out.println("Please write Simple and readable code");
	}
	
	@Override
	public void thinkSimple() {
		
		System.out.println("I am cool myself. I know what i am doing!!!");
		
	}
}

How to submit a form to Hybris from external application

Gate crash is embarrassing, back door entry is risky. Great is to be welcomed by a friend inside the party, when you are not invited.

Recently, i came to a situation, where i wanted to submit a form to hybris from a application. I thought it would be easy, and all i need is to do a post to a URL.

Booom. It came out with a flat Bad or missing csrf value error.

Once i thought, perhaps i am trying to breach the hybris security. Since there is a contract between client (browser) and the server (hybris) to exchange information. To keep this information just between them, a shared private token is used. This token, known as csrf token, is bound to a session.

@sumitg88 talked about it one of his blog.

Bypassing a request from security layer is one thing. What i wanted was to go through the security layer, and still be able to submit a form, from outside the spring context of Hybris storefront.

I created an API in storefront, which can pass a csrf-token for the current session. The current session can be opened by application, by hitting the home page, may be in an iframe, or through a java program in backend.

Hybris forcefully adds a csrf token inside a hidden field, in every spring mvc form. You can see this happening by going to html source of a page with form. This token is actually validated against the session token to allow a request to pass to the services.

hiddenFields.put(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(request.getSession()));

In Html forms you can see:

      <input type="hidden" name="CSRFToken" value="0b4eefff-1a05-4bdb-843a-fa9598633dab">

Our API could give the same csrf token, which we can pass through our form in external application. This way, Hybris will take this request as a valid one, and we can submit the form.

The API could look like below:

      public static String getTokenForSession(final HttpSession session)
	{

		// cannot allow more than one token on a session - in the case of two requests trying to
		// init the token concurrently
		Enumeration<String> enumeration=session.getAttributeNames();
		String csrfTokenAttr=null;
		String token=null;
		while(enumeration.hasMoreElements())
		{
			String attrName=enumeration.nextElement();

			if (attrName.contains("CSRFTokenManager.tokenval"))
			{ 
				csrfTokenAttr=attrName;
			}
		}
		synchronized (session)
		{
			token = (String) session.getAttribute(csrfTokenAttr);
			if (null == token)
			{
				token = UUID.randomUUID().toString();
				session.setAttribute(csrfTokenAttr, token);
			}
		}
		return token;
	}

Once you have a valid token, from one of the session, you can submit any form smoothly.

Enjoy!!!!

Hot Deployment – Hybris

Introduction

In this tutorial I will be covering the configuration of JRebel with Hybris. With JRebel configured you will be able to modify java source classes and compile them on the fly.

“No need to build and start the server again and again”

The configuration is very simple, just 3 steps and you are good to go!

Step 1

  • Download JRebel: Archive can be downloaded from the below link http://zeroturnaround.com/software/jrebel/download/prev-releases/
  • Extract the zip file at a location of your preference, for eg: C:/jrebel
    unzip
  • Active JRebel:
    – Go inside bin folder of JRebel.
    – Start the activation utility by running “activate-gui.cmd” file.
    – It will open a Jrebel activation window. The window will contain 2 tabs:
    Try JRebel    for free and I already have a license.Choose Try JRebel for FREE and fill the basic information.

jrebelfreeform
OR
Buy a license and fill the information in the I already have a license section.

Step 2

  • Add the below given property in local.properties file
    tomcat.javaoptions=-agentpath:C:/jrebel/lib/jrebel64.dll
    ** change the version of the jrebel[XX].dll according to the machine specifications.

 Creation of rebel.xml file:
– You will be required to add the rebel.xml file in the resource folder of each extension.

rebel.png

– Create a new rebel.xml class and copy/paste the below given content into the file:

<?xml version=”1.0″ encoding=”UTF-8″?>
<application xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns=”http://www.zeroturnaround.com&#8221; xsi:schemaLocation=”http://www.zeroturnaround.com http://update.zeroturnaround.com/jrebel/rebel-2_1.xsd”&gt;
<classpath>
<!– Make sure to replace Absolute_Path with your concrete values –>
    <dir name=”{Absolute_Path}/classes”/>
</classpath>
</application>

**   The absolute path should be the complete path to the classes folder.
Example: C:/hybris/bin/custom/demo/demofacades/classes

***The classes folder is the compiled source folder of Hybris and not IDE’s(eclipse).

Step 3

  • Change the IDE(eclipse) compile output path in “.classpath” file of the extension.classpath.png
    TO
    classpath1.png
    Path structure:
    path.png
    All the configurations are completed.You just need to recompile the code from IDE(eclipse) after making the changes in the Java source file.For Eclipse you need to do the below mentioned step:

    • Just go to Project -> Clean
    • Select “Clean projects selected below” option and select the extensions which contains the modified java source classes.
    • Select “Start build immediately”.
    • Select “Build only the selected projects”.
    • Press OK and you are done!

Load balancing configurations for SAP Hybris

As mentioned in one of my previous post if not setup correctly clustered environment can be a nightmare. Below are some of the configurations worth noting beforehand:

Server Affinity: a lost session

An HTTP (s) session should always be served by only one SAP Hybris application server otherwise session will be lost and user would need to re-login, even worse anonymous user will lose his cart and all other settings. To avoid this embarrassing experience, enable Sticky Session at application load balancing layer which will stick one session to one SAP hybris server.

Redirect rules: 

Very often redirect rules are defined at load balancing layer to redirect complete URL (base + context )-e.g. http://doodle.com/fun to base URL  e.g. http://doodle.com.

Here one exception should be medias because their urls are appended with /medias at end of base URL and redirecting these URLs to base URL wont load medias:

eg. a call to medias URL –  e.g. http://doodle.com/medias/abc/456789.jpg will be replace with http://doodle.com which will fail loading of medias into SAP Hybris applications.