Javascript: Constructor function changes


var Employee=function(){

    console.log("Employee Constructor Function");

};

var Manager=function(){
console.log("Manager constructor function");
};

Manager.prototype=new Employee;

console.log("Manager.prototype.constructor::"+Manager.prototype.constructor);

Output:

Employee Constructor Function

Manager.prototype.constructor::function (){

    console.log("Employee Constructor Function");

}

Prototype and constructor in javascript object

var Employee=function(){
    console.log("Employee Constructor Function");
};

var e=new Employee();

console.log("Employee prototype::"+Employee.prototype);
console.log("Employee Constructor::"+Employee.prototype.constructor);
console.log("e.__proto__::"+e.__proto__);
console.log("e.__proto__.constructor::"+e.__proto__.constructor);
console.log("object constructor function::"+e.constructor);

Spring MVC + Hibernate + MySQL java based configuration

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.springframework.samples.service.service</groupId>
	<artifactId>productkart</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<properties>

		<!-- Generic properties -->
		<java.version>1.6</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

		<!-- Web -->
		<jsp.version>2.2</jsp.version>
		<jstl.version>1.2</jstl.version>
		<servlet.version>3.0.1</servlet.version>


		<!-- Spring -->
		<spring-framework.version>4.0.2.RELEASE</spring-framework.version>

		<!-- Hibernate / JPA -->
		<hibernate.version>4.3.5.Final</hibernate.version>

		<!-- Logging -->
		<logback.version>1.0.13</logback.version>
		<slf4j.version>1.7.5</slf4j.version>

		<!-- Test -->
		<junit.version>4.11</junit.version>

	</properties>

	<dependencies>

		<!-- Spring MVC -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>

		<!-- Other Web dependencies -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlet.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>${jsp.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- Spring and Transactions -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		<!-- Spring MVC -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>


		<!-- Logging with SLF4J & LogBack -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
			<scope>runtime</scope>
		</dependency>

		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>


		<!-- Test Artifacts -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring-framework.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>1.9.5</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-remote-shell</artifactId>
			<version>1.0.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
			<version>1.0.0.RELEASE</version>
		</dependency>

		<!-- MySQL database driver -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.9</version>
		</dependency>

	</dependencies>
</project>

Web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">
    <display-name>productkart</display-name>
</web-app>

Replacement of ApplicationContext.xml

package com.productkart.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("com.productkart.web")
public class Config {

	@Bean
	public ViewResolver setupViewResolver(){
		ResourceBundleViewResolver resourceBundleViewResolver=new ResourceBundleViewResolver();
		resourceBundleViewResolver.setBasenames(new String[]{"spring/views/resourceviews"});
		return resourceBundleViewResolver;
	}
}

src/main/resources/spring/views/resourceviews.properties

showMessage.(class)=org.springframework.web.servlet.view.JstlView
showMessage.url=/WEB-INF/view/showMessage.jsp

Replacement of data-context.xml

package com.productkart.dao.configuration;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;

@Configuration
@PropertySource("classpath:com/productkart/dao/mysqlconfig.properties")
public class MySQLDatabaseConfig {

	 	private static final String DATABASE_DRIVER = "jdbc.driverClassName";
	    private static final String DATABASE_PASSWORD = "jdbc.password";
	    private static final String DATABASE_URL = "jdbc.url";
	    private static final String DATABASE_USERNAME = "jdbc.username";
	         
	    private static final String HIBERNATE_DIALECT = "hibernate.dialect";
	    private static final String HIBERNATE_SHOW_SQL = "hibernate.show_sql";
	    private static final String ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";

	    @Autowired
	     Environment env;
	       
	         
        @Bean
        public DataSource dataSource() {
               final DriverManagerDataSource dataSource = new DriverManagerDataSource();
                 
                dataSource.setDriverClassName(env.getRequiredProperty(DATABASE_DRIVER));
                dataSource.setUrl(env.getRequiredProperty(DATABASE_URL));
                dataSource.setUsername(env.getRequiredProperty(DATABASE_USERNAME));
                dataSource.setPassword(env.getRequiredProperty(DATABASE_PASSWORD));
                 
                return dataSource;
        }
        
        
        @Bean
        public LocalSessionFactoryBean sessionFactory(){
        	 final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
             sessionFactory.setDataSource(dataSource());
             sessionFactory.setPackagesToScan(new String[]{env.getRequiredProperty(ENTITYMANAGER_PACKAGES_TO_SCAN)});
             sessionFactory.setHibernateProperties(this.hibernateProperties());

             return sessionFactory;
        }
        
        final Properties hibernateProperties() {
            return new Properties() {
                /**
				 * 
				 */
				private static final long serialVersionUID = 3083741219093456400L;

				{
                    this.put("hibernate.dialect", env.getRequiredProperty(HIBERNATE_DIALECT));
                    this.put("hibernate.show_sql", env.getRequiredProperty(HIBERNATE_SHOW_SQL));
                    this.put("use_sql_comments", true);
                }
            };
        }
        
        @Bean
        public HibernateTransactionManager transactionManager(){
        	final HibernateTransactionManager hibernateTransactionManager=new HibernateTransactionManager();
        	hibernateTransactionManager.setSessionFactory(sessionFactory().getObject());
        	return hibernateTransactionManager;
        }
        
}

src/main/resources/com/productkart/dao/mysqlconfig.properties

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/product_kart
jdbc.username = root
jdbc.password = 1234
hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql = true
entitymanager.packages.to.scan = com.productkart.model

Replacement of web.xml dispatcherServlet configuration

package com.productkart.configuration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import com.productkart.dao.configuration.MySQLDatabaseConfig;

public class WebInitializer implements WebApplicationInitializer {

	public void onStartup(ServletContext servletContext) throws ServletException {
		AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
		ctx.register(MySQLDatabaseConfig.class);
		 ctx.register(Config.class);
		 
		 ctx.setServletContext(servletContext);
		 
		 Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
		 servlet.addMapping("/");
		 servlet.setLoadOnStartup(1);
	}

}

Modal Class Product

package com.productkart.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="product")
public class Product implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6082590531017752969L;
	private Integer productId;
	private String productNm;
	private String productDesc;
	private Double productCost;
	private Character logicalDelFl;
	/**
	 * @return the productId
	 */
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="product_id", unique=true, nullable=false)
	public Integer getProductId() {
		return productId;
	}
	/**
	 * @param productId the productId to set
	 */
	public void setProductId(Integer productId) {
		this.productId = productId;
	}
	/**
	 * @return the productNm
	 */
	@Column(name="product_nm", unique=true, nullable=false)
	public String getProductNm() {
		return productNm;
	}
	/**
	 * @param productNm the productNm to set
	 */
	public void setProductNm(String productNm) {
		this.productNm = productNm;
	}
	/**
	 * @return the productDesc
	 */
	@Column(name="product_desc")
	public String getProductDesc() {
		return productDesc;
	}
	/**
	 * @param productDesc the productDesc to set
	 */
	public void setProductDesc(String productDesc) {
		this.productDesc = productDesc;
	}
	
	/**
	 * @return the productCost
	 */
	@Column(name="product_cost")
	public Double getProductCost() {
		return productCost;
	}
	/**
	 * @param productCost the productCost to set
	 */
	public void setProductCost(Double productCost) {
		this.productCost = productCost;
	}
	/**
	 * @return the logicalDelFl
	 */
	@Column(name="lgcl_del_fl")
	public Character getLogicalDelFl() {
		return logicalDelFl;
	}
	/**
	 * @param logicalDelFl the logicalDelFl to set
	 */
	public void setLogicalDelFl(Character logicalDelFl) {
		this.logicalDelFl = logicalDelFl;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Product [productId=" + productId + ", productNm=" + productNm
				+ ", productDesc=" + productDesc + ", productCost="
				+ productCost + ", logicalDelFl=" + logicalDelFl + "]";
	}

	
	
}

Product Table


create database product_kart;

create table product(
	product_id int not null AUTO_INCREMENT,
	product_nm varchar(100) not null,
	product_desc varchar(250),
	product_cost decimal,
	lgcl_del_fl char(1) DEFAULT 'N',
	PRIMARY KEY (product_id),
	UNIQUE KEY (product_nm)
)ENGINE=INNODB;

Junit Test Case

package com.productkart.dao.configuration;

import static org.junit.Assert.assertNotNull;

import javax.transaction.Transactional;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;

import com.productkart.model.Product;

@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(defaultRollback = true)
@ContextConfiguration(classes = { MySQLDatabaseConfig.class })
public class MySQLDatabaseConfigTest {
	@Autowired
	private SessionFactory sessionFactory;
	
	@Test
	@Transactional
	public void thatConfigurationWorks(){
		final Product product=new Product();
		product.setProductNm("Sony MP3 Player X1 Series");
		product.setProductDesc("Sony MP3 Player");
		product.setProductCost(100.00d);
		product.setLogicalDelFl('N');
		final Session session=sessionFactory.getCurrentSession();
		session.save(product);
		final Integer productId=product.getProductId();
		assertNotNull(productId);
		final Product loadedProduct=(Product)session.get(Product.class, productId);
		Assert.assertEquals(loadedProduct.hashCode(), product.hashCode());
		Assert.assertEquals(loadedProduct.getProductNm(), product.getProductNm());
		Assert.assertEquals(loadedProduct.getProductDesc(), product.getProductDesc());
		Assert.assertEquals(loadedProduct.getProductCost(), product.getProductCost());
		Assert.assertEquals(loadedProduct.getLogicalDelFl(), product.getLogicalDelFl());
	}
}

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- configuration file for LogBack (slf4J implementation)
See here for more details: http://gordondickens.com/wordpress/2013/03/27/sawing-through-the-java-loggers/ -->
<configuration scan="true" scanPeriod="30 seconds">

    <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
        <resetJUL>true</resetJUL>
    </contextListener>

    <!-- To enable JMX Management -->
    <jmxConfigurator/>

    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%-5level %logger{26} - %msg%n</pattern>
        </encoder>
    </appender>

	<logger name="org.hibernate" level="INFO"/>
	<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE"/> 
   <!-- Uncomment and add your logger here:
    <logger name="org.springframework.samples.service.service" level="debug"/> -->
         
    <root level="info">
        <appender-ref ref="console"/>
    </root>
</configuration>

Spring ResourceBundleViewResolver using java based configuration


@Configuration
@EnableWebMvc
@ComponentScan("com.productkart.web")
public class Config {

	@Bean
	public ViewResolver setupViewResolver(){
		ResourceBundleViewResolver resourceBundleViewResolver=new ResourceBundleViewResolver();
		resourceBundleViewResolver.setBasenames(new String[]{"spring/views/resourceviews"});
		return resourceBundleViewResolver;
	}
}


Properties file: src/main/java/spring/views/resourceviews.properties

showMessage.(class)=org.springframework.web.servlet.view.JstlView
showMessage.url=/WEB-INF/view/showMessage.jsp

Spring MVC Java based configuration

applicationContext.xml replacement:

package com.productkart.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("com.productkart.web")
public class Config {

	@Bean
	public ViewResolver setupUrlBasedViewResolver(){
		UrlBasedViewResolver urlBasedViewResolver=new UrlBasedViewResolver();
		urlBasedViewResolver.setPrefix("/WEB-INF/view/");
		urlBasedViewResolver.setSuffix(".jsp");
		urlBasedViewResolver.setViewClass(JstlView.class);
		return urlBasedViewResolver;
	}
}

web.xml spring mvc dispatcherServlet replacement:

package com.productkart.configuration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class WebInitializer implements WebApplicationInitializer {

	public void onStartup(ServletContext servletContext) throws ServletException {
		AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
		 ctx.register(Config.class);
		 
		 ctx.setServletContext(servletContext);
		 
		 Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
		 servlet.addMapping("/");
		 servlet.setLoadOnStartup(1);
	}

}

Need servlet-api 3.0.1 for this in pom.xml

<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>

Jaxb example

JAXB – Java Architecture for XML Binding
1. Marshalling – Converting a java object into XML format – jaxbMarshaller.marshal().
2. Unmarshalling – Converting xml into java object – jaxbMarshaller.unmarshal().

From jdk 1.6, jaxb comes bundled with jdk.

Main annotations: @XmlRootElement, @XmlElement, @XmlAttribute, @XmlType
Main Classes : JAXBContext, Marshaller, Unmarshaller

 


import java.io.ByteArrayInputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name="Product")
@XmlType(propOrder={"price","name"})
public class Product {
	
	private String name;
	private String sku;
	private double price;
	
	
	
	
	public Product(String name, String sku, double price) {
		super();
		this.name = name;
		this.sku = sku;
		this.price = price;
	}
	public Product() {
		super();
		// TODO Auto-generated constructor stub
	}
	@XmlElement(name="product_name")
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	@XmlAttribute(name="product_sku")
	public String getSku() {
		return sku;
	}
	public void setSku(String sku) {
		this.sku = sku;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	
	@Override
	public String toString() {
		return "Product [name=" + name + ", sku=" + sku + ", price=" + price
				+ "]";
	}

	
	public static void main(String[] args) throws JAXBException {
		Product product=new Product("Product1","sku1",15.0d);
		JAXBContext jaxbContext=JAXBContext.newInstance(Product.class);
		Marshaller marshaller=jaxbContext.createMarshaller();
		
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.marshal(product, System.out);
		
		
		//unmarshall example
		String xmlProduct="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"+
		"<Product product_sku=\"sku1\">"+
		"<product_name>Product1</product_name>"+
	    "<price>15.0</price>"+
		"</Product>";
		
		
		Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		Product product2 = (Product) jaxbUnmarshaller.unmarshal(new ByteArrayInputStream(xmlProduct.getBytes()));
		System.out.println(product2);
		
	}
	

}

output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Product product_sku="sku1">
    <price>15.0</price>
    <product_name>Product1</product_name>
</Product>
Product [name=Product1, sku=sku1, price=15.0]