Wednesday 28 March 2018

Javascript Validation Code to Block Free Emails (Gmail, Yahoo) & Allow Business Emails in Forms

Leejo.

<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script type="text/javascript">

$(document).ready(function(e){

$('#btnSubmit').click(function(){ 

var email = $('#Email').val();

var reg = /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)(?!yahoo.co.in)(?!aol.com)(?!abc.com)(?!xyz.com)(?!pqr.com)(?!rediffmail.com)(?!live.com)(?!outlook.com)(?!me.com)(?!msn.com)(?!ymail.com)([\w-]+\.)+[\w-]{2,4})?$/;

if (reg.test(email)){

return 0;

}

else{

alert('Please Enter Business Email Address');

return false;

}

});

});

</script>

</head>

<body>

<form id="yourid" action="" method="POST/GET">

<input type="text" name="email" id="Email">

<input type="submit" id="btnSubmit" name="download_submit" value="Submit">

</form>

</body>

</html>

Friday 16 March 2018

Jdbctemplate ,jpareposcutry

JPA

Using JpaRepository

 

 

JdbcTemplate operations

1.jdbcTemplate.query(qry, new BookMapper());----getting

2.jdbcTemplate.queryForObject

String qry="select * from book_master where book_id = ?";

return jdbcTemplate.queryForObject(qry, new BookMapper(),book_id);

3. jdbcTemplate.update

for adding

String qry="INSERT INTO book_master (book_name,book_author) VALUES(?,?)";

return jdbcTemplate.update(qry,book.getBook_name(),book.getBook_author());

String qry="UPDATE book_master set book_name=?,book_author=? where book_id=?";

jdbcTemplate.update(qry,book.getBook_name(),book.getBook_author(),book.getBook_id());

Spring ioc di

spring

1.What is Inversion of Control?

.Inversion of Control is a principle in software engineering by which the control of objects or portions of a program is transferred to a container or framework

.IoC enables a framework to take control of the flow of a program and make calls to our custom code. To enable this, frameworks use abstractions with additional behavior built in

. If we want to add our own behavior, we need to extend the classes of the framework or plugin our own classes.

-->Advantage

.decoupling the execution of a task from its implementation

.making it easier to switch between different implementations

.greater modularity of a program

.greater ease in testing a program by isolating a component or mocking its dependencies and allowing components to communicate through contracts

 

 

--Inversion of Control can be achieved through various mechanisms such as: Strategy design pattern, Service Locator pattern, Factory pattern, and Dependency Injection (DI).

 

2.What is Dependency Injection?

.Dependency injection is a pattern through which to implement IoC, where the control being inverted is the setting of object’s dependencies.

.The act of connecting objects with other objects, or “injecting” objects into other objects, is done by an assembler rather than by the objects themselves.

3.The Spring IoC Container

.In the Spring framework, the IoC container is represented by the interface ApplicationContext. The Spring container is responsible for instantiating, configuring and assembling objects known as beans, as well as managing their lifecycle.

.The Spring framework provides several implementations of the ApplicationContext interface 

--ClassPathXmlApplicationContext and FileSystemXmlApplicationContext for standalone applications

--WebApplicationContext,AnnotationConfigWebApplicationContext for web applications.   

.In order to assemble beans, the container uses configuration metadata, which can be in the form of XML configuration or annotations.

eg:ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");

4.Dependency Injection in Spring

public class Store {

private Item item;

public Store(Item item) {

this.item = item;

}

}

--To set the item attribute in the example above, we can use metadata. Then, the container will read this metadata and use it to assemble beans at runtime.

--Dependency Injection in Spring can be done through constructors, setters or fields.

5. Constructor-Based Dependency Injection

http://www.baeldung.com/inversion-control-and-dependency-injection-in-spring

6.Setter-Based Dependency Injection

7.Autowiring Dependencies

Wiring allows the Spring container to automatically resolve dependencies between collaborating beans by inspecting the beans that have been defined.

There are four modes of autowiring a bean using an XML configuration:

no: the default value – this means no autowiring is used for the bean and we have to explicitly name the dependencies

byName: autowiring is done based on the name of the property, therefore Spring will look for a bean with the same name as the property that needs to be set

byType: similar to the byName autowiring, only based on the type of the property. This means Spring will look for a bean with the same type of the property to set. If there’s more than one bean of that type, the framework throws an exception.

constructor: autowiring is done based on constructor arguments, meaning Spring will look for beans with the same type as the constructor arguments

@Bean(autowire = Autowire.BY_TYPE)

Java class loader

What is Java ClassLoader?

We know that Java Program runs on Java Virtual Machine (JVM). When we compile a Java Class, it transforms it in the form of bytecode that is platform and machine independent compiled program and store it as a .class file. After that when we try to use a Class, Java ClassLoader loads that class into memory.

There are three types of built-in ClassLoader in Java:

1.Bootstrap Class Loader – It loads JDK internal classes, typically loads rt.jar and other core classes for example java.lang.* package classes

2.Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.

3.System Class Loader – It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options.

1-->You should never be messing with rt.jar, it contains class files which is trusted by JVM and loaded without stringent security check it does for other class files. The runtime (rt.jar) holds all the (most of the..) java classes that form the Java SE. It is added to the classpath automatically

follow linkhttps://www.journaldev.com/349/java-classloader

Override hashcode and equals why

Override only equals

If only equals is overriden, then when you call myMap.put(first,someValue) first will hash to some bucket and when you call myMap.put(second,someOtherValue) it will hash to some other bucket (as they have a different hashCode). So, although they are equal, as they don't hash to the same bucket, the map can't realize it and both of them stay in the map.

Although it is not necessary to override equals() if we override hashCode(), let's see what would happen in this particular case where we know that two objects of MyClass are equal if their importantField is equal but we do not override equals().

Override only hashCode

Imagine you have this

MyClass first = new MyClass("a","first");

MyClass second = new MyClass("a","second");

If you only override hashCode then when you call myMap.put(first,someValue) it takes first, calculates its hashCode and stores it in a given bucket. Then when you call myMap.put(second,someOtherValue) it should replace first with second as per the Map Documentation because they are equal (according to the business requirement).

But the problem is that equals was not redefined, so when the map hashes second and iterates through the bucket looking if there is an object k such that second.equals(k) is true it won't find any as second.equals(first) will be false.

Hope it was clear

Word count using collection

package com.lightbend.akka.sample;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.HashMap;

import java.util.LinkedHashMap;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Set;

public class Testr {

//

// public static void main(String[] argv) {

//  Map<String, String> map = new HashMap<String, String>();

//  map.put("1","one");

//  map.put("2","two");

//  map.put("3","three");

//  map.put("4","four");

//   

// System.out.println(getKeyFromValue(map,"three"));

//  }

//

//  public static Object getKeyFromValue(Map hm, Object value) {

//  for (Object o : hm.keySet()) {

//  if (hm.get(o).equals(value)) {

//  return o;

//  }

//  }

//  return null;

//  }

// main() method - entry point to start execution

public static void main(String[] args) {

 

// sample test string

String testStr = "Science blank Maths blank blank Physics blank Maths Science Science";

 

// invoke to count & print for supplied file

countAndPrintRepeatedWordOccurences(testStr);

}

 

/**

* this method is used to count number repeated word occurrences

* @param fileName

*/

public static void countAndPrintRepeatedWordOccurences(String strContent) {

 

// Step 1: create Map of String-Integer

Map<String, Integer> mapOfRepeatedWord = new HashMap<String, Integer>();

 

// Step 2: split line using space as delimiter

String[] words = strContent.split(" ");

 

// Step 3: iterate through String[] array

for(String word : words) {

 

// Step 4: convert all String into lower case, before comparison

String tempUCword = word.toLowerCase();

 

// Step 5: check whether Map contains particular word, already 

if(mapOfRepeatedWord.containsKey(tempUCword)){

 

// Step 6: If contains, increase count value by 1

mapOfRepeatedWord.put(tempUCword, mapOfRepeatedWord.get(tempUCword) + 1);

else {

 

// Step 7: otherwise, make a new entry

mapOfRepeatedWord.put(tempUCword, 1);

}

}

 

System.out.println("Before sorting : \n");

System.out.println("Words" + "\t\t" + "Count");

System.out.println("======" + "\t\t" + "=====");

 

// Step 8: print word along with its count

for(Map.Entry<String, Integer> entry : mapOfRepeatedWord.entrySet()){

System.out.println(entry.getKey() + "\t\t" + entry.getValue());

}

 

// Step 9: Sorting logic by invoking sortByCountValue() method

Map<String, Integer> wordLHMap = sortByCountValue(mapOfRepeatedWord);

 

System.out.println("\n\nAfter sorting in descending order of count : \n");

System.out.println("Words" + "\t\t" + "Count");

System.out.println("======" + "\t\t" + "=====");

 

// Step 10: Again print after sorting

for(Map.Entry<String, Integer> entry : wordLHMap.entrySet()){

System.out.println(entry.getKey() + "\t\t" + entry.getValue());

}

}

 

/**

* this method sort acc. to count value

* @param mapOfRepeatedWord

* @return

*/

public static Map<String, Integer> sortByCountValue(

Map<String, Integer> mapOfRepeatedWord) {

 

// get entrySet from HashMap object

Set<Map.Entry<String, Integer>> setOfWordEntries = mapOfRepeatedWord.entrySet();

 

// convert HashMap to List of Map entries

List<Map.Entry<String, Integer>> listOfwordEntry = 

new ArrayList<Map.Entry<String, Integer>>(setOfWordEntries);

 

// sort list of entries using Collections class utility method sort(ls, cmptr)

Collections.sort(listOfwordEntry, 

new Comparator<Map.Entry<String, Integer>>() {

 

@Override

public int compare(Entry<String, Integer> es1, 

Entry<String, Integer> es2) {

return es2.getValue().compareTo(es1.getValue()); // NOTE

}

});

 

// store into LinkedHashMap for maintaining insertion order

Map<String, Integer> wordLHMap = 

new LinkedHashMap<String, Integer>();

 

// iterating list and storing in LinkedHahsMap

for(Map.Entry<String, Integer> map : listOfwordEntry){

wordLHMap.put(map.getKey(), map.getValue());

}

 

return wordLHMap;

}

}

Jax -rs

Webservice

1.Jersey is an open source framework for developing RESTful Web Services. It serves as a reference implementation of JAX-RS.

2.In a REST based architecture everything is a resource. A resource is accessed via a common interface based on the HTTP standard methods. In a REST based architecture you have a REST server which provides access to the resources. A REST client can access and modify the REST resources.

3.Every resource should support the HTTP common operations. Resources are identified by global IDs (which are typically URIs).REST allows that resources have different representations, e.g., text, XML, JSON etc. The REST client can ask for a specific representation via the HTTP protocol (content negotiation)

4.A RESTFul web services are based on HTTP methods and the concept of REST. A RESTFul web service defines the base URI for the services

===>jersy type controller

@Path("/authenticate")

@POST

@Produces(MediaType.APPLICATION_JSON)

@Consumes(MediaType.APPLICATION_JSON)

===>spring web service

@GetMapping("books")

Sunday 11 March 2018

Spring boot

spring boot: use because of --> if we wan to develop an end to end sys like controller service or from scratch we can use spring boot

. spring boot feature that provide when create an API or application 

. spring boot is==== spring is frame for entrprice java applicationn ,, boot stands for is bootstrap a spring application ,,it make easy to create stand alone ,production -grade spring based application that you can "just run"

--stand alone 

--production grade 

. Spring is dependency injunction in older definition ,, now it is more..... lot of things in spring ,, 

. spring has infrastructure suport to connect with db like casandra,mongo

. spring have not of configuration,in different ways

.spring boot ---

its stand alone , what u get u can start run ,and don't want start web server don't want to search for servlet ,and also is production ready

 

.--->convert simple maven to spring boot project

we using a <parent> tag with spring parameter to show the app is child of this parent spring 

 

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.0.0.RELEASE</version>

<relativePath/> <!-- lookup parent from repository -->

</parent>

this parent project above showing

spring boot team create a project  "spring-boot-starter-parent" above spring boot team created a project called spring-boot-starter-parent ,which contains opinionated set of maven configuration

and it provide set of maven depetency into pom.xml for creating the project. 

then we add "spring-boot-starter-jdbc" , "spring-boot-starter-web" which download the jar which mete dependency (these are articact id in dependency)

-->there is <properties> tag in pom.xml ,here which is used for use latest version of jdk  

<properties>

<java.version>1.8</java.version>

</properties>

-->in spring boot application we have a class with public static void main because spring boot is stand alone son need a class which bootstrap the app,,so don not need diployee on server or servelt container

main methord start the app, it create the servelet container and it do everything 

--> steps in class which has main method

1.we need to tell this is the spring application for that use @SpringBootApplication this tell this is the starting position

2.the we need to tell,spring boot to start this application and create servelet container and host this application on that servelt container ,this step done in one line

is SpringAppliction.run(CourseApi.class,args); ----->courseApi is calls which contain the main method

@SpringBootApplication

public class CourseApi {

//this class we are going for boot strap the application

public static void main(String[] args) {

SpringApplication.run(CourseApi.class, args);

}

}

spring is container that contain controller,business services,data services spring has container that contain all those services this is called application context of the application

each logics are implemented in classes with corresponding annotation like service classes annotated with @service and data access annotated with @Repository and son on.

spring want to look these classes and distinguish these classes according to annotation.so we need to scan the class path. so need give component scan.
#####
->@SpringBootApplication(scanBasePackages= {"com.leejo.controller"})

-->Here we need controller to handle the request,@RestController ->it means we can map to request to methord of class which use this anottation

 

-->@ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.

@ResponseBody is a marker for the HTTP response body and @ResponseStatus declares the status code of the HTTP response.

@ResponseEntity in detail===> we can many things with responseentity

@RequestMapping("/handle")

public ResponseEntity<String> handle() {

URI location = ...;

HttpHeaders responseHeaders = new HttpHeaders();

responseHeaders.setLocation(location);

responseHeaders.set("MyResponseHeader", "MyValue");

return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);

}

--->RequestEntity and ResponseEntity

 

@RequestMapping("getTopicsRequest")

public ResponseEntity<List<Topics>> getTopicsRequest(RequestEntity<List<Topics>> requestEntity){

System.out.println("request body : " + requestEntity.getBody());

HttpHeaders headers = requestEntity.getHeaders();

System.out.println("request headers : " + headers);

HttpMethod method = requestEntity.getMethod();

System.out.println("request method : " + method);

System.out.println("request url: " + requestEntity.getUrl());

return new ResponseEntity<>(null,HttpStatus.OK);

}

 

--->@RequestBody sample this can use viseversa with RequestEntity

@RequestMapping("getTopicsRequestBody")

public ResponseEntity<List<Topics>> getTopicsRequestBody(@RequestBody List<Topics> topics){

System.out.println("request body : " + topics);

return new ResponseEntity<>(null,HttpStatus.OK);

}

if you want to show the URI as requestentity above exapmle we have to use "UriComponentsBuilder" in parameter list

@PostMapping("book")

public ResponseEntity<Void> addBook(@RequestBody Book book,UriComponentsBuilder builder){

int flag=bookServiceImpl.addBook(book);

if(flag==0) {

return new ResponseEntity<Void>(HttpStatus.CONFLICT);

}

HttpHeaders headers = new HttpHeaders();

headers.setLocation(builder.path("/book/{book_id}").buildAndExpand(book.getBook_id()).toUri());

return new ResponseEntity<Void>(headers, HttpStatus.CREATED);

}