Sunday, August 9, 2015

AngularJS Basics

AngularJS is a Javascript framework which makes it incredibly easy to build web applications

Features of AngularJS: There are many features in AngularJS, primarily 2-way data binding, OO way of JS development, easy mapping between dom and JS model, Create custom tags, Dirty check on objects, implementing Routers.

Components:
  • RouteProvider
  • AngularJS templates (or) partials. 
  • Module
  • Controller

MVC: 
  • View holds the html fragments
  • Controller - holds the action to be performed
  • Model: holds data by getting from the REST services. 

Some attributes: 
  • ng-app: tell that this html page contains angularJS app
  • ng-model: bind the model to the div
  • ng-bind: used to bind the input tag to the model
  • ng-repeat: used to iterate through a list of model and display content. 
  • ng-controller: defines the controller that will be used for this div or section. 
  • ng-show | ng-hide: hide or show a div or section
  • ng-include: include another file in the html


AngularJS Directives: 
You can use directives in different ways:
  • As an attribute to a tag. 
  • As an element
  • As a class
  • As a comment
ng-init: used to initialise angularJS variables

You can also create custom directives: 

You have to use .directive method in the module to define a directive
myAppModule.directive('colorList', function () {
    return {
        restrict: 'AE',
        template:
              "<button ng-click='showHideColors()' type='button'>"
            + "{{isHidden ? 'Show Available Colors' : 'Hide Available Colors'}}"
            + "</button><div ng-hide='isHidden' id='colorContainer'>"
            + "</div>"

        }
});

AngularJS validation: 
  • $dirty
  • $valid
  • $invalid
  • $pristine

AngularJS Expressions: 
<p>My first expression: {{ 5 + 5 }}</p>
(or) 
<p>My first expression: {{ emp.getValue }}</p>
where emp is a angularJS model. 

AngularJS Filters: used to filter a list of values and display 
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ lastName | uppercase }}</p>
</div>

You can also create custom filters in AngularJS:


Events:
  • ng-click
  • ng-double-click

Angular Services:
$http: 
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php")
    .success(function(response) {$scope.names = response.records;});
});

var promise = $http({method: 'POST', url: 'memberservices/register', data: theData});

$window: represents browser window object. 
$location: gets information about the url and gives it to your application
$document: jqlite reference

You can also create custom services: 



—————————— Code Snippets ————————
Simplest AngularJS program
Enter your name : <input type="text" ng-model="ename">
Hello {{ ename }}
<script type="text/javascript" src="../js/lib/angular.min.js"></script>

Sample app code: 
<div ng-app="myApp" ng-controller="myCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName= "John";
    $scope.lastName= "Doe";
});
</script>

RouteProvider: used to define which AngularJS controller to call when you hit a URL
helloWorldApp.config(['$routeProvider', '$locationProvider', 
function($routeProvider, $locationProvider){ 
 $routeProvider. 
   when('/', { 
     templateUrl: 'partials/main.html', 
     controller: 'MainCtrl' }).
   when('/show', { 
     templateUrl: 'partials/show.html', 
     controller: 'ShowCtrl' 
}); 

AngularJS Templates: 
  • ng-view

AngularJS Controllers: 
  • Define methods which would inturn get the data from the server
      • use $http
var addonsControllers = 
  angular.module('addonsControllers', []);

addonsControllers.controller('AddonsCtrl', 
  ['$scope', 'checkCreds', '$location', 'AddonsList', '$http', 'getToken',
    function AddonsCtrl($scope, checkCreds, $location, AddonsList, 
      $http, getToken) {
        if (checkCreds() !== true) {
            $location.path('/loginForm');
        }

        $http.defaults.headers.common['Authorization'] = 
          'Basic ' + getToken();
        AddonsList.getList({},
           function success(response) { 
              console.log("Success:" + 
                     JSON.stringify(response));
                    $scope.addonsList = response;
           },
           function error(errorResponse) {
              console.log("Error:" + 
                     JSON.stringify(errorResponse));                   
           }
        );
        $scope.addonsActiveClass = "active";
}]);

ng-repeat
<li ng-repeat="phone in phones | filter:query">
          {{phone.name}}
          <p>{{phone.snippet}}</p>
        </li>


External controllers: 
<div ng-app="myApp" ng-controller="personCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}

</div>


<script src="personController.js"></script>

Spring security - different options

Spring provides options to perform authentication and authorisation. 

Authenticating using Spring: 
Spring provides the following features as part of authentication: 
  • Basic Authentication: process authentication based on user credentials present int he urls. 
  • Form based login: This is a default form which is provided as popup box to enter user credentials. 
  • Custom form: You can also create your own forms, but need to follow some rules so that Spring knows which is the form, its userid and password fields. 
  • Logout service: The user can logout using the logout url, the user object maintained in the session is removed. 
  • Remember me support. 

The data for authentication can reside in different places. Spring authentication provider provides support for user details to be 
  • hardcoded in memory files 
  <authentication-provider>
    <user-service>
        <user name="admin" password="secret" authorities="ROLE_ADMIN,ROLE_USER" />
        <user name="user1" password="1111" authorities="ROLE_USER" />
        <user name="user2" password="2222" disabled="true" authorities="ROLE_USER" />
    </user-service>
  </authentication-provider>
  • in the user SQL database. 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .dataSource(dataSource)
                .usersByUsernameQuery(
                        "SELECT username, password, 'true' as enabled FROM member WHERE username = ?")
                .authoritiesByUsernameQuery(
                        "SELECT member.username, member_role.role as authorities " +
                        "FROM member, member_role " +
                        "WHERE  member.username = ? AND member.id = member_role.member_id");
    }
  • Custom store - may be file or NOSQL storage. 
Create your own user details object and validate from wherever you want - DB, ftp etc., 
  • Identity store, you can retrieve using LDAP.
    <authentication-manager>
      <authentication-provider>
        <password-encoder hash="{sha}" />
        <ldap-user-service server-ref="ldapServer"
          user-search-filter="uid={0}" user-search-base="ou=people"
          group-search-filter="member={0}" group-search-base="ou=groups" />
      </authentication-provider>
    </authentication-manager>

    <ldap-server id="ldapServer"
        url="ldap://localhost:1389/dc=springrecipes,dc=com"
        manager-dn="cn=Directory Manager" manager-password="ldap" />

The configuration will also need to take care of what is the form page, what is the default successful url once logged in, the logout url, url signatures that need to be authenticated, userid and password field, action url of spring security. 

Securing URL Access

You can secure methods using different ways: 

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class ApplicationConfig { ... }

In the controller, 
  @Secured({"ROLE_USER", "ROLE_GUEST"})
    public List<Message> listMessages() {
        ...

    }

Implementing Data access layer using Spring - different options

This scrap note explains different ways by which you can implement Data access layer using Spring. Spring provides different ways for faster development of Data access layers. 

Using Direct JDBC: 
  • Creating the Datasource
In this you can configure the Datasource by providing the JDBC url, connection factory, user credentials string and create the DAO manually 
  • Creating DAO and accessing them
You can manually create the DAO and manually define methods for inserting, deleting, retrieving and modifying the entities. 

Using JDBC Template: 
In this you can use JDBCTemplate which simplifies the work for you, you have to create the JDBCTemplate on top of the data source you have defined. JDBCTemplate can be used to query and provide simple implementations to map to objects. 

Using Spring Data Modules: 
Spring data modules are the easiest way to implement DAO. 
In this you using data modules defined for each database type such as MongoDB, Cassandra or JPA etc., 

In Spring data modules you
  • Directly define the entities. 
  • The default CRUD implementation is provided for you. 
  • In case of custom implementation for DAO, you just provide the interface definition, the implementation is provided by the container. 

Its a very fast way of developing the Repository layer. 

There are lot of Spring data modules available such as
  • Spring data MongoDB
  • Spring data Cassandra
  • Spring data JPA 
  • Spring data REDIS

You can find more information about Spring data projects in http://projects.spring.io/spring-data/

When to use what: 
You can use Spring data modules for faster development, however it is not very flexible, but supports most of the day to day activities you perform with the DB, in case you want more control - you can go for JDBC Template. If you want full control, you can go for direct JDBC implementations, but you have to spend a lot of time in the mapping etc., 

Spring and Transaction management
There are 2 ways by which you can handle transactions
  • Programmatic way
  • Declarative way

Programmatic:
In the programmatic way, you have to manage your transaction which means you have to commit or rollback using the transaction manager API. 

Declarative: 
Declarative is the preferred way by most developers. 
  • Using AOP
  • Using @Transactional annotation. 

The @Transactional attribute supports the following attributes
  • REQUIRED
  • REQUIRES_NEW
  • SUPPORTS
  • NOT_SUPPORTED
  • MANDATORY
  • NEVER
  • NESTED

Isolation attributes
  • Dirty read
  • Non repeatable read
  • Phantom read
  • Lost updates. 

Isolation levels by Spring
  • DEFAULT
  • READ_UNCOMMITTED
  • READ_COMMITTED
  • REPEATABLE_READ
  • SERIALIZABLE


Spring MVC - Refreshing basics

Spring MVC is a way provided by Spring to handle and operate on web requests. 

The following steps are performed for any web requests. 
  • The request is sent to the Dispatcher servlet
  • The Dispatcher servlet passes the request to the handler mapping component. 
  • The handler mapping component returns the respective controller. 
  • The Controller receives the request along with the request attributes, performs the business logic and returns back the Model and view. 
  • The dispatcher servlet resolves the view name using the View resolver component.
  • The dispatcher servlet now knows which view to forward to, hence returns the respective view to the page. 

What should you do to get started using Spring mvc
  • Include required maven artifacts such as spring-webmvc and spring-web in your pom.xml
  • Add the component scanning class, just to tell container which classes to look out for. 
  • @EnableWebMvc to enable spring mvc in your application configuration file. 
  • Create Spring controllers: 
    • Tell the class that this is a controller class using @Controller
    • Define @RequestMapping annotation at the class level 
    • Define @RequestMapping annotation at the method level 
  • Create JSP views and provide view resolver mapping. 
  • Provide implementation in the controller method by accepting the input parameters, processing it and returning response. 

Signature of the controller method: 

The signature of the method of the controller is open ended, hence it can accept a variety of input parameters. Following are the possible parameters. 
  • The servlet request or servlet response
  • Request parameters annotated by @RequestParam annotation
  • Model attributes annotated by @ModelAttribute annotation
  • Cookie value in the incoming request using @CookieValue annotation
  • Map or model map for the user to had his own attributes. 
  • Errors or BindingResult for the user to add errors / validation result. 
and more options such as SessionStatus. 

@RequestMapping options: 
@RequestMapping("/member/add”)
@RequestMapping(value={"/member/remove","/member/delete"}, method=RequestMethod.GET)
@RequestMapping(value= "processUser", method =  RequestMethod.POST)

Note
  • You can use handler interceptor to provide implementation for pre / post processing of web requests. 
  • You can use resource bundle & message properties to implement internationalization. 
  • You can handle all the exceptions in one place using HandlerExceptionResolvers. 
  • You can publish data as rest services using @Requestmapping and @PathVariable. The return type can be XML or JSON depending upon the configuration 
  • You can produce JSON responses using Jackson mapping and @ResponseBody annotation. 
  • You can also access REST services using RESTTemplate class, there are multiple methods available to perform REST operation such as getForObject, put, delete, postForEntity etc., 
  • You can publish RSS feds using jdom. 


Spring basics

Spring - Basics (refreshing the basics)

This scrap note includes: 
  • Configuring beans using @Configuration
  • Creating beans and referencing them
  • Bean scopes

Configuring beans using @Configuration
You can configure actions such as configuring all the beans, reading resources from the property files, establishing connection to database in the @Configuration class.

@Configuration
@ComponentScan(basePackages = "com.deiveehan")
@PropertySource(value = "classpath:application.properties")
public class ApplicationConfig {

  @Inject
  Environment environment;

  @Bean
  public InternalResourceViewResolver configureInternalResourceViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    return resolver;
  }
}

Note: 
  • @Configuration is used to tell that this is a Bean configuration file. 
  • @ComponentScan is used to tell the container where to look for the class files. 
  • @PropertySource is used to define the properties file. 
  • environment.getProperty("host”) is used to get the property value. 
  • @Bean is used to define the beans. 

Creating beans and referencing them

You can create beans in 2 ways - using xml or using bean configuration files. 

Using annotation: 
@Bean is used to define a bean and 

Referencing beans: 
@Autowired is used to reference a bean
You can autowire a bean at the class level and at the method level. 

Example: 
@Configuration
@EnableMongoRepositories(basePackages = {
"com.deivee.framework.mongorepository",
“com.deivee.app.mongorepository" })
public class MongoDBConfig {

@Autowired
Environment environment;

@Bean
public Mongo mongo() throws Exception {
  return new Mongo(environment.getProperty("host"));
}
@Bean
public MongoTemplate mongoTemplate() throws Exception {
  return new MongoTemplate(mongo(),
  environment.getProperty("mongoDBName"));
}
}

and the MongoTemplate can be accessed in any bean class as below

@Autowired MongoTemplate. 

Bean scopes

There are 5 different types of bean scopes in Spring
  • singleton (single bean instance per container)
  • prototype (new bean each time when referred)
  • request (new bean for each request) 
  • session (available for the entire session)
  • globalsession (for a global http session, valid for portal application). 

For example you can create the scope for the bean when you create it. 
@Component
@Scope("prototype")
public class LoginAction {
Misc: 

  • You can use @PostConstruct to perform action after it is constructed and use @PreDestroy to perform action before it is destroyed. 
  • You can use @Profile to create profiles for different environment. 
  • You can detect the type of device that is sending the request using this String userAgent = request.getHeader("User-Agent”); the value of userAgent will be android, iPad, kindle etc., 
  • You can also use spring with other web frameworks such as JSF. 

Friday, July 24, 2015

Vuzix glass - Basics

What is Vuzix: 

Vuzix is an android based wearable device with recording features & connectivity options such as Wifi/BLE capabilities, mainly designed for professional users


How to run: 
  • Mode: 
    • local: apps can be load into onboarded memory. 
    • paring Android device and using Vuzix as a heads up display. 
    • Both: local and pairing to communicate and collaborate with android device. 
  • OS 2.0 
    • provided by Vuzix which is built on top of Android 4.0.4. 
    • Support for Android, iOS (in development). 

Features: 
  • Captures 5MP camera and 1080p HD videos, memory - 4gb expandable to 32 GB. 
  • provides 3 buttons - to control vuzix and the android apps (i.e., select options in android app, back and android menu options can be controlled in Vuzix). 
  • Voice navigation: Recognition performed locally, so no internet connection required, can also navigate completely using voice, (eg., move right, left, show menu, go home etc
  • M100 can act as a heads up display for legacy android apps while the partner device itself can act as a touch pad / keyboard controls. 
  • Gesturing. 
  • Built in native apps in M100 which helps the user in performing basic features such as 
    • calling msging where the head unit can be used to scroll contacts and initiate call, the partner device will be used for calling while M100 will be used as a headset. 
    • view calendar apps and move to next appointment by using voice commands and more. 
  • Smart glass manager Android app which can be used to control the M100 device. 

General spec: 
Vuzix: 5MP, 1080p, WQVGA display, left / right eye usable, 1 GB RAM, Android 4.0.4, 4GB flash expandable to 32 GB via external miscrosd slot. supports BLE / wifi. 
Glass: 5MP, 720p, 16gb flash (not expandable), supports Bluetooth / wifi. 

How to get started in Vuzix. 
  • Sign up and purchase Vuzix SDK - cost $199, pay an annual registration fee if you want to stay updated. 
  • Vuzix promises to have a M100 specific app store in the future. As of now, we need to upload programs using ADB drivers. 

Differences from google glass: 
  • While Glass app need to be compiled with GDK (i.e., Android native apps cannot be viewed in Glass, the app need to be compiled in GDK to be viewed), Vuzix can act as a head display for Android apps. The apps being viewed in M100 can be controlled via the buttons, voice commands or even the android device (acting as a touch pad and keyboard). 
  • Glass supports latest version (Kit kat) while Vuzix supports ICS -4.0.4). 
  • Glass has companion app for Android and IOS while Vuzix supports Android today, IOS in development. 
  • Glass 1500$ while Vuzix costs 1000$ and SDK costs 199$, GDK is free. 
  • Vuzix has 1GB RAM and 4gb built in flash (expandable to 32 GB), while glass does not provide an external SD card slot. 
  • Glass gets heated within 10-15 mins of using continuously and gets heated even faster if you are using AR app, not sure about Vuzix. 
Hope you got some information about vuzix. 
Visit this site for more information about Vuzix products 

Tuesday, July 21, 2015

NFC Basics


What is NFC 
Near field communication is a set of protocols that helps devices to communicate with each other by establishing a connection either by touching the devices or bringing them close to each other (typically 4 cm). Its a set of short-range wireless technologies requiring less distance to initiate a connection. 

NFC tags: There are variety range of NFC tags available in the market
types ranging from coins, cards, wearble, stickers, business cards etc., You can also write to tags. 

What can you store in NFC tag: 
Depends on the type of the tag and its memory, for example a small NFC tag can store just the url whereas a business card can store more information about the user. 

NFC Readers: There are lot of NFC tag readers, you can also write applications using Android / IOS api to read NFC information. 

Why NFC
  • Quick handshake time. 
  • potential for signal interference or hackers trying to steal your data is reduced. 
  • NFC consumes less battery power 

Applications of NFC: 
  • Payment for products through mobile phones
  • NFC based wearables can become a cashless payment system. 
  • Access control
  • Queue management - who registered first. 
  • Launch an app: open maps and launch direction to home when you tap your mobile on a nfc tag in the car
  • Perform an action: For example set an alarm whenever you tap on a sticker
  • Share business cards information
  • using Mobile phone for boarding passes. 
  • NFC enabled parking meters

Difference between NFC and bluetooth: 
  • NFC is designed for less data transfer - less than 400 kb whereas you can transfer more data using bluetooth
  •  quick handshake - typically takes 0.1 second, whereas bluetooth takes more time to establish the connection. 
Questions to ask before choosing NFC as a solution: 
  • Is your application requires close contact with the devices less than 10 cm. 
  • Is it a one way communication. 
  • Is the action performed important since it requires the user to hold or tap the device within 10 cm. If not choose other technology such as RFID or bluetooth. 

You can also use NFC to initiate a connection and then use other technology to transfer more data.