Friday 29 April 2016

Activiti BPMN elements

The simple diagrams that BPMN consists of to represent the business workflow prove to be helpful for both business users and developers. The four basic categories of BPMN elements are as follows:
  1. ‹‹ Flow objects
  2. ‹‹ Connecting objects
  3. ‹‹ Swim lanes
  4. ‹‹ Artifacts

Flow objects
Flow objects consist of various shapes that represent the core elements of business process representation, which characterize the behavior of a business process. To represent the flow of the object, three elements are used: events, activities, and gateways.
  • Events :Events can be considered as the actions that occur during the business process. They are represented using a circle in a business process diagram. An intermediate event is represented using concentric circles. There are three types of events: start, intermediate, and end.
    • The start event : The start event indicates the start of your business process. It is represented using a single circle. In your business process, you should have only one start event. The start event can be represented as follows:
    • Intermediate event : Intermediate event refers to the events taking place between the start and end of the business process. These events do not affect the business process as they do not start or terminate the business process. You can have n number of intermediate events within your business process. The intermediate events are represented using concentric circles, as follows:
    • The end event : The end event is represented using a thick-bordered circle as follows, and indicates the end of your business process; there should be at least one end event within your business process:
  • Activities : Activities represent the tasks or work that is being performed within a business process. The shape that represents the activities in a BPMN is a round-cornered rectangle. There are various types of activities, such as task, Sub-Process, and the call activity. 
    • Task : A task activity is used in a business process when there is an activity to be implemented within a process. It is represented by a round-cornered rectangle. Tasks can be used when there are some actions to be performed in your business process. Various types of tasks  are provided by BPMN, such as the script task, user task, service task, and mail task. A task is represented as follows: The following are the different types of tasks:
      • Script task: This task is used for the automation of a task. We can have our logic     implemented here.
      • User task: This task can be used in a business process when human interaction is     required for the business, for example, when details are to be filled or verified by   a human. 
      • Mail task: This is a type of service task that has services implemented to send e-mails or notifications from the process.
      • Service task: This refers to a custom task in which you want some specific operations to be done. Similar to the mail task, which is a type of service task that is used to send e-mails from the process, we have a custom service written for the process.
    • Sub-Process : A Sub-Process is a task that is used to represent levels within our business process. This task is useful when we want to display the leveled diagram of a business process. A Sub-Process will be represented as follows:
    • The call activity : With the help of the call activity, we can re-use a global process or task that is available within the process engine. On executing the call activity, the control of execution is transferred to the global process or task. A call activity is represented as follows: 

Friday 22 April 2016

What is BPM (Business Process Modeling)? Lifecycle of BPM.

BPM Stands for Business Process Modeling, with respect to system engineering, providers method, and techniques to make a business process more efficient, adaptive and effective to accomplish business tasks. We will use the BPMN 2.0 modeling notations for designing our business process with the Activiti Engine. It provides a comprehensive approach to aligning an organization's business process as per the client's requirement. With the help of BPM, organizations can be more effective, efficient, and capable of accepting changes rather focusing on a traditional hierarchical  management approach.

The BPM lifecycle

The creation of a business process comprises the five phases of business process management, commonly known as the BPM lifecycle. The five phases are as follows:

  1. Design
  2. Modeling
  3. Execution
  4. Monitoring
  5. Optimization

Each phase is designed to implement a successful process solution. With the help of the BPM lifecycle, one can understand that implementing a business process is an ongoing process due to the changes occurring within the business environment. The five phases of the BPM lifecycle are as follows:

Design
The design phase of a lifecycle is responsible for the identification and design of a business process. The areas focused on within this phase are identifying activities, analyzing possible changes within the organization, defining service-level agreements, and specifying process details, such as actors, notifications, and escalations, within the business process. The main purpose of this phase is to ensure that a correct and efficient theoretical design is prepared. This phase belongs to the process owners who are deciding the process flow for the organization.

Modeling
Modeling is the second phase of the cycle; it's where the business process is validated and fully specified. In the design phase, the theoretical design is prepared, whereas in this phase, the theoretical business process is designed using various BPMN elements. This phase is mainly the responsibility of system analysts and integrators. 

Execution
Once the theoretical design is transformed into a model, it can be implemented in the business process application. Now, it's time to automate the execution of the business process. This is the phase where the services are defined to automate the business process. The languages used to create the services are WSBPEL and BPMN 2.0. This phase belongs to the developers who are developing the business process.

Monitoring
The monitoring phase keeps track of the individual processes. Performance monitoring for each and every process can be provided statistically, and the states of the process can also be maintained. In the monitoring phase, problems within a business process can be identified and corrective steps can be taken to improve it.

Optimization
The optimization phase is the last phase of the lifecycle. In this phase, the performance information of the process is fetched from the monitoring phase and improvements within the process and changes in the business requirement are identified. Once the optimization phase is completed, the business process again goes into the design phase and the cycle is completed.

Creating our first process in Activiti BPM.

Now is the right time to look at one simple process in Activiti. We will be using the Eclipse IDE for designing the business process. For now, we will just gain an understanding about creating a process.

We will create a simple leave process for employees in which we will have a script task and a user task. A script task is used for adding some logic within a process and a user task is used to indicate that there is some human interaction required in the process. 

Perform the following steps to create a process in Activiti:
  1. Create a new Activiti project in Eclipse by navigating to File > New > Project > Activiti. Project and name your project SimpleLeave-Process.The 
  2. SimpleLeave-Process project will have a folder structure as shown in the following screenshot:
  3. Now create an Activiti Diagram in the src/main/rersource/diagram folder structure.
  4. To create a diagram, navigate to File > New > Other > Activiti Diagram and name your diagram SimpleLeaveProcess. The folder structure is shown in the following screenshot:
  5. On opening the .bpmn file, a white canvas will appear on which you can design the business process.
  6. To draw a business process, there is a Palette option available which contains most of the BPMN diagrams for designing the business process. First, we will be adding a StartEvent on the canvas from the Event tab of the Palette option. All these options  are shown in the following screenshot:
  7. To add a script task, click on StartEvent and it will display the options as shown in the following screenshot. From those options, select the new element option, which will list down all the elements; from those elements, select Create script task, as shown in the following screenshot:
  8. To add a user task, click on Script Task and select new user task, which is the optiondisplayed with a human icon as shown in the following screenshot:
  9. As each and every business process should have at least one end event, to add an end event, click on User Task and select the new end event option, as shown in the following screenshot: 
  10. After adding the end event to the process, your business process should look similar to the following screenshot: 

  11. Now we have to make some changes to the properties of the process.
  12. First, we will change the properties of the start event. Select the start event, open the Properties tab, and add Form Properties in the Form tab using the New button as shown in the following screenshot:
  13. Now, edit the properties for the script task. In the Main config tab, there is a Script field available; within that, insert the print statement out:println"ApplyforLeaveby"+Empname;. The Empname property is the form property that we created in the start event. The script task will print the message on the console when it is executed, as shown in the following screenshot:
  14. Now we will edit the user task properties. In the General tab, we will populate the Name property, which will be displayed in the user task node, as shown in the following screenshot:
  15. As the user task is to be performed by a specific user, we have to provide the name of the user who will be responsible for executing it.
  16. We have to populate the Assignee property of the Main config tab with the name of the person to whom the task should be assigned; as shown in the following screenshot, we will be assigning it to kermit:
  17. We can  view the .bpmn file in the XML format. Right-click on the SimpleLeaveProcess.bpmn  file, browse to OpenWith | XML Editor, and it will be available in the XML format. The result of this step is shown in the following screenshot:

Thursday 21 April 2016

Getting Started with Activiti BPM

Let's take a quick tour of the Activiti components so you can get an idea of what the core modules are in the Activiti BPM that make it a lightweight and solid framework. You can refer to the following figure for an overview of the Activiti modules:

In this figure, you can see that Activiti is divided into various modules. Activiti Modeler, Activiti Designer, and Activiti Kickstart are part of Modelling, and they are used to design your business process. Activiti Engine can be integrated with your application, and is placed at its center as a part of Runtime. To the right of Runtime, there are Activiti Explorer and Activiti Rest, which are part of Management and used in handling business processes. Let's see each component briefly to get an idea about it. 

The Activiti Engine
The Activiti Engine is a framework that is responsible for deploying the process definitions, starting the business process instance, and executing the tasks. 

The following are the important features of the Activiti Engine:
  1. Performs various tasks of a process engine
  2. Runs a BPMN 2 standard process
  3. ‹‹It can be configured with JTA and Spring
  4. Easy to integrate with other technology
  5. Rock-solid engine
  6. Execution is very fast
  7. Easy to query history information
  8. Provides support for asynchronous execution
  9. It can be built with cloud for scalability.
  10. Ability to test the process execution.‹
  11. Provides support for event listeners, which can be used to add custom logic to the business process.
  12. Using Activiti Engine APIs or the REST API, you can configure a process engine
  13. Workflow execution using services

You can interact with Activiti using various available services. With the help of process engine services, you can interact with workflows using the available APIs. Objects of process engines and services are threadsafe, so you can place a reference to one of them to represent a whole server.

In the preceding figure, you can see that the Process Engine is at the central point and can be instantiated using ProcessEngineConfiguration. The Process Engine provides the following services:

  1. RepositoryService: This service is responsible for storing and retrieving our business process from the repository
  2. RuntimeService: Using this service, we can start our business process and fetch information about a process that is in execution
  3. TaskService: This service specifies the operations needed to manage human (standalone) tasks, such as the claiming, completing, and assigning of tasks
  4. IdentityService: This service is useful for managing users, groups, and the relationships between them
  5. ManagementService: This service exposes engine, admin, and maintenance operations, which have no relation to the runtime execution of business processes
  6. HistoryService: This service provides services for getting information about ongoing and past process instances
  7. FormService: This service provides access to form data and renders forms for starting new process instances and completing tasks

The Activiti Modeler
The Activiti Modeler is an open source modeling tool provided by the KIS BPM process solution. Using the Activiti Modeler, you can manage your Activity Server and the deployments of business processes. It's a web-based tool for managing your Activiti projects. It also provides a web form editor, which helps you to design forms, make changes, and design business processes easily.

The Activiti Designer
The Activiti Designer is used to add technical details to an imported business process model or the process created using the Activiti Modeler, which is only used to design business process workflows. The Activiti Designer can be used to graphically model, test, and deploy BPMN 2.0 processes. It also provides a feature to design processes, just as the Activiti Modeler does. It is mainly used by developers to add technical detail to business processes. The Activiti Designer is an IDE that can only be integrated with the Eclipse plugin.

The Activiti Explorer
The Activiti Explorer is a web-based application that can be easily accessed by a non-technical person who can then run that business process. Apart from running the business process, it also provides an interface for process-instance management, task management, and user management, and also allows you to deploy business processes and to generate reports based on historical data.

The Activiti REST
The Activiti REST provides a REST API to access the Activiti Engine. To access the Activiti REST API, we need to deploy activiti-rest.war to a servlet container, such as Apache Tomcat. You can configure Activiti in your own web application using the Activiti REST API. It uses the JSON format and is built upon Restlet. Activiti also provides a Java API. If you don't want to use the REST API, you can use the Java API.

Wednesday 20 April 2016

What is Activiti? Installing Activiti step

Activiti is a lightweight, open source workflow and a Business Process Management (BPM) platform distributed under the Apache license. It can also be clustered and managed on a Cloud environment. It is the best platform to build BPM for people-to-people communication. It can be used very easily in every Java environment. It supports all aspects of BPM in the full context of software development. You can build any custom process language as per your requirement. It is a technology that is welcomed, because it allows people to use the tools that they are accustomed to, instead of replacing them with new ones. You can even involve a person with minimal technical know-how in implementing business workflows. It's easy to get up and running with the setup utility. It also has a  superfast and rock-solid BPMN 2 process engine, which provides the best platform for collaboration between non-technical business users and technical developers.

Downloading and installing Activiti BPM

To start with Activiti, we will first download it. To download Activiti, just go through its website at Download Activiti and download the latest version, activiti-5.20.0.zip, into your local system. Now extract that ZIP file and you will get all the directories for all the operating systems (the file structures will be the same). You will get the list of directories and files as shown in the following screenshot:


In the database directory, you will find the entire SQL scripting file. The wars directory contains activiti-explorer.war and activiti-rest.war. You can also find Java documents and the user guide in the docs directory. The libs directory contains all the Activiti JAR files.

Prerequisites for Activiti
Before starting the installation of Activiti, there are some prerequisite software applications that should be installed on your system.

JDK 6 or higher
Activiti runs on a version of JDK higher than or equal to Version 6. Go to Download JDK and click on the Download JDK button. There are installation instructions on this page. To verify that your
installation was successful, run the following command in the command prompt:

java -version

Execution of this command should print the installed version of your JDK.

Eclipse Juno or Indigo
Eclipse will be required when you start working with Activiti Designer as the Activiti Designer only works with Indigo or Juno. Hence, download Eclipse Juno or Indigo from Download Eclipse, unzip the downloaded file, and you can start Eclipse from within the Eclipse folder.

To install the Activiti framework on the system, we will use Apache Tomcat; perform the following steps:


  1. Download the latest Apache Tomcat from Download Tomcat and extract it onto your local system.
  2. Copy activiti-explorer.war from the activiti-5.x\wars folder and place it in the apache-tomcat-7.0.33\webapps folder, as shown in the following screenshot:
  3. Now we will start the Apache Tomcat server so that the activiti-explorer.war file is deployed to the webapps folder.
  4. The Windows operating system, browse to apache-tomcat-7.0.33\bin and double-click on startup.bat, as shown in the following screenshot:
  5. Now, the startup.bat file will start executing and deploying the Activiti Explorer on the system. During installation, it will set up the Activiti Engine, H2 database, default users, and much more. The result of this installation can be seen in the following screenshot:
  6. All the directories of the Activiti Explorer will be created on the apache-tomcat-7.0.33\webapps\activiti-explorer path once the installation is completed.
  7. For the Linux operating system, we can use the command prompt to start Apache Tomcat.
  8. The location of the war file will be the same as that for the Windows operating system. To start Apache Tomcat, we need to browse to the ../apache-tomcat-7.0.33/bin path using the command prompt and execute the following command:

    sh catalina.sh run

Monday 18 April 2016

Use Zone To Trigger Angular Digest Loop For External Functions

To continue my series on the power of Zone, I examine yet another powerful and useful way you can use zones to improve your application. If this is your first time learning about Zone, read my introduction to Zone titled Taming Asynchronous Tasks in JavaScript with Zone.js. Anyone familiar with Angular apps has run into the concept of the $digest loop. This is essentially a pass to update data-binding. When the model is mutated, which can happen a number of ways, anything observing the model is notified. The watchers may also mutate the model further which results in a recursive call until either the changes settle or the maximum recursion is reached.

The problem with this approach is that Angular is only aware of changes that happen within the loop. Directives that ship with Angular are automatically called within the loop so their changes are propagated. It is not uncommon to introduce a third-party library that may mutate the model somehow. When this happens, Angular is not aware of the changes because it happens outside of the loop. When you are able to intercept the update yourself, you can make it inside of a call to $apply which will notify Angular of the change. However, you don’t always have the luxury of intercepting third-party modules.

To demonstrate how Zone can help, I created a simple (contrived) scenario. Assume you have a simple clock you wish to display:

The timer, however, comes from a third party control. It exposes a timer object and runs on a timer but you can only kick it off – you have no control of the actual code that makes the updates. Again, to keep it simple, assume this amazing control works like this (remember, you only have access to the externalTimeObj, and something else kicks it off).



But the problem is you don’t see any updates (here’s the proof). Even though the timer object is updating, it happens outside of the digest loop so Angular isn’t aware. What’s worse is that the only way you can update your timer to call $apply is to get in and modify the source code which isn’t ever a great idea. If only there was a way to create an execution context that would automatically update the digest loop when done. Then you could call the initialization methods for the third-party timer control from within that execution context and capture the updates. Wait, there is! We have Zone.

First, create a zone that is dedicated to initiating the digest loop when it’s work is finished. OK, don’t, because I’ve already done it and it looks like this:

The digestCapture variable is necessary to allow Angular to initialize the call into the digest loop. If we bootstrap Angular in this zone we’ll create too much overhead because Angular methods that already execute in the digest loop will trigger a redundant call when the task is complete. Notice how once the digest call is captured, the check for it is removed by replacing the onZoneEnter function with a no-op.

There is no need to change any of the Angular code (that’s why I love this approach – open to extensibility, closed to change). Simply add the code to capture the digest function:

There is also no need to change the third-party control. Instead, we just move our third-party control initialization into the zone (again, we’re using the interval here but this could be any call into the third-party API as once it happens in a zone it is captured for that zone).

That’s it! Now we’ve got a way to initialize our third-party controls and ensure any time they return from an asynchronous task that we are able to notify Angular our model has mutated by running the digest loop. See the code running yourself.

Interception Using Decorator And Lazy Loading With AngularJS

Angular provides it’s own dependency injection that supports everything from annotations to decorators. Interception is a feature that allows you to extend, intercept, or otherwise manipulate existing services. It makes it easy to monkey-patch existing APIs to suite the specific needs of your application. You can build an app that relies on the built-in services for common functionality such as logging and still apply your own custom behavior as needed.


To illustrate this, consider a simple Angular app. The markup simply displays a title:
The controller is a bit more interesting because it configures the title and then logs a few messages to the console. By default, Angular’s $log service provides a safe way to log information to the browser’s console. I say “safe” because it will check if the console is present before attempting to use it so you won’t throw exceptions on older browsers. Let’s look at  a simple controller that is injected its $scope to set up the title and the $log service to log a warning and an error. Notice how the service uses the $injector property (array) to annotate its dependencies – you can verify this by changing the name of the constructor parameters to see they will still be injected correctly.

var MyController = (function () {
    function MyController($scope, $log) {
        this.$scope = $scope;
        this.$log = $log;
        $scope.title = 'Decorator example';
        $log.warn('This is a warning.');
        $log.error('This is an error.');
    }
    MyController.$injector = ['$scope', '$log'];
    return MyController;
})();
Wiring up the app is then simple:

var app = angular.module('myApp', []);
app.controller('MyController', MyController);

When you run the app in a browser with the console open, you’ll see the warning and error written to the console of course, some systems may wish to capture errors and warnings in a different way. You may want to present a debug console to the user regardless of the browser they are in, or even wire up a service that can record exceptions on the server. Either way, instead of writing your own logging service, you can use Angular’s decorator to monkey-patch the $log service and extend it with your own functionality. This supports the open/closed principle, to keep your components open to extension but closed to direct modification.

First I’ll extend the markup to provide a console area. I wouldn’t normally do this using the $rootScope but it will keep the example simple. It also shows how we can set up a global area outside of any of the controllers:

Now let’s create a service that simply picks up anything generated as a warning or an error and keeps track of it. (If you wanted to, you could take what I wrote about providers in my last post and use that to configure how much history the service keeps).



var MyConsole = (function () {
    function MyConsole() {
        this.lines = [];
        this.writeLn = this.pushFn;
             }
    MyConsole.prototype.pushFn = function (message) {
        this.lines.push(message);
    };
    return MyConsole;
})();

Notice : this simply tracks an array internally and exposes a method to write to it. By itself, it won’t do much good because there is no way to see what’s actually being written. In the HTML we’re expecting something called console that contains a collection. Normally you’d wire this in your app’s run section or similar, but for fun let’s have the service itself set up the root scope. The problem is that in using the service to monkey-patch the logger, we’ll have to instantiate it before the $rootScope is created by Angular. If we try to inject it as a dependency, we’ll get an exception. To fix this, we’ll keep track of whether we have the root scope or not, and ask the $injector if it is a available. Here is the updated service:

var MyConsole = (function () {
    function MyConsole($injector) {
        this.lines = [];
        this.rootScope = false;
        this.writeLn = this.lazyRootCheckFn;
        this.injector = $injector;
    }
    MyConsole.prototype.pushFn = function (message) {
        this.lines.push(message);
    };
 
    MyConsole.prototype.lazyRootCheckFn = function (message) {
        this.pushFn(message);
        if (!this.rootScope && this.injector.has('$rootScope')) {
            this.rootScope = true;
            this.injector.get('$rootScope').console = this.lines;
            this.writeLn = this.pushFn;
        }
    };
    MyConsole.$inject = ['$injector'];
    return MyConsole;
})();

Notice : that there are two internal functions that can be exposed as the outer writeLn function. At first, a function called lazyRootCheckFn that checks for the $rootScope is wired in. It asks the $injector if it has the $rootScope yet, and when it does, wires it up. It then swaps the external function with the simpler function called pushFn that simply adds the message to the list. This prevents it from checking again every time it is called because the $rootScope wire-up is a one-time event. This is also how you can lazy-load dependencies when they are not available to your app, because the $injector is the first thing Angular wires up as it handles everything else and allows you to query whether something has been configured yet using the has function. Now the console on the root scope is wired to the collection of messages and ready for data-binding. Of course, you won’t see anything yet because the logger needs to be intercepted.

To intercept a service, request the $provide service during your app’s configuration:
app.config([
    '$provide', function ($provide) {
}]);

This service exposes a function named decorator that allows you to intercept a service. You pass the decorator the service you wish to intercept, then an annotated function that you use for decoration. That function should request a dependency named $delegate. The $delegate dependency passed in is the service you wish to intercept (in this case, the $log service). At the end of the function, you return the service to take it’s place. You could return an entirely new service that mimics the API of the original, or in the case of our example simply monkey-patch the existing service and return it “as is.” Here I just return the original service:
$provide.decorator('$log', [
'$delegate',
'myConsole',
function ($delegate, myConsole) {
    return $delegate; // this is the $log service
}]);
I want to intercept calls to warn and error, so I created a function to reuse for patching:

var swap = function (originalFn) {
    return function () {
        var args = [].slice.call(arguments);
        angular.forEach(args, function (value, index) {
            myConsole.writeLn(value);
        });
        originalFn.apply(null, args);

    }
};

The function returns a new function that effectively parses out the arguments into an array, sends them to my own version of the console service, then calls the original function with the arguments list. Now I can monkey-patch the existing methods to call my own:

$delegate.warn = swap($delegate.warn);
$delegate.error = swap($delegate.error);
That’s it! My controller has no clue anything changed and is still faithfully calling the $log service. However, as a result of intercepting that service and adding a call to myConsole, and the fact that myConsole lazy-loads the $rootScope and wires up, it now will display errors and warnings on the page itself:

Thursday 7 April 2016

AngularJS Modularization

There are many custom module provide in angularjs to develop the user friendly code. Angulajs comes with a built-in dependency injection machanism. you can devided into application into multiple different types of components which Angularjs can inject into each other.

Modularizing your application makes it easier to reuse, configure and test the components in your application.

Angularjs contains following types of core objects and components.

  1. Value
  2. Service
  3. Provider
  4. Factory
  5. Constant
  1. Value
    A value is simple object in angularjs. it can be a number, string or javascript object. value are typically used as configuration which is injected into factories, services, or controllers.

    A value is global type of variable/object declaration in angularjs. That variable/object you can inject with any others angularjs module.

    A value has to belong to an Angularjs module. value are defined using value() function on the module. there are contains two parameter.

    • First parameter contains name of the value.
    • Second parameter is the value itself.

    Syntax : modulename.value('value_name','value_it_self');

    Example :
    var myApp = angular.module("myApp", []);
    myApp.value("numbervalue",'123456');
    myApp.value("stringvalue",'Kaushik Parmar');
    myApp.value("objectvalue",{key1: val1, key2: val2, key3: val3});


    Factories, Services and controllers can now reference these values by their name.

    Injecting a Value:
    Injectiong value into angularjs controller function is done simply by adding parameter with the same name as the value.

    Example :
    var myApp = angular.module("myApp", []);
    myApp.value("numberValue",'123456');
    myApp.controller("MyController", ['$scope', 'numberValue', function($scope, numberValue){
             console.log(numberValue);
    }]);


  2. Service
    The service are singleton object or function that carry out specific tasks. it holds some business logic.Separation of concern is at the heart while designing an AngularJS application. Your controller must be responsible for binding model data to views using $scope. It does not contain logic to fetch the data or manipulating it.

    Thus service is a stateless object that contains some useful functions. These functions can be called from anywhere; Controllers, Directive, Filters etc. Thus we can divide our application in logical units. The business logic or logic to call HTTP url to fetch data from server can be put within a service object.

    Putting business and other logic within services has many advantages. First it fulfills the principle of separation of concern or segregation of duties. Each component is responsible for its own work making application more manageable. Second this way each component can be more testable. AngularJS provides first class support for unit testing. Thus we can quickly write tests for our services making them robust and less error prone.

    There are two types of services available in AngularJS

    1. Internal Service

      AngularJS provides internally many services that we can use in our application. $http is best example of internal services. There are other useful internal services such as $routre, $window, $location.

      These services can be used with in controller by just declaring them as dependencies.

      Example :

      app.controller('myController', ['$scope', '$http', '$location', function($scope, $http, $location){
          // your business logic put here.
      }])

    2. External Service (Custom Services)

      We can define our own services in angularjs app and use them wherever required. There are way to declare services in your angularjs application.

      Example.

      var app = angular.module('myapp', []);
      app.service('my_own_service', function(){
                 this.users = ['John', 'James', 'Jake'];
      });

      or

      app.service('my_own_service', function() {
          this.method1 = function() {
                   //..
          }
          this.method2 = function() {
                   //..
          }
      });

  3. Provider
  4. Factory
  5. Constant

Running PHP applications in Apache Tomcat 7

Apache Tomcat 7 is a popular server for running Java applications – but say you have a unique instance where you want to run both PHP and Java applications on Tomcat but don’t want to run two separate servers (i.e. Apache HTTPD + Tomcat) to achieve it?

[ Note : This method is not working on tomcat 8. ]

For this we are going to use the PHP – Java Bridge for Tomcat, which is a handy little package that will sort out PHP execution on top of Tomcat.

Step 1: Start download the Javabridge template. This will give you a WAR file that you can directly drop in to your Tomcat server’s webapps folder.
  • For Windows users, the next step is to download PHP and extract it somewhere:
  • For Linux users, just install php5 using apt-get or your preferred package management tool.
Step 2: To add PHP to the PATH variable. Append the path to your PHP folder to the end of your respective PATH variable.

Step 3: Deploy the JavaBridgeTemplate.war file in to your Tomcat server’ or Drop the JavaBridgeTemplate.war file in to your Tomcat server’s webapps folder and start Tomcat.
        How to Deploy .war file into your tomcat server?

  1. Put this url (http://localhost:8080/manager/html) url in web browser then display one prompt where you put your tomcat manager gui username and password and login. 
  2. Then display one tomcat manager dashboard.
  3. There you find "WAR file to deploy" option and select the your JavaBridgeTemplate.war and press deploy button.
Step 4: When you navigate to your server’s Java Bridge folder (this is http://localhost:8080/JavaBridgeTemplate/ by default), you’ll be able to see the Java Bridge’s index page
       If you go tohttp://localhost:8080/JavaBridgeTemplate/test.php, you’ll be able to see the output from the phpinfo() function

If you open up test.php in the JavaBridgeTemplate folder in your Tomcat’s webapp folder, you can edit some of the code:

Now you can deploy any PHP application within the JavaBridgeTemplate folder and rename the folder to whatever you want. You can add many folders like this for different PHP applications.

Note : that the JavaBridge runs PHP as CGI. If you want to enable/disable specific PHP extensions you can simply enable them as you would do normally on your php.ini file.
     

Saturday 2 April 2016

Route provider in AngularJS


Thursday 31 March 2016

State provider in AngularJS

Introduction
AngularJS is a well-known Javascript framework nowadays. It provides a great support to create SPA (Single Page Applications), easing some of the tedious stuff needed when writing client-side Javascript applications (boilerplate code, DOM bindings, URL routing, etc).

AngularJS is shipped with all the necessary things to build expressive applications without depending on third-party libraries. Nevertheless, in very short time, AngularJS has created a great and very active community around it, creating different AngularJS components over well-known Javascript libraries, like Bootstrap, jQuery UI, etc. These new components are very useful to improve and maximize the potential of our applications.

One of the key points when creating single page applications is the routing mechanism used. The main objective of routing mechanism is to achieve that the user navigates the application like a normal site, but also avoiding or reducing the annoying waiting time due to a page change (page transition).

AngularJS already provides support for routing through the ngRoute module. ngRoute is a basic routing library where we can specify just one view and controller for any route (URL).
But there are situations when we need more control over routes or we need composite or nested views and we can’t achieve it easily with ngRoute.

The AngularJS community has created the AngularUI library. It provides different components which can be used in our AngularJS applications. This library has been broken down into several modules, so that, we can choose only the components we are interested in, instead of including the whole library.

AngularJS UI-Router
The UI-Router is a routing framework for AngularJS built by the AngularUI team, providing a different approach than ngRoute. Unlike ngRoute, it allows us to change the application views based on the state of the application and not just the URL route. In other words, it converts the parts of the application interface into a state machine.

As stated before, UI-Router is organised around states, which may optionally have routes, as well as other kind of behaviours attached. States are bound to named, nested and parallel views, allowing powerfully managing the application’s interface. With this approach, views and routes aren’t tied to the site URL, so we can change the parts of the site using the routing even if the URL does not change.

The library provides a lot of extra control in views: nested views, multiple views on the same page, etc. In order to have a finer grain control over the application routing, UI-Router is a great library to take advantage of.

States VS URL Routes
One of the drawbacks of routes is that we have to tie a route with an URL, having to use ngInclude or other method to change different parts of the page managed by this route. Using states, we are not tied to the URLs to modify parts of the application. States allows us to change parts of the pages using its routing process even when we don’t need to change the URL. Like ngRoute, uiRoute allows to configure the states, routing, controllers and views using the .config() command of AngularJS but there are some reasons because uiRoute has some advantages over the features provided by ngRoute:

UI-Router allows nested views and multiple views in each state. States are bound to named, nested and parallel views. It allows to manage the application’s interface in a more powerful way
With states you can access different information about the states and pass information between them

You can determine in which state you are on each moment, so you can act over the UI accordingly, for example, putting an active class to the navigation element for that state. States can be bound to URLs or not but states bound to URLs will be updated every time the URL changed using the custom uiRouter element ui-sref. Very handy for URLs based applications
State decorators can be used to modify dynamically the states configuration. It can be used to add custom functionality to ui-router, for example inferring template URLs based on the state name instead of configure them on each state beforehand

Components
As stated in the introduction to this routing library, the AngularJS UI-Router is built around states which allow us to have states bound to URLs like ngRoute module, but also leave us to have nested states and states with multiple views which is a very powerful feature we can take advantage in our applications. This is thanks to ui-router is based on states, not just a URL.
AngularJS Ui-Router provides a set of components we can use to create powerful, maintainable and well-structured applications:
  1. $state/$stateProvider: Manages state definitions, the current state, and state transitions. This includes triggering transition-related events and callbacks, asynchronously resolving any dependencies of the target state, and updating $location to reflect the current state. For states that have URLs, a rule is automatically registered with $urlRouterProvider that performs a transition to that state
  2. ui-sref directive: Equivalent to href or ng-href in <a /> elements except the target value is a state name. Adds an appropriate href to the element according to the state associated URL\ui-view directive: Renders views defined in the current state. Essentially ui-view directives are (optionally named) placeholders that gets filled with views defined in the current state
  3. $urlRouter/$urlRouterProvider: Manages a list of rules that are matched against $location whenever it changes
State Manager
To deal with the states creation, AngularJS UI-Router provides the $stateProvider component. It works similar to AngularJS $routeProvider, but it is focused on states. A state corresponds to a part of  the application in terms of the UI and navigation. A state describes (using the controller, template and view properties) the looks of that part if the UI and what is done there. States usually have things in common, so state hierarchies are used to leverage these relationships (parent/child states are known as nested states)

Define states
To define states, we use the .config method (as we already knew), but instead of setting our routes on $routeProvider, we set our states on the $stateProvider
    .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/home', templateUrl: 'partials/home.html' }) });

The lines above create a state named home using the state configuration object provided. This object has similar options to the one used when creating routes using $routeProvider in ngRoute module.

When an URL is specified in the state configuration object, this state is bound to an URL. When a state is activated, its template is inserted into the HTML tag containing the ui-view attribute of its parent state’s template.When a state is activated, its templates are automatically inserted into the ui-view of its parent state’s template. If the state is a top-level state (it does not have a parent state), then its parent template is the index.html of the application.
    <!-- index.html --> <body ng-controller="MainController"> <section ui-view></section> </body>

Templates
As we have already seen, templates are configured in the state configuration object when creating a state. There are different ways to define the template for a specific state:templates on each
  1. template: A string of HTML content or a function that returns HTML
  2. templateUrl: A string containing the URL path to a template or a function that returns a URL path string.
  3. templateProvider: A function that returns an HTML content string. This function can be injected and has access to local.
  4. Controllers: We can assign a controller to the template of a state. Just like in ngRoute, we can either associate an already registered controller with a URL using the string function name or we can create a controller function that operates as the controller for the state. It should be noted that if there is no template defined, then the controller will not be created. The controllers are specified using the controller key of the state configuration object and there are different ways to do this:
    * Using function to create the controller*/ $stateProvider.state('home', { template: '<h1>{{welcome}}</h1>', controller: function($scope){ $scope.welcome = 'Hello World'; } }) /* Using controller name if you already have a controller defined on the module */ $stateProvider.state('home', { template: ..., controller: 'HomeController' }) 14 /* Using controller as syntax */ $stateProvider.state('home', { template: '<h1>{{home.welcome}}</h1>', controller: function(){ this.welcome = 'Hello World'; }, controllerAs: 'home' })

If you need to resolve a list of dependencies which have to be injected to the controller before changing to the state, the resolve key of the state configuration object must be used. Check this to know more about this functionality.

State parameters
Like routes in ngRoute, When defining the URL of our states we can specify some placeholders in the URL and they will be converted as parameters which can be accessed in the controller through the $stateParams object:

    $stateProvider .state('orders', { url: '/order/:orderId', template: '<div><h1>Welcome to your order history</h1> <div>Showing order id {{orderId}}</div> </div>', controller: function($scope, $stateParams) { $scope.orderId = $stateParams.orderId; } })

We can also use curly braces to specify parameters in the URL: /order/{orderId}.
Take into account that in state controllers, the $stateParams object will only contain the parameters that were registered with that state. So we will not see the parameters registered on other states, including ancestors. To avoid that, we should create a resolve in the parent state to add the parent state parameter in order to be available in child states. Check this to see how to do it.


Activating states
There are three main ways to activate a state of our application:Navigate to the url associated with the state.

  1. Click a link containing the ui-sref directive (we will learn more about this later)
  2. Using $state.go method

Nested states
To leverage all the power provided by the Ui-Route library, we will have to use undoubtedly the nested states. States can be nested within each other which means that the child state will be rendered inside the ui-view of the parent state. Child states, in turn, can have nested states and so on.
In order to define child states, we can use the dot notation in the state name when defining a new state with $stateProvider:

    $stateProvider .state('home', { url: '/home' template: '<div>Home</div><div ui-view></div>' }) .state('home.main', { url: '/main', template: '<div>Main News</div>' }); .state('home.news', { url: 'news', template: '<div>List of News</div><ul><li ng-repeat="new in news"><a>{{new.title}}</a></li></ul>', controller: function($scope){ $scope.news = [{ title: 'First News' }, { title: 'Second News' }]; } });

The example above creates a “home” state bound to the “/home” URL and two child states, “main” bound to “/home/main” URL and “news” bound to “/home/news” URL. When activating one of the child states, the specific template will be rendered inside the ui-view element of the parent (home) state.
Child states can inherit some of the information contained in the parent state like resolved dependencies and custom state data properties.

Abstract states
There are situations where we need to have some common information available in several states.For this purpose UI-Router provides the possibility to specify abstract states.
Abstract states can have child states but they can not be activated itself neither transitioned to. An abstract state is implicitly activated when one of its child states are activated.
This is useful when:

  1. we need to prepend a url to all the child state urls
  2. we need to insert a template with its own ui-view that the child states will fill
  3. we need to provide resolved dependencies (via resolve) in order to be used by child states
  4. we need to provide inherited custom state data in order to be used by child states or events
  5. Abstract states are defined specifying the abstract key in the state configuration object set to true.
    $stateProvider .state('home', { abstract: true, templateURL: 'home.html' })

Multiple named views
Besides to provide parent/child relationship in states, UI-Router gives us the capability to have multiple named views inside states which will not be bound to any URL.
Having multiple views in our application can be very powerful. For example, maybe you have a sidebar on your site that has things like tweets, recommended items, advertising banner, popular posts, recent posts, users or whatever. These different blocks can all be separated and injected into our template. Each view will have its own controller and template, so our application will be better organized and cleaner.
This feature allows us having our application modular and also lets us reuse data in different templates to reduce the amount of duplicate code. In order to specify named views in states, we have to make use of the views property of state configuration object.
For example, if we have a view like this:
    <!-- partial-aside.html --> <div> <div ui-view="tweets"></div> <div ui-view="recommendations"></div> <div ui-view="users"></div> </div> /*We can create named views to fill each of these templates:*/ $stateProvider .state('aside', { views: { '': { templateUrl: 'partial-aside.html' }, 'tweets': { ... templates and/or controllers ... }, 'recommendations': {}, 'users': {}, } })

As stated in the official documentation, if we set the views parameter, then the state’s templateUrl, template, and templateProvider will be ignored. If we want to include a parent template in our routes, we’ll need to define an abstract state that contains a template, and a child state under the layout state that contains the ‘views’ object

Relative vs Absolute Naming
When using multiple views, UI-Router assigns every view to an absolute name. The structure for this is viewName@stateName, where viewname is the name used in the view directive and state name is the state’s absolute name, e.g. aside. You can also choose to write your view names in the absolute syntax. Remember that if an @ is used then the view path is considered absolute.
The next example has been taken from the documentation and it explains really well how to define relative and absolute names and how they are resolved:

  1. Relative Naming
  2. Relatively targets the 'detail' view in this state's parent state, 'contacts'.
    <div ui-view='detail'/> within contacts.html for example,
    "detail" : { },

    Relatively targets the unnamed view in this state's parent state, 'contacts'.
    <div ui-view/> within contacts.html for example,
    "" : { },









  3. Absolute Naming
  4. Absolutely targets the 'info' view in this state, 'contacts.detail'.
    within contacts.detail.html for example,
    "info@contacts.detail" : { }

    Absolutely targets the 'detail' view in the 'contacts' state.
    <div ui-view='detail'/> within contacts.html for example,
    "detail@contacts" : { }

    Absolutely targets the unnamed view in parent 'contacts' state.
    <div ui-view/> within contacts.html for example,
    "@contacts" : { }

    Absolutely targets the 'status' view in root unnamed state.
    <div ui-view='status'/> within index.html for example,
    "status@" : { }

    Absolutely targ8ets the unnamed view in root unnamed state.
    <div ui-view/> within index.html for example,
    "@" : { }

    $stateProvider .state('contacts', { templateUrl: 'contacts.html' }) .state('contacts.detail', { views: { "detail" : { }, "" : { }, "info@contacts.detail" : { } "detail@contacts" : { } "@contacts" : { } "status@" : { } "@" : { } });

$state
$state service is responsible for representing states as well as transitioning between them. It also provides interfaces to ask for current state or even states you’re coming from.
To see all the properties and methods of $state, check the documentation.
Link to other states using ui-sref
When creating a link with UI-Router, we will use ui-sref directive. The href will be generated from this and we can link to a certain state of our application.

Solve the Regular Falsi method equation using C

 In false positions, instead of always using the midpoint of [a,b] as the iteration point, you use the x-intercept of the line between (a,f(a)) and (b,f(b)). That is, given (a,f(a)) and (b,f(b)), compute the equation of the line between these points;
 Set y=0 and solve for x to find the x-intercept; call this intercept c. So
 . Now evaluate f(c) to determine whether it is positive or negative, and keep either a or b depending on the sign of f(c), just like in bisection.

To change your bisection code into a false positions code, copy bisect.f into another file, say falsa.f. Change the program name and comment line to reflect the change to false positions. The only line you need to change in the body of the code is the definition of y. Instead of y=(a+b)/2, you need to calculate the x-intercept, called c in the previous paragraph.

Run both bisection and false positions to find
. False position starts out slower than bisection - after the first two steps, the interval in which the root lies is smaller under bisection. But once false positions gets close to the root, it zips in quickly. So the method of false position shares with bisection the advantage of trapping a root and, therefore, always converging. But false position has a decided advantage in the speed with which it converges.

We next turn to another algorithm, Newton's method for finding roots. Newton's method does not always converge. But, when it does converge, it is very fast (at least once it is ``close enough'' to the root). Newton's method also has the advantage of not requiring a bracketing interval with positive and negative values (so Newton's method will allow us to solve tex2html_wrap_inline357 , whereas bisection and false positions will not).

The Regula-Falsi Method (sometimes called the False Position Method) is a method used to find a numerical estimate of an equation.This method attempts to solve an equation of the form f(x)=0. (This is very common in most numerical analysis applications.) Any equation can be written in this form.

Algorithm Requirements

This algorithm requires a function f(x) and two points a and b for which f(x) is positive for one of the values and negative for the other. We can write this condition as f(a).f(b)<0.
If the function f(x) is continuous on the interval [a,b] with f(a).f(b)<0, the algorithm will eventually converge to a solution.
This algorithm can not be implemented to find a tangential root. That is a root that is tangent to the x-axis and either positive or negative on both side of the root. For example f(x)=(x-3)2, has a tangential root at x=3.

Interceptor in AngularJS

What is interceptor?

Interceptor is generally some type of filter. it is work as a filter to make any type of request and response. interceptor are monitering to perform task.

Angular JS  built in service  $http  is used to make http server requests.  More often than not you would find yourself in a situation where you would want to run hooks for the http calls, i.e execute some logic before or after the http call. For example appending the auth token  to every api request or generic http response error handling. For this $http interceptors become quite handy. One more very important use of interceptors is to log http requests made to external API’s which can be used for analytics.

The interceptors are service factories that are registered with the $httpProvider by adding them to the $httpProvider.interceptors array. The factory is called and injected with dependencies (if specified) and returns the interceptor.

There are two kinds of interceptors (and two kinds of rejection interceptors):

request: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.

requestError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.

response: interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.

responseError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.

Let’s clear things with an example.

Response Interceptor

A response interceptor function takes a promise object as argument and returns the resolved promise.  The example Below handles 401 errors from the servers and does suitable error handling.  If the http request returns a success response it does not do anything. But if there is a error, it checks for the error code from the server and if its 401, redirects the user to the login page.

  1. myapp.factory('myHttpResponseInterceptor',['$q','$location',function($q,$location){ return { response: function(response){ return promise.then( function success(response) { return response; }, function error(response) { if(response.status === 401){ $location.path('/signin'); return $q.reject(response); } else{ return $q.reject(response); } }); } } }]); myapp.config(['$httpProvider',function($httpProvider) { $httpProvider.interceptors.push('myHttpResponseInterceptor'); }]);

Request Interceptor

A request interceptor function takes in a config object and returns a modified config object.  In the Example Below we are going to add a ‘auth token’ parameter to every request made to the API server.


  1. myapp.factory('httpRequestInterceptor', function ($cookieStore) { return { request: function (config) { var token = $cookieStore.get("auth"); config.url = URI(config.url).addSearch({'_auth_token':token}).toString(); return config; } }; }); myapp.config(function ($httpProvider) { $httpProvider.interceptors.push('httpRequestInterceptor'); });

  1. angular.module('MyApp', []) .config(function ($provide, $httpProvider) { $provide.factory('MyHttpInterceptor', function ($q) { return { request: function (config) { return config || $q.when(config); }, requestError: function (rejection) { return $q.reject(rejection); }, response: function (response) { return response || $q.when(response); }, responseError: function (rejection) { return $q.reject(rejection); } }; }); }); myapp.config(function ($httpProvider) { $httpProvider.interceptors.push('MyHttpInterceptor'); });

Saturday 26 March 2016

AngularJS: $watch, $digest and $apply

While browsing reddit, I read an article I felt over-complicated an explanation of $watch, $digest and $apply, and perhaps gave people a little bit of the wrong idea about what it is.

What is a $watch? 


Let's talk about this first. $watch is arguably the most important internal feature of Angular. $watches can be used to watch any value, and trigger a function call when that value changes. A $watch can be set up from any $scope by calling $scope.$watch() as shown below.

Setting up a $watch


There are two ways to set up a watch, by expression, or by function. Technically, they both do the same thing. If you pass an expression (a string), it will be evaluated against $scope and converted to a function to be watched. If you pass a function, it just watches that function, with no conversion necessary.


By Expression

The following will watch 'foo'. Which is an expression evaluated against $scope.
  1. //$scope.$watch(<function/expression>, <handler>); $scope.$watch('foo', function(newVal, oldVal) { console.log(newVal, oldVal); });


By Function

To set up a $watch by function, you can do the following, which is technically the same as what is shown above:
  1. $scope.$watch(function() { return $scope.foo; }, function(newVal, oldVal) { console.log(newVal, oldVal); });


Facts about $watch:

  • A watcher can evaluate any value.
  • A watcher's handler can execute anything when aforementioned value has changed.
  • All watchers are evaluated when $digest() is called.
  • If the first argument of a $watch is a string, it is $eval'ed into a function prior to registration. It's functionally equivalent to passing a function as the first argument, just with an extra step internally.


What is $digest?


At it's core, the important thing to know about $digest is that it loops through all watchers on the scope it was called on and it's child scopes. and evaluates them to see if they've changed, executing their handlers if they have. That's the important part you need to know.

How to call $digest:

  1. $scope.$digest();


What is $apply?


Simply put, it's a wrapper around $rootScope.$digest that evaluates any expression passed to it prior to calling $digest(). That's it.  So, if you're calling it by itself without passing an argument to it, you may as well just call $digest().

How to call $apply:


  1. $scope.$apply('foo = "test"'); //or $scope.$apply(function(scope) { scope.foo = 'test'; }); //or $scope.$apply(function(){ $scope.foo = 'test'; });

So when does a $digest/$apply happen?


At key moments defined by the framework. The Angular framework has built in calls to $digest and $apply to it's services and directives as well as some internal calls. But basically it's like this, things like $timeout perform a setTimeout, then call $apply or $digest (it actual does a little more than that, but that's the basic idea). $http.get(), same deal, makes an AJAX call, returns it, then queues up a $digest.  Then there are directives, like inputs with ngModel for example. Updates to the input will also trigger a $digest. You get the idea.

How do $watch, $digest, and $apply relate to updating my view?


  • The directive registers a $watch that looks for a change in the model on the $scope. The handler will update the DOM element's value.
  • The directive registers an event handler of some sort in the DOM that will get a value from the DOM and apply it to the model in $scope. It will also call $apply or $digest.
  • When you update the model in the scope via some in-framework call... $http.get() for example, it kicks off a $digest after it completes.
  • The $digest checks the $watch the directive registered, sees the change and fires the handler associated to it, updating the DOM element.

Why does Angular work this way?


Since Angular wanted to use plain-old-JavaScript-objects (*POJSO© Ben Lesh 2013 all rights reserved!! Brought to you by Carl's Jr), a digest was the only real choice. Why? Well you can observe setter and getters on known properties real-time, but there's really no way to build an event into adding new values to or removing values from an object or array, particularly when it's done by an indexer, ala hash table or array index. So a digest becomes necessary. How do I know this? Because I tried to write my own framework and quickly found myself writing a half-assed version of Angular. The only other option that I know of would be to completely wrap the model observation up in a construct with set() and get() functions... think Knockout... which makes the JavaScript code uglier to deal with (IMO).


Some Guidelines For Use:


  • $watch
    • DO use $watch in directives to update the DOM when a $scope value changes.
    • DON'T use $watch in a controller. It's hard to test and completely unnecessary in almost every case. Use a method on the scope to update the value(s) the watch was changing instead.
  • $digest/$apply
    • DO use $digest/$apply in directives to let Angular know you've made changes after an asynchronous call, such as a DOM event.
    • DO use $digest/$apply in services to let Angular know some asynchronous operation has returned, such as a WebSocket update, or an event from a 3rd party library like Facebook API.
    • DON'T use $digest/$apply in a controller. This will make your code harder to test, and asynchronous operations outside of the Angular framework don't belong in your controllers. They belong in services and directives.
Remember these are guidelines, not hard, fast rules. More importantly, they're my guidelines, so take them with a grain of salt.



When to use $apply vs $digest?


 $scope.$digest should rarely be used outside of some very specific instances. Such as an isolated scope in a directive that might want to only update itself. Or, in an extreme edge case if a scope object has been created for some other isolated purpose. $scope.$apply or $rootScope.$digest should be favored most of the time, as the general desired effect is to update an entire view or model. 

Create Thumbnail in Video in Spring and ffmpeg

import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.jcodec.api.Fr...