Thursday 14 May 2015

Lower Bound in Java With Example

Lower Bound in Java With Exampl

You can use an lower bounded wildcard to put the restrictions on a variable. For example, say you want to write a method that works on List<Integer>,List<Number> and List<Object> or — anything that can hold Integer values. Only; you can achieve this by using lower bounded wildcard.

To declare an lower-bounded wildcard, use the wildcard character ('?'), followed by the super keyword, followed by its lower bound.

To write the method that works on lists of Integer and the supertypes of Integer, such as Integer, Number, and Object, you would specify List<? super Integer>. The termList<Integer> is more restrictive than List<? super Integer> because the former matches a list of type Integer only, whereas the latter matches a list of any type that is a supertype of Integer.

Consider the following showNumbers method for Example:

we have used List<? super Integer> which will allow us to pass list of all the Call which is super class of Integer. so here when you call showNumbers Method then you can pass List of type List<Integer>, List<Number>, List<Object>.


import java.util.*;
public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");
        List<Object> li=new ArrayList<Object>();
       
        for (int i = 1; i <= 10; i++) {
        li.add(i);
        }
    HelloWorld.addNumbers(li);
       
     }
    
     public static void addNumbers(List<? super Integer> list) {
    for (int i = 0; i <= list.size()-1; i++) {
         System.out.println(list.get(i));
         }
}
}

Upper Bound in Java With Example


Upper Bound in Java With Exampl

You can use an upper bounded wildcard to relax the restrictions on a variable. For example, say you want to write a method that works on List<Integer>, List<Double>, and List<Number>; you can achieve this by using an upper bounded wildcard.

To declare an upper-bounded wildcard, use the wildcard character ('?'), followed by the extends keyword, followed by its upper bound. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).

To write the method that works on lists of Number and the subtypes of Number, such as Integer, Double, and Float, you would specify List<? extends Number>. The term List<Number> is more restrictive than List<? extends Number> because the former matches a list of type Number only, whereas the latter matches a list of type Number or any of its subclasses.

Consider the following showNumbers method for Example:

 we have used List<? extends Number> which will allow us to pass list of all the Call which is derived from Number all whose super class is Number. so here when you call showNumbers Method then you can pass List of type List<Integer>, List<Float>, List<Double>, List<Number>, etc.. which includes Number class as parent Class.

HelloWorld.java

import java.util.*;
public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");
        List<Double> li=new ArrayList<Double>();
       
        for (double i = 1; i <= 10; i++) {
               li.add(i);
        }

        HelloWorld.addNumbers(li);
       
     }
    
     public static void showNumbers(List<? extends Number> list) {
     for (int i = 0; i <= list.size()-1; i++) {
         System.out.println(list.get(i));
         }
     }
}

Sunday 10 May 2015

populate dropdown using ajax in java

Populate Dropdown Using Ajax In Java

Here i have created some code which will bring the data using ajax from your controller of spring to your view and populate dropdown on the view.

Below is the controller method from where we are returning data to generate dropdown on view.  

Controller method

@RequestMapping(value="/getAddressList",method=RequestMethod.POST)
    public void getAddressList(Map<String, Object> map,HttpServletRequest request,HttpServletResponse response) throws IOException {
       
       
        List<WebAddress> addresses=new ArrayList<WebAddress>();
        for (Address add : addressService.listAddress()) {
                    WebAddress wadd=new WebAddress();
                    wadd.setId(add.getId());
                    wadd.setAddress1(add.getAddress1());
                    wadd.setAddress2(add.getAddress2());
                    wadd.setCity(add.getCity());
                    //wadd.setContacts(add.getContacts());
                    wadd.setState(add.getState());
                    wadd.setZip(add.getZip());
                    addresses.add(wadd);
        }
       
       
        Gson gson=new Gson();
   
       
        response.getWriter().write(gson.toJson(addresses));
    }



Now we are writing view and ajax call which will get the data and populate the dropdown on view.
for that we will create one select tag with ID let take dropdownID and then we will add options to this select box using jquery / javascript as Below

JSP view and page script
 

<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {


        $.ajax({
            type : "POST",
            dataType : 'json',
            url : "http://localhost:8080/getAddressList",
            success : function(data) {
                console.log(data);
                alert(data[0].address1);
                var options="<option value=''>--select country--</option>";
                $.each(data,function(k,v){
                    options +="<option value="+v.id+">"+v.address1 +","+v.address2+","+v.city+"</option>";
            
                    });         

                   $("dropdownID").html(options);
                }
        });
       
    });

</script>


<!--------your other html code -------->

<select id="dropdownID"></select>

<!--------your other html code -------->


[ERROR] Nested in org.springframework.web.util.NestedServletException: Request p rocessing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: 'xxxxxxxx', no session or session was closed: org.hibernate.LazyInitializationException: failed to lazily initialize a collect ion of role: 'xxxxxxxx', no session or session was c losed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitia lizationException(AbstractPersistentCollection.java:383) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitia lizationExceptionIfNotConnected(AbstractPersistentCollection.java:375) at org.hibernate.collection.AbstractPersistentCollection.initialize(Abst ractPersistentCollection.java:368) at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPe rsistentCollection.java:111) at org.hibernate.collection.PersistentBag.iterator(PersistentBag.java:27 2) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr ite(CollectionTypeAdapterFactory.java:95) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr ite(CollectionTypeAdapterFactory.java:60) at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(Typ eAdapterRuntimeTypeWrapper.java:68) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(Re flectiveTypeAdapterFactory.java:89) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.wr ite(ReflectiveTypeAdapterFactory.java:195) at com.google.gson.internal.bind.ObjectTypeAdapter.write(ObjectTypeAdapt er.java:107) at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(Typ eAdapterRuntimeTypeWrapper.java:68) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr ite(CollectionTypeAdapterFactory.java:96) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr ite(CollectionTypeAdapterFactory.java:60) at com.google.gson.Gson.toJson(Gson.java:593) at com.google.gson.Gson.toJson(Gson.java:572) at com.google.gson.Gson.toJson(Gson.java:527) at com.google.gson.Gson.toJson(Gson.java:507) at net.demo.contact.controller.ContactController.getAddressList(ContactC ontroller.java:64) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl. java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces sorImpl.java:43)

[ERROR] Nested in org.springframework.web.util.NestedServletException: Request p
rocessing failed; nested exception is org.hibernate.LazyInitializationException:
 failed to lazily initialize a collection of role: net.demo.contact.form.Address
.contacts, no session or session was closed:
org.hibernate.LazyInitializationException: failed to lazily initialize a collect
ion of role: net.demo.contact.form.Address.contacts, no session or session was c
losed
        at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitia
lizationException(AbstractPersistentCollection.java:383)
        at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitia
lizationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
        at org.hibernate.collection.AbstractPersistentCollection.initialize(Abst
ractPersistentCollection.java:368)
        at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPe
rsistentCollection.java:111)
        at org.hibernate.collection.PersistentBag.iterator(PersistentBag.java:27
2)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr
ite(CollectionTypeAdapterFactory.java:95)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr
ite(CollectionTypeAdapterFactory.java:60)
        at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(Typ
eAdapterRuntimeTypeWrapper.java:68)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(Re
flectiveTypeAdapterFactory.java:89)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.wr
ite(ReflectiveTypeAdapterFactory.java:195)
        at com.google.gson.internal.bind.ObjectTypeAdapter.write(ObjectTypeAdapt
er.java:107)
        at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(Typ
eAdapterRuntimeTypeWrapper.java:68)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr
ite(CollectionTypeAdapterFactory.java:96)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr
ite(CollectionTypeAdapterFactory.java:60)
        at com.google.gson.Gson.toJson(Gson.java:593)
        at com.google.gson.Gson.toJson(Gson.java:572)
        at com.google.gson.Gson.toJson(Gson.java:527)
        at com.google.gson.Gson.toJson(Gson.java:507)
        at net.demo.contact.controller.ContactController.getAddressList(ContactC
ontroller.java:64)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.
invokeHandlerMethod(HandlerMethodInvoker.java:174)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandle
rAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandle
rAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(Dispatch
erServlet.java:771)


SOLUTION

You are getting this error because, when you are trying to return a data in JSON or GSON from controller. you are returning the object which is provided by the service. and this object contains dependencies of other objects like if we have used any relationships (@OneToMany or @ManyToMany or @ManyToOne or @OneToOne ) in the object so when we are converting this object to JSON or GSON it is going into that all dependencies to get the data. so we are getting this error of  nested exception is org.hibernate.LazyInitializationException.

to solve this you can do below thing.

STEP - 1 ) Create SIMPLE POJO class with all the fields which you want in your JSON data like..

  I have one model which i want to return named Contactas below but we have used we have used @ManyToOne dependency in this so when we will try to return it directly we will get above error. so now see the next step.

import java.io.Serializable;

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

@Entity
@Table(name="CONTACTS")
public class Contact implements Serializable  {
    private static final long serialVersionUID = 1L;
   
    @Id
    @Column(name="ID")
    @GeneratedValue
    private Integer id;
   
    @Column(name="FIRSTNAME")
    private String firstname;

    @Column(name="LASTNAME")
    private String lastname;

    @Column(name="EMAIL")
    private String email;
   
    @Column(name="TELEPHONE")
    private String telephone;
   
    @ManyToOne
    private Address address;
   
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public String getEmail() {
        return email;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getFirstname() {
        return firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
   
}

STEP-2 ) Create simple POJO class of model but without hibernate annotation like.

public class ContactPOJO  {
    private Integer id;
   
    private String firstname;

    private String lastname;

    private String email;
   
    private String telephone;
   
    private Address address;
   
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public String getEmail() {
        return email;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getFirstname() {
        return firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
   
}

STEP - 3 ) Now use this class to return the data as i have used below.

  try {
            Gson gson=new Gson();
            Contact c=contactService.getContactById(contactId);  //////Object which are receiving from service

            ContactPOJO wc=new ContactPOJO();                   ///// Object we create to return in json formate
            wc.setId(c.getId());
            wc.setFirstname(c.getFirstname());
            wc.setLastname(c.getLastname());
            wc.setEmail(c.getEmail());
            wc.setTelephone(c.getTelephone());
            wc.setAddressId(c.getAddress().getId());

            response.getWriter().write(gson.toJson(wc));

        } catch (IOException e) {
            e.printStackTrace();
        }

STEP - 4 ) Now you will not get the error.

Please follow if you like this. contact me you need some help.




spring mvc dropdown onchange example

spring mvc dropdown onchange example

In Spring controller , write below code to bind the <form:select />, <form:option /> or <form:options />, we will use bellow value to render HTML form:select box :

@Controller

@RequestMapping("/")

public TestController{

protected ModelAndView createSelectWithValue(HttpServletRequest request) throws Exception { 
 
        Map cData = new HashMap(); 
 
        Map<String,String> countryList = new LinkedHashMap<String,String>(); 
 
        countryList.put("TX", "Texas");
 countryList.put("IN", "India");
 countryList.put("NY", "New York");
 countryList.put("NJ", "New Jessy");
 cData.put("cList", countryList); 
  
        ModelAndView mav=new ModelAndView();
        mav.addAttribute("selectedCountry","IN"); 
        mav.addAttribute("cList",cData);
        mav.setView("index");
  
        return mav;
  }
}
 
 
index.jsp
 
1) javascript which we will call onchange of spring mvc dropdown (<form:select />)
  
 <script type="text/javascript">

 function getValue(obj)
 {
  alert("You have selected Country: " + obj.value);
 }
 
</script>
 
2) spring mvc dropdown with onchange event
 
   <select id="country" name="country" onchange="getValue(this);"> 
 
      <option value="">--select country--</option>
 
      <c:forEach items="${cList}" var="name"> 
 
            <option value="${name[0]}" >${name[1]}</option>
        
      </c:forEach>
  </select> 
 
 
 
 

Wednesday 6 May 2015

basic authentication in express nodejs

Basic Authentication In Express Nodejs

To set a basic authentication to your project in node js. you need to have below modules.

npm install express --save
npm install basic-auth --save

Now use this module in your application

server.js

var express = require('express');
var auth = require('basic-auth');
var app = express();


app.use(function (req, res, next) {

    var user = auth(req);
    if (user === undefined) {
        res.statusCode = 401;
        res.setHeader('WWW-Authenticate', 'Basic realm="et3ebs6126a"');
        res.end('Unauthorized');
     } else
     {
        obj = new Object();
        obj.name = user['name'];
        obj.passkey = user['pass'];
                   console.log("Check Login");
            if(obj.name=="USERNAME" and obj.passkey="PASSWORD")
            {
                next();
            } else
            {
                res.statusCode = 401;
                res.setHeader('WWW-Authenticate', 'Basic realm="et3ebs6126a"');
                res.end('Unauthorized');
           }
    }
   
});



When ever you will try to open your project it will ask for authentication.

basic-auth-with-express-nodejs

Tuesday 5 May 2015

knex seed using nodejs example

Creating Seed for using Migrations in Knex

Migrations allow for you to define sets of schema changes so upgrading a database is a breeze.

Migration CLI

The migration CLI is bundled with the knex install, and is driven by the node-liftoffmodule. To install globally, run:
$ npm install knex -g
 
The 0.6 migrations use a knexfile, which specify various configuration settings for the module.
To create a new knexfile, run the following:
$ knex init

will create a sample knexfile.js - the file which contains our various database configurations. Once you have a knexfile.js, you can use the migration tool to create migration files to the specified directory (default migrations). Creating new migration files can be achieved by running:
$ knex migrate:make your_migration_name
Once you have the migrations in place you wish to run, you can run:
$ knex migrate:latest
To update your database to the latest version.

Seed files

Seed files allow you to populate your database with test or seed data independent of your migration files.

Seed CLI

To create a seed file, run:
$ knex seed:make your_seed_name
 
Seed files are created in the directory specified in your knexfile.js for the current environment.
A sample seed configuration looks like:
 
development: {
  client: ...,
  connection: { ... },
  seeds: {
      directory: './seeds/dev'
  }
}
 
If no seeds.directory is defined, files are created in ./seeds.
Note that the seed directory needs to be a relative path. Absolute paths are not supported (nor is it good practice).
Your seed file will contain the code like
'use strict';
exports.seed = function(knex, Promise) {
    return Promise.join(
        // Deletes ALL existing entries
        knex('users').del(),

        // Inserts seed entries
        knex('users').insert({user_name: 'testUserBySeed', passkey: 'passkey'})
       
    );
};
 
To run seed files, execute:
$ knex seed:run
 
Seed files are executed in alphabetical order. Unlike migrations, every seed file will be executed when you run the command. You should design your seed files to reset tables as needed before inserting data.

knexfile.js

A knexfile.js or knexfile.coffee generally contains all of the configuration for your database. It can optionally provide different configuration for different environments. You may pass a --knexfile option to any of the command line statements to specify an alternate path to your knexfile.

Basic configuration:

module.exports = {
  client: 'pg',
  connection: process.env.DATABASE_URL || {
    username: 'me',
    database: 'my_app'
  }
};

Environment configuration:

module.exports = {
  development: {
    client: 'pg',
    connection: {
      username: 'me',
      database: 'my_app'
    }
  },
  production: {
    client: 'pg',
    connection: process.env.DATABASE_URL
  }
};

Migration API

knex.migrate is the class utilized by the knex migrations cli. Each method takes an optional config object, which may specify specifies the database, directory,extension, and tableName for the migrations.
makeknex.migrate.make(name, [config]) 
Creates a new migration, with the name of the migration being added.
latestknex.migrate.latest([config]) 
Runs all migrations that have not yet been run.
rollbackknex.migrate.rollback([config]) 
Rolls back the latest migration group.
currentVersionknex.migrate.currentVersion([config]) 
Retrieves and returns the current migration version, as a promise. If there aren't any migrations run yet, returns "none" as the value for the currentVersion.

Seed API

knex.seed is the class utilized by the knex seed CLI. Each method takes an optionalconfig object, which may specify the relative directory for the migrations.
makeknex.seed.make(name, [config]) 
Creates a new seed file, with the name of the seed file being added.
runknex.seed.run([config]) 
Runs all seed files for the current environment.

Source code available at https://github.com/jayesh36/RESTFull-API-with-express-knex-promises-with-testcase-in-mocha

REST Full API Test case with Mocha in Nodejs

REST Full API Test case with Mocha in Nodejs 

First of all install mocha globally on your node server.

npm install -g mocha

We will also use some more modules to write a test case install that modules also by below steps.

npm install --save supertest
npm install --save assert
npm install --save should

Now create test folder in your project by writing

mkdir test

Now place your testCase.js file in side this folder

Now to run test just write below command

mocha

If you want to run test case using "npm test"  command then create file named makefile without any extension and put below code in that file

test:
 @./node_modules/.bin/mocha

.PHONY: test


Then add the following lines to your package.json file:

"scripts": {
"test": "make test"       //  OR mocha test
}

----------------------------------------------------------------------

testCase.js file
----------------------------------------------------------------------

var assert = require('assert');

var request = require('supertest');
var age = request.agent();
var should = require('should');
var recentevent = "";
var recentuser = "";
var recentcompany = "";

describe('dbop', function () {

    it('should axpect 401 Unauthorized', function (done) {
        request("localhost:3000")
        .get("/users")
        .expect(401) //Status code
        .end(function (err, res) {
            if (err) {
                throw err;
            }

            done();
        });

    });

    function loginUser() {
        return function (done) {
            request("localhost:3000")
            .post('/users')
            .set("Authorization", "basic " + new Buffer("TESTUS:passkey").toString("base64"))
            .expect(200)
            .end(onResponse);

            function onResponse(err, res) {
                if (err)
                    return done(err);
                return done();
            }
        };
    }
    it('should authorized', loginUser());

    function getAllUser() {
        return function (done) {
            request("localhost:3000")
            .get("/users")
            .set("Authorization", "basic " + new Buffer("TESTUS:passkey").toString("base64"))
            .set('accept', 'application/json')
            .expect(200) //Status code
            .end(function (err, res) {
                if (err) {
                    throw new Error("error");
                }
                res.should.have.body;
                console.log(res.body);

                done();
            });

        }
    }

    it('should get all users', getAllUser());

    it('should add user', function (done) {
        request("localhost:3000")
        .post("/users")
        .set("Authorization", "basic " + new Buffer("TESTUS:passkey").toString("base64"))
        .set('accept', 'application/json')
        .send({
            "user_name" : "testUser",
            "passkey" : "testKey",
            "companyid" : "10"
        })
        .expect(200) //Status code
        .end(function (err, res) {
            if (err) {
                throw new Error("error");
            }
            // Should.js fluent syntax applied
            //res.body.should.have.property('id');
            res.should.have.body;
            console.log(res.body);
            recentuser = res.body.id;
            //.should.not.equal(null);
            //res.body.passkey.should.not.equal(null);

            done();
        });

    });

   
});

Result:

restfull-api-test-with-mocha-nodejs


Source code available at https://github.com/jayesh36/RESTFull-API-with-express-knex-promises-with-testcase-in-mocha/tree/master/test