Translate

10 May 2017

Spring Boot

What is Spring Boot?

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".
  • Building an end to end app
  • Spring Boot Features
  • Configuration and Customization


What is Spring?
  • Application frameworks
  • Programming and configuration model
  • Infrastructure support


Problems with Spring
  • Huge framework
  • Multiple setup steps
  • Multiple configuration steps
  • Multiple build and deploy steps


What Spring Boot give us
  • Opinionated
  • Convention over Configuration
  • Stand alone
  • Production ready


Java dependencies-Maven


Maven is a build automation tool used primarily for Java projects. The word maven means "accumulator of knowledge" in Yiddish.

Maven addresses two aspects of building software:
  • it describes how software is built
  • it describes its dependencies.


Maven takes care of
  • Dependency Management
  • Building a deployable unit - Packaging War Ear
  • Running things you want - like unit tests
  • Multiple Modules
  • Running application in Tomcat
  • Generating sample projects. Maven Archetypes archetype:generate


Project Object Model (pom.xml) :

POM stands for "Project Object Model". It is an XML representation of a Maven project held in a file named pom.xml.

The POM contains information about the project and various configuration detail used by Maven to build the project(s).

All POM files require the project element and three mandatory fields: groupId, artifactId, version.

Root element of POM.xml is project and it has major sub-nodes :
  • project: It is the root element of project
  • modelVersion: It is the sub element of project. It specifies the modelVersion. It should be set to 4.0.0.
  • groupId: It is the sub element of project. It specifies the id for the project group.
  • artifactId: It is the sub element of project. It specifies the id for the artifact (project). An artifact is something that is either produced or used by a project. Examples of artifacts produced by Maven for a project include: JARs, source and binary distributions, and WARs.
  • version: It is the sub element of project. It specifies the version of the artifact under given group.

Creating a Maven Java Project





Update the  pom.xml file 


Building Spring Boot Application



Starting Sprint Boot
  • Sets up default configuration
  • Starts Spring application context
  • Performs class path scan
  • Starts Tomcat server


Add a controller
  • A Java class
  • Marked with annotations
  • Has info about
    • What URL access triggers it?
    • What method to run when accessed?






Embedded Tomcat Server
  • Convenience
  • Servlet container config is now application config
  • Standalone application
  • Useful for microservices architecture

REST API
  • GET          /topics           gets all topics
  • GET          /topics/id      gets the topic
  • POST        /topics           create new topic
  • PUT          /topics/id      updates the topic
  • DELETE     /topics/id      deletes the topic

Creating a Business Service











25 April 2017

Testing NodeJS


Testing Patterns
  • Unit: Small tests covering individual functions.
  • Integration: Integrated modules(combined functionality).
  • Functional: Focused on end result of larger actions.
  • Acceptance: Typically client-side, end-to-end testing.

JavaScript Testing Frameworks
  • jasmine
  • karma
  • expresso
  • mocha
  • node-tap
  • intern
  • node-unit
  • vows
  • node-qunit
  • More...

MOCHA 
http://mochajs.org/

Mocha is used to unit test nodeJS applications.

MOCHA Setup

-install mocha as a development dependency for project


-Update package.json


Asynchronous Testing


Basic Tests and Assertions

assert.equal: check more or less equal
assert.strictEqual: exactly equal in type and value


Running the Test



Assertion Methods
  • equal: Asserts non-strict equality (==) of actual and expected.
  • strictEqual: Asserts strict equality (===) of actual and expected.
  • deepEqual: Asserts that actual is deeply equal to expected.
  • isOk: Asserts that object is truthy. 
  • isNull: Asserts that value is null.
  • isTrue: Asserts that value is true.
  • fail: Throw a failure. Node.js assert module-compatible.
  • match: Asserts that value matches the regular expression regexp.
  • throws: Asserts that function will throw an error that is an instance of constructor, or alternately that it will throw an error with message matching regexp.

Testing Tips
  • Keep your modules small.
  • Be sure to test success AND error cases.
  • Test expected AND unexpected data.
  • Don't forget that modules are cached.

Testing with Mocks

  • Use mocha to test javascript code. Invoke the command mocha to start the tests.
  • Use chai for assertions.
  • If we find any problematic code then use sinon to spy or stub them to see/ control the behaviour of the functions.
  • Use nock to mock servers to prevent making any http calls to the outside environment.
  • Use rewire to set/ get variables/external dependencies in the javascript file.
  • Use istanbul to calculate the code coverage done by these unit tests.

12 April 2017

Spring Framework



Introduction
  • Rod Johnson started SpringSource company and developed Spring framework for Apache 2.0 in June 2003.
  • The Spring Framework is an open source application framework and inversion of control container for the Java platform.
  • It provides comprehensive infrastructure support or developing Java applications.
  • Spring handles the infrastructure so you can focus on your application.

Why Spring?
  • Spring is a framework like Struts and Hibernate.
  • Spring is famous in the industry.
  • Spring and Hibernate are extremely popular and widely used in the industry.
  • Spring framework is lightweight as it does not involve installation, start and stop activities associated with a container.

Java Frameworks

In Java technology there are so many frameworks that helps the programmers to build complex applications easily.

You can choose these frameworks for building your applications.
  • Hibernate: Database access mechanism
  • Struts: Web layer
  • EJBs: Services like transactions, security, and messaging
  • Log4J: Logging
  • More...

-Java Frameworks problem:
  • Applications that use these varied frameworks and services become difficult to maintain as it grows including testing.

-Applications need:
  • Applications that use a number of frameworks and the services have to remain maintainable.
  • Codes should be loosely coupled with the frameworks so that testing and reusability become easy.

-Spring Framework advantages:
  • Spring Framework provides a light-weight solution to develop maintainable and reusable enterprise applications.
  • It provides very simple and rich facilities to integrate various frameworks, technologies, and services in the application.

-To back up its attack on Java complexity, Spring employs four key strategies:
  • Lightweight and minimally invasive development with Plain Old Java Objects(POJOs).
  • Loose coupling through dependency injection and interface orientation.
  • Declarative programming through aspects and common conventions.
  • Boilerplate reduction through aspects and templates.


Spring Featured/Modules
  • Inversion of Control: Done through Dependency Injection.
  • Aspect Oriented Programming: Enabling implementing cross-cutting concerns.
  • Data Access: Works with JDBC and Hibernate.
  • Model View Controller: Provide MVC Support through servlets and struts. This is web framework.
  • Remote Access Framework: Supports remote access through RMI, web service through SOAP and REST.
  • Remote Management: JMX is the technology that is used to manage the system objects and devices like printers.
  • Messaging: Uses JMS to communicate through Message Queues.
  • Testing: Supports classes for writing unit test cases and integration test cases.
  • Convention over Configuration: Spring Roo is another framework which eases the development. This is Rapid Application Development tool.
  • Authentication and Authorization: This is provided by Spring Security module.

Spring Architecture


Architecture has 5 layers:
  • Data Access/Integration
  • Web
  • Aspect
  • Core
  • Test

Data Access/Integration has JDBC, ORM, OXM, JMS and Transaction modules.
  • JDBC: JDBC code can be done using JDBC Template.
  • ORM: Can develop code using ORM tools like Hibernate, iBatis etc.
  • OXM: OXM stands for Object to XML Mapping. It supports technologies like JAB.
  • JMS: Can send JMS operations in this module.
  • Transaction: Supports both Programmatic and Declarative Transaction Management. Programmatic is handling in the program and declarative is handling either as part of Annotation or using XML.

Web layer has WebSocket, Servlet, Web, Portlet modules.
  • WebSocket: This module provides support for WebSocket-based, two-way communication between the client and the server in web applications.
  • Servlet: Used for servlets.
  • Web: This module will initialize the IOC Container using servlet listener.
  • Portlet: This module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module.

Aspect and Test layer
  • AOP: Used for Aspect Oriented Programming. This will allow to define interceptors and point-cuts to separate them as required.
  • Aspects: This module helps to integrate with AspectJ. AspectJ is another AOP framework.
  • Instrumentation: Instrumentation is the ability to monitor the level of products performance, to diagnose the errors and write the trace information.
  • Messaging: The Messaging module provides support for STOMP as the WebSocket sub-protocol to use in applications. It also supports an annotation programming model for routing and processing STOMP messages from WebSocket clients.
  • Test: Supports to test the spring modules using Junit framework.

Core layer has Beans, Core, Context, SpEL modules.
  • Beans: It implements beanfactory through factory pattern.
  • Core: It has DI and IOC features.
  • Context: Used for ApplicationContext. It uses Core and Beans module.
  • SpEL: This module provides a powerful expression language for querying and manipulating an object graph at runtime.

28 March 2017

AngularJS

Angular is a JavaScript framework that helps build web applications.

Benefits of AngularJS

  • Dependency Injection
  • Two Way Data-Binding
  • Testing
  • Model View Controller
  • Directives, Filters, etc...

Module in AngularJS

A module is a container for different parts of your application i.e controllers, services, directives, filters, etc.

var app=angular.module("myModule",[]);

Controller in AngularJS

In angular a controller is a JavaScript function. The job of the controller is to build a model for the view to display.

var myController=function($scope){
$scope.message="Angular JS";
};

when the controller name is misspelled,
  • An error is raised. To see the error, use browser developer tools.
  • The building expressions in the view that are in the scope of the controller will not be evaluated.
when the property name in the binding expression is misspelled,
  • angular will not report any error. It will simply return null or undefined.

Two way Data-Binding in AngularJS

The two way Data-Binding, keeps the model and the view in sync at all times, that is a change in the model updates the view and a change in the view updates the model.

Binding expression updates the view when the model changes
{{firstname}}

ng-model directive updates the model when the view changes
<input type="text" ng-model="firstname">

ng-model directive can be used with
  • input
  • select
  • textarea

AngularJS Filters

Filters are used to format, sort, and filter data.

Filters can be used with a binding expression or a directive.
  • currency Format a number to a currency format.
  • date Format a date to a specified format.
  • filter Select a subset of items from an array.
  • json Format an object to a JSON string.
  • limitTo Limits an array/string, into a specified number of elements/characters.
  • lowercase Format a string to lower case.
  • number Format a number to a string.
  • orderBy Orders an array by an expression.
  • uppercase Format a string to upper case.
To apply a filter use pipe(|) character
{{ expression | filterName:parameter }}

To sort the data in Angular
-Use orderBy filter
 {{ orderBy_expression | orderBy: expression : reverse }}
 {{ x in cars | orderBy:'model':false }}
 to sort in ascending order, set reverse to false.
 to sort in descending order, set reverse to true.

AngularJS Services

A service in Angular is simply an object that provide some sort of service that can be used with in an angular application.

Services encapsulate reusable logic that does not belong anywhere else(i.e Directives, Filters, Views, Models, and Controllers)

Benefits of using services:
  • Reusability
  • Dependency Injection
  • Testability

12 March 2017

Express JS


Introduction
  • Developed by TJ Holowaychuk in November 2010.
  • Is a web application framework for Node.js.
  • Free and open-source software.
  • Licensed under MIT.

Features
  • Facilitates the rapid development.
  • Allow to set up middleware to respond to HTTP requests.
  • Defines a routing table.
  • Allows to dynamically render HTML pages.

Environment Setup
  • Install node.js and npm
  • Install express module by npm command

--save: Package will appear in your dependencies.

Express Routing
  • Refers how an application responds to a client request to an endpoint.
  • Each route can have one or more handler functions.
app.METHOD(PATH,HANDLER)




Express JS URL Binding


✦req.params used to read the bind values(name,age).
✦regular expression also used to name parameter.


Express JS Middleware
  • Express is middleware web framework that has minimal functionality of its own.
  • An Express application is essentially a series of middleware function calls.
  • Middleware functions access to the request object, the response object, and the next middleware function.

✦app.use() used to Mounts the middleware function or mount to a specified path,the middleware function is executed when the base path matches.
✦The order you place your middleware is very important. Everything will happen in the order that they appear.



Express Router

✦Express router is a class which helps us to create router handlers. By router handler i mean to not just providing routing to our app but also can extend this routing to handle validation, handle 404 or other errors etc.




Express JS Templating

✦Template engine allows you to use static template files in your application.
✦Some popular template engines that work with Express are Pug, Mustache, and EJS.
✦Here, we'll use Pug.

Pug
✦Is a templating engine for express.
✦Earlier it was called Jade.
✦npm command is used to install this package. 


Express Static Files

⊿Are files that clients use as they are from the server.
⊿Files such as images, CSS files, and JavaScript files are served using express.static middleware function.
⊿Express looks up the files relative to the static directory.
app.use(express.static(__dirname+'public'));
⊿We can also set multiple static directories.

26 February 2017

What is MongoDB?
SQL
not allowed





MongoDB is an open source document database with the scalability and flexibility that you want with the querying and indexing that you need.
MongoDB supports dynamic schema design, allowing the documents in a collection to have different fields and structures. The database uses a document storage and data interchange format called BSON, which provides a binary representation of JSON-like documents.

  • MongoDB stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structure can be changed over time.
  • The document model maps to the objects in your application code, making data easy to work with.
  • Ad hoc queries, indexing, and real time aggregation provide powerful ways to access and analyze your data.
  • MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution are built in and easy to use.
  • MongoDB is free and open-source, published under the GNU Affero General Public License.

Install the MongoDB

Go to the https://www.mongodb.com/ website and download the mongodb.


MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is c:\data\db. So you need to create this folder on that location.
or
If you have to install the MongoDB at a different location, then you need to specify an alternate path for \data\db by setting the path dbpath in mongod.
command: mongod --dbpath [PATH_TO_DATA_DIRECTORY]

Start MongoDB

⊿Go to the mongodb installed directory.


⊿Then open the mongod server.


mongod is a primary daemon process for the mongodb system. It handles data requests, manages data access, and performs background management operations.

⊿After open the mongo application.


Some commands

display already exist databases



switched to database(create a new or use already exist)



display the current switched database


add the following document(primary) to the database(Student)


primary: primary school students
each results stored separate document(primary) in mongodb.
add same record without error. Because mongodb generate unique ObjectId. 

display the all document values


display the all document values in arrange format


ObjectId is added by mongodb. It's act as primary key(unique).

display the particular name document


used regular expression to find the document

  • db.primary.find({"name":/a/})          //like %a%
  • db.primary.find({"name":/^a/})        //like a%
  • db.primary.find({"name":/a$/})        //like %a


ᐅ update the particular document



remove the particular document