Thursday, 17 May 2018

Mokito

package com.in28minutes.springboot.controller;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.mockito.Mockito;

import org.skyscreamer.jsonassert.JSONAssert;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;

import org.springframework.boot.test.mock.mockito.MockBean;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpStatus;

import org.springframework.http.MediaType;

import org.springframework.mock.web.MockHttpServletResponse;

import org.springframework.test.context.junit4.SpringRunner;

import org.springframework.test.web.servlet.MockMvc;

import org.springframework.test.web.servlet.MvcResult;

import org.springframework.test.web.servlet.RequestBuilder;

import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import com.in28minutes.springboot.model.Course;

import com.in28minutes.springboot.service.StudentService;


@RunWith(SpringRunner.class)

@WebMvcTest(value = StudentController.class, secure = false)

public class StudentControllerTest {

@Autowired

private MockMvc mockMvc;

@MockBean

private StudentService studentService;

Course mockCourse = new Course("Course1", "Spring", "10 Steps",

Arrays.asList("Learn Maven", "Import Project", "First Example",

"Second Example"));

String exampleCourseJson = "{\"name\":\"Spring\",\"description\":\"10 Steps\",\"steps\":[\"Learn Maven\",\"Import Project\",\"First Example\",\"Second Example\"]}";

@Test

public void retrieveDetailsForCourse() throws Exception {

Mockito.when(

studentService.retrieveCourse(Mockito.anyString(),

Mockito.anyString())).thenReturn(mockCourse);

RequestBuilder requestBuilder = MockMvcRequestBuilders.get(

"/students/Student1/courses/Course1").accept(

MediaType.APPLICATION_JSON);

MvcResult result = mockMvc.perform(requestBuilder).andReturn();

System.out.println("leejo:"+result.getResponse());

String expected = "{id:Course1,name:Spring,description:110 Steps}";

// {"id":"Course1","name":"Spring","description":"10 Steps, 25 Examples and 10K Students","steps":["Learn Maven","Import Project","First Example","Second Example"]}

JSONAssert.assertEquals(expected, result.getResponse()

.getContentAsString(), false);

}

@Test

public void createStudentCourse() throws Exception {

Course mockCourse = new Course("1", "Smallest Number", "1",

Arrays.asList("1", "2", "3", "4"));

// studentService.addCourse to respond back with mockCourse

Mockito.when(

studentService.addCourse(Mockito.anyString(),

Mockito.any(Course.class))).thenReturn(mockCourse);

// Send course as body to /students/Student1/courses

RequestBuilder requestBuilder = MockMvcRequestBuilders

.post("/students/Student1/courses")

.accept(MediaType.APPLICATION_JSON).content(exampleCourseJson)

.contentType(MediaType.APPLICATION_JSON);

MvcResult result = mockMvc.perform(requestBuilder).andReturn();

MockHttpServletResponse response = result.getResponse();

assertEquals(HttpStatus.CREATED.value(), response.getStatus());

assertEquals("http://localhost/students/Student1/courses/1",

response.getHeader(HttpHeaders.LOCATION));

}

}

study this too   https://memorynotfound.com/unit-test-spring-mvc-rest-service-junit-mockito/

Show quoted text

Monday, 16 April 2018

WebMvcConfigurerAdapter

package com.leejo.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;

import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.PropertySource;

import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

import org.springframework.core.env.Environment;

import org.springframework.orm.hibernate4.HibernateTemplate;

import org.springframework.orm.hibernate4.HibernateTransactionManager;

import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;

import org.springframework.transaction.annotation.EnableTransactionManagement;

import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.leejo.bo.Interceptor;

import com.leejo.model.Student;

/**

* @author Leejo Jose

* @date 01-11-2017

*

*/

@Configuration

@ComponentScan("com.leejo")

@EnableWebMvc

@PropertySource("classpath:db.properties")

@EnableTransactionManagement

public class ApplicationContextConfig extends WebMvcConfigurerAdapter{

@Bean(name = "viewResolver")

public InternalResourceViewResolver getViewResolver() {

InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

viewResolver.setPrefix("/WEB-INF/views/");

viewResolver.setSuffix(".jsp");

return viewResolver;

}  

//leejo jose demo

@Autowired

private Environment env;

@Bean

public DataSource getDataSource() {

BasicDataSource dataSource = new BasicDataSource();

dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));

dataSource.setUrl(env.getProperty("jdbc.url"));

dataSource.setUsername(env.getProperty("jdbc.username"));

dataSource.setPassword(env.getProperty("jdbc.password"));  

return dataSource;

}

@Bean

@Autowired

public HibernateTransactionManager transactionManager(SessionFactory sessionFactory)

{

HibernateTransactionManager htm = new HibernateTransactionManager();

htm.setSessionFactory(sessionFactory);

return htm;

}

@Bean

@Autowired

public HibernateTemplate getHibernateTemplate(SessionFactory sessionFactory)

{

HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);

return hibernateTemplate;

}

@Autowired

@Bean(name = "sessionFactory")

public SessionFactory getSessionFactory(DataSource dataSource) {

LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);  

//sessionBuilder.addAnnotatedClasses(User.class,UserProfile.class,Student.class);

sessionBuilder.scanPackages("com.leejo.model");

return sessionBuilder.buildSessionFactory();

}

@Bean

public Properties getHibernateProperties()

{

Properties properties = new Properties();

properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));

properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));

properties.put("hibernate.current_session_context_class", env.getProperty("hibernate.current_session_context_class"));

return properties;

}

@Override

public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");

registry.addResourceHandler("/uploads/**").addResourceLocations("/uploads/");

registry.addResourceHandler("/albums/**").addResourceLocations("/albums/");

}

@Bean

public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {

return new PropertySourcesPlaceholderConfigurer();

}

@Autowired

@Bean(name = "studentService")

public Student getUserDetails(){

return new Student();

}

@Override

public void addInterceptors(InterceptorRegistry registry) {

// TODO Auto-generated method stub

registry.addInterceptor(new Interceptor());

}

}

Monday, 2 April 2018

Java 8

forEach() method in Iterable interface

Whenever we need to traverse through a Collection, we need to create an Iterator whose whole purpose is to iterate over and then we have business logic in a loop for each of the elements in the Collection. We might get ConcurrentModificationException if iterator is not used properly.

Java 8 has introduced forEach method in java.lang.Iterable interface so that while writing code we focus on business logic only. forEach method takes java.util.function.Consumer object as argument, so it helps in having our business logic at a separate location that we can reuse. Let’s see forEach usage with simple example.

example

package com.leejo.forech;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import java.util.function.Consumer;

import java.lang.Integer;

public class Java8ForEachExample {

public static void main(String[] args) {

//creating sample Collection

List<Integer> myList = new ArrayList<Integer>();

for(int i=0; i<10; i++) myList.add(i);

//traversing using Iterator

Iterator<Integer> it = myList.iterator();

while(it.hasNext()){

Integer i = it.next();

System.out.println("Iterator Value::"+i);

}

//traversing through forEach method of Iterable with anonymous class

myList.forEach(new Consumer<Integer>() {

public void accept(Integer t) {

System.out.println("forEach anonymous class Value::"+t);

}

});

//traversing with Consumer interface implementation

MyConsumer action = new MyConsumer();

myList.forEach(action);

}

}

//Consumer implementation that can be reused

class MyConsumer implements Consumer<Integer>{

public void accept(Integer t) {

System.out.println("Consumer impl Value::"+t);

}

}

---The number of lines might increase but forEach method helps in having the logic for iteration and business logic at separate place resulting in higher separation of concern and cleaner code.

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